diff --git a/.github/workflows/e2e-standard-profile.yaml b/.github/workflows/e2e-standard-profile.yaml index 89e323fa3a2..be2e9aaa225 100644 --- a/.github/workflows/e2e-standard-profile.yaml +++ b/.github/workflows/e2e-standard-profile.yaml @@ -105,11 +105,17 @@ on: trusted_main: required: true type: boolean + hosted_model: + required: false + type: string + default: "" secrets: DOCKERHUB_USERNAME: required: false DOCKERHUB_TOKEN: required: false + HOSTED_PROVIDER_API_KEY: + required: false NVIDIA_API_KEY: required: false NVIDIA_INFERENCE_API_KEY: @@ -150,6 +156,7 @@ jobs: ENV: /dev/null EXECUTION_ID: ${{ inputs.execution_id }} GITHUB_WORKSPACE_VALUE: ${{ github.workspace }} + HOSTED_MODEL: ${{ inputs.hosted_model }} HOST_PACKAGES: ${{ inputs.host_packages }} HOST_PREPARATION: ${{ inputs.host_preparation }} INSTALL_MODE: ${{ inputs.install_mode }} @@ -181,6 +188,21 @@ jobs: if [[ "$ARTIFACT_LAYOUT" == "flat-shard" && "$SHARD" == "default" ]]; then fail "flat shard layout requires a named shard" fi + hosted_credential="" + case "$CATALOGUE_ID" in + hermes-fixed-bearer-inference-switch) [[ "$TARGET_ID" == "hermes-inference-switch" && "$TEST_FILE" == "test/e2e/live/hermes-inference-switch.test.ts" && "$SHARD" == "hermes-provider" ]] || fail "fixed hosted identity"; hosted_credential=NOUS_API_KEY ;; + hermes-fixed-anthropic-inference-switch) [[ "$TARGET_ID" == "hermes-inference-switch" && "$TEST_FILE" == "test/e2e/live/hermes-inference-switch.test.ts" && "$SHARD" == "anthropic-prod" ]] || fail "fixed hosted identity"; hosted_credential=ANTHROPIC_API_KEY ;; + hermes-fixed-openrouter-inference-switch) [[ "$TARGET_ID" == "hermes-inference-switch" && "$TEST_FILE" == "test/e2e/live/hermes-inference-switch.test.ts" && "$SHARD" == "openrouter-api" ]] || fail "fixed hosted identity"; hosted_credential=OPENROUTER_API_KEY ;; + openclaw-fixed-openai-inference-switch) [[ "$TARGET_ID" == "openclaw-inference-switch" && "$TEST_FILE" == "test/e2e/live/openclaw-inference-switch.test.ts" && "$SHARD" == "openai-api" ]] || fail "fixed hosted identity"; hosted_credential=OPENAI_API_KEY ;; + openclaw-fixed-anthropic-inference-switch) [[ "$TARGET_ID" == "openclaw-inference-switch" && "$TEST_FILE" == "test/e2e/live/openclaw-inference-switch.test.ts" && "$SHARD" == "anthropic-prod" ]] || fail "fixed hosted identity"; hosted_credential=ANTHROPIC_API_KEY ;; + *) [[ -z "${HOSTED_MODEL:-}" ]] || fail "unexpected hosted model" ;; + esac + if [[ -n "$hosted_credential" ]]; then + [[ "$RUNTIME_PROVIDER" == "docker" ]] || fail "fixed hosted runtime" + [[ "$HOSTED_MODEL" =~ ^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$ ]] || fail "hosted model" + fi + printf 'hosted_credential=%s + ' "$hosted_credential" >>"$GITHUB_OUTPUT" artifact_directory="e2e-artifacts/live/${TARGET_ID}" upload_name="e2e-${EXECUTION_ID}" if [[ "$SHARD" != "default" ]]; then @@ -532,6 +554,9 @@ jobs: INSTALL_MODE: ${{ inputs.install_mode }} CATALOGUE_ID: ${{ inputs.catalogue_id }} TEST_FILE: ${{ inputs.test_file }} + HOSTED_PROVIDER_API_KEY: ${{ inputs.trusted_main && secrets.HOSTED_PROVIDER_API_KEY || '' }} + HOSTED_CREDENTIAL_NAME: ${{ steps.execution_plan.outputs.hosted_credential }} + HOSTED_MODEL: ${{ inputs.hosted_model }} NVIDIA_API_KEY: ${{ inputs.trusted_main && secrets.NVIDIA_API_KEY || '' }} NVIDIA_INFERENCE_API_KEY: ${{ inputs.trusted_main && secrets.NVIDIA_INFERENCE_API_KEY || '' }} COMPATIBLE_API_KEY: ${{ inputs.compatible_api_key && inputs.trusted_main && secrets.NVIDIA_INFERENCE_API_KEY || '' }} @@ -551,6 +576,13 @@ jobs: export OPENSHELL_BIN "$OPENSHELL_BIN" --version fi + if [[ -n "$HOSTED_CREDENTIAL_NAME" ]]; then + [[ -n "$HOSTED_PROVIDER_API_KEY" ]] || { echo "::error::Selected hosted provider credential is unavailable" >&2; exit 1; } + printf -v "$HOSTED_CREDENTIAL_NAME" '%s' "$HOSTED_PROVIDER_API_KEY" + export "$HOSTED_CREDENTIAL_NAME" + export NEMOCLAW_SWITCH_MODEL="$HOSTED_MODEL" + fi + unset HOSTED_PROVIDER_API_KEY npx tsx tools/e2e/target-catalogue.mts run "$CATALOGUE_ID" "$TEST_FILE" - name: Finalize runner comparison telemetry diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 3c373ae006f..908efd2ed9e 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -25,6 +25,11 @@ on: required: false default: false type: boolean + hosted_model: + description: "Explicit model ID for one manually selected fixed hosted inference target. No default model is chosen." + required: false + default: "" + type: string inference_mode: description: "Inference adapter mode for compatible Vitest E2E jobs: mock, internal-nvidia, or public-nvidia." required: false @@ -375,6 +380,7 @@ jobs: selected_jobs: ${{ steps.matrix.outputs.selected_jobs }} selected_workflow_jobs: ${{ steps.matrix.outputs.selected_workflow_jobs }} catalogue_standard_matrix: ${{ steps.matrix.outputs.catalogue_standard_matrix }} + catalogue_fixed_hosted_matrix: ${{ steps.matrix.outputs.catalogue_fixed_hosted_matrix }} catalogue_nvidia_api_matrix: ${{ steps.matrix.outputs.catalogue_nvidia_api_matrix }} catalogue_nvidia_inference_matrix: ${{ steps.matrix.outputs.catalogue_nvidia_inference_matrix }} catalogue_github_read_matrix: ${{ steps.matrix.outputs.catalogue_github_read_matrix }} @@ -659,6 +665,7 @@ jobs: - id: matrix name: Generate E2E target matrix env: + HOSTED_MODEL: ${{ inputs.hosted_model }} INFERENCE_MODE: ${{ inputs.inference_mode || 'mock' }} NEMOCLAW_GATEWAY_RUNTIMES: ${{ inputs.jobs == 'portable-hermes-finalization' && 'podman' || inputs.gateway_runtimes || inputs.gateway_runtime || 'docker' }} JOBS: ${{ inputs.jobs }} @@ -670,9 +677,14 @@ jobs: run: | set -euo pipefail if [[ "${JOBS:-}" == "native-runtime-qualification-producer" && -z "${TARGETS:-}" ]]; then + if [[ -n "${HOSTED_MODEL:-}" ]]; then + echo "::error::hosted_model requires an explicit fixed hosted qualification target" >&2 + exit 1 + fi { echo 'matrix=[]' echo 'test_matrix=[]' + echo 'catalogue_fixed_hosted_matrix=[]' echo 'catalogue_standard_matrix=[]' echo 'catalogue_nvidia_api_matrix=[]' echo 'catalogue_nvidia_inference_matrix=[]' @@ -3310,6 +3322,55 @@ jobs: DOCKERHUB_USERNAME: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_USERNAME || '' }} DOCKERHUB_TOKEN: ${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_TOKEN || '' }} + catalogue-fixed-hosted: + name: ${{ matrix.display_name }} (${{ matrix.runtime_provider }}) + needs: [base-image-publication, generate-matrix, package-openshell-sdk] + if: ${{ needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix != '[]' && github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }} + strategy: + fail-fast: false + matrix: + include: ${{ fromJSON(needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix) }} + uses: ./.github/workflows/e2e-standard-profile.yaml + with: + candidate_repository: ${{ inputs.checkout_repository || github.repository }} + candidate_sha: ${{ inputs.checkout_sha || github.sha }} + runtime_provider: ${{ matrix.runtime_provider }} + execution_id: ${{ matrix.execution_id }} + coverage_variant: ${{ matrix.coverage_variant }} + risk_signal_expected_sha: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.checkout_sha || '' }} + risk_signal_correlation_id: ${{ github.event_name == 'workflow_dispatch' && inputs.checkout_sha != '' && inputs.correlation_id || '' }} + cli_artifact_provenance: ${{ needs.generate-matrix.outputs.cli_artifact_provenance }} + openshell_sdk_artifact_name: ${{ needs.package-openshell-sdk.outputs.artifact_name }} + managed_image_revision: ${{ needs.base-image-publication.outputs.managed_image_revision }} + managed_image_receipt: ${{ needs.base-image-publication.outputs.managed_image_receipt }} + managed_image_catalog: ${{ needs.base-image-publication.outputs.managed_image_catalog }} + workload_source: ${{ needs.generate-matrix.outputs.workload_source }} + credential_boundary: Selected fixed hosted provider + hosted_model: ${{ inputs.hosted_model }} + target_id: ${{ matrix.target_id }} + catalogue_id: ${{ matrix.id }} + runner: ${{ matrix.runner_key != '' && fromJSON(needs.generate-matrix.outputs.runner_routing)[matrix.runner_key] || matrix.runner }} + checkout_sha: ${{ inputs.checkout_sha }} + workflow_sha: ${{ inputs.workflow_sha }} + test_file: ${{ matrix.test_file }} + timeout_minutes: ${{ matrix.timeout_minutes }} + install_mode: ${{ matrix.install_mode }} + install_non_interactive: ${{ matrix.install_non_interactive }} + restore_cli: ${{ matrix.restore_cli }} + cloudflared: ${{ matrix.cloudflared }} + host_packages: ${{ matrix.host_packages }} + host_preparation: ${{ matrix.host_preparation }} + runner_comparison: ${{ matrix.runner_comparison }} + compatible_api_key: ${{ matrix.compatible_api_key }} + github_token: false + shard: ${{ matrix.shard }} + artifact_layout: ${{ matrix.artifact_layout }} + trusted_main: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }} + secrets: + DOCKERHUB_USERNAME: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_USERNAME || '' }} + DOCKERHUB_TOKEN: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && secrets.DOCKERHUB_TOKEN || '' }} + HOSTED_PROVIDER_API_KEY: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }} + catalogue-nvidia-api: name: ${{ matrix.display_name }} (${{ matrix.runtime_provider }}) needs: [base-image-publication, generate-matrix, package-openshell-sdk] @@ -6213,6 +6274,7 @@ jobs: live, shared-e2e, catalogue-standard, + catalogue-fixed-hosted, catalogue-nvidia-api, catalogue-nvidia-inference, catalogue-github-read, diff --git a/Dockerfile b/Dockerfile index 9d07be75ff2..e4b84d164b2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -648,12 +648,9 @@ FROM openclaw-managed-messaging-npm-cache-1 AS openclaw-managed-messaging-npm-ca FROM scratch AS openclaw-dependency-payload -COPY agents/openclaw/openclaw-runtime/package.json /usr/local/lib/nemoclaw/openclaw-runtime/package.json -COPY agents/openclaw/openclaw-runtime/package-lock.json /usr/local/lib/nemoclaw/openclaw-runtime/package-lock.json -COPY agents/openclaw/mcporter-runtime/package.json /usr/local/lib/nemoclaw/mcporter-runtime/package.json -COPY agents/openclaw/mcporter-runtime/package-lock.json /usr/local/lib/nemoclaw/mcporter-runtime/package-lock.json -COPY agents/openclaw/wechat-runtime/package.json /usr/local/lib/nemoclaw/wechat-runtime/package.json -COPY agents/openclaw/wechat-runtime/package-lock.json /usr/local/lib/nemoclaw/wechat-runtime/package-lock.json +COPY agents/openclaw/openclaw-runtime/package.json agents/openclaw/openclaw-runtime/package-lock.json /usr/local/lib/nemoclaw/openclaw-runtime/ +COPY agents/openclaw/mcporter-runtime/package.json agents/openclaw/mcporter-runtime/package-lock.json /usr/local/lib/nemoclaw/mcporter-runtime/ +COPY agents/openclaw/wechat-runtime/package.json agents/openclaw/wechat-runtime/package-lock.json /usr/local/lib/nemoclaw/wechat-runtime/ COPY ci/npm-audit-exceptions.json ci/reviewed-npm-audit.json /scripts/ COPY scripts/lib/reviewed-npm-archive.mts scripts/lib/bundled-npm-package.mts scripts/lib/reviewed-npm-audit.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/patch-bundled-npm-ip-address.mts scripts/lib/reviewed-npm-identity.mts /scripts/lib/ COPY scripts/lib/verify-mcporter-audit.sh /scripts/lib/verify-mcporter-audit.sh @@ -696,8 +693,8 @@ COPY scripts/managed-startup-hold.sh /usr/local/bin/nemoclaw-managed-startup-hol COPY nemoclaw-blueprint/scripts/*.js /usr/local/lib/nemoclaw/preloads/ COPY --from=runtime-preload-builder /opt/nemoclaw-root/dist/lib/messaging/channels/ /usr/local/lib/nemoclaw/preloads-compiled-channels/ COPY scripts/codex-acp-wrapper.sh /usr/local/bin/nemoclaw-codex-acp -COPY scripts/generate-openclaw-config.mts /scripts/ -COPY scripts/validate-openclaw-tool-search.mts /scripts/ +COPY scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ +COPY src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/ COPY --from=managed-startup-runtime-builder /out/managed-startup-image-runtime.cjs /usr/local/lib/nemoclaw/managed-startup-image-runtime.cjs COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ @@ -1546,8 +1543,9 @@ RUN mkdir -p /sandbox/.nemoclaw/blueprints/0.1.0 \ && cp -r /opt/nemoclaw-blueprint/* /sandbox/.nemoclaw/blueprints/0.1.0/ # Copy configuration inputs before the cached non-messaging plugin install. -COPY scripts/generate-openclaw-config.mts /scripts/ -COPY scripts/validate-openclaw-tool-search.mts /scripts/ +COPY scripts/generate-openclaw-config.mts scripts/validate-openclaw-tool-search.mts /scripts/ +COPY src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/ +RUN chmod 444 /src/lib/inference/native-hosted/openrouter-headers.ts COPY src/lib/extra-agents-validation.ts src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ COPY nemoclaw-blueprint/openclaw-plugins/ /usr/local/share/nemoclaw/openclaw-plugins/ diff --git a/agents/hermes/Dockerfile b/agents/hermes/Dockerfile index ddd0f2b6ded..5ad705dd87b 100644 --- a/agents/hermes/Dockerfile +++ b/agents/hermes/Dockerfile @@ -62,6 +62,7 @@ COPY agents/hermes/patch-profile-policy-defaults.py /opt/nemoclaw-hermes-config/ COPY agents/hermes/managed_policy.py /opt/nemoclaw-hermes-config/managed_policy.py COPY agents/hermes/host/managed-tool-gateway-matrix.json /opt/nemoclaw-hermes-config/managed-tool-gateway-matrix.json COPY src/lib/hermes-managed-route.ts /src/lib/hermes-managed-route.ts +COPY src/lib/inference/native-hosted/openrouter-headers.ts src/lib/inference/native-hosted/profiles.ts /src/lib/inference/native-hosted/ COPY src/lib/tool-disclosure.ts src/lib/providerless-inference.ts /src/lib/ COPY src/lib/messaging/ /src/lib/messaging/ COPY scripts/lib/openclaw-npm-remediation.mts /scripts/lib/openclaw-npm-remediation.mts @@ -377,7 +378,7 @@ RUN chmod -R a+rX /opt/nemoclaw-hermes-plugin/ # read-only. RUN find /opt/nemoclaw-hermes-config -type d -exec chmod 755 {} + \ && find /opt/nemoclaw-hermes-config -type f -exec chmod 444 {} + \ - && chmod 444 /src/lib/hermes-managed-route.ts /src/lib/tool-disclosure.ts /src/lib/providerless-inference.ts \ + && chmod 444 /src/lib/inference/native-hosted/profiles.ts /src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/hermes-managed-route.ts /src/lib/tool-disclosure.ts /src/lib/providerless-inference.ts \ && chmod 444 /scripts/lib/reviewed-npm-archive.mts /scripts/lib/bundled-npm-package.mts \ /scripts/lib/openclaw-npm-remediation.mts /scripts/lib/reviewed-npm-audit.mts \ /scripts/lib/reviewed-npm-identity.mts \ @@ -601,7 +602,7 @@ RUN /usr/bin/python3 -I \ # restart. Map only an externally supervised unplanned SIGTERM to private status # 79 so NemoClaw can wait for its root-owned recovery transaction. Every other # restart and failure path remains upstream. -ARG NEMOCLAW_HERMES_EXTERNAL_SUPERVISOR_RESTART_PATCHER_SHA256=ae31d7a1113b1144ef0977fb736439bac35820499a6134a66e3c6b6179d08e37 +ARG NEMOCLAW_HERMES_EXTERNAL_SUPERVISOR_RESTART_PATCHER_SHA256=ab51dec1bfc2593e5ad05d09356ead4a666243607e242d421835f2161cc956b6 ARG NEMOCLAW_HERMES_EXTERNAL_SUPERVISOR_RECOVERY_PATCHER_SHA256=8428d7f0ebe5545bf87f0800dba88d05c26c458447a8558960d0738cc5a0bdad ARG NEMOCLAW_HERMES_GATEWAY_SHUTDOWN_RECOVERY_PATCHED_SHA256=fcabcd3483565c7709aca1b8d38d4c4cb4fedc0997e0c881c2e643721f57f538 # hadolint ignore=DL4006 @@ -756,7 +757,7 @@ RUN node \ # file has to also rewrite the Dockerfile-committed hash, which reviewers gate). # Regenerate with `sha256sum agents/hermes/{hermes-wrapper.py,hermes-cli-adapter-v1.json,validate-cli-adapter.py,validate-env-secret-boundary.py,finalize-tirith-marker.py,cron-restore-control.py}`. ARG NEMOCLAW_HERMES_CLI_ADAPTER_SHA256=d892e57585485880e41c9bd0afe5b851e131997ab6ac86956a58db0704147781 -ARG NEMOCLAW_HERMES_WRAPPER_SHA256=1d6e6e46de34ccd5904e1a1add45eca536790902e610a46303a1811bb926eb81 +ARG NEMOCLAW_HERMES_WRAPPER_SHA256=1554ccf23f28133855bc170646a62050fe308bac69aecae3ce9df8b438195dad ARG NEMOCLAW_HERMES_CLI_ADAPTER_VALIDATOR_SHA256=5205a5446d0a509c5bc60f77fd97ec579449c2c7291dcc2878a788f25f078d6f ARG NEMOCLAW_HERMES_VALIDATOR_SHA256=8a034b4ecd32b69487d7524200c59446cf8df40a19e92b064d81f052dd8a51c4 ARG NEMOCLAW_HERMES_TIRITH_FINALIZER_SHA256=a1e6b1c53ab297569abb87c29d15c294d729e46005bfd022136b4c447a791819 diff --git a/agents/hermes/config/managed-policy.ts b/agents/hermes/config/managed-policy.ts index 15f24675451..15e79786f96 100644 --- a/agents/hermes/config/managed-policy.ts +++ b/agents/hermes/config/managed-policy.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; import type { HermesManagedRouting } from "../../../src/lib/hermes-managed-route.ts"; import { applyHermesManagedRoute } from "../../../src/lib/hermes-managed-route.ts"; import type { HermesBuildSettings } from "./build-env.ts"; @@ -288,6 +289,10 @@ export function buildHermesManagedPolicy( upstreamProvider: settings.upstreamProvider, inferenceApi: settings.inferenceApi, contextWindow: settings.contextWindow, + credentialEnv: + nativeHostedProfile(settings.upstreamProvider)?.endpoint === settings.baseUrl + ? nativeHostedProfile(settings.upstreamProvider)?.credentialEnv + : undefined, }); const managedToolGatewayPresets = effectiveManagedToolGatewayPresets(settings); diff --git a/agents/hermes/hermes-wrapper.py b/agents/hermes/hermes-wrapper.py index 9d584264b67..9c59a94f903 100755 --- a/agents/hermes/hermes-wrapper.py +++ b/agents/hermes/hermes-wrapper.py @@ -141,6 +141,19 @@ def _resolve_gateway_env_path(guard_path: str) -> str: return os.path.join(_self_dir(), ".env") +def _resolve_native_inference_guard() -> str | None: + installed = "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py" + if os.path.isfile(installed): + return installed + if os.path.abspath(__file__) == "/usr/local/bin/hermes": + return installed + local = os.path.join(_self_dir(), "runtime-config-guard.py") + return local if os.path.isfile(local) else None + + +_NATIVE_INFERENCE_HASH_FILE = "/etc/nemoclaw/hermes.config-hash" + + def _resolve_cli_adapter() -> str: if os.path.isfile(_INSTALLED_CLI_ADAPTER): return _INSTALLED_CLI_ADAPTER @@ -812,6 +825,27 @@ def main(argv: list[str]) -> int: try: adapter = _load_cli_adapter(_resolve_cli_adapter()) adapter_result, exec_argv = _adapt_cli_argv(argv, adapter) + native_guard = _resolve_native_inference_guard() + if ( + native_guard is not None + and argv not in (["-h"], ["--help"], ["--version"], ["-V"], ["chat", "-h"], ["chat", "--help"]) + # The exact restart control command must reach the supervisor after + # rebuild restores the home but before startup reconciles its hashes. + # Replacement startup and direct gateway run still validate the route. + and argv != ["gateway", "restart"] + and (argv[:1] == ["gateway"] or _parse_managed_invocation(argv, adapter) is not None) + ): + python3 = _resolve_trusted_python3() + if python3 is None: + print("[SECURITY] Native inference credential validation is unavailable", file=sys.stderr) + return 1 + result = subprocess.run( + [python3, "-I", native_guard, "native-inference-credential", + "--hermes-dir", _MANAGED_HERMES_HOME, + "--hash-file", _NATIVE_INFERENCE_HASH_FILE], check=False + ) + if result.returncode != 0: + return result.returncode if adapter_result == "translated": _require_upstream_cli_version(real_hermes, adapter["upstream_cli_version"]) except _AmbiguousProviderModelSession: diff --git a/agents/hermes/managed_policy.py b/agents/hermes/managed_policy.py index 37605b752dd..6284deaa27d 100644 --- a/agents/hermes/managed_policy.py +++ b/agents/hermes/managed_policy.py @@ -92,9 +92,16 @@ def load_managed_policy(path: Path = MANAGED_POLICY_PATH) -> dict: has_routing = any( key in config for key in ("model", "providers", "custom_providers", "_nemoclaw_upstream") ) - if has_routing and policy_value(config, "model.api_key") != HERMES_PROXY_REWRITE_SENTINEL: + if has_routing and policy_value(config, "model.api_key") not in { + HERMES_PROXY_REWRITE_SENTINEL, + "${OPENAI_API_KEY}", + "${ANTHROPIC_API_KEY}", + "${GEMINI_API_KEY}", + "${OPENROUTER_API_KEY}", + "${NVIDIA_INFERENCE_API_KEY}", + }: raise ManagedPolicyError( - "managed policy model.api_key must use the OpenShell proxy rewrite sentinel" + "managed policy model.api_key must use the OpenShell proxy rewrite sentinel or an approved credential environment reference" ) for managed_path in managed_paths: policy_value(config, managed_path) diff --git a/agents/hermes/patch-external-supervisor-restart.py b/agents/hermes/patch-external-supervisor-restart.py index 1490d06e8f1..1694d6eeada 100755 --- a/agents/hermes/patch-external-supervisor-restart.py +++ b/agents/hermes/patch-external-supervisor-restart.py @@ -48,19 +48,20 @@ def _restart_via_external_supervisor() -> bool: def _cmd_restart(args): ''' -OLD_RESTART_BRANCH = ''' if restart_all: - _restart_all(system) +OLD_RESTART_BRANCH = " if restart_all and _dispatch_all_via_service_manager_if_s6(\"restart\"):\n" +NEW_RESTART_BRANCH = ''' if not restart_all and _restart_via_external_supervisor(): return - - # The Windows restart path handles both registered installs and detached restarts. -''' -NEW_RESTART_BRANCH = ''' if restart_all: - _restart_all(system) - return - if _restart_via_external_supervisor(): - return - - # The Windows restart path handles both registered installs and detached restarts. + # A restart without a verified supervisor may launch from this CLI process. + # Preserve native route validation before any service-manager/manual fallback. + import subprocess + native_guard = subprocess.run( + [sys.executable, "-I", "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", + "native-inference-credential", "--hermes-dir", "/sandbox/.hermes", + "--hash-file", "/etc/nemoclaw/hermes.config-hash"], check=False + ) + if native_guard.returncode != 0: + sys.exit(native_guard.returncode) + if restart_all and _dispatch_all_via_service_manager_if_s6("restart"): ''' @@ -68,7 +69,8 @@ def patch_file(path: Path) -> None: source = path.read_text(encoding="utf-8") already_patched = source.count(HELPER) == 1 and source.count(NEW_RESTART_BRANCH) == 1 - if already_patched and source.count(OLD_RESTART_BRANCH) == 0: + # The replacement retains the original service-manager branch after its guard. + if already_patched and source.count(OLD_RESTART_BRANCH) == 1: return helper_count = source.count(HELPER_MARKER) diff --git a/agents/hermes/runtime-config-guard.py b/agents/hermes/runtime-config-guard.py index 8619a8bc916..ae3ef464eb3 100755 --- a/agents/hermes/runtime-config-guard.py +++ b/agents/hermes/runtime-config-guard.py @@ -776,7 +776,10 @@ def require_markerless_runtime() -> None: def _validate_action_readiness(action: str, startup_owner: bool) -> None: - if action == "inspect-private-mutable-topology": + if action in { + "native-inference-credential", + "inspect-private-mutable-topology", + }: return installed_current = os.path.abspath(__file__) == INSTALLED_RUNTIME_CONFIG_GUARD try: @@ -1435,6 +1438,47 @@ def assert_mcp_integrity_snapshot_current(snapshot: McpIntegritySnapshot) -> Non opened.close() +def _native_inference_hash_file(hermes_dir: str, strict_hash_file: str) -> str: + # Reuse the same procfs authority as config mutations; a bad strict hash + # never selects the compatibility path. + direct_start = _pid1_is_nemoclaw_start() + pid1_uid = _process_effective_uid(1) if direct_start else None + if direct_start and pid1_uid is not None and pid1_uid != 0: + return os.path.join(hermes_dir, ".config-hash") + if not direct_start: + try: + sandbox_uid = pwd.getpwnam("sandbox").pw_uid + except KeyError: + sandbox_uid = -1 + if sandbox_uid >= 0 and _openshell_supervised_nonroot_start_is_live(0, sandbox_uid): + return os.path.join(hermes_dir, ".config-hash") + return strict_hash_file + + +def validate_native_inference_credential(hermes_dir: str, hash_file: str) -> None: + """Validate the current integrity-bound route, including after a switch.""" + try: + selected_hash_file = _native_inference_hash_file(hermes_dir, hash_file) + snapshot = inspect_mcp_integrity_snapshot(hermes_dir, selected_hash_file) + config = yaml.safe_load(snapshot.config_text) + api_key = config.get("model", {}).get("api_key") + if api_key == "sk-OPENSHELL-PROXY-REWRITE" or api_key is None: + assert_mcp_integrity_snapshot_current(snapshot) + return + keys = ("NVIDIA_INFERENCE_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY") + key = next((name for name in keys if api_key == "${" + name + "}"), None) + if key is None or re.fullmatch( + rf"openshell:resolve:env:(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{key}", + os.environ.get(key, ""), + ) is None: + raise UnsafePathError("invalid native credential") + assert_mcp_integrity_snapshot_current(snapshot) + except (OSError, ValueError, AttributeError, yaml.YAMLError, UnsafePathError): + raise UnsafePathError( + "Native inference requires an intact managed route and an issued OpenShell credential handle" + ) from None + + def inspect_mcp_integrity(hermes_dir: str, hash_file: str) -> str: snapshot = inspect_mcp_integrity_snapshot(hermes_dir, hash_file) assert_mcp_integrity_snapshot_current(snapshot) @@ -3293,6 +3337,7 @@ def main() -> int: "inspect-mutation-owner", "write-config", "recover-prestate-lock", + "native-inference-credential", "inspect-private-mutable-topology", ), ) @@ -3323,7 +3368,11 @@ def main() -> int: if args.mcp_transition != "preserve" and args.action != "refresh-hashes": raise UnsafePathError("--mcp-transition requires refresh-hashes") _validate_action_readiness(args.action, args.startup_owner) - if args.action == "inspect-private-mutable-topology": + if args.action == "native-inference-credential": + if not args.hash_file: + raise UnsafePathError("native-inference-credential requires --hash-file") + validate_native_inference_credential(args.hermes_dir, args.hash_file) + elif args.action == "inspect-private-mutable-topology": inspect_private_mutable_topology() print("same-uid-nonroot") elif args.action == "ensure-api-key": diff --git a/agents/hermes/start.sh b/agents/hermes/start.sh index 548cd78acdf..9cf7f01953c 100755 --- a/agents/hermes/start.sh +++ b/agents/hermes/start.sh @@ -2721,6 +2721,11 @@ validate_hermes_env_secret_boundary() { "$_HERMES_PYTHON" -I "$_HERMES_BOUNDARY_VALIDATOR" env-file "$env_file" } +validate_hermes_native_inference_credential() { + "$_HERMES_PYTHON" -I "$_HERMES_RUNTIME_CONFIG_GUARD" native-inference-credential \ + --hermes-dir "$HERMES_DIR" --hash-file "$HERMES_HASH_FILE" || return 1 +} + validate_hermes_runtime_env_secret_boundary() { HERMES_LAZY_INSTALL_TARGET="$HERMES_SANDBOX_LAZY_INSTALL_TARGET" "${_HERMES_BOUNDARY_TIMEOUT[@]}" \ "$_HERMES_PYTHON" -I "$_HERMES_BOUNDARY_VALIDATOR" runtime-env @@ -2897,6 +2902,7 @@ prepare_hermes_nonroot_runtime() { refresh_hermes_runtime_config_hashes compat || return 1 configure_messaging_channels || return 1 prepare_tirith_marker_retry || return 1 + validate_hermes_native_inference_credential || return 1 } migrate_legacy_hermes_dashboard_state() { @@ -3046,6 +3052,7 @@ prepare_hermes_root_runtime() { refresh_hermes_provider_placeholders both || return 1 configure_messaging_channels || return 1 prepare_tirith_marker_retry || return 1 + validate_hermes_native_inference_credential || return 1 } launch_hermes_gateway_current_user() { diff --git a/agents/langchain-deepagents-code/Dockerfile b/agents/langchain-deepagents-code/Dockerfile index 017bd503d66..7276d3fe7c8 100644 --- a/agents/langchain-deepagents-code/Dockerfile +++ b/agents/langchain-deepagents-code/Dockerfile @@ -154,6 +154,10 @@ RUN set -eu; \ # wrapper, startup script, and shared blueprint files. COPY agents/langchain-deepagents-code/generate-config-entrypoint.ts /opt/nemoclaw-deepagents-code/generate-config.ts COPY agents/langchain-deepagents-code/generate-config.ts /opt/nemoclaw-deepagents-code/agents/langchain-deepagents-code/generate-config.ts +COPY src/lib/inference/native-hosted/openrouter-headers.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/openrouter-headers.ts +COPY src/lib/inference/native-hosted/profiles.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts +RUN chmod 444 /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts \ + /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/openrouter-headers.ts COPY src/lib/inference/managed-dcode/identity.ts /opt/nemoclaw-deepagents-code/src/lib/inference/managed-dcode/identity.ts COPY src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts COPY agents/langchain-deepagents-code/managed-dcode-runtime.py /opt/nemoclaw-deepagents-code/managed-dcode-runtime.py diff --git a/agents/langchain-deepagents-code/generate-config.ts b/agents/langchain-deepagents-code/generate-config.ts index 129744b2dbd..b8b1410181a 100644 --- a/agents/langchain-deepagents-code/generate-config.ts +++ b/agents/langchain-deepagents-code/generate-config.ts @@ -16,6 +16,9 @@ import { resolveManagedDcodeIdentity, } from "../../src/lib/inference/managed-dcode/identity.ts"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../src/lib/inference/native-nvidia/contract.ts"; +import { NATIVE_HOSTED_PROFILES } from "../../src/lib/inference/native-hosted/profiles.ts"; + +import { OPENROUTER_DEFAULT_HEADERS } from "../../src/lib/inference/native-hosted/openrouter-headers.ts"; type ReasoningEffort = "low" | "medium" | "high"; @@ -41,7 +44,6 @@ const NEMOTRON_ULTRA_MODEL_IDS = new Set([ "nvidia/nvidia/nemotron-3-ultra", ]); const MANAGED_INFERENCE_API_KEY_ENV = "DEEPAGENTS_CODE_OPENAI_API_KEY"; -const ATTACHED_PROVIDER_API_KEY_ENV = "NVIDIA_INFERENCE_API_KEY"; function readSettings(env: NodeJS.ProcessEnv): Settings { const providerKey = normalizeCommentMetadata( @@ -161,17 +163,27 @@ function providerConfigLines( model: string, baseUrl: string, reasoningEffort: ReasoningEffort | null, + upstreamProvider: string, ): string[] { - const apiKeyEnv = - baseUrl === NVIDIA_HOSTED_NATIVE_ENDPOINT - ? ATTACHED_PROVIDER_API_KEY_ENV - : MANAGED_INFERENCE_API_KEY_ENV; + const profile = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.logicalProvider === upstreamProvider && candidate.endpoint === baseUrl, + ); + const apiKeyEnv = profile?.credentialEnv ?? MANAGED_INFERENCE_API_KEY_ENV; return [ `[models.providers.${provider}]`, `models = ${tomlArray([model])}`, `api_key_env = ${tomlString(apiKeyEnv)}`, `base_url = ${tomlString(baseUrl)}`, "enabled = true", + ...(provider === "openrouter" + ? [ + "", + "[models.providers.openrouter.params.default_headers]", + ...OPENROUTER_DEFAULT_HEADERS.map( + ([name, value]) => `${tomlString(name)} = ${tomlString(value)}`, + ), + ] + : []), ...(provider === "openai" ? [ "", @@ -198,7 +210,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..0d75bd53538 100644 --- a/agents/langchain-deepagents-code/managed-dcode-runtime.py +++ b/agents/langchain-deepagents-code/managed-dcode-runtime.py @@ -1078,14 +1078,26 @@ def managed_inference_base_url() -> str: return value -def managed_inference_api_key(base_url: str) -> str: - """Select the non-secret credential for the validated image-owned route.""" - if base_url != "https://integrate.api.nvidia.com/v1": +def managed_inference_api_key() -> str: + """Use only the issued handle for the root-owned native inference route.""" + base_url = managed_inference_base_url() + profiles = { + "nvidia-prod": ("https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"), + "openai-api": ("https://api.openai.com/v1", "OPENAI_API_KEY"), + "anthropic-prod": ("https://api.anthropic.com", "ANTHROPIC_API_KEY"), + "gemini-api": ("https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"), + "openrouter-api": ("https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"), + "hermes-provider": ("https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY"), + } + profile = profiles.get(_managed_upstream_provider()) + credential_env = profile[1] if profile and base_url == profile[0] else None + if credential_env is None: return "nemoclaw-managed-inference" - name = "NVIDIA_INFERENCE_API_KEY" - value = os.environ.get(name, "") - if not _is_openshell_placeholder_for_name(name, value): - raise RuntimeError("native NVIDIA inference requires an OpenShell credential placeholder") + value = os.environ.get(credential_env, "") + if re.fullmatch( + rf"openshell:resolve:env:(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{credential_env}", value + ) is None: + raise RuntimeError("Native inference requires an issued OpenShell credential handle") return value diff --git a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py index 1dd687ee1f5..0546b2da48e 100644 --- a/agents/langchain-deepagents-code/patch-managed-deepagents-code.py +++ b/agents/langchain-deepagents-code/patch-managed-deepagents-code.py @@ -471,17 +471,19 @@ def _get_provider_kwargs(provider: str, *, model_name: str | None = None) -> dic managed_reasoning_effort, ) - if provider not in {"openai", "openrouter"}: + if provider not in {"openai", "openrouter", "anthropic"}: raise ModelConfigError( "Only NemoClaw-managed inference providers are enabled" ) + if provider == "anthropic" and managed_inference_base_url() != "https://api.anthropic.com": + raise ModelConfigError("Anthropic requires the selected native Anthropic route") # Load once so malformed TOML still fails through the upstream config error # path, but do not consume mutable provider classes, credentials, params, or # endpoints from it. ModelConfig.load() base_url = managed_inference_base_url() kwargs = { - "api_key": managed_inference_api_key(base_url), + "api_key": managed_inference_api_key(), "base_url": base_url, } if provider == "openai": @@ -1567,13 +1569,21 @@ def _nemoclaw_codex_mount(self) -> None: def _nemoclaw_select_with_auth_check(self, model_spec: str, provider: str) -> None: if provider: - if provider not in {"openai", "openrouter"}: + if provider not in {"openai", "openrouter", "anthropic"}: self.app.notify( "Only NemoClaw-managed inference providers are enabled.", severity="warning", markup=False, ) return + from deepagents_code._nemoclaw_managed import managed_inference_base_url + if provider == "anthropic" and managed_inference_base_url() != "https://api.anthropic.com": + self.app.notify( + "Anthropic requires the selected native Anthropic route.", + severity="warning", + markup=False, + ) + return from deepagents_code.config_manifest import ( is_provider_package_installed, provider_install_extra, diff --git a/agents/pi/Dockerfile b/agents/pi/Dockerfile index cdfb37e5b17..172ea3f535d 100644 --- a/agents/pi/Dockerfile +++ b/agents/pi/Dockerfile @@ -119,13 +119,15 @@ RUN set -eu; \ installed_version="$(printf '%s' "$pi_version" | tr -d '[:space:]')"; \ [ "$installed_version" = "${PI_VERSION}" ] -COPY agents/pi/generate-config.ts /opt/nemoclaw-pi/generate-config.ts +COPY agents/pi/generate-config.ts agents/pi/resolve-native-credential.ts /opt/nemoclaw-pi/ +COPY src/lib/inference/native-hosted/profiles.ts src/lib/inference/native-hosted/openrouter-headers.ts /src/lib/inference/native-hosted/ COPY scripts/lib/entrypoint-env-wrapper.sh /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh COPY agents/pi/start.sh /usr/local/bin/nemoclaw-start COPY scripts/managed-startup-hold.sh /usr/local/bin/nemoclaw-managed-startup-hold COPY nemoclaw-blueprint/ /opt/nemoclaw-blueprint/ -RUN chmod 444 /opt/nemoclaw-pi/generate-config.ts /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh \ +RUN test -x /usr/local/bin/node \ + && chmod 444 /src/lib/inference/native-hosted/profiles.ts /src/lib/inference/native-hosted/openrouter-headers.ts /opt/nemoclaw-pi/generate-config.ts /opt/nemoclaw-pi/resolve-native-credential.ts /usr/local/lib/nemoclaw/entrypoint-env-wrapper.sh \ && chmod 755 /usr/local/bin/nemoclaw-start /usr/local/bin/nemoclaw-managed-startup-hold \ && chmod -R a+rX /opt/nemoclaw-blueprint @@ -267,7 +269,7 @@ RUN set -eu; \ # upstream provider credential pattern. # hadolint ignore=DL4006 RUN set -eu; \ - if env | grep -Eq '^(NVIDIA_API_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|OPENROUTER_API_KEY)='; then \ + if env | grep -Eq '^(NVIDIA_API_KEY|NVIDIA_INFERENCE_API_KEY|OPENAI_API_KEY|ANTHROPIC_API_KEY|GEMINI_API_KEY|OPENROUTER_API_KEY)='; then \ echo "ERROR: an upstream provider credential is present in the Pi image environment" >&2; \ exit 1; \ fi; \ diff --git a/agents/pi/generate-config.ts b/agents/pi/generate-config.ts index b58fc4e2fd0..c0d549cf950 100644 --- a/agents/pi/generate-config.ts +++ b/agents/pi/generate-config.ts @@ -7,6 +7,8 @@ // OpenShell supplies the managed route credential to the running agent, and the // upstream provider credential never enters the sandbox. +import { OPENROUTER_DEFAULT_HEADERS } from "../../src/lib/inference/native-hosted/openrouter-headers.ts"; +import { nativeHostedProfile } from "../../src/lib/inference/native-hosted/profiles.ts"; import { chmodSync, mkdirSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; @@ -130,14 +132,22 @@ function buildModel(settings: Settings): Record { } function buildConfig(settings: Settings): ManagedPiConfig { + const nativeProfile = nativeHostedProfile(settings.upstreamProvider); + const nativeCredentialEnv = + nativeProfile?.endpoint === settings.baseUrl ? nativeProfile.credentialEnv : null; const config = { $comment: `Generated by NemoClaw. This file contains no provider secrets. NemoClaw provider route: ${settings.providerKey}; upstream provider: ${settings.upstreamProvider}; API: ${settings.inferenceApi}.`, defaultModel: settings.model, providers: { [MANAGED_PROVIDER_ID]: { api: settings.inferenceApi, - apiKey: MANAGED_PROVIDER_API_KEY, + apiKey: nativeCredentialEnv + ? `!/usr/local/bin/node /opt/nemoclaw-pi/resolve-native-credential.ts ${nativeCredentialEnv}` + : MANAGED_PROVIDER_API_KEY, baseUrl: settings.baseUrl, + ...(settings.upstreamProvider === "openrouter-api" && nativeCredentialEnv + ? { headers: Object.fromEntries(OPENROUTER_DEFAULT_HEADERS) } + : {}), models: [buildModel(settings)], }, }, diff --git a/agents/pi/resolve-native-credential.ts b/agents/pi/resolve-native-credential.ts new file mode 100644 index 00000000000..66f12e55f14 --- /dev/null +++ b/agents/pi/resolve-native-credential.ts @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Pi's supported credential-command resolver reads this at request time. +// Never return raw credentials or fabricate an unversioned OpenShell handle. +const allowedKeys = new Set([ + "NVIDIA_INFERENCE_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "OPENROUTER_API_KEY", +]); +const key = process.argv[2] ?? ""; +const value = process.env[key] ?? ""; +if ( + process.argv.length !== 3 || + !allowedKeys.has(key) || + !new RegExp(`^openshell:resolve:env:(?:v[0-9]{1,20}|s[0-9a-f]{64})_${key}$`).test(value) || + /[\r\n]/u.test(value) +) { + console.error("Native inference requires an issued OpenShell credential handle"); + process.exit(1); +} +process.stdout.write(value); + +export {}; diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 9a6bd60d8bf..e400290f2a4 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -15,26 +15,26 @@ "testFileCount": 77, "liveFileCount": 185, "direct": { - "expectCalls": 1234, - "matcherAssertions": 1213, + "expectCalls": 1232, + "matcherAssertions": 1211, "nodeAssertions": 104, "namedAssertionHelpers": 426, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 166, - "assertionPoints": 1959, + "assertionPoints": 1957, "generatedProbeBlocks": 87, "generatedProbeConditions": 216 }, "unique": { - "expectCalls": 1659, - "matcherAssertions": 1633, + "expectCalls": 1657, + "matcherAssertions": 1631, "nodeAssertions": 127, "namedAssertionHelpers": 671, "failCalls": 1, - "throwGuards": 528, + "throwGuards": 532, "objectFieldAssertions": 243, - "assertionPoints": 3203, + "assertionPoints": 3205, "generatedProbeBlocks": 209, "generatedProbeConditions": 721 }, @@ -62,13 +62,13 @@ "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], "test/e2e/live/double-onboard.test.ts": [36,43,36,43,0], "test/e2e/live/external-gateway-health.test.ts": [4,5,4,11,0], - "test/e2e/live/full-e2e.test.ts": [27,30,28,60,7], + "test/e2e/live/full-e2e.test.ts": [27,30,28,62,7], "test/e2e/live/gpu-double-onboard.test.ts": [21,24,21,24,0], "test/e2e/live/gpu-e2e.test.ts": [36,44,69,90,3], "test/e2e/live/hermes-discord.test.ts": [10,25,17,64,14], "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], - "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,77,1], + "test/e2e/live/hermes-inference-switch.test.ts": [44,50,55,77,1], "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], @@ -95,7 +95,7 @@ "test/e2e/live/onboard-repair.test.ts": [21,25,21,25,0], "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], - "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,52,1], + "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,54,1], "test/e2e/live/openclaw-skill-cli.test.ts": [10,14,10,14,1], "test/e2e/live/openclaw-slack-pairing.test.ts": [11,18,26,84,10], "test/e2e/live/openshell-credential-generation-window.test.ts": [42,92,43,112,18], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 37479232fde..537db24f78a 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\nProposed budget transition for PR #12769: extend double-onboard with same-name OpenClaw model-change recreation, replacement identity, primary model, and registry selection. Seven new checks replace three redundant checks, adding four assertion points. The file budget changes from [36,43,36,43,0] to [42,47,42,47,0]. Other file budgets remain unchanged relative to the current base. This renewal preserves the seven-assertion concurrent-gateway reduction from #12608 and the merged #12767 live-file and restoration-probe accounting. It retains the original four-point increase approved through #12776 and renewed through #12849. Disposition: https://github.com/NVIDIA/NemoClaw/pull/12769#issuecomment-6065766101. This prerequisite must merge before #12769 uses the exception. A changed base or candidate budget invalidates this entry. Remove after #12769 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.", + "$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\nProposed budget transition for PR #12769: extend double-onboard with same-name OpenClaw model-change recreation, replacement identity, primary model, and registry selection. Seven new checks replace three redundant checks, adding four assertion points. The file budget changes from [36,43,36,43,0] to [42,47,42,47,0]. Other file budgets remain unchanged relative to the current base. This renewal preserves the seven-assertion concurrent-gateway reduction from #12608 and the merged #12767 live-file and restoration-probe accounting. It retains the original four-point increase approved through #12776 and renewed through #12849. Disposition: https://github.com/NVIDIA/NemoClaw/pull/12769#issuecomment-6065766101. This prerequisite must merge before #12769 uses the exception. A changed base or candidate budget invalidates this entry. Remove after #12769 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 #12648 adds seven live assertion points for native compatible onboarding, a fresh authenticated agent request, and native status/health after duplicate deterministic checks were removed. User-provided recorded direction from Aaron Erickson (@ericksoa): https://nvidia.slack.com/archives/C0B1FQ51FP0/p1791301358361059. This proposed entry binds the main base budget bytes to this exact candidate budget and requires maintainer review before landing. The recorded direction does not waive the independent trusted-base check; the exception must reach its trusted policy or that specific failure needs separate explicit maintainer disposition. A changed budget invalidates the corresponding entry. Remove after #12648 merges.\n\nPR #12593 adds two necessary OpenClaw qualification input guards for an explicit model and the selected protocol. Existing live expectations remain unchanged. Deterministic support tests cover both refusals. This entry also includes the previously recorded Slice 2 guard transition and binds only the main base and candidate budget hashes. Aaron Erickson approved necessary budget increases in the recorded decision linked above. Independent enforcement requires this entry in its trusted base policy; no gate is waived. Remove after #12593 merges.", "schemaVersion": 1, "exceptions": [ { @@ -36,6 +36,16 @@ "pullRequest": 12777, "baseBudgetSha256": "53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441", "headBudgetSha256": "8bdce2cee059bb402f1f504e267f99cc39f1f7bf98928ffe0fb1bc95674dfa80" + }, + { + "pullRequest": 12648, + "baseBudgetSha256": "53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441", + "headBudgetSha256": "c1717e8c7f4eb215cc39ef8738c20f9871aff63b58aea4fdb9defdbcefda1d04" + }, + { + "pullRequest": 12593, + "baseBudgetSha256": "53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441", + "headBudgetSha256": "e8fb0b98decdc20f8253ed0f378f39e6a5b6b0ce44c9f1f2ad6e612a8c086c15" } ] } diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index dc71bc77af4..045d10b9821 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:3bf1dcebb4fdefe4ad588b15f287e2546a570c4464897835c37599de2ec1b66b", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:3bf1dcebb4fdefe4ad588b15f287e2546a570c4464897835c37599de2ec1b66b", + "digest": "sha256:1d042f71e146de375c909df9b07691e4c8a9782e9032f3a196362e020b750614", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:1d042f71e146de375c909df9b07691e4c8a9782e9032f3a196362e020b750614", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "9abef33ddf73105c8f3f952ced9ce4eb53252126", + "revision": "9640e8c6c43d0ecf563b711233daaa1ef5da7b02", "release": "v0.1.0", - "cohort": "ghrun-37676667241-1" + "cohort": "ghrun-37731249553-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 8154ec8d0fd..2eb80a2ff82 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:f3d7ed13c07c7c3840414752aa72e77178fa957137951c25ad4afa84206b11ac", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:f3d7ed13c07c7c3840414752aa72e77178fa957137951c25ad4afa84206b11ac", + "digest": "sha256:7760fe9a1a59eb370d9469c913d674c0c5f3c6ba64b6440cb7819184754cc528", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:7760fe9a1a59eb370d9469c913d674c0c5f3c6ba64b6440cb7819184754cc528", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "9abef33ddf73105c8f3f952ced9ce4eb53252126", + "revision": "9640e8c6c43d0ecf563b711233daaa1ef5da7b02", "release": "v0.1.0", - "cohort": "ghrun-37676667241-1" + "cohort": "ghrun-37731249553-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index c022fecd2e9..7df2ec4655f 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -95,9 +95,9 @@ }, { "name": "OpenRouter", - "status": "tested", + "status": "caveated", "endpoint_type": "OpenAI-compatible", - "notes": "First-class onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw registers the `openrouter-api` provider through OpenShell's `openai` profile with a host runtime adapter URL; host-side validation and runtime traffic send the default OpenRouter attribution headers." + "notes": "Onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw attaches the native OpenRouter provider for `https://openrouter.ai/api/v1`; host-side validation and agent requests preserve the required attribution headers. Live qualification of this migrated path remains pending." }, { "name": "OpenAI", @@ -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. Most inference uses OpenShell's `inference.local` endpoint through the Deep Agents Code OpenAI-compatible provider. NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861." + "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. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use `inference.local`. OpenShell keeps provider credentials outside the sandbox. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861." } ], @@ -207,8 +207,8 @@ }, { "name": "Managed inference", - "status": "tested", - "notes": "Provider-routed model calls through OpenShell, transparent to the agent. Most providers use `inference.local` inside the sandbox; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table." + "status": "caveated", + "notes": "Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use `inference.local` inside the sandbox. OpenShell keeps provider credentials outside the sandbox. Existing tested paths retain their evidence; live qualification of the newly migrated OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider paths remains pending." }, { "name": "Declarative network policy", diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 246e8940458..616fc7dc3a5 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -6,8 +6,8 @@ "src/lib/onboard/preflight.test.ts": 1875, "test/generation/generate-openclaw-config.test.ts": 1844, "test/installer-integration/install-preflight.test.ts": 2995, - "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 3376, - "test/onboarding/onboard-messaging.test.ts": 1960, + "test/agents/openclaw/runtime/nemoclaw-start.test.ts": 3308, + "test/onboarding/onboard-messaging.test.ts": 1869, "test/onboarding/onboard-selection.test.ts": 4125 } } diff --git a/docs/about/ecosystem-deepagents.mdx b/docs/about/ecosystem-deepagents.mdx index b57c09467e8..663d378c749 100644 --- a/docs/about/ecosystem-deepagents.mdx +++ b/docs/about/ecosystem-deepagents.mdx @@ -74,7 +74,7 @@ The following table compares custom OpenShell integration with `nemo-deepagents | Capability | Custom OpenShell + Deep Agents | `nemo-deepagents onboard` | |---|---|---| | Sandbox isolation | You define and apply OpenShell seccomp, Landlock, network namespace isolation, and no-new-privileges policy. | NemoClaw applies the managed Deep Agents policy through the blueprint and requires the runtime checks that the managed agent runtime depends on. | -| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding and keeps provider credentials outside the sandbox. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses a sandbox-attached provider for `https://integrate.api.nvidia.com/v1`. | +| Credential handling | You create OpenShell providers manually and decide how `dcode` receives endpoint credentials. | NemoClaw creates OpenShell providers during onboarding and keeps provider credentials outside the sandbox. Supported fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local/v1`. | | Image hardening | Depends on your base image and install steps. | NemoClaw installs the pinned Deep Agents Code package in `/opt/venv`, uses managed launchers, and rejects unsupported runtime paths such as unmanaged MCP autoloading, nested sandbox providers, and alternate model routes. | | Filesystem policy | You define read-only and read-write paths in policy YAML. | NemoClaw defines a targeted layout: system paths are read-only, `/sandbox` and `/tmp` are writable, and Deep Agents state lives under `/sandbox/.deepagents`. | | Inference setup | You configure OpenShell inference routing and Deep Agents provider settings manually. | NemoClaw validates the selected provider from the host, configures the OpenShell route, and writes `/sandbox/.deepagents/config.toml` for the managed OpenAI-compatible path. | @@ -104,6 +104,6 @@ Use the following table to choose NemoClaw or custom OpenShell integration. - [About Managed MCP Servers](../manage-sandboxes/mcp-servers/about-managed-mcp-servers) explains the managed MCP security and lifecycle boundary. - [Understand Deep Agents Trace Export](../monitoring/understand-deepagents-trace-export) explains the managed trace data and receiver trust boundaries. - [Quickstart with Deep Agents](../get-started/quickstart) installs NemoClaw and launches your first Deep Agents sandbox. -- [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) explains provider choices, shared `inference.local` routes, and the native NVIDIA provider path. +- [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) explains provider choices, shared `inference.local` routes, and native hosted provider paths. - [Deep Agents Code overview](https://docs.langchain.com/oss/python/deepagents/code/overview) explains upstream `dcode` capabilities and commands. - [Community Solutions](../resources/community-contributions) explains how to contribute community-driven examples, showcases, and complete blueprint patterns. diff --git a/docs/about/ecosystem-hermes.mdx b/docs/about/ecosystem-hermes.mdx index 60968612b9b..b63cc40c3d3 100644 --- a/docs/about/ecosystem-hermes.mdx +++ b/docs/about/ecosystem-hermes.mdx @@ -43,8 +43,8 @@ flowchart TB NemoClaw sits above OpenShell in the operator workflow. It calls OpenShell APIs and CLI commands to create and configure the sandbox that runs Hermes. -Models and endpoints sit behind OpenShell's inference routing. -NemoClaw onboarding connects your provider choice to that route, including the Hermes Provider route when you onboard through `nemohermes`. +Fixed hosted providers, including Hermes Provider, use native endpoints through OpenShell providers attached to the selected sandbox. +Custom, local, and Model Router selections use the shared `inference.local` route. The following table shows the scope of each component in the stack. @@ -75,10 +75,10 @@ The following table compares custom OpenShell integration with `nemohermes onboa | Capability | Custom OpenShell + Hermes | `nemohermes onboard` | |---|---|---| | Sandbox isolation | Yes, when you apply OpenShell seccomp, Landlock, network namespace isolation, and no-new-privileges enforcement through your policy. | Yes. NemoClaw applies these through the blueprint and layers a Hermes-specific restrictive policy on top. | -| Credential handling | You create OpenShell providers manually with `openshell provider create` and configure placeholder resolution at egress. | NemoClaw creates OpenShell providers during onboarding and filters sensitive host environment variables from the sandbox creation command to reduce accidental leakage through build args. | +| Credential handling | You create OpenShell providers manually with `openshell provider create` and configure placeholder resolution at egress. | OpenShell retains provider credentials outside the sandbox; Hermes uses a placeholder that OpenShell resolves at egress. NemoClaw filters sensitive host environment variables from sandbox creation to reduce accidental leakage through build args. | | Image hardening | Depends on your base image and install steps. | NemoClaw removes build toolchains (`gcc`, `g++`, `make`) and network probes (`netcat`) from the runtime image to reduce attack surface. | | Filesystem policy | You define read-only and read-write paths in policy YAML. | NemoClaw defines a targeted layout: system paths (`/usr`, `/lib`, `/etc`) are read-only; `/sandbox` and `/sandbox/.hermes` are writable for agent state and configuration. | -| Inference setup | You configure OpenShell inference routing and Hermes `config.yaml` manually. | NemoClaw validates the selected provider and model from the host, configures the OpenShell route, and writes the managed model settings into `/sandbox/.hermes/config.yaml`. Hermes Provider onboarding is available through `nemohermes`. | +| Inference setup | You configure OpenShell inference routing and Hermes `config.yaml` manually. | NemoClaw validates the selected provider and model from the host and writes managed model settings into `/sandbox/.hermes/config.yaml`. Fixed hosted providers use sandbox-attached OpenShell providers and native endpoints. Custom, local, and Model Router selections use the shared `inference.local` route. | | Managed MCP | You register providers, network policy, and Hermes MCP configuration yourself. | NemoClaw manages authenticated HTTPS Streamable HTTP MCP server lifecycle, ownership records, policy, and credential placeholders through host-side commands. | | Channel messaging | OpenShell delivers channel credentials through its provider system and L7 proxy. You configure Hermes platform adapters manually. | NemoClaw configures supported channels during onboarding or through lifecycle commands and writes the managed Hermes channel settings. | | Blueprint versioning | No NemoClaw blueprint; your image tag is whatever you built locally. | NemoClaw downloads the blueprint artifact, checks version compatibility, and verifies its digest before applying. Repeated onboarding uses the selected blueprint and recorded configuration; host and platform differences can still affect the result. | diff --git a/docs/about/how-it-works.mdx b/docs/about/how-it-works.mdx index 4bb9cfd3a3c..110a3e75fa5 100644 --- a/docs/about/how-it-works.mdx +++ b/docs/about/how-it-works.mdx @@ -210,8 +210,9 @@ Refer to [Recover and Rebuild Sandboxes](../manage-sandboxes/operate-sandboxes/r ## Inference Routing -Most managed providers send model requests through `inference.local` instead of directly to an upstream endpoint. -NVIDIA Endpoints uses a sandbox-attached OpenShell provider that permits approved requests to `integrate.api.nvidia.com`. +NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider use sandbox-attached OpenShell providers. +The agent calls the selected provider's native endpoint, and OpenShell supplies its credential only for approved requests. +Custom endpoints and local providers retain the shared `inference.local` route. During onboarding, NemoClaw validates the selected provider and model, configures the applicable OpenShell route or provider attachment, and writes the matching model reference into the managed agent configuration. In both paths, OpenShell keeps the provider credential outside the sandbox and sends only approved requests to the upstream endpoint. When you select the Model Router provider, `inference.local` routes to a host-side router that chooses from a configured model pool available through NVIDIA Endpoints for each request. diff --git a/docs/about/overview.mdx b/docs/about/overview.mdx index 9f2b4035a61..bc7dfdc0dd8 100644 --- a/docs/about/overview.mdx +++ b/docs/about/overview.mdx @@ -37,7 +37,7 @@ NemoClaw groups its supported capabilities around running, connecting, controlli | Area | Capability | |---|---| | Run supported agents | Onboards OpenClaw, Hermes, or LangChain Deep Agents Code into an agent-specific sandbox image and configuration. | -| Route inference | Connects supported hosted and local inference providers through OpenShell-managed routes. Most use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. | +| Route inference | Connects supported hosted and local inference providers through OpenShell-managed routes. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. OpenShell keeps provider credentials outside the sandbox. | | Control sandbox access | Applies network policy, filesystem policy, process controls, and managed inference through OpenShell. | | Operate the lifecycle | Reports host readiness, creates or updates sandboxes, reports status and logs, and rebuilds or recovers sandboxes while preserving the native agent home. | | Connect Model Context Protocol (MCP) servers | Manages authenticated HTTPS Streamable HTTP MCP servers for all supported agent runtimes. OpenShell replaces credential placeholders at approved egress boundaries. | diff --git a/docs/deployment/deploy-to-headless-server.mdx b/docs/deployment/deploy-to-headless-server.mdx index e13b2d2fc3e..38c0b442572 100644 --- a/docs/deployment/deploy-to-headless-server.mdx +++ b/docs/deployment/deploy-to-headless-server.mdx @@ -206,7 +206,7 @@ $$nemoclaw headless-agent status $$nemoclaw headless-agent connect --probe-only ``` -`$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified. Its main `Inference` line probes the selected provider path from inside the sandbox. Shared providers use `https://inference.local/v1/models`, then send an inference request over the same route when that probe reports the route reachable. NVIDIA Endpoints verifies the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1` with an inference request. Status repeats inference requests up to three total attempts when they return a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after a final failure or after all transient attempts fail. +`$$nemoclaw headless-agent status` exits nonzero when the sandbox, gateway, local container, or authoritative inference route is not verified. Its main `Inference` line probes the selected provider path from inside the sandbox. Custom, local, and Model Router selections use `https://inference.local/v1/models`, then send an inference request over the same route when that probe reports the route reachable. Fixed hosted providers verify their native endpoints through sandbox-attached OpenShell providers with an inference request. Status repeats inference requests up to three total attempts when they return a transient gateway status; refer to the [CLI commands reference](../reference/commands) for the retried statuses and their token cost. The line reports `healthy` when the route served the request, `unauthorized` when the route rejected it with HTTP `401` or `403`, and `unhealthy` after a final failure or after all transient attempts fail. @@ -269,7 +269,7 @@ unset TOKEN -Deep Agents Code does not expose a dashboard URL or gateway token. Most model traffic uses the OpenShell-managed `inference.local` route. NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. +Deep Agents Code does not expose a dashboard URL or gateway token. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the OpenShell-managed `inference.local` route. diff --git a/docs/get-started/quickstart-hermes.mdx b/docs/get-started/quickstart-hermes.mdx index f9aac5332bb..29476a6ee58 100644 --- a/docs/get-started/quickstart-hermes.mdx +++ b/docs/get-started/quickstart-hermes.mdx @@ -352,8 +352,8 @@ Use these details when your first-run path needs more control. After you select a provider and model, review the summary and apply the configuration. NemoClaw writes Hermes configuration into `/sandbox/.hermes` and starts the Hermes gateway inside the sandbox. - NVIDIA Endpoints traffic uses the native NVIDIA endpoint through the least-privilege sandbox-attached OpenShell provider. - Other managed inference providers continue to use `inference.local`. + Fixed hosted providers use their native endpoints through least-privilege sandbox-attached OpenShell providers. + Custom, local, and Model Router selections continue to use `inference.local`. The Hermes image includes runtime dependencies for supported NemoClaw messaging integrations, the API service, and its health endpoint. The base image does not include unsupported Hermes integrations. diff --git a/docs/get-started/quickstart-langchain-deepagents-code.mdx b/docs/get-started/quickstart-langchain-deepagents-code.mdx index c6603548ae8..9f819ec23b9 100644 --- a/docs/get-started/quickstart-langchain-deepagents-code.mdx +++ b/docs/get-started/quickstart-langchain-deepagents-code.mdx @@ -165,7 +165,7 @@ The wizard asks for an inference provider, model, required credential, and sandb When you edit inference, NemoClaw clears the credential staged for the discarded selection. NemoClaw preserves the sandbox name. When you edit the sandbox name, NemoClaw preserves the inference selection. The sandbox prompt shows the prior name as its default. After you apply the configuration, routine editing ends. If inference setup fails and offers a `back` recovery action, you can return to provider and model selection and then review the updated configuration again. Provider registration, inference setup, policy selection, and sandbox creation then continue forward. The default Deep Agents sandbox name is `deepagents-code`. Use a distinct name, such as `my-deepagents`, when you run Deep Agents, Hermes, and OpenClaw sandboxes side by side. Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inference-provider) for provider-specific prompts. -The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. NVIDIA Endpoints uses `https://integrate.api.nvidia.com/v1` through a least-privilege OpenShell provider attached to the sandbox. Other managed providers use `https://inference.local/v1`. Both paths put a scoped placeholder in the agent config instead of the real provider key. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. +The image installs hash-locked Deep Agents Code `0.1.55` with NVIDIA provider support. After the terminal smoke checks, onboarding runs `dcode --version` and compares the result with the version required by the agent manifest. Fresh and resumed onboarding exit nonzero instead of reporting the runtime ready when the installed version is too old, uses an incompatible version scheme, or cannot be verified. If the version check fails, review the reported version error and run `nemo-deepagents rebuild` before resuming onboarding. NemoClaw writes `/sandbox/.deepagents/config.toml` with an OpenAI-compatible provider and sets `use_responses_api = false` for Chat Completions compatibility. Supported fixed hosted providers use their native endpoints through least-privilege OpenShell providers attached to the sandbox. Custom, local, and Model Router selections use `https://inference.local/v1`. Both paths put a scoped placeholder in the agent config instead of the real provider key. When onboarding records a reasoning effort on a `compatible-endpoint` route that uses `openai-completions`, managed startup writes that value to a root-owned file and Deep Agents Code model requests carry it as an `extra_body.reasoning_effort` request parameter. Leave `NEMOCLAW_REASONING_EFFORT` unset to keep the endpoint's own default. Deep Agents Code has no runtime `inference set` path, so re-onboard the sandbox with `nemo-deepagents onboard --fresh --name --recreate-sandbox` to change the recorded effort. When you use NVIDIA Endpoints without selecting another model, new Deep Agents Code sandboxes default to `nvidia/nemotron-3-ultra-550b-a55b`. For this model, the managed image maps the OpenAI-compatible route to Deep Agents `0.7.5`'s native Nemotron 3 Ultra harness profile, including model-specific tool-calling, filesystem, retry, context, and final-answer safeguards. Rebuild existing Deep Agents Code sandboxes after upgrading to NemoClaw v0.0.76 or later so their image includes this profile. This agent-specific default does not change the shared Nemotron 3 Super default for OpenClaw and Hermes. The image launcher normalizes the runtime proxy environment for interactive, login-shell, and direct-exec paths and removes inherited proxy credentials and bypass entries before `dcode` starts. Managed interactive sessions pre-complete Deep Agents Code's optional first-run onboarding, skip its dependency and model selection screens, then open the TUI with the model selected during NemoClaw onboarding. The image includes `ripgrep` and `dos2unix`, and ordinary sessions suppress the optional Tavily warning unless web search is configured or invoked. @@ -252,7 +252,7 @@ nemo-deepagents rebuild If you upgrade from a release that persisted LangSmith environment values, rebuild each existing Deep Agents Code sandbox so its image includes the corrected `start.sh`. If an existing sandbox displays `Choose a Recommended Model`, rebuild it so its image includes the managed startup behavior. -`status` reports the selected harness as a terminal runtime and prints the interactive/headless command shape. If `status` reports `Runtime health: degraded` with an OOM kill count, rebuild the sandbox to restore the terminal runtime. Proxy launchers and startup scripts are baked into the sandbox image. After upgrading from a release that used `inference.local` for NVIDIA Endpoints, recreate each NVIDIA sandbox during onboarding. NemoClaw does not add the required native provider attachment to an existing beta sandbox. NemoClaw v0.0.78 and newer clients fail closed when a pre-v0.0.78 sandbox image lacks the trusted `/usr/local/lib/nemoclaw/dcode-managed-exec` route-probe helper, even when the installed Deep Agents Code version still matches the managed manifest. Rebuild the sandbox to install that image-owned helper before retrying `status`, `doctor`, `connect`, or onboarding recovery. There is no dashboard port or long-running gateway process for this harness. +`status` reports the selected harness as a terminal runtime and prints the interactive/headless command shape. If `status` reports `Runtime health: degraded` with an OOM kill count, rebuild the sandbox to restore the terminal runtime. Proxy launchers and startup scripts are baked into the sandbox image. After upgrading from a release that used `inference.local` for a fixed hosted provider, recreate that sandbox during onboarding. NemoClaw does not add the required native provider attachment to an existing beta sandbox. NemoClaw v0.0.78 and newer clients fail closed when a pre-v0.0.78 sandbox image lacks the trusted `/usr/local/lib/nemoclaw/dcode-managed-exec` route-probe helper, even when the installed Deep Agents Code version still matches the managed manifest. Rebuild the sandbox to install that image-owned helper before retrying `status`, `doctor`, `connect`, or onboarding recovery. There is no dashboard port or long-running gateway process for this harness. ## Next Steps diff --git a/docs/get-started/quickstart-pi.mdx b/docs/get-started/quickstart-pi.mdx index 132b09483b9..cf7bda9280d 100644 --- a/docs/get-started/quickstart-pi.mdx +++ b/docs/get-started/quickstart-pi.mdx @@ -49,7 +49,7 @@ For an existing installation, run the canonical onboarding command. nemoclaw onboard --agent pi --name my-pi ``` -Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell. Most providers give Pi the managed `https://inference.local/v1` route. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox at `https://integrate.api.nvidia.com/v1`. The credential remains in OpenShell provider state across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. +Choose a provider and model that use the OpenAI Chat Completions API. NemoClaw keeps the upstream provider credential in OpenShell. Supported fixed hosted providers give Pi their native endpoint through a least-privilege OpenShell provider attached to the sandbox. Custom, local, and Model Router selections use the managed `https://inference.local/v1` route. The credential remains in OpenShell provider state across rebuild and sandbox destruction. When no sandbox needs that provider, remove it explicitly with `nemoclaw credentials reset --yes`. Stock onboarding selects a Pi managed-image digest. It does not build the Pi Dockerfile on the host. The reviewed Dockerfile is a trusted CI image-build source, not a user onboarding mechanism. A missing, incomplete, mutable, or inconsistent image contract fails before sandbox creation. diff --git a/docs/get-started/quickstart.mdx b/docs/get-started/quickstart.mdx index 3dbd044bb6a..abb1da7dfb1 100644 --- a/docs/get-started/quickstart.mdx +++ b/docs/get-started/quickstart.mdx @@ -375,8 +375,8 @@ Use these details when your first-run path needs more control. After confirmation, NemoClaw registers the selected provider with OpenShell. - Most providers use the shared `inference.local` route. - NVIDIA Endpoints uses a least-privilege provider attached to the sandbox instead. + Fixed hosted providers use native endpoints through least-privilege providers attached to the sandbox. + Custom, local, and Model Router selections use the shared `inference.local` route. The wizard asks whether to enable web search and offers Brave Search or Tavily Search. Provide `BRAVE_API_KEY` for Brave Search or `TAVILY_API_KEY` for Tavily Search when prompted. NemoClaw validates the selected key before it creates the sandbox, registers a sandbox-scoped OpenShell provider, and writes only an OpenShell resolver placeholder into the OpenClaw configuration. diff --git a/docs/inference/choose-inference-provider.mdx b/docs/inference/choose-inference-provider.mdx index 9687448a1b6..3ae16365828 100644 --- a/docs/inference/choose-inference-provider.mdx +++ b/docs/inference/choose-inference-provider.mdx @@ -32,7 +32,7 @@ Use this status table to distinguish validated provider integrations from adapte | Provider | Status | Endpoint type | Notes | |----------|--------|---------------|-------| | NVIDIA Endpoints | Tested | OpenAI-compatible | Hosted models on integrate.api.nvidia.com | -| OpenRouter | Tested | OpenAI-compatible | First-class onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw registers the `openrouter-api` provider through OpenShell's `openai` profile with a host runtime adapter URL; host-side validation and runtime traffic send the default OpenRouter attribution headers. | +| OpenRouter | Tested with limitations | OpenAI-compatible | Onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw attaches the native OpenRouter provider for `https://openrouter.ai/api/v1`; host-side validation and agent requests preserve the required attribution headers. Live qualification of this migrated path remains pending. | | OpenAI | Tested | Native OpenAI-compatible | Uses OpenAI model IDs | | Other OpenAI-compatible endpoint | Tested with limitations | Custom OpenAI-compatible | Custom base-URL adapter for servers that implement OpenAI-compatible `/v1/chat/completions` or `/v1/responses`. Behavior on OpenAI-compatible proxies, gateways, and self-hosted implementations may vary; this row claims the adapter, not the universe of compatible endpoints. | | Anthropic | Tested | Native Anthropic | Uses anthropic-messages | diff --git a/docs/inference/how-inference-routing-works.mdx b/docs/inference/how-inference-routing-works.mdx index f8bbf7c65f3..681faf3451b 100644 --- a/docs/inference/how-inference-routing-works.mdx +++ b/docs/inference/how-inference-routing-works.mdx @@ -14,23 +14,23 @@ This design keeps provider credentials outside the sandbox. ## Request Path -Most providers use the shared `inference.local` route inside the sandbox. -OpenShell intercepts each request on the host and forwards it to the provider and model selected during onboarding. +NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider use sandbox-attached OpenShell providers. +The agent addresses the selected provider's native endpoint, and OpenShell supplies the credential for approved requests. ```text -Sandbox agent -> inference.local -> shared OpenShell route -> selected provider and model +Sandbox agent -> provider API hostname -> sandbox-attached OpenShell provider -> selected provider ``` -NVIDIA Endpoints use a sandbox-attached OpenShell provider instead of the shared route. -The agent addresses the NVIDIA API hostname, but OpenShell still intercepts the request and supplies the host-managed credential. +Each sandbox receives its selected provider attachment. +A failed native request does not fall back to `inference.local`. + +Custom endpoints, local providers, and Model Router retain the shared OpenShell route. +The sandbox uses `inference.local` for those selections. ```text -Sandbox agent -> integrate.api.nvidia.com -> sandbox-attached OpenShell provider -> NVIDIA +Sandbox agent -> inference.local -> shared OpenShell route -> selected provider and model ``` -Host-side services such as Model Router and the OpenRouter runtime adapter remain behind the OpenShell route. -The sandbox uses `inference.local` for those services instead of calling their host ports directly. - ## Credential Boundary Provider credentials stay on the host and flow through the OpenShell provider system. @@ -45,7 +45,8 @@ When a rebuild reuses an automatically bridged compatible-endpoint route without ## Deep Agents Configuration -For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with a managed OpenAI-compatible provider, a scoped placeholder API key, and `use_responses_api = false`. Most providers use `https://inference.local/v1`. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox at `https://integrate.api.nvidia.com/v1`. +For Deep Agents, NemoClaw writes `/sandbox/.deepagents/config.toml` with a managed OpenAI-compatible provider, a scoped placeholder API key, and `use_responses_api = false`. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. +Custom and local selections retain `https://inference.local/v1`. The managed `dcode` runtime uses Chat Completions through OpenShell even when a compatible endpoint also supports the Responses API. diff --git a/docs/inference/model-capability-audit.mdx b/docs/inference/model-capability-audit.mdx index a9b21934b7b..fda58e1e85c 100644 --- a/docs/inference/model-capability-audit.mdx +++ b/docs/inference/model-capability-audit.mdx @@ -121,14 +121,14 @@ When importing a completed row from an issue comment, preserve the commit SHA, w | OpenClaw primary agent | NVIDIA Endpoints (retired route) | `deepseek-ai/deepseek-v4-pro` | Managed `inference.local` OpenAI-compatible completions | `unsupported` | The featured-model feed still listed this model after the NVIDIA Endpoints model catalog removed it. NemoClaw excludes it from featured selections. | The retirement exclusion applies to NVIDIA Endpoints featured selections. It does not determine whether another compatible endpoint serves the same model ID. | Select a supported NVIDIA Endpoints model. | `src/lib/inference/nvidia-featured-models.ts`, `src/lib/inference/nvidia-featured-models.test.ts`. | | OpenClaw primary agent | NVIDIA Endpoints (retired route) | `z-ai/glm-5.2` | Managed `inference.local` OpenAI-compatible completions | `unsupported` | [Issue #10222](https://github.com/NVIDIA/NemoClaw/issues/10222) records authenticated NVIDIA Endpoints `/v1/models` results from WSL and DGX Spark with no GLM model IDs. NemoClaw excludes this model from featured selections. | The retirement exclusion applies to NVIDIA Endpoints featured selections. It does not determine whether another compatible endpoint serves the same model ID. | Select a supported NVIDIA Endpoints model. | `src/lib/inference/nvidia-featured-models.ts`, `src/lib/inference/nvidia-featured-models.test.ts`. | | OpenClaw primary agent | NVIDIA Endpoints | Any model from `CLOUD_MODEL_OPTIONS` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions. | `not-yet-run` | Add one evidence row per model before changing state. | Record `none`, model-specific setup, or provider-class transport behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/config.ts`. | -| OpenClaw primary agent | OpenAI | Any model from `REMOTE_MODEL_OPTIONS.openai` | `openai` provider through `https://inference.local/v1`. | `not-yet-run` | Add one evidence row per model before changing state. | Record Responses or Chat Completions behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | -| OpenClaw primary agent | Anthropic | Any model from `REMOTE_MODEL_OPTIONS.anthropic` | `anthropic` provider through `https://inference.local` with `anthropic-messages`. | `not-yet-run` | Add one evidence row per model before changing state. | Record native Anthropic Messages behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | -| OpenClaw primary agent | Gemini | Any model from `REMOTE_MODEL_OPTIONS.gemini` | Managed `inference.local` OpenAI-compatible route. | `not-yet-run` | Add one evidence row per model before changing state. | Record provider state and tool-result continuation behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`. | +| OpenClaw primary agent | OpenAI | Any model from `REMOTE_MODEL_OPTIONS.openai` | Attached OpenShell provider `nemoclaw-openai-api-v1` at `https://api.openai.com/v1` using OpenAI Responses or Chat Completions. | `not-yet-run` | Add one evidence row per model before changing state. | Record Responses or Chat Completions behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`, `src/lib/inference/native-hosted/profiles.ts`. | +| OpenClaw primary agent | Anthropic | Any model from `REMOTE_MODEL_OPTIONS.anthropic` | Attached OpenShell provider `nemoclaw-anthropic-prod-v1` at `https://api.anthropic.com` using Anthropic Messages. | `not-yet-run` | Add one evidence row per model before changing state. | Record native Anthropic Messages behavior explicitly. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`, `src/lib/inference/native-hosted/profiles.ts`. | +| OpenClaw primary agent | Gemini | Any model from `REMOTE_MODEL_OPTIONS.gemini` | Attached OpenShell provider `nemoclaw-gemini-api-v1` at `https://generativelanguage.googleapis.com/v1beta/openai` using OpenAI-compatible Chat Completions. | `not-yet-run` | Add one evidence row per model before changing state. | Record provider state and tool-result continuation behavior. | Expand into per-model rows as evidence lands. | `src/lib/inference/model-prompts.ts`, `src/lib/inference/config.ts`, `src/lib/inference/native-hosted/profiles.ts`. | | OpenClaw primary agent | Local Ollama | Default `nemotron-3-nano:30b` or any installed model selected by onboarding. | Managed `inference.local` route to the host Ollama proxy. | `not-yet-run` | Add local daemon, model tag, and trajectory evidence before changing state. | Record tool capability, streaming usage, and local proxy behavior. | Add one row per audited local model tag. | `src/lib/inference/local.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Local vLLM | Any model from `VLLM_MODELS`. | Managed `inference.local` route to the host vLLM server. | `not-yet-run` | Add vLLM serve flags, model id, and trajectory evidence before changing state. | Record parser flags, reasoning parser, and tool-call parser behavior. | Add one row per audited vLLM model id. | `src/lib/inference/vllm-models.ts`, `src/lib/inference/config.ts`. | | OpenClaw primary agent | Other OpenAI-compatible endpoint | User-selected `custom-model` or another configured model id. | Managed `inference.local` route to the compatible endpoint. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record endpoint API path forcing and store/streaming assumptions. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | | OpenClaw primary agent | Other Anthropic-compatible endpoint | User-selected `custom-anthropic-model` or another configured model id. | `anthropic` route when supported, otherwise managed compatible route. | `not-yet-run` | Add endpoint class and trajectory evidence before changing state. | Record native Anthropic Messages or compatible-route transport behavior. | Add one row per endpoint class that is validated. | `src/lib/inference/config.ts`. | -| Hermes sandbox API | Hermes Provider | Default `moonshotai/kimi-k2.6` or any model from `HERMES_PROVIDER_MODEL_OPTIONS`. | Hermes Provider route through NemoClaw managed inference. | `not-yet-run` | Add Hermes session, request dump, logs, and local API evidence before changing state. | Generated config uses native `tools.tool_search.enabled: on` with snake-case 5/20 limits; core tools stay direct while deferred MCP and non-core plugin tools use structured search, describe, and call. | Verify a deferred-tool trajectory and keep it separate from OpenClaw `mode: tools` evidence. | `agents/hermes/config/managed-policy.ts`, `test/generation/generate-hermes-config.test.ts`. | +| Hermes sandbox API | Hermes Provider | Default `moonshotai/kimi-k2.6` or any model from `HERMES_PROVIDER_MODEL_OPTIONS`. | Attached OpenShell provider `nemoclaw-hermes-provider-v1` at `https://inference-api.nousresearch.com/v1` using OpenAI-compatible Chat Completions. | `not-yet-run` | Add Hermes session, request dump, logs, and local API evidence before changing state. | Generated config uses native `tools.tool_search.enabled: on` with snake-case 5/20 limits; core tools stay direct while deferred MCP and non-core plugin tools use structured search, describe, and call. | Verify a deferred-tool trajectory and keep it separate from OpenClaw `mode: tools` evidence. | `agents/hermes/config/managed-policy.ts`, `src/lib/inference/native-hosted/profiles.ts`, `test/generation/generate-hermes-config.test.ts`. | | Deep Agents interactive `dcode` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add separate default-disabled and thread-opt-in terminal transcripts, host status output, reset evidence, and route evidence before changing state. | The managed Ultra profile preserves required nonempty tool-call content and rejects the observed literal `[content]` execute placeholder before shell dispatch; optional `thread-opt-in` remains a per-thread approval affordance. | Verify a terminal task with approval prompts intact, then separately verify explicit thread activation, reset behavior, policy enforcement, placeholder rejection, and no provider credential in sandbox-visible files. | `agents/langchain-deepagents-code/generate-config.ts`, `agents/langchain-deepagents-code/profile-plugin`, `docs/get-started/quickstart-langchain-deepagents-code`. | | Deep Agents headless `dcode -n` | NVIDIA Endpoints | `nvidia/nemotron-3-ultra-550b-a55b` | Attached OpenShell provider `nemoclaw-nvidia-prod-v1` at `https://integrate.api.nvidia.com/v1` using OpenAI-compatible Chat Completions with `use_responses_api = false`. | `not-yet-run` | Add headless command transcript and status output before changing state. | Headless mode uses the managed Ultra profile, preserves required nonempty tool-call content, rejects the observed literal `[content]` execute placeholder, has no approval UI, and auto-approves non-shell tools while managed shell execution remains disabled. | Verify a bounded non-shell task, placeholder rejection, and the approval boundary separately from interactive evidence. | `agents/langchain-deepagents-code/dcode-wrapper.sh`, `agents/langchain-deepagents-code/profile-plugin`, `docs/security/best-practices`. | diff --git a/docs/inference/switch-providers.mdx b/docs/inference/switch-providers.mdx index 871b2a689b4..f50e82a70b1 100644 --- a/docs/inference/switch-providers.mdx +++ b/docs/inference/switch-providers.mdx @@ -49,7 +49,7 @@ $$nemoclaw inference set --provider --model --sandbox ``` For `openrouter-api`, NemoClaw verifies the selected model through the sandbox before it commits agent configuration. -It skips the host-side provider probe because the OpenRouter adapter uses the sandbox-only `host.openshell.internal` route. +It verifies the native endpoint through the recorded sandbox-attached provider, preserving the required OpenRouter attribution headers. If sandbox verification fails, NemoClaw tries to restore the previous inference selection and does not commit the agent configuration. diff --git a/docs/inference/understand-provider-validation.mdx b/docs/inference/understand-provider-validation.mdx index a9de17568bc..20e54d2534e 100644 --- a/docs/inference/understand-provider-validation.mdx +++ b/docs/inference/understand-provider-validation.mdx @@ -52,7 +52,8 @@ If the last retry fails or times out, validation stops without another Chat Comp -The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. +The managed Deep Agents runtime keeps `use_responses_api = false` and uses Chat Completions. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. +Custom and local selections retain `https://inference.local/v1`. `NEMOCLAW_PREFERRED_API` does not change that runtime selection. diff --git a/docs/inference/use-anthropic.mdx b/docs/inference/use-anthropic.mdx index 913589f97d5..a9f295e287d 100644 --- a/docs/inference/use-anthropic.mdx +++ b/docs/inference/use-anthropic.mdx @@ -11,6 +11,7 @@ content: --- The Anthropic provider routes supported agents to the native Anthropic Messages API through OpenShell. The provider uses the `anthropic-messages` protocol. +OpenShell attaches the provider to the selected sandbox and supplies credentials for approved requests to `https://api.anthropic.com`. ## Credential diff --git a/docs/inference/use-google-gemini.mdx b/docs/inference/use-google-gemini.mdx index 2ff8745839d..bec21eb9258 100644 --- a/docs/inference/use-google-gemini.mdx +++ b/docs/inference/use-google-gemini.mdx @@ -10,7 +10,7 @@ content: type: "how_to" --- The Google Gemini provider routes NemoClaw to Google's OpenAI-compatible Chat Completions endpoint. -The sandbox continues to use the managed `inference.local` route. +The sandbox calls `https://generativelanguage.googleapis.com/v1beta/openai` through its attached OpenShell provider. ## Credential diff --git a/docs/inference/use-hermes-provider.mdx b/docs/inference/use-hermes-provider.mdx index 979b292d35a..a75ad08cc55 100644 --- a/docs/inference/use-hermes-provider.mdx +++ b/docs/inference/use-hermes-provider.mdx @@ -15,7 +15,8 @@ This option is available only for Hermes Agent. ## Credential Boundary -NemoClaw uses the host OpenShell provider registered during onboarding. +NemoClaw attaches the hosted provider to the selected sandbox during onboarding. +Hermes calls `https://inference-api.nousresearch.com/v1`, and OpenShell supplies the provider credential for approved requests. The sandbox does not receive raw provider credentials. ## Model Choices diff --git a/docs/inference/use-openai.mdx b/docs/inference/use-openai.mdx index 1128ef8f655..f66e6bd1a7e 100644 --- a/docs/inference/use-openai.mdx +++ b/docs/inference/use-openai.mdx @@ -10,7 +10,7 @@ content: type: "how_to" --- The OpenAI provider routes NemoClaw inference to the OpenAI API through OpenShell. -The sandbox uses the managed `inference.local` route and does not receive the raw OpenAI API key. +The sandbox calls `https://api.openai.com/v1` through its attached OpenShell provider and does not receive the raw OpenAI API key. ## Credential diff --git a/docs/inference/use-openrouter.mdx b/docs/inference/use-openrouter.mdx index 2c5f4042e38..e72a6661176 100644 --- a/docs/inference/use-openrouter.mdx +++ b/docs/inference/use-openrouter.mdx @@ -4,13 +4,13 @@ title: "Use OpenRouter" sidebar-title: "Use OpenRouter" description: "Configure NemoClaw to route hosted inference through OpenRouter." -description-agent: "Sets up OpenRouter as the NemoClaw inference provider. Use when onboarding with an OpenRouter API key or tracing the OpenRouter host adapter." -keywords: ["NemoClaw OpenRouter", "OpenRouter API key", "OpenRouter adapter"] +description-agent: "Sets up OpenRouter as the NemoClaw inference provider. Use when onboarding with an OpenRouter API key or checking native OpenRouter routing." +keywords: ["NemoClaw OpenRouter", "OpenRouter API key", "OpenRouter native endpoint"] content: type: "how_to" --- OpenRouter provides an OpenAI-compatible Chat Completions route for OpenClaw, Hermes, and LangChain Deep Agents Code. -NemoClaw keeps the sandbox on `https://inference.local/v1` and sends upstream traffic through a host adapter. +The sandbox calls `https://openrouter.ai/api/v1` through its attached OpenShell provider. ## Credential @@ -32,19 +32,12 @@ Run the onboarding wizard and select **OpenRouter**. $$nemoclaw onboard ``` -NemoClaw registers the `openrouter-api` provider through the OpenShell `openai` profile. +NemoClaw installs its OpenRouter provider profile and attaches the provider to the selected sandbox. -## Host Adapter +## Request Headers -NemoClaw starts or reuses a local host adapter on port `11437` by default. -It registers OpenShell with `OPENAI_BASE_URL=http://host.openshell.internal:11437/v1`. - -The adapter accepts only the OpenShell bearer credential bound during setup and forwards requests to `https://openrouter.ai/api/v1`. -It adds the default `HTTP-Referer` and `X-OpenRouter-Title` attribution headers. -The adapter does not store the API key. - -The adapter exposes a host health endpoint and writes logs to `~/.nemoclaw/openrouter-runtime-adapter.log`. -Set `NEMOCLAW_OPENROUTER_RUNTIME_ADAPTER_PORT` before onboarding to use a different host port. +NemoClaw configures the agent to send the `HTTP-Referer` and `X-OpenRouter-Title` attribution headers. +OpenShell keeps the API key outside the sandbox and replaces the agent's credential placeholder for approved OpenRouter requests. ## Validation @@ -53,5 +46,5 @@ NemoClaw skips the Responses API probe and uses managed Chat Completions at runt ## Related Topics -- [About Inference Routing](../about-inference-routing) explains why the sandbox does not call the adapter directly. +- [About Inference Routing](../about-inference-routing) explains the sandbox-attached provider and credential boundary. - [Understand Provider Validation](../validate-inference/understand-provider-validation) describes provider validation behavior. diff --git a/docs/inference/verify-inference-route.mdx b/docs/inference/verify-inference-route.mdx index f5ce92e2dab..9dd4585ac95 100644 --- a/docs/inference/verify-inference-route.mdx +++ b/docs/inference/verify-inference-route.mdx @@ -4,7 +4,7 @@ title: "Verify the Sandbox Inference Route" sidebar-title: "Verify the Inference Route" description: "Verify that a NemoClaw sandbox can reach its configured model through its selected inference provider." -description-agent: "Verifies the in-sandbox inference path for native NVIDIA providers and shared inference routes." +description-agent: "Verifies the in-sandbox inference path for native hosted providers and shared inference routes." keywords: ["verify inference provider", "nemoclaw inference route", "sandbox inference health"] content: type: "how_to" @@ -14,14 +14,14 @@ Reading the active route confirms configuration, but it does not authenticate a ## Confirm the Configured Route -Read the selected inference path first. +Read the selected sandbox's inference path first. ```bash -$$nemoclaw inference get +$$nemoclaw inference get ``` -For a selected sandbox with a valid native NVIDIA attachment, the command returns that sandbox's recorded provider, model, and `https://integrate.api.nvidia.com/v1` endpoint. -For other providers, the command reads the live shared gateway route. +For a selected sandbox with a valid native hosted attachment, the command returns that sandbox's recorded provider, model, and native endpoint, such as `https://api.openai.com/v1` for OpenAI or `https://integrate.api.nvidia.com/v1` for NVIDIA Endpoints. +For providers that still use the shared route, the command reads the live gateway route. Confirm that the provider, model, and endpoint match the path you intended to configure. ## Check Sandbox Inference Health @@ -32,9 +32,9 @@ Run the named sandbox status command. $$nemoclaw status ``` -For NVIDIA Endpoints, the `Inference` row verifies the recorded sandbox attachment. -It then sends a native Chat Completions request to `https://integrate.api.nvidia.com/v1`. -It does not probe `https://inference.local/v1/models` for this provider. +For fixed hosted providers, the `Inference` row verifies the recorded sandbox attachment. +It then sends an inference request to the selected native endpoint using the configured API family. +It does not probe `https://inference.local/v1/models` for these providers. For shared-route providers, the `Inference` row first checks the sandbox's `inference.local` path. When that route responds, `status` sends an inference request through the same path. @@ -44,8 +44,8 @@ The row reports `healthy` only when the route returns a structurally valid resul An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. Status diagnostics do not include the response body. An ordinary HTTP `404` from `/v1/models` reports an unhealthy route because the model catalog is absent. -The recorded `openrouter-api` provider uses NemoClaw's Chat Completions-only OpenRouter adapter. -Its models route returns `404` by design, so `status` requires a successful inference request before it reports the route as healthy. +OpenRouter uses its native `https://openrouter.ai/api/v1` endpoint through the recorded sandbox-attached provider. +Its status check requires a successful inference request for the selected model, with the required OpenRouter attribution headers. When the models route responds and `status` sends an inference request, a failing row names the endpoint that request used. When the models route itself does not respond, the row names the models route. An HTTP `401` or `403` response reports `unauthorized`. @@ -75,7 +75,7 @@ For those routes, continue to the final route check, then use the status command ## Understand Final Route Checks -For NVIDIA Endpoints, onboarding verifies the sandbox-attached provider through the native endpoint. +For fixed hosted providers, onboarding verifies the sandbox-attached provider through the selected native endpoint. It does not request the shared `inference.local` models route. For shared-route providers, onboarding first requests `https://inference.local/v1/models` from inside the sandbox after policy and process recovery. @@ -86,7 +86,6 @@ Each attempt allows 2 seconds for the route to return an HTTP response. For OpenClaw, this leaves time for client overhead before its 2.5-second provider preflight stops. A transport failure, an unsupported models-route HTTP 404, or HTTP 5xx leaves the onboarding session retryable at final verification. -For a supported OpenRouter agent, onboarding accepts the adapter's catalog 404 only after a bounded inference request validates the selected model. Onboarding retries any other 404 within its startup budget, then reports the missing model catalog and exits nonzero if the failure persists. Confirm the provider and model configuration and restore the endpoint's `/v1/models` route. Run `$$nemoclaw onboard --resume` to verify the retained session again without rebuilding a healthy sandbox. diff --git a/docs/inference/view-active-inference-route.mdx b/docs/inference/view-active-inference-route.mdx index f343f98318b..bb4b7025955 100644 --- a/docs/inference/view-active-inference-route.mdx +++ b/docs/inference/view-active-inference-route.mdx @@ -3,8 +3,8 @@ # SPDX-License-Identifier: Apache-2.0 title: "View the Selected Inference Path" sidebar-title: "View the Inference Path" -description: "Inspect a sandbox-attached NVIDIA provider or the live NemoClaw-managed OpenShell inference route." -description-agent: "Shows the selected sandbox's native NVIDIA provider path or the live shared route for another provider. Use when checking the active inference path." +description: "Inspect a sandbox-attached hosted provider or the live shared OpenShell inference route." +description-agent: "Shows the selected sandbox native hosted provider path or its live shared route. Use when checking inference configuration." keywords: ["nemoclaw inference get", "active inference provider", "active inference model", "compatible endpoint URL"] content: @@ -12,8 +12,8 @@ content: --- Use the NemoClaw CLI to read the selected inference provider and model. -When the selected sandbox has a valid native NVIDIA provider attachment, the command reports the sandbox's recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. -For other providers, the command reads the live OpenShell inference route. +When the selected sandbox has a valid recorded native hosted provider attachment, the command reports its recorded provider, model, and fixed profile endpoint without reading the shared gateway route. +For other selections, the command reads the live shared OpenShell inference route. For a compatible custom provider, the command also reports its persisted endpoint URL when the registry provider and model match the live route. This command reports configuration state and does not authenticate a model request. @@ -21,8 +21,8 @@ This command reports configuration state and does not authenticate a model reque Run the direct route command when you need the active provider, model, and applicable custom endpoint URL. The direct form first checks the default sandbox in the registry that `NEMOCLAW_GATEWAY_PORT` selects. -It reports that sandbox's native NVIDIA provider path when a valid attachment exists. -Otherwise, it reads the gateway that `NEMOCLAW_GATEWAY_PORT` selects. +It reports that sandbox's native hosted provider path when a valid recorded attachment exists. +Otherwise, it reads the shared route on the selected gateway. ```bash $$nemoclaw inference get @@ -72,8 +72,9 @@ Endpoint: https://inference.example.com/v1 } ``` -A valid native NVIDIA attachment adds the fixed NVIDIA endpoint to the provider-and-model output. -Other managed providers keep the provider-and-model output. +Native hosted providers report the provider and model recorded for the selected sandbox, plus the profile's fixed endpoint. +This output does not verify that the attachment or credential is currently usable; run the named sandbox status command for that check. +The following endpoint-omission rules apply to shared compatible routes. Unpublished sandbox rows do not participate in endpoint selection. Equivalent stored URL forms, such as a trailing slash difference, count as the same endpoint identity. NemoClaw omits the endpoint when participating registry metadata is absent, conflicting, invalid, too long, uses another path shape, or contains userinfo, a query, a fragment, control characters, or recognized credential material in any URL component. @@ -103,11 +104,12 @@ $$nemoclaw inference get ``` `NEMOCLAW_GATEWAY_PORT` first selects the sandbox registry and fallback gateway. -When the named sandbox has a valid native NVIDIA provider attachment, the command reports its recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. +When the named sandbox has a valid recorded native hosted provider attachment, the command reports its recorded provider, model, and fixed profile endpoint without reading the shared gateway route. Otherwise, when that registry contains the named sandbox, the command resolves its recorded gateway and reads that gateway-wide route. For a compatible custom provider, the command reports an endpoint only when every eligible published row on the resolved gateway matches the live route and records the same safe, reusable endpoint. The command does not search registries for other gateway ports. -For other providers, OpenShell exposes one inference route to every sandbox registered on the same gateway. +The shared inference route applies to sandboxes that still use `inference.local`. +Native hosted selections use their own sandbox attachments. ## Include Sandbox Health diff --git a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx index 3ff6f514088..c30b133c6a6 100644 --- a/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx +++ b/docs/manage-sandboxes/recover-rebuild-sandboxes.mdx @@ -190,14 +190,14 @@ During the lease, `launch` still verifies the owning OpenShell gateway, exact li Every configured route must serve a valid response to a bounded request for the recorded model before NemoClaw accepts or publishes launch readiness. Shared-route providers use `inference.local`. -Their models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. -NVIDIA Endpoints verifies its sandbox-attached provider at `integrate.api.nvidia.com` and runs the bounded model request without the shared-route models probe. +Their models probe must return HTTP 2xx. +Fixed hosted providers verify their sandbox-attached OpenShell provider and run the bounded model request at their native endpoint without the shared-route models probe. A failed required probe or model request rejects launch readiness. This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. Every configured route must serve a valid response to a bounded request for the recorded model before NemoClaw accepts or publishes launch readiness. -The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models`. +Shared-route providers require HTTP 2xx from the models probe. Fixed hosted providers verify their sandbox-attached provider and send the model request to its native endpoint. A failed request rejects launch readiness and identifies the inference request as the failed check. diff --git a/docs/manage-sandboxes/workspace-files.mdx b/docs/manage-sandboxes/workspace-files.mdx index 9bf47acf798..3dec004cf5e 100644 --- a/docs/manage-sandboxes/workspace-files.mdx +++ b/docs/manage-sandboxes/workspace-files.mdx @@ -283,7 +283,7 @@ Deep Agents Code normally creates the `/sandbox/.deepagents/agent/` paths below | Path | Purpose | |---|---| -| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path, including shared `inference.local` routes or the native NVIDIA provider. | +| `/sandbox/.deepagents/config.toml` | NemoClaw-generated model and provider configuration for the selected OpenShell-managed inference path, including shared `inference.local` routes or a native hosted provider. | | `/sandbox/.deepagents/.state/` | Deep Agents Code runtime state, including persisted session and MCP-related state. | | `/sandbox/.deepagents/agent/AGENTS.md` | Global memory file for the default Deep Agents Code agent, loaded at session start. | | `/sandbox/.deepagents/agent/memories/` | Topic-specific markdown memories that Deep Agents Code can read and update across sessions. | diff --git a/docs/monitoring/monitor-sandbox-activity.mdx b/docs/monitoring/monitor-sandbox-activity.mdx index 63a656bae2b..2905a0dae8b 100644 --- a/docs/monitoring/monitor-sandbox-activity.mdx +++ b/docs/monitoring/monitor-sandbox-activity.mdx @@ -27,7 +27,7 @@ Run the status command to view sandbox state, gateway health, and the active inf $$nemoclaw status ``` -`$$nemoclaw status` probes the selected provider path from inside the sandbox as the authoritative inference check. Shared providers use `https://inference.local/v1/models`. NVIDIA Endpoints uses the sandbox-attached OpenShell provider at `https://integrate.api.nvidia.com/v1` and verifies it with an inference request. +`$$nemoclaw status` probes the selected provider path from inside the sandbox as the authoritative inference check. Custom, local, and Model Router selections use `https://inference.local/v1/models`. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers and verify them with an inference request. For local Ollama and local vLLM routes, it also prints labeled host-side backend diagnostics that help identify which hop failed. Review these output fields. diff --git a/docs/reference/architecture.mdx b/docs/reference/architecture.mdx index 11fe4fce8a5..5c6278e6d65 100644 --- a/docs/reference/architecture.mdx +++ b/docs/reference/architecture.mdx @@ -29,8 +29,8 @@ graph LR USER(["👤 User"]):::user subgraph EXTERNAL["External Services"] - SHARED_INFERENCE["Shared-route inference providers
OpenAI · Anthropic · Ollama
vLLM · Model Router
"]:::external - NVIDIA_INFERENCE["NVIDIA Endpoints
integrate.api.nvidia.com"]:::external + SHARED_INFERENCE["Shared-route inference providers
Custom endpoints · Ollama
vLLM · Model Router
"]:::external + HOSTED_INFERENCE["Fixed hosted providers
Selected native endpoint"]:::external INTEGRATIONS["Integration APIs
MCP · GitHub · package indexes"]:::external INTERNET["Internet
PyPI · npm · GitHub · APIs"]:::external end @@ -65,9 +65,9 @@ graph LR BP -->|"Defines sandbox
shape + policies"| SANDBOX STATE -->|"Backup + restore"| SANDBOX - AGENT -->|"Most inference requests
inference.local · no credentials"| GW + AGENT -->|"Shared-route inference requests
inference.local · no credentials"| GW GW -->|"Shared-route request with
credential injected"| SHARED_INFERENCE - AGENT -->|"Attached NVIDIA provider
restricted request · placeholder credential"| NVIDIA_INFERENCE + AGENT -->|"Attached hosted provider
restricted request · placeholder credential"| HOSTED_INFERENCE INTEGRATIONS -->|"External APIs"| INTEG INTEG -->|"Policy-gated access"| AGENT @@ -171,14 +171,14 @@ graph TB end end - SHARED_INFER["Shared-route inference provider
OpenAI · Anthropic · Ollama
vLLM · Model Router
"]:::external - NVIDIA_INFER["NVIDIA Endpoints
integrate.api.nvidia.com"]:::external + SHARED_INFER["Shared-route inference provider
Custom endpoints · Ollama
vLLM · Model Router
"]:::external + HOSTED_INFER["Fixed hosted providers
Selected native endpoint"]:::external CLI -->|"openshell CLI
(orchestrates)"| GW GW -->|"creates/recreates
Docker-driver sandbox"| SANDBOX SANDBOX -->|"shared-route requests
inference.local · placeholder credentials"| GW GW -->|"shared-route egress
credential injected at L7 proxy"| SHARED_INFER - SANDBOX -->|"attached NVIDIA provider
restricted egress · placeholder rewritten"| NVIDIA_INFER + SANDBOX -->|"attached hosted provider
restricted egress · placeholder rewritten"| HOSTED_INFER class HOST host class DOCKER docker @@ -195,12 +195,12 @@ Layering from top to bottom: | Docker daemon | Host service | Runs the Docker-driver sandbox container and, on affected Linux hosts, the optional gateway compatibility container. | | Sandbox container | Docker container | Runs the selected supported agent runtime and NemoClaw integration under Landlock + seccomp + netns. | | OpenShell L7 proxy | Gateway process | Intercepts shared-route agent egress and rewrites `Authorization` headers (Bearer/Bot) and URL-path segments to inject the real credential at the network boundary. | -| OpenShell attached NVIDIA provider | Provider profile attached to the sandbox | Restricts NVIDIA Endpoints egress by host, method, path, and binary, then rewrites the placeholder credential at the egress boundary. | +| OpenShell attached hosted provider | Provider profile attached to the sandbox | Restricts fixed hosted provider egress by host, method, path, and binary, then rewrites the placeholder credential at the egress boundary. | NemoClaw never gives the sandbox a raw provider key. At onboard time it registers credentials with OpenShell's provider and placeholder system. Shared routes use the gateway L7 proxy to substitute the real value at egress. -NVIDIA Endpoints uses the sandbox-attached provider profile to enforce the restricted request and replace its placeholder at egress. +Fixed hosted providers use sandbox-attached provider profiles to enforce restricted requests and replace their placeholders at egress. The CLI helper `isInferenceRouteReady` (in `src/lib/onboard.ts`) is a host-side readiness check used by the resume flow to decide whether the active route already covers the chosen provider and model. It is not a runtime component. @@ -358,20 +358,20 @@ Inside the sandbox: ## Inference Routing Agent inference follows one of two OpenShell-managed paths. -Most providers use the shared `inference.local` route through the OpenShell gateway: +Custom, local, and Model Router selections use the shared `inference.local` route through the OpenShell gateway: ```text Supported agent runtime (sandbox) ──▶ inference.local ──▶ OpenShell gateway ──▶ Provider endpoint ``` -NVIDIA Endpoints uses a restricted provider attached to the sandbox: +NVIDIA Endpoints, OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider use restricted providers attached to the sandbox: ```text -Supported agent runtime (sandbox) ──▶ integrate.api.nvidia.com ──▶ NVIDIA Endpoints +Supported agent runtime (sandbox) ──▶ Selected native endpoint ──▶ Hosted provider OpenShell attached-provider policy and placeholder rewrite ``` -The NVIDIA request does not use the shared `inference.local` route. +These hosted requests do not use the shared `inference.local` route. The attached OpenShell profile allows only the configured endpoint, methods, paths, and binaries, and it replaces the placeholder credential at egress. When you select the Model Router provider, the OpenShell gateway routes to a host-side router process instead of a single upstream model. @@ -397,7 +397,7 @@ Refer to [Choose an Inference Provider](../inference/learn-and-choose/choose-inf Provider credentials live in OpenShell's credential store, not on the host filesystem. NemoClaw never writes them to host disk. The OpenShell L7 proxy injects values for shared routes. -The sandbox-attached NVIDIA provider rewrites its placeholder credential at egress. +The sandbox-attached hosted provider rewrites its placeholder credential at egress. Refer to [Credential Storage](../security/credential-storage) for the inspection, rotation, and migration flow. ## Host-Side State and Config diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index fbf215fa45e..52ecc55a38d 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -322,7 +322,8 @@ If either identity cannot be verified, do not remove files by name alone. Do not remove the requested output file to clean up a temporary link. Version 1 exports Docker-managed OpenClaw sandboxes and canonical managed Hermes or LangChain Deep Agents Code sandboxes in the default workspace. -Supported sandboxes use hosted external inference or the native NVIDIA hosted provider with its default endpoint, an immutable managed image, a NemoClaw-owned gateway, and an explicit representable policy. +Supported sandboxes use hosted external inference or a fixed native hosted provider with its default endpoint, an immutable managed image, a NemoClaw-owned gateway, and an explicit representable policy. +Native hosted export requires a matching provider profile, attachment receipt, endpoint, API family, and credential reference. OpenClaw exports for attached Ollama with a managed proxy and the fixed managed vLLM profile include a named service with `image: null`. Replace only that value with an official, immutable, compatible v1 runtime image before v1 parsing or planning. Other local inference and Podman exports remain deferred. @@ -1148,8 +1149,8 @@ During that lease, another `launch` still verifies these conditions: - The recorded inference selection matches its provider path, and every configured route serves a valid response to a bounded request for the recorded model. Shared-route providers use `inference.local`. - NVIDIA Endpoints verifies the recorded sandbox-attached provider and sends the request to `https://integrate.api.nvidia.com/v1`. - The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models` when the bounded model request succeeds. + Fixed hosted providers verify the recorded sandbox-attached provider and send the request to the selected native endpoint. + The shared-route models probe must return HTTP 2xx. A failed model request rejects readiness before the agent starts. This check is stricter than the HTTP 200–499 reachability diagnostic used by ordinary `connect`. @@ -1157,7 +1158,7 @@ During that lease, another `launch` still verifies these conditions: - The recorded inference selection matches the live route, and every configured route serves a valid response to a bounded request for the recorded model. - The models probe must return HTTP 2xx, except that `openrouter-api` can return HTTP 404 for `GET /v1/models`. + Shared-route providers require HTTP 2xx from the models probe. Fixed hosted providers verify their sandbox-attached provider and send the model request to its native endpoint. A failed model request rejects readiness before the agent starts. @@ -1230,7 +1231,7 @@ A recognized broken shared-route result lets `connect` attempt DNS or route repa When the initial shared-route probe cannot return a trusted result, `connect` fails closed before health-driven repair and before opening SSH. It prints a bounded, redacted last-probe detail and points you to `$$nemoclaw doctor`. -For NVIDIA Endpoints, `connect` does not inspect or change the unrelated shared route. +For fixed hosted providers, `connect` does not inspect or change the unrelated shared route. It verifies the recorded sandbox-attached provider and sends a native inference request for the selected model. The request must return a structurally valid successful inference result before `connect` opens SSH. @@ -1658,7 +1659,7 @@ $$nemoclaw my-assistant start When that deadline expires, `start` keeps the existing container, exits non-zero, and prints the `NEMOCLAW_CONNECT_TIMEOUT` value to use on the next run. -After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Most providers use `https://inference.local`; NVIDIA Endpoints uses the sandbox-attached OpenShell provider for `https://integrate.api.nvidia.com/v1`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. For a shared gateway route, `doctor` still classifies an HTTP `401` or `403` response as reachable. The native NVIDIA doctor probe instead requires a 2xx response from the sandbox-attached provider. Correct the provider credential when `start` reports either status. +After the gateway and forward checks pass, `start` sends one inference request through the sandbox's selected provider path using its recorded provider and model. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local`. A reachable provider path can still reject an inference request or return an invalid result, so the command exits non-zero in either case. It prints the probe result, including the HTTP status when the path returned one, and points you to the sandbox doctor command. Ordinary providers request 16 reply tokens; Gemini requests 256 reply tokens so reasoning has room before visible content. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Each run consumes provider tokens on a hosted path. When the sandbox records no provider or no model, `start` skips the request and exits `0`. For a shared gateway route, `doctor` still classifies an HTTP `401` or `403` response as reachable. Native hosted doctor checks require a 2xx models response for NVIDIA Endpoints, or a valid inference response for other fixed hosted providers. Correct the provider credential when `start` reports either status. ### `$$nemoclaw status` @@ -1673,7 +1674,7 @@ nonzero. A stopped runtime without recorded stop intent remains a For a `compatible-endpoint` route that uses `openai-completions`, the text output prints `Reasoning effort` as `low`, `medium`, `high`, or `endpoint-default`. The line is omitted for another provider or API family. -Pass `--json` to emit a structured per-sandbox report instead of the text renderer. The JSON output includes at least `schemaVersion`, `name`, `found`, `agent`, `agentDisplayName`, `agentRuntime`, `dcodeAutoApprovalMode`, `model`, `provider`, `recordedRoute`, `liveRoute`, `routeDrift`, `phase`, `gatewayState`, `inferenceHealth`, `rpcIssue`, `hostGpuDetected`, `sandboxGpuEnabled`, `sandboxGpuMode`, `sandboxGpuDevice`, `openshellDriver`, `openshellVersion`, `policies`, `policiesAvailable`, `llamaCpp`, `failureLayer`, `terminalRuntimeHealth`, `servingProcessHealth`, and `dockerPaused`. `policies` is derived from the current OpenShell policy; NemoClaw does not persist a second preset list or baseline-exclusion ledger. `policiesAvailable` is `false` when that live policy cannot be read or parsed, distinguishing an unavailable result from a verified empty `policies` array; text status prints `Policies: unavailable` for the same state. When the live gateway route matches the sandbox's recorded llama.cpp route, `llamaCpp.kind` is `attached`, `managed`, or `unavailable`. An attached route also includes its fixed loopback `llamaCpp.endpointUrl`. An unavailable result means NemoClaw could not safely verify the managed ownership receipt; it does not include an endpoint and provides a secret-free diagnostic and recovery action. During route drift, `status` omits the `llamaCpp` route attribution; inspect `routeDrift` before acting on endpoint information. Text status can still show managed-runtime details from the sandbox-owned receipt. The schema-version `1` `model` and `provider` fields keep their established live-route meaning when the gateway route is readable, except that a native NVIDIA sandbox reports its recorded sandbox-scoped route because the shared route is unrelated. Use `recordedRoute` for the sandbox's durable provider and model and `liveRoute` for the gateway-global route. When the live shared route differs for a shared-route provider, text output prints both routes and JSON output sets `routeDrift.live`, `routeDrift.recorded`, and `routeDrift.canConnect`. Native NVIDIA attachments do not report shared-route drift. When `routeDrift.canConnect` is `false`, `connect` cannot safely restore the recorded route because provider-global identity differs or required route or gateway metadata is incomplete. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for the route-sharing workflow. `openshellDriver` and `openshellVersion` are always strings (falling back to `"unknown"` when the registry has no value), so consumers can rely on `typeof` checks. `agent` is always a string and reports `openclaw` when the registry records no agent for the sandbox. `failureLayer` is `null` when no preflight failure was detected and otherwise one of `docker_unreachable`, `sandbox_container_stopped`, or `sandbox_dashboard_port_conflict`; when set, `inferenceHealth` is suppressed to `null` so automation does not see a stale remote-provider healthy status during a local outage. `inferenceHealth.ok` reports whether the selected provider path returned a structurally valid result for one request sent from inside the sandbox. The result must match Chat Completions, Responses, or Anthropic Messages for the selected route. An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. The probe captures at most 64 KiB and does not include the response body in diagnostics. The path probe treats any final HTTP status from `200` through `499` as reachable, so a route with an invalidated provider credential answers HTTP `401` while the path is up. Shared-route requests use the live gateway route's provider and model, then fall back to the recorded values when the live route is unreadable. Native NVIDIA requests always use the sandbox's recorded provider and model. When the live shared provider matches the recorded provider, the request uses the sandbox's recorded API family, even when only the model differs. This includes `openai-responses`. When the live shared provider differs, NemoClaw does not carry the recorded API family to that provider. Each attempt requests 16 reply tokens for ordinary providers or 256 for Gemini. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Hosted requests consume provider tokens on every attempt. When the inference request returns HTTP `429`, `502`, `503`, or `504`, `status` retries the provider path and inference request together up to three total attempts, with a two-second delay between failed attempts, because those statuses are transient gateway and availability answers rather than evidence that the path is broken. Before each retry, it writes the failed probe boundary, an HTTP status when one is available, the next attempt, total attempts, and delay to stderr; `--json` keeps stdout machine-readable. On an ordinary run, every other failure is final on the first attempt with no delay: HTTP `401`, `403`, `404`, and `500`, an invalid 2xx response body, a request that returned no HTTP status, and a failing provider-path probe. When the same run recovers a managed gateway, `status` retries any failed route or inference probe on that schedule instead, while the restarted delivery chain settles. Each route probe has a 10-second timeout. Three complete route probes plus their 95-second inference wrappers and two delays can take about 319 seconds. When NemoClaw sends an inference request, `inferenceHealth.subprobes` reports the provider-path result as the `route reachability` hop, so a failing verdict still shows that the path itself answered. `inferenceHealth.failureLabel` reports why the inference request failed: +Pass `--json` to emit a structured per-sandbox report instead of the text renderer. The JSON output includes at least `schemaVersion`, `name`, `found`, `agent`, `agentDisplayName`, `agentRuntime`, `dcodeAutoApprovalMode`, `model`, `provider`, `recordedRoute`, `liveRoute`, `routeDrift`, `phase`, `gatewayState`, `inferenceHealth`, `rpcIssue`, `hostGpuDetected`, `sandboxGpuEnabled`, `sandboxGpuMode`, `sandboxGpuDevice`, `openshellDriver`, `openshellVersion`, `policies`, `policiesAvailable`, `llamaCpp`, `failureLayer`, `terminalRuntimeHealth`, `servingProcessHealth`, and `dockerPaused`. `policies` is derived from the current OpenShell policy; NemoClaw does not persist a second preset list or baseline-exclusion ledger. `policiesAvailable` is `false` when that live policy cannot be read or parsed, distinguishing an unavailable result from a verified empty `policies` array; text status prints `Policies: unavailable` for the same state. When the live gateway route matches the sandbox's recorded llama.cpp route, `llamaCpp.kind` is `attached`, `managed`, or `unavailable`. An attached route also includes its fixed loopback `llamaCpp.endpointUrl`. An unavailable result means NemoClaw could not safely verify the managed ownership receipt; it does not include an endpoint and provides a secret-free diagnostic and recovery action. During route drift, `status` omits the `llamaCpp` route attribution; inspect `routeDrift` before acting on endpoint information. Text status can still show managed-runtime details from the sandbox-owned receipt. The schema-version `1` `model` and `provider` fields keep their established live-route meaning when the gateway route is readable, except that a native hosted sandbox reports its recorded sandbox-scoped route because the shared route is unrelated. Use `recordedRoute` for the sandbox's durable provider and model and `liveRoute` for the gateway-global route. When the live shared route differs for a shared-route provider, text output prints both routes and JSON output sets `routeDrift.live`, `routeDrift.recorded`, and `routeDrift.canConnect`. Native hosted attachments do not report shared-route drift. When `routeDrift.canConnect` is `false`, `connect` cannot safely restore the recorded route because provider-global identity differs or required route or gateway metadata is incomplete. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for the route-sharing workflow. `openshellDriver` and `openshellVersion` are always strings (falling back to `"unknown"` when the registry has no value), so consumers can rely on `typeof` checks. `agent` is always a string and reports `openclaw` when the registry records no agent for the sandbox. `failureLayer` is `null` when no preflight failure was detected and otherwise one of `docker_unreachable`, `sandbox_container_stopped`, or `sandbox_dashboard_port_conflict`; when set, `inferenceHealth` is suppressed to `null` so automation does not see a stale remote-provider healthy status during a local outage. `inferenceHealth.ok` reports whether the selected provider path returned a structurally valid result for one request sent from inside the sandbox. The result must match Chat Completions, Responses, or Anthropic Messages for the selected route. An empty body, malformed JSON, provider-error envelope, or wrong response shape reports `unhealthy`, even with a 2xx status. The probe captures at most 64 KiB and does not include the response body in diagnostics. The path probe treats any final HTTP status from `200` through `499` as reachable, so a route with an invalidated provider credential answers HTTP `401` while the path is up. Shared-route requests use the live gateway route's provider and model, then fall back to the recorded values when the live route is unreadable. Native hosted requests always use the sandbox's recorded provider and model. When the live shared provider matches the recorded provider, the request uses the sandbox's recorded API family, even when only the model differs. This includes `openai-responses`. When the live shared provider differs, NemoClaw does not carry the recorded API family to that provider. Each attempt requests 16 reply tokens for ordinary providers or 256 for Gemini. The request allows up to 90 seconds, and the host wrapper allows 95 seconds for bounded process startup and cleanup. Hosted requests consume provider tokens on every attempt. When the inference request returns HTTP `429`, `502`, `503`, or `504`, `status` retries the provider path and inference request together up to three total attempts, with a two-second delay between failed attempts, because those statuses are transient gateway and availability answers rather than evidence that the path is broken. Before each retry, it writes the failed probe boundary, an HTTP status when one is available, the next attempt, total attempts, and delay to stderr; `--json` keeps stdout machine-readable. On an ordinary run, every other failure is final on the first attempt with no delay: HTTP `401`, `403`, `404`, and `500`, an invalid 2xx response body, a request that returned no HTTP status, and a failing provider-path probe. When the same run recovers a managed gateway, `status` retries any failed route or inference probe on that schedule instead, while the restarted delivery chain settles. Each route probe has a 10-second timeout. Three complete route probes plus their 95-second inference wrappers and two delays can take about 319 seconds. When NemoClaw sends an inference request, `inferenceHealth.subprobes` reports the provider-path result as the `route reachability` hop, so a failing verdict still shows that the path itself answered. `inferenceHealth.failureLabel` reports why the inference request failed: - `unauthorized` when the route rejected it with HTTP `401` or `403`. - `unhealthy` when the route returned another failing HTTP status or an invalid 2xx response body. @@ -1706,7 +1707,7 @@ $$nemoclaw my-assistant status --json $$nemoclaw sandbox status my-assistant --json ``` -The command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. Most providers use `https://inference.local/v1`; NVIDIA Endpoints uses the sandbox-attached provider for `https://integrate.api.nvidia.com/v1`. That inference request is the authoritative inference health check, and both checks exercise the path that agent traffic uses. The main `Inference` line reports one of these states: +The command probes the selected provider path from inside the sandbox, and when that probe reports the path reachable it sends an inference request over the same path. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `https://inference.local/v1`. That inference request is the authoritative inference health check, and both checks exercise the path that agent traffic uses. The main `Inference` line reports one of these states: | State | Meaning | | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -1718,9 +1719,9 @@ The command probes the selected provider path from inside the sandbox, and when | `not probed` | NemoClaw could not run the authoritative route probe from a reachable sandbox. | | `not verified` | NemoClaw could not verify the sandbox or gateway state, so it skips inference probing. | -An authentication response on a shared gateway route probe confirms that the route is reachable, not that provider credentials are valid. For those shared routes, `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. The native NVIDIA doctor probe is different: it verifies the sandbox-attached provider directly and requires a 2xx response. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. +An authentication response on a shared gateway route probe confirms that the route is reachable, not that provider credentials are valid. For those shared routes, `$$nemoclaw doctor` sends no inference request, so it reports an HTTP `401` or `403` route response as reachable and exits `0` where `status` reports `unauthorized`. Native hosted checks first verify the recorded sandbox-attached provider. NVIDIA Endpoints requires a 2xx models response; other fixed hosted providers require a structurally valid response to an inference request for the recorded model. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative selected-provider result or determine the command exit status. -The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` sends no inference request, so it always reports the `Inference (upstream)` state that it measured. +The `Inference (upstream)` check authenticates with the host credential that NemoClaw resolves for the provider, such as `NVIDIA_INFERENCE_API_KEY`. OpenShell stores the credential that the sandbox's selected provider path uses. The CLI cannot read the stored value back, so the two credentials can hold different secrets. When the managed sandbox path has already served the inference request, an `unauthorized` result on `Inference (upstream)` describes the host credential. NemoClaw then reports that check as `not probed` and names both credential sources. An `Inference (upstream)` check that fails for another reason, such as `unreachable`, still reports its own state. Local backend and auth proxy checks, such as `Inference (auth proxy)`, always report their own state and their own repair step. `$$nemoclaw doctor` always reports the `Inference (upstream)` state that it measured; that host-side diagnostic does not override its authoritative sandbox check. Local providers add host-side backend diagnostics. For Local Ollama, the command can also print an `Inference (auth proxy)` diagnostic when a proxy token is available. Use these diagnostics to identify a failing auxiliary hop after checking the main `Inference` line. @@ -1861,7 +1862,8 @@ The `Registered gateway binding` result depends on the sandbox registry: - For a registered sandbox with an invalid binding, the check fails, and `doctor` does not select, probe, or recover a gateway from that binding. - For an unregistered sandbox name, `doctor` uses the gateway selected by `NEMOCLAW_GATEWAY_PORT` for its other gateway checks and omits the `Registered gateway binding` check. -For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Most providers probe the shared gateway route at `https://inference.local/v1/models`; responses from `200` through `499`, including `401` and `403`, pass that reachability check. NVIDIA Endpoints instead probes its sandbox-attached provider at `https://integrate.api.nvidia.com/v1/models` and requires a 2xx response. For the shared route, HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. For native NVIDIA, any non-2xx response or unavailable probe fails it. Host-side upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox path is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. + +For inference health, `doctor` treats the selected provider path inside the sandbox as authoritative. Custom, local, and Model Router selections probe the shared gateway route at `https://inference.local/v1/models`; responses from `200` through `499`, including `401` and `403`, pass that reachability check. NVIDIA Endpoints instead probes its sandbox-attached provider at `https://integrate.api.nvidia.com/v1/models` and requires a 2xx response. For the shared route, HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. For native NVIDIA, any non-2xx response or unavailable probe fails it. Other fixed hosted providers verify their recorded sandbox attachment and send an inference request to the selected native endpoint; a missing attachment, failed request, or invalid response fails the check. Host-side upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox path is reachable. For gateway runtimes, `doctor` also reports an informational `Serving process: not checked` result because its fresh sandbox probes do not attest the long-running gateway process. This result does not fail the readiness check. Terminal runtimes omit it because they have no long-running gateway process. The `Inference` `Route` check warns when either the provider or model is unknown. After the gateway is healthy, run `$$nemoclaw status` to refresh the route information. Warnings do not make the command fail. Failed checks, including a failed or unavailable authoritative inference route, exit non-zero so scripts can use `doctor` as a readiness gate. Use `--json` for machine-readable output. For a `compatible-endpoint` route that uses `openai-completions`, the JSON report includes an informational `Inference` check labeled `Reasoning effort`. The check reports `low`, `medium`, `high`, or `endpoint-default` and never includes credentials. Because the check has `info` status, it does not change the command's exit status. @@ -2060,7 +2062,7 @@ The sandbox must be running for `nemohermes my-assistant gateway-token --quiet` -`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. Most model traffic uses the OpenShell-managed `inference.local` route. NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. +`gateway-token` is not applicable to Deep Agents sandboxes because there is no OpenClaw gateway token. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the OpenShell-managed `inference.local` route. @@ -3232,7 +3234,7 @@ After the rebuild succeeds, retrieve the replacement token with `nemohermes my-a
-After restore, the command starts Deep Agents with the complete source native home, including `config.toml`, hooks, skills, memories, histories, packages, and unrelated native entries. Before changing the sandbox, rebuild verifies that the recorded provider path is still reachable and that the target provider, model, reasoning settings, web search selection, base image, current agent MCP source, and current live OpenShell policy can be captured. Most providers use `inference.local`; NVIDIA Endpoints uses its sandbox-attached provider at `integrate.api.nvidia.com`. If those checks fail after backup, NemoClaw keeps the existing sandbox intact. Use rebuild after a failed Deep Agents version check, after enabling Tavily Search, or as the apply step for legacy MCP migration. +After restore, the command starts Deep Agents with the complete source native home, including `config.toml`, hooks, skills, memories, histories, packages, and unrelated native entries. Before changing the sandbox, rebuild verifies that the recorded provider path is still reachable and that the target provider, model, reasoning settings, web search selection, base image, current agent MCP source, and current live OpenShell policy can be captured. Custom, local, and Model Router selections use `inference.local`; fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. If those checks fail after backup, NemoClaw keeps the existing sandbox intact. Use rebuild after a failed Deep Agents version check, after enabling Tavily Search, or as the apply step for legacy MCP migration. @@ -3498,7 +3500,7 @@ When at least one sandbox is registered and the named NemoClaw gateway is unreac ### `$$nemoclaw inference get` Show the provider and model for the selected inference path. -When the selected sandbox has a valid native NVIDIA provider attachment, the command reports its recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. +When the selected sandbox has a valid native hosted provider attachment, the command reports its recorded provider, model, and fixed profile endpoint without reading the shared gateway route. For other providers, the command reports the active live route from the NemoClaw-managed OpenShell gateway that `NEMOCLAW_GATEWAY_PORT` selects. For a compatible custom provider, also show the persisted endpoint URL when the selected gateway's matching registry metadata is safe, unambiguous, and reusable. Use this command when you want the selected inference path without the rest of the sandbox status output. @@ -3509,13 +3511,13 @@ $$nemoclaw inference get $$nemoclaw inference get --json ``` -A valid native NVIDIA attachment adds the fixed NVIDIA endpoint to the recorded provider-and-model output. +A valid native hosted attachment adds the fixed profile endpoint to the recorded provider-and-model output. Other managed providers keep the provider-and-model output. Compatible providers add the endpoint only when published same-gateway metadata matches the live route and is safe to display; otherwise the command keeps the live provider and model and returns credential-free recovery information. Refer to [View the Selected Inference Path](../inference/manage-inference/view-active-inference-route) for the exact text and JSON fields, omission states, safety rules, and recovery procedures. For the sandbox-first grammar, `NEMOCLAW_GATEWAY_PORT` first selects the sandbox registry and fallback gateway. -When `` has a valid native NVIDIA provider attachment, the command reports its recorded provider, model, and fixed NVIDIA endpoint without reading the shared gateway route. +When `` has a valid native hosted provider attachment, the command reports its recorded provider, model, and fixed profile endpoint without reading the shared gateway route. Otherwise, when that registry contains ``, the command resolves the sandbox's recorded gateway and reads that gateway's live route. It does not search registries for other gateway ports. When the live provider and model match the sandbox's recorded route, text and JSON output identify a `llama-cpp-local` route as `managed` or `attached`. @@ -3536,12 +3538,12 @@ $$nemoclaw my-assistant inference get -Switch the active inference provider or model for a NemoClaw-managed OpenClaw sandbox. For NVIDIA Endpoints, the command attaches or updates the sandbox's native NVIDIA provider. For other providers, it updates the shared OpenShell gateway route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For OpenClaw, the patch updates the OpenClaw config provider namespace and selected model. After any changed config sync, NemoClaw uses the managed supervisor to restart only the OpenClaw gateway and verify its health and forwards. The sandbox remains running, but agent requests are briefly interrupted. If the restart fails, the selected inference path and config remain committed; run `$$nemoclaw gateway restart` to finish applying the switch. After every changed synchronized inference selection, NemoClaw also verifies that the local CLI device has the managed gateway's required pairing scopes before it reports success. If pairing does not converge, the selected inference path and config remain committed. Run `$$nemoclaw doctor --fix`, then retry the agent turn. +Switch the active inference provider or model for a NemoClaw-managed OpenClaw sandbox. For fixed hosted providers, the command attaches or updates the sandbox's native OpenShell provider. For custom, local, and Model Router selections, it updates the shared OpenShell gateway route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For OpenClaw, the patch updates the OpenClaw config provider namespace and selected model. After any changed config sync, NemoClaw uses the managed supervisor to restart only the OpenClaw gateway and verify its health and forwards. The sandbox remains running, but agent requests are briefly interrupted. If the restart fails, the selected inference path and config remain committed; run `$$nemoclaw gateway restart` to finish applying the switch. After every changed synchronized inference selection, NemoClaw also verifies that the local CLI device has the managed gateway's required pairing scopes before it reports success. If pairing does not converge, the selected inference path and config remain committed. Run `$$nemoclaw doctor --fix`, then retry the agent turn. -Switch the active inference provider or model for a NemoClaw-managed Hermes sandbox. For NVIDIA Endpoints, the command attaches or updates the sandbox's native NVIDIA provider. For other providers, it updates the shared OpenShell gateway route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For Hermes, the patch updates the shared native `/sandbox/.hermes/config.yaml` (`model.default`, `model.base_url`, `model.provider: custom`, API-family mode when needed, and the OpenShell proxy API-key placeholder) and does not rebuild or restart the gateway. The gateway, CLI, TUI, and Web Dashboard read that same configuration. Keeping the placeholder preserves dashboard and API authentication after provider switches. Under the `nemohermes` alias, the command uses the registered Hermes sandbox when exactly one exists; otherwise pass `--sandbox ` to target one explicitly. +Switch the active inference provider or model for a NemoClaw-managed Hermes sandbox. For fixed hosted providers, the command attaches or updates the sandbox's native OpenShell provider. For custom, local, and Model Router selections, it updates the shared OpenShell gateway route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For Hermes, the patch updates the shared native `/sandbox/.hermes/config.yaml` (`model.default`, `model.base_url`, `model.provider: custom`, API-family mode when needed, and the OpenShell proxy API-key placeholder) and does not rebuild or restart the gateway. The gateway, CLI, TUI, and Web Dashboard read that same configuration. Keeping the placeholder preserves dashboard and API authentication after provider switches. Under the `nemohermes` alias, the command uses the registered Hermes sandbox when exactly one exists; otherwise pass `--sandbox ` to target one explicitly. @@ -3549,7 +3551,7 @@ Switch the active inference provider or model for a NemoClaw-managed Hermes sand By default, the command syncs the default registered sandbox. -For providers other than NVIDIA Endpoints, each OpenShell gateway exposes one shared inference route to every sandbox registered on that gateway. NVIDIA Endpoints instead uses a sandbox-attached provider and does not change the shared route. +For custom, local, and Model Router selections, each OpenShell gateway exposes one shared inference route to every sandbox registered on that gateway. Fixed hosted providers use sandbox-attached providers and do not change the shared route. Before changing the route, NemoClaw compares it with every same-gateway registry entry, including stopped sandboxes. When only the provider or model differs, the command names the affected sandboxes and warns immediately before it re-points the shared route. Those sandboxes use the new live route until `connect`, onboarding, or another `inference set` command re-points it. @@ -3572,7 +3574,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 providers other than NVIDIA Endpoints, NemoClaw updates the shared OpenShell inference route and syncs the selected sandbox's agent config. For NVIDIA Endpoints, NemoClaw attaches or updates the selected sandbox's native NVIDIA provider and syncs its agent config without changing the shared route. NemoClaw resolves the OpenShell gateway from the target sandbox's recorded gateway binding, including non-default `NEMOCLAW_GATEWAY_PORT` deployments. Do not run `openshell inference set` directly on a shared NemoClaw gateway because that bypasses registry compatibility checks and can break other sandboxes. When either flag is missing, `$$nemoclaw inference set` reports both required flags without suggesting a raw OpenShell command. The command updates the host registry after the selected inference path changes. +Pass both `--provider` and `--model` to select the provider and model for the target sandbox. For custom, local, and Model Router selections, NemoClaw updates the shared OpenShell inference route and syncs the selected sandbox's agent config. For fixed hosted providers, NemoClaw attaches or updates the selected sandbox's native OpenShell provider and syncs its agent config without changing the shared route. NemoClaw resolves the OpenShell gateway from the target sandbox's recorded gateway binding, including non-default `NEMOCLAW_GATEWAY_PORT` deployments. Do not run `openshell inference set` directly on a shared NemoClaw gateway because that bypasses registry compatibility checks and can break other sandboxes. When either flag is missing, `$$nemoclaw inference set` reports both required flags without suggesting a raw OpenShell command. The command updates the host registry after the selected inference path changes. @@ -4423,9 +4425,9 @@ Keep `NEMOCLAW_CUA_ENABLED=1` set whenever NemoClaw uses the experimental `nemoc application 'nemocua'`. Choose a non-host-local inference provider instead. -When NemoCUA uses the recorded `openrouter-api` provider, `https://inference.local/v1/models` returns `HTTP 404` by design because NemoClaw's OpenRouter adapter serves Chat Completions without a model catalog. +When NemoCUA uses the recorded `openrouter-api` provider, it uses the native OpenRouter endpoint through a sandbox-attached provider. NemoClaw reports the route ready only after a bounded inference request successfully serves the selected model. -If that request fails, the expected catalog response does not make the route ready. +If that request fails, endpoint reachability alone does not make the route ready. | Variable | Format | Effect | | -------------------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | diff --git a/docs/reference/enterprise-readiness.mdx b/docs/reference/enterprise-readiness.mdx index 48541df5164..12c44defe9b 100644 --- a/docs/reference/enterprise-readiness.mdx +++ b/docs/reference/enterprise-readiness.mdx @@ -82,7 +82,7 @@ Each row links to deeper documentation and, when a concrete fix is in progress, | Audit and session records | Supported with caveats | OpenClaw stores per-session JSONL event logs, and Hermes stores its own runtime state. Deep Agents Code has no equivalent session-log export, but it can emit bounded-content traces when you explicitly enable observability. Export is manual per sandbox. | | Resource quotas | Supported with caveats | The entrypoint applies best-effort process and file-descriptor limits (`ulimit -u 512`, `ulimit -n 65536`). Set hard limits through the container runtime for fail-closed enforcement. Refer to [Process Controls](../security/security-controls/process-controls). | | Cost and spend controls | Platform or partner-owned | Deny-by-default egress and routed inference reduce exfiltration and stray endpoints, but NemoClaw does not enforce per-token spend budgets. Set spend limits with your inference provider and monitor unattended agents. | -| Credential isolation | Supported | Inference credentials stay in OpenShell provider state and never enter the sandbox. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. CLI output redaction adds defense in depth, and OpenClaw sandboxes also run a memory secret scanner. Refer to [Credential Storage](../security/credential-storage) and [Security Best Practices](../security/best-practices). | +| Credential isolation | Supported | Inference credentials stay in OpenShell provider state and never enter the sandbox. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. CLI output redaction adds defense in depth, and OpenClaw sandboxes also run a memory secret scanner. Refer to [Credential Storage](../security/credential-storage) and [Security Best Practices](../security/best-practices). | | Upgrades and lifecycle | Supported with caveats | Upgrade NemoClaw, then run `$$nemoclaw rebuild` to recreate the sandbox with the current image while backing up and restoring its complete native home. Do not update the agent runtime in place inside the sandbox because the agent is image-pinned. Version attachment flexibility remains tracked in [#2217](https://github.com/NVIDIA/NemoClaw/issues/2217). | | State persistence | Supported | OpenShell preserves the native home/workspace across routine lifecycle operations. NemoClaw transfers the complete native tree during rebuild and recreation. Refer to [Persist Sandbox State](../manage-sandboxes/state-and-backups/create-and-restore-snapshots). | | Remote and cloud deployment | Supported with caveats | Provision a tested Linux host, connect over SSH, run the installer, and run `$$nemoclaw onboard`. For OpenClaw or Hermes, keep the agent dashboard bound to loopback and access it through SSH port forwarding. Automatic recovery after a host reboot is not guaranteed; follow the manual recovery flow in [Deploy to a Headless Server](../deployment/deploy-to-headless-server). | @@ -132,7 +132,7 @@ Use the following phrasing to describe NemoClaw accurately in customer and field - Describe NemoClaw as an open-source reference stack for running agents more safely inside OpenShell, in active development, rather than a finished enterprise control plane. - State that egress is deny-by-default and that an operator approves new endpoints, so the agent cannot reach arbitrary hosts. -- Explain that inference credentials remain in OpenShell provider state, so the sandbox never holds provider keys. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. +- Explain that inference credentials remain in OpenShell provider state, so the sandbox never holds provider keys. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. - Frame centralized fleet management, operator RBAC, enterprise SSO, and multi-tenant isolation as roadmap-only or out of scope today, and avoid presenting them as current capabilities. - Position cost controls and spend limits as provider-owned, and recommend setting provider-side limits for unattended agents. - When a customer hits a known limitation, point to the workaround in this guide and the tracked issue rather than promising a fix date. diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index 6c8f228a32e..1254884ecee 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -86,7 +86,8 @@ The separate `raw.githubusercontent.com` route lets Deep Agents Code follow GitH -When you select NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1` provider to the sandbox instead of using `inference.local` or the broader baseline compatibility rule. +Fixed hosted providers use restricted sandbox-attached OpenShell profiles for their selected endpoint, protocol paths, and agent binaries. +For NVIDIA Endpoints, NemoClaw attaches the `nemoclaw-nvidia-prod-v1` provider to the sandbox instead of using `inference.local` or the broader baseline compatibility rule. This attached provider is the effective NVIDIA Endpoints route. Its profile permits only `GET /v1/models` and `POST /v1/chat/completions` at `integrate.api.nvidia.com:443` from the listed agent-runtime and readiness-verification binaries. The NVIDIA API key remains in OpenShell provider state and does not enter the sandbox. @@ -217,7 +218,7 @@ Unset, blank, or whitespace-only `NEMOCLAW_POLICY_TIER` values use the `balanced ### Inference -Most providers use the OpenShell-managed `inference.local` route. NVIDIA Endpoints instead uses its least-privilege, sandbox-attached OpenShell provider at `integrate.api.nvidia.com`. In both cases, OpenShell mediates inference traffic and keeps provider credentials outside the sandbox. +Fixed hosted providers use their native endpoints through least-privilege, sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the OpenShell-managed `inference.local` route. In both cases, OpenShell mediates inference traffic and keeps provider credentials outside the sandbox. diff --git a/docs/reference/pi-support.mdx b/docs/reference/pi-support.mdx index f77581163fd..6e2a68cd2d2 100644 --- a/docs/reference/pi-support.mdx +++ b/docs/reference/pi-support.mdx @@ -33,7 +33,7 @@ Pi is a NemoClaw agent runtime. Docker is the initial compute runtime. Pi-specif | Host platform | Linux AMD64 or Linux ARM64 | | Compute runtime | Docker | | Managed API | OpenAI Chat Completions | -| Sandbox route | Shared: `https://inference.local/v1`; NVIDIA: `https://integrate.api.nvidia.com/v1` | +| Sandbox route | Fixed hosted: selected native endpoint; custom, local, and Model Router: `https://inference.local/v1` | | Qualification model | `nvidia/nemotron-3-super-120b-a12b` | | Interactive command | `pi` | | Headless command | `pi --no-approve --print` | @@ -60,11 +60,11 @@ Each receipt must match the protected inputs and an image digest in the candidat Pi reads a generated `/sandbox/.pi/agent/models.json` file. The file contains the model, managed route, API family, and a non-secret route placeholder. It does not contain the upstream provider credential. -The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. Most providers give Pi the managed `inference.local` route. NVIDIA Endpoints instead uses the least-privilege OpenShell provider attached to the sandbox for `integrate.api.nvidia.com`. Direct unmanaged provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. +The upstream credential remains in OpenShell provider state. It survives rebuild and sandbox destruction until an operator runs `nemoclaw credentials reset --yes` after all dependent sandboxes are gone. Supported fixed hosted providers give Pi their native endpoint through a least-privilege OpenShell provider attached to the sandbox. Custom, local, and Model Router selections use the managed `https://inference.local/v1` route. Direct unmanaged provider access is denied. NemoClaw rejects an unsupported API family, empty model, credential-bearing base URL, or malformed model tuning before Pi starts. -When Pi uses the recorded `openrouter-api` provider, `https://inference.local/v1/models` returns `HTTP 404` by design because NemoClaw's OpenRouter adapter serves Chat Completions without a model catalog. +When Pi uses the recorded `openrouter-api` provider, requests use the attached native OpenRouter endpoint and preserve its required attribution headers. NemoClaw reports the route ready only after a bounded inference request successfully serves the selected model. -If that request fails, the expected catalog response does not make the route ready. +If that request fails, a successful endpoint reachability check does not make the route ready. The initial qualification requires streaming, a structured `read` tool call, a successful tool result, and an independently checked final response with `nvidia/nemotron-3-super-120b-a12b`. diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index 0e833988e1d..19c448ecf3a 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. Most inference uses OpenShell's `inference.local` endpoint through the Deep Agents Code OpenAI-compatible provider. NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861. | +| 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. Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use `inference.local`. OpenShell keeps provider credentials outside the sandbox. Live runtime acceptance, broader launch material, and terminal-agent diagnostics are tracked at open issue #4861. | {/* agent-status:end */} ## Platforms @@ -95,7 +95,7 @@ NemoClaw routes inference through the OpenShell gateway. Each row below is a pro | Provider | Status | Endpoint type | Notes | |----------|--------|---------------|-------| | NVIDIA Endpoints | Tested | OpenAI-compatible | Hosted models on integrate.api.nvidia.com | -| OpenRouter | Tested | OpenAI-compatible | First-class onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw registers the `openrouter-api` provider through OpenShell's `openai` profile with a host runtime adapter URL; host-side validation and runtime traffic send the default OpenRouter attribution headers. | +| OpenRouter | Tested with limitations | OpenAI-compatible | Onboarding route for OpenClaw, Hermes, and LangChain Deep Agents Code. NemoClaw attaches the native OpenRouter provider for `https://openrouter.ai/api/v1`; host-side validation and agent requests preserve the required attribution headers. Live qualification of this migrated path remains pending. | | OpenAI | Tested | Native OpenAI-compatible | Uses OpenAI model IDs | | Other OpenAI-compatible endpoint | Tested with limitations | Custom OpenAI-compatible | Custom base-URL adapter for servers that implement OpenAI-compatible `/v1/chat/completions` or `/v1/responses`. Behavior on OpenAI-compatible proxies, gateways, and self-hosted implementations may vary; this row claims the adapter, not the universe of compatible endpoints. | | Anthropic | Tested | Native Anthropic | Uses anthropic-messages | @@ -135,7 +135,7 @@ Each row below is a launch-facing capability claim that NemoClaw makes in docs, |------------|--------|-------| | Guided onboarding | Tested | Single-command interactive wizard (`$$nemoclaw onboard`) that walks the user through inference provider selection, credential setup, and sandbox creation or update. It opens the agent dashboard when the selected runtime provides one. Non-interactive mode is supported with `--non-interactive` and `NEMOCLAW_*` environment variables for CI and scripted installs. | | Sandboxed execution | Tested with limitations | Landlock, seccomp, network namespace isolation, no-new-privileges, privilege dropping, and process limits (nproc 512 at `scripts/lib/sandbox-rlimits.sh:8`) are tested and on by default. OpenShell owns capability enforcement for managed entrypoints, exec processes, and connect shells; those paths do not call NemoClaw capability handling. Direct container runtimes that explicitly override the image user to root retain the existing compatibility drop and required `setpriv` transition. Direct container launches must configure capabilities at the container runtime. | -| Managed inference | Tested | Provider-routed model calls through OpenShell, transparent to the agent. Most providers use `inference.local` inside the sandbox; NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell keeps provider credentials outside the sandbox. Supports every entry in the Providers table. | +| Managed inference | Tested with limitations | Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use `inference.local` inside the sandbox. OpenShell keeps provider credentials outside the sandbox. Existing tested paths retain their evidence; live qualification of the newly migrated OpenAI, Anthropic, Google Gemini, OpenRouter, and Hermes Provider paths remains pending. | | Declarative network policy | Tested | YAML-defined egress with policy presets. Presets include `slack`, `discord`, `telegram`, `weather`, `openclaw-pricing`, `huggingface`, `npm`, `pypi`, `brew`, and others. Hot-reloadable at runtime with `$$nemoclaw policy add`. | | State persistence and rebuild transfer | Tested | OpenShell preserves the native agent home during routine lifecycle operations. Before destructive replacement, NemoClaw archives and integrity-checks the complete native home/workspace, then restores it into the replacement sandbox. | | Agent skills | Tested | Packaged agent skills are discoverable by Cursor, Claude Code, and other coding assistants under `.agents/skills/`. Skills also install into the sandbox with `$$nemoclaw skill install`. | diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index 1a8f25d51dd..267426eb46d 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -1331,10 +1331,10 @@ curl -fsSL https://www.nvidia.com/nemoclaw.sh | bash ### Onboarding reports a model-catalog HTTP 404 -NemoClaw's OpenRouter adapter serves Chat Completions but does not serve a model catalog. -An `HTTP 404` response from `https://inference.local/v1/models` is expected when the recorded provider is `openrouter-api`. -NemoClaw accepts that response only after a bounded inference request serves the selected model. -Onboarding and `status` report the route ready when that request succeeds. +OpenRouter uses a sandbox-attached provider at `https://openrouter.ai/api/v1`. +Onboarding and `status` verify the selected model with an inference request through that provider. +They do not use the shared `inference.local` model catalog for OpenRouter. +For a custom or local shared route, a missing model catalog remains a failure to investigate. Re-check the route and the recorded provider and model: @@ -1342,7 +1342,7 @@ Re-check the route and the recorded provider and model: $$nemoclaw status ``` -If the inference request fails, `status` reports that failure instead of accepting the catalog response. +If the inference request fails, `status` reports that failure and leaves model health unverified. Confirm the OpenRouter credential and selected model, then continue the recorded session: ```bash @@ -2042,7 +2042,7 @@ Verify that the inference provider endpoint is reachable from the host. Check th $$nemoclaw status ``` -The main `Inference` line checks the provider path from inside the sandbox and sends an inference request over the path the agent uses. For shared-route providers, `status` probes `https://inference.local/v1/models` before it sends the request through `https://inference.local`. For NVIDIA Endpoints, it verifies the recorded sandbox attachment and sends the request directly to `https://integrate.api.nvidia.com/v1/chat/completions`; it does not probe `inference.local`. When an inference request returns a transient gateway status, `status` makes up to three request attempts before it reports a failure. Shared-route retries repeat the route probe and request, while NVIDIA Endpoints retries only the native request. It prints the next attempt and two-second delay to stderr before each retry. Each inference request attempt has a 90-second request timeout. If the main line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. +The main `Inference` line checks the provider path from inside the sandbox and sends an inference request over the path the agent uses. For custom, local, and Model Router selections, `status` probes `https://inference.local/v1/models` before it sends the request through `https://inference.local`. For fixed hosted providers, it verifies the recorded sandbox attachment and sends the request directly to the provider's native endpoint; it does not probe `inference.local`. When an inference request returns a transient gateway status, `status` makes up to three request attempts before it reports a failure. Shared-route retries repeat the route probe and request, while native hosted retries repeat only the request. It prints the next attempt and two-second delay to stderr before each retry. Refer to the [CLI commands reference](commands) for the current probe timeouts and token cost. If the main line shows `unauthorized`, `unhealthy`, `unreachable`, or `not probed`, inspect the labeled diagnostic lines to identify the failing hop. An `unauthorized` line means the route answered but rejected the request, so refresh the provider credential rather than the route. For local Ollama and local vLLM, `Inference (ollama backend)` or the corresponding local-backend line reports the host-side service separately. If a local-backend diagnostic fails, start the backend. For Local Ollama, current releases can also print `Inference (auth proxy)` when a proxy token is available. Docker Desktop on Windows Subsystem for Linux (WSL) reaches host loopback directly, so its auth-proxy diagnostic is non-authoritative. Native Docker Engine inside WSL is unqualified; enable Docker Desktop WSL integration, then rerun onboarding. diff --git a/docs/security/best-practices.mdx b/docs/security/best-practices.mdx index 4b9be7193fb..31d51d6cc12 100644 --- a/docs/security/best-practices.mdx +++ b/docs/security/best-practices.mdx @@ -114,7 +114,7 @@ NemoClaw allows a credential source only in the process that is intended to hold | Execution path | Rule | |---|---| -| Host-brokered provider | Discover and use host credentials only through OpenShell-managed providers. Most providers expose `inference.local`; NVIDIA Endpoints uses a sandbox-attached least-privilege provider with placeholder credential rewriting. The sandbox receives no raw host credential. | +| Host-brokered provider | Discover and use host credentials only through OpenShell-managed providers. Custom, local, and Model Router selections expose `inference.local`; fixed hosted providers use sandbox-attached least-privilege providers with placeholder credential rewriting. The sandbox receives no raw host credential. | | Sandbox-direct provider | Keep only credential sources that are deliberately provisioned and reachable inside the sandbox. | | Ambient metadata provider | Disable SDK discovery when the metadata endpoint cannot exist across the sandbox boundary. Do not make an internal or link-local endpoint reachable merely to satisfy an automatic probe. | | New agent or provider | Declare the enabled credential sources and add agent-specific tests proving that unavailable sources are not probed. | @@ -144,7 +144,7 @@ NemoClaw's host-local Amazon Bedrock adapter runs outside this sandbox credentia #### Hermes Managed Inference Credential Discovery -NemoClaw configures Hermes with a custom provider. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. The shipped Hermes image does not install the optional native Bedrock dependency. +NemoClaw configures Hermes with a custom provider. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. The shipped Hermes image does not install the optional native Bedrock dependency. AWS credential discovery for supported Bedrock inference therefore remains in NemoClaw's host-local adapter, outside the sandbox. If direct Hermes Bedrock support is added later, it must apply the same unavailable-metadata rule and include Hermes-specific credential-probe acceptance tests before it is enabled. @@ -153,7 +153,7 @@ If direct Hermes Bedrock support is added later, it must apply the same unavaila #### Deep Agents Managed Inference Credential Discovery -NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route. Most providers use `inference.local`; NVIDIA Endpoints uses a sandbox-attached OpenShell provider for `integrate.api.nvidia.com`. +NemoClaw configures the managed `dcode` runtime with a generated OpenAI-compatible route. Fixed hosted providers use native endpoints through sandbox-attached OpenShell providers; custom, local, and Model Router selections use `inference.local`. The sandbox receives a placeholder route key, not the upstream provider credential. The managed launchers reject credential-shaped environment values and upstream auth files before Deep Agents Code starts, so provider discovery stays on the host-side OpenShell boundary. If you need a new sandbox-direct credential source, design it as an explicit provider or MCP integration instead of placing secrets in `/sandbox/.deepagents`. @@ -180,7 +180,7 @@ Endpoint rules restrict allowed HTTP methods and URL paths. | Aspect | Detail | |---|---| -| Default | Some endpoints allow GET and POST on `/**` (for example, `clawhub.ai`). Others restrict methods and paths to specific API routes. The sandbox-attached NVIDIA inference provider allows POST only to `/v1/chat/completions` and GET only to `/v1/models`; it does not permit embedding requests. Read-only endpoints such as `docs.openclaw.ai`, the OpenClaw `npm_registry` baseline entry, and the `pypi` preset allow GET only (PyPI also allows HEAD). The broader `npm` preset is an intentional exception: npm/Yarn registry traffic uses L4 pass-through for Node 22 undici CONNECT compatibility. While that preset is active, NemoClaw temporarily aligns the overlapping baseline npm endpoint with the same reviewed L4 metadata because OpenShell 0.0.116 requires a single connection mode. | +| Default | Some endpoints allow GET and POST on `/**` (for example, `clawhub.ai`). Others restrict methods and paths to specific API routes. Each sandbox-attached hosted provider restricts its own methods and paths. For example, the NVIDIA profile allows POST only to `/v1/chat/completions` and GET only to `/v1/models`, excluding embedding requests. Read-only endpoints such as `docs.openclaw.ai`, the OpenClaw `npm_registry` baseline entry, and the `pypi` preset allow GET only (PyPI also allows HEAD). The broader `npm` preset is an intentional exception: npm/Yarn registry traffic uses L4 pass-through for Node 22 undici CONNECT compatibility. While that preset is active, NemoClaw temporarily aligns the overlapping baseline npm endpoint with the same reviewed L4 metadata because OpenShell 0.0.116 requires a single connection mode. | | What you can change | Add methods (PUT, DELETE, PATCH) or restrict paths to specific prefixes. | | Risk if relaxed | Allowing all methods on an API endpoint gives the agent write and delete access. For example, allowing DELETE on `api.github.com` lets the agent delete repositories. | | Recommendation | Use GET-only rules for endpoints that the agent only reads. Add write methods only for endpoints where the agent must create or modify resources. Restrict paths to specific API routes when possible. | @@ -305,9 +305,9 @@ The agent never receives the provider API key. | Aspect | Detail | |---|---| -| Default | Most providers use the shared `inference.local` route. NVIDIA Endpoints uses a sandbox-attached provider for `integrate.api.nvidia.com`. OpenShell owns the credential and upstream endpoint in both cases. | +| Default | Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. Custom, local, and Model Router selections use the shared `inference.local` route. OpenShell owns the credential and upstream endpoint in both cases. | | What you can change | You select a supported provider. NemoClaw selects and enforces that provider's managed path. | -| Risk if bypassed | Adding an unowned provider endpoint to network policy bypasses NemoClaw's managed provider boundary and could let an agent use a stolen or hardcoded key. The NVIDIA Endpoints path is not a bypass: its checked-in OpenShell provider profile restricts the endpoint, methods, paths, and binaries, then rewrites a placeholder credential at the egress boundary. | +| Risk if bypassed | Adding an unowned provider endpoint to network policy bypasses NemoClaw's managed provider boundary and could let an agent use a stolen or hardcoded key. Each fixed hosted provider uses a checked-in OpenShell profile that restricts the endpoint, methods, paths, and binaries, then rewrites a placeholder credential at egress. | | Recommendation | Do not add inference provider hosts to network policy for NemoClaw model traffic. Use the provider path created by onboarding. The `claude-code` preset is a separate opt-in exception for running the Claude Code CLI with its own credentials, not a way to configure NemoClaw inference. | ### Provider Trust Tiers diff --git a/docs/security/credential-rotation.mdx b/docs/security/credential-rotation.mdx index a31f7d9b7df..aea0188b6bf 100644 --- a/docs/security/credential-rotation.mdx +++ b/docs/security/credential-rotation.mdx @@ -181,9 +181,10 @@ unset TAVILY_API_KEY Use `credentials reset` only when you need to remove an inference or web search provider before its replacement is available. Run `$$nemoclaw credentials list` first, then pass the provider name from that output. -The native NVIDIA provider cannot be reset while it is attached to a sandbox. +A native hosted provider cannot be reset while any recorded sandbox uses it. Use [Rotate an Inference API key](#rotate-an-inference-api-key) to replace its credential in place. -To remove it completely, preserve required sandbox state, destroy every attached sandbox, and then run: +To remove it completely, preserve required sandbox state, destroy every recorded sandbox that uses it, and then run `credentials reset` with its provider name. +For example, to remove the NVIDIA provider: ```bash $$nemoclaw credentials reset nvidia-prod --yes diff --git a/docs/security/gateway-authentication-controls.mdx b/docs/security/gateway-authentication-controls.mdx index f1b341cb410..41be0218ed3 100644 --- a/docs/security/gateway-authentication-controls.mdx +++ b/docs/security/gateway-authentication-controls.mdx @@ -153,8 +153,8 @@ Hermes exposes an OpenAI-compatible API on the forwarded Hermes port and can opt Do not publish those endpoints on shared or public networks unless you put them behind your own access controls. NemoClaw keeps provider credentials in OpenShell. -NVIDIA Endpoints traffic uses the native NVIDIA endpoint through the sandbox-attached OpenShell provider. -Other managed inference providers continue to use `inference.local`. +Fixed hosted providers use their native endpoints through sandbox-attached OpenShell providers. +Custom, local, and Model Router selections continue to use `inference.local`. Generated Hermes runtime files use OpenShell resolver placeholders for managed-tool and messaging credentials. Hermes startup rejects raw secret-shaped values in sandbox-visible environment or config fields, while allowing empty values, migration sentinels, OpenShell resolver placeholders, and expected Slack placeholder forms. diff --git a/docs/security/process-controls.mdx b/docs/security/process-controls.mdx index 7e8972d6f68..1ed76e2e373 100644 --- a/docs/security/process-controls.mdx +++ b/docs/security/process-controls.mdx @@ -292,7 +292,7 @@ A registry-side tag change cannot silently select another managed sandbox image. For managed `inference.local` routes, the entrypoint clears the NVIDIA credential aliases before setup and command execution. It removes only the exact legacy NemoClaw-generated profile for the selected managed provider and preserves other profiles. -The native NVIDIA route uses `integrate.api.nvidia.com` with an OpenShell-managed placeholder credential. It does not retain a supplied NVIDIA credential in the sandbox. +Fixed hosted providers use their selected native endpoints with OpenShell-managed placeholder credentials. They do not retain supplied provider credentials in the sandbox. Other unmanaged direct routes retain supplied credentials. The entrypoint and migration flows enforce `chmod 600` on auth-profile files under `~/.openclaw`. This prevents other users on the host from reading stored credentials that remain. diff --git a/managed-inference/provider-profiles/nemoclaw-anthropic-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-anthropic-inference-v1.yaml new file mode 100644 index 00000000000..4b1811659fc --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-anthropic-inference-v1.yaml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-anthropic-inference-v1 +display_name: NemoClaw Anthropic Hosted Inference +description: Native Anthropic hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: Anthropic hosted inference API key + env_vars: + - ANTHROPIC_API_KEY + required: true + auth_style: header + header_name: x-api-key + query_param: '' +endpoints: + - host: api.anthropic.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1/models" } + - allow: { method: POST, path: "/v1/messages" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-gemini-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-gemini-inference-v1.yaml new file mode 100644 index 00000000000..4cfff55d78f --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-gemini-inference-v1.yaml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-gemini-inference-v1 +display_name: NemoClaw Google Gemini Hosted Inference +description: Native Google Gemini hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: Google Gemini hosted inference API key + env_vars: + - GEMINI_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: generativelanguage.googleapis.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1beta/openai/models" } + - allow: { method: POST, path: "/v1beta/openai/chat/completions" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-hermes-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-hermes-inference-v1.yaml new file mode 100644 index 00000000000..76453cd18da --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-hermes-inference-v1.yaml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-hermes-inference-v1 +display_name: NemoClaw Hermes Provider Hosted Inference +description: Native Hermes Provider hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: Hermes Provider hosted inference API key + env_vars: + - OPENAI_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: inference-api.nousresearch.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1/models" } + - allow: { method: POST, path: "/v1/chat/completions" } + - allow: { method: POST, path: "/v1/responses" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-openai-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-openai-inference-v1.yaml new file mode 100644 index 00000000000..e0749d7ce93 --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-openai-inference-v1.yaml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-openai-inference-v1 +display_name: NemoClaw OpenAI Hosted Inference +description: Native OpenAI hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: OpenAI hosted inference API key + env_vars: + - OPENAI_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: api.openai.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/v1/models" } + - allow: { method: POST, path: "/v1/chat/completions" } + - allow: { method: POST, path: "/v1/responses" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml b/managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml new file mode 100644 index 00000000000..a1a0d05a8c6 --- /dev/null +++ b/managed-inference/provider-profiles/nemoclaw-openrouter-inference-v1.yaml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +id: nemoclaw-openrouter-inference-v1 +display_name: NemoClaw OpenRouter Hosted Inference +description: Native OpenRouter hosted inference access for NemoClaw agents +category: inference +credentials: + - name: api_key + description: OpenRouter hosted inference API key + env_vars: + - OPENROUTER_API_KEY + required: true + auth_style: bearer + header_name: authorization + query_param: '' +endpoints: + - host: openrouter.ai + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/api/v1/models" } + - allow: { method: POST, path: "/api/v1/chat/completions" } +binaries: + - /usr/local/bin/node + - /usr/bin/node + - /opt/hermes/.venv/bin/python + - /opt/hermes/.venv/bin/python3 + - /opt/venv/bin/python3 + - /usr/local/bin/curl + - /usr/bin/curl +inference_capable: true diff --git a/scripts/generate-openclaw-config.mts b/scripts/generate-openclaw-config.mts index a915d7258f3..9901a7f248d 100755 --- a/scripts/generate-openclaw-config.mts +++ b/scripts/generate-openclaw-config.mts @@ -1,6 +1,7 @@ #!/usr/bin/env node // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 + // // Generate openclaw.json from environment variables. // @@ -27,6 +28,8 @@ // NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME, NEMOCLAW_OPENCLAW_OTEL_SAMPLE_RATE, // NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION. +import { OPENROUTER_DEFAULT_HEADERS } from "../src/lib/inference/native-hosted/openrouter-headers.ts"; + import { hasProviderlessInferenceEnvironment } from "../src/lib/providerless-inference.ts"; import { @@ -970,10 +973,25 @@ export function buildConfig(env: Env = process.env): JsonObject { maxTokens, }); } + const nativeRoutes: Record = { + "nvidia-prod": ["https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"], + "openai-api": ["https://api.openai.com/v1", "OPENAI_API_KEY"], + "anthropic-prod": ["https://api.anthropic.com", "ANTHROPIC_API_KEY"], + "gemini-api": ["https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"], + "openrouter-api": ["https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"], + "hermes-provider": ["https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY"], + }; + const nativeProfile = nativeRoutes[upstreamProvider]; const providers = { [providerKey]: { + ...(upstreamProvider === "openrouter-api" + ? { headers: Object.fromEntries(OPENROUTER_DEFAULT_HEADERS) } + : {}), baseUrl: inferenceBaseUrl, - apiKey: "unused", + apiKey: + nativeProfile && inferenceBaseUrl === nativeProfile[0] + ? `\${${nativeProfile[1]}}` + : "unused", api: inferenceApi, timeoutSeconds: agentTimeout, models: providerModels, diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 4349fe1984b..4d948f732d9 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -613,6 +613,9 @@ def add_key(value): def walk(value): if isinstance(value, str): + for native_key in ("NVIDIA_INFERENCE_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"): + if value == "${" + native_key + "}": + add_key(native_key) if value.startswith(prefix): add_key(value[len(prefix) :]) alias_index = value.find(alias_marker) @@ -883,6 +886,14 @@ replacement_patterns = [ def rewrite(value): if isinstance(value, str): + for native_key in ("NVIDIA_INFERENCE_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"): + if value == "${" + native_key + "}": + state = runtime_state(native_key) + handle = state.get("value", "") + if state.get("kind") != "placeholder" or not re.fullmatch( + rf"openshell:resolve:env:(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{native_key}", handle + ): + raise SystemExit("[SECURITY] Native inference requires an issued OpenShell credential handle") for pattern, key, new in replacement_patterns: updated, count = pattern.subn(new, value) if count: diff --git a/src/commands/credentials.test.ts b/src/commands/credentials.test.ts index d102a91bc3a..4f65f6702df 100644 --- a/src/commands/credentials.test.ts +++ b/src/commands/credentials.test.ts @@ -339,18 +339,34 @@ describe("credentials oclif adapter source coverage", () => { it("deletes provider credentials with --yes", async () => { const log = vi.spyOn(console, "log").mockImplementation(() => {}); + mocks.runOpenshellProviderCommand.mockReturnValueOnce({ + status: 1, + stderr: "Error: provider 'nvidia-prod' not found", + }); await CredentialsResetCommand.run(["nvidia-prod", "--yes"], rootDir); expect(mocks.prompt).not.toHaveBeenCalled(); - expect(mocks.runOpenshellProviderCommand).toHaveBeenCalledWith( - ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], - { - ignoreError: true, - stdio: ["ignore", "pipe", "pipe"], - suppressOutput: true, - timeout: 30_000, - }, - ); + expect(mocks.runOpenshellProviderCommand.mock.calls).toEqual([ + [ + ["provider", "get", "-g", "nemoclaw", "nvidia-prod"], + { + ignoreError: true, + maxBuffer: 64 * 1024, + suppressOutput: true, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + }, + ], + [ + ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + { + ignoreError: true, + stdio: ["ignore", "pipe", "pipe"], + suppressOutput: true, + timeout: 30_000, + }, + ], + ]); const output = log.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); log.mockRestore(); expect(output).toContain("Removed provider 'nvidia-prod'"); diff --git a/src/commands/inference/get.ts b/src/commands/inference/get.ts index 33b0d5c5ba5..f4facccf1ee 100644 --- a/src/commands/inference/get.ts +++ b/src/commands/inference/get.ts @@ -10,7 +10,7 @@ export default class InferenceGetCommand extends NemoClawCommand { static enableJsonFlag = true; static summary = "Show the selected NemoClaw inference path"; static description = - "Read the selected sandbox's native NVIDIA provider path or the live shared OpenShell route."; + "Read the selected sandbox's native hosted provider path or the live shared OpenShell route."; static usage = ["inference get [--json]"]; static examples = ["<%= config.bin %> inference get", "<%= config.bin %> inference get --json"]; static flags = {}; diff --git a/src/commands/sandbox/inference/get.ts b/src/commands/sandbox/inference/get.ts index 4b8f9124bab..4a1b51d787f 100644 --- a/src/commands/sandbox/inference/get.ts +++ b/src/commands/sandbox/inference/get.ts @@ -6,14 +6,14 @@ import { NemoClawCommand } from "../../../lib/cli/nemoclaw-oclif-command"; import { sandboxNameArg } from "../../../lib/sandbox/command-support"; // Sandbox-first mirror of the global inference:get command; both delegate to -// the shared runInferenceGet action that selects native NVIDIA or shared-route output. +// the shared runInferenceGet action that selects native hosted or shared-route output. export default class SandboxInferenceGetCommand extends NemoClawCommand { static id = "sandbox:inference:get"; static strict = true; static enableJsonFlag = true; static summary = "Show the selected NemoClaw inference path"; static description = - "Read the sandbox's native NVIDIA provider path or its gateway's live shared route. NEMOCLAW_GATEWAY_PORT selects the sandbox registry and fallback gateway; a registered sandbox's binding selects its recorded gateway."; + "Read the sandbox's native hosted provider path or its gateway's live shared route. NEMOCLAW_GATEWAY_PORT selects the sandbox registry and fallback gateway; a registered sandbox's binding selects its recorded gateway."; static usage = [" inference get [--json]"]; static examples = [ "<%= config.bin %> my-assistant inference get", diff --git a/src/lib/actions/credentials-add.ts b/src/lib/actions/credentials-add.ts index 04152905933..86525b38474 100644 --- a/src/lib/actions/credentials-add.ts +++ b/src/lib/actions/credentials-add.ts @@ -1,6 +1,11 @@ +import { + getNativeHostedProviderAuthority, + setNativeHostedProviderAuthority, +} from "../state/registry/native-nvidia-provider-authority"; // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES, nativeHostedProfile } from "../inference/native-hosted/profiles"; import fs from "node:fs"; import { isIP } from "node:net"; import path from "node:path"; @@ -14,15 +19,10 @@ import { OPENSHELL_OPERATION_TIMEOUT_MS } from "../adapters/openshell/timeouts"; import { resolveAgentNameAlias } from "../agent/aliases"; import { CLI_NAME } from "../cli/branding"; import { - ensureNativeNvidiaProvider, - NativeNvidiaProviderError, - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - nativeNvidiaProviderProfilePath, - persistNativeNvidiaProviderAuthority, -} from "../inference/native-nvidia"; + ensureNativeHostedProvider, + persistNativeHostedProviderAuthority, + nativeHostedProviderProfilePath, +} from "../inference/native-hosted"; import { HERMES_TAVILY_PROVIDER_PROFILE_ID, TAVILY_PROVIDER_PROFILE_AGENTS, @@ -38,10 +38,6 @@ import { SECRET_PATTERNS } from "../security/secret-patterns"; import { assertEndpointResolvesPublic } from "../security/trusted-private-endpoint"; import { withMcpCredentialOwnershipLock } from "../state/mcp-lifecycle-lock/credential-ownership"; import { ROOT } from "../state/paths"; -import { - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, -} from "../state/registry/native-nvidia-provider-authority"; import { forgetExtraProvider, recordExtraProvider } from "./global"; export type CredentialsAddInput = { @@ -61,8 +57,8 @@ export type CredentialsAddResult = { export type CredentialsAddDeps = Readonly<{ providerAdapter?: OpenShellProviderAdapter; - getNativeNvidiaProviderAuthority?: typeof getNativeNvidiaProviderAuthority; - setNativeNvidiaProviderAuthority?: typeof setNativeNvidiaProviderAuthority; + getNativeHostedProviderAuthority?: typeof getNativeHostedProviderAuthority; + setNativeHostedProviderAuthority?: typeof setNativeHostedProviderAuthority; }>; const ENV_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,255}$/; @@ -143,8 +139,9 @@ async function providerConfigEndpointFailure( function bundledProviderProfile(type: string): { profileType: string; profilePath: string } | null { const profileType = type.toLowerCase(); - if (profileType === NVIDIA_HOSTED_NATIVE_PROFILE_ID) { - return { profileType, profilePath: nativeNvidiaProviderProfilePath() }; + const hostedProfile = NATIVE_HOSTED_PROFILES.find((profile) => profile.profileId === profileType); + if (hostedProfile) { + return { profileType, profilePath: nativeHostedProviderProfilePath(hostedProfile) }; } const profilePath = path.join( ROOT, @@ -273,8 +270,12 @@ export async function runCredentialsAddAction( } const normalizedType = type.toLowerCase(); - const nativeNvidiaCredentialAlias = - provider === NVIDIA_HOSTED_LOGICAL_PROVIDER && normalizedType === "nvidia"; + const hostedProfile = nativeHostedProfile(provider); + const expectedType = + provider === "nvidia-prod" ? "nvidia" : provider === "anthropic-prod" ? "anthropic" : "openai"; + const nativeHostedCredentialAlias = + hostedProfile && + (normalizedType === expectedType || normalizedType === hostedProfile.profileId); const isTavily = normalizedType === TAVILY_PROVIDER_PROFILE_ID || normalizedType === HERMES_TAVILY_PROVIDER_PROFILE_ID; @@ -294,12 +295,12 @@ export async function runCredentialsAddAction( ]); } } - const effectiveType = nativeNvidiaCredentialAlias - ? NVIDIA_HOSTED_NATIVE_PROFILE_ID + const effectiveType = nativeHostedCredentialAlias + ? hostedProfile!.profileId : isTavily ? webSearchProviderProfileId(normalizedType, agentName) : type; - const effectiveProvider = nativeNvidiaCredentialAlias ? NVIDIA_HOSTED_NATIVE_PROVIDER : provider; + const effectiveProvider = nativeHostedCredentialAlias ? hostedProfile!.providerName : provider; const compatibilityWarnings = normalizedType === TAVILY_PROVIDER_PROFILE_ID && !agentName ? [ @@ -386,6 +387,9 @@ export async function runCredentialsAddAction( config.push({ key, value }); } + if (nativeHostedCredentialAlias && config.length) + return fail([" Native hosted provider profiles do not accept --config overrides."]); + const endpointFailure = await providerConfigEndpointFailure(config); if (endpointFailure) return fail(endpointFailure); @@ -397,41 +401,45 @@ export async function runCredentialsAddAction( return fail(recoveryFailureLines); } + const hostedHostCredentialEnv = hostedProfile?.hostCredentialEnv ?? hostedProfile?.credentialEnv; if ( - nativeNvidiaCredentialAlias && + nativeHostedCredentialAlias && !fromExisting && - (credentials.length !== 1 || credentials[0] !== NVIDIA_HOSTED_CREDENTIAL_ENV) + (credentials.length !== 1 || credentials[0] !== hostedHostCredentialEnv) ) { return fail([ - ` Native NVIDIA inference requires exactly --credential ${NVIDIA_HOSTED_CREDENTIAL_ENV}.`, + ` Native ${hostedProfile!.label} inference requires exactly --credential ${hostedHostCredentialEnv}.`, ]); } - if (nativeNvidiaCredentialAlias) { + if (nativeHostedCredentialAlias) { return withMcpCredentialOwnershipLock(async () => { try { const expected = ( - deps.getNativeNvidiaProviderAuthority ?? getNativeNvidiaProviderAuthority - )(target.gatewayName); - const receipt = await ensureNativeNvidiaProvider({ + deps.getNativeHostedProviderAuthority ?? getNativeHostedProviderAuthority + )(target.gatewayName, hostedProfile!.profileId); + const receipt = await ensureNativeHostedProvider({ + profile: hostedProfile!, adapter: providerAdapter, target, - credentialValue: fromExisting - ? null - : (process.env[NVIDIA_HOSTED_CREDENTIAL_ENV] ?? null), + credentialValue: fromExisting ? null : (process.env[hostedHostCredentialEnv!] ?? null), reuseExistingCredential: fromExisting, ...(expected ? { expected } : {}), }); if (!expected) { - await persistNativeNvidiaProviderAuthority({ + await persistNativeHostedProviderAuthority({ adapter: providerAdapter, target, + profile: hostedProfile!, gatewayName: target.gatewayName, receipt, - readAuthority: - deps.getNativeNvidiaProviderAuthority ?? getNativeNvidiaProviderAuthority, + readAuthority: (gatewayName) => + (deps.getNativeHostedProviderAuthority ?? getNativeHostedProviderAuthority)( + gatewayName, + hostedProfile!.profileId, + ), writeAuthority: - deps.setNativeNvidiaProviderAuthority ?? setNativeNvidiaProviderAuthority, + deps.setNativeHostedProviderAuthority ?? setNativeHostedProviderAuthority, }); } return ok([ @@ -440,10 +448,7 @@ export async function runCredentialsAddAction( ` Select it with '${CLI_NAME} inference set --provider ${provider} --model '.`, ]); } catch (error) { - const detail = - error instanceof NativeNvidiaProviderError || error instanceof Error - ? error.message - : String(error); + const detail = error instanceof Error ? error.message : String(error); return fail([` Could not register provider '${provider}'.`, ` ${detail}`]); } }); @@ -477,7 +482,7 @@ export async function runCredentialsAddAction( // Registration records this provider as an explicit extra-provider intent. // Rebuild validates that intent against current source-backed MCP entries; // orphaned providers retained by conservative MCP removal are not intent. - const recordedReservation = nativeNvidiaCredentialAlias + const recordedReservation = nativeHostedCredentialAlias ? false : recordExtraProvider(effectiveProvider); let keepReservation = false; diff --git a/src/lib/actions/credentials-native-hosted.test.ts b/src/lib/actions/credentials-native-hosted.test.ts new file mode 100644 index 00000000000..9bf89f63748 --- /dev/null +++ b/src/lib/actions/credentials-native-hosted.test.ts @@ -0,0 +1,98 @@ +// 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 { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; +import { providerAdapter } from "../../../test/helpers/credentials-provider-adapter"; +import { runCredentialsAddAction } from "./credentials-add"; +import { setGlobalCliActionRuntimeHooksForTest } from "./global"; + +vi.mock("../onboard/gateway-teardown-authority", () => ({ + resolveGatewayCredentialMutationAuthority: vi.fn(() => ({})), +})); +vi.mock("../state/mcp-lifecycle-lock/credential-ownership", () => ({ + withMcpCredentialOwnershipLock: (operation: () => Promise | T) => operation(), +})); + +describe("native hosted credential registration", () => { + beforeEach(() => { + setGlobalCliActionRuntimeHooksForTest({ + recoverNamedGatewayRuntime: async () => ({ recovered: true }), + recordExtraProvider: () => true, + forgetExtraProvider: () => true, + }); + }); + afterEach(() => { + setGlobalCliActionRuntimeHooksForTest({}); + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + }); + it.each(NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"))( + "records standalone $label ownership after confirmed registration", + async (profile) => { + const recordExtraProvider = vi + .spyOn(await import("./global"), "recordExtraProvider") + .mockReturnValue(true); + const hostCredential = profile.hostCredentialEnv ?? profile.credentialEnv; + vi.stubEnv("OPENAI_API_KEY", "unrelated-openai-key"); + vi.stubEnv(hostCredential, "host-only-test-value"); + let present = false; + const adapter = providerAdapter({ + getProvider: vi.fn(async () => + present + ? { + ok: true as const, + value: { + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], + configKeys: [], + revision: { id: "registered-id", resourceVersion: 1 }, + }, + } + : { + ok: false as const, + error: { + kind: "command" as const, + reason: "not_found" as const, + message: "not found", + }, + }, + ), + createProvider: vi.fn(async () => { + present = true; + return { ok: true as const }; + }), + }); + const save = vi.fn(); + const result = await runCredentialsAddAction( + { + provider: profile.logicalProvider, + type: profile.profileId, + credentials: [hostCredential], + configPairs: [], + fromExisting: false, + }, + { + providerAdapter: adapter, + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority: save, + }, + ); + expect(result.exitCode).toBe(0); + expect(adapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + credentials: [{ name: profile.credentialEnv, value: "host-only-test-value" }], + }), + ); + expect(save).toHaveBeenCalledWith("nemoclaw", { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "registered-id", + }); + expect(recordExtraProvider).not.toHaveBeenCalled(); + expect(JSON.stringify(result)).not.toContain("host-only-test-value"); + }, + ); +}); diff --git a/src/lib/actions/credentials-native-reset.test.ts b/src/lib/actions/credentials-native-reset.test.ts index 37c9a814ba3..2452601b186 100644 --- a/src/lib/actions/credentials-native-reset.test.ts +++ b/src/lib/actions/credentials-native-reset.test.ts @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { setGlobalCliActionRuntimeHooksForTest } from "./global"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import { runCredentialsResetAction } from "./credentials/reset"; vi.mock("../onboard/gateway-teardown-authority", () => ({ @@ -14,7 +15,13 @@ vi.mock("../onboard/gateway-teardown-authority", () => ({ function adapter( deleteProvider: OpenShellProviderAdapter["deleteProvider"], ): OpenShellProviderAdapter { - return { deleteProvider: vi.fn(deleteProvider) } as unknown as OpenShellProviderAdapter; + return { + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), + deleteProvider: vi.fn(deleteProvider), + } as unknown as OpenShellProviderAdapter; } describe("native NVIDIA credential reset ownership", () => { @@ -48,8 +55,8 @@ describe("native NVIDIA credential reset ownership", () => { operations.push("delete"); return deleteResult; }); - const clearNativeNvidiaProviderAuthority = vi.fn(() => operations.push("clear-authority")); - const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName: string) => + const clearNativeHostedProviderAuthority = vi.fn(() => operations.push("clear-authority")); + const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName?: string) => gatewayName === "nemoclaw" ? ["alpha"] : [], ); @@ -57,7 +64,7 @@ describe("native NVIDIA credential reset ownership", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames, withGatewayRouteMutationLock: async (_gatewayName, operation) => { operations.push("lock"); @@ -72,19 +79,127 @@ describe("native NVIDIA credential reset ownership", () => { "nemoclaw", ); expect(deleteProvider).not.toHaveBeenCalled(); - expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines).toContain(" 'nvidia-prod' is recorded by sandbox(es): alpha."); expect(result.failureLines).toContain(" No provider or ownership authority was changed."); expect(result.failureLines).toContain(" nemoclaw alpha destroy"); }, ); + it.each( + NATIVE_HOSTED_PROFILES.flatMap((profile) => + (["present", "timeout", "authentication", "schema"] as const).map((state) => ({ + profile, + state, + })), + ), + )( + "preserves providers and native authority when legacy observation is $state for $profile.logicalProvider", + async ({ profile, state }) => { + const deleteProvider = vi.fn(async () => ({ + ok: true, + })); + const clearNativeHostedProviderAuthority = vi.fn(); + const providerAdapter = adapter(deleteProvider); + providerAdapter.getProvider = vi.fn(async () => + state === "present" + ? { + ok: true, + value: { + name: profile.logicalProvider, + type: "nvidia", + credentialKeys: ["NVIDIA_API_KEY"], + configKeys: [], + }, + } + : { + ok: false, + error: { kind: state, message: "observation failed" }, + }, + ); + const result = await runCredentialsResetAction( + { provider: profile.logicalProvider, confirmed: true }, + { + providerAdapter, + clearNativeHostedProviderAuthority, + listNativeHostedProviderAttachmentSandboxNames: () => [], + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gateway, operation) => operation(), + }, + ); + expect(result.exitCode).toBe(1); + expect(providerAdapter.getProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: profile.logicalProvider, + timeoutMs: 30_000, + }); + expect(deleteProvider).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); + expect(result.failureLines.join("\n")).toContain("ownership conflict"); + }, + ); + + it("refuses hosted reset for an owned receipt under the gateway lock", async () => { + const operations: string[] = []; + const deleteProvider = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); + const result = await runCredentialsResetAction( + { provider: "openai-api", confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeHostedProviderAuthority, + listNativeHostedProviderAttachmentSandboxNames: (profileId, gatewayName) => { + operations.push("inspect"); + expect(profileId).toBe("nemoclaw-openai-inference-v1"); + expect(gatewayName).toBe("nemoclaw"); + return ["alpha"]; + }, + withGatewayRouteMutationLock: async (_gatewayName, operation) => { + operations.push("lock"); + return operation(); + }, + }, + ); + expect(operations).toEqual(["lock", "inspect"]); + expect(result.exitCode).toBe(1); + expect(deleteProvider).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); + expect(result.failureLines).toContain(" 'openai-api' is recorded by sandbox(es): alpha."); + }); + + it.each(NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"))( + "removes native identity only after legacy absence for $label", + async (profile) => { + const deleteProvider = vi.fn(async () => ({ + ok: true, + })); + const clearNativeHostedProviderAuthority = vi.fn(); + const result = await runCredentialsResetAction( + { provider: profile.logicalProvider, confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeHostedProviderAuthority, + listNativeHostedProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gateway, operation) => operation(), + }, + ); + expect(result.exitCode).toBe(0); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + profile.providerName, + ]); + expect(clearNativeHostedProviderAuthority).toHaveBeenCalledExactlyOnceWith( + "nemoclaw", + profile.profileId, + ); + }, + ); + it("does not let another gateway's attachment block the selected gateway reset", async () => { const deleteProvider = vi.fn(async () => ({ ok: true, })); - const clearNativeNvidiaProviderAuthority = vi.fn(); - const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName: string) => + const clearNativeHostedProviderAuthority = vi.fn(); + const listNativeNvidiaProviderAttachmentSandboxNames = vi.fn((gatewayName?: string) => gatewayName === "other-gateway" ? ["beta"] : [], ); @@ -92,7 +207,7 @@ describe("native NVIDIA credential reset ownership", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames, withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), }, @@ -102,19 +217,82 @@ describe("native NVIDIA credential reset ownership", () => { expect(listNativeNvidiaProviderAttachmentSandboxNames).toHaveBeenCalledExactlyOnceWith( "nemoclaw", ); - expect(deleteProvider).toHaveBeenCalledOnce(); - expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledExactlyOnceWith("nemoclaw"); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + "nemoclaw-nvidia-prod-v1", + ]); + expect(clearNativeHostedProviderAuthority).toHaveBeenCalledExactlyOnceWith( + "nemoclaw", + "nemoclaw-nvidia-inference-v1", + ); }); + it.each(NATIVE_HOSTED_PROFILES)( + "keeps explicit $label native identity reset separate from legacy removal", + async (profile) => { + const deleteProvider = vi.fn(async () => ({ + ok: true, + })); + const providerAdapter = adapter(deleteProvider); + await runCredentialsResetAction( + { provider: profile.providerName, confirmed: true }, + { + providerAdapter, + clearNativeHostedProviderAuthority: vi.fn(), + listNativeHostedProviderAttachmentSandboxNames: () => [], + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gateway, operation) => operation(), + }, + ); + expect(providerAdapter.getProvider).not.toHaveBeenCalled(); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + profile.providerName, + ]); + }, + ); + + it.each(["nemoclaw-nvidia-prod-v1"])( + "preserves authority when deleting %s fails", + async (failedName) => { + const deleteProvider = vi.fn(async (input) => + input.providerName === failedName + ? { + ok: false, + error: { + kind: "command", + reason: "failed", + message: "delete failed", + }, + } + : { ok: true }, + ); + const clearNativeHostedProviderAuthority = vi.fn(); + const result = await runCredentialsResetAction( + { provider: "nvidia-prod", confirmed: true }, + { + providerAdapter: adapter(deleteProvider), + clearNativeHostedProviderAuthority, + listNativeNvidiaProviderAttachmentSandboxNames: () => [], + withGatewayRouteMutationLock: async (_gateway, operation) => operation(), + }, + ); + expect(result.exitCode).toBe(1); + expect(deleteProvider.mock.calls.map(([input]) => input.providerName)).toEqual([ + "nemoclaw-nvidia-prod-v1", + ]); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); + expect(result.failureLines.join("\n")).toContain("delete failed"); + }, + ); + it("fails closed before reset when registry ownership cannot be read", async () => { const deleteProvider = vi.fn(); - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const result = await runCredentialsResetAction( { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter(deleteProvider), - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames: () => { throw new Error("opaque registry failure"); }, @@ -124,7 +302,7 @@ describe("native NVIDIA credential reset ownership", () => { expect(result.exitCode).toBe(1); expect(deleteProvider).not.toHaveBeenCalled(); - expect(clearNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(clearNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(result.failureLines).toEqual([ " Could not safely inspect native NVIDIA inference ownership on gateway 'nemoclaw'.", " No provider or ownership authority was changed.", diff --git a/src/lib/actions/credentials-provider-adapter.test.ts b/src/lib/actions/credentials-provider-adapter.test.ts index 56ca7f6e447..203668d728c 100644 --- a/src/lib/actions/credentials-provider-adapter.test.ts +++ b/src/lib/actions/credentials-provider-adapter.test.ts @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import readline from "node:readline"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; +import { providerAdapter } from "../../../test/helpers/credentials-provider-adapter"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; @@ -23,64 +25,6 @@ vi.mock("../gateway-start-guidance", () => ({ gatewayStartGuidance: () => "Start the gateway again with `nemoclaw onboard`.", })); -function providerAdapter( - overrides: Partial = {}, -): OpenShellProviderAdapter { - const listProviders: OpenShellProviderAdapter["listProviders"] = async () => ({ - ok: true, - value: { names: [] }, - }); - const createProvider: OpenShellProviderAdapter["createProvider"] = async () => ({ - ok: true, - }); - const getProvider: OpenShellProviderAdapter["getProvider"] = async (request) => ({ - ok: true, - value: { name: request.providerName, type: "generic", credentialKeys: [], configKeys: [] }, - }); - const updateProvider: OpenShellProviderAdapter["updateProvider"] = async () => ({ - ok: true, - }); - const importProviderProfile: OpenShellProviderAdapter["importProviderProfile"] = async () => ({ - ok: true, - }); - const inspectProviderProfile: OpenShellProviderAdapter["inspectProviderProfile"] = async () => ({ - ok: true, - value: { credentialKeys: [] }, - }); - const deleteProvider: OpenShellProviderAdapter["deleteProvider"] = async () => ({ - ok: true, - }); - const detachProvider: OpenShellProviderAdapter["detachProvider"] = async () => ({ - ok: true, - value: { changed: true }, - }); - const attachProvider: OpenShellProviderAdapter["attachProvider"] = async () => ({ ok: true }); - const listProviderAttachments: OpenShellProviderAdapter["listProviderAttachments"] = - async () => ({ ok: true, value: { names: [] } }); - const configureProviderRefresh: OpenShellProviderAdapter["configureProviderRefresh"] = - async () => ({ ok: true }); - const getProviderRefreshStatus: OpenShellProviderAdapter["getProviderRefreshStatus"] = - async () => ({ ok: true, value: { status: "refreshed" } }); - return { - ensureProviderPolicyComposition: vi - .fn() - .mockResolvedValue({ ok: true, value: undefined }), - listProviders: vi.fn(listProviders), - createProvider: vi.fn(createProvider), - getProvider: vi.fn(getProvider), - updateProvider: vi.fn(updateProvider), - importProviderProfile: vi.fn(importProviderProfile), - inspectProviderProfile: vi.fn(inspectProviderProfile), - deleteProvider: vi.fn(deleteProvider), - detachProvider: vi.fn(detachProvider), - attachProvider: vi.fn(attachProvider), - listProviderAttachments: vi.fn(listProviderAttachments), - configureProviderRefresh: vi.fn(configureProviderRefresh), - getProviderRefreshStatus: vi.fn(getProviderRefreshStatus), - ...overrides, - }; -} - function nativeNvidiaProviderAdapter(): OpenShellProviderAdapter { let providerPresent = false; return providerAdapter({ @@ -172,7 +116,7 @@ describe("credential actions use typed OpenShell provider results", () => { }); const providerId = "11111111-2222-4333-8444-555555555555"; const adapter = nativeNvidiaProviderAdapter(); - const setNativeNvidiaProviderAuthority = vi.fn(); + const setNativeHostedProviderAuthority = vi.fn(); const result = await runCredentialsAddAction( { @@ -184,8 +128,8 @@ describe("credential actions use typed OpenShell provider results", () => { }, { providerAdapter: adapter, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority, + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority, }, ); @@ -202,7 +146,7 @@ describe("credential actions use typed OpenShell provider results", () => { config: [], fromExisting: false, }); - expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw", { + expect(setNativeHostedProviderAuthority).toHaveBeenCalledWith("nemoclaw", { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -226,8 +170,8 @@ describe("credential actions use typed OpenShell provider results", () => { }, { providerAdapter: adapter, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority: () => { + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority: () => { throw new Error("state directory is read-only"); }, }, @@ -258,7 +202,7 @@ describe("credential actions use typed OpenShell provider results", () => { }, })), }); - const setNativeNvidiaProviderAuthority = vi.fn(); + const setNativeHostedProviderAuthority = vi.fn(); const result = await runCredentialsAddAction( { @@ -270,20 +214,20 @@ describe("credential actions use typed OpenShell provider results", () => { }, { providerAdapter: adapter, - getNativeNvidiaProviderAuthority: () => ({ + getNativeHostedProviderAuthority: () => ({ schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", providerId: "11111111-2222-4333-8444-555555555555", }), - setNativeNvidiaProviderAuthority, + setNativeHostedProviderAuthority, }, ); expect(result.exitCode).toBe(1); expect(result.failureLines.join("\n")).toContain("changed identity"); expect(adapter.updateProvider).not.toHaveBeenCalled(); - expect(setNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(setNativeHostedProviderAuthority).not.toHaveBeenCalled(); }); it("lists the native NVIDIA provider only by its logical credential name", async () => { @@ -989,7 +933,7 @@ describe("credential actions use typed OpenShell provider results", () => { }); it.each(["nvidia-prod", "nemoclaw-nvidia-prod-v1"])( - "preserves attached native NVIDIA providers during credential reset via %s", + "preserves attached NVIDIA providers during credential reset via %s", async (provider) => { const deleteProvider = vi.fn(async () => ({ ok: false, @@ -1001,7 +945,14 @@ describe("credential actions use typed OpenShell provider results", () => { }, })); const detachProvider = vi.fn(); - const adapter = providerAdapter({ deleteProvider, detachProvider }); + const adapter = providerAdapter({ + deleteProvider, + detachProvider, + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), + }); const result = await runCredentialsResetAction( { provider, confirmed: true }, @@ -1030,9 +981,73 @@ describe("credential actions use typed OpenShell provider results", () => { }, ); + it.each(NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"))( + "preserves $label authority on failed reset and clears it after confirmed deletion", + async (profile) => { + const clear = vi.fn(); + const deletion = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "failed", message: "failed" }, + }) + .mockResolvedValueOnce({ ok: true }); + const adapter = providerAdapter({ + deleteProvider: deletion, + getProvider: vi.fn(async () => ({ + ok: false as const, + error: { kind: "command" as const, reason: "not_found" as const, message: "absent" }, + })), + }); + const failed = await runCredentialsResetAction( + { provider: profile.logicalProvider, confirmed: true }, + { providerAdapter: adapter, clearNativeHostedProviderAuthority: clear }, + ); + expect(failed.exitCode).toBe(1); + expect(clear).not.toHaveBeenCalled(); + const succeeded = await runCredentialsResetAction( + { provider: profile.logicalProvider, confirmed: true }, + { providerAdapter: adapter, clearNativeHostedProviderAuthority: clear }, + ); + expect(succeeded.exitCode).toBe(0); + expect(deletion.mock.calls.map(([request]) => request.providerName)).toEqual([ + profile.providerName, + profile.providerName, + ]); + expect(clear).toHaveBeenCalledExactlyOnceWith("nemoclaw", profile.profileId); + }, + ); + + it.each(NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"))( + "clears $label ownership when reset confirms the provider is already absent", + async (profile) => { + const clear = vi.fn(); + const adapter = providerAdapter({ + getProvider: vi.fn(async () => ({ + ok: false as const, + error: { kind: "command" as const, reason: "not_found" as const, message: "absent" }, + })), + deleteProvider: vi.fn(async () => ({ + ok: false as const, + error: { kind: "command" as const, reason: "not_found" as const, message: "absent" }, + })), + }); + const result = await runCredentialsResetAction( + { provider: profile.logicalProvider, confirmed: true }, + { providerAdapter: adapter, clearNativeHostedProviderAuthority: clear }, + ); + expect(result.exitCode).toBe(0); + expect(clear).toHaveBeenCalledExactlyOnceWith("nemoclaw", profile.profileId); + }, + ); + it("clears native NVIDIA gateway authority only after provider deletion is confirmed", async () => { - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const adapter = providerAdapter({ + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), deleteProvider: vi.fn(async () => ({ ok: true as const })), }); @@ -1040,19 +1055,26 @@ describe("credential actions use typed OpenShell provider results", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter, - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames: () => [], withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), }, ); expect(result.exitCode).toBe(0); - expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw"); + expect(clearNativeHostedProviderAuthority).toHaveBeenCalledWith( + "nemoclaw", + "nemoclaw-nvidia-inference-v1", + ); }); it("clears native NVIDIA authority when the provider is already absent", async () => { - const clearNativeNvidiaProviderAuthority = vi.fn(); + const clearNativeHostedProviderAuthority = vi.fn(); const adapter = providerAdapter({ + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "absent" }, + })), deleteProvider: vi.fn(async () => ({ ok: false as const, error: { @@ -1067,14 +1089,17 @@ describe("credential actions use typed OpenShell provider results", () => { { provider: "nvidia-prod", confirmed: true }, { providerAdapter: adapter, - clearNativeNvidiaProviderAuthority, + clearNativeHostedProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames: () => [], withGatewayRouteMutationLock: async (_gatewayName, operation) => operation(), }, ); expect(result.exitCode).toBe(0); - expect(clearNativeNvidiaProviderAuthority).toHaveBeenCalledWith("nemoclaw"); + expect(clearNativeHostedProviderAuthority).toHaveBeenCalledWith( + "nemoclaw", + "nemoclaw-nvidia-inference-v1", + ); }); it("reports recovery for sandboxes detached before final deletion fails (#9806)", async () => { diff --git a/src/lib/actions/credentials/reset.ts b/src/lib/actions/credentials/reset.ts index 44b88d161b1..86288121f55 100644 --- a/src/lib/actions/credentials/reset.ts +++ b/src/lib/actions/credentials/reset.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + NATIVE_HOSTED_PROFILES, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter-cli"; import type { OpenShellProviderAdapter, @@ -13,21 +17,21 @@ import { NAME_VALID_PATTERN, PROVIDER_NAME_VALID_PATTERN, } from "../../name-validation"; -import { CLI_NAME } from "../../cli/branding"; import { - NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../../inference/native-nvidia"; + NVIDIA_HOSTED_CREDENTIAL_ENV, +} from "../../inference/native-nvidia/contract"; +import { CLI_NAME } from "../../cli/branding"; import { isBridgeProviderName, recoverCredentialGatewayTargetOrExit, } from "../../credentials/command-support"; import { prompt as askPrompt, KNOWN_CREDENTIAL_ENV_KEYS } from "../../credentials/store"; +import { clearNativeHostedProviderAuthority } from "../../state/registry/native-nvidia-provider-authority"; import { withGatewayRouteMutationLock } from "../../inference/gateway-route-mutation-lock"; import { - clearNativeNvidiaProviderAuthority, listNativeNvidiaProviderAttachmentSandboxNames, + listNativeHostedProviderAttachmentSandboxNames, } from "../../state/registry/native-nvidia-provider-authority"; import { forgetExtraProvider } from "../global"; @@ -44,9 +48,10 @@ export type CredentialsResetResult = { export type CredentialsResetDeps = Readonly<{ providerAdapter?: OpenShellProviderAdapter; - clearNativeNvidiaProviderAuthority?: typeof clearNativeNvidiaProviderAuthority; listNativeNvidiaProviderAttachmentSandboxNames?: typeof listNativeNvidiaProviderAttachmentSandboxNames; + listNativeHostedProviderAttachmentSandboxNames?: typeof listNativeHostedProviderAttachmentSandboxNames; withGatewayRouteMutationLock?: typeof withGatewayRouteMutationLock; + clearNativeHostedProviderAuthority?: typeof clearNativeHostedProviderAuthority; }>; export type CredentialsProviderDeleteWithRecoveryResult = Readonly<{ @@ -98,32 +103,42 @@ function detachedSandboxGuidance(key: string, sandboxes: readonly string[]): str ]; } -function nativeNvidiaResetBlockers( +function nativeHostedResetBlockers( deps: CredentialsResetDeps, + profile: NativeHostedProfile, gatewayName: string, ): { ok: true; sandboxes: readonly string[] } | { ok: false } { try { return { ok: true, - sandboxes: ( - deps.listNativeNvidiaProviderAttachmentSandboxNames ?? - listNativeNvidiaProviderAttachmentSandboxNames - )(gatewayName), + sandboxes: + profile.logicalProvider !== "nvidia-prod" + ? ( + deps.listNativeHostedProviderAttachmentSandboxNames ?? + listNativeHostedProviderAttachmentSandboxNames + )(profile.profileId, gatewayName) + : ( + deps.listNativeNvidiaProviderAttachmentSandboxNames ?? + listNativeNvidiaProviderAttachmentSandboxNames + )(gatewayName), }; } catch { return { ok: false }; } } -function nativeNvidiaResetBlockedResult(sandboxes: readonly string[]): CredentialsResetResult { +function nativeHostedResetBlockedResult( + sandboxes: readonly string[], + profile: NativeHostedProfile, +): CredentialsResetResult { return fail([ - ` Could not remove provider '${NVIDIA_HOSTED_LOGICAL_PROVIDER}'.`, + ` Could not remove provider '${profile.logicalProvider}'.`, "", - ` '${NVIDIA_HOSTED_LOGICAL_PROVIDER}' is recorded by sandbox(es): ${sandboxes.join(", ")}.`, + ` '${profile.logicalProvider}' is recorded by sandbox(es): ${sandboxes.join(", ")}.`, " No provider or ownership authority was changed.", - ` To rotate the credential in place, set ${NVIDIA_HOSTED_CREDENTIAL_ENV} and rerun '${CLI_NAME} onboard --name '.`, + ` To rotate the credential in place, set ${profile.hostCredentialEnv ?? profile.credentialEnv} and rerun '${CLI_NAME} onboard --name '.`, " To remove the provider completely, preserve any required sandbox state, destroy every recorded sandbox,", - ` then rerun '${CLI_NAME} credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER}'.`, + ` then rerun '${CLI_NAME} credentials reset ${profile.logicalProvider}'.`, ...sandboxes.map((sandbox) => ` ${CLI_NAME} ${sandbox} destroy`), ]); } @@ -133,10 +148,12 @@ export async function runCredentialsResetAction( deps: CredentialsResetDeps = {}, ): Promise { const key = input.provider; - const nativeNvidiaProvider = - key === NVIDIA_HOSTED_LOGICAL_PROVIDER || key === NVIDIA_HOSTED_NATIVE_PROVIDER; - const providerName = nativeNvidiaProvider ? NVIDIA_HOSTED_NATIVE_PROVIDER : key; - const publicKey = nativeNvidiaProvider ? NVIDIA_HOSTED_LOGICAL_PROVIDER : key; + const nativeProfile = NATIVE_HOSTED_PROFILES.find( + (profile) => profile.logicalProvider === key || profile.providerName === key, + ); + const providerName = nativeProfile?.providerName ?? key; + const publicKey = nativeProfile?.logicalProvider ?? key; + if (!PROVIDER_NAME_VALID_PATTERN.test(key)) { return fail([ " Provider name must be 1-128 chars, start with a letter, and use only letters, digits, '.', '_', or '-'.", @@ -168,22 +185,39 @@ export async function runCredentialsResetAction( const providerAdapter = deps.providerAdapter ?? createCliOpenShellProviderAdapter(); const resetProvider = async (): Promise => { - if (nativeNvidiaProvider) { - const blockers = nativeNvidiaResetBlockers(deps, target.gatewayName); - if (!blockers.ok) { + if (nativeProfile) { + const blockers = nativeHostedResetBlockers(deps, nativeProfile, target.gatewayName); + if (!blockers.ok) return fail([ - ` Could not safely inspect native NVIDIA inference ownership on gateway '${target.gatewayName}'.`, + ` Could not safely inspect native ${nativeProfile.label} inference ownership on gateway '${target.gatewayName}'.`, " No provider or ownership authority was changed.", " Repair the existing NemoClaw state and retry.", ]); - } - if (blockers.sandboxes.length > 0) { - return nativeNvidiaResetBlockedResult(blockers.sandboxes); + if (blockers.sandboxes.length > 0) + return nativeHostedResetBlockedResult(blockers.sandboxes, nativeProfile); + } + + if (nativeProfile && key === nativeProfile.logicalProvider) { + const legacy = await providerAdapter.getProvider({ + target, + providerName: nativeProfile.logicalProvider, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + // Native authority binds only the native identity. No durable legacy receipt exists. + if (legacy.ok || legacy.error.kind !== "command" || legacy.error.reason !== "not_found") { + return fail([ + ` Provider ownership conflict for '${nativeProfile.logicalProvider}'.`, + legacy.ok + ? " NemoClaw has no durable ownership proof for this legacy provider." + : " NemoClaw could not confirm that the legacy provider is absent.", + " No provider or ownership authority was changed.", + " Inspect the legacy provider with its owner before retrying the logical reset.", + ]); } } const recovery = await deleteProviderWithRecovery(providerName, target, providerAdapter, { - detachAttached: !nativeNvidiaProvider, + detachAttached: !nativeProfile, }); if ( @@ -192,9 +226,10 @@ export async function runCredentialsResetAction( recovery.error?.kind === "command" && recovery.error.reason === "not_found" ) { - if (nativeNvidiaProvider) { - (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( + if (nativeProfile) { + (deps.clearNativeHostedProviderAuthority ?? clearNativeHostedProviderAuthority)( target.gatewayName, + nativeProfile.profileId, ); } const removedLocal = forgetExtraProvider(key); @@ -211,15 +246,15 @@ export async function runCredentialsResetAction( if (!outcome.ok) return fail(outcome.lines); forgetExtraProvider(publicKey); - if (nativeNvidiaProvider) { - (deps.clearNativeNvidiaProviderAuthority ?? clearNativeNvidiaProviderAuthority)( + if (nativeProfile) { + (deps.clearNativeHostedProviderAuthority ?? clearNativeHostedProviderAuthority)( target.gatewayName, + nativeProfile.profileId, ); } return ok(outcome.lines); }; - - if (!nativeNvidiaProvider) return resetProvider(); + if (!nativeProfile) return resetProvider(); return (deps.withGatewayRouteMutationLock ?? withGatewayRouteMutationLock)( target.gatewayName, resetProvider, diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index e60ba29acf7..e6e8aa2d19a 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -179,7 +179,7 @@ describe("runInferenceGet", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, providerName: "nemoclaw-nvidia-prod-v1" as const, @@ -924,6 +924,33 @@ describe("runInferenceGet", () => { }, ); + it.each( + ["default", "named"].flatMap((lookup) => + [false, true].map((permission) => ({ lookup, permission })), + ), + )( + "maps $lookup registry lookup errors with permission=$permission to recovery guidance", + async ({ lookup, permission }) => { + const deps = createDeps({ ok: true, value: { state: "unconfigured" } }); + const fail = () => { + throw permission + ? new ConfigPermissionError("/safe/state/sandboxes.json", "read") + : new ConfigCorruptError("/safe/state/sandboxes.json"); + }; + deps.getDefaultSandbox = lookup === "default" ? fail : () => "alpha"; + deps.getSandbox = fail; + await expect(runInferenceGet({}, deps)).rejects.toMatchObject({ + name: "InferenceGetError", + message: expect.stringContaining( + permission + ? "Cannot read config file: /safe/state/sandboxes.json" + : "Configuration file is present but is not valid JSON: /safe/state/sandboxes.json", + ), + }); + expect(deps.observeInferenceRoute).not.toHaveBeenCalled(); + }, + ); + it("sanitizes route values only for human-readable output", async () => { const deps = createDeps(configuredRoute("openai\u001b[2J", "gpt\u0007-5.4")); diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index fa0e0ffc070..f37094c21a1 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../inference/native-hosted/profiles"; import { captureOpenshell } from "../adapters/openshell/runtime"; import { createSynchronousCliOpenShellInferenceRouteObserver } from "../adapters/openshell/inference-route-cli"; import type { @@ -21,10 +22,9 @@ import { } from "../inference/gateway-route-compatibility"; import { parseHttpsPinRouteId } from "../inference/https-pin-runtime"; import { - isNativeNvidiaProvider, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - normalizeNativeNvidiaProviderAttachment, -} from "../inference/native-nvidia"; + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, +} from "../inference/native-hosted"; import { inspectManagedLlamaCppOwnership } from "../inference/llama-cpp/managed-state"; import { valueLooksLikeSecret } from "../security/credential-filter"; import { ConfigCorruptError, ConfigPermissionError } from "../state/config-io"; @@ -309,19 +309,32 @@ export async function runInferenceGet( options: InferenceGetOptions = {}, deps: InferenceGetDeps = defaultDeps(), ): Promise { - const selectedSandboxName = options.sandboxName ?? deps.getDefaultSandbox?.() ?? null; - const selectedSandbox = selectedSandboxName - ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) - : null; + let selectedSandbox: ReturnType | null; + try { + const selectedSandboxName = options.sandboxName ?? deps.getDefaultSandbox?.() ?? null; + selectedSandbox = selectedSandboxName + ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) + : null; + } catch (error) { + throw new InferenceGetError(formatGatewayResolutionFailure(error, options.sandboxName)); + } + const receipt = normalizeNativeHostedProviderAttachment( + selectedSandbox?.nativeHostedProviderAttachment, + ); + if (receipt && nativeHostedProfile(selectedSandbox?.provider)?.profileId !== receipt.profileId) { + throw new InferenceGetError( + "Recorded native inference provider does not match the selected provider.", + ); + } if ( selectedSandbox && - isNativeNvidiaProvider(selectedSandbox.provider) && - normalizeNativeNvidiaProviderAttachment(selectedSandbox.nativeNvidiaProviderAttachment) + isNativeHostedProvider(selectedSandbox.provider) && + normalizeNativeHostedProviderAttachment(selectedSandbox.nativeHostedProviderAttachment) ) { const payload: InferenceGetResult = { provider: selectedSandbox.provider ?? null, model: selectedSandbox.model ?? null, - endpointUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + endpointUrl: nativeHostedProfile(selectedSandbox.provider)!.endpoint, }; if (!options.quiet) { if (options.json) { @@ -329,7 +342,9 @@ export async function runInferenceGet( } else { deps.log(`Provider: ${formatRouteValueForDisplay(payload.provider)}`); deps.log(`Model: ${formatRouteValueForDisplay(payload.model)}`); - deps.log(`Endpoint: ${formatRouteValueForDisplay(NVIDIA_HOSTED_NATIVE_ENDPOINT)}`); + deps.log( + `Endpoint: ${formatRouteValueForDisplay(nativeHostedProfile(selectedSandbox.provider)!.endpoint)}`, + ); } } return payload; diff --git a/src/lib/actions/inference-route-api.test.ts b/src/lib/actions/inference-route-api.test.ts index a0413a92882..af0e0ea4cf9 100644 --- a/src/lib/actions/inference-route-api.test.ts +++ b/src/lib/actions/inference-route-api.test.ts @@ -94,6 +94,21 @@ describe("readOpenClawPrimaryRouteApi", () => { }); describe("resolveRuntimeInferenceApi", () => { + it("uses native NVIDIA Completions despite stale route history", () => { + expect( + resolve( + {}, + { + provider: "nvidia-prod", + currentProvider: "nvidia-prod", + session: session({ + provider: "nvidia-prod", + preferredInferenceApi: "anthropic-messages", + }), + }, + ), + ).toBe("openai-completions"); + }); it("uses the current config route API before matching onboard history", () => { expect( resolve( diff --git a/src/lib/actions/inference-route-api.ts b/src/lib/actions/inference-route-api.ts index bee719cbdbf..79b74f91bf2 100644 --- a/src/lib/actions/inference-route-api.ts +++ b/src/lib/actions/inference-route-api.ts @@ -1,7 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { getSandboxInferenceConfig, resolveAgentInferenceApi } from "../inference/config"; +import { + getSandboxInferenceConfig, + resolveAgentInferenceApi, + isNativeNvidiaProvider, + nativeHostedProfile, +} from "../inference/config"; import type { ConfigObject } from "../security/credential-filter"; import { isConfigObject } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; @@ -106,6 +111,7 @@ export function resolveRuntimeInferenceApi(options: { session: Session | null; }): InferenceApi | null { const { agentName, config, currentProvider, provider, sandboxName, session } = options; + if (isNativeNvidiaProvider(provider)) return "openai-completions"; if (provider === "anthropic-prod") return "anthropic-messages"; const agentApi = resolveAgentInferenceApi(agentName, provider, null); if (agentApi) return normalizeInferenceApi(agentApi); @@ -125,3 +131,25 @@ export function resolveRuntimeInferenceApi(options: { if (provider === "compatible-anthropic-endpoint") return "anthropic-messages"; return null; } + +export function resolveNativeInferenceRegistryMetadata(input: { + provider: string; + model: string; + previousProvider: string | null | undefined; + previousApi: string | null | undefined; +}) { + const profile = nativeHostedProfile(input.provider); + if (!profile) return null; + const route = getSandboxInferenceConfig( + input.model, + input.provider, + input.previousProvider === input.provider ? (input.previousApi ?? null) : null, + ); + return { + endpointUrl: profile.endpoint, + endpointSource: null, + credentialEnv: profile.credentialEnv, + preferredInferenceApi: route.inferenceApi, + nimContainer: null, + }; +} diff --git a/src/lib/actions/inference-set-compatible-provider.test.ts b/src/lib/actions/inference-set-compatible-provider.test.ts index 1e15421d96f..12192f3a5da 100644 --- a/src/lib/actions/inference-set-compatible-provider.test.ts +++ b/src/lib/actions/inference-set-compatible-provider.test.ts @@ -1484,7 +1484,10 @@ describe("runInferenceSet compatible providers", () => { inferenceRouteMutator: { setInferenceRoute: noBindingSet }, }); await expect( - runInferenceSet({ provider: "openai-api", model: "gpt-test", noVerify: true }, noBindingDeps), + runInferenceSet( + { provider: "ollama-local", model: "gpt-test", noVerify: true }, + noBindingDeps, + ), ).rejects.toThrow("provider not found"); expect(noBindingSet).toHaveBeenCalledOnce(); }); diff --git a/src/lib/actions/inference-set-failure-handling.test.ts b/src/lib/actions/inference-set-failure-handling.test.ts index 753688479a7..4d6a2d3b87c 100644 --- a/src/lib/actions/inference-set-failure-handling.test.ts +++ b/src/lib/actions/inference-set-failure-handling.test.ts @@ -97,20 +97,29 @@ describe("runInferenceSet failure handling", () => { const deps = createDeps({ config: {}, openshellStatus: 17 }); await expect( - runInferenceSet({ provider: "openai-api", model: "openai/model-a" }, deps), - ).rejects.toThrow(/OpenShell inference route update with verification failed/); + runInferenceSet({ provider: "ollama-local", model: "openai/model-a" }, deps), + ).rejects.toThrow(/OpenShell inference route update failed/); expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); it("gives same-gateway recovery guidance for an ambiguous production mutation", async () => { - const deps = createDeps({ config: {}, openshellStatus: 17 }); + const deps = createDeps({ + config: {}, + captureOpenshell: () => ({ + status: 1, + output: "", + stdout: "", + stderr: "", + error: Object.assign(new Error("timed out"), { code: "ETIMEDOUT" }), + }), + }); await expect( - runInferenceSet({ provider: "openai-api", model: "openai/model-a" }, deps), + runInferenceSet({ provider: "ollama-local", model: "openai/model-a" }, deps), ).rejects.toThrow( - /route state is unknown.*Inspect gateway 'nemoclaw', then rerun the same `nemoclaw inference set` command\./su, + /without a confirmed result.*Inspect gateway 'nemoclaw', then rerun the same `nemoclaw inference set` command\./su, ); expect(deps.calls.captureOpenshell).toHaveBeenCalledOnce(); @@ -123,7 +132,7 @@ describe("runInferenceSet failure handling", () => { const createProvider = vi.fn(); const base = createDeps({ config: {}, - entries: [{ name: "alpha", agent: "openclaw", provider: "openai-api", model: "old-model" }], + entries: [{ name: "alpha", agent: "openclaw", provider: "ollama-local", model: "old-model" }], inferenceRouteMutator: { setInferenceRoute }, inferenceRouteObserver: { observeInferenceRoute: vi.fn(async () => ({ @@ -142,7 +151,7 @@ describe("runInferenceSet failure handling", () => { }; await expect( - runInferenceSet({ provider: "openai-api", model: "new-model" }, deps), + runInferenceSet({ provider: "ollama-local", model: "new-model" }, deps), ).rejects.toThrow(/Cannot reconcile.*gateway 'nemoclaw'.*gateway unavailable/su); expect(createProvider).not.toHaveBeenCalled(); @@ -162,7 +171,7 @@ describe("runInferenceSet failure handling", () => { ok: true as const, value: { state: "configured" as const, - route: { provider: "openai-api", model: "old-model" }, + route: { provider: "ollama-local", model: "old-model" }, }, }; }); @@ -185,13 +194,13 @@ describe("runInferenceSet failure handling", () => { }); const deps = createDeps({ config: {}, - entries: [{ name: "alpha", agent: "openclaw", provider: "openai-api", model: "old-model" }], + entries: [{ name: "alpha", agent: "openclaw", provider: "ollama-local", model: "old-model" }], inferenceRouteObserver: { observeInferenceRoute }, inferenceRouteMutator: { setInferenceRoute }, }); await expect( - runInferenceSet({ provider: "openai-api", model: "new-model" }, deps), + runInferenceSet({ provider: "ollama-local", model: "new-model" }, deps), ).rejects.toThrow( /gateway schema mismatch.*Inspect gateway 'nemoclaw', then rerun the same `nemoclaw inference set` command\./su, ); @@ -199,8 +208,8 @@ describe("runInferenceSet failure handling", () => { expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); await expect( - runInferenceSet({ provider: "openai-api", model: "new-model" }, deps), - ).resolves.toMatchObject({ provider: "openai-api", model: "new-model" }); + runInferenceSet({ provider: "ollama-local", model: "new-model" }, deps), + ).resolves.toMatchObject({ provider: "ollama-local", model: "new-model" }); expect(events).toEqual([ "observe:nemoclaw", @@ -225,7 +234,8 @@ describe("runInferenceSet failure handling", () => { status: null, output: "", stdout: "", - stderr: `error: provider 'openai-api' not found at https://${username}:${password}@gateway.example.test/v1?token=${querySecret} ${"x".repeat(3_000)}`, + stderr: `error: provider 'ollama-local' not found at https://${username}:${password}@gateway.example.test/v1?token=${querySecret} ${"x".repeat(3_000)}`, + error: Object.assign(new Error("spawnSync openshell ENOBUFS"), { code: "ENOBUFS" }), signal: "SIGTERM", }) @@ -237,7 +247,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((error: Error) => error); @@ -282,17 +292,17 @@ describe("runInferenceSet failure handling", () => { status: 1, output: "", stdout: "", - stderr: "error: provider 'openai-api' not found in gateway", + stderr: "error: provider 'ollama-local' not found in gateway", }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((e: Error) => e); expect(err).toBeInstanceOf(Error); const message = (err as Error).message; - expect(message).toMatch(/provider 'openai-api' not found/); + expect(message).toMatch(/provider 'ollama-local' not found/); expect(message).toMatch(/Registered providers: nvidia-prod/); expect(message).not.toMatch(/stale-local|telegram-bridge/); expect(message).toMatch(/Tip: register a new provider with `nemoclaw onboard`/); @@ -317,15 +327,13 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/model-a" }, + { provider: "ollama-local", model: "openai/model-a" }, deps, ).catch((e: Error) => e); expect(err).toBeInstanceOf(Error); const message = (err as Error).message; - expect(message).toMatch( - /OpenShell inference route update with verification failed with exit 42/, - ); + expect(message).toMatch(/OpenShell inference route update failed with exit 42/); expect(message).toMatch(/network timeout connecting to gateway/); expect(message).not.toContain("nvapi-secret-value"); expect(message).not.toMatch(/Registered providers/); @@ -342,8 +350,8 @@ describe("runInferenceSet failure handling", () => { deps.calls.captureOpenshell .mockReturnValueOnce({ status: 1, - output: "error: provider 'openai-api' not found in gateway", - stdout: "error: provider 'openai-api' not found in gateway", + output: "error: provider 'ollama-local' not found in gateway", + stdout: "error: provider 'ollama-local' not found in gateway", stderr: "", }) .mockReturnValueOnce({ @@ -354,7 +362,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((e: Error) => e); @@ -372,14 +380,14 @@ describe("runInferenceSet failure handling", () => { status: 1, output: "", stdout: "", - stderr: "error: provider 'openai-api' not found in gateway", + stderr: "error: provider 'ollama-local' not found in gateway", }) .mockImplementationOnce(() => { throw new Error(`gateway provider query failed token=${querySecret}`); }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((e: Error) => e); @@ -402,7 +410,7 @@ describe("runInferenceSet failure handling", () => { status: 1, output: "", stdout: "", - stderr: "error: provider 'openai-api' not found in gateway", + stderr: "error: provider 'ollama-local' not found in gateway", }) .mockReturnValueOnce({ status: null, @@ -414,7 +422,7 @@ describe("runInferenceSet failure handling", () => { }); const err = await runInferenceSet( - { provider: "openai-api", model: "openai/gpt-5.4-mini" }, + { provider: "ollama-local", model: "openai/gpt-5.4-mini" }, deps, ).catch((error: Error) => error); diff --git a/src/lib/actions/inference-set-gateway-route-containment.test.ts b/src/lib/actions/inference-set-gateway-route-containment.test.ts index 46e6148f76b..080d2798079 100644 --- a/src/lib/actions/inference-set-gateway-route-containment.test.ts +++ b/src/lib/actions/inference-set-gateway-route-containment.test.ts @@ -27,6 +27,45 @@ const entry = (name: string, overrides: Partial = {}): SandboxEntr }); describe("runtime shared gateway route containment", () => { + it.each([ + ["openai-api", "openai-api", "openai-responses"], + ["hermes-provider", "hermes-provider", "openai-responses"], + ["gemini-api", "openai-api", "openai-completions"], + ["anthropic-prod", "openai-api", "anthropic-messages"], + ])("persists native %s protocol from prior %s", (provider, previousProvider, api) => { + const prepared = prepareInferenceSetRoute({ + entry: entry("alpha", { + provider: previousProvider, + preferredInferenceApi: "openai-responses", + }), + sandboxName: "alpha", + provider, + model: "model-a", + customRoute: {}, + session: null, + sandboxes: [], + }); + expect(prepared.preliminaryRegistryMetadata.preferredInferenceApi).toBe(api); + }); + + it("refuses custom endpoint metadata for a fixed native provider", () => { + expect(() => + prepareInferenceSetRoute({ + entry: entry("alpha"), + sandboxName: "alpha", + provider: "openai-api", + model: "model-a", + customRoute: { + endpointUrl: "https://untrusted.example/v1", + credentialEnv: "OTHER_KEY", + inferenceApi: "openai-completions", + }, + session: null, + sandboxes: [], + }), + ).toThrow(); + }); + afterEach(() => { vi.unstubAllEnvs(); delete process.env[HTTPS_PIN_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV]; @@ -82,18 +121,18 @@ describe("runtime shared gateway route containment", () => { const deps = createDeps({ config: {}, entries: [ - entry("alpha", { provider: "openrouter-api", model: "openrouter/model-a" }), - entry("stopped-peer", { provider: "openrouter-api", model: "openrouter/model-a" }), + entry("alpha", { provider: "ollama-local", model: "local/model-a" }), + entry("stopped-peer", { provider: "ollama-local", model: "local/model-a" }), ], defaultSandbox: "alpha", }); await expect( runInferenceSet( - { provider: "openrouter-api", model: "openrouter/model-b", sandboxName: "alpha" }, + { provider: "ollama-local", model: "local/model-b", sandboxName: "alpha" }, deps, ), - ).resolves.toMatchObject({ sandboxName: "alpha", model: "openrouter/model-b" }); + ).resolves.toMatchObject({ sandboxName: "alpha", model: "local/model-b" }); expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( [ @@ -103,9 +142,9 @@ describe("runtime shared gateway route containment", () => { "nemoclaw", "--no-verify", "--provider", - "openrouter-api", + "ollama-local", "--model", - "openrouter/model-b", + "local/model-b", ], expect.objectContaining({ ignoreError: true }), ); @@ -117,9 +156,7 @@ describe("runtime shared gateway route containment", () => { message.includes("Setting OpenShell inference route"), ); expect(warningIndex).toBeGreaterThanOrEqual(0); - expect(messages[warningIndex]).toContain( - "'stopped-peer' (openrouter-api / openrouter/model-a)", - ); + expect(messages[warningIndex]).toContain("'stopped-peer' (ollama-local / local/model-a)"); expect(warningIndex).toBeLessThan(mutationIndex); }); @@ -131,8 +168,8 @@ describe("runtime shared gateway route containment", () => { entry("alpha", { gatewayName: "nemoclaw-9090", gatewayPort: 9090, - provider: "openrouter-api", - model: "openrouter/model-a", + provider: "ollama-local", + model: "local/model-a", }), entry("default-gateway-peer"), ], @@ -142,10 +179,10 @@ describe("runtime shared gateway route containment", () => { await expect( runInferenceSet( - { provider: "openrouter-api", model: "openrouter/model-b", sandboxName: "alpha" }, + { provider: "ollama-local", model: "local/model-b", sandboxName: "alpha" }, deps, ), - ).resolves.toMatchObject({ sandboxName: "alpha", model: "openrouter/model-b" }); + ).resolves.toMatchObject({ sandboxName: "alpha", model: "local/model-b" }); expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( [ @@ -155,9 +192,9 @@ describe("runtime shared gateway route containment", () => { "nemoclaw-9090", "--no-verify", "--provider", - "openrouter-api", + "ollama-local", "--model", - "openrouter/model-b", + "local/model-b", ], expect.objectContaining({ ignoreError: true }), ); @@ -171,7 +208,7 @@ describe("runtime shared gateway route containment", () => { entry("alpha", { gatewayName: "nemoclaw-9090", gatewayPort: 9090, - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -685,8 +722,8 @@ describe("runtime shared gateway route containment", () => { try { const entries = [ entry("route-lock-alpha", { - provider: "openrouter-api", - model: "openrouter/model-a", + provider: "ollama-local", + model: "local/model-a", }), entry("route-lock-beta"), ]; @@ -712,14 +749,14 @@ describe("runtime shared gateway route containment", () => { const results = await Promise.allSettled([ runInferenceSet( { - provider: "openrouter-api", - model: "openrouter/model-a", + provider: "ollama-local", + model: "local/model-a", sandboxName: entries[0].name, }, deps, ), runInferenceSet( - { provider: "anthropic-prod", model: "claude-new", sandboxName: entries[1].name }, + { provider: "ollama-local", model: "local/model-b", sandboxName: entries[1].name }, deps, ), ]); @@ -731,8 +768,8 @@ describe("runtime shared gateway route containment", () => { ), ).toHaveLength(2); expect(entries).toEqual([ - expect.objectContaining({ provider: "openrouter-api", model: "openrouter/model-a" }), - expect.objectContaining({ provider: "anthropic-prod", model: "claude-new" }), + expect.objectContaining({ provider: "ollama-local", model: "local/model-a" }), + expect.objectContaining({ provider: "ollama-local", model: "local/model-b" }), ]); expect( deps.calls.log.mock.calls.some(([message]) => diff --git a/src/lib/actions/inference-set-hermes-run.test.ts b/src/lib/actions/inference-set-hermes-run.test.ts index 5583bdf7fe8..027512e0792 100644 --- a/src/lib/actions/inference-set-hermes-run.test.ts +++ b/src/lib/actions/inference-set-hermes-run.test.ts @@ -21,6 +21,95 @@ describe("runInferenceSet Hermes routing", () => { portableMocks.assertUnavailable.mockReset(); }); + it("creates the first native Hermes provider from its Nous API key", async () => { + const deps = createDeps({ + config: { + model: { default: "baseline", provider: "custom", base_url: "https://inference.local/v1" }, + }, + entry: { + name: "hermes", + agent: "hermes", + gatewayName: "nemoclaw", + provider: "compatible-endpoint", + model: "baseline", + }, + defaultSandbox: "hermes", + target: HERMES_TARGET, + resolveCredentialValue: (name) => (name === "NOUS_API_KEY" ? "nous-test-credential" : ""), + }); + const create = vi.spyOn(deps.providerAdapter, "createProvider"); + const attach = vi.spyOn(deps.providerAdapter, "attachProvider"); + await runInferenceSet( + { + provider: "hermes-provider", + model: "selected-model", + sandboxName: "hermes", + noVerify: true, + }, + deps, + ); + expect(create).toHaveBeenCalledWith( + expect.objectContaining({ + name: "nemoclaw-hermes-provider-v1", + credentials: [{ name: "OPENAI_API_KEY", value: "nous-test-credential" }], + }), + ); + expect(attach).toHaveBeenCalledWith( + expect.objectContaining({ + providerName: "nemoclaw-hermes-provider-v1", + sandboxName: "hermes", + }), + ); + expect(deps.calls.resolveCredentialValue).toHaveBeenCalledWith("NOUS_API_KEY"); + expect(JSON.stringify(deps.calls.writeSandboxConfig.mock.calls)).not.toContain( + "nous-test-credential", + ); + expect(JSON.stringify(deps.calls.updateSandbox.mock.calls)).not.toContain( + "nous-test-credential", + ); + }); + + it("reuses an owned Hermes provider without a manual Nous API key", async () => { + const deps = createDeps({ + config: { + model: { + default: "baseline", + provider: "custom", + base_url: "https://inference-api.nousresearch.com/v1", + }, + }, + entry: { + name: "hermes", + agent: "hermes", + gatewayName: "nemoclaw", + provider: "hermes-provider", + model: "baseline", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "owned-oauth-provider", + }, + }, + defaultSandbox: "hermes", + target: HERMES_TARGET, + resolveCredentialValue: () => "", + }); + const create = vi.spyOn(deps.providerAdapter, "createProvider"); + const update = vi.spyOn(deps.providerAdapter, "updateProvider"); + await runInferenceSet( + { + provider: "hermes-provider", + model: "selected-model", + sandboxName: "hermes", + noVerify: true, + }, + deps, + ); + expect(create).not.toHaveBeenCalled(); + expect(update).not.toHaveBeenCalled(); + }); + it("rejects schema-5 before OpenShell or registry mutation (#9203)", async () => { portableMocks.assertUnavailable.mockImplementation(() => { throw new Error("schema-5 rejected"); @@ -30,6 +119,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -65,6 +161,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -103,6 +206,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -122,26 +232,8 @@ describe("runInferenceSet Hermes routing", () => { deps, ); - expect(deps.calls.captureOpenshell).toHaveBeenCalledWith( - [ - "inference", - "set", - "-g", - "nemoclaw", - "--no-verify", - "--provider", - "hermes-provider", - "--model", - "openai/gpt-5.4-mini", - ], - { - ignoreError: true, - includeStderr: true, - includeStreams: true, - maxBuffer: 1024 * 1024, - timeout: 30_000, - }, - ); + expect(deps.calls.captureOpenshell).not.toHaveBeenCalled(); + expect(config).toEqual({ _nemoclaw_upstream: { provider: "hermes-provider", @@ -151,23 +243,23 @@ describe("runInferenceSet Hermes routing", () => { custom_providers: [ { name: "hermes-provider", - base_url: "https://inference.local/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + base_url: "https://inference-api.nousresearch.com/v1", + api_key: "${OPENAI_API_KEY}", discover_models: true, }, ], model: { default: "openai/gpt-5.4-mini", provider: "custom", - base_url: "https://inference.local/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + base_url: "https://inference-api.nousresearch.com/v1", + api_key: "${OPENAI_API_KEY}", context_length: 128_000, }, providers: { "hermes-provider": { name: "hermes-provider", - api: "https://inference.local/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api: "https://inference-api.nousresearch.com/v1", + api_key: "${OPENAI_API_KEY}", default_model: "openai/gpt-5.4-mini", discover_models: true, }, @@ -228,6 +320,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -261,6 +360,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -308,6 +414,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", }, @@ -362,6 +475,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "openai/gpt-5.4-mini", }, @@ -412,7 +532,7 @@ describe("runInferenceSet Hermes routing", () => { provider_key: "compatible-anthropic-endpoint", model: "claude-sonnet-proxy", }); - expect(deps.calls.updateSandbox.mock.calls.at(-1)).toEqual([ + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( "hermes", expect.objectContaining({ provider: "compatible-anthropic-endpoint", @@ -421,7 +541,7 @@ describe("runInferenceSet Hermes routing", () => { credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", preferredInferenceApi: "openai-completions", }), - ]); + ); expect(result).toMatchObject({ providerKey: "inference", primaryModelRef: "inference/claude-sonnet-proxy", @@ -484,6 +604,13 @@ describe("runInferenceSet Hermes routing", () => { entry: { name: "hermes", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "openai/gpt-5.4-mini", }, @@ -580,6 +707,13 @@ describe("runInferenceSet Hermes routing", () => { { name: "hermes-one", agent: "hermes", + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "hermes-provider-id", + }, provider: "hermes-provider", model: "z-ai/glm-5.1", }, diff --git a/src/lib/actions/inference-set-live-rollback.test.ts b/src/lib/actions/inference-set-live-rollback.test.ts index 500d28bebd7..07f9a558b5f 100644 --- a/src/lib/actions/inference-set-live-rollback.test.ts +++ b/src/lib/actions/inference-set-live-rollback.test.ts @@ -6,6 +6,148 @@ import { runInferenceSet } from "./inference-set"; import { createCompatibleProviderCapture, createDeps } from "./inference-set.test-support"; describe("runInferenceSet live rollback authority", () => { + it("restores the peer shared route after a failed departure from native inference", async () => { + const setInferenceRoute = vi.fn< + import("../adapters/openshell/inference-route").OpenShellInferenceRouteMutator["setInferenceRoute"] + >(async () => ({ ok: true as const })); + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "old-model", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + captureOpenshell: createCompatibleProviderCapture({ + name: "compatible-endpoint", + type: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + configKey: "OPENAI_BASE_URL", + initiallyPresent: false, + }), + inferenceRouteMutator: { setInferenceRoute }, + inferenceRouteObserver: { + observeInferenceRoute: async () => ({ + ok: true, + value: { + state: "configured", + route: { provider: "peer-provider", model: "peer-model" }, + }, + }), + }, + probeSandboxRoute: async () => ({ ok: false, detail: "probe refused", httpStatus: 401 }), + }); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "new-model", + endpointUrl: "http://host.openshell.internal:18767/v1", + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions", + }, + deps, + ), + ).rejects.toThrow("probe refused"); + expect(setInferenceRoute.mock.calls.map(([input]) => input.route)).toEqual([ + { provider: "compatible-endpoint", model: "new-model" }, + { provider: "peer-provider", model: "peer-model" }, + ]); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + + it.each([ + { failure: "registry", configure: (_deps: ReturnType) => {} }, + { + failure: "rollback", + configure: (deps: ReturnType) => { + vi.mocked(deps.inferenceRouteMutator.setInferenceRoute) + .mockResolvedValueOnce({ ok: true }) + .mockRejectedValueOnce(new Error("route restore denied")); + vi.mocked(deps.providerAdapter.attachProvider).mockRejectedValueOnce( + new Error("attachment restore denied"), + ); + }, + }, + { + failure: "config", + configure: (deps: ReturnType) => { + deps.calls.setOpenClawConfigValues.mockImplementation(() => { + throw new Error("config sync denied"); + }); + }, + }, + ])( + "preserves the correct rollback boundary for $failure failure", + async ({ failure, configure }) => { + const setInferenceRoute = vi.fn< + import("../adapters/openshell/inference-route").OpenShellInferenceRouteMutator["setInferenceRoute"] + >(async () => ({ ok: true as const })); + const deps = createDeps({ + config: { models: { providers: {} } }, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + captureOpenshell: createCompatibleProviderCapture({ + name: "compatible-endpoint", + type: "openai", + credentialEnv: "COMPATIBLE_API_KEY", + configKey: "OPENAI_BASE_URL", + initiallyPresent: false, + }), + inferenceRouteMutator: { setInferenceRoute }, + inferenceRouteObserver: { + observeInferenceRoute: async () => ({ + ok: true, + value: { state: "configured", route: { provider: "anthropic", model: "peer-model" } }, + }), + }, + updateSandbox: () => failure === "config", + }); + const attachProvider = vi.spyOn(deps.providerAdapter, "attachProvider"); + configure(deps); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "gpt-5.4", + noVerify: true, + endpointUrl: "http://host.openshell.internal:18767/v1", + credentialEnv: "COMPATIBLE_API_KEY", + inferenceApi: "openai-completions", + }, + deps, + ), + ).rejects.toThrow( + failure === "rollback" + ? /Failed to update NemoClaw registry.*route restore denied.*attachment restore denied/su + : failure === "config" + ? /config sync denied/su + : /Failed to update NemoClaw registry/u, + ); + expect(setInferenceRoute.mock.calls.map(([input]) => input.route)).toEqual([ + { provider: "compatible-endpoint", model: "gpt-5.4" }, + ...(failure === "config" ? [] : [{ provider: "anthropic", model: "peer-model" }]), + ]); + expect(attachProvider).toHaveBeenCalledTimes(failure === "config" ? 0 : 1); + }, + ); + it("does not reapply or report restoration when the observed route already matches the rejected route", async () => { const captureOpenshell = createCompatibleProviderCapture({ name: "compatible-endpoint", diff --git a/src/lib/actions/inference-set-local-provider.test.ts b/src/lib/actions/inference-set-local-provider.test.ts index e82d02b0272..01c45637f33 100644 --- a/src/lib/actions/inference-set-local-provider.test.ts +++ b/src/lib/actions/inference-set-local-provider.test.ts @@ -90,7 +90,7 @@ describe("runInferenceSet local-provider verification", () => { expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); - it("does not run local validation or force --no-verify for cloud providers", async () => { + it("does not run local validation or mutate the shared route for native cloud providers", async () => { const deps = createDeps({ config: localConfig(), session: baseSession(), @@ -100,7 +100,6 @@ describe("runInferenceSet local-provider verification", () => { expect(deps.calls.validateLocalProvider).not.toHaveBeenCalled(); expect(deps.calls.ensureLocalProviderReachable).not.toHaveBeenCalled(); - const args = deps.calls.captureOpenshell.mock.calls[0][0] as string[]; - expect(args).not.toContain("--no-verify"); + expect(deps.calls.captureOpenshell).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts index 27f7077ad45..24b5959eda9 100644 --- a/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts +++ b/src/lib/actions/inference-set-openclaw-gateway-restart.test.ts @@ -7,7 +7,7 @@ import { runInferenceSet } from "./inference-set"; import { defaultInferenceGatewayRestart } from "./inference-set-gateway-restart"; import { baseSession, createDeps } from "./inference-set.test-support"; -const nativeNvidiaReceipt = { +const nativeHostedReceipt = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, providerName: "nemoclaw-nvidia-prod-v1" as const, @@ -65,7 +65,8 @@ describe("runInferenceSet OpenClaw gateway restart", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/model-a", - nativeNvidiaProviderAttachment: nativeNvidiaReceipt, + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: nativeHostedReceipt, }, session: baseSession({ provider: "nvidia-prod", model: "nvidia/model-a" }), }); @@ -201,7 +202,7 @@ describe("runInferenceSet OpenClaw gateway restart", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod", @@ -224,7 +225,8 @@ describe("runInferenceSet OpenClaw gateway restart", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/model-a", - nativeNvidiaProviderAttachment: nativeNvidiaReceipt, + gatewayName: "nemoclaw", + nativeHostedProviderAttachment: nativeHostedReceipt, }, session: baseSession({ provider: "nvidia-prod", model: "nvidia/model-a" }), }); diff --git a/src/lib/actions/inference-set-openclaw-run.test.ts b/src/lib/actions/inference-set-openclaw-run.test.ts index 75d1db2a966..0bd47669184 100644 --- a/src/lib/actions/inference-set-openclaw-run.test.ts +++ b/src/lib/actions/inference-set-openclaw-run.test.ts @@ -1,14 +1,65 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { describe, expect, it, vi } from "vitest"; import type { OpenClawConfigUpdate } from "../sandbox/config"; import type { ConfigObject } from "../security/credential-filter"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import { runInferenceSet } from "./inference-set"; import { baseSession, createDeps } from "./inference-set.test-support"; describe("runInferenceSet OpenClaw routing", () => { + it("refuses publication after failed detach and permits a later clean switch", async () => { + const old = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "old-provider", + }; + const deps = createDeps({ + config: {}, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "old", + nativeHostedProviderAttachment: old, + }, + }); + const detach = vi.spyOn(deps.providerAdapter, "detachProvider"); + detach.mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "unknown", message: "detach failed", status: 1 }, + } as any); + await expect( + runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps), + ).rejects.toThrow("detach failed"); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + }), + ).toEqual({ ok: true, value: { names: [old.providerName] } }); + await runInferenceSet({ provider: "gemini-api", model: "gemini-test", noVerify: true }, deps); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + }), + ).toEqual({ + ok: true, + value: { names: ["nemoclaw-gemini-api-v1"] }, + }); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + provider: "gemini-api", + }), + ); + }); + it("requires recreation instead of silently migrating a legacy NVIDIA sandbox", async () => { const deps = createDeps({ config: {}, @@ -27,7 +78,7 @@ describe("runInferenceSet OpenClaw routing", () => { expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); }); - it("does not infer native NVIDIA provider authority from a peer sandbox", async () => { + it("rejects peer sandbox receipts without gateway NVIDIA authority", async () => { const peerAttachment = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, @@ -41,8 +92,8 @@ describe("runInferenceSet OpenClaw routing", () => { name: "alpha", agent: "openclaw", gatewayName: "nemoclaw", - provider: "openai-api", - model: "gpt-5.4", + provider: "", + model: "", }, { name: "beta", @@ -57,17 +108,40 @@ describe("runInferenceSet OpenClaw routing", () => { resolveCredentialValue: () => "", }); + vi.spyOn(deps.providerAdapter, "getProvider").mockResolvedValue({ + ok: true, + value: { + name: peerAttachment.providerName, + type: peerAttachment.profileId, + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { id: peerAttachment.providerId, resourceVersion: 1 }, + }, + }); + + let attachedToAlpha = false; + vi.spyOn(deps.providerAdapter, "attachProvider").mockImplementation(async () => { + attachedToAlpha = true; + return { ok: true }; + }); + vi.spyOn(deps.providerAdapter, "listProviderAttachments").mockImplementation(async () => ({ + ok: true, + value: { names: attachedToAlpha ? [peerAttachment.providerName] : [] }, + })); + await expect( runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps), ).rejects.toThrow(/without a matching NemoClaw ownership receipt/u); expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); - it("selects a native NVIDIA provider registered before any sandbox used it", async () => { + it.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "hermes-provider"), + )("selects a native $label provider registered before any sandbox used it", async (profile) => { const gatewayAuthority = { schemaVersion: 1 as const, - profileId: "nemoclaw-nvidia-inference-v1" as const, - providerName: "nemoclaw-nvidia-prod-v1" as const, + profileId: profile.profileId, + providerName: profile.providerName, providerId: "11111111-2222-4333-8444-555555555555", }; let attached = false; @@ -77,16 +151,16 @@ describe("runInferenceSet OpenClaw routing", () => { getProvider: vi.fn(async () => ({ ok: true as const, value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], configKeys: [], revision: { id: gatewayAuthority.providerId, resourceVersion: 1 }, }, })), listProviderAttachments: vi.fn(async () => ({ ok: true as const, - value: { names: attached ? ["nemoclaw-nvidia-prod-v1"] : [] }, + value: { names: attached ? [profile.providerName] : [] }, })), attachProvider: vi.fn(async () => { attached = true; @@ -99,29 +173,27 @@ describe("runInferenceSet OpenClaw routing", () => { name: "alpha", agent: "openclaw", gatewayName: "nemoclaw", - provider: "openai-api", - model: "gpt-5.4", + provider: "", + model: "", }, - getNativeNvidiaProviderAuthority: () => gatewayAuthority, + getNativeHostedProviderAuthority: () => gatewayAuthority, providerAdapter, resolveCredentialValue: () => "", }); await runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, + { provider: profile.logicalProvider, model: "selected-model", noVerify: true }, deps, ); + const recordAuthority = deps.calls.setNativeHostedProviderAuthority; + expect(recordAuthority).toHaveBeenCalledWith("nemoclaw", gatewayAuthority); expect(deps.calls.updateSandbox).toHaveBeenCalledWith( "alpha", expect.objectContaining({ - nativeNvidiaProviderAttachment: gatewayAuthority, + nativeHostedProviderAttachment: gatewayAuthority, }), ); - expect(deps.calls.setNativeNvidiaProviderAuthority).toHaveBeenCalledWith( - "nemoclaw", - gatewayAuthority, - ); }); it("does not record or attach a native NVIDIA provider replaced during credential rotation", async () => { @@ -170,10 +242,11 @@ describe("runInferenceSet OpenClaw routing", () => { name: "alpha", agent: "openclaw", gatewayName: "nemoclaw", - provider: "openai-api", - model: "gpt-5.4", + provider: "nvidia-prod", + model: "nvidia/previous-model", + nativeHostedProviderAttachment: gatewayAuthority, }, - getNativeNvidiaProviderAuthority: () => gatewayAuthority, + getNativeHostedProviderAuthority: () => gatewayAuthority, providerAdapter, resolveCredentialValue: () => "replacement-credential", }); @@ -184,53 +257,14 @@ describe("runInferenceSet OpenClaw routing", () => { /changed identity during its credential update.*No provider receipt was recorded/u, ); - expect(deps.calls.setNativeNvidiaProviderAuthority).not.toHaveBeenCalled(); + expect(providerAdapter.updateProvider).toHaveBeenCalledOnce(); + expect(getProvider).toHaveBeenCalledTimes(2); + expect(deps.calls.setNativeHostedProviderAuthority).not.toHaveBeenCalled(); expect(attachProvider).not.toHaveBeenCalled(); expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); it("creates a new native NVIDIA provider after reset removes retained authority", async () => { - const providerId = "22222222-3333-4444-8555-666666666666"; - let providerPresent = false; - let attached = false; - const createProvider = vi.fn(async () => { - providerPresent = true; - return { ok: true }; - }); - const providerAdapter = { - ensureProviderPolicyComposition: vi.fn(async () => ({ ok: true as const })), - importProviderProfile: vi.fn(async () => ({ ok: true as const })), - getProvider: vi.fn(async () => - providerPresent - ? { - ok: true as const, - value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { id: providerId, resourceVersion: 1 }, - }, - } - : { - ok: false as const, - error: { - kind: "command" as const, - reason: "not_found" as const, - message: "provider not found", - }, - }, - ), - createProvider, - listProviderAttachments: vi.fn(async () => ({ - ok: true as const, - value: { names: attached ? ["nemoclaw-nvidia-prod-v1"] : [] }, - })), - attachProvider: vi.fn(async () => { - attached = true; - return { ok: true as const }; - }), - } as unknown as OpenShellProviderAdapter; const deps = createDeps({ config: {}, entry: { @@ -239,16 +273,20 @@ describe("runInferenceSet OpenClaw routing", () => { gatewayName: "nemoclaw", provider: "openai-api", model: "gpt-5.4", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "openai-owned", + }, }, - providerAdapter, resolveCredentialValue: () => "replacement-credential", }); - + const createProvider = vi.spyOn(deps.providerAdapter, "createProvider"); await runInferenceSet( { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps, ); - expect(createProvider).toHaveBeenCalledExactlyOnceWith({ target: { kind: "named", gatewayName: "nemoclaw" }, name: "nemoclaw-nvidia-prod-v1", @@ -257,16 +295,16 @@ describe("runInferenceSet OpenClaw routing", () => { config: [], fromExisting: false, }); + const receipt = expect.objectContaining({ + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "id-nemoclaw-nvidia-prod-v1", + }); expect(deps.calls.updateSandbox).toHaveBeenCalledWith( "alpha", expect.objectContaining({ - nativeNvidiaProviderAttachment: expect.objectContaining({ providerId }), + nativeHostedProviderAttachment: receipt, }), ); - expect(deps.calls.setNativeNvidiaProviderAuthority).toHaveBeenCalledWith( - "nemoclaw", - expect.objectContaining({ providerId }), - ); }); it("removes a new native NVIDIA provider when authority persistence fails (#12562)", async () => { @@ -317,9 +355,15 @@ describe("runInferenceSet OpenClaw routing", () => { gatewayName: "nemoclaw", provider: "openai-api", model: "gpt-5.4", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "previous-openai-id", + }, }, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority: () => { + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority: () => { throw new Error("state directory is read-only"); }, providerAdapter, @@ -338,32 +382,7 @@ describe("runInferenceSet OpenClaw routing", () => { expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); }); - it("detaches native NVIDIA access only after another provider is healthy", async () => { - let attached = true; - const detachProvider = vi.fn(async () => { - attached = false; - return { ok: true, value: { changed: true } }; - }); - const providerAdapter = { - getProvider: vi.fn(async () => ({ - ok: true, - value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { - id: "11111111-2222-4333-8444-555555555555", - resourceVersion: 1, - }, - }, - })), - detachProvider, - listProviderAttachments: vi.fn(async () => ({ - ok: true, - value: { names: attached ? ["nemoclaw-nvidia-prod-v1"] : [] }, - })), - } as unknown as OpenShellProviderAdapter; + it("detaches previous native access before publishing another provider", async () => { const deps = createDeps({ config: { agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, @@ -374,16 +393,17 @@ describe("runInferenceSet OpenClaw routing", () => { agent: "openclaw", provider: "nvidia-prod", model: "nvidia/old-model", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", providerId: "11111111-2222-4333-8444-555555555555", }, }, - providerAdapter, }); + const detachProvider = vi.spyOn(deps.providerAdapter, "detachProvider"); + await runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps); expect(detachProvider).toHaveBeenCalledExactlyOnceWith( @@ -394,175 +414,102 @@ describe("runInferenceSet OpenClaw routing", () => { ); expect(deps.calls.restartSandboxGateway).toHaveBeenCalledOnce(); expect(detachProvider.mock.invocationCallOrder[0]).toBeLessThan( - deps.calls.restartSandboxGateway.mock.invocationCallOrder[0], - ); - const departureUpdate = deps.calls.updateSandbox.mock.calls.find( - ([name, updates]) => - name === "alpha" && - Object.prototype.hasOwnProperty.call(updates, "nativeNvidiaProviderAttachment"), - )?.[1]; - expect(departureUpdate).toEqual( - expect.objectContaining({ nativeNvidiaProviderAttachment: undefined }), - ); - expect(departureUpdate).not.toHaveProperty("nativeNvidiaProviderAuthority"); - }); - - it("retains gateway authority as the sole durable receipt across a round trip", async () => { - const attachment = { - schemaVersion: 1 as const, - profileId: "nemoclaw-nvidia-inference-v1" as const, - providerName: "nemoclaw-nvidia-prod-v1" as const, - providerId: "11111111-2222-4333-8444-555555555555", - }; - const entry = { - name: "alpha", - agent: "openclaw" as const, - gatewayName: "nemoclaw", - provider: "nvidia-prod", - model: "nvidia/old-model", - nativeNvidiaProviderAttachment: attachment, - }; - let gatewayAuthority = attachment; - const updateSandbox = vi.fn((name: string, updates: Record) => { - expect(name).toBe(entry.name); - Object.assign(entry, updates); - return true; - }); - const deps = createDeps({ - config: { - agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, - models: { providers: {} }, - }, - entry, - updateSandbox, - getNativeNvidiaProviderAuthority: () => gatewayAuthority, - setNativeNvidiaProviderAuthority: (_gatewayName, receipt) => { - gatewayAuthority = receipt; - }, - resolveCredentialValue: () => "", - }); - - await runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps); - - expect(entry).toMatchObject({ - provider: "openai-api", - }); - expect(entry.nativeNvidiaProviderAttachment).toBeUndefined(); - expect(entry).not.toHaveProperty("nativeNvidiaProviderAuthority"); - expect(gatewayAuthority).toEqual(attachment); - - await runInferenceSet( - { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, - deps, + deps.calls.updateSandbox.mock.invocationCallOrder[0], ); - - expect(entry).toMatchObject({ - provider: "nvidia-prod", - nativeNvidiaProviderAttachment: attachment, - }); - expect(entry).not.toHaveProperty("nativeNvidiaProviderAuthority"); - expect(gatewayAuthority).toEqual(attachment); - }); - - it("rejects a replaced NVIDIA provider before restoring detached access", async () => { - const attachProvider = vi.fn(); - const providerAdapter = { - importProviderProfile: vi.fn(async () => ({ ok: true })), - getProvider: vi.fn(async () => ({ - ok: true, - value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { - id: "replacement-provider-id", - resourceVersion: 1, - }, - }, - })), - attachProvider, - } as unknown as OpenShellProviderAdapter; - const deps = createDeps({ - config: { - agents: { defaults: { model: { primary: "inference/gpt-5.4" } } }, - models: { providers: {} }, - }, - entry: { - name: "alpha", - agent: "openclaw", - gatewayName: "nemoclaw", - provider: "openai-api", - model: "gpt-5.4", - }, - getNativeNvidiaProviderAuthority: () => ({ - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "recorded-provider-id", + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + nativeHostedProviderAttachment: expect.objectContaining({ + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + }), }), - providerAdapter, - resolveCredentialValue: () => "", - }); - - await expect( - runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps), - ).rejects.toThrow(/changed identity.*No provider was changed/u); - expect(attachProvider).not.toHaveBeenCalled(); - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + ); + expect( + deps.calls.updateSandbox.mock.calls.some( + ([, patch]) => + Object.hasOwn(patch, "nativeHostedProviderAttachment") && + patch.nativeHostedProviderAttachment === undefined, + ), + ).toBe(false); + expect( + deps.calls.captureOpenshell.mock.calls.some( + ([args]) => args[0] === "inference" && args[1] === "set", + ), + ).toBe(false); }); - it("does not publish a non-native route when native NVIDIA detach fails", async () => { - const providerAdapter = { - getProvider: vi.fn(async () => ({ - ok: true, - value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], - configKeys: [], - revision: { - id: "11111111-2222-4333-8444-555555555555", - resourceVersion: 1, - }, - }, - })), - detachProvider: vi.fn(async () => ({ - ok: false, - error: { kind: "command", reason: "failed", message: "detach denied" }, - })), - } as unknown as OpenShellProviderAdapter; - const config: ConfigObject = { - agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, - models: { providers: {} }, - }; - const deps = createDeps({ - config, - entry: { - name: "alpha", - agent: "openclaw", - provider: "nvidia-prod", - model: "nvidia/old-model", - nativeNvidiaProviderAttachment: { - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "11111111-2222-4333-8444-555555555555", - }, - }, - providerAdapter, - }); - - await expect( - runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps), - ).rejects.toThrow("Could not detach native NVIDIA provider from sandbox 'alpha'"); - - expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); - expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); - expect(deps.calls.restartSandboxGateway).not.toHaveBeenCalled(); - expect(config.agents).toEqual({ - defaults: { model: { primary: "inference/nvidia/old-model" } }, + it.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "hermes-provider"), + )("changes only the selected sandbox's native $label attachment (#12589)", async (profile) => { + const original = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.logicalProvider === "nvidia-prod", + )!; + const receipt = { + schemaVersion: 1 as const, + profileId: original.profileId, + providerName: original.providerName, + providerId: "original-provider", + }; + const deps = createDeps({ + config: {}, + entries: [ + { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "old", + nativeHostedProviderAttachment: receipt, + }, + { + name: "beta", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "peer-model", + nativeHostedProviderAttachment: receipt, + }, + ], }); + await runInferenceSet( + { + sandboxName: "alpha", + provider: profile.logicalProvider, + model: "new-model", + noVerify: true, + }, + deps, + ); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "alpha", + }), + ).toEqual({ ok: true, value: { names: [profile.providerName] } }); + expect( + await deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "beta", + }), + ).toEqual({ ok: true, value: { names: [original.providerName] } }); + expect(deps.calls.updateSandbox.mock.calls.every(([name]) => name === "alpha")).toBe(true); + expect(deps.calls.updateSandbox).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ + endpointUrl: profile.endpoint, + credentialEnv: profile.credentialEnv, + preferredInferenceApi: + profile.logicalProvider === "anthropic-prod" + ? "anthropic-messages" + : "openai-completions", + }), + ); + expect( + deps.calls.captureOpenshell.mock.calls.some( + ([args]) => args[0] === "inference" && args[1] === "set", + ), + ).toBe(false); }); it.each([ @@ -621,7 +568,7 @@ describe("runInferenceSet OpenClaw routing", () => { expect(providerUpdate?.value).toEqual({ api: "openai-completions", baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod" }, models: alreadyExists ? [otherModel, selectedModel] : [selectedModel, otherModel], }); @@ -771,11 +718,11 @@ describe("runInferenceSet OpenClaw routing", () => { expect.objectContaining({ provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - endpointUrl: null, - credentialEnv: null, + endpointUrl: "https://integrate.api.nvidia.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", nimContainer: null, - preferredInferenceApi: null, - nativeNvidiaProviderAttachment: expect.objectContaining({ + preferredInferenceApi: "openai-completions", + nativeHostedProviderAttachment: expect.objectContaining({ providerName: "nemoclaw-nvidia-prod-v1", }), }), @@ -968,4 +915,227 @@ describe("runInferenceSet OpenClaw routing", () => { }, }); }); + it("verifies retained NVIDIA authority across a single-sandbox round trip", async () => { + const attachment = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1" as const, + providerName: "nemoclaw-nvidia-prod-v1" as const, + providerId: "11111111-2222-4333-8444-555555555555", + }; + const entry = { + name: "alpha", + agent: "openclaw" as const, + gatewayName: "nemoclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeNvidiaProviderAttachment: attachment, + nativeHostedProviderAttachment: attachment, + }; + const updateSandbox = vi.fn((name: string, updates: Record) => { + expect(name).toBe(entry.name); + Object.assign(entry, updates); + return true; + }); + const deps = createDeps({ + config: { + agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, + models: { providers: {} }, + }, + entry, + updateSandbox, + getNativeHostedProviderAuthority: () => attachment, + resolveCredentialValue: (key) => (key === "OPENAI_API_KEY" ? "synthetic-openai-key" : ""), + }); + + await runInferenceSet({ provider: "openai-api", model: "gpt-5.4", noVerify: true }, deps); + + expect(entry).toMatchObject({ + provider: "openai-api", + }); + expect(entry.nativeNvidiaProviderAttachment).toBeUndefined(); + expect(entry.nativeHostedProviderAttachment).toMatchObject({ + profileId: "nemoclaw-openai-inference-v1", + }); + + await runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, + deps, + ); + + expect(entry).toMatchObject({ + provider: "nvidia-prod", + nativeHostedProviderAttachment: attachment, + }); + }); + + it("rejects a replaced NVIDIA provider before restoring detached access", async () => { + const attachProvider = vi.fn(); + const providerAdapter = { + importProviderProfile: vi.fn(async () => ({ ok: true })), + getProvider: vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { + id: "replacement-provider-id", + resourceVersion: 1, + }, + }, + })), + attachProvider, + } as unknown as OpenShellProviderAdapter; + const deps = createDeps({ + config: { + agents: { defaults: { model: { primary: "inference/gpt-5.4" } } }, + models: { providers: {} }, + }, + entry: { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "ollama-local", + model: "gpt-5.4", + }, + getNativeHostedProviderAuthority: () => ({ + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "recorded-provider-id", + }), + providerAdapter, + resolveCredentialValue: () => "", + }); + + await expect( + runInferenceSet({ provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, deps), + ).rejects.toThrow(/changed identity.*No provider was changed/u); + expect(attachProvider).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + }); + + it("does not publish a non-native route when native NVIDIA detach fails", async () => { + const providerAdapter = { + getProvider: vi.fn(async () => ({ + ok: true, + value: { + name: "nemoclaw-nvidia-prod-v1", + type: "nemoclaw-nvidia-inference-v1", + credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + configKeys: [], + revision: { + id: "11111111-2222-4333-8444-555555555555", + resourceVersion: 1, + }, + }, + })), + detachProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "failed", message: "detach denied" }, + })), + } as unknown as OpenShellProviderAdapter; + const config: ConfigObject = { + agents: { defaults: { model: { primary: "inference/nvidia/old-model" } } }, + models: { providers: {} }, + }; + const deps = createDeps({ + config, + entry: { + name: "alpha", + agent: "openclaw", + provider: "nvidia-prod", + model: "nvidia/old-model", + nativeNvidiaProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }, + providerAdapter, + }); + + await expect( + runInferenceSet({ provider: "ollama-local", model: "model-a", noVerify: true }, deps), + ).rejects.toThrow("Could not detach native NVIDIA provider from sandbox 'alpha'"); + + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); + expect(deps.calls.restartSandboxGateway).not.toHaveBeenCalled(); + expect(config.agents).toEqual({ + defaults: { model: { primary: "inference/nvidia/old-model" } }, + }); + }); + + it.each([ + ["adding", false], + ["updating", true], + ] as const)( + "preserves other native models when %s the requested model", + async (_operation, alreadyExists) => { + const otherModel = { + id: "nvidia/other-model", + name: "Native custom model", + contextWindow: 65536, + compat: { supportsStore: false }, + params: { temperature: 0.3 }, + }; + const requestedModel = { + id: "nvidia/new-model", + name: "Native selected model", + maxTokens: 8192, + }; + const config: ConfigObject = { + agents: { defaults: { model: { primary: "inference/nvidia/other-model" } } }, + models: { + providers: { + inference: { + api: "openai-completions", + models: alreadyExists ? [otherModel, requestedModel] : [otherModel], + }, + }, + }, + }; + const deps = createDeps({ config, session: baseSession() }); + + await runInferenceSet( + { provider: "nvidia-prod", model: "nvidia/new-model", noVerify: true }, + deps, + ); + + const updates: OpenClawConfigUpdate[] | undefined = + deps.calls.setOpenClawConfigValues.mock.calls[0]?.[1]; + const providerUpdate = updates?.find( + (update) => update.dotpath === "models.providers.inference", + ); + const selectedModel = alreadyExists + ? { + ...requestedModel, + name: "inference/nvidia/new-model", + compat: { supportsStore: false }, + } + : { + id: "nvidia/new-model", + name: "inference/nvidia/new-model", + params: { temperature: 0.3 }, + compat: { supportsStore: false }, + }; + expect(providerUpdate?.value).toEqual({ + api: "openai-completions", + baseUrl: "https://integrate.api.nvidia.com/v1", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", + headers: { "X-NemoClaw-Upstream-Provider": "nvidia-prod" }, + models: alreadyExists ? [otherModel, selectedModel] : [selectedModel, otherModel], + }); + expect(otherModel).toEqual({ + id: "nvidia/other-model", + name: "Native custom model", + contextWindow: 65536, + compat: { supportsStore: false }, + params: { temperature: 0.3 }, + }); + }, + ); }); diff --git a/src/lib/actions/inference-set-openrouter.test.ts b/src/lib/actions/inference-set-openrouter.test.ts index ee060c57bd7..853f3b05b51 100644 --- a/src/lib/actions/inference-set-openrouter.test.ts +++ b/src/lib/actions/inference-set-openrouter.test.ts @@ -14,7 +14,10 @@ import { const ULTRA = "nvidia/nemotron-3-ultra-550b-a55b"; const SUPER = "nvidia/nemotron-3-super-120b-a12b"; -function openRouterDeps(probeSandboxRoute?: Parameters[0]["probeSandboxRoute"]) { +function openRouterDeps( + probeSandboxRoute?: Parameters[0]["probeSandboxRoute"], + native = true, +) { return createDeps({ probeSandboxRoute, config: { @@ -28,6 +31,16 @@ function openRouterDeps(probeSandboxRoute?: Parameters[0]["pr gatewayPort: 18085, provider: OPENROUTER_PROVIDER_NAME, model: ULTRA, + ...(native + ? { + nativeHostedProviderAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "openrouter-provider-id", + }, + } + : {}), }, session: baseSession({ provider: OPENROUTER_PROVIDER_NAME, @@ -48,6 +61,7 @@ function expectNoConfigCommit(deps: ReturnType) { expect(deps.calls.setOpenClawConfigValues).not.toHaveBeenCalled(); expect(deps.calls.updateSession).not.toHaveBeenCalled(); expect(deps.calls.restartSandboxGateway).not.toHaveBeenCalled(); + expect(deps.getSandbox("alpha")?.model).toBe(ULTRA); } describe("OpenRouter model switch verification", () => { @@ -72,11 +86,14 @@ describe("OpenRouter model switch verification", () => { expect(execute).toHaveBeenCalledOnce(); expect(execute).toHaveBeenCalledWith( "alpha", - expect.stringContaining("https://inference.local/v1/chat/completions"), + expect.stringContaining("https://openrouter.ai/api/v1/chat/completions"), READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, { gatewayName: "nemoclaw-18085" }, ); expect(execute.mock.calls[0]?.[1]).toContain(`"model":"${SUPER}"`); + expect(execute.mock.calls[0]?.[1]).toContain("HTTP-Referer:"); + expect(execute.mock.calls[0]?.[1]).toContain("X-OpenRouter-Title:"); + expect(routeSelections(deps)).toEqual([]); expect(execute.mock.invocationCallOrder[0]).toBeLessThan( deps.calls.updateSandbox.mock.invocationCallOrder[0], ); @@ -102,7 +119,7 @@ describe("OpenRouter model switch verification", () => { error: "invalid response body", }, ])( - "restores Ultra when the real sandbox probe receives $label (#12628)", + "preserves Ultra when the real sandbox probe receives $label (#12628)", async ({ status, stdout, error }) => { const execute = vi.fn>(async () => ({ status, @@ -127,7 +144,8 @@ describe("OpenRouter model switch verification", () => { READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, { gatewayName: "nemoclaw-18085" }, ); - expect(routeSelections(deps).map((args) => args.at(-1))).toEqual([SUPER, ULTRA]); + expect(routeSelections(deps)).toEqual([]); + expect(deps.getSandbox("alpha")?.model).toBe(ULTRA); expectNoConfigCommit(deps); }, ); @@ -143,25 +161,14 @@ describe("OpenRouter model switch verification", () => { const result = await runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model }, deps); expect(result.model).toBe(model); - expect(routeSelections(deps)).toEqual([ - [ - "inference", - "set", - "-g", - "nemoclaw-18085", - "--no-verify", - "--provider", - OPENROUTER_PROVIDER_NAME, - "--model", - model, - ], - ]); + expect(routeSelections(deps)).toEqual([]); expect(deps.calls.probeSandboxRoute).toHaveBeenCalledWith({ gatewayName: "nemoclaw-18085", sandboxName: "alpha", provider: OPENROUTER_PROVIDER_NAME, model, preferredInferenceApi: "openai-completions", + nativeProvider: true, }); expect(deps.calls.probeSandboxRoute.mock.invocationCallOrder[0]).toBeLessThan( deps.calls.updateSandbox.mock.invocationCallOrder[0], @@ -175,7 +182,7 @@ describe("OpenRouter model switch verification", () => { ); it.each([401, 502])( - "restores Ultra when sandbox verification returns HTTP %s (#12628)", + "preserves Ultra when sandbox verification returns HTTP %s (#12628)", async (httpStatus) => { const deps = openRouterDeps(); deps.calls.probeSandboxRoute.mockResolvedValue({ @@ -187,16 +194,17 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), ).rejects.toThrow( - /Sandbox-side verification rejected.*previous OpenShell inference selection was restored/s, + /Sandbox-side verification rejected.*shared OpenShell inference selection was not changed/s, ); - expect(routeSelections(deps).map((args) => args.at(-1))).toEqual([SUPER, ULTRA]); + expect(routeSelections(deps)).toEqual([]); + expect(deps.getSandbox("alpha")?.model).toBe(ULTRA); expect(deps.calls.probeSandboxRoute).toHaveBeenCalledOnce(); expectNoConfigCommit(deps); }, ); - it("restores Ultra after sandbox transport retries fail (#12628)", async () => { + it("preserves Ultra after sandbox transport retries fail (#12628)", async () => { const deps = openRouterDeps(); deps.calls.probeSandboxRoute.mockResolvedValue({ ok: false, @@ -206,47 +214,40 @@ describe("OpenRouter model switch verification", () => { await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), - ).rejects.toThrow(/previous OpenShell inference selection was restored/); + ).rejects.toThrow(/shared OpenShell inference selection was not changed/); expect(deps.calls.probeSandboxRoute).toHaveBeenCalledTimes(3); - expect(routeSelections(deps).map((args) => args.at(-1))).toEqual([SUPER, ULTRA]); + expect(routeSelections(deps)).toEqual([]); + expect(deps.getSandbox("alpha")?.model).toBe(ULTRA); expectNoConfigCommit(deps); }); - it("restores Ultra when the sandbox probe throws (#12628)", async () => { + it("preserves Ultra when the sandbox probe throws (#12628)", async () => { const deps = openRouterDeps(); deps.calls.probeSandboxRoute.mockRejectedValue(new Error("sandbox dial failed")); await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), - ).rejects.toThrow(/sandbox dial failed.*previous OpenShell inference selection was restored/s); + ).rejects.toThrow(/sandbox dial failed.*shared OpenShell inference selection was not changed/s); - expect(routeSelections(deps).map((args) => args.at(-1))).toEqual([SUPER, ULTRA]); + expect(routeSelections(deps)).toEqual([]); + expect(deps.getSandbox("alpha")?.model).toBe(ULTRA); expectNoConfigCommit(deps); }); - it("reports a failed restore without committing agent configuration (#12628)", async () => { - const deps = openRouterDeps(); - deps.calls.probeSandboxRoute.mockResolvedValue({ - ok: false, - httpStatus: 401, - detail: "HTTP 401", - }); - const setInferenceRoute = vi - .fn() - .mockResolvedValueOnce({ ok: true }) - .mockResolvedValueOnce({ - ok: false, - ambiguous: false, - error: { kind: "command", exitCode: 1, message: "restore failed" }, - }); - deps.inferenceRouteMutator = { setInferenceRoute }; + it("refuses legacy OpenRouter selection without a native attachment receipt before mutation", async () => { + const deps = openRouterDeps(undefined, false); + const updateProvider = vi.spyOn(deps.providerAdapter, "updateProvider"); + const attachProvider = vi.spyOn(deps.providerAdapter, "attachProvider"); await expect( runInferenceSet({ provider: OPENROUTER_PROVIDER_NAME, model: SUPER }, deps), - ).rejects.toThrow(/Failed to restore the previous OpenShell inference selection/); + ).rejects.toThrow(/predates native hosted provider attachments/); - expect(setInferenceRoute).toHaveBeenCalledTimes(2); + expect(routeSelections(deps)).toEqual([]); + expect(updateProvider).not.toHaveBeenCalled(); + expect(attachProvider).not.toHaveBeenCalled(); + expect(deps.calls.probeSandboxRoute).not.toHaveBeenCalled(); expectNoConfigCommit(deps); }); }); diff --git a/src/lib/actions/inference-set-patch-hermes.test.ts b/src/lib/actions/inference-set-patch-hermes.test.ts index 61b47018703..15e0e1232c7 100644 --- a/src/lib/actions/inference-set-patch-hermes.test.ts +++ b/src/lib/actions/inference-set-patch-hermes.test.ts @@ -1,12 +1,48 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import { describe, expect, it } from "vitest"; import { HERMES_PROXY_REWRITE_SENTINEL } from "../hermes-managed-route"; import type { ConfigObject } from "../security/credential-filter"; import { patchHermesInferenceConfig } from "./inference-set"; describe("patchHermesInferenceConfig", () => { + it.each(NATIVE_HOSTED_PROFILES)( + "updates all credential leaves for $label and restores legacy mode", + (profile) => { + const config: ConfigObject = {}; + patchHermesInferenceConfig(config, profile.logicalProvider, "selected"); + const reference = `\${${profile.credentialEnv}}`; + expect((config.model as ConfigObject).api_key).toBe(reference); + expect( + Object.values(config.providers as ConfigObject).map( + (value) => (value as ConfigObject).api_key, + ), + ).toEqual([reference]); + expect((config.custom_providers as ConfigObject[]).map((value) => value.api_key)).toEqual([ + reference, + ]); + patchHermesInferenceConfig(config, "compatible-endpoint", "selected", "openai-completions"); + expect((config.model as ConfigObject).api_key).toBe(HERMES_PROXY_REWRITE_SENTINEL); + expect(JSON.stringify(config)).not.toContain(reference); + }, + ); + + it("keeps OpenRouter attribution in both Hermes provider representations", () => { + const config: ConfigObject = {}; + patchHermesInferenceConfig(config, "openrouter-api", "selected"); + const headers = { + "HTTP-Referer": "https://www.nvidia.com/nemoclaw/", + "X-OpenRouter-Title": "NVIDIA NemoClaw", + }; + expect(config.providers).toMatchObject({ "openrouter-api": { extra_headers: headers } }); + expect(config.custom_providers).toEqual([expect.objectContaining({ extra_headers: headers })]); + patchHermesInferenceConfig(config, "gemini-api", "selected"); + expect(JSON.stringify(config)).not.toContain("HTTP-Referer"); + expect(JSON.stringify(config)).not.toContain("X-OpenRouter-Title"); + }); + it("updates the complete Hermes route for the selected provider", () => { const config: ConfigObject = { model: { @@ -32,8 +68,8 @@ describe("patchHermesInferenceConfig", () => { expect(config.model).toEqual({ default: "openai/gpt-5.4-mini", provider: "custom", - base_url: "https://inference.local/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + base_url: "https://inference-api.nousresearch.com/v1", + api_key: "${OPENAI_API_KEY}", }); expect(config._nemoclaw_upstream).toEqual({ provider: "hermes-provider", @@ -43,8 +79,8 @@ describe("patchHermesInferenceConfig", () => { expect(config.providers).toEqual({ "hermes-provider": { name: "hermes-provider", - api: "https://inference.local/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api: "https://inference-api.nousresearch.com/v1", + api_key: "${OPENAI_API_KEY}", default_model: "openai/gpt-5.4-mini", discover_models: true, }, @@ -52,8 +88,8 @@ describe("patchHermesInferenceConfig", () => { expect(config.custom_providers).toEqual([ { name: "hermes-provider", - base_url: "https://inference.local/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + base_url: "https://inference-api.nousresearch.com/v1", + api_key: "${OPENAI_API_KEY}", discover_models: true, }, ]); @@ -88,7 +124,7 @@ describe("patchHermesInferenceConfig", () => { }); it.each(["no-key-required", "sk-real-looking-key-that-must-not-survive"])( - "replaces stale Hermes API keys with the OpenShell proxy rewrite sentinel [case %#]", + "replaces stale Hermes API keys with the issued credential environment reference [case %#]", (api_key) => { const config: ConfigObject = { model: { @@ -101,7 +137,7 @@ describe("patchHermesInferenceConfig", () => { patchHermesInferenceConfig(config, "hermes-provider", "openai/gpt-5.4-mini"); - expect((config.model as ConfigObject).api_key).toBe(HERMES_PROXY_REWRITE_SENTINEL); + expect((config.model as ConfigObject).api_key).toBe("${OPENAI_API_KEY}"); }, ); @@ -110,7 +146,7 @@ describe("patchHermesInferenceConfig", () => { model: { default: "openai/gpt-5.4-mini", provider: "custom", - base_url: "https://inference.local/v1", + base_url: "https://api.anthropic.com/v1", }, }; @@ -119,14 +155,14 @@ describe("patchHermesInferenceConfig", () => { expect(result.route).toMatchObject({ providerKey: "anthropic", primaryModelRef: "anthropic/claude-sonnet-4-6", - inferenceBaseUrl: "https://inference.local", + inferenceBaseUrl: "https://api.anthropic.com", inferenceApi: "anthropic-messages", }); expect(config.model).toEqual({ default: "claude-sonnet-4-6", provider: "custom", - base_url: "https://inference.local", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + base_url: "https://api.anthropic.com", + api_key: "${ANTHROPIC_API_KEY}", api_mode: "anthropic_messages", }); }); @@ -147,7 +183,7 @@ describe("patchHermesInferenceConfig", () => { default: "nvidia/nemotron-3-super-120b-a12b", provider: "custom", base_url: "https://integrate.api.nvidia.com/v1", - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: "${NVIDIA_INFERENCE_API_KEY}", }); }); diff --git a/src/lib/actions/inference-set-patch-openclaw.test.ts b/src/lib/actions/inference-set-patch-openclaw.test.ts index 780684464e8..e5ebbb40c5e 100644 --- a/src/lib/actions/inference-set-patch-openclaw.test.ts +++ b/src/lib/actions/inference-set-patch-openclaw.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import { describe, expect, it } from "vitest"; import type { ConfigObject } from "../security/credential-filter"; import { patchOpenClawInferenceConfig } from "./inference-set"; @@ -13,6 +14,39 @@ function providerModels(config: ConfigObject, providerKey: string): ConfigObject } describe("patchOpenClawInferenceConfig", () => { + it.each(NATIVE_HOSTED_PROFILES)( + "uses $label workload references and clears them on switch", + (profile) => { + const config: ConfigObject = { + models: { providers: { inference: { apiKey: "stale-sentinel" } } }, + }; + const first = patchOpenClawInferenceConfig(config, profile.logicalProvider, "selected"); + const providers = (config.models as ConfigObject).providers as ConfigObject; + expect((providers[first.route.providerKey] as ConfigObject).apiKey).toBe( + `\${${profile.credentialEnv}}`, + ); + patchOpenClawInferenceConfig(config, "compatible-endpoint", "selected", "openai-completions"); + expect(Object.values(providers).map((value) => (value as ConfigObject).apiKey)).not.toContain( + `\${${profile.credentialEnv}}`, + ); + }, + ); + + it("adds OpenRouter attribution and removes only owned headers when switching away", () => { + const config: ConfigObject = { + models: { providers: { inference: { headers: { "X-Operator": "keep" } } } }, + }; + patchOpenClawInferenceConfig(config, "openrouter-api", "selected"); + const providers = (config.models as ConfigObject).providers as ConfigObject; + expect((providers.inference as ConfigObject).headers).toEqual({ + "X-Operator": "keep", + "HTTP-Referer": "https://www.nvidia.com/nemoclaw/", + "X-OpenRouter-Title": "NVIDIA NemoClaw", + }); + patchOpenClawInferenceConfig(config, "gemini-api", "selected"); + expect((providers.inference as ConfigObject).headers).toEqual({ "X-Operator": "keep" }); + }); + it.each([undefined, null, 16384])( "updates only the selected model's context when the resolved window is %s", (contextWindow) => { @@ -82,7 +116,7 @@ describe("patchOpenClawInferenceConfig", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", models: [ { @@ -152,7 +186,7 @@ describe("patchOpenClawInferenceConfig", () => { expect((config.models as ConfigObject).providers).toEqual({ inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", models: [ { @@ -208,7 +242,7 @@ describe("patchOpenClawInferenceConfig", () => { providers: { inference: { baseUrl: "https://integrate.api.nvidia.com/v1", - apiKey: "unused", + apiKey: "${NVIDIA_INFERENCE_API_KEY}", api: "openai-completions", models: [ { @@ -309,8 +343,8 @@ describe("patchOpenClawInferenceConfig", () => { mode: "merge", providers: { anthropic: { - baseUrl: "https://inference.local", - apiKey: "unused", + baseUrl: "https://api.anthropic.com", + apiKey: "${ANTHROPIC_API_KEY}", api: "anthropic-messages", models: [ { diff --git a/src/lib/actions/inference-set-route-containment.ts b/src/lib/actions/inference-set-route-containment.ts index 3319c39c9ed..8a40c2bc219 100644 --- a/src/lib/actions/inference-set-route-containment.ts +++ b/src/lib/actions/inference-set-route-containment.ts @@ -25,6 +25,7 @@ import { ConfigUrlValidationError } from "../sandbox/config"; import type { ConfigValue } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; import type { SandboxEntry } from "../state/registry"; +import { resolveNativeInferenceRegistryMetadata } from "./inference-route-api"; import { InferenceSetError } from "./inference-set-error"; /** @@ -381,6 +382,13 @@ function registryMetadataForProviderSwitch(options: { }): RegistryInferenceMetadata { const { entry, provider, model, sandboxName, session, explicitMetadata } = options; if (explicitMetadata) return explicitMetadata; + const nativeMetadata = resolveNativeInferenceRegistryMetadata({ + provider, + model, + previousProvider: entry.provider, + previousApi: entry.preferredInferenceApi, + }); + if (nativeMetadata) return nativeMetadata; if (entry.provider === provider) { return { endpointUrl: entry.endpointUrl ?? null, diff --git a/src/lib/actions/inference-set.test-support.ts b/src/lib/actions/inference-set.test-support.ts index c93d815c813..c1f0acaa899 100644 --- a/src/lib/actions/inference-set.test-support.ts +++ b/src/lib/actions/inference-set.test-support.ts @@ -10,11 +10,7 @@ import type { import { createCliOpenShellInferenceRouteMutator } from "../adapters/openshell/inference-route-cli"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; -import { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../inference/native-nvidia"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import type { AgentConfigTarget } from "../sandbox/config"; import type { ConfigObject, ConfigValue } from "../security/credential-filter"; import type { Session } from "../state/onboard-session"; @@ -74,78 +70,87 @@ function nativeAwareProviderAdapter( base: OpenShellProviderAdapter, entries: SandboxEntry[], ): OpenShellProviderAdapter { - const recordedEntry = entries.find( - (entry) => entry.nativeNvidiaProviderAttachment?.providerName === NVIDIA_HOSTED_NATIVE_PROVIDER, - ); - const providerId = - recordedEntry?.nativeNvidiaProviderAttachment?.providerId ?? - "11111111-2222-4333-8444-555555555555"; - let providerPresent = recordedEntry !== undefined; - const attachments = new Set( - entries - .filter( - (entry) => - entry.nativeNvidiaProviderAttachment?.providerName === NVIDIA_HOSTED_NATIVE_PROVIDER, - ) - .map((entry) => entry.name), + const states = new Map( + NATIVE_HOSTED_PROFILES.map((profile) => { + const entriesForProvider = entries.filter( + (entry) => entry.nativeHostedProviderAttachment?.providerName === profile.providerName, + ); + return [ + profile.providerName, + { + profile, + providerId: + entriesForProvider[0]?.nativeHostedProviderAttachment?.providerId ?? + `id-${profile.providerName}`, + present: entriesForProvider.length > 0, + attachments: new Set(entriesForProvider.map((entry) => entry.name)), + }, + ]; + }), ); - const isNative = (providerName: string): boolean => - providerName === NVIDIA_HOSTED_NATIVE_PROVIDER; return { ...base, ensureProviderPolicyComposition: async () => ({ ok: true, value: undefined }), importProviderProfile: async (request) => - request.profilePath.endsWith(`${NVIDIA_HOSTED_NATIVE_PROFILE_ID}.yaml`) + NATIVE_HOSTED_PROFILES.some((profile) => + request.profilePath.endsWith(`${profile.profileId}.yaml`), + ) ? ({ ok: true } as const) : await base.importProviderProfile(request), getProvider: async (request) => { - if (!isNative(request.providerName)) return await base.getProvider(request); - if (!providerPresent) { + const state = states.get(request.providerName); + if (!state) return await base.getProvider(request); + if (!state.present) return { ok: false, error: { kind: "command", reason: "not_found", message: "provider not found" }, } as const; - } return { ok: true, value: { - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentialKeys: [NVIDIA_HOSTED_CREDENTIAL_ENV], + name: state.profile.providerName, + type: state.profile.profileId, + credentialKeys: [state.profile.credentialEnv], configKeys: [], - revision: { id: providerId, resourceVersion: 1 }, + revision: { id: state.providerId, resourceVersion: 1 }, }, } as const; }, createProvider: async (request) => { - if (!isNative(request.name)) return await base.createProvider(request); - providerPresent = true; + const state = states.get(request.name); + if (!state) return await base.createProvider(request); + state.present = true; return { ok: true } as const; }, updateProvider: async (request) => { - if (!isNative(request.providerName)) return await base.updateProvider(request); - providerPresent = true; + const state = states.get(request.providerName); + if (!state) return await base.updateProvider(request); + state.present = true; return { ok: true } as const; }, attachProvider: async (request) => { - if (!isNative(request.providerName)) return await base.attachProvider(request); - attachments.add(request.sandboxName); + const state = states.get(request.providerName); + if (!state) return await base.attachProvider(request); + state.attachments.add(request.sandboxName); return { ok: true } as const; }, detachProvider: async (request) => { - if (!isNative(request.providerName)) return await base.detachProvider(request); - const changed = attachments.delete(request.sandboxName); - return { ok: true, value: { changed } } as const; - }, - listProviderAttachments: async (request) => { - if (!providerPresent) return await base.listProviderAttachments(request); + const state = states.get(request.providerName); + if (!state) return await base.detachProvider(request); return { ok: true, - value: { - names: attachments.has(request.sandboxName) ? [NVIDIA_HOSTED_NATIVE_PROVIDER] : [], - }, + value: { changed: state.attachments.delete(request.sandboxName) }, } as const; }, + listProviderAttachments: async (request) => + ({ + ok: true, + value: { + names: [...states.values()] + .filter((state) => state.present && state.attachments.has(request.sandboxName)) + .map((state) => state.profile.providerName), + }, + }) as const, }; } @@ -278,8 +283,8 @@ export function createDeps(options: { restartSandboxGateway?: InferenceSetDeps["restartSandboxGateway"]; settleOpenClawPairing?: InferenceSetDeps["settleOpenClawPairing"]; withGatewayRouteMutationLock?: InferenceSetDeps["withGatewayRouteMutationLock"]; - getNativeNvidiaProviderAuthority?: InferenceSetDeps["getNativeNvidiaProviderAuthority"]; - setNativeNvidiaProviderAuthority?: InferenceSetDeps["setNativeNvidiaProviderAuthority"]; + getNativeHostedProviderAuthority?: InferenceSetDeps["getNativeHostedProviderAuthority"]; + setNativeHostedProviderAuthority?: InferenceSetDeps["setNativeHostedProviderAuthority"]; }): InferenceSetDeps & { calls: { captureOpenshell: ReturnType; @@ -304,7 +309,7 @@ export function createDeps(options: { restartSandboxGateway: ReturnType; settleOpenClawPairing: ReturnType; withGatewayRouteMutationLock: ReturnType; - setNativeNvidiaProviderAuthority: ReturnType; + setNativeHostedProviderAuthority: ReturnType; }; getSession: () => Session | null; } { @@ -324,7 +329,17 @@ export function createDeps(options: { setOpenClawConfigValues: vi.fn(), writeSandboxConfig: vi.fn(), recomputeSandboxConfigHash: vi.fn(), - updateSandbox: vi.fn(options.updateSandbox ?? (() => true)), + updateSandbox: vi.fn( + options.updateSandbox ?? + ((name, patch) => { + const entry = sandboxes[name]; + if (!entry) return false; + sandboxes[name] = { ...entry, ...patch }; + const index = entries.findIndex((candidate) => candidate.name === name); + if (index >= 0) entries[index] = sandboxes[name]; + return true; + }), + ), readSandboxConfig: vi.fn(() => options.config), updateSession: vi.fn((mutator: (value: Session) => Session | void) => { const current = session ?? baseSession(); @@ -377,7 +392,7 @@ export function createDeps(options: { (async (_gatewayName: string, operation: () => Promise | unknown) => await operation()), ), - setNativeNvidiaProviderAuthority: vi.fn(), + setNativeHostedProviderAuthority: vi.fn(), }; const providerAdapter = options.providerAdapter ?? @@ -427,9 +442,9 @@ export function createDeps(options: { getDefaultSandbox: () => defaultSandbox, getSandbox: (name: string) => sandboxes[name] ?? null, listSandboxes: () => ({ sandboxes: entries, defaultSandbox }), - getNativeNvidiaProviderAuthority: options.getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority: - options.setNativeNvidiaProviderAuthority ?? calls.setNativeNvidiaProviderAuthority, + getNativeHostedProviderAuthority: options.getNativeHostedProviderAuthority, + setNativeHostedProviderAuthority: + options.setNativeHostedProviderAuthority ?? calls.setNativeHostedProviderAuthority, updateSandbox: calls.updateSandbox, getRequestedAgent: () => options.requestedAgent, loadSession: () => session, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 9d50e1fb6bc..9733f27b7b2 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -11,18 +11,20 @@ import { shellQuote } from "../core/shell-quote"; import { applyHermesManagedRoute } from "../hermes-managed-route"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; import { + nativeHostedProfile, + isNativeHostedCredentialReference, + OPENROUTER_DEFAULT_HEADERS, getProviderSelectionConfig, getSandboxInferenceConfig, - detachNativeNvidiaProvider, - ensureNativeNvidiaProvider, - ensureNativeNvidiaProviderAttached, - isNativeNvidiaProvider, - NVIDIA_HOSTED_CREDENTIAL_ENV, - normalizeNativeNvidiaProviderAttachment, - persistNativeNvidiaProviderAuthority, - resolveGatewayNativeNvidiaProviderAuthority, + detachNativeHostedProvider, + ensureNativeHostedProvider, + persistNativeHostedProviderAuthority, + ensureNativeHostedProviderAttached, + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, + resolveGatewayNativeHostedProviderAuthority, resolveAgentInferenceApi, - type NativeNvidiaProviderAttachment, + type NativeHostedProviderAttachment, type SandboxInferenceConfig, } from "../inference/config"; import { resolveContextWindowForModel } from "../inference/context-window"; @@ -179,8 +181,8 @@ export interface InferenceSetDeps extends InferenceGatewayRestartDeps { sandboxes: SandboxEntry[]; defaultSandbox: string | null; }; - getNativeNvidiaProviderAuthority?: typeof registry.getNativeNvidiaProviderAuthority; - setNativeNvidiaProviderAuthority: typeof registry.setNativeNvidiaProviderAuthority; + getNativeHostedProviderAuthority?: typeof registry.getNativeHostedProviderAuthority; + setNativeHostedProviderAuthority: typeof registry.setNativeHostedProviderAuthority; updateSandbox: (name: string, updates: Partial) => boolean; getRequestedAgent: () => string | null | undefined; loadSession: () => onboardSession.Session | null; @@ -313,8 +315,8 @@ function defaultDeps(): InferenceSetDeps { getDefaultSandbox: registry.getDefault, getSandbox: registry.getSandbox, listSandboxes: registry.listSandboxes, - getNativeNvidiaProviderAuthority: registry.getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority: registry.setNativeNvidiaProviderAuthority, + getNativeHostedProviderAuthority: registry.getNativeHostedProviderAuthority, + setNativeHostedProviderAuthority: registry.setNativeHostedProviderAuthority, updateSandbox: registry.updateSandbox, getRequestedAgent: () => process.env.NEMOCLAW_AGENT, loadSession: onboardSession.loadSession, @@ -690,13 +692,26 @@ function buildProviderConfig( const providerConfig: ConfigObject = { ...existing, baseUrl: route.inferenceBaseUrl, - apiKey: typeof existing.apiKey === "string" && existing.apiKey ? existing.apiKey : "unused", + apiKey: route.inferenceCredentialEnv + ? `\${${route.inferenceCredentialEnv}}` + : typeof existing.apiKey === "string" && + existing.apiKey && + !isNativeHostedCredentialReference(existing.apiKey) + ? existing.apiKey + : "unused", api: route.inferenceApi, models: selectedIndex < 0 ? [selectedModel, ...existingModels] : existingModels.map((entry, index) => (index === selectedIndex ? selectedModel : entry)), }; + const headers = cloneConfigObject(providerConfig.headers); + for (const [name, value] of OPENROUTER_DEFAULT_HEADERS) { + if (provider === "openrouter-api") headers[name] = value; + else if (headers[name] === value) delete headers[name]; + } + if (Object.keys(headers).length > 0) providerConfig.headers = headers; + else delete providerConfig.headers; return upstreamProviderMarker ? withOpenClawUpstreamProviderHeader(providerConfig, upstreamProviderMarker) : providerConfig; @@ -723,6 +738,15 @@ export function patchOpenClawInferenceConfig( const models = ensureObject(config, "models"); models.mode = "merge"; const providers = ensureObject(models, "providers"); + for (const [key, value] of Object.entries(providers)) { + if ( + isConfigObject(value) && + key !== route.providerKey && + isNativeHostedCredentialReference(value.apiKey) + ) { + value.apiKey = "unused"; + } + } const existingProvider = cloneConfigObject(providers[route.providerKey]); providers[route.providerKey] = buildProviderConfig( existingProvider, @@ -819,6 +843,7 @@ export function patchHermesInferenceConfig( applyHermesManagedRoute(config, { model, baseUrl: route.inferenceBaseUrl, + credentialEnv: route.inferenceCredentialEnv, upstreamProvider: provider, inferenceApi: route.inferenceApi, contextWindow, @@ -934,56 +959,63 @@ function assertReasoningEffortRoute( } } -function assertNativeNvidiaMigrationReady(input: { +function assertNativeHostedMigrationReady(input: { provider: string; previousProvider: string; - previousAttachment?: NativeNvidiaProviderAttachment; + previousAttachment?: NativeHostedProviderAttachment; sandboxName: string; }): void { if ( - isNativeNvidiaProvider(input.provider) && - isNativeNvidiaProvider(input.previousProvider) && + isNativeHostedProvider(input.provider) && + isNativeHostedProvider(input.previousProvider) && !input.previousAttachment ) { throw new InferenceSetError( - `Sandbox '${input.sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before changing its NVIDIA model.`, + `Sandbox '${input.sandboxName}' predates native hosted provider attachments. Recreate this beta sandbox before changing its hosted inference selection.`, 2, ); } } -async function prepareNativeNvidiaSelection(input: { +async function prepareNativeHostedSelection(input: { provider: string; - expectedAttachment?: NativeNvidiaProviderAttachment; + expectedAttachment?: NativeHostedProviderAttachment; + gatewayName: string; sandboxName: string; deps: InferenceSetDeps; }): Promise<{ - attachment?: NativeNvidiaProviderAttachment; + attachment?: NativeHostedProviderAttachment; attachmentChanged: boolean; }> { - if (!isNativeNvidiaProvider(input.provider)) return { attachmentChanged: false }; + if (!isNativeHostedProvider(input.provider)) return { attachmentChanged: false }; + const profile = nativeHostedProfile(input.provider)!; const target = { kind: "named", gatewayName: input.gatewayName } as const; - const ensured = await ensureNativeNvidiaProvider({ + const ensured = await ensureNativeHostedProvider({ adapter: input.deps.providerAdapter, target, - credentialValue: input.deps.resolveCredentialValue(NVIDIA_HOSTED_CREDENTIAL_ENV) || null, - ...(input.expectedAttachment ? { expected: input.expectedAttachment } : {}), + profile, + credentialValue: + input.deps.resolveCredentialValue(profile.hostCredentialEnv ?? profile.credentialEnv) || null, + ...(input.expectedAttachment?.profileId === profile.profileId + ? { expected: input.expectedAttachment } + : {}), }); - if (input.deps.getNativeNvidiaProviderAuthority) { - await persistNativeNvidiaProviderAuthority({ - adapter: input.deps.providerAdapter, - target, - gatewayName: input.gatewayName, - receipt: ensured, - ...(input.expectedAttachment ? { existing: input.expectedAttachment } : {}), - readAuthority: input.deps.getNativeNvidiaProviderAuthority, - writeAuthority: input.deps.setNativeNvidiaProviderAuthority, - }); - } else { - input.deps.setNativeNvidiaProviderAuthority(input.gatewayName, ensured); - } - const attached = await ensureNativeNvidiaProviderAttached({ + await persistNativeHostedProviderAuthority({ + adapter: input.deps.providerAdapter, + target, + profile, + gatewayName: input.gatewayName, + receipt: ensured, + ...(input.expectedAttachment?.profileId === profile.profileId + ? { existing: input.expectedAttachment } + : {}), + readAuthority: (gatewayName) => + readRegisteredNativeAuthority(input.deps, gatewayName, input.provider), + writeAuthority: (gatewayName, receipt) => + recordNativeProviderAuthority(input.deps, gatewayName, receipt), + }); + const attached = await ensureNativeHostedProviderAttached({ adapter: input.deps.providerAdapter, target, sandboxName: input.sandboxName, @@ -992,10 +1024,10 @@ async function prepareNativeNvidiaSelection(input: { return { attachment: attached.receipt, attachmentChanged: attached.changed }; } -async function rollbackNativeNvidiaSelection(input: { +async function rollbackNativeHostedSelection(input: { attachmentChanged: boolean; registryCommitted: boolean; - attachment?: NativeNvidiaProviderAttachment; + attachment?: NativeHostedProviderAttachment; gatewayName: string; sandboxName: string; error: unknown; @@ -1003,7 +1035,7 @@ async function rollbackNativeNvidiaSelection(input: { }): Promise { if (!input.attachmentChanged || input.registryCommitted || !input.attachment) return; try { - await detachNativeNvidiaProvider({ + await detachNativeHostedProvider({ adapter: input.deps.providerAdapter, target: { kind: "named", gatewayName: input.gatewayName }, sandboxName: input.sandboxName, @@ -1017,15 +1049,19 @@ async function rollbackNativeNvidiaSelection(input: { } } -async function detachPreviousNativeNvidiaBeforePublish(input: { - selectingNativeNvidia: boolean; - previousAttachment?: NativeNvidiaProviderAttachment; +async function detachPreviousNativeHostedBeforePublish(input: { + selectedProviderName?: string; + previousAttachment?: NativeHostedProviderAttachment; gatewayName: string; sandboxName: string; deps: InferenceSetDeps; }): Promise { - if (input.selectingNativeNvidia || !input.previousAttachment) return false; - await detachNativeNvidiaProvider({ + if ( + !input.previousAttachment || + input.selectedProviderName === input.previousAttachment.providerName + ) + return false; + await detachNativeHostedProvider({ adapter: input.deps.providerAdapter, target: { kind: "named", gatewayName: input.gatewayName }, sandboxName: input.sandboxName, @@ -1034,42 +1070,58 @@ async function detachPreviousNativeNvidiaBeforePublish(input: { return true; } -function nativeNvidiaDepartureRegistryFields( - detached: boolean, -): Pick | Record { - return detached ? { nativeNvidiaProviderAttachment: undefined } : {}; -} - -async function restorePreviousNativeNvidiaAfterFailedPublish(input: { +async function restorePreviousNativeHostedAfterFailedPublish(input: { detached: boolean; committed: boolean; - previousAttachment?: NativeNvidiaProviderAttachment; + routeApplied: boolean; + routeAmbiguous: boolean; + restoreRoute: () => Promise; + previousAttachment?: NativeHostedProviderAttachment; gatewayName: string; sandboxName: string; error: unknown; deps: InferenceSetDeps; }): Promise { - if (!input.detached || input.committed || !input.previousAttachment) return; - try { - await ensureNativeNvidiaProviderAttached({ - adapter: input.deps.providerAdapter, - target: { kind: "named", gatewayName: input.gatewayName }, - sandboxName: input.sandboxName, - expected: input.previousAttachment, - }); - } catch (reattachError) { + if (input.committed || !input.previousAttachment) return; + const recoveryErrors: string[] = []; + if (input.routeApplied && !input.routeAmbiguous) { + try { + const failure = await input.restoreRoute(); + if (failure) + recoveryErrors.push( + `Failed to restore the previous OpenShell inference selection: ${failure}`, + ); + } catch (error) { + recoveryErrors.push( + `Failed to restore the previous OpenShell inference selection: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + if (input.detached) { + try { + await ensureNativeHostedProviderAttached({ + adapter: input.deps.providerAdapter, + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: input.previousAttachment, + }); + } catch (error) { + recoveryErrors.push( + `Native hosted-provider access was detached before the failed switch, but restoring the attachment failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + if (recoveryErrors.length > 0) { const detail = input.error instanceof Error ? input.error.message : String(input.error); - const recoveryDetail = - reattachError instanceof Error ? reattachError.message : String(reattachError); throw new InferenceSetError( - `${detail}\n Native NVIDIA access was detached before the failed switch, but restoring the attachment failed: ${recoveryDetail}`, + `${detail}\n ${recoveryErrors.join("\n ")}`, input.error instanceof InferenceSetError ? input.error.exitCode : 1, ); } } async function applyInferenceRouteSelection(input: { - nativeNvidia: boolean; + nativeHosted: boolean; provider: string; model: string; gatewayName: string; @@ -1078,8 +1130,8 @@ async function applyInferenceRouteSelection(input: { onAmbiguousFailure: () => void; deps: InferenceSetDeps; }): Promise { - if (input.nativeNvidia) { - input.deps.log(` Using attached native NVIDIA provider: ${input.provider} / ${input.model}`); + if (input.nativeHosted) { + input.deps.log(` Using attached native hosted provider: ${input.provider} / ${input.model}`); return false; } input.deps.log(` Setting OpenShell inference route: ${input.provider} / ${input.model}`); @@ -1111,29 +1163,29 @@ async function applyInferenceRouteSelection(input: { } function observeInferenceRouteForSelection(input: { - nativeNvidia: boolean; + nativeHosted: boolean; gatewayName: string; deps: InferenceSetDeps; }): Promise { - if (input.nativeNvidia) return Promise.resolve({ state: "unconfigured" }); + if (input.nativeHosted) return Promise.resolve({ state: "unconfigured" }); return observeInferenceRouteBeforeMutation(input.deps, input.gatewayName); } function providerBackedRouteLacksRollbackTarget(input: { - nativeNvidia: boolean; + nativeHosted: boolean; directProviderBinding: boolean; httpsPinProviderBinding: boolean; probeDirectSandboxBridge: boolean; rollbackRoute: boolean; - previousNativeNvidiaAttachment: boolean; + previousNativeHostedAttachment: boolean; }): boolean { return ( - !input.nativeNvidia && + !input.nativeHosted && (input.directProviderBinding || input.httpsPinProviderBinding || input.probeDirectSandboxBridge) && !input.rollbackRoute && - !input.previousNativeNvidiaAttachment + !input.previousNativeHostedAttachment ); } @@ -1267,6 +1319,37 @@ function resolveMatchingAgentConfigTarget( return target; } +function readRegisteredNativeAuthority( + deps: InferenceSetDeps, + gatewayName: string, + provider: string, +) { + return deps.getNativeHostedProviderAuthority?.( + gatewayName, + nativeHostedProfile(provider)!.profileId, + ); +} + +function recordNativeProviderAuthority( + deps: InferenceSetDeps, + gatewayName: string, + attachment?: NativeHostedProviderAttachment, +): void { + if (!attachment) return; + deps.setNativeHostedProviderAuthority(gatewayName, attachment); +} + +function inferenceSelectionRecoveryDetail( + selectingNativeHosted: boolean, + previousProvider: string, + previousModel: string, +): string { + if (selectingNativeHosted) { + return "The shared OpenShell inference selection was not changed."; + } + return `The previous OpenShell inference selection was restored to '${previousProvider}' / '${previousModel}'.`; +} + async function runInferenceSetWithoutHostLock( options: InferenceSetOptions, deps: InferenceSetDeps, @@ -1360,7 +1443,7 @@ async function runInferenceSetWithoutHostLock( // Registered peers are compared exactly as recorded. In particular, a // stopped legacy Hermes row that still records the Anthropic frontend will // depend on that route when restarted and must not be normalized away. - const selectingNativeNvidia = isNativeNvidiaProvider(provider); + const selectingNativeHosted = isNativeHostedProvider(provider); const routeSandboxes = deps.listSandboxes().sandboxes; const preparedRoute = prepareInferenceSetRoute({ entry: routeEntry, @@ -1369,7 +1452,7 @@ async function runInferenceSetWithoutHostLock( model, customRoute, session: routeSession, - sandboxes: selectingNativeNvidia ? [] : routeSandboxes, + sandboxes: selectingNativeHosted ? [] : routeSandboxes, }); if (preparedRoute.gatewayName !== expectedGatewayName) { throw new InferenceSetError( @@ -1379,7 +1462,7 @@ async function runInferenceSetWithoutHostLock( ); } const preMutationRoute = await observeInferenceRouteForSelection({ - nativeNvidia: selectingNativeNvidia, + nativeHosted: selectingNativeHosted, gatewayName: preparedRoute.gatewayName, deps, }); @@ -1445,7 +1528,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 || + selectingNativeHosted || provider === "openrouter-api" || isSandboxBridgeProviderBinding(directProviderBinding) || loopbackNoAuthProxyRoute; @@ -1526,20 +1609,22 @@ async function runInferenceSetWithoutHostLock( assertReasoningEffortRoute(reasoningEffortRequest, provider, preMutationInferenceApi); const previousProvider = typeof entry.provider === "string" ? entry.provider.trim() : ""; const previousModel = typeof entry.model === "string" ? entry.model.trim() : ""; - const previousNativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAttachment, + const previousNativeHostedAttachment = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment, ); - assertNativeNvidiaMigrationReady({ + assertNativeHostedMigrationReady({ provider, previousProvider, - previousAttachment: previousNativeNvidiaAttachment, + previousAttachment: previousNativeHostedAttachment, sandboxName, }); - const nativeNvidiaProviderAuthority = selectingNativeNvidia - ? resolveGatewayNativeNvidiaProviderAuthority({ + const nativeHostedProviderAuthority = selectingNativeHosted + ? resolveGatewayNativeHostedProviderAuthority({ + profile: nativeHostedProfile(provider)!, gatewayName: preparedRoute.gatewayName, - gatewayAuthority: deps.getNativeNvidiaProviderAuthority?.(preparedRoute.gatewayName), - recordedAttachment: previousNativeNvidiaAttachment, + gatewayAuthority: readRegisteredNativeAuthority(deps, preparedRoute.gatewayName, provider), + recordedGatewayName: entry.gatewayName, + recordedAttachment: previousNativeHostedAttachment, }) : undefined; const rollbackRoute = preMutationRoute.state === "configured" ? preMutationRoute.route : null; @@ -1557,12 +1642,12 @@ async function runInferenceSetWithoutHostLock( ].some(([previous, next]) => previous !== next)); if ( providerBackedRouteLacksRollbackTarget({ - nativeNvidia: selectingNativeNvidia, + nativeHosted: selectingNativeHosted, directProviderBinding: Boolean(directProviderBinding), httpsPinProviderBinding: Boolean(httpsPinProviderBinding), probeDirectSandboxBridge: probeSandboxRoute, rollbackRoute: Boolean(rollbackRoute), - previousNativeNvidiaAttachment: Boolean(previousNativeNvidiaAttachment), + previousNativeHostedAttachment: Boolean(previousNativeHostedAttachment), }) ) { throw new InferenceSetError( @@ -1579,13 +1664,13 @@ async function runInferenceSetWithoutHostLock( let providerMutation: Awaited> | null = null; let assertProviderCurrentBeforeSelection: (() => Promise) | null = null; - let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; - let nativeNvidiaAttachmentChanged = false; - let nativeNvidiaRegistryCommitted = false; - let previousNativeNvidiaDetached = false; - let previousNativeNvidiaDetachCommitted = false; + let nativeHostedProviderAttachment: NativeHostedProviderAttachment | undefined; + let nativeHostedAttachmentChanged = false; + let nativeHostedRegistryCommitted = false; + let previousNativeHostedDetached = false; + let previousNativeHostedDetachCommitted = false; const restorePreviousInferenceSelection = async (): Promise => { - if (selectingNativeNvidia || previousNativeNvidiaAttachment) { + if (selectingNativeHosted) { appliedInferenceSelection = false; return null; } @@ -1615,15 +1700,16 @@ async function runInferenceSetWithoutHostLock( return null; }; try { - const nativeNvidiaSelection = await prepareNativeNvidiaSelection({ + const nativeHostedSelection = await prepareNativeHostedSelection({ provider, - expectedAttachment: nativeNvidiaProviderAuthority, + expectedAttachment: nativeHostedProviderAuthority, + gatewayName: preparedRoute.gatewayName, sandboxName, deps, }); - nativeNvidiaProviderAttachment = nativeNvidiaSelection.attachment; - nativeNvidiaAttachmentChanged = nativeNvidiaSelection.attachmentChanged; + nativeHostedProviderAttachment = nativeHostedSelection.attachment; + nativeHostedAttachmentChanged = nativeHostedSelection.attachmentChanged; const providerBinding = httpsPinProviderBinding ?? directProviderBinding; if (providerBinding) { providerMutation = await prepareInferenceSetProviderBinding({ @@ -1682,7 +1768,8 @@ async function runInferenceSetWithoutHostLock( await assertProviderCurrentBeforeSelection?.(); if (routeImpactWarning) deps.log(` ${routeImpactWarning}`); appliedInferenceSelection = await applyInferenceRouteSelection({ - nativeNvidia: selectingNativeNvidia, + nativeHosted: selectingNativeHosted, + provider, model, gatewayName: preparedRoute.gatewayName, @@ -1720,7 +1807,7 @@ async function runInferenceSetWithoutHostLock( provider, model, preferredInferenceApi: preMutationInferenceApi, - ...(selectingNativeNvidia ? { nativeProvider: true } : {}), + ...(selectingNativeHosted ? { nativeProvider: true } : {}), }, previousProvider, previousModel, @@ -1766,17 +1853,21 @@ async function runInferenceSetWithoutHostLock( } throw new InferenceSetError( `Sandbox-side verification rejected provider '${provider}' / '${model}': ${probe.detail}. ` + - `The previous OpenShell inference selection was restored to '${rollbackRoute?.provider ?? previousProvider}' / '${rollbackRoute?.model ?? previousModel}'.`, + inferenceSelectionRecoveryDetail( + selectingNativeHosted, + rollbackRoute?.provider ?? previousProvider, + rollbackRoute?.model ?? previousModel, + ), ); } } - // Removing native NVIDIA access is a security gate for publishing another + // Removing native hosted access is a security gate for publishing another // route. Do not commit the non-native registry/config while the sandbox can // still use the credential-bearing attached provider. - previousNativeNvidiaDetached = await detachPreviousNativeNvidiaBeforePublish({ - selectingNativeNvidia, - previousAttachment: previousNativeNvidiaAttachment, + previousNativeHostedDetached = await detachPreviousNativeHostedBeforePublish({ + selectedProviderName: nativeHostedProfile(provider)?.providerName, + previousAttachment: previousNativeHostedAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, deps, @@ -1801,8 +1892,8 @@ async function runInferenceSetWithoutHostLock( nimContainer: registryMetadata.nimContainer ?? null, }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), - ...nativeNvidiaDepartureRegistryFields(previousNativeNvidiaDetached), + nativeHostedProviderAttachment, + nativeNvidiaProviderAttachment: undefined, }); if ( !deps.updateSandbox( @@ -1820,8 +1911,8 @@ async function runInferenceSetWithoutHostLock( `Failed to update NemoClaw registry for sandbox '${sandboxName}'.`, ); } - nativeNvidiaRegistryCommitted = Boolean(nativeNvidiaProviderAttachment); - previousNativeNvidiaDetachCommitted = previousNativeNvidiaDetached; + nativeHostedRegistryCommitted = Boolean(nativeHostedProviderAttachment); + previousNativeHostedDetachCommitted = previousNativeHostedDetached; const preferredInferenceApi = explicitPreferredInferenceApi ?? @@ -2001,19 +2092,23 @@ async function runInferenceSetWithoutHostLock( }; } catch (error) { if (error instanceof OpenClawInferenceConfigSyncError) throw error; - await restorePreviousNativeNvidiaAfterFailedPublish({ - detached: previousNativeNvidiaDetached, - committed: previousNativeNvidiaDetachCommitted, - previousAttachment: previousNativeNvidiaAttachment, + await restorePreviousNativeHostedAfterFailedPublish({ + detached: previousNativeHostedDetached, + committed: previousNativeHostedDetachCommitted, + routeApplied: appliedInferenceSelection, + routeAmbiguous: ambiguousInferenceSelection, + restoreRoute: restorePreviousInferenceSelection, + previousAttachment: previousNativeHostedAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, error, deps, }); - await rollbackNativeNvidiaSelection({ - attachmentChanged: nativeNvidiaAttachmentChanged, - registryCommitted: nativeNvidiaRegistryCommitted, - attachment: nativeNvidiaProviderAttachment, + await rollbackNativeHostedSelection({ + attachmentChanged: nativeHostedAttachmentChanged, + registryCommitted: nativeHostedRegistryCommitted, + attachment: nativeHostedProviderAttachment, + gatewayName: preparedRoute.gatewayName, sandboxName, error, @@ -2054,6 +2149,44 @@ async function runInferenceSetWithoutHostLock( } } +async function completePendingNativeProviderDetach( + sandboxName: string, + gatewayName: string, + deps: InferenceSetDeps, +): Promise { + const entry = resolveTargetSandbox(sandboxName, deps).entry; + const pending = normalizeNativeHostedProviderAttachment(entry.pendingNativeHostedProviderDetach); + if (!pending) { + if (entry.pendingNativeHostedProviderDetach !== undefined) { + throw new InferenceSetError("Invalid pending native provider cleanup receipt."); + } + return; + } + if (nativeHostedProfile(entry.provider)?.providerName === pending.providerName) { + throw new InferenceSetError( + "Refusing to detach the currently selected native inference provider.", + ); + } + await detachNativeHostedProvider({ + adapter: deps.providerAdapter, + target: { kind: "named", gatewayName }, + sandboxName, + expected: pending, + }); + if ( + !deps.updateSandbox(sandboxName, { + pendingNativeHostedProviderDetach: undefined, + ...(!isNativeHostedProvider(entry.provider) + ? { nativeHostedProviderAttachment: undefined } + : {}), + }) + ) { + throw new InferenceSetError( + "Native provider access was removed, but its cleanup receipt could not be cleared. Retry before changing providers.", + ); + } +} + export async function runInferenceSet( options: InferenceSetOptions, deps: InferenceSetDeps = defaultDeps(), @@ -2098,6 +2231,7 @@ export async function runInferenceSet( deps.runtimeProviders, ); const gatewayName = resolveSandboxGatewayName(lockedSelection.entry); + await completePendingNativeProviderDetach(selected.sandboxName, gatewayName, deps); const mutation = await deps.withGatewayRouteMutationLock(gatewayName, () => runInferenceSetWithoutHostLock( { ...options, sandboxName: selected.sandboxName }, @@ -2115,6 +2249,7 @@ export async function runInferenceSet( if (mutation.openClawConfigSyncPending) { clearOpenClawConfigSyncPending(selected.sandboxName, deps); } + return mutation.result; }); } diff --git a/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts b/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts index 4b86a295c55..c01b1856d2d 100644 --- a/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts +++ b/src/lib/actions/sandbox/connect-flow-dcode-probe-preamble.test.ts @@ -76,10 +76,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, - inferenceGetOutput: "Provider: nvidia-prod\nModel: nvidia/nemotron-3-super-120b-a12b\n", + inferenceGetOutput: + "Provider: custom-shared-provider\nModel: nvidia/nemotron-3-super-120b-a12b\n", sessionAgent: { name: "langchain-deepagents-code" }, }); const runBuffered = harness.sandboxRunBufferedSpy.getMockImplementation()!; @@ -111,7 +112,7 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", sessionAgent: { name: "langchain-deepagents-code" }, - registryEntry: { provider: "nvidia-prod", model: "nvidia/nemotron", ...missing }, + registryEntry: { provider: "custom-shared-provider", model: "nvidia/nemotron", ...missing }, }); await expect(harness.connectSandbox("alpha")).rejects.toThrow("process.exit(1)"); @@ -127,11 +128,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [output], sessionAgent: { name: "langchain-deepagents-code" }, }); @@ -153,11 +154,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [ { status: 0, @@ -188,11 +189,11 @@ describe("connectSandbox DCode probe preamble boundary", () => { const harness = createConnectHarness({ agentName: "langchain-deepagents-code", registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [`exec: ${DCODE_MANAGED_EXEC_LAUNCHER}: not found`], sessionAgent: { name: "langchain-deepagents-code" }, }); diff --git a/src/lib/actions/sandbox/connect-flow.test.ts b/src/lib/actions/sandbox/connect-flow.test.ts index 3bdc1ae7a5d..012733694e0 100644 --- a/src/lib/actions/sandbox/connect-flow.test.ts +++ b/src/lib/actions/sandbox/connect-flow.test.ts @@ -67,7 +67,7 @@ function configureAlignedInferenceGet(harness: ReturnType { registry.getSandbox.mockReturnValue({ name: "alpha", agent: "langchain-deepagents-code", - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", gpuEnabled: false, }); @@ -243,7 +243,7 @@ describe("connectSandbox flow", () => { { status: 0, output: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", }, ], ["sandbox exec", { status: 0, output: "OK 200" }], @@ -335,10 +335,11 @@ describe("connectSandbox flow", () => { const longProbeDetail = `route probe unavailable NVIDIA_API_KEY=super-secret ${"x".repeat(400)}`; const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, - inferenceGetOutput: "Provider: nvidia-prod\nModel: nvidia/nemotron-3-super-120b-a12b\n", + inferenceGetOutput: + "Provider: custom-shared-provider\nModel: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: [longProbeDetail], }); @@ -363,7 +364,7 @@ describe("connectSandbox flow", () => { it("fails closed without repair when the route probe transport throws (#6192)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -389,7 +390,7 @@ describe("connectSandbox flow", () => { it("fails closed without repair when the route probe transport times out (#6192)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -426,7 +427,7 @@ describe("connectSandbox flow", () => { it("fails closed without repair when the OpenShell CA boundary is unavailable (#6192)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -826,10 +827,11 @@ describe("connectSandbox flow", () => { it("probe-only mode exits before reporting success when inference.local returns no trusted result (#8502)", async () => { const harness = createConnectHarness({ registryEntry: { - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, - inferenceGetOutput: "Provider: nvidia-prod\nModel: nvidia/nemotron-3-super-120b-a12b\n", + inferenceGetOutput: + "Provider: custom-shared-provider\nModel: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: ["route probe unavailable"], }); @@ -1031,7 +1033,7 @@ describe("connectSandbox flow", () => { "mismatched", { inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/other-model\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/other-model\n", }, ], ["unreachable", { inferenceProbeResponses: ["BROKEN 503"] }], diff --git a/src/lib/actions/sandbox/connect-route-containment.test.ts b/src/lib/actions/sandbox/connect-route-containment.test.ts index dbff9033854..7e8d85ea6d7 100644 --- a/src/lib/actions/sandbox/connect-route-containment.test.ts +++ b/src/lib/actions/sandbox/connect-route-containment.test.ts @@ -57,7 +57,7 @@ describe("connect route containment", () => { const sandbox: SandboxEntry = { name: "demo", model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", openshellDriver: "vm", gpuEnabled: false, }; @@ -79,12 +79,12 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "anthropic-prod", + provider: "other-shared-provider", model: "claude-sonnet-4-20250514", } as const; const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: alpha, registryEntries: [ alpha, @@ -93,7 +93,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, ], @@ -109,7 +109,7 @@ describe("connect route containment", () => { "inference", "set", "--provider", - "anthropic-prod", + "other-shared-provider", "--model", "claude-sonnet-4-20250514", ]), @@ -120,7 +120,7 @@ describe("connect route containment", () => { const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); expect(errorOutput).toContain("differs from the recorded route for sandbox 'alpha'"); expect(errorOutput).toContain( - "Aligning the gateway to anthropic-prod/claude-sonnet-4-20250514", + "Aligning the gateway to other-shared-provider/claude-sonnet-4-20250514", ); expect(exitSpy).not.toHaveBeenCalled(); }); @@ -205,7 +205,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/model-a", } as const; const harness = createConnectHarness({ @@ -223,7 +223,7 @@ describe("connect route containment", () => { await lockEntered; const peer = harness.registryEntries.find((candidate) => candidate.name === "peer"); expect(peer).toBeDefined(); - Object.assign(peer!, { provider: "anthropic-prod", model: "claude-new" }); + Object.assign(peer!, { provider: "other-shared-provider", model: "claude-new" }); releaseLock(); await expect(connect).resolves.toBeUndefined(); @@ -236,7 +236,7 @@ describe("connect route containment", () => { expect.objectContaining({ ignoreError: true, timeout: 15_000 }), ); expect(harness.runOpenshellSpy).toHaveBeenCalledWith( - expect.arrayContaining(["inference", "set", "--provider", "nvidia-prod"]), + expect.arrayContaining(["inference", "set", "--provider", "custom-shared-provider"]), expect.any(Object), ); expect(exitSpy).not.toHaveBeenCalled(); @@ -251,7 +251,7 @@ describe("connect route containment", () => { gatewayPort: 8080, provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -262,7 +262,7 @@ describe("connect route containment", () => { await expect(harness.connectSandbox("alpha", { probeOnly: true })).resolves.toBeUndefined(); - expect(harness.verifyNativeNvidiaProviderAttachmentSpy).toHaveBeenCalledWith( + expect(harness.verifyNativeHostedProviderAttachmentSpy).toHaveBeenCalledWith( expect.objectContaining({ sandboxName: "alpha", target: { kind: "named", gatewayName: "nemoclaw" }, @@ -303,7 +303,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/model-a", } as const; const harness = createConnectHarness({ @@ -350,7 +350,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, }); @@ -381,7 +381,7 @@ describe("connect route containment", () => { name: "alpha", pendingRouteReservation: true, gatewayName: "nemoclaw", - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/model-a", }, }); @@ -398,7 +398,7 @@ describe("connect route containment", () => { it("exits before repairing a lone incomplete legacy custom route (#6315)", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: { name: "alpha", agent: "openclaw", @@ -436,12 +436,12 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", } as const; const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: alpha, registryEntries: [ alpha, @@ -450,7 +450,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "anthropic-prod", + provider: "other-shared-provider", model: "claude-sonnet-4-20250514", }, ], @@ -473,12 +473,12 @@ describe("connect route containment", () => { gatewayName: "nemoclaw-9090", gatewayPort: 9090, openshellDriver: "docker", - provider: "anthropic-prod", + provider: "other-shared-provider", model: "claude-sonnet-4-20250514", } as const; const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: ["BROKEN 503", "BROKEN 503", "OK 200"], registryEntry: alpha, registryEntries: [ @@ -488,7 +488,7 @@ describe("connect route containment", () => { agent: "openclaw", gatewayName: "nemoclaw", gatewayPort: 8080, - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", }, ], @@ -513,7 +513,7 @@ describe("connect route containment", () => { "nemoclaw-9090", "--no-verify", "--provider", - "anthropic-prod", + "other-shared-provider", "--model", "claude-sonnet-4-20250514", ]); diff --git a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts index db1ef3bd89d..72c6a19c0cb 100644 --- a/src/lib/actions/sandbox/connect-route-lifecycle.test.ts +++ b/src/lib/actions/sandbox/connect-route-lifecycle.test.ts @@ -46,10 +46,10 @@ describe("connectSandbox route lifecycle", () => { it("warns and aligns a diverged route during a quiet probe-only connect (#3726)", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: { model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "other-shared-provider", }, }); @@ -58,10 +58,10 @@ describe("connectSandbox route lifecycle", () => { const errorOutput = harness.errorSpy.mock.calls.map((call) => String(call[0] ?? "")).join("\n"); expect(errorOutput).toContain("differs from the recorded route"); expect(errorOutput).toContain( - "Aligning the gateway to anthropic-prod/claude-sonnet-4-20250514", + "Aligning the gateway to other-shared-provider/claude-sonnet-4-20250514", ); expect(errorOutput).toContain( - "nemoclaw inference set --provider 'nvidia-prod' --model 'nvidia/nemotron-3-super-120b-a12b' --sandbox 'alpha'", + "nemoclaw inference set --provider 'custom-shared-provider' --model 'nvidia/nemotron-3-super-120b-a12b' --sandbox 'alpha'", ); expect(harness.runOpenshellSpy).toHaveBeenCalledWith( [ @@ -71,7 +71,7 @@ describe("connectSandbox route lifecycle", () => { "nemoclaw", "--no-verify", "--provider", - "anthropic-prod", + "other-shared-provider", "--model", "claude-sonnet-4-20250514", ], @@ -87,11 +87,11 @@ describe("connectSandbox route lifecycle", () => { it("stops after an ambiguous route swap before probing or attempting repair", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/old-model\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/old-model\n", inferenceSetResult: { status: null, output: "", signal: "SIGTERM" }, registryEntry: { model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "other-shared-provider", }, }); @@ -165,7 +165,7 @@ describe("connectSandbox route lifecycle", () => { registryEntry: { name: sandboxName, model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "other-shared-provider", }, }); @@ -187,12 +187,12 @@ describe("connectSandbox route lifecycle", () => { try { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: ['BROKEN 503 {"error":"inference service unavailable"}', "OK 200"], registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", openshellDriver: "vm", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); @@ -215,10 +215,10 @@ describe("connectSandbox route lifecycle", () => { it.each([ ["null", null, null], - ["provider-only", "nvidia-prod", null], + ["provider-only", "custom-shared-provider", null], ["model-only", null, "nvidia/test"], ["blank-provider", " ", "nvidia/test"], - ["blank-model", "nvidia-prod", " "], + ["blank-model", "custom-shared-provider", " "], ] as const)( "skips inference reconciliation for %s registry entries (#5937)", async (_description, provider, model) => { @@ -237,10 +237,10 @@ describe("connectSandbox route lifecycle", () => { it("does not reset an inference route that already matches the sandbox", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); @@ -257,7 +257,7 @@ describe("connectSandbox route lifecycle", () => { const harness = createConnectHarness({ registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); harness.captureOpenshellSpy @@ -285,12 +285,12 @@ describe("connectSandbox route lifecycle", () => { it("stops before opening SSH when route repair and reset both fail", async () => { const harness = createConnectHarness({ inferenceGetOutput: - "Gateway inference:\n Provider: nvidia-prod\n Model: nvidia/nemotron-3-super-120b-a12b\n", + "Gateway inference:\n Provider: custom-shared-provider\n Model: nvidia/nemotron-3-super-120b-a12b\n", inferenceProbeResponses: Array(7).fill('BROKEN 503 {"error":"upstream unavailable"}'), registryEntry: { model: "nvidia/nemotron-3-super-120b-a12b", openshellDriver: "kubernetes", - provider: "nvidia-prod", + provider: "custom-shared-provider", }, }); @@ -306,7 +306,7 @@ describe("connectSandbox route lifecycle", () => { "nemoclaw", "--no-verify", "--provider", - "nvidia-prod", + "custom-shared-provider", "--model", "nvidia/nemotron-3-super-120b-a12b", ], diff --git a/src/lib/actions/sandbox/connect.ts b/src/lib/actions/sandbox/connect.ts index b14fb93c2ef..2471159093b 100644 --- a/src/lib/actions/sandbox/connect.ts +++ b/src/lib/actions/sandbox/connect.ts @@ -122,8 +122,9 @@ import { type ProbeTimingRecorder, publicationFromDecision, publishLaunchReadiness, - getNativeNvidiaProviderAttachment, - requireNativeNvidiaInferenceHealth, + getNativeHostedProviderAttachment, + LaunchReadinessEvidenceError, + requireNativeHostedInferenceHealth, settlePortableOpenClawPairing, withLaunchReadinessMutationGate, } from "./launch-readiness"; @@ -1717,9 +1718,9 @@ async function ensureSandboxInferenceRouteUnlocked( assertNoOpenShellGatewayEndpointOverride(); const { provider, model } = inference; const gatewayName = getPersistedSandboxTargetGatewayName(sb); - const nativeNvidiaAttachment = getNativeNvidiaProviderAttachment(sb); - if (nativeNvidiaAttachment) { - await requireNativeNvidiaInferenceHealth({ + const nativeHostedAttachment = getNativeHostedProviderAttachment(sb); + if (nativeHostedAttachment) { + await requireNativeHostedInferenceHealth({ sandboxName, gatewayName, agentName: agent?.name, @@ -1879,7 +1880,20 @@ async function ensureSandboxInferenceRoute( if (!snapshot) return { sandbox: null, routeHealthy: null }; if (registry.getSandboxEntryInference(snapshot).kind !== "configured") return { sandbox: snapshot, routeHealthy: null }; - if (getNativeNvidiaProviderAttachment(snapshot)) { + let nativeAttachment: ReturnType; + try { + nativeAttachment = getNativeHostedProviderAttachment(snapshot); + } catch (error) { + if (!(error instanceof LaunchReadinessEvidenceError)) throw error; + if (!quiet) { + console.error( + ` Error: sandbox '${sandboxName}' has no valid native hosted provider attachment receipt. Recreate the sandbox to restore native inference.`, + ); + console.error(` Run: ${CLI_NAME} ${sandboxName} doctor`); + } + return { sandbox: snapshot, routeHealthy: false }; + } + if (nativeAttachment) { return ensureSandboxInferenceRouteUnlocked(sandboxName, agent, { quiet }); } const gatewayName = getPersistedSandboxTargetGatewayName(snapshot); diff --git a/src/lib/actions/sandbox/doctor-flow.test.ts b/src/lib/actions/sandbox/doctor-flow.test.ts index 00f57b89fda..0f28f4fe804 100644 --- a/src/lib/actions/sandbox/doctor-flow.test.ts +++ b/src/lib/actions/sandbox/doctor-flow.test.ts @@ -629,38 +629,95 @@ describe("runSandboxDoctor flow", () => { }, ); - it("uses the recorded native NVIDIA attachment instead of an unrelated shared route", async () => { + it.each(["nativeNvidiaProviderAttachment", "nativeHostedProviderAttachment"] as const)( + "uses the recorded NVIDIA %s instead of an unrelated shared route", + async (receiptField) => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }; + const harness = createDoctorHarness("nvidia-prod", { + registryOverrides: { [receiptField]: receipt }, + }); + + const report = await harness.runSandboxDoctor("alpha", ["--json"], { quietJson: true }); + + expect(harness.captureOpenShellSpy).not.toHaveBeenCalledWith( + expect.arrayContaining(["inference", "get"]), + expect.anything(), + ); + expect(harness.probeSandboxInferenceGatewayHealthSpy).not.toHaveBeenCalled(); + expect(harness.verifyNativeNvidiaStatusAttachmentSpy).toHaveBeenCalledWith({ + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", + expected: receipt, + }); + expect(harness.probeSandboxNativeNvidiaModelsHealthSpy).toHaveBeenCalledWith("alpha", { + gatewayName: "nemoclaw-19080", + agentName: "openclaw", + }); + expect(report?.checks).toContainEqual( + expect.objectContaining({ + label: "Inference route (native NVIDIA)", + status: "ok", + }), + ); + }, + ); + + it("keeps native OpenAI selection, gateway and Responses mode when the shared route differs", async () => { const receipt = { schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: "11111111-2222-4333-8444-555555555555", + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "owned-openai", }; - const harness = createDoctorHarness("nvidia-prod", { - registryOverrides: { nativeNvidiaProviderAttachment: receipt }, + const harness = createDoctorHarness("openai-api", { + registryOverrides: { + nativeHostedProviderAttachment: receipt, + preferredInferenceApi: "openai-responses", + }, }); - + const originalCapture = harness.captureOpenShellSpy.getMockImplementation()!; + harness.captureOpenShellSpy.mockImplementation((args: string[], ...rest: unknown[]) => + args[0] === "inference" && args[1] === "get" + ? { status: 0, output: "Provider: nvidia-prod\nModel: unrelated-model\n" } + : originalCapture(args, ...rest), + ); + const verify = vi + .spyOn(requireDist("./inference-route-health.js"), "verifyNativeHostedStatusAttachment") + .mockResolvedValue(undefined); + const invoke = vi + .spyOn(requireDist("./inference-invocation-probe.js"), "probeSandboxInferenceInvocation") + .mockResolvedValue({ ok: true }); const report = await harness.runSandboxDoctor("alpha", ["--json"], { quietJson: true }); - expect(harness.captureOpenShellSpy).not.toHaveBeenCalledWith( expect.arrayContaining(["inference", "get"]), expect.anything(), ); expect(harness.probeSandboxInferenceGatewayHealthSpy).not.toHaveBeenCalled(); - expect(harness.verifyNativeNvidiaStatusAttachmentSpy).toHaveBeenCalledWith({ + expect(verify).toHaveBeenCalledWith({ gatewayName: "nemoclaw-19080", sandboxName: "alpha", expected: receipt, }); - expect(harness.probeSandboxNativeNvidiaModelsHealthSpy).toHaveBeenCalledWith("alpha", { - gatewayName: "nemoclaw-19080", - agentName: "openclaw", - }); + expect(invoke).toHaveBeenCalledWith( + { + gatewayName: "nemoclaw-19080", + sandboxName: "alpha", + provider: "openai-api", + model: "registry-model", + agentName: "openclaw", + preferredInferenceApi: "openai-responses", + nativeProvider: true, + }, + {}, + 95000, + ); expect(report?.checks).toContainEqual( - expect.objectContaining({ - label: "Inference route (native NVIDIA)", - status: "ok", - }), + expect.objectContaining({ label: "Inference route (native OpenAI)", status: "ok" }), ); }); diff --git a/src/lib/actions/sandbox/doctor-inference.test.ts b/src/lib/actions/sandbox/doctor-inference.test.ts index 0544d8b9ec1..137e703bbb7 100644 --- a/src/lib/actions/sandbox/doctor-inference.test.ts +++ b/src/lib/actions/sandbox/doctor-inference.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES } from "../../inference/native-hosted/profiles"; import { describe, expect, it, vi } from "vitest"; import type { ProviderHealthStatus } from "../../inference/health"; import { collectInferenceChecks, collectManagedLlamaCppDoctorChecks } from "./doctor-inference"; @@ -32,6 +33,137 @@ function upstream(overrides: Partial = {}): ProviderHealth } describe("doctor inference checks", () => { + it.each(NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"))( + "verifies and invokes the selected native $label provider without a shared route", + async (profile) => { + const receipt = { + schemaVersion: 1 as const, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "owned-provider", + }; + const verify = vi.fn(async () => undefined); + const invoke = vi.fn(async () => ({ ok: true as const })); + const shared = vi.fn(async () => gateway(true)); + const checks = await collectInferenceChecks( + "alpha", + { + provider: profile.logicalProvider, + model: "selected-model", + preferredInferenceApi: "openai-responses", + agentName: "hermes", + nativeHostedProviderAttachment: receipt, + }, + true, + { + gatewayName: "selected-gateway", + verifyNativeHostedStatusAttachmentImpl: verify, + probeSandboxInferenceInvocationImpl: invoke, + probeSandboxInferenceGatewayHealthImpl: shared, + probeProviderHealthImpl: () => null, + }, + ); + expect(verify).toHaveBeenCalledWith({ + gatewayName: "selected-gateway", + sandboxName: "alpha", + expected: receipt, + }); + expect(invoke).toHaveBeenCalledWith( + { + sandboxName: "alpha", + gatewayName: "selected-gateway", + agentName: "hermes", + provider: profile.logicalProvider, + model: "selected-model", + preferredInferenceApi: "openai-responses", + nativeProvider: true, + }, + {}, + 95000, + ); + expect(shared).not.toHaveBeenCalled(); + expect(checks).toContainEqual( + expect.objectContaining({ + label: `Inference route (native ${profile.label})`, + status: "ok", + }), + ); + }, + ); + + it("does not invoke or fall back when native ownership verification fails", async () => { + const profile = NATIVE_HOSTED_PROFILES.find((item) => item.logicalProvider === "openai-api")!; + const verify = vi.fn(async () => { + throw new Error("provider identity changed"); + }); + const invoke = vi.fn(async () => ({ ok: true as const })); + const shared = vi.fn(async () => gateway(true)); + const checks = await collectInferenceChecks( + "alpha", + { + provider: profile.logicalProvider, + model: "selected-model", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "owned", + }, + }, + true, + { + gatewayName: "selected-gateway", + verifyNativeHostedStatusAttachmentImpl: verify, + probeSandboxInferenceInvocationImpl: invoke, + probeSandboxInferenceGatewayHealthImpl: shared, + probeProviderHealthImpl: () => upstream(), + }, + ); + expect(verify).toHaveBeenCalledOnce(); + expect(invoke).not.toHaveBeenCalled(); + expect(shared).not.toHaveBeenCalled(); + expect(checks).toContainEqual( + expect.objectContaining({ + label: "Inference route (native OpenAI)", + status: "fail", + detail: expect.stringContaining("provider identity changed"), + }), + ); + }); + + it("refuses a native provider receipt that belongs to another selection before any probe", async () => { + const verify = vi.fn(async () => undefined); + const invoke = vi.fn(async () => ({ ok: true as const })); + const shared = vi.fn(async () => gateway(true)); + const checks = await collectInferenceChecks( + "alpha", + { + provider: "openai-api", + model: "selected-model", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "other", + }, + }, + true, + { + gatewayName: "selected-gateway", + verifyNativeHostedStatusAttachmentImpl: verify, + probeSandboxInferenceInvocationImpl: invoke, + probeSandboxInferenceGatewayHealthImpl: shared, + probeProviderHealthImpl: () => null, + }, + ); + expect(verify).not.toHaveBeenCalled(); + expect(invoke).not.toHaveBeenCalled(); + expect(shared).not.toHaveBeenCalled(); + expect(checks).toContainEqual( + expect.objectContaining({ label: "Inference route (native OpenAI)", status: "fail" }), + ); + }); + it.each([ ["nvidia-prod", "nvidia/nemotron", "ok"], ["nvidia-prod", "unknown", "warn"], @@ -97,7 +229,7 @@ describe("doctor inference checks", () => { it("makes a broken inference.local route authoritative over a healthy upstream (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "openai-api", model: "gpt-5.4" }, + { provider: "ollama-local", model: "gpt-5.4" }, true, { probeProviderHealthImpl: () => upstream(), @@ -116,7 +248,7 @@ describe("doctor inference checks", () => { it("keeps failed upstream health diagnostic when inference.local works (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "openai-api", model: "gpt-5.4" }, + { provider: "ollama-local", model: "gpt-5.4" }, true, { probeProviderHealthImpl: () => @@ -137,7 +269,7 @@ describe("doctor inference checks", () => { it("keeps inference.local authoritative when the upstream diagnostic throws (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "openai-api", model: "gpt-5.4" }, + { provider: "ollama-local", model: "gpt-5.4" }, true, { probeProviderHealthImpl: () => { @@ -159,7 +291,7 @@ describe("doctor inference checks", () => { ); }); - it.each(["nvidia-router", "hermes-provider"])( + it.each(["nvidia-router", "ollama-local"])( "probes inference.local for %s without a direct health check (#6192)", async (provider) => { const routeProbe = vi.fn(async () => gateway(false)); @@ -182,7 +314,7 @@ describe("doctor inference checks", () => { it("reports an HTTP 503 inference.local route as unhealthy (#6192)", async () => { const checks = await collectInferenceChecks( "alpha", - { provider: "openai-api", model: "model" }, + { provider: "ollama-local", model: "model" }, true, { probeProviderHealthImpl: () => upstream(), @@ -204,7 +336,7 @@ describe("doctor inference checks", () => { async (failureMode) => { const checks = await collectInferenceChecks( "alpha", - { provider: "openai-api", model: "model" }, + { provider: "ollama-local", model: "model" }, true, { probeProviderHealthImpl: () => upstream(), diff --git a/src/lib/actions/sandbox/doctor-inference.ts b/src/lib/actions/sandbox/doctor-inference.ts index 168670e5905..1d4feaf5ea9 100644 --- a/src/lib/actions/sandbox/doctor-inference.ts +++ b/src/lib/actions/sandbox/doctor-inference.ts @@ -1,6 +1,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + isNativeHostedProvider, + nativeHostedProfile, + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../inference/native-hosted"; +import { + probeSandboxInferenceInvocation, + READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, +} from "./inference-invocation-probe"; +import { + buildSandboxInferenceRouteHealth, + verifyNativeHostedStatusAttachment, +} 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"; @@ -12,7 +26,7 @@ import { isNativeNvidiaProvider, normalizeNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import { classifyInferenceRouteFailureLabel, formatUntrustedProbeDetail, @@ -27,11 +41,13 @@ import { export type DoctorInferenceRoute = { model: string; provider: string; + preferredInferenceApi?: string | null; effectiveReasoningEffort?: EffectiveReasoningEffort | null; /** Sandbox route endpoint recorded at onboard; selects the bearerless local vLLM host port. */ recordedEndpointUrl?: string | null; agentName?: string | null; nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + nativeHostedProviderAttachment?: NativeHostedProviderAttachment; }; type ManagedLlamaCppDoctorDeps = { @@ -78,6 +94,8 @@ export function collectManagedLlamaCppDoctorChecks( } type DoctorInferenceDeps = { + verifyNativeHostedStatusAttachmentImpl?: typeof verifyNativeHostedStatusAttachment; + probeSandboxInferenceInvocationImpl?: typeof probeSandboxInferenceInvocation; gatewayName?: string | null; probeProviderHealthImpl?: typeof probeProviderHealth; probeSandboxInferenceGatewayHealthImpl?: typeof probeSandboxInferenceGatewayHealth; @@ -87,6 +105,61 @@ type DoctorInferenceDeps = { includeServingProcessCheck?: boolean; }; +async function collectNativeHostedRouteProbe( + sandboxName: string, + route: DoctorInferenceRoute, + sandboxReachable: boolean, + deps: DoctorInferenceDeps, +): Promise { + const profile = nativeHostedProfile(route.provider)!; + const unavailable = (detail: string): ProviderHealthStatus => ({ + ok: false, + probed: false, + providerLabel: `Native ${profile.label} route`, + endpoint: profile.endpoint, + detail, + failureLabel: "unreachable", + }); + if (!sandboxReachable) + return unavailable("The sandbox is not reachable through its named gateway."); + const receipt = normalizeNativeHostedProviderAttachment(route.nativeHostedProviderAttachment); + if (!deps.gatewayName || !receipt || receipt.profileId !== profile.profileId) { + return unavailable( + "The selected native provider ownership receipt or gateway binding is missing or mismatched.", + ); + } + try { + await (deps.verifyNativeHostedStatusAttachmentImpl ?? verifyNativeHostedStatusAttachment)({ + gatewayName: deps.gatewayName, + sandboxName, + expected: receipt, + }); + } catch (error) { + return unavailable( + `The recorded native provider attachment could not be verified: ${formatUntrustedProbeDetail(error instanceof Error ? error.message : String(error))}`, + ); + } + const invocation = await ( + deps.probeSandboxInferenceInvocationImpl ?? probeSandboxInferenceInvocation + )( + { + sandboxName, + gatewayName: deps.gatewayName, + agentName: route.agentName, + provider: route.provider, + model: route.model, + preferredInferenceApi: route.preferredInferenceApi ?? null, + nativeProvider: true, + }, + {}, + READINESS_INFERENCE_INVOCATION_TIMEOUT_MS, + ).catch(() => null); + return buildSandboxInferenceRouteHealth(null, null, invocation, { + provider: route.provider, + nativeHosted: true, + }); +} + async function collectNativeNvidiaRouteProbe( sandboxName: string, route: DoctorInferenceRoute, @@ -315,16 +388,21 @@ export async function collectInferenceChecks( const effortCheck = reasoningEffortCheck(route); if (effortCheck) checks.push(effortCheck); const nativeNvidia = isNativeNvidiaProvider(route.provider); + const nativeHosted = nativeHostedProfile(route.provider); const routeProbe = nativeNvidia ? await collectNativeNvidiaRouteProbe(sandboxName, route, sandboxReachable, deps) - : await collectInferenceRouteProbe( - sandboxName, - sandboxReachable, - deps.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth, - deps.gatewayName, - ); + : nativeHosted + ? await collectNativeHostedRouteProbe(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: nativeHosted + ? `Inference route (native ${nativeHosted.label})` + : "Inference route (gateway)", }); for (const diagnostic of collectProviderHealthDiagnostics( route, @@ -346,3 +424,5 @@ export async function collectInferenceChecks( } return checks; } + +export { isNativeHostedProvider, normalizeNativeHostedProviderAttachment }; diff --git a/src/lib/actions/sandbox/doctor.ts b/src/lib/actions/sandbox/doctor.ts index 2f51a29964a..a90bff145d9 100644 --- a/src/lib/actions/sandbox/doctor.ts +++ b/src/lib/actions/sandbox/doctor.ts @@ -36,6 +36,8 @@ import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { runSandboxAutoPairApprovalPass } from "./auto-pair-approval"; import { + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, collectInferenceChecks, collectManagedLlamaCppDoctorChecks, type DoctorInferenceRoute, @@ -389,8 +391,9 @@ async function resolveInferenceRoute( gatewayName: string | null, ): Promise { const recordedNativeNvidia = isNativeNvidiaProvider(sb?.provider); + const recordedNativeHosted = isNativeHostedProvider(sb?.provider); let live: { provider: string; model: string } | null = null; - if (!recordedNativeNvidia && openshellBin && openshellConnected && gatewayName) { + if (!recordedNativeHosted && openshellBin && openshellConnected && gatewayName) { const result = await createSynchronousCliOpenShellInferenceRouteObserver( captureOpenshell, ).observeInferenceRoute({ @@ -404,11 +407,15 @@ async function resolveInferenceRoute( provider: live?.provider || sb?.provider || "unknown", effectiveReasoningEffort: resolveDoctorReasoningEffort(sb), recordedEndpointUrl: sb?.endpointUrl, + preferredInferenceApi: sb?.preferredInferenceApi, agentName: sb?.agent, + nativeHostedProviderAttachment: normalizeNativeHostedProviderAttachment( + sb?.nativeHostedProviderAttachment ?? sb?.nativeNvidiaProviderAttachment, + ), ...(recordedNativeNvidia ? { nativeNvidiaProviderAttachment: normalizeNativeNvidiaProviderAttachment( - sb?.nativeNvidiaProviderAttachment, + sb?.nativeHostedProviderAttachment ?? sb?.nativeNvidiaProviderAttachment, ), } : {}), diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 52a09c8603e..c72d9a9879e 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 { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; import { spawnSync } from "node:child_process"; import { getChatCompletionsProbePayload } from "../../inference/openai-probe-models"; @@ -98,6 +99,72 @@ const NVCF_BODY_VARIANTS = [ ["extra whitespace", `{"status":404,"detail":"Function 'abc-123': Not found for account"}`], ] as const; +describe("native hosted inference protocol requests", () => { + it.each<[string, string, string, string[]]>([ + ["openai-api", "openai-responses", "https://api.openai.com/v1/responses", []], + [ + "anthropic-prod", + "anthropic-messages", + "https://api.anthropic.com/v1/messages", + ["anthropic-version: 2023-06-01"], + ], + [ + "gemini-api", + "openai-completions", + "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", + [], + ], + [ + "openrouter-api", + "openai-completions", + "https://openrouter.ai/api/v1/chat/completions", + ["HTTP-Referer: https://www.nvidia.com/nemoclaw/", "X-OpenRouter-Title: NVIDIA NemoClaw"], + ], + [ + "openrouter-api", + "openai-responses", + "https://openrouter.ai/api/v1/chat/completions", + ["HTTP-Referer: https://www.nvidia.com/nemoclaw/", "X-OpenRouter-Title: NVIDIA NemoClaw"], + ], + [ + "hermes-provider", + "openai-responses", + "https://inference-api.nousresearch.com/v1/responses", + [], + ], + [ + "hermes-provider", + "openai-completions", + "https://inference-api.nousresearch.com/v1/chat/completions", + [], + ], + ])( + "sends %s requests to its native protocol endpoint (#12589)", + (provider, preferredInferenceApi, endpoint, headers) => { + const credentialEnv = nativeHostedProfile(provider)!.credentialEnv; + const handle = `openshell:resolve:env:v42_${credentialEnv}`; + const result = runProbeCommandWithBody( + "200", + "{}", + tmpdir(), + { + ...input, + provider, + preferredInferenceApi, + nativeProvider: true, + } as typeof input, + { [credentialEnv]: handle }, + ); + expect(result.argv).toContain(endpoint); + expect(result.argv).toContain( + `${provider === "anthropic-prod" ? "x-api-key: " : "Authorization: Bearer "}${handle}`, + ); + expect(result.argv).toEqual(expect.arrayContaining(headers)); + expect(result.argv.join(" ")).not.toContain("inference.local"); + }, + ); +}); + describe("sandbox inference invocation probe", () => { it("ignores personal curl configuration when an inference request fails (#11520)", () => { const dir = mkdtempSync(path.join(tmpdir(), "nemoclaw-curl-config-")); @@ -144,11 +211,11 @@ describe("sandbox inference invocation probe", () => { nativeProvider: true, }); - expect(command).toContain("https://integrate.api.nvidia.com/v1/chat/completions"); - expect(command).toContain('AUTH_HEADER="Authorization: Bearer ${NVIDIA_INFERENCE_API_KEY}"'); + expect(command).toContain("Authorization: Bearer "); + expect(command).toContain("${NVIDIA_INFERENCE_API_KEY:-}"); expect(command).not.toContain("https://inference.local"); expect(command).not.toContain("NVIDIA_API_KEY"); - expect(command).toContain("openshell:resolve:env:"); + expect(command).not.toContain("nemoclaw-openshell-provider"); }); it("uses the supervisor credential in the shared native model request (#12822)", () => { diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index d897e32408e..519841fa3db 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; +import { nativeInferenceProbeAuthScript } from "../../inference/probe/native-inference-probe-auth"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; +import { getOpenRouterCurlHeaders } from "../../inference/openrouter"; import { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; import type { OpenShellSandboxBufferedCommandExecutor, @@ -14,10 +16,7 @@ import { } from "../../adapters/openshell/sandbox-observer"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; import { getSandboxInferenceConfig } from "../../inference/config"; -import { - isNativeNvidiaProvider, - NVIDIA_HOSTED_NATIVE_ENDPOINT, -} from "../../inference/native-nvidia"; +import { isNativeHostedProvider } from "../../inference/native-hosted"; import { validateInferenceResponseBody } from "../../inference/health"; import { MIN_PROBE_REPLY_TOKENS, @@ -87,19 +86,24 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { input.provider, input.preferredInferenceApi, ); - const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); + const useNativeHosted = input.nativeProvider === true && isNativeHostedProvider(input.provider); const baseUrl = ( - useNativeNvidia - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : isNativeNvidiaProvider(input.provider) + useNativeHosted + ? nativeHostedProfile(input.provider)!.endpoint + : isNativeHostedProvider(input.provider) ? "https://inference.local/v1" : config.inferenceBaseUrl ).replace(/\/+$/u, ""); - const apiBaseUrl = baseUrl.endsWith("/v1") ? baseUrl : `${baseUrl}/v1`; + const apiBaseUrl = + config.inferenceApi === "anthropic-messages" && !baseUrl.endsWith("/v1") + ? `${baseUrl}/v1` + : baseUrl; + const nativeHeaders = + useNativeHosted && input.provider === "openrouter-api" ? getOpenRouterCurlHeaders() : []; if (config.inferenceApi === "anthropic-messages") { return { endpoint: `${apiBaseUrl}/messages`, - headers: ["anthropic-version: 2023-06-01"], + headers: ["anthropic-version: 2023-06-01", ...nativeHeaders], payload: { model: input.model, max_tokens: MIN_PROBE_REPLY_TOKENS, @@ -110,7 +114,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { if (config.inferenceApi === "openai-responses" || config.inferenceApi === "responses") { return { endpoint: `${apiBaseUrl}/responses`, - headers: [], + headers: nativeHeaders, payload: { model: input.model, input: "Reply with OK", @@ -120,7 +124,7 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { } return { endpoint: `${apiBaseUrl}/chat/completions`, - headers: [], + headers: nativeHeaders, payload: { model: input.model, [resolveMaxTokensField(input.model)]: resolveProbeReplyTokens(input.provider, input.model), @@ -141,19 +145,23 @@ export function buildSandboxInferenceInvocationCommand( input: SandboxInferenceInvocationInput, ): string { const request = buildProbeRequest(input); - const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); - const headerArgs = - ["Content-Type: application/json", ...request.headers] - .map((header) => `-H ${shellQuote(header)}`) - .join(" ") + (useNativeNvidia ? ' -H "$AUTH_HEADER"' : ""); + const headerArgs = ["Content-Type: application/json", ...request.headers] + .map((header) => `-H ${shellQuote(header)}`) + .join(" "); + const nativeCredentialEnv = + input.nativeProvider === true ? nativeHostedProfile(input.provider)?.credentialEnv : undefined; + const authScript = nativeCredentialEnv + ? nativeInferenceProbeAuthScript(nativeCredentialEnv, input.provider === "anthropic-prod") + : []; + const authArg = nativeCredentialEnv ? ' -H "$AUTH_HEADER"' : ""; const payload = shellQuote(JSON.stringify(request.payload)); const endpoint = shellQuote(request.endpoint); return [ "umask 077", - ...(useNativeNvidia ? [NATIVE_NVIDIA_AUTH_HEADER_SCRIPT] : []), + ...authScript, "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"; }`, + `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}${authArg} --data-binary ${payload} ${endpoint}) || { rc=$?; printf 'curl-error:%s\\n' "$rc"; exit "$rc"; }`, "printf '%s\\n' \"$code\"", // A non-2xx body never leaves the sandbox (#6195). A 404 is classified // here instead, so status can name the cause the onboarding probe already diff --git a/src/lib/actions/sandbox/inference-route-health.test.ts b/src/lib/actions/sandbox/inference-route-health.test.ts index d08c9ac4145..7516bd031ec 100644 --- a/src/lib/actions/sandbox/inference-route-health.test.ts +++ b/src/lib/actions/sandbox/inference-route-health.test.ts @@ -136,7 +136,7 @@ describe("sandbox inference route health", () => { expect.objectContaining({ sandboxName: "alpha", target: { kind: "named", gatewayName: "nemoclaw-19080" }, - command: ["sh", "-c", expect.stringContaining("NVIDIA_INFERENCE_API_KEY")], + command: ["sh", "-c", expect.stringContaining("${NVIDIA_INFERENCE_API_KEY:-}")], }), ); }); @@ -155,7 +155,7 @@ describe("buildSandboxInferenceRouteHealth (#10080)", () => { gateway(503, false), null, { ok: true }, - { provider: "nvidia-prod", nativeNvidia: true }, + { provider: "nvidia-prod", nativeHosted: true }, ); expect(result).toMatchObject({ @@ -176,7 +176,7 @@ describe("buildSandboxInferenceRouteHealth (#10080)", () => { httpStatus: 401, endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", }, - { provider: "nvidia-prod", nativeNvidia: true }, + { provider: "nvidia-prod", nativeHosted: true }, ); expect(result).toMatchObject({ diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 46b4ff718a1..5198313c55f 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; +import { nativeInferenceProbeAuthScript } from "../../inference/probe/native-inference-probe-auth"; import { buildSandboxCommandEnvironment } from "../../adapters/sandbox/command-transport"; import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/openshell/sandbox-command"; import { createCliOpenShellSandboxCommandExecutor } from "../../adapters/openshell/sandbox-command-cli"; @@ -11,11 +11,14 @@ import * as agentRuntime from "../../agent/runtime"; import { REPOSITORY_ROOT } from "../../core/repository-root"; import type { ProviderHealthStatus } from "../../inference/health"; import { - isNativeNvidiaProvider, + isNativeHostedProvider, + verifyNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../inference/native-hosted"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT, - verifyNativeNvidiaProviderAttachment, type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import { isOpenRouterRuntimeAdapterModelsRoute404 } from "../../inference/openrouter"; import { RETRIABLE_HTTP_PROBE_STATUSES } from "../../inference/probe/transient-http-policy"; import { @@ -53,7 +56,28 @@ export async function verifyNativeNvidiaStatusAttachment(input: { await input.verify(input); return; } - await verifyNativeNvidiaProviderAttachment({ + await verifyNativeHostedProviderAttachment({ + adapter: createCliOpenShellProviderAdapter(), + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: input.expected, + }); +} + +export type VerifyNativeHostedStatusAttachment = (input: { + gatewayName: string; + sandboxName: string; + expected: NativeHostedProviderAttachment; +}) => Promise; + +export async function verifyNativeHostedStatusAttachment(input: { + gatewayName: string; + sandboxName: string; + expected: NativeHostedProviderAttachment; + verify?: VerifyNativeHostedStatusAttachment; +}): Promise { + if (input.verify) return input.verify(input); + await verifyNativeHostedProviderAttachment({ adapter: createCliOpenShellProviderAdapter(), target: { kind: "named", gatewayName: input.gatewayName }, sandboxName: input.sandboxName, @@ -70,7 +94,7 @@ export type SandboxInferenceRouteHealth = { const NATIVE_NVIDIA_MODELS_ENDPOINT = `${NVIDIA_HOSTED_NATIVE_ENDPOINT}/models`; const NATIVE_NVIDIA_MODELS_PROBE_SCRIPT = [ - NATIVE_NVIDIA_AUTH_HEADER_SCRIPT, + ...nativeInferenceProbeAuthScript("NVIDIA_INFERENCE_API_KEY"), `HTTP_CODE=$(/usr/bin/curl -q -s -o /dev/null -w '%{http_code}' -H "$AUTH_HEADER" --connect-timeout 3 --max-time 15 ${NATIVE_NVIDIA_MODELS_ENDPOINT} 2>/dev/null) || HTTP_CODE=000`, 'case "$HTTP_CODE" in 2[0-9][0-9]) printf \'OK %s\' "$HTTP_CODE" ;; *) printf \'BROKEN %s\' "$HTTP_CODE" ;; esac', ].join("; "); @@ -334,7 +358,7 @@ function buildInvokedRouteHealth( export type SandboxInferenceRouteHealthContext = { provider: string | null; - nativeNvidia?: boolean; + nativeHosted?: boolean; }; // A models route that answers but is credential-gated (401/403) stays @@ -367,11 +391,17 @@ export function buildSandboxInferenceRouteHealth( invocation: SandboxInferenceInvocationResult | null, context: SandboxInferenceRouteHealthContext, ): ProviderHealthStatus { - if (context.nativeNvidia && isNativeNvidiaProvider(context.provider)) { + if (context.nativeHosted && isNativeHostedProvider(context.provider)) { const endpoint = invocation && !invocation.ok && invocation.endpoint ? invocation.endpoint - : `${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions`; + : resolveSandboxInferenceInvocationEndpoint({ + sandboxName: "", + provider: context.provider!, + model: "", + preferredInferenceApi: null, + nativeProvider: true, + }); const diagnostics = providerHealthDiagnostics(providerHealth, Boolean(invocation?.ok)); const nativeHealth: ProviderHealthStatus = invocation?.ok ? { @@ -379,7 +409,7 @@ export function buildSandboxInferenceRouteHealth( probed: true, providerLabel: "Inference route", endpoint, - detail: "The attached OpenShell provider served a native NVIDIA inference request.", + detail: "The attached OpenShell provider served a native hosted inference request.", } : { ok: false, @@ -387,8 +417,8 @@ export function buildSandboxInferenceRouteHealth( providerLabel: "Inference route", endpoint, detail: invocation - ? `The native NVIDIA route did not serve an inference request: ${invocation.detail}.` - : "Could not probe the native NVIDIA route from inside the sandbox. Recreate legacy beta sandboxes before using this route.", + ? `The native hosted route did not serve an inference request: ${invocation.detail}.` + : "Could not probe the native hosted route from inside the sandbox. Recreate legacy beta sandboxes before using this route.", failureLabel: classifyInferenceInvocationFailureLabel(invocation?.httpStatus ?? null), }; return diagnostics.length > 0 ? { ...nativeHealth, subprobes: diagnostics } : nativeHealth; diff --git a/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts b/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts index a18d819dd0a..b864b8332a6 100644 --- a/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-gateway-health.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { execFileSync } from "node:child_process"; import { describe, expect, it, vi } from "vitest"; @@ -9,6 +10,7 @@ import type { OpenShellSandboxBufferedCommandExecutor } from "../../adapters/ope import { loadAgent } from "../../agent/defs"; import type { SandboxEntry } from "../../state/registry"; import { + getNativeHostedProviderAttachment, LaunchReadinessEvidenceError, LaunchReadinessObservationError, requireLaunchSemanticHealth, @@ -20,6 +22,16 @@ import { } from "./process-recovery"; describe("launch-readiness gateway health scope", () => { + it("refuses native readiness without an ownership receipt", () => { + expect(() => + getNativeHostedProviderAttachment({ + name: "alpha", + provider: "openai-api", + model: "selected", + } as SandboxEntry), + ).toThrow(LaunchReadinessEvidenceError); + }); + it.each([ ["becomes observable", [null, null, null, null, null, true], true], ["remains unavailable", [null, null, null, null, null, null], false], @@ -209,7 +221,14 @@ const dcodeAgent = loadAgent("langchain-deepagents-code"); const OPENROUTER_GATEWAY_AGENTS = ["openclaw", "hermes"] as const; function dcodeEntry(provider = "openrouter-api"): SandboxEntry { + const profile = nativeHostedProfile(provider)!; return { + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "owned", + }, name: SANDBOX, agent: "langchain-deepagents-code", provider, @@ -225,6 +244,7 @@ function dcodeHealthDeps( httpStatus = 404, ): LaunchReadinessHealthDeps { return { + verifyNativeHostedAttachment: vi.fn(async () => undefined), smoke: vi.fn(async () => ({ ok: true }) as const), gatewayHealth: vi.fn(async () => true), forwardsHealthy: vi.fn(() => true), @@ -281,6 +301,7 @@ describe("Deep Agents Code launch readiness", () => { provider, model: MODEL, preferredInferenceApi: null, + nativeProvider: true, }); }); @@ -318,11 +339,11 @@ describe("Deep Agents Code launch readiness", () => { describe("OpenRouter launch readiness", () => { it.each(OPENROUTER_GATEWAY_AGENTS)( - "accepts the %s catalog 404 after the recorded inference request succeeds (#12621)", + "accepts native %s readiness after the recorded inference request succeeds (#12621)", async (agentName) => { const agent = loadAgent(agentName); const entry = { - name: SANDBOX, + ...dcodeEntry(), agent: agentName, provider: "openrouter-api", model: MODEL, @@ -340,16 +361,18 @@ describe("OpenRouter launch readiness", () => { provider: "openrouter-api", model: MODEL, preferredInferenceApi: "openai-completions", + nativeProvider: true, }); + expect(currentDeps.inferenceProbe).not.toHaveBeenCalled(); }, ); it.each(OPENROUTER_GATEWAY_AGENTS)( - "rejects the %s catalog 404 when the recorded inference request fails (#12621)", + "rejects native %s readiness when the recorded inference request fails (#12621)", async (agentName) => { const agent = loadAgent(agentName); const entry = { - name: SANDBOX, + ...dcodeEntry(), agent: agentName, provider: "openrouter-api", model: MODEL, @@ -376,7 +399,9 @@ describe("OpenRouter launch readiness", () => { provider: "openrouter-api", model: MODEL, preferredInferenceApi: "openai-completions", + nativeProvider: true, }); + expect(currentDeps.inferenceProbe).not.toHaveBeenCalled(); }, ); }); diff --git a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts index 3547a5cb609..a1dbc67d2ba 100644 --- a/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts +++ b/src/lib/actions/sandbox/launch-readiness-observation-timing.test.ts @@ -163,7 +163,7 @@ describe("launch readiness observation timing", () => { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", credentialEnv: "NVIDIA_INFERENCE_API_KEY", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -178,7 +178,7 @@ describe("launch readiness observation timing", () => { const invoke = vi.fn(async () => ({ ok: true }) as const); currentDeps.getSandbox = () => nativeEntry; currentDeps.capture = capture; - currentDeps.verifyNativeNvidiaAttachment = verifyAttachment; + currentDeps.verifyNativeHostedAttachment = verifyAttachment; currentDeps.inferenceInvocationProbe = invoke; const decision = await inspectLaunchReadiness(SANDBOX, currentDeps); diff --git a/src/lib/actions/sandbox/launch-readiness.test.ts b/src/lib/actions/sandbox/launch-readiness.test.ts index 877a0cfdef6..e5b66fe68af 100644 --- a/src/lib/actions/sandbox/launch-readiness.test.ts +++ b/src/lib/actions/sandbox/launch-readiness.test.ts @@ -970,11 +970,11 @@ describe("launch readiness validation", () => { it("uses terminal-agent smoke health for a supported non-OpenClaw runtime", async () => { sandbox = { ...entry("langchain-deepagents-code"), - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "model-a", credentialEnv: "NVIDIA_API_KEY", }; - routeOutput = "Gateway Inference:\n\n Provider: nvidia-prod\n Model: model-a\n"; + routeOutput = "Gateway Inference:\n\n Provider: custom-shared-provider\n Model: model-a\n"; const currentDeps = deps(); currentDeps.inferenceInvocationProbe = async () => ({ ok: true }); const gatewayHealth = vi.fn(async () => true); @@ -996,11 +996,11 @@ describe("launch readiness validation", () => { it("rejects a Deep Agents Code lease when model discovery succeeds but inference fails (#11520)", async () => { sandbox = { ...entry("langchain-deepagents-code"), - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "model-a", credentialEnv: "NVIDIA_API_KEY", }; - routeOutput = "Gateway Inference:\n\n Provider: nvidia-prod\n Model: model-a\n"; + routeOutput = "Gateway Inference:\n\n Provider: custom-shared-provider\n Model: model-a\n"; const currentDeps = deps(); currentDeps.inferenceInvocationProbe = vi.fn(async () => ({ ok: true }) as const); await createAcceptedLease(currentDeps); diff --git a/src/lib/actions/sandbox/launch-readiness.ts b/src/lib/actions/sandbox/launch-readiness.ts index 5289c9c06a6..1a95219837c 100644 --- a/src/lib/actions/sandbox/launch-readiness.ts +++ b/src/lib/actions/sandbox/launch-readiness.ts @@ -65,7 +65,7 @@ import { type LaunchReadinessObservationStage, LaunchReadinessObservationError as ObservationError, recordLaunchReadinessObservationFailure, - getNativeNvidiaProviderAttachment, + getNativeHostedProviderAttachment, requireLaunchSemanticHealth, resolveLaunchInteractiveCommand, resolveTrustedLaunchAgent, @@ -86,10 +86,10 @@ import { } from "./launch-readiness/openclaw-pairing-qualification"; export { createProbeTimingRecorder, type ProbeTimingRecorder } from "./probe/timing"; -export { createBoundLaunchReadinessDeps }; +export { createBoundLaunchReadinessDeps, LaunchReadinessEvidenceError }; export { - getNativeNvidiaProviderAttachment, - requireNativeNvidiaInferenceHealth, + getNativeHostedProviderAttachment, + requireNativeHostedInferenceHealth, } from "./launch-readiness/health"; const LIVE_POLICY_MAX_BYTES = 2 * 1_024 * 1_024; @@ -826,9 +826,9 @@ async function captureLaunchIdentity( } const inferenceSelection = normalizeInferenceSelection(entry); const inference = registry.getSandboxEntryInference(entry); - const nativeNvidia = Boolean(getNativeNvidiaProviderAttachment(entry)); + const nativeHosted = Boolean(getNativeHostedProviderAttachment(entry)); let liveInference: { provider: string; model: string } | null = null; - if (!nativeNvidia) { + if (!nativeHosted) { const inferenceGetStartedAt = performance.now(); let inferenceResult: Awaited< ReturnType< diff --git a/src/lib/actions/sandbox/launch-readiness/health.ts b/src/lib/actions/sandbox/launch-readiness/health.ts index d06401f587f..14cae0539b5 100644 --- a/src/lib/actions/sandbox/launch-readiness/health.ts +++ b/src/lib/actions/sandbox/launch-readiness/health.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../../inference/native-hosted/profiles"; import { captureOpenshell } from "../../../adapters/openshell/runtime"; import { createCliOpenShellProviderAdapter } from "../../../adapters/openshell/provider-adapter-cli"; import type { OpenShellSandboxBufferedCommandExecutor } from "../../../adapters/openshell/sandbox-command"; @@ -19,10 +20,10 @@ import { } from "../../../onboard/sandbox-recreate-probe"; import type { SandboxEntry } from "../../../state/registry"; import { - normalizeNativeNvidiaProviderAttachment, - verifyNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "../../../inference/native-nvidia"; + normalizeNativeHostedProviderAttachment, + verifyNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../../inference/native-hosted"; import { createSynchronousCliOpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route-cli"; import type { OpenShellInferenceRouteObserver } from "../../../adapters/openshell/inference-route"; import { @@ -77,10 +78,10 @@ export interface LaunchReadinessHealthDeps { gatewayName: string, ) => Promise>; inferenceInvocationProbe?: typeof runSandboxInferenceInvocationProbe; - verifyNativeNvidiaAttachment?: (input: { + verifyNativeHostedAttachment?: (input: { sandboxName: string; gatewayName: string; - expected: NativeNvidiaProviderAttachment; + expected: NativeHostedProviderAttachment; }) => Promise; recordObservationTiming?: (stage: LaunchReadinessObservationStage, elapsedMs: number) => void; recordObservationFailure?: (stage: LaunchReadinessObservationStage) => void; @@ -135,8 +136,8 @@ export class LaunchReadinessObservationError extends Error { /** The required observation could not produce authoritative evidence. */ export class LaunchReadinessEvidenceError extends Error { - constructor() { - super("launch readiness evidence unavailable"); + constructor(message = "launch readiness evidence unavailable") { + super(message); } } @@ -205,32 +206,41 @@ export function resolveTrustedLaunchAgent( return agent; } -export function getNativeNvidiaProviderAttachment( +export function getNativeHostedProviderAttachment( entry: SandboxEntry, -): NativeNvidiaProviderAttachment | null { - return normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) ?? null; +): NativeHostedProviderAttachment | null { + const receipt = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment, + ); + const profile = nativeHostedProfile(entry.provider); + if ((profile && !receipt) || (receipt && profile?.profileId !== receipt.profileId)) { + throw new LaunchReadinessEvidenceError( + "No valid native hosted provider attachment receipt. Recreate the sandbox to restore native inference.", + ); + } + return receipt ?? null; } -export async function requireNativeNvidiaInferenceHealth(input: { +export async function requireNativeHostedInferenceHealth(input: { sandboxName: string; gatewayName: string; agentName?: string; entry: SandboxEntry; deps: LaunchReadinessHealthDeps; }): Promise { - const expected = getNativeNvidiaProviderAttachment(input.entry); + const expected = getNativeHostedProviderAttachment(input.entry); if (!expected) return false; const provider = normalizedString(input.entry.provider); const model = normalizedString(input.entry.model); if (!provider || !model) throw new LaunchReadinessEvidenceError(); - if (input.deps.verifyNativeNvidiaAttachment) { - await input.deps.verifyNativeNvidiaAttachment({ + if (input.deps.verifyNativeHostedAttachment) { + await input.deps.verifyNativeHostedAttachment({ sandboxName: input.sandboxName, gatewayName: input.gatewayName, expected, }); } else { - await verifyNativeNvidiaProviderAttachment({ + await verifyNativeHostedProviderAttachment({ adapter: createCliOpenShellProviderAdapter(), target: { kind: "named", gatewayName: input.gatewayName }, sandboxName: input.sandboxName, @@ -349,9 +359,9 @@ export async function requireLaunchSemanticHealth( } if (inferenceConfigured) { const inferenceStartedAt = performance.now(); - if (getNativeNvidiaProviderAttachment(entry)) { + if (getNativeHostedProviderAttachment(entry)) { try { - await requireNativeNvidiaInferenceHealth({ + await requireNativeHostedInferenceHealth({ sandboxName, gatewayName, agentName, diff --git a/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts b/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts index b1b81fcff19..9b2cda581b1 100644 --- a/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts +++ b/src/lib/actions/sandbox/policy-channel-remove-flow.test.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; import { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; @@ -24,8 +28,11 @@ import * as commandTransport from "../../adapters/sandbox/command-transport"; describe("policy channel remove/enable flows", () => { let exitSpy: MockInstance; let logSpy: MockInstance; + let testHome: string; beforeEach(() => { + testHome = mkdtempSync(join(tmpdir(), "nemoclaw-channel-remove-")); + vi.stubEnv("HOME", testHome); exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number | string | null) => { throw new Error(`process.exit(${code ?? 0})`); }) as never); @@ -45,6 +52,8 @@ describe("policy channel remove/enable flows", () => { afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); + rmSync(testHome, { recursive: true, force: true }); }); async function arrangeChannelRemoval( diff --git a/src/lib/actions/sandbox/rebuild-credential-preflight.ts b/src/lib/actions/sandbox/rebuild-credential-preflight.ts index 1e9b55f1627..2b907c6f91f 100644 --- a/src/lib/actions/sandbox/rebuild-credential-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-credential-preflight.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { runOpenshell } from "../../adapters/openshell/runtime"; -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia/contract"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; import { CLI_NAME } from "../../cli/branding"; import { R, RD } from "../../cli/terminal-style"; import type { RebuildSandboxEntry } from "./rebuild-flow-helpers"; @@ -23,12 +23,6 @@ const hermesProviderAuth = require("../../hermes-provider-auth") as { exists: boolean; credentialKeys: string[] | null; }>; - registerHermesInferenceProvider: ( - apiKey: string, - runOpenshellFn: typeof runOpenshell, - credentialEnv?: string, - baseUrl?: string, - ) => Promise; }; export type RebuildBail = (message: string, code?: number) => never; @@ -60,11 +54,6 @@ function normalizeHermesRebuildAuthMethod(value: unknown): "oauth" | "api_key" | return null; } -function nonEmptyString(value: unknown): string | null { - const normalized = String(value || "").trim(); - return normalized || null; -} - async function preflightHermesProviderCredentials( persistedAuthMethod: unknown, credentialEnv: string | null, @@ -73,15 +62,16 @@ async function preflightHermesProviderCredentials( const authMethod = normalizeHermesRebuildAuthMethod(persistedAuthMethod) || (credentialEnv === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV ? "api_key" : null); - const expectedCredentialEnv = - authMethod === "api_key" - ? hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV - : hermesProviderAuth.HERMES_INFERENCE_CREDENTIAL_ENV; + // Native Hermes stores either logical authentication method under one profile key. + const expectedCredentialEnv = hermesProviderAuth.HERMES_INFERENCE_CREDENTIAL_ENV; const binding = await hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); if (binding.exists) { const matches = - binding.credentialKeys?.length === 1 && binding.credentialKeys[0] === expectedCredentialEnv; + binding.credentialKeys?.length === 1 && + (binding.credentialKeys[0] === expectedCredentialEnv || + (authMethod === "api_key" && + binding.credentialKeys[0] === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV)); if (matches) { log("Hermes Provider rebuild preflight: credential binding matches"); return true; @@ -98,38 +88,8 @@ async function preflightHermesProviderCredentials( return false; } - if (authMethod === "api_key") { - const envKey = nonEmptyString( - process.env[hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV], - ); - log( - `Hermes Provider rebuild preflight: OpenShell provider missing; API key env=${envKey ? "present" : "missing"}`, - ); - if (envKey) { - try { - console.log( - " Hermes Provider is not registered in OpenShell; registering it from the configured exported API-key environment variable before rebuild.", - ); - await hermesProviderAuth.registerHermesInferenceProvider( - envKey, - runOpenshell, - hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV, - ); - const registered = await hermesProviderAuth.inspectHermesProviderBinding(runOpenshell); - return ( - registered.credentialKeys?.length === 1 && - registered.credentialKeys[0] === hermesProviderAuth.HERMES_NOUS_API_KEY_CREDENTIAL_ENV - ); - } catch (err) { - log( - `Hermes Provider rebuild preflight: failed to register OpenShell provider: ${ - err instanceof Error ? err.message : String(err) - }`, - ); - } - } - } - + // A rebuild may reuse only the recorded provider identity. Recreating a + // missing provider here would mutate credentials before the receipt check. console.error(""); console.error( ` ${RD}Rebuild preflight failed:${R} Hermes Provider is not registered in OpenShell.`, @@ -137,7 +97,7 @@ async function preflightHermesProviderCredentials( console.error(" Hermes Provider credentials must be stored in OpenShell, not host-side files."); if (authMethod === "api_key") { console.error( - ` Export the Hermes Provider API key and rerun rebuild, or re-run ${CLI_NAME} onboard to register it.`, + ` Re-run ${CLI_NAME} onboard to recreate the sandbox with its native provider attachment.`, ); } else { console.error( @@ -178,9 +138,15 @@ export async function preflightRebuildCredentials( sb.endpointUrl, ); const rebuildProvider = sb.provider; - const nativeAttachment = normalizeNativeNvidiaProviderAttachment( - sb.nativeNvidiaProviderAttachment, - ); + const rawAttachment = + sb.nativeHostedProviderAttachment !== undefined + ? sb.nativeHostedProviderAttachment + : sb.nativeNvidiaProviderAttachment; + const nativeAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); + if (rawAttachment !== undefined && !nativeAttachment) { + bail("Malformed native provider attachment; sandbox is untouched."); + return false; + } if (nativeAttachment) { if ( !(await checkRebuildGatewayProviderOrBail(rebuildProvider, rebuildCredentialEnv, log, bail, { diff --git a/src/lib/actions/sandbox/rebuild-dcode-target.ts b/src/lib/actions/sandbox/rebuild-dcode-target.ts index 2a30c700746..13742c8b085 100644 --- a/src/lib/actions/sandbox/rebuild-dcode-target.ts +++ b/src/lib/actions/sandbox/rebuild-dcode-target.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { GATEWAY_PORT } from "../../core/ports"; -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; import { resolveGatewayPortFromName, resolveSandboxGatewayName, @@ -14,7 +14,7 @@ export const DCODE_AGENT_NAME = "langchain-deepagents-code"; export type DcodeRebuildRegistryEntry = SandboxGatewayBinding & { agent?: string | null; dashboardPort?: number | null; - nativeNvidiaProviderAttachment?: unknown; + nativeHostedProviderAttachment?: unknown; }; export type DcodeRebuildResumeConfig = { @@ -71,7 +71,7 @@ export function resolveDcodeRebuildTarget( provider: requiredString(resumeConfig.provider, "inference provider"), model: requiredString(resumeConfig.model, "inference model"), preferredInferenceApi: resumeConfig.preferredInferenceApi, - ...(normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) + ...(normalizeNativeHostedProviderAttachment(entry.nativeHostedProviderAttachment) ? { nativeProvider: true } : {}), }; diff --git a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts index e1359aa62ba..579a798973e 100644 --- a/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-credential-preflight.test.ts @@ -6,15 +6,52 @@ import { makeMessagingPlan } from "../../../../test/helpers/messaging-plan-fixtu import { expectNoSandboxDelete } from "../../../../test/helpers/rebuild-delete-assertions"; import { rebuildBackupPhase } from "../../../../test/helpers/rebuild-flow-harness"; import { - createRebuildFlowHarness, + createRebuildFlowHarness as createBaseRebuildFlowHarness, installRebuildFlowTestHooks, snapshotEnv, } from "../../../../test/helpers/rebuild-flow-generic-harness"; +import { + nativeHostedProfile, + NATIVE_HOSTED_PROFILES, +} from "../../inference/native-hosted/profiles"; import { makePreparedRecoveryManifest, nativeProviderRebuildScenario, } from "./rebuild-flow-test-fixtures"; +function createRebuildFlowHarness( + options: NonNullable[0]>, +) { + const provider = options.sandboxEntry?.provider; + const profile = nativeHostedProfile(typeof provider === "string" ? provider : null); + return createBaseRebuildFlowHarness({ + ...options, + ...(profile && options.sandboxEntry + ? { + sandboxEntry: { + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "11111111-2222-4333-8444-555555555555", + }, + ...options.sandboxEntry, + }, + } + : {}), + ...(profile?.logicalProvider === "hermes-provider" && !options.runOpenshell + ? { + runOpenshell: providerRuntime( + options.hermesProviderExists === false ? [] : ["hermes-provider"], + { + "hermes-provider": "OPENAI_API_KEY", + }, + ), + } + : {}), + }); +} + type Harness = ReturnType; const MODEL = "test/model"; @@ -46,18 +83,21 @@ function providerRuntime( ]), ]; const describeProvider = (provider: string) => { + const native = nativeHostedProfile(provider); const output = [ - `Name: ${provider}`, - "Type: openai", + `Name: ${native?.providerName ?? provider}`, + `Type: ${native?.profileId ?? "openai"}`, + "Id: 11111111-2222-4333-8444-555555555555", + "Resource version: 1", `Credential keys: ${providerCredentialKeys(provider).join(", ")}`, - "Config keys: OPENAI_BASE_URL", + `Config keys: ${native ? "" : "OPENAI_BASE_URL"}`, ].join("\n"); return { status: 0, output, stdout: output, stderr: "" }; }; const missingProvider = { status: 1, output: "", stdout: "", stderr: "provider not found" }; const inventoryOutput = JSON.stringify( registeredProviders.map((provider) => ({ - name: provider, + name: nativeHostedProfile(provider)?.providerName ?? provider, credential_keys: providerCredentialKeys(provider), ...(credentialExpiresAtMs[provider] ? { credential_expires_at_ms: credentialExpiresAtMs[provider] } @@ -65,7 +105,10 @@ function providerRuntime( })), ); return (args: string[]) => { - const provider = args[0] === "provider" && args[1] === "get" ? args[2] : undefined; + const requested = args[0] === "provider" && args[1] === "get" ? args[2] : undefined; + const provider = + NATIVE_HOSTED_PROFILES.find((profile) => profile.providerName === requested) + ?.logicalProvider ?? requested; return args[0] === "provider" && args[1] === "list" ? { status: 0, output: inventoryOutput, stdout: inventoryOutput, stderr: "" } : provider === undefined @@ -239,10 +282,30 @@ describe("rebuildSandbox flow: credential preflight", () => { provider: "nvidia-prod", model: MODEL, credentialEnv: "NVIDIA_INFERENCE_API_KEY", + nativeHostedProviderAttachment: undefined, }, hydrateCredentialEnv: (credentialEnv) => credentialEnv === "NVIDIA_INFERENCE_API_KEY" ? "saved-provider-key" : null, - runOpenshell: providerRuntime(["nvidia-prod"]), + runOpenshell: (args) => { + const stdout = + args[0] === "settings" + ? JSON.stringify({ scope: "global", settings: { providers_v2_enabled: "true" } }) + : args[1] === "get" + ? "Name: nvidia-prod\nType: nvidia\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: NVIDIA_BASE_URL" + : JSON.stringify([ + { + name: "nvidia-prod", + credential_keys: ["NVIDIA_INFERENCE_API_KEY"], + credential_expires_at_ms: {}, + }, + ]); + return args.includes("nemoclaw-nvidia-prod-v1") + ? { status: 1, output: "provider not found", stdout: "", stderr: "provider not found" } + : (args[0] === "settings" && args[1] === "get") || + (args[0] === "provider" && ["get", "list"].includes(args[1])) + ? { status: 0, output: stdout, stdout, stderr: "" } + : undefined; + }, }); configureSession(harness, "nvidia-prod", "NVIDIA_INFERENCE_API_KEY"); @@ -299,11 +362,9 @@ describe("rebuildSandbox flow: credential preflight", () => { await expect( harness.rebuildSandbox("alpha", ["--yes", "--force"], { throwOnError: true }), - ).rejects.toThrow("Missing gateway provider credential: nvidia-prod/NVIDIA_INFERENCE_API_KEY"); + ).rejects.toThrow("Could not verify gateway provider: nvidia-prod"); - expect(diagnostics(harness)).toContain( - "provider 'nvidia-prod' no longer exposes credential NVIDIA_INFERENCE_API_KEY", - ); + expect(diagnostics(harness)).toContain("could not verify provider 'nvidia-prod' in OpenShell"); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); expect(harness.onboardSpy).not.toHaveBeenCalled(); expectNoSandboxDelete(harness.runOpenshellSpy); @@ -313,7 +374,6 @@ describe("rebuildSandbox flow: credential preflight", () => { it.each([ ["has no expiration map", undefined], ["has an explicit non-expiring value", { NVIDIA_INFERENCE_API_KEY: 0 }], - ["is absent from another credential's expiration map", { OTHER_API_KEY: 1_000 }], ["has a future expiration", { NVIDIA_INFERENCE_API_KEY: 8_640_000_000_000_000 }], ])( "continues when the selected provider credential %s (#10394)", @@ -341,6 +401,32 @@ describe("rebuildSandbox flow: credential preflight", () => { }, ); + it("does not expire a custom provider credential because another key expired (#10394)", async () => { + const harness = createRebuildFlowHarness({ + sandboxEntry: { + provider: "compatible-endpoint", + model: MODEL, + credentialEnv: "COMPATIBLE_API_KEY", + endpointUrl: "https://inference.example.test/v1", + preferredInferenceApi: "openai-completions", + }, + hydrateCredentialEnv: () => "saved-provider-key", + runOpenshell: providerRuntime( + ["compatible-endpoint"], + { "compatible-endpoint": "COMPATIBLE_API_KEY" }, + { "compatible-endpoint": { OTHER_API_KEY: 1_000 } }, + ), + }); + configureSession(harness, "compatible-endpoint", "COMPATIBLE_API_KEY", { + endpointUrl: "https://inference.example.test/v1", + preferredInferenceApi: "openai-completions", + }); + await expect( + harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).resolves.toBeUndefined(); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); + }); + it("preserves the sandbox when the provider loses the selected credential key during backup (#10394)", async () => { let backedUp = false; const validProvider = providerRuntime(["nvidia-prod"]); @@ -363,9 +449,7 @@ describe("rebuildSandbox flow: credential preflight", () => { await expect( harness.rebuildSandbox("alpha", ["--yes", "--force"], { throwOnError: true }), - ).rejects.toThrow( - "no longer exposes credential NVIDIA_INFERENCE_API_KEY before sandbox deletion", - ); + ).rejects.toThrow("is indeterminate before sandbox deletion"); expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); expectNoSandboxDelete(harness.runOpenshellSpy); @@ -815,7 +899,7 @@ describe("rebuildSandbox flow: credential preflight", () => { expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); }); - it("registers an exported Hermes API key before backup without logging it", async () => { + it("preserves a missing native Hermes identity despite an exported API key", async () => { const restoreEnv = snapshotEnv(["NOUS_API_KEY"]); process.env.NOUS_API_KEY = "nous-key-from-env"; @@ -835,28 +919,28 @@ describe("rebuildSandbox flow: credential preflight", () => { hermesAuthMethod: "api_key", }); - await expect( - harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); - - expect(harness.registerHermesInferenceProviderSpy).toHaveBeenCalledWith( - "nous-key-from-env", - expect.any(Function), - "NOUS_API_KEY", + const failure = await harness + .rebuildSandbox("alpha", ["--yes"], { throwOnError: true }) + .catch((error: Error) => error); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain( + "Native inference provider identity changed or is missing", ); - const output = [...harness.logSpy.mock.calls, ...harness.errorSpy.mock.calls] + + expect(harness.registerHermesInferenceProviderSpy).not.toHaveBeenCalled(); + const output = [ + [(failure as Error).message], + ...harness.logSpy.mock.calls, + ...harness.errorSpy.mock.calls, + ] .flat() .map(String) .join("\n"); - expect(output).toContain( - "Hermes Provider is not registered in OpenShell; registering it from the configured exported API-key environment variable before rebuild.", - ); - expect(output).not.toContain("NOUS_API_KEY"); + expect(output).toContain("sandbox is untouched"); expect(output).not.toContain("nous-key-from-env"); - expect(harness.backupSandboxStateSpy).toHaveBeenCalledOnce(); - expect(harness.registerHermesInferenceProviderSpy.mock.invocationCallOrder[0]!).toBeLessThan( - harness.backupSandboxStateSpy.mock.invocationCallOrder[0]!, - ); + expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); + expectNoSandboxDelete(harness.runOpenshellSpy); + expect(harness.onboardSpy).not.toHaveBeenCalled(); } finally { restoreEnv(); } @@ -878,13 +962,17 @@ describe("rebuildSandbox flow: credential preflight", () => { hermesAuthMethod: "oauth", }); - await expect( - harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow("Missing Hermes Provider credentials"); + const failure = await harness + .rebuildSandbox("alpha", ["--yes"], { throwOnError: true }) + .catch((error: Error) => error); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain( + "Native inference provider identity changed or is missing", + ); - const output = diagnostics(harness); - expect(output).toContain("Hermes Provider is not registered in OpenShell"); - expect(output).toContain("credentials must be stored in OpenShell"); + const output = `${(failure as Error).message}\n${diagnostics(harness)}`; + expect(output).toContain("sandbox is untouched"); + expectNoSandboxDelete(harness.runOpenshellSpy); expect(output).not.toContain("Missing credential: OPENAI_API_KEY"); expect(harness.backupSandboxStateSpy).not.toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts index 41d0629a774..107b2b952a5 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-credentials.test.ts @@ -6,6 +6,7 @@ import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; +import { createNativeProviderCommandRuntime } from "../../../../test/support/native-provider-command-runtime"; import { expectNoSandboxDelete } from "../../../../test/helpers/rebuild-delete-assertions"; import { createRebuildFlowHarness, @@ -79,8 +80,15 @@ describe("rebuildSandbox flow: target credentials", () => { webSearchEnabled: true, fromDockerfile: dockerfile, hermesAuthMethod: "api_key", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, }, - hermesCredentialKeys: ["NOUS_API_KEY"], + runOpenshell: createNativeProviderCommandRuntime("hermes-provider", true).run, + hermesCredentialKeys: ["OPENAI_API_KEY"], }); harness.session.webSearchConfig = null; harness.session.hermesAuthMethod = "oauth"; @@ -118,7 +126,14 @@ describe("rebuildSandbox flow: target credentials", () => { provider: "hermes-provider", model: "hermes-model", hermesAuthMethod: "oauth", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, }, + runOpenshell: createNativeProviderCommandRuntime("hermes-provider", true).run, }); await expect( @@ -129,14 +144,87 @@ describe("rebuildSandbox flow: target credentials", () => { expect(harness.session.credentialEnv).toBe("OPENAI_API_KEY"); }); + it.each(["unchanged", "collision", "disabled"] as const)( + "rechecks legacy Hermes migration target before deletion (%s)", + async (state) => { + const changed = state === "collision"; + const disabled = state === "disabled"; + const restoreEnv = snapshotEnv(["NOUS_API_KEY"]); + process.env.NOUS_API_KEY = "fixture-legacy-nous-key"; + let backupStarted = false; + const harness = createRebuildFlowHarness({ + sandboxEntry: { + provider: "hermes-provider", + model: "hermes-model", + hermesAuthMethod: "api_key", + credentialEnv: "NOUS_API_KEY", + }, + beforeBackup: () => { + backupStarted = true; + }, + hermesCredentialKeys: ["NOUS_API_KEY"], + hydrateCredentialEnv: (key) => (key === "NOUS_API_KEY" ? "fixture-legacy-nous-key" : null), + runOpenshell: (args) => { + const result = + args[0] === "settings" && args[1] === "get" + ? { + status: 0, + stdout: JSON.stringify({ + scope: "global", + settings: { providers_v2_enabled: disabled ? "false" : "true" }, + }), + stderr: "", + } + : args[0] === "provider" && + args[1] === "get" && + args.includes("nemoclaw-hermes-provider-v1") + ? changed && backupStarted + ? { + status: 0, + stdout: + "Name: nemoclaw-hermes-provider-v1\nType: nemoclaw-hermes-inference-v1\nId: unowned-id\nResource version: 1\nCredential keys: OPENAI_API_KEY\nConfig keys: ", + stderr: "", + } + : { status: 1, stdout: "", stderr: "provider not found" } + : undefined; + return result && { ...result, output: result.stdout || result.stderr }; + }, + }); + try { + const outcome = await harness + .rebuildSandbox("alpha", ["--yes"], { throwOnError: true }) + .then( + () => "rebuilt", + (error: Error) => error.message, + ); + expect(outcome).toEqual( + disabled + ? expect.stringContaining("provider policy could not be activated") + : changed + ? expect.stringContaining("Replacement validation failed") + : "rebuilt", + ); + expect(harness.onboardSpy).toHaveBeenCalledTimes(changed || disabled ? 0 : 1); + expect(harness.backupSandboxStateSpy).toHaveBeenCalledTimes(disabled ? 0 : 1); + expect( + harness.runOpenshellSpy.mock.calls.some( + ([args]) => Array.isArray(args) && args[0] === "sandbox" && args[1] === "delete", + ), + ).toBe(!changed && !disabled); + } finally { + restoreEnv(); + } + }, + ); + it("rejects a shared Hermes Provider whose credential binding changed", async () => { const harness = createRebuildFlowHarness({ sandboxEntry: { provider: "hermes-provider", model: "hermes-model", - hermesAuthMethod: "api_key", + hermesAuthMethod: "oauth", }, - hermesCredentialKeys: ["OPENAI_API_KEY"], + hermesCredentialKeys: ["NOUS_API_KEY"], }); await expect( diff --git a/src/lib/actions/sandbox/rebuild-flow-target-image.test.ts b/src/lib/actions/sandbox/rebuild-flow-target-image.test.ts index fd838827380..dd501db8399 100644 --- a/src/lib/actions/sandbox/rebuild-flow-target-image.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-target-image.test.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { createNativeProviderCommandRuntime } from "../../../../test/support/native-provider-command-runtime"; + import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -30,12 +32,6 @@ type RetainedContextMutation = { }; const FIXED_CONTEXT_TIME = new Date("2026-01-01T00:00:00.000Z"); -const NVIDIA_PROVIDER_OUTPUT = [ - "Name: nvidia-prod", - "Type: openai", - "Credential keys: NVIDIA_INFERENCE_API_KEY", - "Config keys: OPENAI_BASE_URL", -].join("\n"); const retainedContextMetadataMutations: RetainedContextMutation[] = [ { label: "file special bits change", @@ -333,17 +329,15 @@ describe("rebuildSandbox flow: target image", () => { provider: "nvidia-prod", model: "nvidia/nemotron", credentialEnv: "NVIDIA_INFERENCE_API_KEY", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, }, sessionSandboxName: "some-other-sandbox", - runOpenshell: (args) => - args[0] === "provider" && args[1] === "get" - ? { - status: 0, - output: NVIDIA_PROVIDER_OUTPUT, - stdout: NVIDIA_PROVIDER_OUTPUT, - stderr: "", - } - : undefined, + runOpenshell: createNativeProviderCommandRuntime("nvidia-prod", true).run, }); const staleEndpoint = "https://stale.example.test/v1"; harness.session.endpointUrl = staleEndpoint; diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index 3deb98867be..32a13193104 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -74,6 +74,7 @@ import { revalidatePreparedRecoveryBeforeDelete, } from "./rebuild-prepared-recovery"; import { + checkRebuildGatewayCredentialReuseOrBail, inspectRebuildGatewayProviderRegistration, validateRebuildHostInferenceCredential, shouldVerifyRebuildGatewayProvider, @@ -844,6 +845,18 @@ async function rebuildSandboxUnlocked( "Host inference credential could not be validated before sandbox deletion. Check the credential and recorded endpoint, then retry rebuild.", }; } + if ( + !resumeConfig.nativeHostedProviderAttachment && + !resumeConfig.nativeNvidiaProviderAttachment + ) { + await checkRebuildGatewayCredentialReuseOrBail( + sandboxName, + resumeConfig, + Boolean(credentialEnv && hydrateCredentialEnv(credentialEnv)), + log, + bail, + ); + } if ( !recreateOptions.rebuildProviderReconfigure && shouldVerifyRebuildGatewayProvider(resumeConfig.provider) @@ -855,7 +868,8 @@ async function rebuildSandboxUnlocked( runtimeSelection, undefined, resumeConfig.credentialEnv, - resumeConfig.nativeNvidiaProviderAttachment, + resumeConfig.nativeHostedProviderAttachment ?? + resumeConfig.nativeNvidiaProviderAttachment, ); if (registration !== "registered") { return { diff --git a/src/lib/actions/sandbox/rebuild-preflight-phase.ts b/src/lib/actions/sandbox/rebuild-preflight-phase.ts index b5e9e6c62ad..795c8e695ae 100644 --- a/src/lib/actions/sandbox/rebuild-preflight-phase.ts +++ b/src/lib/actions/sandbox/rebuild-preflight-phase.ts @@ -336,7 +336,8 @@ export async function runRebuildPreflightPhase( // but before backup or any destructive rebuild work begins. const { resumeConfig } = preparedTarget.targetConfig; const hostCredentialAvailable = Boolean( - resumeConfig.credentialEnv && hydrateCredentialEnv(resumeConfig.credentialEnv), + preparedTarget.targetConfig.credentialEnv && + hydrateCredentialEnv(preparedTarget.targetConfig.credentialEnv), ); if ( !(await checkRebuildGatewayCredentialReuseOrBail( diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts index 26198d53ec7..d2b57585d83 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.test.ts @@ -6,7 +6,7 @@ import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/prov import { NVIDIA_HOSTED_NATIVE_PROVIDER, NVIDIA_HOSTED_NATIVE_PROFILE_ID, -} from "../../inference/native-nvidia"; +} from "../../inference/native-nvidia/contract"; import * as openshellRuntime from "../../adapters/openshell/runtime"; import type { GatewayProviderMetadata } from "../../onboard/gateway-provider-metadata"; import { @@ -102,6 +102,71 @@ describe("canRecreateMissingRebuildGatewayProvider", () => { }); describe("inspectRebuildGatewayProviderRegistration", () => { + it.each([ + ["recorded", {}, "registered"], + ["replaced", { revision: { id: "foreign", resourceVersion: 2 } }, "indeterminate"], + ["expired", { credentialExpiresAtMs: { OPENAI_API_KEY: 1 } }, "expired"], + ] as const)("checks generic hosted receipt %s", async (_label, changes, expected) => { + const adapter = createCliOpenShellProviderAdapter(); + const get = vi.spyOn(adapter, "getProvider").mockResolvedValue({ + ok: true, + value: { + name: "nemoclaw-openai-api-v1", + type: "nemoclaw-openai-inference-v1", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + credentialExpiresAtMs: {}, + revision: { id: "recorded-id", resourceVersion: 1 }, + ...changes, + }, + }); + await expect( + inspectRebuildGatewayProviderRegistration( + "openai-api", + vi.fn(), + "Preflight", + undefined, + adapter, + "OPENAI_API_KEY", + { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }, + ), + ).resolves.toBe(expected); + expect(get).toHaveBeenCalledWith( + expect.objectContaining({ + providerName: "nemoclaw-openai-api-v1", + includeCredentialExpirations: true, + }), + ); + }); + it("inspects the logical legacy registration without a native receipt", async () => { + const adapter = createCliOpenShellProviderAdapter(); + const get = vi.spyOn(adapter, "getProvider").mockResolvedValue({ + ok: true, + value: { + name: "openai-api", + type: "openai", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: ["OPENAI_BASE_URL"], + credentialExpiresAtMs: {}, + }, + }); + await expect( + inspectRebuildGatewayProviderRegistration( + "openai-api", + vi.fn(), + "Preflight", + undefined, + adapter, + "OPENAI_API_KEY", + ), + ).resolves.toBe("registered"); + expect(get).toHaveBeenCalledWith(expect.objectContaining({ providerName: "openai-api" })); + }); it.each([ ["exact native binding", {}, "registered"], ["replaced provider", { revision: { id: "foreign", resourceVersion: 2 } }, "indeterminate"], @@ -197,6 +262,110 @@ describe("inspectRebuildGatewayProviderRegistration", () => { }); describe("checkRebuildGatewayCredentialReuseOrBail", () => { + it.each([ + "missing", + "owned", + "unowned", + "replaced", + "indeterminate", + "keyless", + "policy-disabled", + "policy-unavailable", + ] as const)("checks receiptless migration target %s on recorded gateway", async (state) => { + const native = { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + } as const; + const providerAdapter = createCliOpenShellProviderAdapter(); + const get = vi.spyOn(providerAdapter, "getProvider").mockResolvedValue( + state === "missing" || state === "indeterminate" || state.startsWith("policy-") + ? { + ok: false, + error: { + kind: "command", + reason: state === "indeterminate" ? "failed" : "not_found", + message: "unavailable", + }, + } + : { + ok: true, + value: { + name: native.providerName, + type: native.profileId, + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { + id: state === "replaced" ? "foreign" : native.providerId, + resourceVersion: 1, + }, + }, + }, + ); + const activatePolicy = vi + .spyOn(providerAdapter, "ensureProviderPolicyComposition") + .mockResolvedValue( + state.startsWith("policy-") + ? { + ok: false, + error: { + kind: "command", + reason: state === "policy-disabled" ? "conflict" : "failed", + message: "policy unavailable", + }, + } + : { ok: true, value: undefined }, + ); + const readNativeAuthority = vi + .fn() + .mockReturnValue(state === "owned" || state === "replaced" ? native : undefined); + const outcome = checkRebuildGatewayCredentialReuseOrBail( + "alpha", + config({ + gatewayName: "nemoclaw", + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + }), + state !== "keyless", + vi.fn(), + throwingBail, + { + providerAdapter, + readNativeAuthority, + readGatewayProviderMetadata: vi.fn(), + readRecordedProviderEndpoints: vi.fn(), + }, + ); + await expect( + outcome.then( + (result) => ({ result }), + (error) => ({ error: error.message }), + ), + ).resolves.toEqual( + state === "missing" || state === "owned" + ? { result: true } + : { error: expect.stringContaining("sandbox is untouched") }, + ); + expect(activatePolicy).toHaveBeenCalledTimes( + ["missing", "owned", "policy-disabled", "policy-unavailable"].includes(state) ? 1 : 0, + ); + expect( + activatePolicy.mock.calls.every( + ([request]) => request.target.kind === "named" && request.target.gatewayName === "nemoclaw", + ), + ).toBe(true); + expect( + get.mock.calls.every( + ([request]) => request.target.kind === "named" && request.target.gatewayName === "nemoclaw", + ), + ).toBe(true); + expect( + readNativeAuthority.mock.calls.every( + ([gateway, profile]) => gateway === "nemoclaw" && profile === native.profileId, + ), + ).toBe(true); + }); it("accepts an exact complete registry route and gateway provider identity", async () => { await expect( checkRebuildGatewayCredentialReuseOrBail("alpha", config(), false, vi.fn(), throwingBail, { @@ -397,3 +566,64 @@ describe("checkRebuildGatewayCredentialReuseOrBail", () => { expect(diagnostics).not.toContain("secret-canary"); }); }); + +describe("native rebuild provider identity", () => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }; + it.each([false, true])( + "checks the recorded identity even when a host key is available: %s", + async (hostCredentialAvailable) => { + const read = vi.fn(async () => ({ + name: receipt.providerName, + type: receipt.profileId, + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { id: "replacement-id", resourceVersion: 1 }, + })); + await expect( + checkRebuildGatewayCredentialReuseOrBail( + "alpha", + config({ provider: "openai-api", nativeHostedProviderAttachment: receipt }), + hostCredentialAvailable, + vi.fn(), + throwingBail, + { + readGatewayProviderMetadata: read, + readRecordedProviderEndpoints: vi.fn(() => []), + }, + ), + ).rejects.toThrow("identity changed"); + expect(read).toHaveBeenCalledWith(receipt.providerName); + }, + ); + it("reuses the exact native provider without reading a host credential", async () => { + const read = vi.fn(async () => ({ + name: receipt.providerName, + type: receipt.profileId, + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { id: receipt.providerId, resourceVersion: 1 }, + })); + await expect( + checkRebuildGatewayCredentialReuseOrBail( + "alpha", + config({ + provider: "openai-api", + credentialEnv: "OPENAI_API_KEY", + nativeHostedProviderAttachment: receipt, + }), + false, + vi.fn(), + throwingBail, + { + readGatewayProviderMetadata: read, + readRecordedProviderEndpoints: vi.fn(() => []), + }, + ), + ).resolves.toBe(true); + }); +}); diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.ts index 03244d2bf10..21525632ec2 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.ts @@ -19,16 +19,16 @@ import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider import type { RunProviderCommand } from "../../adapters/openshell/provider-adapter-cli"; import { runOpenshellProviderCommand } from "../../adapters/openshell/provider-command"; import type { OpenShellRuntimeSelection } from "../../adapters/openshell/runtime-selection"; +import { + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../inference/native-hosted/contract"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { RD as _RD, R } from "../../cli/terminal-style"; import { hasBedrockRuntimeAwsAuthEnv, isBedrockRuntimeEndpoint, } from "../../inference/bedrock-runtime"; -import { - isNativeNvidiaProvider, - nativeNvidiaProviderAttachmentFromMetadata, - type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; import type { GatewayProviderMetadata } from "../../onboard/gateway-provider-metadata"; import { assessRecoveredProviderCredentialReuse, @@ -160,40 +160,56 @@ export async function inspectRebuildGatewayProviderRegistration( runtimeSelection?: OpenShellRuntimeSelection, providerAdapter = rebuildProviderAdapter(runtimeSelection), credentialKey?: string | null, - nativeAttachment?: NativeNvidiaProviderAttachment, + nativeAttachment?: NativeHostedProviderAttachment, ): Promise { - if (nativeAttachment && !isNativeNvidiaProvider(provider)) return "indeterminate"; + const nativeProfile = nativeAttachment ? nativeHostedProfile(provider) : undefined; + if ( + nativeAttachment && + (!nativeProfile || + nativeAttachment.profileId !== nativeProfile.profileId || + nativeAttachment.providerName !== nativeProfile.providerName) + ) + return "indeterminate"; + const effectiveCredentialKey = nativeProfile + ? credentialKey + ? nativeProfile.credentialEnv + : null + : credentialKey; const result = await providerAdapter.getProvider({ - providerName: nativeAttachment?.providerName ?? provider, + providerName: nativeAttachment?.providerName ?? nativeProfile?.providerName ?? provider, target: managedProviderGatewayTarget, - ...(credentialKey ? { includeCredentialExpirations: true } : {}), + ...(effectiveCredentialKey ? { includeCredentialExpirations: true } : {}), }); - if (result.ok && nativeAttachment) { - try { - if ( - nativeNvidiaProviderAttachmentFromMetadata(result.value).providerId !== - nativeAttachment.providerId - ) - return "indeterminate"; - } catch { - return "indeterminate"; - } - } - const expiresAtMs = result.ok && credentialKey ? result.value.credentialExpiresAtMs : undefined; - const credentialExpiresAtMs = credentialKey ? expiresAtMs?.[credentialKey] : undefined; + if (result.ok && nativeAttachment && result.value.revision?.id !== nativeAttachment.providerId) + return "indeterminate"; + const expiresAtMs = + result.ok && effectiveCredentialKey ? result.value.credentialExpiresAtMs : undefined; + const credentialExpiresAtMs = effectiveCredentialKey + ? expiresAtMs?.[effectiveCredentialKey] + : undefined; const credentialKeyMissing = Boolean( - result.ok && credentialKey && !result.value.credentialKeys.includes(credentialKey), + result.ok && + effectiveCredentialKey && + !result.value.credentialKeys.includes(effectiveCredentialKey), ); const registration = result.ok - ? credentialKey && expiresAtMs === undefined + ? nativeProfile && + (result.value.name !== nativeProfile.providerName || + result.value.type !== nativeProfile.profileId || + result.value.configKeys.length !== 0 || + result.value.credentialKeys.length !== 1 || + result.value.credentialKeys[0] !== nativeProfile.credentialEnv || + !result.value.revision?.id) ? "indeterminate" - : credentialKeyMissing - ? "credential_missing" - : credentialExpiresAtMs !== undefined && - credentialExpiresAtMs > 0 && - credentialExpiresAtMs <= Date.now() - ? "expired" - : "registered" + : effectiveCredentialKey && expiresAtMs === undefined + ? "indeterminate" + : credentialKeyMissing + ? "credential_missing" + : credentialExpiresAtMs !== undefined && + credentialExpiresAtMs > 0 && + credentialExpiresAtMs <= Date.now() + ? "expired" + : "registered" : result.error.kind === "command" && result.error.reason === "not_found" ? "missing" : "indeterminate"; @@ -214,8 +230,14 @@ export async function inspectRebuildGatewayProviderRegistration( } type GatewayCredentialReusePreflightDeps = { + providerAdapter?: OpenShellProviderAdapter; + readNativeAuthority?: typeof registry.getNativeHostedProviderAuthority; hasBedrockRuntimeAwsAuth?(): boolean; - readGatewayProviderMetadata(provider: string): Promise; + readGatewayProviderMetadata( + provider: string, + ): Promise< + (GatewayProviderMetadata & { revision?: { id: string; resourceVersion: number } | null }) | null + >; readRecordedProviderEndpoints(provider: string, excludeSandboxName: string): string[] | null; }; @@ -328,7 +350,7 @@ export async function checkRebuildGatewayProviderOrBail( log: (msg: string) => void, bail: (msg: string, code?: number) => never, options: { - nativeAttachment?: NativeNvidiaProviderAttachment; + nativeAttachment?: NativeHostedProviderAttachment; allowProviderReconfigure?: boolean; hostCredentialAvailable?: boolean; onProviderReconfigureRequired?: (provider: string, credentialEnv: string) => void; @@ -416,10 +438,80 @@ export async function checkRebuildGatewayCredentialReuseOrBail( bail: (msg: string, code?: number) => never, deps: GatewayCredentialReusePreflightDeps = defaultGatewayCredentialReusePreflightDeps(), ): Promise { - if (config.nativeNvidiaProviderAttachment) { - return checkRebuildGatewayProviderOrBail(config.provider, config.credentialEnv, log, bail, { - nativeAttachment: config.nativeNvidiaProviderAttachment, - }); + const native = nativeHostedProfile(config.provider); + if (native) { + if ( + config.nativeHostedProviderAttachment === undefined && + config.nativeNvidiaProviderAttachment === undefined + ) { + if (hostCredentialAvailable && config.gatewayName) { + const authority = (deps.readNativeAuthority ?? registry.getNativeHostedProviderAuthority)( + config.gatewayName, + native.profileId, + ); + const providerAdapter = deps.providerAdapter ?? rebuildProviderAdapter(); + const result = await providerAdapter.getProvider({ + providerName: native.providerName, + target: { kind: "named", gatewayName: config.gatewayName }, + }); + const absent = + !result.ok && + result.error.kind === "command" && + result.error.reason === "not_found" && + !authority; + const owned = + result.ok && + authority && + authority.profileId === native.profileId && + authority.providerName === native.providerName && + authority.providerId === result.value.revision?.id && + result.value.name === native.providerName && + result.value.type === native.profileId && + result.value.configKeys.length === 0 && + result.value.credentialKeys.length === 1 && + result.value.credentialKeys[0] === native.credentialEnv; + if (absent || owned) { + const policy = await providerAdapter.ensureProviderPolicyComposition({ + target: { kind: "named", gatewayName: config.gatewayName }, + }); + if (policy.ok) return true; + bail( + "Native rebuild migration provider policy could not be activated; sandbox is untouched.", + ); + return false; + } + bail( + "Native rebuild migration target ownership could not be verified; sandbox is untouched.", + ); + return false; + } + bail("Native rebuild migration requires a host credential; sandbox is untouched."); + return false; + } + if (config.nativeNvidiaProviderAttachment) { + return checkRebuildGatewayProviderOrBail(config.provider, config.credentialEnv, log, bail, { + nativeAttachment: config.nativeNvidiaProviderAttachment, + }); + } + const expected = normalizeNativeHostedProviderAttachment(config.nativeHostedProviderAttachment); + const observed = await deps.readGatewayProviderMetadata(native.providerName); + if ( + !expected || + expected.providerName !== native.providerName || + expected.profileId !== native.profileId || + !observed || + observed.name !== native.providerName || + observed.type !== native.profileId || + observed.revision?.id !== expected.providerId || + observed.configKeys.length !== 0 || + observed.credentialKeys.length !== 1 || + observed.credentialKeys[0] !== native.credentialEnv + ) { + bail("Native inference provider identity changed or is missing; sandbox is untouched."); + return false; + } + log(`Preflight native inference: verified recorded provider '${native.providerName}'`); + return true; } if (hostCredentialAvailable || !config.provider || !config.credentialEnv) return true; const isBedrockRuntime = @@ -466,7 +558,9 @@ export async function checkRebuildGatewayCredentialReuseOrBail( recoveredPreferredInferenceApi: route?.preferredInferenceApi, expectedProviderType: remoteConfig.providerType, expectedCredentialEnv: config.credentialEnv, - gatewayProvider: await deps.readGatewayProviderMetadata(config.provider), + gatewayProvider: await deps.readGatewayProviderMetadata( + nativeHostedProfile(config.provider)?.providerName ?? config.provider, + ), endpointIdentity: endpointFlavor ? { flavor: endpointFlavor, diff --git a/src/lib/actions/sandbox/rebuild-resume-config.ts b/src/lib/actions/sandbox/rebuild-resume-config.ts index 3c7f8e4b0a6..c8ef4e6dcc2 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.ts @@ -20,7 +20,7 @@ import type { ReasoningEffort } from "../../onboard/reasoning-mode"; import type { RegistryInferenceRoute } from "../../onboard/rebuild-route-handoff"; import * as onboardSession from "../../state/onboard-session"; import type { AmbientRecreateEnvAssessment } from "./rebuild-env-isolation"; -import type { RebuildSandboxEntry } from "./rebuild-flow-helpers"; +import { resolveSandboxGatewayName, type RebuildSandboxEntry } from "./rebuild-flow-helpers"; import { assessRebuildAmbientEnv, assessRebuildInferencePreflight, @@ -46,6 +46,8 @@ const hermesProviderAuth = require("../../hermes-provider-auth") as { * from ambient selection env. */ export interface RebuildResumeConfig { + readonly gatewayName?: string; + readonly nativeHostedProviderAttachment?: import("../../inference/native-hosted").NativeHostedProviderAttachment; readonly nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; readonly agent: string | null; readonly provider: string; @@ -250,6 +252,7 @@ export function prepareRebuildResumeConfig( return null; } return { + gatewayName: resolveSandboxGatewayName(sb), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), agent: rebuildAgent, provider: trustedSelection.provider, @@ -264,7 +267,16 @@ export function prepareRebuildResumeConfig( compatibleEndpointReasoningEffort, pinEndpoint: rebuildEndpoint.known || explicitTargetEndpoint !== null, endpointUrl, - registryInferenceRoute, + registryInferenceRoute: + registryInferenceRoute && sb.nativeHostedProviderAttachment + ? { + ...registryInferenceRoute, + nativeHostedProviderAttachment: sb.nativeHostedProviderAttachment, + } + : registryInferenceRoute, + ...(sb.nativeHostedProviderAttachment + ? { nativeHostedProviderAttachment: sb.nativeHostedProviderAttachment } + : {}), ambient, }; } diff --git a/src/lib/actions/sandbox/start.test.ts b/src/lib/actions/sandbox/start.test.ts index 640616ae51c..1a6375b7f73 100644 --- a/src/lib/actions/sandbox/start.test.ts +++ b/src/lib/actions/sandbox/start.test.ts @@ -17,6 +17,8 @@ import { createRuntimeProviderBundleRegistry } from "../../onboard/runtime-provi import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { type SandboxStartDeps, startSandbox } from "./start"; +import { resolveSandboxInferenceInvocationEndpoint } from "./inference-invocation-probe"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; afterEach(() => { vi.restoreAllMocks(); @@ -639,6 +641,63 @@ describe("startSandbox native lifecycle", () => { expect(h.verifyGateway).toHaveBeenCalledOnce(); }); + it.each([ + { + provider: "openai-api", + attachmentKey: "nativeHostedProviderAttachment", + endpoint: "https://api.openai.com/v1/chat/completions", + }, + { + provider: "nvidia-prod", + attachmentKey: "nativeHostedProviderAttachment", + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + }, + { + provider: "nvidia-prod", + attachmentKey: "nativeNvidiaProviderAttachment", + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + }, + { + provider: "nvidia-prod", + attachmentKey: null, + endpoint: "https://inference.local/v1/chat/completions", + }, + ] as const)( + "probes $provider through its recorded $attachmentKey path after start", + async ({ provider, attachmentKey, endpoint }) => { + const profile = nativeHostedProfile(provider)!; + const probeInferenceInvocation = vi.fn< + NonNullable + >(async (input) => { + expect(resolveSandboxInferenceInvocationEndpoint(input)).toBe(endpoint); + return { ok: true }; + }); + const h = harness({ probeInferenceInvocation }); + h.getSandbox.mockReturnValue( + sandbox({ + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw-18080", + stopped: true, + provider, + model: provider === "nvidia-prod" ? "nvidia/nemotron-3-super-120b-a12b" : "gpt-4o", + preferredInferenceApi: "openai-completions", + ...(attachmentKey + ? { + [attachmentKey]: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "native-provider-id", + }, + } + : {}), + }), + ); + await expect(startSandbox("my-sandbox", h.deps)).resolves.toEqual({ exitCode: 0 }); + expect(probeInferenceInvocation).toHaveBeenCalledOnce(); + }, + ); + it("returns nonzero when the native gateway cannot serve an agent request", async () => { const probeInferenceInvocation = vi.fn( async () => diff --git a/src/lib/actions/sandbox/start.ts b/src/lib/actions/sandbox/start.ts index 301d559feb7..b3dd872dc1e 100644 --- a/src/lib/actions/sandbox/start.ts +++ b/src/lib/actions/sandbox/start.ts @@ -17,6 +17,7 @@ import { CURRENT_RUNTIME_PROVIDER_BUNDLES, type RuntimeProviderBundleRegistry, } from "../../onboard/runtime-provider/access"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; import type { SandboxEntry } from "../../state/registry"; import * as registry from "../../state/registry"; import { @@ -164,6 +165,11 @@ async function checkStartedSandboxInference( provider, model, preferredInferenceApi: sandbox.preferredInferenceApi ?? null, + ...(normalizeNativeHostedProviderAttachment( + sandbox.nativeHostedProviderAttachment ?? sandbox.nativeNvidiaProviderAttachment, + ) + ? { nativeProvider: true } + : {}), }; const probe = () => (deps.probeInferenceInvocation ?? probeSandboxInferenceInvocation)( diff --git a/src/lib/actions/sandbox/status-inference.test.ts b/src/lib/actions/sandbox/status-inference.test.ts index c6f72d5a9ae..7c89a9bf026 100644 --- a/src/lib/actions/sandbox/status-inference.test.ts +++ b/src/lib/actions/sandbox/status-inference.test.ts @@ -47,7 +47,7 @@ describe("sandbox status inference.local route health (#6192)", () => { } | null; routeProbeThrows?: boolean; }) { - const provider = options.provider ?? "nvidia-prod"; + const provider = options.provider ?? "custom-shared-provider"; const reportInferenceProbeError = vi.fn(); let sandbox = { name: "alpha", @@ -274,7 +274,7 @@ describe("sandbox status inference.local route health (#6192)", () => { expect(report.servingProcessHealth).toBeNull(); }); - it.each(["nvidia-router", "hermes-provider"])( + it.each(["nvidia-router", "custom-shared-provider"])( "probes inference.local for %s without a direct health probe (#6192)", async (provider) => { const deps = snapshotDeps({ @@ -297,6 +297,25 @@ describe("sandbox status inference.local route health (#6192)", () => { }, ); + it("refuses Hermes Provider without native ownership instead of probing the shared route", async () => { + const deps = snapshotDeps({ + provider: "hermes-provider", + routeHealth: { + ok: true, + endpoint: "https://inference.local/v1/models", + httpStatus: 200, + detail: "unrelated shared route reachable", + }, + }); + + const snapshot = await collectSandboxStatusSnapshot("alpha", { deps }); + + expect(snapshot.inferenceHealth).toMatchObject({ ok: false, probed: false }); + expect(deps.inferenceRouteObserver.observeInferenceRoute).not.toHaveBeenCalled(); + expect(deps.probeSandboxInferenceGatewayHealthImpl).not.toHaveBeenCalled(); + expect(deps.probeSandboxInferenceInvocationImpl).not.toHaveBeenCalled(); + }); + it("keeps an upstream failure diagnostic when inference.local is healthy (#6192)", async () => { const deps = snapshotDeps({ providerHealth: { @@ -325,7 +344,7 @@ describe("sandbox status inference.local route health (#6192)", () => { it("probes the live route while status displays the sandbox's recorded route (#6315)", async () => { const deps = snapshotDeps({ - provider: "nvidia-prod", + provider: "custom-shared-provider", liveProvider: "openai-api", liveModel: "gpt-5.2", routeHealth: { @@ -338,11 +357,11 @@ describe("sandbox status inference.local route health (#6192)", () => { const snapshot = await collectSandboxStatusSnapshot("alpha", { deps }); - expect(snapshot.currentProvider).toBe("nvidia-prod"); + expect(snapshot.currentProvider).toBe("custom-shared-provider"); expect(snapshot.currentModel).toBe("nvidia/nemotron"); expect(snapshot.routeDrift).toEqual({ live: { provider: "openai-api", model: "gpt-5.2" }, - recorded: { provider: "nvidia-prod", model: "nvidia/nemotron" }, + recorded: { provider: "custom-shared-provider", model: "nvidia/nemotron" }, canConnect: true, }); expect(deps.probeProviderHealthImpl).toHaveBeenCalledWith("openai-api", { diff --git a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts index 96e20c3891d..efb3dd63c97 100644 --- a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -605,58 +605,60 @@ describe("collectSandboxStatusSnapshot inference route health", () => { expect(snapshot.inferenceHealth?.okLabel).toBeUndefined(); }); - it.each(["openclaw", "hermes", "langchain-deepagents-code", "pi", "nemocua"])( - "reports a %s OpenRouter 404 route as ready once an invocation succeeds (#12621)", - async (agentName) => { - const gateway: SandboxInferenceRouteHealth = { - ok: true, - endpoint: "https://inference.local/v1/models", - httpStatus: 404, - detail: - "Inference gateway responded HTTP 404 on https://inference.local/v1/models (full chain reachable).", - }; + it("reports native Deep Agents Code OpenRouter ready only after a verified invocation (#10080)", async () => { + const gateway: SandboxInferenceRouteHealth = { + ok: true, + endpoint: "https://inference.local/v1/models", + httpStatus: 404, + detail: + "Inference gateway responded HTTP 404 on https://inference.local/v1/models (full chain reachable).", + }; - const options = snapshotDeps( - gateway, - null, - { ok: true }, - { - agent: agentName, - gatewayName: "nemoclaw-19080", - provider: "openrouter-api", - model: "openai/gpt-4o-mini", - }, - ); - const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: true }) as const); - const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => gateway); - const snapshot = await collectSandboxStatusSnapshot("alpha", { - ...options, - deps: { - ...options.deps, - probeSandboxInferenceGatewayHealthImpl, - probeSandboxInferenceInvocationImpl, + const options = snapshotDeps( + gateway, + null, + { ok: true }, + { + agent: "langchain-deepagents-code", + gatewayName: "nemoclaw-19080", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "owned", }, - }); + provider: "openrouter-api", + model: "openai/gpt-4o-mini", + }, + ); + const probeSandboxInferenceInvocationImpl = vi.fn(async () => ({ ok: true }) as const); + const probeSandboxInferenceGatewayHealthImpl = vi.fn(async () => gateway); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + ...options, + deps: { + ...options.deps, + verifyNativeHostedProviderAttachmentImpl: async () => undefined, + probeSandboxInferenceGatewayHealthImpl, + probeSandboxInferenceInvocationImpl, + }, + }); - expect(probeSandboxInferenceInvocationImpl).toHaveBeenCalledWith( - { - sandboxName: "alpha", - gatewayName: "nemoclaw-19080", - ...(agentName === "langchain-deepagents-code" ? { agentName } : {}), - provider: "openrouter-api", - model: "openai/gpt-4o-mini", - preferredInferenceApi: null, - }, - {}, - 95_000, - ); - expect(probeSandboxInferenceGatewayHealthImpl).toHaveBeenCalledWith("alpha", { + expect(probeSandboxInferenceInvocationImpl).toHaveBeenCalledWith( + { + sandboxName: "alpha", gatewayName: "nemoclaw-19080", - }); - expect(probeSandboxInferenceGatewayHealthImpl).toHaveBeenCalledOnce(); - expect(snapshot.inferenceHealth).toMatchObject({ ok: true }); - }, - ); + agentName: "langchain-deepagents-code", + provider: "openrouter-api", + model: "openai/gpt-4o-mini", + preferredInferenceApi: null, + nativeProvider: true, + }, + {}, + 95_000, + ); + expect(probeSandboxInferenceGatewayHealthImpl).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toMatchObject({ ok: true }); + }); it("pins Hermes status health to its recorded OpenShell gateway (#10302)", async () => { const gateway: SandboxInferenceRouteHealth = { diff --git a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts index 716f5554a94..2de70a76f80 100644 --- a/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-route-drift.test.ts @@ -16,6 +16,7 @@ import { managedLlamaCppStatePaths, reserveManagedLlamaCppOwner, } from "../../inference/llama-cpp/managed-state"; +import { NATIVE_HOSTED_PROFILES } from "../../inference/native-hosted/profiles"; import type { SandboxEntry } from "../../state/registry"; import { collectSandboxStatusSnapshot, getSandboxStatusReport } from "./status-snapshot"; @@ -479,7 +480,7 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", preferredInferenceApi: "openai-completions", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -569,6 +570,133 @@ describe("collectSandboxStatusSnapshot inference invocation route (#9302)", () = expect(snapshot.inferenceHealth).toMatchObject({ ok: true, probed: true }); }); + it.each(NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "nvidia-prod"))( + "refuses inference probes when $label attachment identity cannot be verified", + async (profile) => { + liveGatewayInference("compatible-endpoint", "unrelated/model"); + const expected = { + schemaVersion: 1 as const, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "owned-provider-id", + }; + const sandbox: SandboxEntry = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: profile.logicalProvider, + model: "selected/model", + endpointUrl: profile.endpoint, + nativeHostedProviderAttachment: expected, + }; + const invoke = vi.fn(async () => ({ ok: true }) as const); + const probeProvider = vi.fn(() => null); + const verify = vi.fn(async () => { + throw new Error("Provider identity changed"); + }); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + probeProviderHealthImpl: probeProvider, + probeSandboxInferenceInvocationImpl: invoke, + verifyNativeHostedProviderAttachmentImpl: verify, + }, + } as never); + expect(verify).toHaveBeenCalledWith( + expect.objectContaining({ + gatewayName: "nemoclaw", + sandboxName: "alpha", + expected, + }), + ); + expect(invoke).not.toHaveBeenCalled(); + expect(probeProvider).not.toHaveBeenCalled(); + expect(snapshot.routeDrift).toBeNull(); + expect(snapshot.inferenceHealth).toMatchObject({ + ok: false, + probed: false, + endpoint: profile.endpoint, + detail: expect.stringContaining("Provider identity changed"), + }); + }, + ); + + it("never falls back to a shared route when a native selection has no receipt", async () => { + const sandbox = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "openai-api", + model: "selected-model", + } as SandboxEntry; + const observe = vi.fn(async () => ({ + ok: true, + value: { state: "configured", route: { provider: "nvidia-prod", model: "unrelated" } }, + })); + const shared = vi.fn(async () => ({ + ok: true, + endpoint: "https://inference.local/v1/models", + httpStatus: 200, + detail: "healthy", + })); + const invoke = vi.fn(async () => ({ ok: true })); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + inferenceRouteObserver: { observeInferenceRoute: observe }, + probeProviderHealthImpl: () => null, + probeSandboxInferenceGatewayHealthImpl: shared, + probeSandboxInferenceInvocationImpl: invoke, + }, + } as never); + expect(observe).not.toHaveBeenCalled(); + expect(shared).not.toHaveBeenCalled(); + expect(invoke).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toMatchObject({ ok: false, probed: false }); + }); + + it("refuses a native receipt for a different recorded provider before probing", async () => { + const sandbox: SandboxEntry = { + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + provider: "anthropic-prod", + model: "selected-model", + endpointUrl: "https://api.anthropic.com", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "owned-openai-id", + }, + }; + const verify = vi.fn(async () => undefined); + const invoke = vi.fn(async () => ({ ok: true }) as const); + const probeProvider = vi.fn(() => null); + const snapshot = await collectSandboxStatusSnapshot("alpha", { + deps: { + getSandbox: () => sandbox, + listPublishedSandboxesAcrossGatewayRoots: () => [sandbox], + reconcile: async () => ({ state: "present", output: "Phase: Ready" }), + verifyNativeHostedProviderAttachmentImpl: verify, + probeProviderHealthImpl: probeProvider, + probeSandboxInferenceInvocationImpl: invoke, + }, + } as never); + expect(verify).not.toHaveBeenCalled(); + expect(invoke).not.toHaveBeenCalled(); + expect(probeProvider).not.toHaveBeenCalled(); + expect(snapshot.inferenceHealth).toMatchObject({ + ok: false, + probed: false, + detail: expect.stringContaining("does not match"), + }); + }); + it("reports a missing native NVIDIA attachment before probing inference", async () => { liveGatewayInference("compatible-endpoint", "other/model"); const sandbox = { diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 53c41e2036b..bdcb4b941b5 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -19,6 +19,8 @@ import { retryUntilAsync } from "../../core/retry"; import { withStdoutRedirectedToStderr } from "../../cli/stdout-guard"; import { getLlamaCppRouteDetails, + normalizeNativeHostedProviderAttachment, + nativeHostedProfile, NVIDIA_HOSTED_NATIVE_ENDPOINT, normalizeNativeNvidiaProviderAttachment, type GatewayInference, @@ -60,6 +62,8 @@ import { probeSandboxInferenceGatewayHealth, runSandboxInferenceInvocationProbe, verifyNativeNvidiaStatusAttachment, + verifyNativeHostedStatusAttachment, + type VerifyNativeHostedStatusAttachment, type VerifyNativeNvidiaStatusAttachment, } from "./inference-route-health"; import { @@ -333,6 +337,7 @@ interface CollectSandboxStatusSnapshotDeps { getSandboxStatusPreflightImpl?: typeof getSandboxStatusPreflight; getGatewayPresets?: GetGatewayPresets; inspectManagedLlamaCppOwnership?: typeof inspectManagedLlamaCppOwnership; + verifyNativeHostedProviderAttachmentImpl?: VerifyNativeHostedStatusAttachment; verifyNativeNvidiaProviderAttachmentImpl?: VerifyNativeNvidiaStatusAttachment; } @@ -560,18 +565,24 @@ export async function collectSandboxStatusSnapshot( (postRecoveryPreflight ?? initialPreflight)?.suppressInferenceProbe ?? opts.suppressInferenceProbe === true; const nativeNvidiaAttachment = normalizeNativeNvidiaProviderAttachment( - sb?.nativeNvidiaProviderAttachment, + sb?.nativeNvidiaProviderAttachment ?? sb?.nativeHostedProviderAttachment, ); - const nativeNvidia = Boolean(nativeNvidiaAttachment); + let liveResult: OpenShellInferenceRouteResult | null = null; let gatewayName: string | null = null; + const nativeHostedAttachment = normalizeNativeHostedProviderAttachment( + sb?.nativeHostedProviderAttachment ?? sb?.nativeNvidiaProviderAttachment, + ); + const nativeHosted = Boolean(nativeHostedProfile(sb?.provider) || nativeHostedAttachment); + const nativeAttachmentLabel = nativeNvidiaAttachment ? "Native NVIDIA" : "Native hosted"; if (lookup.state === "present") { try { gatewayName = resolveSandboxGatewayName(sb); - if (!nativeNvidia) { + if (!nativeHosted) { const observer = opts.deps?.inferenceRouteObserver ?? createCliOpenShellInferenceRouteObserver(captureOpenshellForStatus); + liveResult = await observer.observeInferenceRoute({ target: { kind: "named", gatewayName }, timeoutMs: getStatusProbeTimeoutMs(), @@ -614,33 +625,47 @@ 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) { - const expected = nativeNvidiaAttachment; - if (!gatewayName || !expected) { - nativeNvidiaAttachmentFailure = - `Native NVIDIA provider attachment is unavailable for sandbox '${sandboxName}'. ` + - "Recreate the sandbox to restore native NVIDIA inference."; + let nativeHostedAttachmentFailure: string | null = null; + if (!suppressInferenceProbe && lookup.state === "present" && nativeHosted && sb) { + const expected = nativeHostedAttachment; + if (nativeHostedProfile(sb.provider)?.profileId !== expected?.profileId) { + nativeHostedAttachmentFailure = + `Native provider attachment does not match the recorded provider for sandbox '${sandboxName}'. ` + + "Recreate the sandbox to restore native inference."; + } else if (!gatewayName || !expected) { + nativeHostedAttachmentFailure = + `${nativeAttachmentLabel} provider attachment is unavailable for sandbox '${sandboxName}'. ` + + `Recreate the sandbox to restore ${nativeNvidiaAttachment ? "native NVIDIA" : "native hosted"} inference.`; } else { try { - await verifyNativeNvidiaStatusAttachment({ - gatewayName, - sandboxName, - expected, - ...(opts.deps?.verifyNativeNvidiaProviderAttachmentImpl - ? { verify: opts.deps.verifyNativeNvidiaProviderAttachmentImpl } - : {}), - }); + if (nativeNvidiaAttachment && opts.deps?.verifyNativeNvidiaProviderAttachmentImpl) { + await verifyNativeNvidiaStatusAttachment({ + gatewayName, + sandboxName, + expected: nativeNvidiaAttachment, + verify: opts.deps.verifyNativeNvidiaProviderAttachmentImpl, + }); + } else { + await verifyNativeHostedStatusAttachment({ + gatewayName, + sandboxName, + expected, + ...(opts.deps?.verifyNativeHostedProviderAttachmentImpl + ? { verify: opts.deps.verifyNativeHostedProviderAttachmentImpl } + : {}), + }); + } } catch (error) { const detail = sanitizedStatusDetail(error); - nativeNvidiaAttachmentFailure = - `Native NVIDIA provider attachment is unavailable for sandbox '${sandboxName}'` + - `${detail ? `: ${detail}` : "."} Recreate the sandbox to restore native NVIDIA inference.`; + nativeHostedAttachmentFailure = + `${nativeAttachmentLabel} provider attachment is unavailable for sandbox '${sandboxName}'` + + `${detail ? `: ${detail}` : "."} Recreate the sandbox to restore ${nativeNvidiaAttachment ? "native NVIDIA" : "native hosted"} inference.`; } } } + const routeDriftPlan = - !nativeNvidia && sb && sb.provider && sb.model + !nativeHosted && sb && sb.provider && sb.model ? planInferenceRouteReconcile(live, { provider: sb.provider, model: sb.model }) : null; const routeDrift = @@ -671,13 +696,13 @@ export async function collectSandboxStatusSnapshot( // value to null afterwards. let providerHealth: ProviderHealthStatus | null = null; try { - providerHealth = nativeNvidiaAttachmentFailure + providerHealth = nativeHostedAttachmentFailure ? null : maybeGetSandboxStatusInferenceHealth( suppressInferenceProbe, lookup.state === "present", - nativeNvidia ? currentProvider : (live && live.provider) || currentProvider, - nativeNvidia ? currentModel : (live && live.model) || currentModel, + nativeHosted ? currentProvider : (live && live.provider) || currentProvider, + nativeHosted ? currentModel : (live && live.model) || currentModel, opts.deps?.probeProviderHealthImpl, sb?.endpointUrl, ); @@ -700,7 +725,7 @@ export async function collectSandboxStatusSnapshot( // a live model with a recorded provider and request a route neither one // describes. const invocationRoute = - !nativeNvidia && live?.provider && live.model + !nativeHosted && live?.provider && live.model ? { provider: live.provider, model: live.model, @@ -727,14 +752,14 @@ export async function collectSandboxStatusSnapshot( opts.deps?.probeSandboxInferenceGatewayHealthImpl ?? probeSandboxInferenceGatewayHealth; await retryUntilAsync( async () => { - gatewayChain = nativeNvidia + gatewayChain = nativeHosted ? null : gatewayName ? await probe(sandboxName, { gatewayName }) : null; invocation = - !nativeNvidiaAttachmentFailure && - (nativeNvidia || gatewayChain?.ok) && + !nativeHostedAttachmentFailure && + (nativeHosted || gatewayChain?.ok) && canProbeInvocation ? await runSandboxInferenceInvocationProbe( { @@ -744,7 +769,7 @@ export async function collectSandboxStatusSnapshot( provider: invocationProvider, model: invocationModel, preferredInferenceApi: invocationRoute.preferredInferenceApi, - ...(nativeNvidia ? { nativeProvider: true } : {}), + ...(nativeHosted ? { nativeProvider: true } : {}), }, opts.deps?.probeSandboxInferenceInvocationImpl, (error) => @@ -758,7 +783,7 @@ export async function collectSandboxStatusSnapshot( }, { accept: ({ gatewayChain: chain, invocation: result }) => { - if (nativeNvidia) { + if (nativeHosted) { return result?.ok === true || !isTransientInferenceInvocationFailure(result); } if (chain?.ok && (!canProbeInvocation || result?.ok)) return true; @@ -792,19 +817,20 @@ export async function collectSandboxStatusSnapshot( gatewayChain = null; invocation = null; } - inferenceHealth = nativeNvidiaAttachmentFailure + inferenceHealth = nativeHostedAttachmentFailure ? { ok: false, probed: false, - providerLabel: "Native NVIDIA provider attachment", - endpoint: NVIDIA_HOSTED_NATIVE_ENDPOINT, - detail: nativeNvidiaAttachmentFailure, + providerLabel: `${nativeAttachmentLabel} provider attachment`, + endpoint: + sb?.endpointUrl || (nativeNvidiaAttachment ? NVIDIA_HOSTED_NATIVE_ENDPOINT : ""), + detail: nativeHostedAttachmentFailure, failureLabel: "unreachable", probeLabel: "provider attachment", } : buildSandboxInferenceRouteHealth(gatewayChain, providerHealth, invocation, { provider: invocationRoute.provider ?? null, - nativeNvidia, + nativeHosted, }); } // Classify once per snapshot so every renderer observes the same receipt state. @@ -917,8 +943,11 @@ 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 nativeHosted = Boolean( + nativeHostedProfile(sb?.provider) || + normalizeNativeHostedProviderAttachment( + sb?.nativeHostedProviderAttachment ?? sb?.nativeNvidiaProviderAttachment, + ), ); return { schemaVersion: 1, @@ -929,11 +958,11 @@ async function buildSandboxStatusReport( agentRuntime: agent.agentRuntime, dcodeAutoApprovalMode: resolveSandboxStatusDcodeAutoApprovalMode(sb), ...(agent.agentLoadError ? { agentLoadError: agent.agentLoadError } : {}), - // Native NVIDIA inference is sandbox-attached and independent of the + // Native hosted 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: nativeHosted ? currentModel : (liveRoute?.model ?? currentModel), + provider: nativeHosted ? currentProvider : (liveRoute?.provider ?? currentProvider), servingProfileProvenance: sb?.servingProfileProvenance ?? null, llamaCpp, recordedRoute, diff --git a/src/lib/adapters/config/live-export-source-test-fixture.ts b/src/lib/adapters/config/live-export-source-test-fixture.ts index e9913ad9be6..07ee66863ef 100644 --- a/src/lib/adapters/config/live-export-source-test-fixture.ts +++ b/src/lib/adapters/config/live-export-source-test-fixture.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { NativeHostedProfile } from "../../inference/native-hosted/profiles"; import { createHash } from "node:crypto"; import { vi } from "vitest"; @@ -393,3 +394,101 @@ export function braveProvider() { }, }; } + +export function nativeHostedExportFixture(profile: NativeHostedProfile) { + const api = + profile.logicalProvider === "anthropic-prod" ? "anthropic-messages" : "openai-completions"; + const route = resolveManagedStartupInferenceRoute( + "openclaw", + profile.logicalProvider, + "model-a", + api, + ); + const built = buildManagedStartupProfile({ + ...startupInput, + inference: { + ...startupInput.inference, + routeProvider: route.providerKey, + upstreamProvider: profile.logicalProvider, + routedBaseUrl: route.inferenceBaseUrl, + primaryModelRef: route.primaryModelRef, + compatibility: route.inferenceCompat ?? {}, + api, + }, + }); + const sourceEntry: SandboxEntry = { + ...entry, + provider: profile.logicalProvider, + preferredInferenceApi: api, + endpointUrl: profile.endpoint, + credentialEnv: profile.hostCredentialEnv ?? profile.credentialEnv, + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "native-provider-id", + }, + workload: { + ...entry.workload, + encodedProfile: built.encodedProfile, + startupProfileSha256: built.startupProfileSha256, + }, + }; + const readCredential = vi.fn(() => { + throw new Error(readFailureCanary); + }); + const providerValue = { + ...nativeNvidiaProvider(), + metadata: { + ...nativeNvidiaProvider().metadata, + id: "native-provider-id", + name: profile.providerName, + }, + type: profile.profileId, + credentials: Object.defineProperty({}, profile.credentialEnv, { + enumerable: true, + get: readCredential, + }), + }; + const profileValue = nativeHostedProfileFixture(profile, api); + return { sourceEntry, providerValue, profileValue, readCredential }; +} + +function nativeHostedProfileFixture(profile: NativeHostedProfile, api: string) { + const url = new URL(profile.endpoint); + const prefix = url.pathname === "/" ? "/v1" : url.pathname; + return { + ...nativeNvidiaProfile(), + id: profile.profileId, + credentials: [ + { + name: "api_key", + envVars: [profile.credentialEnv] as string[], + required: true, + authStyle: api === "anthropic-messages" ? "header" : "bearer", + headerName: api === "anthropic-messages" ? "x-api-key" : "authorization", + queryParam: "", + pathTemplate: "", + }, + ], + endpoints: [ + { + ...nativeNvidiaEndpoint(), + host: url.hostname, + rules: [ + { allow: { ...emptyNativeAllow, method: "GET", path: `${prefix}/models` } }, + { + allow: { + ...emptyNativeAllow, + method: "POST", + path: `${prefix}/${api === "anthropic-messages" ? "messages" : "chat/completions"}`, + }, + }, + ...(["openai-api", "hermes-provider"].includes(profile.logicalProvider) + ? [{ allow: { ...emptyNativeAllow, method: "POST", path: `${prefix}/responses` } }] + : []), + ], + }, + ], + }; +} diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index 7e1110ba48a..19b68b3a7e0 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -7,6 +7,11 @@ import { exportLiveSource, expectExportRefusal, } from "../../../../test/support/config-export-harness"; +import { + NATIVE_HOSTED_PROFILES, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; +import { getSandboxEntryInference } from "../../state/registry-entry-view"; import { createHash } from "node:crypto"; import { describe, expect, it, vi } from "vitest"; import YAML from "yaml"; @@ -40,6 +45,7 @@ import { legacySharedNvidiaProvider, provider, configuration, + nativeHostedExportFixture, nativeNvidiaEntry, nativeNvidiaProvider, nativeNvidiaProfile, @@ -146,6 +152,25 @@ function mockNativeNvidiaSource(profileWorkspace = "default") { }); } +function mockNativeHostedSource(profile: NativeHostedProfile) { + const fixture = nativeHostedExportFixture(profile); + mockSupportedLiveSource(3, 3, fixture.sourceEntry); + vi.mocked(getSandboxEntryInference).mockReturnValue({ + kind: "configured", + provider: profile.logicalProvider, + model: "model-a", + }); + raw.getProvider.mockResolvedValue({ provider: fixture.providerValue }); + raw.getProviderProfile.mockResolvedValue({ profile: fixture.profileValue }); + raw.getSandbox.mockResolvedValue({ + sandbox: { + ...inventory().sandbox, + spec: { ...inventory().sandbox.spec, providers: [profile.providerName] }, + }, + }); + return fixture; +} + describe("live export snapshot reader", () => { it.each(["openclaw", "hermes"] as const)( "exports %s Tavily from verified SDK reads without reading credential values (#12138)", @@ -680,6 +705,112 @@ describe("live export snapshot reader", () => { }, ); + it("exports NVIDIA from the generic native hosted receipt without a shared route", async () => { + mockNativeNvidiaSource(); + const { nativeNvidiaProviderAttachment, ...rest } = nativeNvidiaEntry(); + vi.mocked(loadRegistry).mockReturnValue({ + sandboxes: { + alpha: { ...rest, nativeHostedProviderAttachment: nativeNvidiaProviderAttachment }, + }, + defaultSandbox: null, + }); + const { result, writeStdout } = await exportLiveSource(); + expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); + expect(writeStdout.mock.calls[0]?.[0]).not.toContain(readFailureCanary); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + expect(raw.getProviderProfile).toHaveBeenCalled(); + }); + + it.each( + NATIVE_HOSTED_PROFILES.filter( + (profile) => !["nvidia-prod", "gemini-api"].includes(profile.logicalProvider), + ), + )("exports native $label without shared-route or credential reads", async (profile) => { + const fixture = mockNativeHostedSource(profile); + const { result, writeStdout, publish } = await exportLiveSource(); + expect(result).toEqual({ ok: true, completion: { kind: "stdout" } }); + const yaml = writeStdout.mock.calls[0]![0]; + const document = asExportedConfig(YAML.parse(yaml)); + expect(document.spec.inferenceProviders[0]).toMatchObject({ + endpoint: profile.endpoint, + credential: { env: profile.hostCredentialEnv ?? profile.credentialEnv }, + }); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + expect(fixture.readCredential).not.toHaveBeenCalled(); + expect(yaml).not.toContain(readFailureCanary); + expect(publish).not.toHaveBeenCalled(); + }); + + it("refuses native Gemini export without shared-route or credential reads", async () => { + const profile = NATIVE_HOSTED_PROFILES.find((row) => row.logicalProvider === "gemini-api")!; + const fixture = mockNativeHostedSource(profile); + const { result, writeStdout, publish } = await exportLiveSource(); + expect(result).toMatchObject({ + ok: false, + failure: { + kind: "observation", + findings: expect.arrayContaining([ + expect.objectContaining({ + field: "spec.inferenceProviders[].provider", + category: "unsupported", + diagnostic: expect.stringContaining("V1 cannot consume this provider"), + }), + ]), + }, + }); + expect(writeStdout).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + expect(fixture.readCredential).not.toHaveBeenCalled(); + expect(JSON.stringify(result)).not.toContain(readFailureCanary); + }); + + it.each<{ + label: string; + change: (fixture: ReturnType) => void; + }>([ + { + label: "provider identity", + change: (fixture) => { + fixture.providerValue.metadata.id = "replacement"; + }, + }, + { + label: "profile host", + change: (fixture) => { + fixture.profileValue.endpoints[0]!.host = "other.example"; + }, + }, + { + label: "profile rules", + change: (fixture) => { + fixture.profileValue.endpoints[0]!.rules[1]!.allow.path = "/v1/*"; + }, + }, + { + label: "credential binding", + change: (fixture) => { + fixture.profileValue.credentials[0]!.envVars = ["OTHER_KEY"]; + }, + }, + { + label: "sandbox attachment", + change: () => { + raw.getSandbox.mockResolvedValue(inventory()); + }, + }, + ])("refuses native hosted $label drift without exporting credentials", async ({ change }) => { + const fixture = mockNativeHostedSource( + NATIVE_HOSTED_PROFILES.find((profile) => profile.logicalProvider === "openai-api")!, + ); + change(fixture); + const { result, writeStdout, publish } = await exportLiveSource(); + expect(result.ok).toBe(false); + expect(writeStdout).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); + expect(fixture.readCredential).not.toHaveBeenCalled(); + }); + it("retains the legacy shared-route NVIDIA export without a native receipt", async () => { mockSupportedLiveSource(); raw.getProvider.mockResolvedValue({ provider: legacySharedNvidiaProvider() }); diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index 1595c828cc6..0e4cb4c1d34 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -14,6 +14,8 @@ import { fingerprintOpenShellSandboxId } from "../openshell/sandbox-identity"; import { namedOpenShellGateway } from "../openshell/sandbox-observer"; import { EXPORT_REGISTRY_EVIDENCE_KEYS, + exportNativeHostedReceipt, + exportNativeHostedProfile, exportWebSearchBinding, } from "../../domain/config/export-evidence"; import type { @@ -101,6 +103,11 @@ function sandboxIdentity(row: Sandbox): ObservedExportSandboxIdentity { } async function readInferenceRoute(entry: Readonly, gatewayName: string) { + // Recognized native receipts use the native export path. Refuse an unmatched + // attachment here rather than substituting the unrelated shared gateway route. + if (entry.nativeHostedProviderAttachment) { + throw new Error("Native provider attachment export is not supported."); + } const selected = getSandboxEntryInference(entry); const observer = createSynchronousCliOpenShellInferenceRouteObserver((args, options) => captureSanitizedResolvedOpenshell(args, { @@ -173,31 +180,34 @@ function inferenceTopology( : "hosted"; } -type NativeNvidiaReceipt = NonNullable; +type NativeHostedReceipt = NonNullable>; function matchesNativeProviderMetadata( provider: Provider, - normalized: ReturnType, routeProvider: string, - receipt: NativeNvidiaReceipt, + receipt: NativeHostedReceipt, ): boolean { - return isDeepStrictEqual( - [ - provider.name, - provider.id, - provider.type, - provider.credentialKeys, - provider.configKeys, - provider.managedProfile?.id, - ], - [ - routeProvider, - receipt.providerId, - receipt.profileId, - expectedCredentialKeys(normalized.credentialEnv, routeProvider), - [], - receipt.profileId, - ], + const profile = exportNativeHostedProfile(receipt); + return ( + profile !== undefined && + isDeepStrictEqual( + [ + provider.name, + provider.id, + provider.type, + provider.credentialKeys, + provider.configKeys, + provider.managedProfile?.id, + ], + [ + routeProvider, + receipt.providerId, + receipt.profileId, + [profile.credentialEnv], + [], + receipt.profileId, + ], + ) ); } @@ -206,10 +216,10 @@ function matchesProviderMetadata( normalized: ReturnType, routeProvider: string, managed: boolean, - nativeReceipt?: NativeNvidiaReceipt, + nativeReceipt?: NativeHostedReceipt, ): boolean { if (nativeReceipt !== undefined) { - return matchesNativeProviderMetadata(provider, normalized, routeProvider, nativeReceipt); + return matchesNativeProviderMetadata(provider, routeProvider, nativeReceipt); } const { type, configKey } = providerContract(normalized.preferredInferenceApi); const builtin = provider.builtinInferenceEndpoint !== undefined; @@ -237,20 +247,22 @@ function matchesProviderMetadata( ); } -function profileContractFor( - routeProvider: string, - nativeReceipt: NativeNvidiaReceipt | undefined, -): "native-nvidia" | "openai" | undefined { - if (nativeReceipt) return "native-nvidia"; +function profileContractFor(routeProvider: string, nativeReceipt: NativeHostedReceipt | undefined) { + if (nativeReceipt) return exportNativeHostedProfile(nativeReceipt); return routeProvider === "ollama-local" ? "openai" : undefined; } function endpointSourceFor( - nativeReceipt: NativeNvidiaReceipt | undefined, + nativeReceipt: NativeHostedReceipt | undefined, builtin: boolean, configKey: "ANTHROPIC_BASE_URL" | "OPENAI_BASE_URL", ): ObservedExportEndpointEvidence["source"] { - if (nativeReceipt) return { kind: "managed-profile", profileId: nativeReceipt.profileId }; + if (nativeReceipt) { + const profile = exportNativeHostedProfile(nativeReceipt); + if (!profile) + throw new Error("The native hosted export receipt does not match a managed profile."); + return { kind: "managed-profile", profileId: profile.profileId }; + } if (builtin) return { kind: "builtin-profile", profileId: "nvidia" }; return { kind: "provider-config", key: configKey }; } @@ -261,7 +273,7 @@ async function readProviderEvidence( gatewayName: string, signal: AbortSignal, managedServing?: ObservedManagedVllmRuntime, - nativeReceipt?: NativeNvidiaReceipt, + nativeReceipt?: NativeHostedReceipt, ): Promise { const { configKey } = providerContract(normalized.preferredInferenceApi); const profileContract = profileContractFor(routeProvider, nativeReceipt); @@ -294,7 +306,7 @@ async function readProviderEvidence( async function resolveLiveInference( entry: Readonly, gatewayName: string, - nativeReceipt: NativeNvidiaReceipt | undefined, + nativeReceipt: NativeHostedReceipt | undefined, ): Promise> { if (!nativeReceipt) { const live = await readInferenceRoute(entry, gatewayName); @@ -302,7 +314,7 @@ async function resolveLiveInference( } const selected = getSandboxEntryInference(entry); if (selected.kind !== "configured") { - throw new Error("The native NVIDIA inference selection is incomplete."); + throw new Error("The native hosted inference selection is incomplete."); } return { provider: nativeReceipt.providerName, @@ -320,10 +332,9 @@ async function inferenceFor( ): Promise { const normalized = normalizeInferenceSelection(entry); const gateway = resolveGatewayBinding(entry); - const nativeReceipt = - entry.provider?.trim() === "nvidia-prod" ? entry.nativeNvidiaProviderAttachment : undefined; + const nativeReceipt = exportNativeHostedReceipt(entry); if (nativeReceipt && !sandbox.providerNames.includes(nativeReceipt.providerName)) { - throw new Error("The native NVIDIA provider is not attached to the sandbox."); + throw new Error("The native hosted provider is not attached to the sandbox."); } const live = await resolveLiveInference(entry, gateway.name, nativeReceipt); beforeRead("provider-metadata"); diff --git a/src/lib/adapters/openshell/native-nvidia-profile-response.ts b/src/lib/adapters/openshell/native-nvidia-profile-response.ts index 0b4b6d7d7da..957f1622e04 100644 --- a/src/lib/adapters/openshell/native-nvidia-profile-response.ts +++ b/src/lib/adapters/openshell/native-nvidia-profile-response.ts @@ -1,9 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -type NativeNvidiaProfileResponse = Readonly<{ +import { + NATIVE_HOSTED_PROFILES, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; + +type NativeHostedProfileResponse = Readonly<{ profile: Readonly<{ - id: "nemoclaw-nvidia-inference-v1"; + id: NativeHostedProfile["profileId"]; source: "user"; scope: "platform" | "workspace"; resourceVersion: bigint | string; @@ -33,15 +38,17 @@ function stringArrayEquals(value: unknown, expected: readonly string[]): boolean ); } -function nativeCredential(value: unknown): boolean { +function nativeCredential(value: unknown, expected: NativeHostedProfile): boolean { const credential = record(value); return ( credential !== null && credential.name === "api_key" && - stringArrayEquals(credential.envVars, ["NVIDIA_INFERENCE_API_KEY"]) && + stringArrayEquals(credential.envVars, [expected.credentialEnv]) && credential.required === true && - credential.authStyle === "bearer" && - credential.headerName === "authorization" && + credential.authStyle === + (expected.logicalProvider === "anthropic-prod" ? "header" : "bearer") && + credential.headerName === + (expected.logicalProvider === "anthropic-prod" ? "x-api-key" : "authorization") && credential.queryParam === "" && credential.pathTemplate === "" && credential.refresh === undefined && @@ -66,12 +73,24 @@ function nativeRule(value: unknown, method: "GET" | "POST", path: string): boole ); } -function nativeEndpoint(value: unknown): boolean { +function nativeEndpoint(value: unknown, expected: NativeHostedProfile): boolean { + const url = new URL(expected.endpoint); + const prefix = url.pathname === "/" ? "/v1" : url.pathname; + const expectedRules: ReadonlyArray = [ + ["GET", `${prefix}/models`], + [ + "POST", + `${prefix}/${expected.logicalProvider === "anthropic-prod" ? "messages" : "chat/completions"}`, + ], + ...(["openai-api", "hermes-provider"].includes(expected.logicalProvider) + ? [["POST", `${prefix}/responses`] as const] + : []), + ]; const endpoint = record(value); const rules = endpoint?.rules; return ( endpoint !== null && - endpoint.host === "integrate.api.nvidia.com" && + endpoint.host === url.hostname && endpoint.port === 443 && emptyArray(endpoint.ports) && endpoint.protocol === "rest" && @@ -79,9 +98,8 @@ function nativeEndpoint(value: unknown): boolean { endpoint.enforcement === "enforce" && endpoint.access === "" && Array.isArray(rules) && - rules.length === 2 && - nativeRule(rules[0], "GET", "/v1/models") && - nativeRule(rules[1], "POST", "/v1/chat/completions") && + rules.length === expectedRules.length && + expectedRules.every(([method, path], index) => nativeRule(rules[index], method, path)) && emptyArray(endpoint.allowedIps) && emptyArray(endpoint.denyRules) && endpoint.allowEncodedSlash === false && @@ -116,17 +134,19 @@ function nativeBinaries(value: unknown): boolean { } /** Verify the live custom profile at the credential, egress, and binary security boundary. */ -export function isManagedNativeNvidiaProfileResponse( +export function isManagedNativeHostedProfileResponse( value: unknown, -): value is NativeNvidiaProfileResponse { + expected: NativeHostedProfile, +): value is NativeHostedProfileResponse { const response = record(value); const profile = record(response?.profile); const revision = profile?.resourceVersion; const credentials = profile?.credentials; const endpoints = profile?.endpoints; return ( + NATIVE_HOSTED_PROFILES.includes(expected) && profile !== null && - profile.id === "nemoclaw-nvidia-inference-v1" && + profile.id === expected.profileId && profile.source === "user" && (profile.scope === "platform" || profile.scope === "workspace") && (typeof revision === "bigint" || typeof revision === "string") && @@ -135,10 +155,10 @@ export function isManagedNativeNvidiaProfileResponse( profile.discovery === undefined && Array.isArray(credentials) && credentials.length === 1 && - nativeCredential(credentials[0]) && + nativeCredential(credentials[0], expected) && Array.isArray(endpoints) && endpoints.length === 1 && - nativeEndpoint(endpoints[0]) && + nativeEndpoint(endpoints[0], expected) && nativeBinaries(profile.binaries) ); } diff --git a/src/lib/adapters/openshell/provider-adapter-cli.test.ts b/src/lib/adapters/openshell/provider-adapter-cli.test.ts index 4112374535f..6e9e120a8d7 100644 --- a/src/lib/adapters/openshell/provider-adapter-cli.test.ts +++ b/src/lib/adapters/openshell/provider-adapter-cli.test.ts @@ -989,7 +989,6 @@ describe("CLI OpenShell provider adapter", () => { ["provider", "profile", "-g", "nemoclaw", "export", "tavily", "--output", "json"], ]); }); - it.each([ [ "endpoint", @@ -1001,6 +1000,19 @@ describe("CLI OpenShell provider adapter", () => { ], }, ], + ...[ + { path_template: "/credential/{api_key}" }, + { token_grant: { token_endpoint: "https://other.example.com/token" } }, + ].map<[string, unknown]>((boundary) => [ + Object.keys(boundary).join(), + { + ...TAVILY_PROFILE, + credentials: TAVILY_PROFILE.credentials.map((credential) => ({ + ...credential, + ...boundary, + })), + }, + ]), ["binary", { ...TAVILY_PROFILE, binaries: [...TAVILY_PROFILE.binaries, "/tmp/widened"] }], [ "credential", diff --git a/src/lib/adapters/openshell/provider-profile.test.ts b/src/lib/adapters/openshell/provider-profile.test.ts index 778ab7889d3..651ecf93fbd 100644 --- a/src/lib/adapters/openshell/provider-profile.test.ts +++ b/src/lib/adapters/openshell/provider-profile.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import assert from "node:assert/strict"; import path from "node:path"; import { describe, expect, it } from "vitest"; @@ -22,6 +23,7 @@ describe("OpenShell endpointless provider profiles", () => { it.each([ ["path_template", "/v1/{credential}"], ["token_grant", { endpoint: "https://attacker.example/token" }], + ["unknown_control", true], ])("rejects an unowned exported credential control: %s (#12558)", (key, value) => { const profile = { id: "native", @@ -46,3 +48,53 @@ describe("OpenShell endpointless provider profiles", () => { expect(exportedProviderProfileMatchesContract(JSON.stringify(exported), expected!)).toBe(false); }); }); + +describe("provider credential discovery boundary", () => { + const profile = { + id: "test", + credentials: [], + endpoints: [], + binaries: [], + inference_capable: true, + }; + it.each([ + [{ credentials: [] }, true], + [{ credentials: ["foreign-source"] }, false], + [{ credentials: "invalid" }, false], + [{ credentials: [1] }, false], + ])("compares credential discovery sources [case %#]", (discovery, accepted) => { + const expected = parseCheckedInProviderProfileContract(JSON.stringify(profile)); + assert(expected, "invalid fixture"); + expect( + exportedProviderProfileMatchesContract(JSON.stringify({ ...profile, discovery }), expected), + ).toBe(accepted); + }); +}); + +describe("known credential controls", () => { + it.each([{ path_template: "" }, { token_grant: { endpoint: "https://issuer.example/token" } }])( + "accepts matching owned credential controls [case %#]", + (control) => { + const profile = { + id: "owned", + credentials: [ + { + name: "api_key", + env_vars: ["API_KEY"], + required: true, + auth_style: "bearer", + header_name: "authorization", + ...control, + }, + ], + endpoints: [], + binaries: ["/usr/bin/curl"], + inference_capable: true, + }; + const source = JSON.stringify(profile); + const expected = parseCheckedInProviderProfileContract(source); + assert(expected, "owned profile rejected"); + expect(exportedProviderProfileMatchesContract(source, expected)).toBe(true); + }, + ); +}); diff --git a/src/lib/adapters/openshell/provider-profile.ts b/src/lib/adapters/openshell/provider-profile.ts index a0f3855b7ad..9fb89719fbf 100644 --- a/src/lib/adapters/openshell/provider-profile.ts +++ b/src/lib/adapters/openshell/provider-profile.ts @@ -11,6 +11,7 @@ type ProviderProfileBoundary = Readonly<{ endpoints: readonly unknown[]; binaries: readonly string[]; inference_capable: boolean; + discovery: { credentials: readonly string[] }; }>; export type CheckedInProviderProfileContract = Readonly<{ @@ -31,6 +32,8 @@ const CREDENTIAL_KEYS = new Set([ "header_name", "name", "query_param", + "path_template", + "token_grant", "refresh", "required", ]); @@ -48,6 +51,14 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null ) { return null; } + const discovery = profile.discovery === undefined ? {} : recordValue(profile.discovery); + if ( + !discovery || + (discovery.credentials !== undefined && + (!Array.isArray(discovery.credentials) || + discovery.credentials.some((value) => typeof value !== "string"))) + ) + return null; const credentials = profile.credentials.map((value) => { const credential = recordValue(value); if ( @@ -60,7 +71,9 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null typeof credential.auth_style !== "string" || typeof credential.header_name !== "string" || (credential.query_param !== undefined && typeof credential.query_param !== "string") || - (credential.refresh !== undefined && recordValue(credential.refresh) === null) + (credential.refresh !== undefined && recordValue(credential.refresh) === null) || + (credential.path_template !== undefined && typeof credential.path_template !== "string") || + (credential.token_grant !== undefined && recordValue(credential.token_grant) === null) ) { return null; } @@ -72,6 +85,8 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null header_name: credential.header_name, query_param: credential.query_param, refresh: credential.refresh ?? null, + path_template: credential.path_template ?? "", + token_grant: credential.token_grant ?? null, }; }); if (credentials.some((credential) => credential === null)) return null; @@ -82,6 +97,7 @@ function providerProfileBoundary(value: unknown): ProviderProfileBoundary | null endpoints: profile.endpoints, binaries: profile.binaries as string[], inference_capable: profile.inference_capable, + discovery: { credentials: (discovery.credentials ?? []) as string[] }, }; } diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index ec4e0c43d91..2df25fb8119 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -24,13 +24,13 @@ import { BuiltinNvidiaProfileResponseSchema, ProviderResponseSchema, } from "./sdk-read-schema"; -import { isManagedNativeNvidiaProfileResponse } from "./native-nvidia-profile-response"; +import { isManagedNativeHostedProfileResponse } from "./native-nvidia-profile-response"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; import { - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, -} from "../../inference/native-nvidia/contract"; + NATIVE_HOSTED_PROFILES, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; import type { OpenShellProviderMetadata } from "./provider-adapter"; @@ -41,7 +41,7 @@ const managedProfileSchemas = { "tavily-hermes-v1": ManagedHermesTavilyProfileResponseSchema, }; type ManagedProfileContract = keyof typeof managedProfileSchemas; -type ProfileContract = ManagedProfileContract | "native-nvidia"; +type ProfileContract = ManagedProfileContract | NativeHostedProfile; export type Provider = Readonly< Pick & { @@ -54,7 +54,7 @@ export type Provider = Readonly< profileWorkspace?: string; // null records a successful not-found read at the OpenAI provider's profile binding. managedProfile?: Readonly<{ - id: ManagedProfileContract | typeof NVIDIA_HOSTED_NATIVE_PROFILE_ID; + id: NativeHostedProfile["profileId"]; source: "builtin" | "user"; scope: "" | "platform" | "workspace"; resourceVersion: string; @@ -96,7 +96,7 @@ async function readManagedProfile( profileWorkspace: string | undefined, ): Promise | null> { const profileId = - profileContract === "native-nvidia" ? NVIDIA_HOSTED_NATIVE_PROFILE_ID : profileContract; + typeof profileContract === "object" ? profileContract.profileId : profileContract; if ( providerType !== profileId || (profileWorkspace !== "" && profileWorkspace !== request.workspace) @@ -121,8 +121,9 @@ async function readManagedProfile( function validateNativeManagedProfileResponse( response: unknown, profileWorkspace: string, + expected: NativeHostedProfile, ): NonNullable { - if (!isManagedNativeNvidiaProfileResponse(response)) { + if (!isManagedNativeHostedProfileResponse(response, expected)) { throw new OpenShellReadError("schema"); } const profile = response.profile; @@ -141,8 +142,8 @@ function validateManagedProfileResponse( profileContract: ProfileContract, profileWorkspace: string, ): NonNullable { - if (profileContract === "native-nvidia") { - return validateNativeManagedProfileResponse(response, profileWorkspace); + if (typeof profileContract === "object") { + return validateNativeManagedProfileResponse(response, profileWorkspace, profileContract); } const { profile } = readValue(managedProfileSchemas[profileContract], response); const builtin = profile.source === "builtin"; @@ -166,9 +167,8 @@ function validateManagedProfileResponse( function managedInferenceEndpointFor( managedProfile: Provider["managedProfile"], ): string | undefined { - return managedProfile?.id === NVIDIA_HOSTED_NATIVE_PROFILE_ID - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : undefined; + return NATIVE_HOSTED_PROFILES.find((profile) => profile.profileId === managedProfile?.id) + ?.endpoint; } async function readProfileEvidence( diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 0ab2fb71aed..1329c063a69 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "ba5f7fc419ada9de012546d8bbaa7f251eb1a9075d1df82af573aaf57809cbe9", - "8bf8a0d80ec7e70687f0f696d8ff1fded3214e5858b6881a5380b4cf25faa455", + "c259c8157abddf52c2cdd4d976b1dca6f98a65a83d7a1b9e0ceba02dbec84f6a", + "c886825c5ec1a4cd4c2461b681b8439bccc18dbfc958348daadd73a4928d3c7d", ]), }); diff --git a/src/lib/credentials/provider-list.ts b/src/lib/credentials/provider-list.ts index 7c393993085..411e3208005 100644 --- a/src/lib/credentials/provider-list.ts +++ b/src/lib/credentials/provider-list.ts @@ -5,7 +5,7 @@ import { listMessagingProviderSuffixes } from "../messaging/channels"; import { NVIDIA_HOSTED_LOGICAL_PROVIDER, NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../inference/native-nvidia"; +} from "../inference/native-nvidia/contract"; const BRIDGE_PROVIDER_SUFFIXES: readonly string[] = [...listMessagingProviderSuffixes()]; diff --git a/src/lib/domain/config/export-evidence.ts b/src/lib/domain/config/export-evidence.ts index eae6be1a39e..d7ec7da7e2e 100644 --- a/src/lib/domain/config/export-evidence.ts +++ b/src/lib/domain/config/export-evidence.ts @@ -1,6 +1,34 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; +import { + NATIVE_HOSTED_PROFILES, + nativeHostedProfile, + type NativeHostedProfile, +} from "../../inference/native-hosted/profiles"; + +export function exportNativeHostedReceipt(entry: { + provider?: string | null; + nativeNvidiaProviderAttachment?: unknown; + nativeHostedProviderAttachment?: unknown; +}) { + const profile = nativeHostedProfile(entry.provider); + const receipt = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment, + ); + return receipt?.profileId === profile?.profileId ? receipt : undefined; +} + +export function exportNativeHostedProfile( + receipt: NonNullable>, +) { + return NATIVE_HOSTED_PROFILES.find( + (profile) => + profile.profileId === receipt.profileId && profile.providerName === receipt.providerName, + ); +} + import type * as TypeBoxModule from "typebox" with { "resolution-mode": "import" }; import { BoundedTextSchema, @@ -73,7 +101,9 @@ export const EXPORT_REGISTRY_EVIDENCE_KEYS = [ "messaging", "model", "name", + "nativeHostedProviderAttachment", "nativeNvidiaProviderAttachment", + "nimContainer", "observabilityEnabled", "openshellDriver", @@ -134,12 +164,7 @@ export interface ObservedExportEndpointEvidence { readonly profileWorkspace?: string; /** null means the OpenAI profile was read at its binding and confirmed absent. */ readonly managedProfile?: { - readonly id: - | "brave" - | "openai" - | "tavily" - | "tavily-hermes-v1" - | "nemoclaw-nvidia-inference-v1"; + readonly id: NativeHostedProfile["profileId"]; readonly source: "builtin" | "user"; readonly scope: "" | "platform" | "workspace"; readonly resourceVersion: string; @@ -154,7 +179,7 @@ export interface ObservedExportEndpointEvidence { | { readonly kind: "builtin-profile"; readonly profileId: "nvidia" } | { readonly kind: "managed-profile"; - readonly profileId: "nemoclaw-nvidia-inference-v1"; + readonly profileId: NativeHostedProfile["profileId"]; }; } diff --git a/src/lib/domain/config/export-source-test-fixture.ts b/src/lib/domain/config/export-source-test-fixture.ts index c37ca036b51..4780a8ef83c 100644 --- a/src/lib/domain/config/export-source-test-fixture.ts +++ b/src/lib/domain/config/export-source-test-fixture.ts @@ -110,7 +110,7 @@ export function dcodeProfileInput( routeProvider: route.providerKey, upstreamProvider: "openai-api", model: "gpt-5", - routedBaseUrl: route.inferenceBaseUrl, + routedBaseUrl: "https://inference.local/v1", upstreamEndpointUrl: endpoint, api: "openai-completions", primaryModelRef: null, diff --git a/src/lib/domain/config/verify-export-source.test.ts b/src/lib/domain/config/verify-export-source.test.ts index 82ed776d8af..688cb4b89e4 100644 --- a/src/lib/domain/config/verify-export-source.test.ts +++ b/src/lib/domain/config/verify-export-source.test.ts @@ -615,6 +615,29 @@ describe("config export source verification (#10938)", () => { }, ); + it.each([ + ["https://inference.local/v1", true], + ["https://api.openai.com/v1", false], + ] as const)( + "requires retained legacy routing or a native receipt for %s", + async (routedBaseUrl, legacy) => { + const observed = changeRetainedProfile( + hermesSnapshot({ endpointUrl: "https://api.openai.com/v1" }), + (profile) => { + profile.inference!.routedBaseUrl = routedBaseUrl; + }, + ); + const result = await exportSnapshots([observed]); + expect(result.outcome.ok).toBe(legacy); + expect(result.publish).not.toHaveBeenCalled(); + expect( + result.writeStdout.mock.calls.map( + ([yaml]) => asExportedConfig(YAML.parse(yaml)).spec.inferenceProviders[0]!.endpoint, + ), + ).toEqual(legacy ? ["https://api.openai.com/v1"] : []); + }, + ); + it("rejects a credential-bearing HTTP inference route that v1 cannot consume (#11977)", () => { const endpoint = "http://host.openshell.internal:35271/v1"; const observed = hermesSnapshot({ toolDisclosure: "progressive", endpointUrl: endpoint }); diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 3359b06659b..6da1f6bf81f 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -5,15 +5,9 @@ import type * as TypeBoxValueModule from "typebox/value" with { "resolution-mode import { isDeepStrictEqual } from "node:util"; import { cloneAndDeepFreeze } from "../../core/immutable"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { normalizeInferenceSelection } from "../../inference/selection"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; -import { - normalizeNativeNvidiaProviderAttachment, - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, -} from "../../inference/native-nvidia/contract"; import type { ManagedStartupProfile } from "../../onboard/managed-startup/profile"; import { buildManagedStartupProfile, @@ -43,7 +37,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, + exportNativeHostedReceipt, +} from "./export-evidence"; import { inspectAgentInterfaces } from "./verify-agent-interfaces"; import { V1ALPHA1_RUNTIME_DEFAULTS } from "./v1alpha1-runtime-defaults"; import type { @@ -526,7 +524,33 @@ function deepAgentsObservability( return agent === "langchain-deepagents-code" ? false : null; } -function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedStartupProfile { +function preserveLegacyExportEndpoint( + entry: ObservedExportRegistry, + inference: ReturnType, + retainedProfile: ManagedStartupProfile, +): void { + // Export verifies the retained image contract; older hosted sandboxes were + // built for the shared route and do not acquire native access by inspection. + if ( + !entry.nativeHostedProviderAttachment && + entry.provider !== "nvidia-prod" && + nativeHostedProfile(entry.provider) + ) { + const legacyEndpoint = + inference.inferenceApi === "anthropic-messages" + ? "https://inference.local" + : "https://inference.local/v1"; + if (retainedProfile.inference?.routedBaseUrl !== legacyEndpoint) { + throw new Error("Native hosted export requires its provider ownership receipt."); + } + inference.inferenceBaseUrl = legacyEndpoint; + } +} + +function expectedManagedStartupProfile( + entry: ObservedExportRegistry, + retainedProfile: ManagedStartupProfile, +): ManagedStartupProfile { if (!isSupportedExportAgent(entry.agent)) { throw new Error("The agent is unsupported."); } @@ -546,6 +570,7 @@ function expectedManagedStartupProfile(entry: ObservedExportRegistry): ManagedSt selected.model, selected.preferredInferenceApi, ); + preserveLegacyExportEndpoint(entry, inference, retainedProfile); const projection = EXPORT_AGENT_PROFILE_PROJECTIONS[agent](inference); const search = exportWebSearchBinding(entry); return buildManagedStartupProfile({ @@ -750,7 +775,7 @@ function expectedProfileWithObservedHostSettings( profile: ManagedStartupProfile, ): ManagedStartupProfile | null { try { - let expected = supportedHostProfile(profile, expectedManagedStartupProfile(entry)); + let expected = supportedHostProfile(profile, expectedManagedStartupProfile(entry, profile)); const servingPreset = profile.inference?.servingPreset; if ( expected.inference && @@ -809,39 +834,49 @@ function classifyManagedStartupProfile( return [...findings, ...classifyProfileEquality(profile, supported)]; } +function nativeEndpointEvidenceMatches(snapshot: QualifiedExportSnapshot): boolean { + const { inference } = snapshot; + const evidence = inference.endpointEvidence; + if (evidence?.source.kind !== "managed-profile") return false; + const receipt = exportNativeHostedReceipt(snapshot.registry); + const profile = nativeHostedProfile(snapshot.registry.provider); + return ( + receipt !== undefined && + profile !== undefined && + (profile.logicalProvider === "anthropic-prod" + ? inference.api === "anthropic-messages" + : inference.api === "openai-completions" || + (["openai-api", "hermes-provider"].includes(profile.logicalProvider) && + inference.api === "openai-responses")) && + isDeepStrictEqual( + [ + evidence.source.profileId, + evidence.provider.name, + evidence.provider.id, + inference.provider, + inference.endpoint, + evidence.endpoint, + inference.credentialEnv, + ], + [ + profile.profileId, + receipt.providerName, + receipt.providerId, + profile.logicalProvider, + profile.endpoint, + profile.endpoint, + profile.hostCredentialEnv ?? profile.credentialEnv, + ], + ) + ); +} + function endpointEvidenceMatchesRoute(snapshot: QualifiedExportSnapshot): boolean { const { inference } = snapshot; const evidence = inference.endpointEvidence; if (!evidence) return false; if (evidence.source.kind === "managed-profile") { - const receipt = 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, - ], - ) - ); + return nativeEndpointEvidenceMatches(snapshot); } if (evidence.source.kind === "builtin-profile") { return ( @@ -916,9 +951,7 @@ function validateSandboxIdentity( function sandboxProviderAttachmentsMatch(snapshot: QualifiedExportSnapshot): boolean { const { registry: entry, sandbox, inference } = snapshot; - const nativeReceipt = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAttachment, - ); + const nativeReceipt = exportNativeHostedReceipt(entry); const inferenceAttachment = nativeReceipt?.providerName ?? inference.provider; const additionalProviders = sandbox.providerNames.filter((name) => name !== inferenceAttachment); const webSearch = exportWebSearchBinding(entry); @@ -1237,10 +1270,7 @@ function validateInferenceRepresentation(snapshot: QualifiedExportSnapshot): Exp } function expectedEndpointProviderName(snapshot: QualifiedExportSnapshot): string { - return ( - normalizeNativeNvidiaProviderAttachment(snapshot.registry.nativeNvidiaProviderAttachment) - ?.providerName ?? snapshot.inference.provider - ); + return exportNativeHostedReceipt(snapshot.registry)?.providerName ?? snapshot.inference.provider; } function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFinding[] { @@ -1508,7 +1538,7 @@ function projectHostSettings( const proxy = authority.profile.proxy; return { ...(interfaces ? { interfaces } : {}), - ...(!hasEqualJsonStructure(proxy, expectedManagedStartupProfile(entry).proxy) + ...(!hasEqualJsonStructure(proxy, expectedManagedStartupProfile(entry, authority.profile).proxy) ? { proxy: { host: proxy.managedHost, port: proxy.managedPort } } : {}), }; diff --git a/src/lib/hermes-managed-route.ts b/src/lib/hermes-managed-route.ts index 30db5326d5c..97ad66e56fd 100644 --- a/src/lib/hermes-managed-route.ts +++ b/src/lib/hermes-managed-route.ts @@ -1,19 +1,22 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// Hermes requires an sk-prefixed value before it sends a request. OpenShell -// removes this non-secret sentinel and injects the route credential at egress. +import { OPENROUTER_DEFAULT_HEADERS } from "./inference/native-hosted/openrouter-headers.ts"; + +// Legacy shared routes use this non-secret sentinel. Native providers consume +// an issued OpenShell credential handle through a runtime environment reference. export const HERMES_PROXY_REWRITE_SENTINEL = "sk-OPENSHELL-PROXY-REWRITE"; type HermesManagedProvider = { name: string; - api_key: typeof HERMES_PROXY_REWRITE_SENTINEL; + api_key: string; discover_models: true; api?: string; base_url?: string; default_model?: string; transport?: string; api_mode?: string; + extra_headers?: Record; }; export type HermesManagedRouting = { @@ -26,7 +29,7 @@ export type HermesManagedRouting = { default: string; provider: "custom"; base_url: string; - api_key: typeof HERMES_PROXY_REWRITE_SENTINEL; + api_key: string; api_mode?: string; context_length?: number; }; @@ -40,6 +43,7 @@ export type HermesManagedRoute = { upstreamProvider: string; inferenceApi: string; contextWindow?: number | null; + credentialEnv?: string; }; function isObjectRecord(value: unknown): value is Record { @@ -76,6 +80,19 @@ export function applyHermesManagedRoute( config: Record, route: HermesManagedRoute, ): asserts config is Record & HermesManagedRouting { + if ( + route.credentialEnv !== undefined && + ![ + "NVIDIA_INFERENCE_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "OPENROUTER_API_KEY", + ].includes(route.credentialEnv) + ) { + throw new Error("Unsupported Hermes inference credential environment key."); + } + const apiKey = route.credentialEnv ? `\${${route.credentialEnv}}` : HERMES_PROXY_REWRITE_SENTINEL; const providerName = route.upstreamProvider || "nemoclaw-inference"; const providerKey = hermesProviderKey(providerName); const apiMode = hermesApiMode(route.inferenceApi); @@ -89,7 +106,7 @@ export function applyHermesManagedRoute( default: route.model, provider: "custom", base_url: route.baseUrl, - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: apiKey, }; if (apiMode) modelConfig.api_mode = apiMode; if (route.contextWindow !== null && route.contextWindow !== undefined) { @@ -100,7 +117,7 @@ export function applyHermesManagedRoute( const providerConfig: Record = { name: providerName, api: route.baseUrl, - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: apiKey, default_model: route.model, discover_models: true, }; @@ -109,10 +126,14 @@ export function applyHermesManagedRoute( const customProvider: Record = { name: providerName, base_url: route.baseUrl, - api_key: HERMES_PROXY_REWRITE_SENTINEL, + api_key: apiKey, discover_models: true, }; if (apiMode) customProvider.api_mode = apiMode; + if (route.upstreamProvider === "openrouter-api") { + providerConfig.extra_headers = Object.fromEntries(OPENROUTER_DEFAULT_HEADERS); + customProvider.extra_headers = Object.fromEntries(OPENROUTER_DEFAULT_HEADERS); + } const providers = isObjectRecord(config.providers) ? { ...config.providers } : {}; if (previousProviderKey && previousProviderKey !== providerKey) { diff --git a/src/lib/hermes-provider-auth.test.ts b/src/lib/hermes-provider-auth.test.ts index 53afa3a0a52..5a248929f1e 100644 --- a/src/lib/hermes-provider-auth.test.ts +++ b/src/lib/hermes-provider-auth.test.ts @@ -6,6 +6,7 @@ import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; +import { createNativeProviderCommandRuntime } from "../../test/support/native-provider-command-runtime"; import { afterEach, describe, expect, it, vi } from "vitest"; const require = createRequire(import.meta.url); @@ -38,16 +39,22 @@ afterEach(() => { clearSourceModule(SOURCE_BROKER); }); +const NATIVE_PROVIDER = "nemoclaw-hermes-provider-v1"; +const NATIVE_PROFILE = "nemoclaw-hermes-inference-v1"; + +function nativeRunner(initiallyExists = false) { + const runtime = createNativeProviderCommandRuntime("hermes-provider", initiallyExists); + return vi.fn( + (args: string[], _opts: { env?: Record } = {}) => + runtime.run(args) ?? { status: 0, stdout: "", stderr: "" }, + ); +} + describe("Hermes provider OpenShell credential handoff", () => { it("inspects exact OpenShell credential key bindings without exposing values", async () => { const auth = loadAuth(); - const binding = await auth.inspectHermesProviderBinding(() => ({ - status: 0, - stdout: - "Name: hermes-provider\nType: openai\nCredential keys: NOUS_API_KEY\nConfig keys: OPENAI_BASE_URL\n", - stderr: "", - })); - expect(binding).toEqual({ exists: true, credentialKeys: ["NOUS_API_KEY"] }); + const binding = await auth.inspectHermesProviderBinding(nativeRunner(true)); + expect(binding).toEqual({ exists: true, credentialKeys: ["OPENAI_API_KEY"] }); }); it("fails closed when OpenShell provider details omit credential metadata", async () => { @@ -57,26 +64,49 @@ describe("Hermes provider OpenShell credential handoff", () => { ).resolves.toEqual({ exists: true, credentialKeys: null }); }); - it("registers the OpenAI provider without a compatibility-profile mutation (#11229)", async () => { + it("registers only the owned native profile with a protected credential", async () => { const auth = loadAuth(); - const runOpenshell = vi - .fn() - .mockReturnValueOnce({ status: 1, stdout: "", stderr: "provider not found" }) - .mockReturnValueOnce({ status: 0, stdout: "", stderr: "" }); + const run = nativeRunner(); + await auth.registerHermesInferenceProvider("nous-key", run); + expect(run.mock.calls.some(([args]) => args.includes("profile"))).toBe(true); + const create = run.mock.calls.find(([args]) => args[1] === "create")!; + expect(create[0]).toEqual( + expect.arrayContaining([NATIVE_PROVIDER, NATIVE_PROFILE, "OPENAI_API_KEY"]), + ); + expect(create[1]?.env?.OPENAI_API_KEY).toBe("nous-key"); + expect(create[0].join(" ")).not.toContain("nous-key"); + }); - await auth.registerHermesInferenceProvider("nous-key", runOpenshell); + it("rejects a noncanonical endpoint before any OpenShell mutation", async () => { + const run = nativeRunner(); + await expect( + loadAuth().registerHermesInferenceProvider( + "key", + run, + "OPENAI_API_KEY", + "https://other.example/v1", + ), + ).rejects.toThrow("noncanonical"); + expect(run).not.toHaveBeenCalled(); + }); - expect(runOpenshell.mock.calls.map(([args]) => args)).toEqual([ - ["provider", "get", "hermes-provider"], - expect.arrayContaining([ - "provider", - "create", - "--name", - "hermes-provider", - "--type", - "openai", - ]), - ]); + it("refuses credential rotation when the recorded provider identity changed", async () => { + const run = nativeRunner(true); + await expect( + loadAuth().ensureHermesProviderApiKeyCredentials("alpha", { + apiKey: "new-key", + runOpenshell: run, + expected: { + schemaVersion: 1, + profileId: NATIVE_PROFILE, + providerName: NATIVE_PROVIDER, + providerId: "replaced-id", + }, + }), + ).rejects.toThrow("changed identity"); + expect(run.mock.calls.some(([args]) => args[1] === "create" || args[1] === "update")).toBe( + false, + ); }); it("registers Nous API-key inference in OpenShell without host-side persistence", async () => { @@ -86,25 +116,20 @@ describe("Hermes provider OpenShell credential handoff", () => { process.env.HOME = tmp; const auth = loadAuth(); const calls: Array<{ args: string[]; env?: Record }> = []; + const run = nativeRunner(); const state = await auth.ensureHermesProviderApiKeyCredentials("my-assistant", { apiKey: "nous-key-1", runOpenshell: (args: string[], opts: { env?: Record } = {}) => { calls.push({ args, env: opts.env }); - return args[1] === "get" - ? { - status: 1, - stdout: "", - stderr: "provider 'hermes-provider' not found", - } - : { status: 0, stdout: "", stderr: "" }; + return run(args, opts); }, }); expect(state.auth_method).toBe("api_key"); expect(state.credential_env).toBe("NOUS_API_KEY"); - expect(calls.some((call) => call.args.includes("hermes-provider"))).toBe(true); - expect(calls.some((call) => call.args.includes("NOUS_API_KEY"))).toBe(true); - expect(calls.some((call) => call.env?.NOUS_API_KEY === "nous-key-1")).toBe(true); + expect(calls.some((call) => call.args.includes(NATIVE_PROVIDER))).toBe(true); + expect(calls.some((call) => call.args.includes("OPENAI_API_KEY"))).toBe(true); + expect(calls.some((call) => call.env?.OPENAI_API_KEY === "nous-key-1")).toBe(true); expect(fs.existsSync(path.join(tmp, ".nemoclaw", "hermes-oauth"))).toBe(false); } finally { if (originalHome === undefined) delete process.env.HOME; @@ -121,6 +146,7 @@ describe("Hermes provider OpenShell credential handoff", () => { const auth = loadAuth(); const fetchCalls: Array<{ url: string; auth: string | null; body: string }> = []; const providerCalls: Array<{ args: string[]; env?: Record }> = []; + const run = nativeRunner(); const state = await auth.ensureHermesProviderOAuthCredentials("my-assistant", { allowInteractiveLogin: true, fetch: (async (url, init) => { @@ -158,7 +184,7 @@ describe("Hermes provider OpenShell credential handoff", () => { api_key: "agent-key-1", key_id: "agent-key-id", expires_in: 1800, - inference_base_url: "https://staging.nous.example/v1", + inference_base_url: "https://inference-api.nousresearch.com/v1", }), { status: 200, headers: { "Content-Type": "application/json" } }, ); @@ -167,26 +193,20 @@ describe("Hermes provider OpenShell credential handoff", () => { noBrowser: true, runOpenshell: (args: string[], opts: { env?: Record } = {}) => { providerCalls.push({ args, env: opts.env }); - return args[1] === "get" - ? { - status: 1, - stdout: "", - stderr: "provider 'hermes-provider' not found", - } - : { status: 0, stdout: "", stderr: "" }; + return run(args, opts); }, }); expect(state.auth_method).toBe("oauth"); expect(state.credential_env).toBe("OPENAI_API_KEY"); - expect(state.inference_base_url).toBe("https://staging.nous.example/v1"); + expect(state.inference_base_url).toBe("https://inference-api.nousresearch.com/v1"); expect(fetchCalls.some((call) => call.auth === "Bearer access-2")).toBe(true); expect(providerCalls.some((call) => call.env?.OPENAI_API_KEY === "agent-key-1")).toBe(true); expect( providerCalls.some((call) => - call.args.includes("OPENAI_BASE_URL=https://staging.nous.example/v1"), + call.args.includes("OPENAI_BASE_URL=https://inference-api.nousresearch.com/v1"), ), - ).toBe(true); + ).toBe(false); expect(fs.existsSync(path.join(tmp, ".nemoclaw", "hermes-oauth"))).toBe(false); } finally { if (originalHome === undefined) delete process.env.HOME; @@ -215,6 +235,7 @@ describe("Hermes provider OpenShell credential handoff", () => { }, }); const providerCalls: Array<{ args: string[]; env?: Record }> = []; + const run = nativeRunner(); const state = await auth.ensureHermesProviderOAuthCredentials("my-assistant", { allowInteractiveLogin: true, fetch: (async (url, init) => { @@ -256,13 +277,7 @@ describe("Hermes provider OpenShell credential handoff", () => { noBrowser: true, runOpenshell: (args: string[], opts: { env?: Record } = {}) => { providerCalls.push({ args, env: opts.env }); - return args[1] === "get" - ? { - status: 1, - stdout: "", - stderr: "provider 'hermes-provider' not found", - } - : { status: 0, stdout: "", stderr: "" }; + return run(args, opts); }, toolGatewayPresets: ["nous-web", "nous-audio"], }); diff --git a/src/lib/hermes-provider-auth.ts b/src/lib/hermes-provider-auth.ts index c59833a7dd8..1ca3e2f9700 100644 --- a/src/lib/hermes-provider-auth.ts +++ b/src/lib/hermes-provider-auth.ts @@ -1,6 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + ensureNativeHostedProvider, + type NativeHostedProviderAttachment, +} from "./inference/native-hosted"; +import { nativeHostedProfile } from "./inference/native-hosted/profiles"; /** * Hermes Provider credential orchestration. * @@ -72,6 +77,7 @@ export type HermesProviderCredentialState = { credential_env: string; inference_base_url: string; agent_key_expires_at?: string | null; + nativeHostedProviderAttachment: NativeHostedProviderAttachment; }; function nonEmptyString(value: unknown): string | null { @@ -88,7 +94,10 @@ function agentKeyExpiresAt(minted: oauth.AgentKeyResponse): string | null { } export function isHermesProviderRegistered(runOpenshell: RunOpenshell): Promise { - return onboardProviders.providerExistsInGateway(HERMES_PROVIDER_NAME, runOpenshell); + return onboardProviders.providerExistsInGateway( + nativeHostedProfile(HERMES_PROVIDER_NAME)!.providerName, + runOpenshell, + ); } export type HermesProviderBinding = { @@ -101,7 +110,7 @@ export async function inspectHermesProviderBinding( ): Promise { const result = await createCliOpenShellProviderAdapter({ run: runOpenshell }).getProvider({ target: { kind: "selected" }, - providerName: HERMES_PROVIDER_NAME, + providerName: nativeHostedProfile(HERMES_PROVIDER_NAME)!.providerName, }); if (!result.ok) { return result.error.kind === "command" && result.error.reason === "not_found" @@ -119,22 +128,31 @@ export async function registerHermesInferenceProvider( runOpenshell: RunOpenshell, credentialEnv = HERMES_INFERENCE_CREDENTIAL_ENV, baseUrl = oauth.DEFAULT_INFERENCE_BASE_URL, -): Promise { + expected?: NativeHostedProviderAttachment, +): Promise { const normalizedApiKey = nonEmptyString(apiKey); if (!normalizedApiKey) { throw new Error("Hermes Provider credential is empty"); } - const result = await onboardProviders.upsertProvider( - HERMES_PROVIDER_NAME, - "openai", - credentialEnv, - baseUrl, - { [credentialEnv]: normalizedApiKey }, - runOpenshell, - ); - if (!result.ok) { - throw new Error(result.message || `failed to upsert provider '${HERMES_PROVIDER_NAME}'`); + const profile = nativeHostedProfile(HERMES_PROVIDER_NAME)!; + if (baseUrl.replace(/\/+$/u, "") !== profile.endpoint) { + throw new Error( + "Hermes Provider returned a noncanonical inference endpoint; fixed native profiles cannot be repointed.", + ); + } + if ( + credentialEnv !== HERMES_INFERENCE_CREDENTIAL_ENV && + credentialEnv !== HERMES_NOUS_API_KEY_CREDENTIAL_ENV + ) { + throw new Error("Unsupported Hermes Provider credential binding"); } + return ensureNativeHostedProvider({ + adapter: createCliOpenShellProviderAdapter({ run: runOpenshell }), + target: { kind: "selected" }, + profile, + credentialValue: normalizedApiKey, + ...(expected ? { expected } : {}), + }); } export async function ensureHermesProviderOAuthCredentials( @@ -145,6 +163,7 @@ export async function ensureHermesProviderOAuthCredentials( log = console.error, fetch = undefined, noBrowser = false, + expected, baseUrl = oauth.DEFAULT_INFERENCE_BASE_URL, toolGatewayPresets = [], }: { @@ -154,6 +173,7 @@ export async function ensureHermesProviderOAuthCredentials( fetch?: typeof globalThis.fetch; noBrowser?: boolean; baseUrl?: string; + expected?: NativeHostedProviderAttachment; toolGatewayPresets?: string[]; } = {}, ): Promise { @@ -170,11 +190,12 @@ export async function ensureHermesProviderOAuthCredentials( minTtlSeconds: AGENT_KEY_MIN_TTL_SECONDS, }); const inferenceBaseUrl = minted.inference_base_url || baseUrl; - await registerHermesInferenceProvider( + const nativeHostedProviderAttachment = await registerHermesInferenceProvider( minted.api_key, runOpenshell, HERMES_INFERENCE_CREDENTIAL_ENV, inferenceBaseUrl, + expected, ); if (Array.isArray(toolGatewayPresets) && toolGatewayPresets.length > 0) { const hermesToolGateway = getHermesToolGatewayBroker(); @@ -188,6 +209,7 @@ export async function ensureHermesProviderOAuthCredentials( } } return { + nativeHostedProviderAttachment, auth_method: "oauth", provider: HERMES_PROVIDER_NAME, credential_env: HERMES_INFERENCE_CREDENTIAL_ENV, @@ -201,11 +223,13 @@ export async function ensureHermesProviderApiKeyCredentials( { apiKey = null, runOpenshell = null, + expected, baseUrl = oauth.DEFAULT_INFERENCE_BASE_URL, }: { apiKey?: string | null; runOpenshell?: RunOpenshell | null; baseUrl?: string; + expected?: NativeHostedProviderAttachment; } = {}, ): Promise { if (!runOpenshell) { @@ -214,13 +238,15 @@ export async function ensureHermesProviderApiKeyCredentials( const normalizedApiKey = nonEmptyString(apiKey); if (!normalizedApiKey) return null; - await registerHermesInferenceProvider( + const nativeHostedProviderAttachment = await registerHermesInferenceProvider( normalizedApiKey, runOpenshell, HERMES_NOUS_API_KEY_CREDENTIAL_ENV, baseUrl, + expected, ); return { + nativeHostedProviderAttachment, auth_method: "api_key", provider: HERMES_PROVIDER_NAME, credential_env: HERMES_NOUS_API_KEY_CREDENTIAL_ENV, diff --git a/src/lib/inference/README.md b/src/lib/inference/README.md index e4e17051f06..fc8e67d08fa 100644 --- a/src/lib/inference/README.md +++ b/src/lib/inference/README.md @@ -25,6 +25,38 @@ onboard-probes.ts onboarding-time inference validation probes Longer term, pure inference decisions should move under `src/lib/domain/inference/**`, and HTTP/process boundaries should move under `src/lib/adapters/**`. +## Native hosted inference + +`native-hosted/profiles.ts` maps fixed hosted selections to checked-in OpenShell provider profiles. +The supported selections are NVIDIA, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider. +Each profile restricts the upstream hostname, TLS port, request paths, and agent executables. +Credential values remain in OpenShell. Sandbox configuration contains only a placeholder credential. + +`native-hosted/index.ts` owns profile import, provider identity checks, attachment, and confirmed removal. +The registry records the selected attachment in `nativeHostedProviderAttachment`. +Credential registration also retains ownership by gateway and profile before any sandbox uses the +provider. Onboarding and inference selection reconcile those receipts with sandbox ownership before +reuse. Reset removes the selected provider's gateway receipt only after deletion is confirmed; +a failed deletion preserves it. Switching providers retains prior ownership without retaining access. +The persistence boundary also reads Slice 1's `nativeNvidiaProviderAttachment` field without changing its provider identity. +Selection does not update the shared `inference.local` route. +A switch retains `pendingNativeHostedProviderDetach` until OpenShell confirms removal of the previous attachment. +Retries complete that cleanup before applying another selection. +Existing beta sandboxes without an attachment receipt require recreation. Status, doctor, connect, +and launch readiness must refuse missing or mismatched ownership; they must not substitute the shared +route. Native probes preserve the selected API protocol and the recorded gateway. +Custom endpoints and local providers retain their existing routing behavior. +V1alpha1 configuration export supports native NVIDIA, OpenAI, Anthropic, OpenRouter, +and Hermes Provider attachments. Gemini export is refused before publication because +V1 cannot consume that provider. Exporting an older shared-route sandbox continues to +verify its original image endpoint without implicitly migrating it. + +Agent configuration preserves the provider's API protocol and native base URL. +OpenRouter attribution comes from `native-hosted/openrouter-headers.ts` and is configured in each supported agent. +Hermes authentication retains its logical OAuth or manual-key selection. +Both authentication methods store the protected native credential under `OPENAI_API_KEY` in OpenShell. +The host's unrelated OpenAI credential must never replace that Hermes credential during model selection. + ## Ollama export observations V1alpha1 configuration export currently refuses attached Ollama before publication. diff --git a/src/lib/inference/config.test.ts b/src/lib/inference/config.test.ts index f5b376f741f..1adc3dd3bbd 100644 --- a/src/lib/inference/config.test.ts +++ b/src/lib/inference/config.test.ts @@ -29,7 +29,7 @@ import { sanitizeRouteValueForDisplay, VLLM_LOCAL_CREDENTIAL_ENV, } from "./config"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia/contract"; describe("resolveAgentDefaultCloudModel", () => { it("uses the Deep Agents manifest default", () => { @@ -231,11 +231,11 @@ describe("inference selection config", () => { }); }); - it("maps the remaining hosted providers to the sandbox inference route", () => { + it("maps fixed hosted providers to their native endpoints", () => { // Full-object assertion for one hosted provider to catch structural regressions expect(getProviderSelectionConfig("openai-api", "gpt-5.4-mini")).toEqual({ endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: "https://api.openai.com/v1", ncpPartner: null, model: "gpt-5.4-mini", profile: DEFAULT_ROUTE_PROFILE, @@ -245,7 +245,7 @@ describe("inference selection config", () => { }); expect(getProviderSelectionConfig("openrouter-api", "moonshotai/kimi-k2.6")).toEqual({ endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: "https://openrouter.ai/api/v1", ncpPartner: null, model: "moonshotai/kimi-k2.6", profile: DEFAULT_ROUTE_PROFILE, @@ -271,7 +271,7 @@ describe("inference selection config", () => { }); expect(getProviderSelectionConfig("hermes-provider", "anthropic/claude-opus-4.7")).toEqual({ endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: "https://inference-api.nousresearch.com/v1", ncpPartner: null, model: "anthropic/claude-opus-4.7", profile: DEFAULT_ROUTE_PROFILE, @@ -391,6 +391,7 @@ describe("getSandboxInferenceConfig", () => { providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/nvidia/nemotron-3-super-120b-a12b`, inferenceBaseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + inferenceCredentialEnv: "NVIDIA_INFERENCE_API_KEY", inferenceApi: "openai-completions", inferenceCompat: { supportsStore: false }, }); @@ -413,6 +414,7 @@ describe("getSandboxInferenceConfig", () => { providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/moonshotai/kimi-k2.6`, inferenceBaseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + inferenceCredentialEnv: "NVIDIA_INFERENCE_API_KEY", inferenceApi: "openai-completions", inferenceCompat: { supportsStore: false }, }); @@ -436,7 +438,8 @@ describe("getSandboxInferenceConfig", () => { expect(getSandboxInferenceConfig("moonshotai/kimi-k2.6", "openrouter-api")).toEqual({ providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/moonshotai/kimi-k2.6`, - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: "https://openrouter.ai/api/v1", + inferenceCredentialEnv: "OPENROUTER_API_KEY", inferenceApi: "openai-completions", inferenceCompat: { supportsStore: false, @@ -501,7 +504,8 @@ describe("getSandboxInferenceConfig", () => { expect(getSandboxInferenceConfig("gemini-2.5-flash", "gemini-api")).toEqual({ providerKey: MANAGED_PROVIDER_ID, primaryModelRef: `${MANAGED_PROVIDER_ID}/gemini-2.5-flash`, - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", + inferenceCredentialEnv: "GEMINI_API_KEY", inferenceApi: "openai-completions", inferenceCompat: { supportsStore: false, @@ -513,7 +517,8 @@ describe("getSandboxInferenceConfig", () => { expect(getSandboxInferenceConfig("gpt-5.4", "openai-api", "openai-responses")).toEqual({ providerKey: "openai", primaryModelRef: "openai/gpt-5.4", - inferenceBaseUrl: INFERENCE_ROUTE_URL, + inferenceBaseUrl: "https://api.openai.com/v1", + inferenceCredentialEnv: "OPENAI_API_KEY", inferenceApi: "openai-responses", inferenceCompat: null, }); diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index 7415409dde8..072f31f6d9a 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -13,27 +13,33 @@ import { LLAMA_CPP_HOST_OPENAI_BASE_URL, LLAMA_CPP_PROVIDER_NAME, } from "./llama-cpp/contract"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; +import { nativeHostedProfile, NATIVE_HOSTED_PROFILES } from "./native-hosted/profiles"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia/contract"; import type { ManagedLlamaCppOwnership } from "./llama-cpp/managed-state"; import { DEFAULT_OLLAMA_MODEL_TAG as DEFAULT_OLLAMA_MODEL } from "./ollama-model-registry"; import { OLLAMA_LOCAL_CREDENTIAL_ENV } from "./ollama/contract"; import { OPENROUTER_CREDENTIAL_ENV, OPENROUTER_PROVIDER_NAME } from "./openrouter"; import { VLLM_LOCAL_CREDENTIAL_ENV } from "./serving/vllm-credential-contract"; -export { isSafeModelId }; +export { isSafeModelId, nativeHostedProfile }; +export { OPENROUTER_DEFAULT_HEADERS } from "./native-hosted/openrouter-headers"; export { OLLAMA_LOCAL_CREDENTIAL_ENV }; export { - detachNativeNvidiaProvider, - ensureNativeNvidiaProvider, - ensureNativeNvidiaProviderAttached, + detachNativeHostedProvider, + ensureNativeHostedProvider, + persistNativeHostedProviderAuthority, + ensureNativeHostedProviderAttached, + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, +} from "./native-hosted"; +export type { NativeHostedProviderAttachment } from "./native-hosted"; +export { isNativeNvidiaProvider, NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_ENDPOINT, normalizeNativeNvidiaProviderAttachment, - persistNativeNvidiaProviderAuthority, - resolveGatewayNativeNvidiaProviderAuthority, -} from "./native-nvidia"; -export type { NativeNvidiaProviderAttachment } from "./native-nvidia"; +} from "./native-nvidia/contract"; +export type { NativeNvidiaProviderAttachment } from "./native-nvidia/contract"; export const INFERENCE_ROUTE_URL = "https://inference.local/v1"; export const NOUS_RECOMMENDED_MODELS_URL = @@ -185,6 +191,7 @@ export interface SandboxInferenceConfig { inferenceBaseUrl: string; inferenceApi: string; inferenceCompat: Record | null; + inferenceCredentialEnv?: string; } /** @@ -212,7 +219,7 @@ export function getProviderSelectionConfig( ): ProviderSelectionConfig | null { const base: Omit = { endpointType: "custom", - endpointUrl: INFERENCE_ROUTE_URL, + endpointUrl: nativeHostedProfile(provider)?.endpoint ?? INFERENCE_ROUTE_URL, ncpPartner: null, profile: DEFAULT_ROUTE_PROFILE, provider, @@ -407,7 +414,17 @@ export function getSandboxInferenceConfig( break; } - return { providerKey, primaryModelRef, inferenceBaseUrl, inferenceApi, inferenceCompat }; + inferenceBaseUrl = nativeHostedProfile(provider)?.endpoint ?? inferenceBaseUrl; + return { + providerKey, + primaryModelRef, + inferenceBaseUrl, + inferenceApi, + inferenceCompat, + ...(nativeHostedProfile(provider) + ? { inferenceCredentialEnv: nativeHostedProfile(provider)!.credentialEnv } + : {}), + }; } /** @@ -498,3 +515,12 @@ export function formatInferenceRouteDriftForDisplay( warning: `gateway inference route (${liveProvider}/${liveModel}) differs from the recorded route ${owner} (${recordedRoute}).`, }; } + +export { + resolveGatewayNativeHostedProviderAuthority, + retainNativeHostedProviderAuthority, +} from "./native-hosted/authority"; + +export function isNativeHostedCredentialReference(value: unknown): boolean { + return NATIVE_HOSTED_PROFILES.some((profile) => value === `\${${profile.credentialEnv}}`); +} diff --git a/src/lib/inference/gateway-route-compatibility.ts b/src/lib/inference/gateway-route-compatibility.ts index 9505a1764c4..91de8c2bc33 100644 --- a/src/lib/inference/gateway-route-compatibility.ts +++ b/src/lib/inference/gateway-route-compatibility.ts @@ -8,8 +8,8 @@ import type { SandboxEntry } from "../state/registry"; export { nativeInferenceProviderForSandbox, - normalizeNativeNvidiaProviderAttachment, -} from "./native-nvidia"; + normalizeNativeHostedProviderAttachment, +} from "./native-hosted"; export type GatewayInferenceRoute = Pick< SandboxEntry, diff --git a/src/lib/inference/managed-dcode/identity.ts b/src/lib/inference/managed-dcode/identity.ts index 211cb7472e8..4545bc88c16 100644 --- a/src/lib/inference/managed-dcode/identity.ts +++ b/src/lib/inference/managed-dcode/identity.ts @@ -4,7 +4,7 @@ export const OPENROUTER_ENDPOINT_URL = "https://openrouter.ai/api/v1"; export const OPENROUTER_PROVIDER_NAME = "openrouter-api"; -export type ManagedDcodeProvider = "openai" | "openrouter"; +export type ManagedDcodeProvider = "openai" | "openrouter" | "anthropic"; export type ManagedDcodeIdentity = { provider: ManagedDcodeProvider; @@ -41,7 +41,7 @@ export function normalizeManagedDcodeEndpointUrl( export function normalizeManagedDcodeModelName(model: string): string { const trimmed = model.trim(); - for (const prefix of ["openai:", "openrouter:"]) { + for (const prefix of ["openai:", "openrouter:", "anthropic:"]) { if (trimmed.startsWith(prefix)) return trimmed.slice(prefix.length); } return trimmed; @@ -69,11 +69,13 @@ export function resolveManagedDcodeIdentity( ): ManagedDcodeIdentity { const providerName = upstreamProvider?.trim(); const provider = - providerName === "openrouter" || - providerName === OPENROUTER_PROVIDER_NAME || - (providerName === "compatible-endpoint" && isOpenRouterEndpointUrl(upstreamEndpointUrl)) - ? "openrouter" - : "openai"; + providerName === "anthropic-prod" + ? "anthropic" + : providerName === "openrouter" || + providerName === OPENROUTER_PROVIDER_NAME || + (providerName === "compatible-endpoint" && isOpenRouterEndpointUrl(upstreamEndpointUrl)) + ? "openrouter" + : "openai"; const normalizedModel = normalizeManagedDcodeModelName(model); return { provider, diff --git a/src/lib/inference/native-hosted/authority.test.ts b/src/lib/inference/native-hosted/authority.test.ts new file mode 100644 index 00000000000..af5c1ab2be1 --- /dev/null +++ b/src/lib/inference/native-hosted/authority.test.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { NATIVE_HOSTED_PROFILES } from "./profiles"; +import { + normalizeNativeHostedProviderAuthorities, + resolveGatewayNativeHostedProviderAuthority, + retainNativeHostedProviderAuthority, +} from "./authority"; + +const [nvidia, openai] = NATIVE_HOSTED_PROFILES; +const nvidiaReceipt = { + schemaVersion: 1 as const, + profileId: nvidia.profileId, + providerName: nvidia.providerName, + providerId: "nvidia-id", +}; +const openaiReceipt = { + schemaVersion: 1 as const, + profileId: openai.profileId, + providerName: openai.providerName, + providerId: "openai-id", +}; + +describe("native hosted provider ownership", () => { + it("retains each vendor identity across a provider round trip", () => { + const receipts = retainNativeHostedProviderAuthority( + retainNativeHostedProviderAuthority([nvidiaReceipt], openaiReceipt), + nvidiaReceipt, + ); + expect(receipts).toEqual([nvidiaReceipt, openaiReceipt]); + expect( + resolveGatewayNativeHostedProviderAuthority({ + profile: nvidia, + gatewayName: "alpha", + recordedGatewayName: "alpha", + gatewayAuthority: nvidiaReceipt, + }), + ).toEqual(nvidiaReceipt); + }); + + it.each(["beta", undefined])( + "does not use explicit proof from gateway %s", + (recordedGatewayName) => { + expect( + resolveGatewayNativeHostedProviderAuthority({ + profile: nvidia, + gatewayName: "alpha", + recordedGatewayName, + recordedAttachment: nvidiaReceipt, + }), + ).toBeUndefined(); + }, + ); + it("uses the registered gateway ownership", () => { + const current = { ...openaiReceipt, providerId: "new-registration" }; + expect( + resolveGatewayNativeHostedProviderAuthority({ + profile: openai, + gatewayName: "alpha", + gatewayAuthority: current, + }), + ).toEqual(current); + }); + + it("refuses conflicting identities even when the current sandbox has a receipt", () => { + expect(() => + resolveGatewayNativeHostedProviderAuthority({ + profile: nvidia, + gatewayName: "alpha", + recordedGatewayName: "alpha", + recordedAttachment: nvidiaReceipt, + gatewayAuthority: { ...nvidiaReceipt, providerId: "replacement" }, + }), + ).toThrow("Conflicting"); + }); + it.each([null, {}, [null], [{ ...openaiReceipt, profileId: "user-owned" }]])( + "rejects malformed ownership state %j", + (value) => { + expect(() => normalizeNativeHostedProviderAuthorities(value)).toThrow("Invalid"); + }, + ); +}); diff --git a/src/lib/inference/native-hosted/authority.ts b/src/lib/inference/native-hosted/authority.ts new file mode 100644 index 00000000000..befc095eb4c --- /dev/null +++ b/src/lib/inference/native-hosted/authority.ts @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + NativeHostedProviderError, + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "./contract"; +import type { NativeHostedProfile } from "./profiles"; + +/** Retained receipts prove ownership even while another provider is selected. */ +export function normalizeNativeHostedProviderAuthorities( + value: unknown, +): NativeHostedProviderAttachment[] | undefined { + if (value === undefined) return undefined; + if (!Array.isArray(value)) + throw new NativeHostedProviderError("Invalid native provider ownership receipts."); + const receipts = new Map(); + for (const raw of value) { + const receipt = normalizeNativeHostedProviderAttachment(raw); + if (!receipt) throw new NativeHostedProviderError("Invalid native provider ownership receipt."); + const previous = receipts.get(receipt.profileId); + if (previous && previous.providerId !== receipt.providerId) { + throw new NativeHostedProviderError( + "Conflicting native provider ownership receipts. No provider was changed.", + ); + } + receipts.set(receipt.profileId, receipt); + } + return [...receipts.values()]; +} + +export function retainNativeHostedProviderAuthority( + previous: unknown, + receipt?: NativeHostedProviderAttachment, +): NativeHostedProviderAttachment[] { + return normalizeNativeHostedProviderAuthorities([ + ...(normalizeNativeHostedProviderAuthorities(previous) ?? []), + ...(receipt ? [receipt] : []), + ])!; +} + +export function resolveGatewayNativeHostedProviderAuthority(input: { + profile: NativeHostedProfile; + gatewayName: string; + gatewayAuthority?: unknown; + recordedGatewayName?: string | null; + recordedAttachment?: NativeHostedProviderAttachment; +}): NativeHostedProviderAttachment | undefined { + const receipts: NativeHostedProviderAttachment[] = []; + const collect = (raw: unknown) => { + const receipt = normalizeNativeHostedProviderAttachment(raw); + if (receipt?.profileId === input.profile.profileId) receipts.push(receipt); + }; + collect(input.gatewayAuthority); + if (input.recordedGatewayName === input.gatewayName) { + collect(input.recordedAttachment); + } + // Only the selected sandbox's active attachment may corroborate the gateway + // identity. Peer and retained receipts describe earlier selections, so they + // cannot establish ownership or veto a newly registered gateway provider. + return normalizeNativeHostedProviderAuthorities(receipts)?.[0]; +} diff --git a/src/lib/inference/native-hosted/contract.ts b/src/lib/inference/native-hosted/contract.ts new file mode 100644 index 00000000000..ea410bde666 --- /dev/null +++ b/src/lib/inference/native-hosted/contract.ts @@ -0,0 +1,44 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { NATIVE_HOSTED_PROFILES } from "./profiles"; + +export type NativeHostedProviderAttachment = Readonly<{ + schemaVersion: 1; + profileId: string; + providerName: string; + providerId: string; +}>; + +export class NativeHostedProviderError extends Error { + constructor(message: string) { + super(message); + this.name = "NativeHostedProviderError"; + } +} + +export function normalizeNativeHostedProviderAttachment( + value: unknown, +): NativeHostedProviderAttachment | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const receipt = value as Record; + const profile = NATIVE_HOSTED_PROFILES.find( + (entry) => entry.profileId === receipt.profileId && entry.providerName === receipt.providerName, + ); + if (!profile) return undefined; + if ( + receipt.schemaVersion !== 1 || + receipt.profileId !== profile.profileId || + receipt.providerName !== profile.providerName || + typeof receipt.providerId !== "string" || + !receipt.providerId.trim() + ) { + return undefined; + } + return { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: receipt.providerId, + }; +} diff --git a/src/lib/inference/native-hosted/index.test.ts b/src/lib/inference/native-hosted/index.test.ts new file mode 100644 index 00000000000..1ede9e2ce48 --- /dev/null +++ b/src/lib/inference/native-hosted/index.test.ts @@ -0,0 +1,622 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import { describe, expect, it, vi } from "vitest"; + +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; +import { parseCheckedInProviderProfileContract } from "../../adapters/openshell/provider-profile"; +import { + ensureNativeHostedProvider, + persistNativeHostedProviderAuthority, + ensureNativeHostedProviderAttached, + nativeHostedProviderProfilePath, + NativeHostedProviderError, + verifyNativeHostedProviderAttachment, +} from "./index"; + +import { NATIVE_HOSTED_PROFILES } from "./profiles"; + +const target = { kind: "named", gatewayName: "nemoclaw" } as const; + +describe.each(NATIVE_HOSTED_PROFILES)("native $label OpenShell provider", (profile) => { + function metadata(overrides: Record = {}) { + return { + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], + configKeys: [], + revision: { id: "provider-id", resourceVersion: 1 }, + ...overrides, + }; + } + + function adapter(overrides: Partial = {}): OpenShellProviderAdapter { + return { + ensureProviderPolicyComposition: vi.fn< + OpenShellProviderAdapter["ensureProviderPolicyComposition"] + >(async () => ({ ok: true, value: undefined })), + importProviderProfile: vi.fn(() => ({ ok: true })), + getProvider: vi.fn(async () => ({ ok: true, value: metadata() })), + createProvider: vi.fn(async () => ({ ok: true })), + updateProvider: vi.fn(async () => ({ ok: true })), + listProviderAttachments: vi.fn(async () => ({ + ok: true, + value: { names: [profile.providerName] }, + })), + listProviders: vi.fn(), + inspectProviderProfile: vi.fn(), + deleteProvider: vi.fn(), + detachProvider: vi.fn(async () => ({ ok: true })), + attachProvider: vi.fn(async () => ({ ok: true })), + configureProviderRefresh: vi.fn(), + getProviderRefreshStatus: vi.fn(), + ...overrides, + } as OpenShellProviderAdapter; + } + + it.each(["create", "update", "reuse"])( + "refuses %s when provider policy activation fails", + async (operation) => { + const providerAdapter = adapter({ + ensureProviderPolicyComposition: vi.fn(async () => ({ + ok: false as const, + error: { + kind: "command" as const, + reason: "failed" as const, + message: "policy unavailable", + }, + })), + }); + vi.mocked(providerAdapter.getProvider).mockResolvedValue( + operation === "create" + ? { ok: false, error: { kind: "command", reason: "not_found", message: "missing" } } + : { ok: true, value: metadata() }, + ); + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: operation === "reuse" ? null : "test-host-credential", + expected: + operation === "create" + ? undefined + : { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/policy/); + expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); + expect(providerAdapter.createProvider).not.toHaveBeenCalled(); + }, + ); + + it.each([verifyNativeHostedProviderAttachment, ensureNativeHostedProviderAttached])( + "refuses a widened profile before observing or attaching a provider (%s)", + async (operation) => { + const providerAdapter = adapter({ + importProviderProfile: vi.fn(() => ({ + ok: false, + error: { kind: "command", reason: "profile_incompatible", message: "wider live profile" }, + })), + }); + await expect( + operation({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/); + expect(providerAdapter.getProvider).not.toHaveBeenCalled(); + expect(providerAdapter.listProviderAttachments).not.toHaveBeenCalled(); + expect(providerAdapter.attachProvider).not.toHaveBeenCalled(); + }, + ); + + it("limits the profile to its fixed TLS endpoint and exact executable paths (#12589)", () => { + const source = fs.readFileSync(nativeHostedProviderProfilePath(profile), "utf8"); + const contract = parseCheckedInProviderProfileContract(source); + + expect(contract?.profileId).toBe(profile.profileId); + expect(contract?.boundary.endpoints).toHaveLength(1); + expect(contract?.boundary.endpoints[0]).toMatchObject({ + host: new URL(profile.endpoint).hostname, + port: 443, + enforcement: "enforce", + }); + expect(contract?.boundary.binaries).not.toEqual( + expect.arrayContaining([expect.stringMatching(/[?*]/u)]), + ); + }); + + it("removes a new provider when authority persistence fails (#12562)", async () => { + let providerPresent = true; + const getProvider = vi.fn(async () => + providerPresent + ? { ok: true, value: metadata() } + : { + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }, + ); + const deleteProvider = vi.fn(async () => { + providerPresent = false; + return { ok: true }; + }); + const receipt = { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + } as const; + + await expect( + persistNativeHostedProviderAuthority({ + profile, + adapter: adapter({ getProvider, deleteProvider }), + target, + gatewayName: "nemoclaw", + receipt, + readAuthority: () => undefined, + writeAuthority: () => { + throw new Error("state directory is read-only"); + }, + }), + ).rejects.toThrow(/newly created provider was removed.*state directory is read-only/su); + expect(deleteProvider).toHaveBeenCalledExactlyOnceWith({ + target, + providerName: profile.providerName, + }); + }); + + it("keeps a provider when a failed write persisted its authority (#12562)", async () => { + const receipt = { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + } as const; + let authority: + | Parameters[0]["receipt"] + | undefined; + const deleteProvider = vi.fn(); + + await expect( + persistNativeHostedProviderAuthority({ + profile, + adapter: adapter({ deleteProvider }), + target, + gatewayName: "nemoclaw", + receipt, + readAuthority: () => authority, + writeAuthority: (_gatewayName, value) => { + authority = value; + throw new Error("directory sync failed"); + }, + }), + ).resolves.toBeUndefined(); + expect(deleteProvider).not.toHaveBeenCalled(); + }); + + it("refuses cleanup when the provider identity changed after a failed write (#12562)", async () => { + const deleteProvider = vi.fn(); + + await expect( + persistNativeHostedProviderAuthority({ + profile, + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ + revision: { id: "replacement-id", resourceVersion: 2 }, + }), + })), + deleteProvider, + }), + target, + gatewayName: "nemoclaw", + receipt: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + readAuthority: () => undefined, + writeAuthority: () => { + throw new Error("state directory is read-only"); + }, + }), + ).rejects.toThrow(/credentials reset .*.*identity changed/su); + expect(deleteProvider).not.toHaveBeenCalled(); + }); + + it("refuses a receipt for another profile before mutation (#12589)", async () => { + const other = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.profileId !== profile.profileId, + )!; + const providerAdapter = adapter(); + const expected = { + schemaVersion: 1 as const, + profileId: other.profileId, + providerName: other.providerName, + providerId: "provider-id", + }; + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-secret", + expected, + }), + ).rejects.toThrow("does not match the selected profile"); + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected, + }), + ).rejects.toThrow("does not match the selected profile"); + expect(providerAdapter.importProviderProfile).not.toHaveBeenCalled(); + expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); + expect(providerAdapter.attachProvider).not.toHaveBeenCalled(); + }); + + it("refuses to attach a replacement provider before mutation (#12589)", async () => { + const providerAdapter = adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ revision: { id: "replacement", resourceVersion: 2 } }), + })), + listProviderAttachments: vi.fn( + async () => ({ ok: true, value: { names: [] } }), + ), + }); + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "original", + }, + }), + ).rejects.toThrow("changed identity before attachment"); + expect(providerAdapter.attachProvider).not.toHaveBeenCalled(); + expect(providerAdapter.detachProvider).not.toHaveBeenCalled(); + }); + + it("rejects provider replacement observed after credential update (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: metadata() }) + .mockResolvedValueOnce({ + ok: true, + value: metadata({ revision: { id: "replacement", resourceVersion: 1 } }), + }); + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ getProvider }), + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow("changed identity during its credential update"); + }); + + it("refuses an existing provider without recorded ownership (#12589)", async () => { + const providerAdapter = adapter(); + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + }), + ).rejects.toThrow("without a matching NemoClaw ownership receipt"); + expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); + expect(providerAdapter.createProvider).not.toHaveBeenCalled(); + }); + + it("does not claim an ambiguous credential update succeeded (#12589)", async () => { + const providerAdapter = adapter({ + updateProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "timeout", message: "timed out" }, + })), + }); + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow("accepted its credential update"); + expect(providerAdapter.updateProvider).toHaveBeenCalledOnce(); + expect(providerAdapter.getProvider).toHaveBeenCalledOnce(); + expect(providerAdapter.attachProvider).not.toHaveBeenCalled(); + }); + + it("creates the internal provider once and records its immutable identity (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: true, + })); + const providerAdapter = adapter({ getProvider, createProvider }); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + }), + ).resolves.toEqual({ + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }); + expect(createProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + name: profile.providerName, + type: profile.profileId, + credentials: [{ name: profile.credentialEnv, value: "opaque-test-secret" }], + config: [], + }), + ); + }); + + it("observes an ambiguous create result without issuing a second mutation (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: false, + error: { kind: "timeout", message: "timed out" }, + })); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ getProvider, createProvider }), + target, + credentialValue: "opaque-test-secret", + }), + ).resolves.toMatchObject({ providerId: "provider-id" }); + expect(createProvider).toHaveBeenCalledOnce(); + }); + + it("creates from an existing gateway credential when recreation has no local key (#12589)", async () => { + const getProvider = vi + .fn() + .mockResolvedValueOnce({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + }) + .mockResolvedValueOnce({ ok: true, value: metadata() }); + const createProvider = vi.fn(async () => ({ + ok: true, + })); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ getProvider, createProvider }), + target, + credentialValue: null, + reuseExistingCredential: true, + }), + ).resolves.toMatchObject({ providerId: "provider-id" }); + expect(createProvider).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + name: profile.providerName, + credentials: [], + fromExisting: true, + }), + ); + }); + + it("refuses a replaced provider before rotating its credential (#12589)", async () => { + const updateProvider = vi.fn(); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: true, + value: metadata({ revision: { id: "replacement-id", resourceVersion: 1 } }), + })), + updateProvider, + }), + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "recorded-id", + }, + }), + ).rejects.toThrow(/changed identity.*No provider was changed/u); + expect(updateProvider).not.toHaveBeenCalled(); + }); + + it("refuses to replace a recorded provider that is missing (#12589)", async () => { + const createProvider = vi.fn(); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: adapter({ + getProvider: vi.fn(async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "not found" }, + })), + createProvider, + }), + target, + credentialValue: "opaque-test-secret", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "recorded-id", + }, + }), + ).rejects.toThrow(/is missing.*No provider was changed/u); + expect(createProvider).not.toHaveBeenCalled(); + }); + + it("fails before provider mutation when the profile collides (#12589)", async () => { + const createProvider = vi.fn(); + const providerAdapter = adapter({ + importProviderProfile: vi.fn(() => ({ + ok: false, + error: { + kind: "command", + reason: "profile_incompatible", + message: "different profile", + }, + })), + createProvider, + }); + + await expect( + ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, + target, + credentialValue: "opaque-test-secret", + }), + ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); + expect(createProvider).not.toHaveBeenCalled(); + }); + + it("requires the exact provider attachment before native inference is published (#12589)", async () => { + const providerAdapter = adapter({ + listProviderAttachments: vi.fn( + async () => ({ ok: true, value: { names: [] } }), + ), + }); + + await expect( + verifyNativeHostedProviderAttachment({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + }), + ).rejects.toThrow(NativeHostedProviderError); + await expect( + verifyNativeHostedProviderAttachment({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + }), + ).rejects.toThrow(/does not have its native .* inference provider attached/u); + }); + + it("removes a newly attached provider when attachment verification fails (#12589)", async () => { + const listProviderAttachments = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }); + const detachProvider = vi.fn(async () => ({ + ok: true, + value: { changed: true }, + })); + const providerAdapter = adapter({ listProviderAttachments, detachProvider }); + + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: providerAdapter, + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow(/does not have its native .* inference provider attached/u); + expect(detachProvider).toHaveBeenCalledExactlyOnceWith({ + target, + sandboxName: "alpha", + providerName: profile.providerName, + }); + }); + + it("preserves verification and cleanup failures after a new attachment (#12589)", async () => { + const listProviderAttachments = vi + .fn() + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ ok: true, value: { names: [] } }) + .mockResolvedValueOnce({ + ok: true, + value: { names: [profile.providerName] }, + }); + + await expect( + ensureNativeHostedProviderAttached({ + profile, + adapter: adapter({ listProviderAttachments }), + target, + sandboxName: "alpha", + expected: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-id", + }, + }), + ).rejects.toThrow( + /does not have its native .* inference provider attached[\s\S]*did not confirm removal/u, + ); + }); +}); diff --git a/src/lib/inference/native-hosted/index.ts b/src/lib/inference/native-hosted/index.ts new file mode 100644 index 00000000000..f43bb50f846 --- /dev/null +++ b/src/lib/inference/native-hosted/index.ts @@ -0,0 +1,500 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import path from "node:path"; + +import type { + OpenShellGatewayTarget, + OpenShellProviderAdapter, + OpenShellProviderError, + OpenShellProviderMetadata, +} from "../../adapters/openshell/sandbox-observer"; +import { REPOSITORY_ROOT } from "../../core/repository-root"; + +import { NATIVE_HOSTED_PROFILES, nativeHostedProfile, type NativeHostedProfile } from "./profiles"; + +import { NativeHostedProviderError, type NativeHostedProviderAttachment } from "./contract"; +export { + NativeHostedProviderError, + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "./contract"; +export { + resolveGatewayNativeHostedProviderAuthority, + retainNativeHostedProviderAuthority, +} from "./authority"; + +export function nativeHostedProviderProfilePath( + profile: NativeHostedProfile, + root = REPOSITORY_ROOT, +): string { + return path.join(root, "managed-inference", "provider-profiles", `${profile.profileId}.yaml`); +} + +export function isNativeHostedProvider(provider: string | null | undefined): boolean { + return nativeHostedProfile(provider) !== undefined; +} + +export function nativeInferenceProviderForSandbox( + provider: string | null | undefined, +): string | null { + const normalized = provider?.trim() || null; + return nativeHostedProfile(normalized)?.providerName ?? normalized; +} + +function assertExpectedProfile( + profile: NativeHostedProfile, + expected?: NativeHostedProviderAttachment, +): void { + if ( + expected && + (expected.profileId !== profile.profileId || expected.providerName !== profile.providerName) + ) { + throw new NativeHostedProviderError( + "Recorded native provider identity does not match the selected profile. No provider was changed.", + ); + } +} + +function providerErrorDetail(error: OpenShellProviderError): string { + return error.message.trim() || "OpenShell did not provide a diagnostic."; +} + +function exactNativeProvider( + metadata: OpenShellProviderMetadata, + profile: NativeHostedProfile, +): boolean { + return ( + metadata.name === profile.providerName && + metadata.type === profile.profileId && + metadata.configKeys.length === 0 && + metadata.credentialKeys.length === 1 && + metadata.credentialKeys[0] === profile.credentialEnv && + Boolean(metadata.revision?.id) + ); +} + +function attachmentFromMetadata( + metadata: OpenShellProviderMetadata, + profile: NativeHostedProfile, +): NativeHostedProviderAttachment { + if (!exactNativeProvider(metadata, profile) || !metadata.revision) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' does not match the NemoClaw-owned ${profile.label} inference boundary. No provider was changed.`, + ); + } + return { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: metadata.revision.id, + }; +} + +async function inspectNativeProvider( + adapter: OpenShellProviderAdapter, + target: OpenShellGatewayTarget, + profile: NativeHostedProfile, +): Promise { + const observed = await adapter.getProvider({ + target, + providerName: profile.providerName, + }); + if (observed.ok) return observed.value; + if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; + throw new NativeHostedProviderError( + `Could not inspect OpenShell provider '${profile.providerName}': ${providerErrorDetail(observed.error)}`, + ); +} + +function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { + return ( + error.kind === "timeout" || + (error.kind === "transport" && + (error.reason === "connection_loss" || error.reason === "unreachable")) || + (error.kind === "command" && error.reason === "uncertain") + ); +} + +function authorityPersistenceRecovery(gatewayName: string, profile: NativeHostedProfile): string { + return `Run 'nemoclaw credentials reset ${profile.logicalProvider} --yes' against gateway '${gatewayName}', then retry.`; +} + +async function removeNewNativeHostedProvider(input: { + profile: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + expected: NativeHostedProviderAttachment; +}): Promise { + const provider = await inspectNativeProvider(input.adapter, input.target, input.profile); + if (!provider) return; + const current = attachmentFromMetadata(provider, input.profile); + if (current.providerId !== input.expected.providerId) { + throw new NativeHostedProviderError( + `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 NativeHostedProviderError( + `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 = attachmentFromMetadata(after, input.profile); + const identity = + observed.providerId === input.expected.providerId ? "still exists" : "changed identity"; + throw new NativeHostedProviderError( + `OpenShell provider '${input.profile.providerName}' ${identity} after cleanup.`, + ); + } +} + +/** Record provider authority or remove only the new, unreferenced provider. */ +export async function persistNativeHostedProviderAuthority(input: { + profile: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + gatewayName: string; + receipt: NativeHostedProviderAttachment; + existing?: NativeHostedProviderAttachment; + readAuthority: (gatewayName: string) => NativeHostedProviderAttachment | undefined; + writeAuthority: (gatewayName: string, receipt: NativeHostedProviderAttachment) => void; +}): Promise { + try { + input.writeAuthority(input.gatewayName, input.receipt); + return; + } catch (writeError) { + const writeDetail = writeError instanceof Error ? writeError.message : String(writeError); + let observed: NativeHostedProviderAttachment | undefined; + try { + observed = input.readAuthority(input.gatewayName); + } catch (readError) { + const readDetail = readError instanceof Error ? readError.message : String(readError); + throw new NativeHostedProviderError( + `NemoClaw could not record or confirm ownership of OpenShell provider '${input.profile.providerName}' for gateway '${input.gatewayName}'. The provider was retained. ${authorityPersistenceRecovery(input.gatewayName, input.profile)}\n Write failure: ${writeDetail}\n Read failure: ${readDetail}`, + ); + } + if (observed?.providerId === input.receipt.providerId) return; + if (input.existing || observed) { + throw new NativeHostedProviderError( + `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. ${authorityPersistenceRecovery(input.gatewayName, input.profile)}\n ${writeDetail}`, + ); + } + try { + await removeNewNativeHostedProvider({ + profile: input.profile, + adapter: input.adapter, + target: input.target, + expected: input.receipt, + }); + } catch (cleanupError) { + const cleanupDetail = + cleanupError instanceof Error ? cleanupError.message : String(cleanupError); + throw new NativeHostedProviderError( + `NemoClaw could not record ownership of OpenShell provider '${input.profile.providerName}' for gateway '${input.gatewayName}', and cleanup did not complete. ${authorityPersistenceRecovery(input.gatewayName, input.profile)}\n Write failure: ${writeDetail}\n Cleanup failure: ${cleanupDetail}`, + ); + } + throw new NativeHostedProviderError( + `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 ensureNativeHostedProvider(input: { + profile: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + credentialValue: string | null; + reuseExistingCredential?: boolean; + expected?: NativeHostedProviderAttachment; + profilePath?: string; +}): Promise { + const { adapter, target, profile } = input; + assertExpectedProfile(profile, input.expected); + await requireNativeHostedProviderProfileBoundary(adapter, target, profile, input.profilePath); + const activatePolicy = async () => { + const policy = await adapter.ensureProviderPolicyComposition({ target }); + if (!policy.ok) { + throw new NativeHostedProviderError( + `Could not activate native ${profile.label} provider policy: ${providerErrorDetail(policy.error)}`, + ); + } + }; + + const before = await inspectNativeProvider(adapter, target, profile); + if (before) { + const receipt = attachmentFromMetadata(before, profile); + if (!input.expected) { + throw new NativeHostedProviderError( + `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 NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity. Recreate the sandbox before using native ${profile.label} inference. No provider was changed.`, + ); + } + await activatePolicy(); + if (!input.credentialValue) return receipt; + const updated = await adapter.updateProvider({ + target, + providerName: profile.providerName, + credentials: [{ name: profile.credentialEnv, value: input.credentialValue }], + config: [], + }); + if (!updated.ok && mutationOutcomeMayBeAmbiguous(updated.error)) { + throw new NativeHostedProviderError( + `OpenShell did not confirm whether provider '${profile.providerName}' accepted its credential update. No provider receipt was recorded.`, + ); + } + if (!updated.ok) { + throw new NativeHostedProviderError( + `Could not update OpenShell provider '${profile.providerName}': ${providerErrorDetail(updated.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target, profile); + if (!observed) { + throw new NativeHostedProviderError( + `OpenShell did not confirm provider '${profile.providerName}' after its credential update.`, + ); + } + const confirmed = attachmentFromMetadata(observed, profile); + if (confirmed.providerId !== receipt.providerId) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity during its credential update. No provider receipt was recorded.`, + ); + } + return confirmed; + } + + if (input.expected) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' is missing. Recreate the sandbox before using native ${profile.label} inference. No provider was changed.`, + ); + } + + if (!input.credentialValue && !input.reuseExistingCredential) { + throw new NativeHostedProviderError( + `A host credential is required to create OpenShell provider '${profile.providerName}'.`, + ); + } + await activatePolicy(); + const created = await adapter.createProvider({ + target, + name: profile.providerName, + type: profile.profileId, + credentials: input.credentialValue + ? [{ name: profile.credentialEnv, value: input.credentialValue }] + : [], + config: [], + fromExisting: !input.credentialValue, + }); + if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { + throw new NativeHostedProviderError( + `Could not create OpenShell provider '${profile.providerName}': ${providerErrorDetail(created.error)}`, + ); + } + const observed = await inspectNativeProvider(adapter, target, profile); + if (!observed) { + throw new NativeHostedProviderError( + `OpenShell did not confirm provider '${profile.providerName}' after creation.`, + ); + } + return attachmentFromMetadata(observed, profile); +} + +async function requireNativeHostedProviderProfileBoundary( + adapter: OpenShellProviderAdapter, + target: OpenShellGatewayTarget, + profile: NativeHostedProfile, + profilePath = nativeHostedProviderProfilePath(profile), +): Promise { + const imported = await adapter.importProviderProfile({ + target, + profilePath: profilePath, + }); + if (!imported.ok) { + const collision = + imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; + throw new NativeHostedProviderError( + collision + ? `OpenShell provider profile '${profile.profileId}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` + : `Could not prepare OpenShell provider profile '${profile.profileId}': ${providerErrorDetail(imported.error)}`, + ); + } +} + +/** Prove that the exact NemoClaw-owned hosted provider is attached to one sandbox. */ +export async function verifyNativeHostedProviderAttachment(input: { + profile?: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected?: NativeHostedProviderAttachment; +}): Promise { + const profile = + input.profile ?? + NATIVE_HOSTED_PROFILES.find( + (candidate) => + candidate.profileId === input.expected?.profileId && + candidate.providerName === input.expected?.providerName, + ); + if (!profile) + throw new NativeHostedProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + await requireNativeHostedProviderProfileBoundary(input.adapter, input.target, profile); + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if (!provider) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' is missing. Recreate the sandbox to restore native ${profile.label} inference.`, + ); + } + const receipt = attachmentFromMetadata(provider, profile); + if (input.expected && input.expected.providerId !== receipt.providerId) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity. Recreate the sandbox before using native ${profile.label} inference.`, + ); + } + const attachments = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!attachments.ok) { + throw new NativeHostedProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, + ); + } + if (!attachments.value.names.includes(profile.providerName)) { + throw new NativeHostedProviderError( + `Sandbox '${input.sandboxName}' does not have its native ${profile.label} inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, + ); + } + return receipt; +} + +/** Attach native hosted access and reconcile an ambiguous command through observation. */ +export async function ensureNativeHostedProviderAttached(input: { + profile?: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeHostedProviderAttachment; +}): Promise<{ receipt: NativeHostedProviderAttachment; changed: boolean }> { + const profile = + input.profile ?? + NATIVE_HOSTED_PROFILES.find( + (candidate) => + candidate.profileId === input.expected?.profileId && + candidate.providerName === input.expected?.providerName, + ); + if (!profile) + throw new NativeHostedProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + await requireNativeHostedProviderProfileBoundary(input.adapter, input.target, profile); + const before = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!before.ok) { + throw new NativeHostedProviderError( + `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, + ); + } + if (before.value.names.includes(profile.providerName)) { + return { + receipt: await verifyNativeHostedProviderAttachment({ ...input, profile }), + changed: false, + }; + } + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if ( + !provider || + attachmentFromMetadata(provider, profile).providerId !== input.expected.providerId + ) { + throw new NativeHostedProviderError( + `OpenShell provider '${profile.providerName}' changed identity before attachment. No provider was attached.`, + ); + } + const attached = await input.adapter.attachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: profile.providerName, + }); + if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { + throw new NativeHostedProviderError( + `Could not attach native ${profile.label} provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, + ); + } + try { + return { + receipt: await verifyNativeHostedProviderAttachment({ ...input, profile }), + changed: true, + }; + } catch (error) { + try { + await detachNativeHostedProvider({ ...input, profile }); + } catch (detachError) { + const detail = error instanceof Error ? error.message : String(error); + const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); + throw new NativeHostedProviderError(`${detail}\n ${detachDetail}`); + } + throw error; + } +} + +/** Detach only the recorded native hosted provider identity and prove absence. */ +export async function detachNativeHostedProvider(input: { + profile?: NativeHostedProfile; + adapter: OpenShellProviderAdapter; + target: OpenShellGatewayTarget; + sandboxName: string; + expected: NativeHostedProviderAttachment; +}): Promise { + const profile = + input.profile ?? + NATIVE_HOSTED_PROFILES.find( + (candidate) => + candidate.profileId === input.expected?.profileId && + candidate.providerName === input.expected?.providerName, + ); + if (!profile) + throw new NativeHostedProviderError("Native inference requires a recorded provider identity."); + assertExpectedProfile(profile, input.expected); + const provider = await inspectNativeProvider(input.adapter, input.target, profile); + if (!provider) return; + const current = attachmentFromMetadata(provider, profile); + if (current.providerId !== input.expected.providerId) { + throw new NativeHostedProviderError( + `Refusing to detach OpenShell provider '${profile.providerName}' because its identity changed.`, + ); + } + const detached = await input.adapter.detachProvider({ + target: input.target, + sandboxName: input.sandboxName, + providerName: profile.providerName, + }); + if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { + throw new NativeHostedProviderError( + `Could not detach native ${profile.label} provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, + ); + } + const after = await input.adapter.listProviderAttachments({ + target: input.target, + sandboxName: input.sandboxName, + }); + if (!after.ok || after.value.names.includes(profile.providerName)) { + throw new NativeHostedProviderError( + `OpenShell did not confirm removal of native ${profile.label} access from sandbox '${input.sandboxName}'.`, + ); + } +} + +export { nativeHostedProfile } from "./profiles"; + +export { normalizeNativeNvidiaProviderAttachment } from "../native-nvidia/contract"; diff --git a/src/lib/inference/native-hosted/openrouter-headers.ts b/src/lib/inference/native-hosted/openrouter-headers.ts new file mode 100644 index 00000000000..fc8736bda52 --- /dev/null +++ b/src/lib/inference/native-hosted/openrouter-headers.ts @@ -0,0 +1,8 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Static attribution shared by native agent requests and the legacy adapter. +export const OPENROUTER_DEFAULT_HEADERS = [ + ["HTTP-Referer", "https://www.nvidia.com/nemoclaw/"], + ["X-OpenRouter-Title", "NVIDIA NemoClaw"], +] as const; diff --git a/src/lib/inference/native-hosted/profiles.ts b/src/lib/inference/native-hosted/profiles.ts new file mode 100644 index 00000000000..c7aa430d477 --- /dev/null +++ b/src/lib/inference/native-hosted/profiles.ts @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +export interface NativeHostedProfile { + readonly label: string; + readonly logicalProvider: string; + readonly profileId: string; + readonly providerName: string; + readonly endpoint: string; + // Host credentials can use a different name from the OpenShell profile binding. + readonly hostCredentialEnv?: "NOUS_API_KEY"; + readonly credentialEnv: + | "NVIDIA_INFERENCE_API_KEY" + | "OPENAI_API_KEY" + | "ANTHROPIC_API_KEY" + | "GEMINI_API_KEY" + | "OPENROUTER_API_KEY"; +} + +export const NATIVE_HOSTED_PROFILES: readonly NativeHostedProfile[] = [ + { + label: "NVIDIA", + logicalProvider: "nvidia-prod", + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + endpoint: "https://integrate.api.nvidia.com/v1", + credentialEnv: "NVIDIA_INFERENCE_API_KEY", + }, + { + label: "OpenAI", + logicalProvider: "openai-api", + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + endpoint: "https://api.openai.com/v1", + credentialEnv: "OPENAI_API_KEY", + }, + { + label: "Anthropic", + logicalProvider: "anthropic-prod", + profileId: "nemoclaw-anthropic-inference-v1", + providerName: "nemoclaw-anthropic-prod-v1", + endpoint: "https://api.anthropic.com", + credentialEnv: "ANTHROPIC_API_KEY", + }, + { + label: "Google Gemini", + logicalProvider: "gemini-api", + profileId: "nemoclaw-gemini-inference-v1", + providerName: "nemoclaw-gemini-api-v1", + endpoint: "https://generativelanguage.googleapis.com/v1beta/openai", + credentialEnv: "GEMINI_API_KEY", + }, + { + label: "OpenRouter", + logicalProvider: "openrouter-api", + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + endpoint: "https://openrouter.ai/api/v1", + credentialEnv: "OPENROUTER_API_KEY", + }, + { + label: "Hermes Provider", + logicalProvider: "hermes-provider", + hostCredentialEnv: "NOUS_API_KEY", + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + endpoint: "https://inference-api.nousresearch.com/v1", + credentialEnv: "OPENAI_API_KEY", + }, +]; + +export function nativeHostedProfile( + provider: string | null | undefined, +): NativeHostedProfile | undefined { + const name = provider?.trim(); + return NATIVE_HOSTED_PROFILES.find((profile) => profile.logicalProvider === name); +} diff --git a/src/lib/inference/native-nvidia.test.ts b/src/lib/inference/native-nvidia.test.ts index 995da9da55e..36a0c13fed4 100644 --- a/src/lib/inference/native-nvidia.test.ts +++ b/src/lib/inference/native-nvidia.test.ts @@ -2,65 +2,28 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; -import { describe, expect, it, vi } from "vitest"; - -import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { describe, expect, it } from "vitest"; import { parseCheckedInProviderProfileContract } from "../adapters/openshell/provider-profile"; import { - ensureNativeNvidiaProvider, - ensureNativeNvidiaProviderAttached, - nativeNvidiaProviderProfilePath, - type NativeNvidiaProviderAttachment, - NativeNvidiaProviderError, - NVIDIA_HOSTED_CREDENTIAL_ENV, NVIDIA_HOSTED_NATIVE_PROFILE_ID, NVIDIA_HOSTED_NATIVE_PROVIDER, - persistNativeNvidiaProviderAuthority, - verifyNativeNvidiaProviderAttachment, -} from "./native-nvidia"; - -const target = { kind: "named", gatewayName: "nemoclaw" } as const; - -function metadata(overrides: Record = {}) { - return { - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentialKeys: [NVIDIA_HOSTED_CREDENTIAL_ENV], - configKeys: [], - revision: { id: "provider-id", resourceVersion: 1 }, - ...overrides, - }; -} + normalizeNativeNvidiaProviderAttachment, +} from "./native-nvidia/contract"; +import { + nativeHostedProviderProfilePath, + normalizeNativeHostedProviderAttachment, +} from "./native-hosted"; +import { nativeHostedProfile } from "./native-hosted/profiles"; -function adapter(overrides: Partial = {}): OpenShellProviderAdapter { - return { - ensureProviderPolicyComposition: vi.fn(async () => ({ ok: true, value: undefined })), - importProviderProfile: vi.fn(() => ({ ok: true })), - getProvider: vi.fn(async () => ({ ok: true, value: metadata() })), - createProvider: vi.fn(async () => ({ ok: true })), - updateProvider: vi.fn(async () => ({ ok: true })), - listProviderAttachments: vi.fn(async () => ({ - ok: true, - value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, - })), - listProviders: vi.fn(), - inspectProviderProfile: vi.fn(), - deleteProvider: vi.fn(), - detachProvider: vi.fn(async () => ({ ok: true })), - attachProvider: vi.fn(async () => ({ ok: true })), - configureProviderRefresh: vi.fn(), - getProviderRefreshStatus: vi.fn(), - ...overrides, - } as OpenShellProviderAdapter; -} +const profile = nativeHostedProfile("nvidia-prod")!; -describe("native NVIDIA OpenShell provider", () => { +describe("native NVIDIA receipt compatibility", () => { it("ships a profile limited to the native models and chat-completions operations (#12558)", () => { - const source = fs.readFileSync(nativeNvidiaProviderProfilePath(), "utf8"); - const profile = parseCheckedInProviderProfileContract(source); + const source = fs.readFileSync(nativeHostedProviderProfilePath(profile), "utf8"); + const contract = parseCheckedInProviderProfileContract(source); - expect(profile?.profileId).toBe(NVIDIA_HOSTED_NATIVE_PROFILE_ID); - expect(profile?.boundary.endpoints).toEqual([ + expect(contract?.profileId).toBe(NVIDIA_HOSTED_NATIVE_PROFILE_ID); + expect(contract?.boundary.endpoints).toEqual([ expect.objectContaining({ host: "integrate.api.nvidia.com", port: 443, @@ -71,486 +34,31 @@ describe("native NVIDIA OpenShell provider", () => { ], }), ]); - expect(profile?.boundary.binaries).not.toEqual( + expect(contract?.boundary.binaries).not.toEqual( expect.arrayContaining([expect.stringMatching(/[?*]/u)]), ); }); - it("creates the internal provider once and records its immutable identity (#12558)", async () => { - const getProvider = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }) - .mockResolvedValueOnce({ ok: true, value: metadata() }); - const createProvider = vi.fn(async () => ({ - ok: true, - })); - const providerAdapter = adapter({ getProvider, createProvider }); - - await expect( - ensureNativeNvidiaProvider({ - adapter: providerAdapter, - target, - credentialValue: "opaque-test-secret", - }), - ).resolves.toEqual({ - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }); - expect(createProvider).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: "opaque-test-secret" }], - config: [], - }), - ); - }); - - it("removes a new provider when authority persistence fails (#12562)", async () => { - let providerPresent = true; - const getProvider = vi.fn(async () => - providerPresent - ? { ok: true, value: metadata() } - : { - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }, - ); - const deleteProvider = vi.fn(async () => { - providerPresent = false; - return { ok: true }; - }); + it("preserves a Slice 1 receipt in both receipt readers", () => { const receipt = { schemaVersion: 1, profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - } as const; - - await expect( - persistNativeNvidiaProviderAuthority({ - adapter: adapter({ getProvider, deleteProvider }), - target, - gatewayName: "nemoclaw", - receipt, - readAuthority: () => undefined, - writeAuthority: () => { - throw new Error("state directory is read-only"); - }, - }), - ).rejects.toThrow(/newly created provider was removed.*state directory is read-only/su); - expect(deleteProvider).toHaveBeenCalledExactlyOnceWith({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); + providerId: "legacy-provider-id", + }; + expect(normalizeNativeNvidiaProviderAttachment(receipt)).toEqual(receipt); + expect(normalizeNativeHostedProviderAttachment(receipt)).toEqual(receipt); }); - it("keeps a provider when a failed write persisted its authority (#12562)", async () => { + it("rejects a hosted vendor receipt in the legacy NVIDIA reader", () => { + const openai = nativeHostedProfile("openai-api")!; const receipt = { schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - } as const; - let authority: NativeNvidiaProviderAttachment | undefined; - const deleteProvider = vi.fn(); - - await expect( - persistNativeNvidiaProviderAuthority({ - adapter: adapter({ deleteProvider }), - target, - gatewayName: "nemoclaw", - receipt, - readAuthority: () => authority, - writeAuthority: (_gatewayName, value) => { - authority = value; - throw new Error("directory sync failed"); - }, - }), - ).resolves.toBeUndefined(); - expect(deleteProvider).not.toHaveBeenCalled(); - }); - - it("refuses cleanup when the provider identity changed after a failed write (#12562)", async () => { - const deleteProvider = vi.fn(); - - await expect( - persistNativeNvidiaProviderAuthority({ - adapter: adapter({ - getProvider: vi.fn(async () => ({ - ok: true, - value: metadata({ - revision: { id: "replacement-id", resourceVersion: 2 }, - }), - })), - deleteProvider, - }), - target, - gatewayName: "nemoclaw", - receipt: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - readAuthority: () => undefined, - writeAuthority: () => { - throw new Error("state directory is read-only"); - }, - }), - ).rejects.toThrow(/credentials reset nvidia-prod.*identity changed/su); - expect(deleteProvider).not.toHaveBeenCalled(); - }); - - it("observes an ambiguous create result without issuing a second mutation (#12558)", async () => { - const getProvider = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }) - .mockResolvedValueOnce({ ok: true, value: metadata() }); - const createProvider = vi.fn(async () => ({ - ok: false, - error: { kind: "timeout", message: "timed out" }, - })); - - await expect( - ensureNativeNvidiaProvider({ - adapter: adapter({ getProvider, createProvider }), - target, - credentialValue: "opaque-test-secret", - }), - ).resolves.toMatchObject({ providerId: "provider-id" }); - expect(createProvider).toHaveBeenCalledOnce(); - }); - - it("creates from an existing gateway credential when recreation has no local key (#12558)", async () => { - const getProvider = vi - .fn() - .mockResolvedValueOnce({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - }) - .mockResolvedValueOnce({ ok: true, value: metadata() }); - const createProvider = vi.fn(async () => ({ - ok: true, - })); - - await expect( - ensureNativeNvidiaProvider({ - adapter: adapter({ getProvider, createProvider }), - target, - credentialValue: null, - reuseExistingCredential: true, - }), - ).resolves.toMatchObject({ providerId: "provider-id" }); - expect(createProvider).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - credentials: [], - fromExisting: true, - }), - ); - }); - - it("refuses a replaced provider before rotating its credential (#12558)", async () => { - const updateProvider = vi.fn(); - - await expect( - ensureNativeNvidiaProvider({ - adapter: adapter({ - getProvider: vi.fn(async () => ({ - ok: true, - value: metadata({ revision: { id: "replacement-id", resourceVersion: 1 } }), - })), - updateProvider, - }), - target, - credentialValue: "opaque-test-secret", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "recorded-id", - }, - }), - ).rejects.toThrow(/changed identity.*No provider was changed/u); - expect(updateProvider).not.toHaveBeenCalled(); - }); - - it("refuses an existing provider without an ownership receipt before mutation (#12558)", async () => { - const updateProvider = vi.fn(); - const attachProvider = vi.fn(); - - await expect( - ensureNativeNvidiaProvider({ - adapter: adapter({ updateProvider, attachProvider }), - target, - credentialValue: "opaque-test-secret", - }), - ).rejects.toThrow(/already exists without a matching NemoClaw ownership receipt/u); - expect(updateProvider).not.toHaveBeenCalled(); - expect(attachProvider).not.toHaveBeenCalled(); - }); - - it("does not record a receipt after an ambiguous credential update (#12558)", async () => { - const getProvider = vi.fn(async () => ({ - ok: true, - value: metadata(), - })); - const updateProvider = vi.fn(async () => ({ - ok: false, - error: { kind: "timeout", message: "timed out" }, - })); - - await expect( - ensureNativeNvidiaProvider({ - adapter: adapter({ getProvider, updateProvider }), - target, - credentialValue: "replacement-secret", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow(/did not confirm.*credential update.*No provider receipt was recorded/u); - expect(updateProvider).toHaveBeenCalledOnce(); - expect(getProvider).toHaveBeenCalledOnce(); - }); - - it("refuses to replace a recorded provider that is missing (#12558)", async () => { - const createProvider = vi.fn(); - - await expect( - ensureNativeNvidiaProvider({ - adapter: adapter({ - getProvider: vi.fn(async () => ({ - ok: false, - error: { kind: "command", reason: "not_found", message: "not found" }, - })), - createProvider, - }), - target, - credentialValue: "opaque-test-secret", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "recorded-id", - }, - }), - ).rejects.toThrow(/is missing.*No provider was changed/u); - expect(createProvider).not.toHaveBeenCalled(); - }); - - it("fails before provider mutation when the profile collides (#12558)", async () => { - const createProvider = vi.fn(); - const providerAdapter = adapter({ - importProviderProfile: vi.fn(() => ({ - ok: false, - error: { - kind: "command", - reason: "profile_incompatible", - message: "different profile", - }, - })), - createProvider, - }); - - await expect( - ensureNativeNvidiaProvider({ - adapter: providerAdapter, - target, - credentialValue: "opaque-test-secret", - }), - ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); - expect(createProvider).not.toHaveBeenCalled(); - }); - - it("requires the exact provider attachment before native inference is published (#12558)", async () => { - const providerAdapter = adapter({ - listProviderAttachments: vi.fn( - async () => ({ ok: true, value: { names: [] } }), - ), - }); - - await expect( - verifyNativeNvidiaProviderAttachment({ - adapter: providerAdapter, - target, - sandboxName: "alpha", - }), - ).rejects.toThrow(NativeNvidiaProviderError); - await expect( - verifyNativeNvidiaProviderAttachment({ - adapter: providerAdapter, - target, - sandboxName: "alpha", - }), - ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); - }); - - it("rejects a matching attachment when the live provider profile exceeds the checked-in boundary (#12562)", async () => { - const getProvider = vi.fn(async () => ({ - ok: true, - value: metadata(), - })); - const listProviderAttachments = vi.fn( - async () => ({ - ok: true, - value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, - }), - ); - const providerAdapter = adapter({ - importProviderProfile: vi.fn(() => ({ - ok: false, - error: { - kind: "command", - reason: "profile_incompatible", - message: "live endpoint rules are wider than the checked-in profile", - }, - })), - getProvider, - listProviderAttachments, - }); - - await expect( - verifyNativeNvidiaProviderAttachment({ - adapter: providerAdapter, - target, - sandboxName: "alpha", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); - expect(getProvider).not.toHaveBeenCalled(); - expect(listProviderAttachments).not.toHaveBeenCalled(); - }); - - it("refuses to attach through a live provider profile that exceeds the checked-in boundary (#12562)", async () => { - const attachProvider = vi.fn(); - const providerAdapter = adapter({ - importProviderProfile: vi.fn(() => ({ - ok: false, - error: { - kind: "command", - reason: "profile_incompatible", - message: "live endpoint rules are wider than the checked-in profile", - }, - })), - attachProvider, - }); - - await expect( - ensureNativeNvidiaProviderAttached({ - adapter: providerAdapter, - target, - sandboxName: "alpha", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow(/conflicts with NemoClaw's checked-in security boundary/u); - expect(attachProvider).not.toHaveBeenCalled(); - }); - - it("removes a newly attached provider when attachment verification fails (#12558)", async () => { - const listProviderAttachments = vi - .fn() - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ ok: true, value: { names: [] } }); - const detachProvider = vi.fn(async () => ({ - ok: true, - value: { changed: true }, - })); - const providerAdapter = adapter({ listProviderAttachments, detachProvider }); - - await expect( - ensureNativeNvidiaProviderAttached({ - adapter: providerAdapter, - target, - sandboxName: "alpha", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow(/does not have its native NVIDIA inference provider attached/u); - expect(detachProvider).toHaveBeenCalledExactlyOnceWith({ - target, - sandboxName: "alpha", - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - }); - - it("preserves verification and cleanup failures after a new attachment (#12558)", async () => { - const listProviderAttachments = vi - .fn() - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ ok: true, value: { names: [] } }) - .mockResolvedValueOnce({ - ok: true, - value: { names: [NVIDIA_HOSTED_NATIVE_PROVIDER] }, - }); - - await expect( - ensureNativeNvidiaProviderAttached({ - adapter: adapter({ listProviderAttachments }), - target, - sandboxName: "alpha", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow( - /does not have its native NVIDIA inference provider attached[\s\S]*did not confirm removal/u, - ); - }); -}); - -it("does not publish credentials when native provider policy is unavailable", async () => { - const providerAdapter = adapter({ - ensureProviderPolicyComposition: vi.fn< - OpenShellProviderAdapter["ensureProviderPolicyComposition"] - >(async () => ({ - ok: false, - error: { kind: "command", reason: "conflict", message: "disabled by administrator" }, - })), + profileId: openai.profileId, + providerName: openai.providerName, + providerId: "openai-id", + }; + expect(normalizeNativeNvidiaProviderAttachment(receipt)).toBeUndefined(); + expect(normalizeNativeHostedProviderAttachment(receipt)).toEqual(receipt); }); - await expect( - ensureNativeNvidiaProvider({ - adapter: providerAdapter, - target, - credentialValue: "opaque-test-secret", - expected: { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: "provider-id", - }, - }), - ).rejects.toThrow("disabled by administrator"); - expect(providerAdapter.createProvider).not.toHaveBeenCalled(); - expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); }); diff --git a/src/lib/inference/native-nvidia/contract.ts b/src/lib/inference/native-nvidia/contract.ts index 5a9ded0042c..5a466c9391e 100644 --- a/src/lib/inference/native-nvidia/contract.ts +++ b/src/lib/inference/native-nvidia/contract.ts @@ -36,6 +36,10 @@ export function normalizeNativeNvidiaProviderAttachment( }; } +export function isNativeNvidiaProvider(provider: string | null | undefined): boolean { + return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; +} + /** Use only the supervisor-issued placeholder inside the sandbox shell. */ export const NATIVE_NVIDIA_AUTH_HEADER_SCRIPT = [ 'case "${NVIDIA_INFERENCE_API_KEY:-}" in *[!a-zA-Z0-9:_]*) exit 2 ;; esac', diff --git a/src/lib/inference/native-nvidia/index.ts b/src/lib/inference/native-nvidia/index.ts deleted file mode 100644 index e449c06b9f6..00000000000 --- a/src/lib/inference/native-nvidia/index.ts +++ /dev/null @@ -1,472 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import path from "node:path"; - -import type { - OpenShellGatewayTarget, - OpenShellProviderAdapter, - OpenShellProviderError, - OpenShellProviderMetadata, -} from "../../adapters/openshell/sandbox-observer"; -import { REPOSITORY_ROOT } from "../../core/repository-root"; -import { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - type NativeNvidiaProviderAttachment, -} from "./contract"; - -export { - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_ENDPOINT, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, - normalizeNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "./contract"; - -export class NativeNvidiaProviderError extends Error { - constructor(message: string) { - super(message); - this.name = "NativeNvidiaProviderError"; - } -} - -export function nativeNvidiaProviderProfilePath(root = REPOSITORY_ROOT): string { - return path.join( - root, - "managed-inference", - "provider-profiles", - `${NVIDIA_HOSTED_NATIVE_PROFILE_ID}.yaml`, - ); -} - -export function isNativeNvidiaProvider(provider: string | null | undefined): boolean { - return provider?.trim() === NVIDIA_HOSTED_LOGICAL_PROVIDER; -} - -export function resolveGatewayNativeNvidiaProviderAuthority(input: { - gatewayName: string; - gatewayAuthority?: NativeNvidiaProviderAttachment | null; - recordedAttachment?: NativeNvidiaProviderAttachment | null; -}): NativeNvidiaProviderAttachment | undefined { - const authorities = new Map(); - for (const receipt of [input.gatewayAuthority, input.recordedAttachment]) { - if (receipt) authorities.set(receipt.providerId, receipt); - } - if (authorities.size > 1) { - throw new NativeNvidiaProviderError( - `Gateway '${input.gatewayName}' has conflicting native NVIDIA provider ownership receipts. No provider was changed.`, - ); - } - return authorities.values().next().value; -} - -export function nativeInferenceProviderForSandbox( - provider: string | null | undefined, -): string | null { - const normalized = provider?.trim() || null; - return isNativeNvidiaProvider(normalized) ? NVIDIA_HOSTED_NATIVE_PROVIDER : normalized; -} - -function providerErrorDetail(error: OpenShellProviderError): string { - return error.message.trim() || "OpenShell did not provide a diagnostic."; -} - -async function requireNativeNvidiaProviderProfileBoundary( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, - profilePath = nativeNvidiaProviderProfilePath(), -): Promise { - const imported = await adapter.importProviderProfile({ target, profilePath }); - if (imported.ok) return; - const collision = - imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; - throw new NativeNvidiaProviderError( - collision - ? `OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}' conflicts with NemoClaw's checked-in security boundary. No provider was changed.` - : `Could not verify OpenShell provider profile '${NVIDIA_HOSTED_NATIVE_PROFILE_ID}': ${providerErrorDetail(imported.error)}`, - ); -} - -function exactNativeProvider(metadata: OpenShellProviderMetadata): boolean { - return ( - metadata.name === NVIDIA_HOSTED_NATIVE_PROVIDER && - metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID && - metadata.configKeys.length === 0 && - metadata.credentialKeys.length === 1 && - metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && - Boolean(metadata.revision?.id) - ); -} - -export function nativeNvidiaProviderAttachmentFromMetadata( - metadata: OpenShellProviderMetadata, -): NativeNvidiaProviderAttachment { - if (!exactNativeProvider(metadata) || !metadata.revision) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' does not match the NemoClaw-owned NVIDIA inference boundary. No provider was changed.`, - ); - } - return { - schemaVersion: 1, - profileId: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - providerId: metadata.revision.id, - }; -} - -async function inspectNativeProvider( - adapter: OpenShellProviderAdapter, - target: OpenShellGatewayTarget, -): Promise { - const observed = await adapter.getProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (observed.ok) return observed.value; - if (observed.error.kind === "command" && observed.error.reason === "not_found") return null; - throw new NativeNvidiaProviderError( - `Could not inspect OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(observed.error)}`, - ); -} - -function mutationOutcomeMayBeAmbiguous(error: OpenShellProviderError): boolean { - return ( - error.kind === "timeout" || - (error.kind === "transport" && - (error.reason === "connection_loss" || error.reason === "unreachable")) || - (error.kind === "command" && error.reason === "uncertain") - ); -} - -function authorityPersistenceRecovery(gatewayName: string): string { - return `Run 'nemoclaw credentials reset ${NVIDIA_HOSTED_LOGICAL_PROVIDER} --yes' against gateway '${gatewayName}', then retry.`; -} - -async function removeNewNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const removed = await input.adapter.deleteProvider({ - target: input.target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!removed.ok && !mutationOutcomeMayBeAmbiguous(removed.error)) { - throw new NativeNvidiaProviderError( - `Could not remove OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(removed.error)}`, - ); - } - const after = await inspectNativeProvider(input.adapter, input.target); - if (after) { - const observed = nativeNvidiaProviderAttachmentFromMetadata(after); - const identity = - observed.providerId === input.expected.providerId ? "still exists" : "changed identity"; - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' ${identity} after cleanup.`, - ); - } -} - -/** Record provider authority or remove only the new, unreferenced provider. */ -export async function persistNativeNvidiaProviderAuthority(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - gatewayName: string; - receipt: NativeNvidiaProviderAttachment; - existing?: NativeNvidiaProviderAttachment; - readAuthority: (gatewayName: string) => NativeNvidiaProviderAttachment | undefined; - writeAuthority: (gatewayName: string, receipt: NativeNvidiaProviderAttachment) => void; -}): Promise { - try { - input.writeAuthority(input.gatewayName, input.receipt); - return; - } catch (writeError) { - const writeDetail = writeError instanceof Error ? writeError.message : String(writeError); - let observed: NativeNvidiaProviderAttachment | undefined; - try { - observed = input.readAuthority(input.gatewayName); - } catch (readError) { - const readDetail = readError instanceof Error ? readError.message : String(readError); - throw new NativeNvidiaProviderError( - `NemoClaw could not record or confirm ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Read failure: ${readDetail}`, - ); - } - if (observed?.providerId === input.receipt.providerId) return; - if (input.existing || observed) { - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The provider was retained because this operation cannot prove that it is unreferenced. ${authorityPersistenceRecovery(input.gatewayName)}\n ${writeDetail}`, - ); - } - try { - await removeNewNativeNvidiaProvider({ - adapter: input.adapter, - target: input.target, - expected: input.receipt, - }); - } catch (cleanupError) { - const cleanupDetail = - cleanupError instanceof Error ? cleanupError.message : String(cleanupError); - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}', and cleanup did not complete. ${authorityPersistenceRecovery(input.gatewayName)}\n Write failure: ${writeDetail}\n Cleanup failure: ${cleanupDetail}`, - ); - } - throw new NativeNvidiaProviderError( - `NemoClaw could not record ownership of OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' for gateway '${input.gatewayName}'. The newly created provider was removed. Retry the command.\n ${writeDetail}`, - ); - } -} - -/** Ensure the least-privilege NVIDIA profile and provider without retrying an ambiguous mutation. */ -export async function ensureNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - credentialValue: string | null; - reuseExistingCredential?: boolean; - expected?: NativeNvidiaProviderAttachment; - profilePath?: string; -}): Promise { - const { adapter, target } = input; - await requireNativeNvidiaProviderProfileBoundary( - adapter, - target, - input.profilePath ?? nativeNvidiaProviderProfilePath(), - ); - - const activatePolicy = async () => { - const policy = await adapter.ensureProviderPolicyComposition({ target }); - if (!policy.ok) { - throw new NativeNvidiaProviderError( - `Could not activate native NVIDIA provider policy: ${providerErrorDetail(policy.error)}`, - ); - } - }; - - const before = await inspectNativeProvider(adapter, target); - if (before) { - const receipt = nativeNvidiaProviderAttachmentFromMetadata(before); - if (!input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' already exists without a matching NemoClaw ownership receipt. No provider was changed.`, - ); - } - if (input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - await activatePolicy(); - if (!input.credentialValue) return receipt; - const updated = await adapter.updateProvider({ - target, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - credentials: [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }], - config: [], - }); - if (!updated.ok && mutationOutcomeMayBeAmbiguous(updated.error)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm whether provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' accepted its credential update. No provider receipt was recorded.`, - ); - } - if (!updated.ok) { - throw new NativeNvidiaProviderError( - `Could not update OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(updated.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after its credential update.`, - ); - } - const observedReceipt = nativeNvidiaProviderAttachmentFromMetadata(observed); - if (observedReceipt.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity during its credential update. No provider receipt was recorded.`, - ); - } - return observedReceipt; - } - - if (input.expected) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox before using native NVIDIA inference. No provider was changed.`, - ); - } - - if (!input.credentialValue && !input.reuseExistingCredential) { - throw new NativeNvidiaProviderError( - `A host credential is required to create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}'.`, - ); - } - await activatePolicy(); - const created = await adapter.createProvider({ - target, - name: NVIDIA_HOSTED_NATIVE_PROVIDER, - type: NVIDIA_HOSTED_NATIVE_PROFILE_ID, - credentials: input.credentialValue - ? [{ name: NVIDIA_HOSTED_CREDENTIAL_ENV, value: input.credentialValue }] - : [], - config: [], - fromExisting: !input.credentialValue, - }); - if (!created.ok && !mutationOutcomeMayBeAmbiguous(created.error)) { - throw new NativeNvidiaProviderError( - `Could not create OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}': ${providerErrorDetail(created.error)}`, - ); - } - const observed = await inspectNativeProvider(adapter, target); - if (!observed) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' after creation.`, - ); - } - return nativeNvidiaProviderAttachmentFromMetadata(observed); -} - -/** Prove that the exact NemoClaw-owned NVIDIA provider is attached to one sandbox. */ -export async function verifyNativeNvidiaProviderAttachment(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected?: NativeNvidiaProviderAttachment; -}): Promise { - await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (input.expected && input.expected.providerId !== receipt.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const attachments = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!attachments.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(attachments.error)}`, - ); - } - if (!attachments.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `Sandbox '${input.sandboxName}' does not have its native NVIDIA inference provider attached. Recreate the sandbox; NemoClaw does not migrate existing beta sandboxes automatically.`, - ); - } - return receipt; -} - -/** Attach native NVIDIA access and reconcile an ambiguous command through observation. */ -export async function ensureNativeNvidiaProviderAttached(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise<{ receipt: NativeNvidiaProviderAttachment; changed: boolean }> { - await requireNativeNvidiaProviderProfileBoundary(input.adapter, input.target); - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' is missing. Recreate the sandbox to restore native NVIDIA inference.`, - ); - } - const receipt = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (receipt.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' changed identity. Recreate the sandbox before using native NVIDIA inference.`, - ); - } - const before = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!before.ok) { - throw new NativeNvidiaProviderError( - `Could not inspect provider attachments for sandbox '${input.sandboxName}': ${providerErrorDetail(before.error)}`, - ); - } - if (before.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: false, - }; - } - const attached = await input.adapter.attachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!attached.ok && !mutationOutcomeMayBeAmbiguous(attached.error)) { - throw new NativeNvidiaProviderError( - `Could not attach native NVIDIA provider to sandbox '${input.sandboxName}': ${providerErrorDetail(attached.error)}`, - ); - } - try { - return { - receipt: await verifyNativeNvidiaProviderAttachment(input), - changed: true, - }; - } catch (error) { - try { - await detachNativeNvidiaProvider(input); - } catch (detachError) { - const detail = error instanceof Error ? error.message : String(error); - const detachDetail = detachError instanceof Error ? detachError.message : String(detachError); - throw new NativeNvidiaProviderError(`${detail}\n ${detachDetail}`); - } - throw error; - } -} - -/** Detach only the recorded native NVIDIA provider identity and prove absence. */ -export async function detachNativeNvidiaProvider(input: { - adapter: OpenShellProviderAdapter; - target: OpenShellGatewayTarget; - sandboxName: string; - expected: NativeNvidiaProviderAttachment; -}): Promise { - const provider = await inspectNativeProvider(input.adapter, input.target); - if (!provider) return; - const current = nativeNvidiaProviderAttachmentFromMetadata(provider); - if (current.providerId !== input.expected.providerId) { - throw new NativeNvidiaProviderError( - `Refusing to detach OpenShell provider '${NVIDIA_HOSTED_NATIVE_PROVIDER}' because its identity changed.`, - ); - } - const detached = await input.adapter.detachProvider({ - target: input.target, - sandboxName: input.sandboxName, - providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, - }); - if (!detached.ok && !mutationOutcomeMayBeAmbiguous(detached.error)) { - throw new NativeNvidiaProviderError( - `Could not detach native NVIDIA provider from sandbox '${input.sandboxName}': ${providerErrorDetail(detached.error)}`, - ); - } - const after = await input.adapter.listProviderAttachments({ - target: input.target, - sandboxName: input.sandboxName, - }); - if (!after.ok || after.value.names.includes(NVIDIA_HOSTED_NATIVE_PROVIDER)) { - throw new NativeNvidiaProviderError( - `OpenShell did not confirm removal of native NVIDIA access from sandbox '${input.sandboxName}'.`, - ); - } -} diff --git a/src/lib/inference/native-nvidia/network-policy.test.ts b/src/lib/inference/native-nvidia/network-policy.test.ts index 9de714bf82b..554c9ba0ef7 100644 --- a/src/lib/inference/native-nvidia/network-policy.test.ts +++ b/src/lib/inference/native-nvidia/network-policy.test.ts @@ -6,7 +6,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import YAML from "yaml"; import { buildNativeNvidiaSandboxPolicy } from "./network-policy"; -import { nativeNvidiaProviderProfilePath } from "./index"; afterEach(() => vi.restoreAllMocks()); @@ -35,7 +34,15 @@ describe("native NVIDIA static policy preparation", () => { { condition: "another profile ID", override: { id: "other-profile" } }, { condition: "inference capability is disabled", override: { inference_capable: false } }, ])("rejects the parsed profile when $condition (#12822)", ({ override }) => { - const profile = YAML.parse(fs.readFileSync(nativeNvidiaProviderProfilePath(), "utf8")); + const profile = YAML.parse( + fs.readFileSync( + new URL( + "../../../../managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", + import.meta.url, + ), + "utf8", + ), + ); vi.spyOn(fs, "readFileSync").mockReturnValue(YAML.stringify({ ...profile, ...override })); expect(() => buildNativeNvidiaSandboxPolicy("version: 1\n")).toThrow( "checked-in provider profile is invalid", diff --git a/src/lib/inference/native-nvidia/network-policy.ts b/src/lib/inference/native-nvidia/network-policy.ts index 3fcf1ffa449..0a5293d5951 100644 --- a/src/lib/inference/native-nvidia/network-policy.ts +++ b/src/lib/inference/native-nvidia/network-policy.ts @@ -8,15 +8,17 @@ import YAML from "yaml"; import { parseCheckedInProviderProfileContract } from "../../adapters/openshell/provider-profile"; import { parseOpenShellPolicy } from "../../adapters/openshell/policy-boundary"; import { NVIDIA_HOSTED_NATIVE_PROFILE_ID } from "./contract"; -import { nativeNvidiaProviderProfilePath } from "./index"; +import { nativeHostedProviderProfilePath, nativeHostedProfile } from "../native-hosted"; const NATIVE_NVIDIA_INFERENCE_POLICY_KEY = "native_nvidia_inference"; /** Keep native access scoped to the same checked-in profile that owns its credential. */ export function buildNativeNvidiaSandboxPolicy(basePolicy: string): string { const parsed = { ...parseOpenShellPolicy(basePolicy).policy }; + const nativeProfile = nativeHostedProfile("nvidia-prod"); + if (!nativeProfile) throw new Error("Native NVIDIA provider profile is unavailable."); const profile = parseCheckedInProviderProfileContract( - fs.readFileSync(nativeNvidiaProviderProfilePath(), "utf8"), + fs.readFileSync(nativeHostedProviderProfilePath(nativeProfile), "utf8"), ); if ( !profile || diff --git a/src/lib/inference/openrouter.ts b/src/lib/inference/openrouter.ts index 983a20680d8..ae449f340ae 100644 --- a/src/lib/inference/openrouter.ts +++ b/src/lib/inference/openrouter.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { OPENROUTER_DEFAULT_HEADERS } from "./native-hosted/openrouter-headers"; + import { OPENROUTER_RUNTIME_ADAPTER_PORT } from "../core/ports"; import { OPENROUTER_ENDPOINT_URL, OPENROUTER_PROVIDER_NAME } from "./managed-dcode/identity"; @@ -11,10 +13,7 @@ export const OPENROUTER_CREDENTIAL_ENV = "OPENROUTER_API_KEY"; // OpenRouter through the OpenAI-compatible provider profile while keeping a // distinct provider name and credential binding in NemoClaw. export const OPENROUTER_PROVIDER_TYPE = "openai"; -export const OPENROUTER_DEFAULT_HEADERS = [ - ["HTTP-Referer", "https://www.nvidia.com/nemoclaw/"], - ["X-OpenRouter-Title", "NVIDIA NemoClaw"], -] as const; +export { OPENROUTER_DEFAULT_HEADERS } from "./native-hosted/openrouter-headers"; export const OPENROUTER_RUNTIME_ADAPTER_BIND_HOST = "0.0.0.0"; export const OPENROUTER_RUNTIME_ADAPTER_LOOPBACK_HOST = "127.0.0.1"; export const OPENROUTER_RUNTIME_ADAPTER_SANDBOX_HOST = "host.openshell.internal"; diff --git a/src/lib/inference/probe/native-inference-probe-auth.test.ts b/src/lib/inference/probe/native-inference-probe-auth.test.ts new file mode 100644 index 00000000000..cf7286809f3 --- /dev/null +++ b/src/lib/inference/probe/native-inference-probe-auth.test.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { describe, expect, it } from "vitest"; +import { nativeInferenceProbeAuthScript } from "./native-inference-probe-auth"; + +describe("native probe workload credential handles", () => { + describe.each([ + "NVIDIA_INFERENCE_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "OPENROUTER_API_KEY", + ] as const)("issued credential binding for %s", (credentialEnv) => { + it.each([ + ["v42", false], + ["v42", true], + [`s${"a".repeat(64)}`, false], + [`s${"a".repeat(64)}`, true], + ] as const)("uses issued %s handle with anthropic=%s", (version, anthropic) => { + const handle = `openshell:resolve:env:${version}_${credentialEnv}`; + const command = [ + ...nativeInferenceProbeAuthScript(credentialEnv, anthropic), + 'printf "%s" "$AUTH_HEADER"', + ].join("; "); + const result = spawnSync("/bin/sh", ["-c", command], { + encoding: "utf8", + env: { PATH: process.env.PATH, [credentialEnv]: handle }, + }); + expect(result.status).toBe(0); + expect(result.stdout).toBe( + `${anthropic ? "x-api-key: " : "Authorization: Bearer "}${handle}`, + ); + expect(result.stderr).toBe(""); + }); + }); + + it.each([ + "", + "sk-real-secret", + "unused", + "nemoclaw-openshell-provider", + "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", + "openshell:resolve:env:v42_OTHER_KEY", + "openshell:resolve:env:sabc_NVIDIA_INFERENCE_API_KEY", + "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY\nInjected: value", + "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY\n", + ])("refuses invalid workload input without exposing it or continuing (%#)", (handle) => { + const command = [ + ...nativeInferenceProbeAuthScript("NVIDIA_INFERENCE_API_KEY"), + 'printf "request-started"', + ].join("; "); + const result = spawnSync("/bin/sh", ["-c", command], { + encoding: "utf8", + env: { PATH: process.env.PATH, NVIDIA_INFERENCE_API_KEY: handle }, + }); + expect(result.status).toBe(1); + expect(result.stdout).toBe("credential-handle-unavailable\n"); + expect(result.stderr).toBe(""); + }); +}); diff --git a/src/lib/inference/probe/native-inference-probe-auth.ts b/src/lib/inference/probe/native-inference-probe-auth.ts new file mode 100644 index 00000000000..de8f67981cd --- /dev/null +++ b/src/lib/inference/probe/native-inference-probe-auth.ts @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { NativeHostedProfile } from "../native-hosted/profiles"; + +/** Consume only the identity-bound handle OpenShell issued inside the workload. */ +export function nativeInferenceProbeAuthScript( + credentialEnv: NativeHostedProfile["credentialEnv"], + anthropic = false, +): string[] { + const pattern = `^openshell:resolve:env:(v[0-9]+|s[0-9a-f]{64})_${credentialEnv}$`; + return [ + `native_handle="\${${credentialEnv}:-}"`, + // Reject control characters as well as real keys and unversioned aliases. + `case "$native_handle" in *[!a-zA-Z0-9:_]*) printf 'credential-handle-unavailable\\n'; exit 1 ;; esac`, + `printf '%s' "$native_handle" | LC_ALL=C grep -Eq '${pattern}' || { printf 'credential-handle-unavailable\\n'; exit 1; }`, + `AUTH_HEADER='${anthropic ? "x-api-key: " : "Authorization: Bearer "}'"$native_handle"`, + ]; +} diff --git a/src/lib/onboard/abandoned-route-reservation.test.ts b/src/lib/onboard/abandoned-route-reservation.test.ts index f0c9c68f4e4..74ca8a2ec68 100644 --- a/src/lib/onboard/abandoned-route-reservation.test.ts +++ b/src/lib/onboard/abandoned-route-reservation.test.ts @@ -95,16 +95,24 @@ describe("abandoned inference route reservation (#11051)", () => { const { baseOptions, baseSelection, createDeps } = await import("./machine/handlers/provider-inference.test-support"); const session = sessionStore.loadSession()!; - Object.assign(session, baseSelection, { sandboxName: SANDBOX }); + const legacySelection = { + ...baseSelection, + provider: "compatible-endpoint", + model: "local/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: null, + preferredInferenceApi: "openai-completions", + }; + Object.assign(session, legacySelection, { sandboxName: SANDBOX }); session.steps.provider_selection.status = "complete"; session.steps.inference.status = "complete"; sessionStore.saveSession(session); const route = { - provider: baseSelection.provider, - model: baseSelection.model, - endpointUrl: baseSelection.endpointUrl, - credentialEnv: baseSelection.credentialEnv, - preferredInferenceApi: baseSelection.preferredInferenceApi, + provider: legacySelection.provider, + model: legacySelection.model, + endpointUrl: legacySelection.endpointUrl, + credentialEnv: legacySelection.credentialEnv, + preferredInferenceApi: legacySelection.preferredInferenceApi, endpointSource: null, gatewayName: GATEWAY, }; diff --git a/src/lib/onboard/build-credential-reuse.test.ts b/src/lib/onboard/build-credential-reuse.test.ts index 5c363d85bee..9bc300d1442 100644 --- a/src/lib/onboard/build-credential-reuse.test.ts +++ b/src/lib/onboard/build-credential-reuse.test.ts @@ -38,20 +38,39 @@ it.each([ }, ); -it("rejects malformed persisted native authority before looking up a provider", async () => { +it.each(["nativeNvidiaProviderAttachment", "nativeHostedProviderAttachment"])( + "rejects malformed persisted %s before looking up a provider", + async (field) => { + vi.spyOn(credentials, "resolveProviderCredential").mockReturnValue(null); + const getSandbox = vi.fn().mockReturnValue({ + name: "alpha", + [field]: { ...attachment, providerId: "" }, + }); + const providerExistsInGateway = vi.fn().mockResolvedValue(true); + await expect( + resolveNonInteractiveBuildCredential({ + helpUrl: null, + recovery: { recoveredFromSandbox: true, sandboxName: "alpha" }, + getSandbox, + providerExistsInGateway, + }), + ).rejects.toThrow("Malformed native NVIDIA provider attachment"); + expect(providerExistsInGateway).not.toHaveBeenCalled(); + }, +); + +it("reuses the generic persisted NVIDIA receipt during keyless recreation", async () => { vi.spyOn(credentials, "resolveProviderCredential").mockReturnValue(null); - const getSandbox = vi.fn().mockReturnValue({ - name: "alpha", - nativeNvidiaProviderAttachment: { ...attachment, providerId: "" }, - }); const providerExistsInGateway = vi.fn().mockResolvedValue(true); - await expect( - resolveNonInteractiveBuildCredential({ - helpUrl: null, - recovery: { recoveredFromSandbox: true, sandboxName: "alpha" }, - getSandbox, - providerExistsInGateway, + const result = await resolveNonInteractiveBuildCredential({ + helpUrl: null, + recovery: { recoveredFromSandbox: true, sandboxName: "alpha" }, + getSandbox: () => ({ + nativeNvidiaProviderAttachment: undefined, + nativeHostedProviderAttachment: attachment, }), - ).rejects.toThrow("Malformed native NVIDIA provider attachment"); - expect(providerExistsInGateway).not.toHaveBeenCalled(); + providerExistsInGateway, + }); + expect(result).toBe(true); + expect(providerExistsInGateway).toHaveBeenCalledExactlyOnceWith("nemoclaw-nvidia-prod-v1"); }); diff --git a/src/lib/onboard/build-credential-reuse.ts b/src/lib/onboard/build-credential-reuse.ts index 2fac36af000..82bbe2ad431 100644 --- a/src/lib/onboard/build-credential-reuse.ts +++ b/src/lib/onboard/build-credential-reuse.ts @@ -30,15 +30,19 @@ import { logMissingNvidiaApiKeyHelp } from "./missing-credential-hints"; export async function resolveNonInteractiveBuildCredential(opts: { helpUrl: string | null | undefined; recovery: { recoveredFromSandbox: boolean; sandboxName?: string | null }; - getSandbox: (name: string) => { nativeNvidiaProviderAttachment?: unknown } | null; + getSandbox: (name: string) => { + nativeNvidiaProviderAttachment?: unknown; + nativeHostedProviderAttachment?: unknown; + } | null; providerExistsInGateway: (name: string) => boolean | Promise; }): Promise { const { helpUrl, recovery, providerExistsInGateway } = opts; const { recoveredFromSandbox, sandboxName } = recovery; + const recovered = recoveredFromSandbox && sandboxName ? opts.getSandbox(sandboxName) : null; const recordedAttachment = - recoveredFromSandbox && sandboxName - ? opts.getSandbox(sandboxName)?.nativeNvidiaProviderAttachment - : undefined; + recovered?.nativeHostedProviderAttachment !== undefined + ? recovered.nativeHostedProviderAttachment + : recovered?.nativeNvidiaProviderAttachment; const nativeAttachment = normalizeNativeNvidiaProviderAttachment(recordedAttachment); if (recordedAttachment !== undefined && !nativeAttachment) { throw new Error("Malformed native NVIDIA provider attachment"); diff --git a/src/lib/onboard/dcode-selection-drift.test.ts b/src/lib/onboard/dcode-selection-drift.test.ts index c005e94c845..fedd53380df 100644 --- a/src/lib/onboard/dcode-selection-drift.test.ts +++ b/src/lib/onboard/dcode-selection-drift.test.ts @@ -114,6 +114,7 @@ describe("live DCode selection drift", () => { it("accepts the generated OpenRouter identity (#9555)", async () => { const output = identity({ + Endpoint: "https://openrouter.ai/api/v1", Provider: "openrouter", Model: "openrouter:nvidia/nemotron-3-ultra-550b-a55b", }); diff --git a/src/lib/onboard/dockerfile-patch.test.ts b/src/lib/onboard/dockerfile-patch.test.ts index 00d7da9d9e5..da3656b3a13 100644 --- a/src/lib/onboard/dockerfile-patch.test.ts +++ b/src/lib/onboard/dockerfile-patch.test.ts @@ -1049,7 +1049,7 @@ describe("dockerfile patch helpers", () => { assert.match(patched, /^ARG NEMOCLAW_MODEL=claude-sonnet-4-5$/m); assert.match(patched, /^ARG NEMOCLAW_PROVIDER_KEY=anthropic$/m); assert.match(patched, /^ARG NEMOCLAW_PRIMARY_MODEL_REF=anthropic\/claude-sonnet-4-5$/m); - assert.match(patched, /^ARG NEMOCLAW_INFERENCE_BASE_URL=https:\/\/inference\.local$/m); + assert.match(patched, /^ARG NEMOCLAW_INFERENCE_BASE_URL=https:\/\/api\.anthropic\.com$/m); assert.match(patched, /^ARG NEMOCLAW_INFERENCE_API=anthropic-messages$/m); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); diff --git a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts index 4e4d0edbc04..961a28d2b8e 100644 --- a/src/lib/onboard/experimental/hermes-portable-build-context-files.ts +++ b/src/lib/onboard/experimental/hermes-portable-build-context-files.ts @@ -144,6 +144,8 @@ export const HERMES_PORTABLE_BUILD_CONTEXT_FILES = [ mode: "100644", }, { path: "src/lib/hermes-managed-route.ts", mode: "100644" }, + { path: "src/lib/inference/native-hosted/openrouter-headers.ts", mode: "100644" }, + { path: "src/lib/inference/native-hosted/profiles.ts", mode: "100644" }, { path: "src/lib/messaging/AGENTS.md", mode: "100644" }, { path: "src/lib/messaging/applier/agent-config-remove.test.ts", mode: "100644" }, { path: "src/lib/messaging/applier/agent-config.ts", mode: "100644" }, diff --git a/src/lib/onboard/experimental/hermes-portable-build-context.ts b/src/lib/onboard/experimental/hermes-portable-build-context.ts index a8ad23bdb68..1018f385fc9 100644 --- a/src/lib/onboard/experimental/hermes-portable-build-context.ts +++ b/src/lib/onboard/experimental/hermes-portable-build-context.ts @@ -87,6 +87,8 @@ const LOCAL_COPY_SOURCES = [ "ci/reviewed-npm-audit.json", "src/lib/actions/sandbox/openshell-child-visible-credentials.v0.0.116.json", "src/lib/hermes-managed-route.ts", + "src/lib/inference/native-hosted/openrouter-headers.ts", + "src/lib/inference/native-hosted/profiles.ts", "src/lib/messaging/", "src/lib/messaging/channels/googlechat/runtime/hermes-adapter.py", "src/lib/tool-disclosure.ts", diff --git a/src/lib/onboard/inference-providers/hermes.test.ts b/src/lib/onboard/inference-providers/hermes.test.ts index 36e720c2cfe..a7c557edd12 100644 --- a/src/lib/onboard/inference-providers/hermes.test.ts +++ b/src/lib/onboard/inference-providers/hermes.test.ts @@ -410,3 +410,51 @@ describe("setupHermesProviderInference SSRF guard (#6072)", () => { expect(deps.runOpenshell).not.toHaveBeenCalled(); }); }); + +describe("native Hermes inference preparation", () => { + it("uses the canonical endpoint without custom DNS rewriting and forwards provider identity", async () => { + const lookup = vi.fn(() => { + throw new Error("must not resolve"); + }); + const deps = makeDeps({ resolveHermesNousApiKey: vi.fn(() => "nous-key"), lookup }); + const expected = { + schemaVersion: 1 as const, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "recorded-id", + }; + await expect( + setupHermesProviderInference( + { + ...makeArgs("https://inference-api.nousresearch.com/v1"), + nativeProvider: true, + expectedNativeProviderAttachment: expected, + }, + deps as any, + ), + ).resolves.toEqual({ ok: true, nativeHostedProviderAttachment: expected }); + expect(deps.hermesProviderAuth.ensureHermesProviderApiKeyCredentials).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ expected }), + ); + expect(lookup).not.toHaveBeenCalled(); + expect(deps.runOpenshell).not.toHaveBeenCalled(); + expect(deps.verifyInferenceRoute).not.toHaveBeenCalled(); + }); + + it("rejects a noncanonical native endpoint before credential acquisition", async () => { + const deps = makeDeps(); + await expect( + setupHermesProviderInference( + { + ...makeArgs("https://different.example/v1"), + nativeProvider: true, + }, + deps as any, + ), + ).rejects.toThrow("canonical endpoint"); + expect(deps.checkHermesProviderStoreReachable).not.toHaveBeenCalled(); + expect(deps.hermesProviderAuth.ensureHermesProviderOAuthCredentials).not.toHaveBeenCalled(); + expect(deps.hermesProviderAuth.ensureHermesProviderApiKeyCredentials).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/onboard/inference-providers/hermes.ts b/src/lib/onboard/inference-providers/hermes.ts index 6270faea04b..7d008b326c6 100644 --- a/src/lib/onboard/inference-providers/hermes.ts +++ b/src/lib/onboard/inference-providers/hermes.ts @@ -4,12 +4,19 @@ // Hermes Provider inference setup flow. // Extracted verbatim from onboard.setupInference (#767). +import { + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../inference/native-hosted"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { rewriteConfigUrlsWithDnsPinning } from "../../sandbox/config"; import type { HermesAuthMethod } from "../hermes-auth"; import type { HermesDeps, SetupInferenceResult } from "./types"; export async function setupHermesProviderInference( args: { + nativeProvider?: boolean; + expectedNativeProviderAttachment?: NativeHostedProviderAttachment; sandboxName: string | null; model: string; provider: string; @@ -34,7 +41,13 @@ export async function setupHermesProviderInference( // inference route), so SSRF validation only applies to an explicitly-supplied // custom endpoint. let resolvedEndpointUrl = endpointUrl; - if (endpointUrl) { + if (args.nativeProvider && endpointUrl) { + const canonical = nativeHostedProfile("hermes-provider")!.endpoint; + if (endpointUrl.replace(/\/+$/u, "") !== canonical) { + throw new Error("Hermes Provider native inference requires its canonical endpoint."); + } + } + if (endpointUrl && !args.nativeProvider) { let parsedEndpoint: URL; try { parsedEndpoint = new URL(endpointUrl); @@ -125,6 +138,7 @@ export async function setupHermesProviderInference( !toolGatewayProviderRegistered || hasFreshNousApiKey || (resolvedHermesAuthMethod === HERMES_AUTH_METHOD_OAUTH && !isNonInteractive()); + let preparedAttachment = args.expectedNativeProviderAttachment; if (shouldPrepareHermesCredentials) { let state: unknown; try { @@ -134,11 +148,17 @@ export async function setupHermesProviderInference( apiKey: resolveHermesNousApiKey(), runOpenshell, baseUrl: resolvedEndpointUrl || undefined, + ...(args.expectedNativeProviderAttachment + ? { expected: args.expectedNativeProviderAttachment } + : {}), }) : await hermesProviderAuth.ensureHermesProviderOAuthCredentials(targetSandbox, { allowInteractiveLogin: !isNonInteractive(), runOpenshell, baseUrl: resolvedEndpointUrl || undefined, + ...(args.expectedNativeProviderAttachment + ? { expected: args.expectedNativeProviderAttachment } + : {}), toolGatewayPresets: hermesToolGateways, }); } catch (err) { @@ -150,6 +170,12 @@ export async function setupHermesProviderInference( if (isNonInteractive()) return exitProcess(1); return { retry: "selection" }; } + if (state && typeof state === "object") { + preparedAttachment = + normalizeNativeHostedProviderAttachment( + (state as { nativeHostedProviderAttachment?: unknown }).nativeHostedProviderAttachment, + ) ?? preparedAttachment; + } if (!state) { const authLabel = hermesAuthMethodLabel(resolvedHermesAuthMethod); error(` ✗ Hermes Provider ${authLabel} is not available on the host.`); @@ -158,6 +184,8 @@ export async function setupHermesProviderInference( } } + if (args.nativeProvider) return { ok: true, nativeHostedProviderAttachment: preparedAttachment }; + const applyResult = await inferenceRouteMutator.setInferenceRoute({ target: { kind: "named", gatewayName }, route: { provider, model }, @@ -176,6 +204,7 @@ export async function setupHermesProviderInference( applyResult.error.kind === "command" ? (applyResult.error.exitCode ?? 1) : 1, ); } + return { retry: "selection" }; } diff --git a/src/lib/onboard/inference-providers/types.ts b/src/lib/onboard/inference-providers/types.ts index 66c4e39d75b..3c95a0b4575 100644 --- a/src/lib/onboard/inference-providers/types.ts +++ b/src/lib/onboard/inference-providers/types.ts @@ -15,13 +15,16 @@ // so they accept whatever the orchestrator hands in without needing to // duplicate every helper's exact signature. +import type { NativeHostedProviderAttachment } from "../../inference/native-hosted"; import type { TrustedPrivateEndpointCapability } from "../../inference/endpoint-ssrf-preflight"; import type { OpenShellInferenceRouteMutator } from "../../adapters/openshell/inference-route"; import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; import type { HermesAuthMethod } from "../hermes-auth"; import type { OnboardInferenceCapabilityCache } from "../inference-capability-cache"; -export type SetupInferenceResult = { ok: true; retry?: undefined } | { retry: "selection" }; +export type SetupInferenceResult = + | { ok: true; retry?: undefined; nativeHostedProviderAttachment?: NativeHostedProviderAttachment } + | { retry: "selection" }; export type RunOpenshell = ( args: string[], @@ -187,7 +190,12 @@ export type HermesDeps = CommonDeps & isHermesProviderRegistered(runOpenshell: any): Promise; ensureHermesProviderApiKeyCredentials( sandboxName: string, - opts: { apiKey: unknown; runOpenshell: any; baseUrl?: string | undefined }, + opts: { + apiKey: unknown; + runOpenshell: any; + baseUrl?: string | undefined; + expected?: NativeHostedProviderAttachment; + }, ): Promise; ensureHermesProviderOAuthCredentials( sandboxName: string, @@ -196,6 +204,7 @@ export type HermesDeps = CommonDeps & runOpenshell: any; baseUrl?: string | undefined; toolGatewayPresets: string[]; + expected?: NativeHostedProviderAttachment; }, ): Promise; }; diff --git a/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts b/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts index 48804c8000c..6b23e6b3cbe 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-openrouter-resume.test.ts @@ -7,50 +7,57 @@ import { createSession } from "../../../state/onboard-session"; import { handleProviderInferenceState } from "./provider-inference"; import { baseOptions, createDeps } from "./provider-inference.test-support"; -describe("OpenRouter provider inference resume", () => { - it("reconciles the adapter when resumed route metadata already matches", async () => { - const session = createSession({ - agent: "langchain-deepagents-code", - sandboxName: "deep-code", +describe("Native hosted provider inference resume", () => { + it.each([ + { provider: "openrouter-api", model: "moonshotai/kimi-k2.6", - credentialEnv: "OPENROUTER_API_KEY", - preferredInferenceApi: "openai-completions", - }); - session.steps.provider_selection.status = "complete"; - const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); - calls.complete.mockResolvedValue(session); + credential: "OPENROUTER_API_KEY", + resumeOptions: { skipHostInferenceSmoke: true, reuseGatewayCredentialWithoutLocalKey: true }, + }, + { provider: "openai-api", model: "gpt-4.1", credential: "OPENAI_API_KEY", resumeOptions: {} }, + ])( + "reconciles $provider when shared route metadata already matches", + async ({ provider, model, credential, resumeOptions }) => { + const session = createSession({ + agent: "langchain-deepagents-code", + sandboxName: "deep-code", + provider, + model, + credentialEnv: credential, + preferredInferenceApi: "openai-completions", + }); + session.steps.provider_selection.status = "complete"; + const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); + calls.complete.mockResolvedValue(session); - await handleProviderInferenceState({ - ...baseOptions(deps, session), - resume: true, - sandboxName: "deep-code", - agent: { name: "langchain-deepagents-code" }, - }); + await handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "deep-code", + agent: { name: "langchain-deepagents-code" }, + }); - expect(calls.setupNim).not.toHaveBeenCalled(); - expect(calls.skipped).not.toHaveBeenCalledWith( - "inference", - "openrouter-api / moonshotai/kimi-k2.6", - ); - expect(calls.setupInference).toHaveBeenCalledWith( - "deep-code", - "moonshotai/kimi-k2.6", - "openrouter-api", - null, - "OPENROUTER_API_KEY", - null, - [], - { - gatewayName: "nemoclaw", - allowToolsIncompatible: false, - skipHostInferenceSmoke: true, - reuseGatewayCredentialWithoutLocalKey: true, - preferredInferenceApi: "openai-completions", - endpointSource: null, - reservationSessionId: session.sessionId, - }, - ); - expect(calls.deleteEnv).toHaveBeenCalledWith("OPENROUTER_API_KEY"); - }); + expect(calls.setupNim).not.toHaveBeenCalled(); + expect(calls.skipped).not.toHaveBeenCalledWith("inference", `${provider} / ${model}`); + expect(calls.setupInference).toHaveBeenCalledWith( + "deep-code", + model, + provider, + null, + credential, + null, + [], + { + gatewayName: "nemoclaw", + allowToolsIncompatible: false, + ...resumeOptions, + preferredInferenceApi: "openai-completions", + endpointSource: null, + reservationSessionId: session.sessionId, + }, + ); + expect(calls.deleteEnv).toHaveBeenCalledWith(credential); + }, + ); }); diff --git a/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts b/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts index 3e6ebc09431..8e424552cab 100644 --- a/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference-resume-requested-name.test.ts @@ -16,10 +16,10 @@ import { baseOptions, createDeps } from "./provider-inference.test-support"; function interruptedResumeSession() { const session = createSession({ - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; diff --git a/src/lib/onboard/machine/handlers/provider-inference.test.ts b/src/lib/onboard/machine/handlers/provider-inference.test.ts index 49a7518110e..2b5446c9396 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test.ts @@ -333,7 +333,11 @@ describe("handleProviderInferenceState", () => { }); it("stops an authoritative rebuild before inference state when route persistence throws", async () => { - const session = createSession({ provider: "openai-api", model: "gpt-test" }); + const session = createSession({ + provider: "compatible-endpoint", + model: "gpt-test", + endpointUrl: "http://127.0.0.1:8000/v1", + }); const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); calls.reserveRoute.mockImplementation(() => { throw new Error("registry save failed"); @@ -600,10 +604,10 @@ describe("handleProviderInferenceState", () => { it("reserves the prompted sandbox route when resume skips already-ready inference (#6562)", async () => { const session = createSession({ - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; @@ -622,11 +626,11 @@ describe("handleProviderInferenceState", () => { expect(calls.setupNim).not.toHaveBeenCalled(); expect(calls.setupInference).not.toHaveBeenCalled(); expect(calls.reserveRoute).toHaveBeenCalledWith("tm", { - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", endpointSource: "inference-set", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", gatewayName: "nemoclaw", reservationSessionId: session.sessionId, @@ -642,10 +646,10 @@ describe("handleProviderInferenceState", () => { async (_label, identity) => { const session = createSession({ sandboxName: "stale-sandbox", - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; @@ -674,10 +678,10 @@ describe("handleProviderInferenceState", () => { it("does not reserve a route when resume skips inference after sandbox completion (#6562)", async () => { const session = createSession({ sandboxName: "completed-sandbox", - provider: "nvidia-prod", - model: "nvidia/nemotron-test", - endpointUrl: "https://integrate.api.nvidia.com/v1", - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", }); session.steps.provider_selection.status = "complete"; @@ -702,6 +706,13 @@ describe("handleProviderInferenceState", () => { const completedSelection = createSession({ sessionId: "resume-selection-session" }); const { deps, calls } = createDeps({ isInferenceRouteReady: vi.fn(() => true) }); calls.complete.mockResolvedValueOnce(completedSelection); + calls.setupNim.mockResolvedValueOnce({ + ...baseSelection, + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", + credentialEnv: "COMPATIBLE_API_KEY", + }); calls.promptName.mockResolvedValue("tm"); const result = await handleProviderInferenceState({ @@ -714,11 +725,11 @@ describe("handleProviderInferenceState", () => { expect(calls.setupInference).not.toHaveBeenCalled(); expect(calls.promptName).toHaveBeenCalledWith(null); expect(calls.reserveRoute).toHaveBeenCalledWith("tm", { - provider: "nvidia-prod", - model: "nvidia/test", - endpointUrl: "https://integrate.api.nvidia.com/v1", + provider: "compatible-endpoint", + model: "compatible/test", + endpointUrl: "http://127.0.0.1:8000/v1", endpointSource: null, - credentialEnv: "NVIDIA_INFERENCE_API_KEY", + credentialEnv: "COMPATIBLE_API_KEY", preferredInferenceApi: "openai-responses", gatewayName: "nemoclaw", reservationSessionId: "resume-selection-session", diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index 7368b0e5435..9c5eeb76b4d 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { clearAutoDetectedCompatibleContextWindow } from "../../../inference/compatible-endpoint-context"; -import { resolveAgentProviderInferenceApi } from "../../../inference/config"; +import { nativeHostedProfile, resolveAgentProviderInferenceApi } from "../../../inference/config"; import type { TrustedPrivateEndpointCapability } from "../../../inference/endpoint-ssrf-preflight"; import { type CurrentGatewayRouteCompatibilityCheck, @@ -532,7 +532,7 @@ function canResumeInferenceRoute(input: { }): boolean { return ( !input.needsBedrockRuntimeAdapter && - input.provider !== OPENROUTER_PROVIDER_NAME && + !nativeHostedProfile(input.provider) && !input.hasHostLocalInference && !input.forceProviderSelection && !input.forceInferenceSetup && diff --git a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts index 21e87bcfa27..b910ef270e5 100644 --- a/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts +++ b/src/lib/onboard/machine/handlers/sandbox-create-intent-boundary.test.ts @@ -42,8 +42,8 @@ describe("sandbox create intent machine boundary", () => { }); it("attaches the internal native NVIDIA provider while retaining the logical selection", async () => { - const session = createSession({ sandboxName: "native-nvidia" }); - const nativeNvidiaProviderAttachment = { + const session = createSession({ sandboxName: "native-hosted" }); + const nativeHostedProviderAttachment = { schemaVersion: 1 as const, profileId: "nemoclaw-nvidia-inference-v1" as const, providerName: "nemoclaw-nvidia-prod-v1" as const, @@ -60,26 +60,26 @@ describe("sandbox create intent machine boundary", () => { toolDisclosure: "progressive" as const, fromDockerfile: null, hermesAuthMethod: null, - nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment, }), }); await handleSandboxState({ ...baseOptions(deps, session), - sandboxName: "native-nvidia", + sandboxName: "native-hosted", provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", }); expect(calls.resolveCreateIntent).toHaveBeenCalledWith( expect.objectContaining({ - sandboxName: "native-nvidia", + sandboxName: "native-hosted", inferenceProvider: "nemoclaw-nvidia-prod-v1", - nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment, }), ); expect(calls.startStep).toHaveBeenCalledWith("sandbox", { - sandboxName: "native-nvidia", + sandboxName: "native-hosted", provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", }); diff --git a/src/lib/onboard/machine/handlers/sandbox.ts b/src/lib/onboard/machine/handlers/sandbox.ts index 8829a674b57..e2a113df401 100644 --- a/src/lib/onboard/machine/handlers/sandbox.ts +++ b/src/lib/onboard/machine/handlers/sandbox.ts @@ -7,7 +7,7 @@ import { type GatewayRouteCompatibilityResult, isAdvisoryGatewayRouteConflict, nativeInferenceProviderForSandbox, - normalizeNativeNvidiaProviderAttachment, + normalizeNativeHostedProviderAttachment, } from "../../../inference/gateway-route-compatibility"; import type { InferenceEndpointSource } from "../../../inference/selection"; import { @@ -133,19 +133,19 @@ type SandboxRecreateWorkloadSkipReason = Extract< { readonly status: "skipped" } >["reason"]; -function nativeNvidiaCreateIntentFields( +function nativeHostedCreateIntentFields( provider: string | null | undefined, entry: SandboxEntry | null, ): { inferenceProvider: string | null; - nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; } { - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - entry?.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + entry?.nativeHostedProviderAttachment, ); return { inferenceProvider: nativeInferenceProviderForSandbox(provider), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), }; } @@ -371,7 +371,7 @@ export interface SandboxStateOptions< resolveSandboxCreateIntent(input: { sandboxName: string; inferenceProvider?: string | null; - nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[]; webSearchConfig: WebSearchConfig | null; @@ -1880,7 +1880,7 @@ class SandboxStateFlow< const reuseRegisteredCredentials = this.resumesSandboxPrompts && this.options.resume; const resolved = await this.deps.resolveSandboxCreateIntent({ sandboxName, - ...nativeNvidiaCreateIntentFields( + ...nativeHostedCreateIntentFields( this.options.provider, this.deps.getSandboxRegistryEntry(sandboxName), ), diff --git a/src/lib/onboard/machine/resume-provider-shim.test.ts b/src/lib/onboard/machine/resume-provider-shim.test.ts index 3c33eb3f0c5..90d268f2455 100644 --- a/src/lib/onboard/machine/resume-provider-shim.test.ts +++ b/src/lib/onboard/machine/resume-provider-shim.test.ts @@ -3,13 +3,30 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -vi.mock("../../credentials/store", () => ({ +vi.mock("../../credentials/store", async (importOriginal) => ({ + ...(await importOriginal()), resolveProviderCredential: vi.fn(() => null), })); import { createResumeProviderShim } from "./resume-provider-shim"; describe("createResumeProviderShim", () => { + it("resumes a native provider using its owned gateway name without a host key", async () => { + const providerExistsInGateway = vi.fn(() => true); + const replaceNamedCredential = vi.fn(); + const shim = createResumeProviderShim({ + isNonInteractive: () => true, + providerExistsInGateway, + isRoutedInferenceProvider: () => false, + replaceNamedCredential, + }); + await expect( + shim.ensureResumeProviderReady("gateway-west", "openai-api", "OPENAI_API_KEY"), + ).resolves.toEqual({ forceInferenceSetup: false, credentialEnv: "OPENAI_API_KEY" }); + expect(providerExistsInGateway).toHaveBeenCalledWith("nemoclaw-openai-api-v1", "gateway-west"); + expect(replaceNamedCredential).not.toHaveBeenCalled(); + }); + afterEach(() => { vi.restoreAllMocks(); }); diff --git a/src/lib/onboard/machine/resume-provider-shim.ts b/src/lib/onboard/machine/resume-provider-shim.ts index 5380eecc80e..9ebf4a419fa 100644 --- a/src/lib/onboard/machine/resume-provider-shim.ts +++ b/src/lib/onboard/machine/resume-provider-shim.ts @@ -3,6 +3,7 @@ import { runOpenshell } from "../../adapters/openshell/runtime"; import { D, R } from "../../cli/terminal-style"; import { isBedrockRuntimeEndpoint } from "../../inference/bedrock-runtime"; +import { nativeHostedProfile } from "../../inference/native-hosted/profiles"; import { DEFAULT_ROUTE_CREDENTIAL_ENV } from "../../inference/config"; import { validateNvidiaApiKeyValue } from "../../validation"; import { hydrateCredentialEnv } from "../credential-env"; @@ -55,7 +56,11 @@ export function createResumeProviderShim(deps: ResumeProviderShimDeps) { remoteProviderConfig: onboardProviders.REMOTE_PROVIDER_CONFIG, defaultRouteCredentialEnv: DEFAULT_ROUTE_CREDENTIAL_ENV, isRoutedInferenceProvider: deps.isRoutedInferenceProvider, - providerExistsInGateway: (name) => deps.providerExistsInGateway(name, gatewayName), + providerExistsInGateway: (name) => + deps.providerExistsInGateway( + nativeHostedProfile(name)?.providerName ?? name, + gatewayName, + ), hydrateCredentialEnv, getProviderLabel: onboardProviders.getProviderLabel, isNonInteractive: deps.isNonInteractive, diff --git a/src/lib/onboard/provider-recovery.ts b/src/lib/onboard/provider-recovery.ts index adf520a4c74..1f975ab6157 100644 --- a/src/lib/onboard/provider-recovery.ts +++ b/src/lib/onboard/provider-recovery.ts @@ -145,6 +145,7 @@ export interface ProviderRecoveryHelpers extends ProviderSelectionRecoveryReader } export interface RecordedInferenceRoute { + nativeHostedProviderAttachment?: import("../inference/native-hosted").NativeHostedProviderAttachment; provider: string; model: string; endpointUrl: string | null; @@ -215,6 +216,7 @@ function completeRecordedInferenceRoute( endpointUrl?: unknown; endpointSource?: unknown; preferredInferenceApi?: unknown; + nativeHostedProviderAttachment?: import("../inference/native-hosted").NativeHostedProviderAttachment; }, source: RecordedInferenceRoute["source"], ): RecordedInferenceRoute | null { @@ -232,7 +234,16 @@ function completeRecordedInferenceRoute( const endpointSource = endpointUrl ? normalizeInferenceEndpointSource(value.endpointSource) : null; - return { ...inference, endpointUrl, endpointSource, preferredInferenceApi, source }; + return { + ...inference, + endpointUrl, + endpointSource, + preferredInferenceApi, + source, + ...(source === "registry" && value.nativeHostedProviderAttachment + ? { nativeHostedProviderAttachment: value.nativeHostedProviderAttachment } + : {}), + }; } export function createProviderRecoveryHelpers(deps: ProviderRecoveryDeps): ProviderRecoveryHelpers { diff --git a/src/lib/onboard/providers.ts b/src/lib/onboard/providers.ts index 0a5654eaf5d..e07016ea690 100644 --- a/src/lib/onboard/providers.ts +++ b/src/lib/onboard/providers.ts @@ -18,8 +18,8 @@ const { isSafeModelId } = require("../validation"); const { compactText } = require("../core/url-utils"); const { createCliOpenShellProviderAdapter } = require("../adapters/openshell/provider-adapter-cli"); const { - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, + getNativeHostedProviderAuthority, + setNativeHostedProviderAuthority, } = require("../state/registry/native-nvidia-provider-authority"); const { LLAMA_CPP_CREDENTIAL_ENV, @@ -397,8 +397,8 @@ function setupInferenceProviderDeps(runOpenshell) { return { providerExistsInGateway, providerAdapter: createCliOpenShellProviderAdapter({ run: runOpenshell }), - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, + getNativeHostedProviderAuthority, + setNativeHostedProviderAuthority, }; } diff --git a/src/lib/onboard/rebuild-route-handoff.test.ts b/src/lib/onboard/rebuild-route-handoff.test.ts index 525c49e6f61..d0bfffa5e78 100644 --- a/src/lib/onboard/rebuild-route-handoff.test.ts +++ b/src/lib/onboard/rebuild-route-handoff.test.ts @@ -204,3 +204,19 @@ describe("createProviderRecoveryReceiptLedger", () => { ).toBe(false); }); }); + +it("preserves an immutable native provider identity across destructive rebuild handoff", () => { + const attachment = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }; + const handoff = createRebuildRouteHandoff("alpha", { + ...registryRoute(), + nativeHostedProviderAttachment: attachment, + }); + attachment.providerId = "changed"; + expect(handoff.route.nativeHostedProviderAttachment?.providerId).toBe("recorded-id"); + expect(Object.isFrozen(handoff.route.nativeHostedProviderAttachment)).toBe(true); +}); diff --git a/src/lib/onboard/rebuild-route-handoff.ts b/src/lib/onboard/rebuild-route-handoff.ts index 72a15f2df98..4d23d6478f7 100644 --- a/src/lib/onboard/rebuild-route-handoff.ts +++ b/src/lib/onboard/rebuild-route-handoff.ts @@ -43,6 +43,13 @@ export function createRebuildRouteHandoff( endpointSource: route.endpointSource ?? null, preferredInferenceApi: route.preferredInferenceApi, source: "registry", + ...(route.nativeHostedProviderAttachment + ? { + nativeHostedProviderAttachment: Object.freeze({ + ...route.nativeHostedProviderAttachment, + }), + } + : {}), }); return Object.freeze({ sandboxName, route: frozenRoute }); } @@ -116,6 +123,13 @@ function freezeRoute(route: RegistryInferenceRoute): RegistryInferenceRoute { endpointSource: route.endpointSource ?? null, preferredInferenceApi: route.preferredInferenceApi, source: "registry", + ...(route.nativeHostedProviderAttachment + ? { + nativeHostedProviderAttachment: Object.freeze({ + ...route.nativeHostedProviderAttachment, + }), + } + : {}), }); } @@ -125,7 +139,13 @@ function routesMatch(left: RegistryInferenceRoute, right: RegistryInferenceRoute left.model === right.model && left.endpointUrl === right.endpointUrl && (left.endpointSource ?? null) === (right.endpointSource ?? null) && - left.preferredInferenceApi === right.preferredInferenceApi + left.preferredInferenceApi === right.preferredInferenceApi && + left.nativeHostedProviderAttachment?.profileId === + right.nativeHostedProviderAttachment?.profileId && + left.nativeHostedProviderAttachment?.providerName === + right.nativeHostedProviderAttachment?.providerName && + left.nativeHostedProviderAttachment?.providerId === + right.nativeHostedProviderAttachment?.providerId ); } diff --git a/src/lib/onboard/recovered-provider-reuse.test.ts b/src/lib/onboard/recovered-provider-reuse.test.ts index 0cfc9961d00..9c60174ce15 100644 --- a/src/lib/onboard/recovered-provider-reuse.test.ts +++ b/src/lib/onboard/recovered-provider-reuse.test.ts @@ -55,51 +55,63 @@ describe("assessRecoveredProviderCredentialReuse", () => { }); it.each( - Array.from([[], ["WRONG_BASE_URL"], ["OPENAI_BASE_URL", "EXTRA_FLAG"]], (value) => [value]), - )( - "requires the exact endpoint-config binding for built-in provider recovery [case %#]", - (configKeys) => { - const builtInOpenAi = { - ...completeRecovery, - selectedKey: "openai", - selectedProvider: "openai-api", - recoveredProvider: "openai-api", - expectedCredentialEnv: "OPENAI_API_KEY", - gatewayProvider: { - name: "openai-api", - type: "openai", - credentialKeys: ["OPENAI_API_KEY"], - configKeys: ["OPENAI_BASE_URL"], - }, - endpointIdentity: undefined, - }; + Array.from( + [["OPENAI_BASE_URL"], ["WRONG_BASE_URL"], ["OPENAI_BASE_URL", "EXTRA_FLAG"]], + (value) => [value], + ), + )("requires zero endpoint-config keys for native provider recovery [case %#]", (configKeys) => { + const builtInOpenAi = { + ...completeRecovery, + selectedKey: "openai", + selectedProvider: "openai-api", + recoveredProvider: "openai-api", + expectedNativeAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "recorded-id", + }, + expectedCredentialEnv: "OPENAI_API_KEY", + gatewayProvider: { + name: "nemoclaw-openai-api-v1", + type: "nemoclaw-openai-inference-v1", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + }, + endpointIdentity: undefined, + }; - expect(assessRecoveredProviderCredentialReuse(builtInOpenAi)).toMatchObject({ - kind: "reuse-gateway-credential", - }); + expect(assessRecoveredProviderCredentialReuse(builtInOpenAi)).toMatchObject({ + kind: "reuse-gateway-credential", + }); - expect( - assessRecoveredProviderCredentialReuse({ - ...builtInOpenAi, - gatewayProvider: { ...builtInOpenAi.gatewayProvider, configKeys }, - }), - ).toMatchObject({ kind: "reject" }); - }, - ); + expect( + assessRecoveredProviderCredentialReuse({ + ...builtInOpenAi, + gatewayProvider: { ...builtInOpenAi.gatewayProvider, configKeys }, + }), + ).toMatchObject({ kind: "reject" }); + }); - it("reuses OpenRouter when its distinct provider name is registered as OpenAI-compatible (#5826)", () => { + it("reuses OpenRouter when its distinct provider name is registered with its native profile", () => { expect( assessRecoveredProviderCredentialReuse({ ...completeRecovery, selectedKey: "openrouter", selectedProvider: "openrouter-api", recoveredProvider: "openrouter-api", + expectedNativeAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "recorded-id", + }, expectedCredentialEnv: "OPENROUTER_API_KEY", gatewayProvider: { - name: "openrouter-api", - type: "openai", + name: "nemoclaw-openrouter-api-v1", + type: "nemoclaw-openrouter-inference-v1", credentialKeys: ["OPENROUTER_API_KEY"], - configKeys: ["OPENAI_BASE_URL"], + configKeys: [], }, endpointIdentity: undefined, }), @@ -117,12 +129,18 @@ describe("assessRecoveredProviderCredentialReuse", () => { selectedProvider: "openrouter-api", recoveredProvider: "openrouter-api", recoveredPreferredInferenceApi: "openai-responses", + expectedNativeAttachment: { + schemaVersion: 1 as const, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "recorded-id", + }, expectedCredentialEnv: "OPENROUTER_API_KEY", gatewayProvider: { - name: "openrouter-api", - type: "openai", + name: "nemoclaw-openrouter-api-v1", + type: "nemoclaw-openrouter-inference-v1", credentialKeys: ["OPENROUTER_API_KEY"], - configKeys: ["OPENAI_BASE_URL"], + configKeys: [], }, endpointIdentity: undefined, }), diff --git a/src/lib/onboard/recovered-provider-reuse.ts b/src/lib/onboard/recovered-provider-reuse.ts index 9a6d91bd453..2b50def81d4 100644 --- a/src/lib/onboard/recovered-provider-reuse.ts +++ b/src/lib/onboard/recovered-provider-reuse.ts @@ -3,6 +3,11 @@ import { canonicalEndpoint, type EndpointFlavor } from "../core/url-utils"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; +import { + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../inference/native-hosted"; +import { nativeHostedProfile } from "../inference/native-hosted/profiles"; import { isSafeModelId } from "../validation"; import type { GatewayProviderMetadata } from "./gateway-provider-metadata"; import type { RecordedInferenceRoute } from "./provider-recovery"; @@ -112,6 +117,7 @@ export function assessRecoveredProviderCredentialReuse(options: { expectedCredentialEnv: string; gatewayProvider: GatewayProviderMetadata | null; endpointIdentity?: EndpointIdentity; + expectedNativeAttachment?: NativeHostedProviderAttachment; }): RecoveredProviderReuseDecision { if (options.hostCredentialAvailable) return { kind: "validate-host-credential" }; if (!options.recoveredFromSandbox) { @@ -149,6 +155,32 @@ export function assessRecoveredProviderCredentialReuse(options: { }; } const gatewayProvider = options.gatewayProvider; + const nativeProfile = nativeHostedProfile(selectedProvider); + if (nativeProfile) { + const expected = normalizeNativeHostedProviderAttachment(options.expectedNativeAttachment); + if ( + !expected || + expected.profileId !== nativeProfile.profileId || + expected.providerName !== nativeProfile.providerName || + !gatewayProvider || + gatewayProvider.name !== nativeProfile.providerName || + gatewayProvider.type !== nativeProfile.profileId || + gatewayProvider.credentialKeys.length !== 1 || + gatewayProvider.credentialKeys[0] !== nativeProfile.credentialEnv || + gatewayProvider.configKeys.length !== 0 + ) { + return { + kind: "reject", + condition: "gateway-provider-identity", + reason: `provider '${selectedProvider}' has no exact native identity in OpenShell`, + }; + } + return { + kind: "reuse-gateway-credential", + preferredInferenceApi: options.recoveredPreferredInferenceApi as string, + }; + } + // #6294: an OpenAI-only agent coerced onto openai-completions registers the // compatible-anthropic-endpoint provider as type=openai (OPENAI_BASE_URL), // so the reuse identity must expect that surface rather than the static @@ -270,7 +302,10 @@ export function resolveRecoveredProviderCredentialReuse( recoveredPreferredInferenceApi: recoveredRoute?.preferredInferenceApi, expectedProviderType: remoteConfig.providerType, expectedCredentialEnv: selectedCredentialEnv, - gatewayProvider: deps.readGatewayProviderMetadata(state.provider), + expectedNativeAttachment: recoveredRoute?.nativeHostedProviderAttachment, + gatewayProvider: deps.readGatewayProviderMetadata( + nativeHostedProfile(state.provider)?.providerName ?? state.provider, + ), endpointIdentity: customFlavor ? { flavor: customFlavor, diff --git a/src/lib/onboard/sandbox-create-intent-resolution.ts b/src/lib/onboard/sandbox-create-intent-resolution.ts index a258271e590..bbe505eb713 100644 --- a/src/lib/onboard/sandbox-create-intent-resolution.ts +++ b/src/lib/onboard/sandbox-create-intent-resolution.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { WebSearchConfig } from "../inference/web-search"; -import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; +import type { NativeHostedProviderAttachment } from "../inference/native-hosted"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; import type { NamedMessagingChannel } from "./messaging-prep"; import { @@ -27,7 +27,7 @@ import { export type CompleteSandboxCreateIntentInput = { sandboxName: string; inferenceProvider?: string | null; - nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + nativeHostedProviderAttachment?: NativeHostedProviderAttachment; hostLocalInferenceRouteOnly?: boolean; enabledChannels: readonly string[] | null; webSearchConfig: WebSearchConfig | null; @@ -146,7 +146,7 @@ export function createSandboxCreateIntentResolver< basePolicyPath: deps.getAgentPolicyPath(input.agent) || deps.defaultPolicyPath, sandboxName: input.sandboxName, inferenceProvider: input.inferenceProvider, - nativeNvidiaProviderAttachment: input.nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment: input.nativeHostedProviderAttachment, hostLocalInferenceRouteOnly: input.hostLocalInferenceRouteOnly === true, channels: deps.channels, enabledChannels: resolveSelectedChannels(input), diff --git a/src/lib/onboard/sandbox-create-intent-types.ts b/src/lib/onboard/sandbox-create-intent-types.ts index d12c693881f..d2eb3073735 100644 --- a/src/lib/onboard/sandbox-create-intent-types.ts +++ b/src/lib/onboard/sandbox-create-intent-types.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { SandboxHostMount } from "../state/registry/types"; -import type { NativeNvidiaProviderAttachment } from "../inference/native-nvidia"; +import type { NativeHostedProviderAttachment } from "../inference/native-hosted"; import type { MessagingChannelConfig } from "../messaging-channel-config"; import type { DockerGpuRoutePlan } from "./docker-gpu-route"; import type { InitialSandboxPolicy } from "./initial-policy"; @@ -48,7 +48,7 @@ export type SandboxCreatePolicyRequest = { export type SandboxCreateIntent = { readonly sandboxName: string; readonly inferenceProvider: string | null; - readonly nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + readonly nativeHostedProviderAttachment?: NativeHostedProviderAttachment; readonly activeMessagingChannels: readonly string[]; readonly messagingProviderRequests: readonly SandboxCreateMessagingProviderRequest[]; readonly reusableMessagingProviders: readonly string[]; @@ -70,7 +70,7 @@ export type ResolveSandboxCreateIntentInput = { basePolicyPath: string; sandboxName: string; inferenceProvider?: string | null; - nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; + nativeHostedProviderAttachment?: NativeHostedProviderAttachment; hostLocalInferenceRouteOnly?: boolean; channels: readonly MessagingChannel[]; enabledChannels: string[] | null; diff --git a/src/lib/onboard/sandbox-create-intent.ts b/src/lib/onboard/sandbox-create-intent.ts index a039c03849a..2ecfc6a5469 100644 --- a/src/lib/onboard/sandbox-create-intent.ts +++ b/src/lib/onboard/sandbox-create-intent.ts @@ -140,7 +140,7 @@ export function resolveSandboxCreateIntent({ basePolicyPath, sandboxName, inferenceProvider, - nativeNvidiaProviderAttachment, + nativeHostedProviderAttachment, hostLocalInferenceRouteOnly = false, channels, enabledChannels, @@ -188,7 +188,7 @@ export function resolveSandboxCreateIntent({ return { sandboxName, inferenceProvider: normalizedInferenceProvider, - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), activeMessagingChannels, messagingProviderRequests: messagingProviderRequests.map((request) => ({ ...request })), reusableMessagingProviders: enabledReusableMessagingProviders, diff --git a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts index d33208f7c6a..22545b3f24b 100644 --- a/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts +++ b/src/lib/onboard/sandbox-create/orchestration-native-nvidia.test.ts @@ -28,20 +28,27 @@ function providerAdapter(providerId: string): OpenShellProviderAdapter { } as unknown as OpenShellProviderAdapter; } -function nativeProviderBoundary(adapter: OpenShellProviderAdapter) { +function nativeProviderBoundary( + adapter: OpenShellProviderAdapter, + inferenceProvider = "nemoclaw-nvidia-prod-v1", + missingReceipt = false, + deferred = false, +) { return createProviderEffectBoundary({ - deferred: false, + deferred, sandboxName: "alpha", gatewayName: "nemoclaw", - expectedNativeNvidiaProviderAttachment: { - schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", - providerId: recordedProviderId, - }, + expectedNativeHostedProviderAttachment: missingReceipt + ? undefined + : { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: recordedProviderId, + }, preparationInput: { openshellDriver: "docker", - inferenceProvider: "nemoclaw-nvidia-prod-v1", + inferenceProvider, messagingProviders: [], messagingProviderRequests: [], extraProviders: [], @@ -71,6 +78,28 @@ function verifiedCreateContext(revalidateSandboxIdentity = vi.fn()) { } describe("native NVIDIA post-create provider verification", () => { + it.each([ + [false, "nemoclaw-nvidia-prod-v1"], + [true, "nemoclaw-nvidia-prod-v1"], + [false, "nemoclaw-openai-api-v1"], + [true, "nemoclaw-openai-api-v1"], + [false, "openai-api"], + [true, "openai-api"], + [false, "nvidia-prod"], + [true, "nvidia-prod"], + ] as const)( + "rejects a missing native receipt before creation with deferred=%s for %s", + async (deferred, inferenceProvider) => { + const adapter = providerAdapter(recordedProviderId); + const boundary = nativeProviderBoundary(adapter, inferenceProvider, true, deferred); + await expect(boundary.validateBeforeCreate()).rejects.toThrow( + "native hosted provider identity receipt", + ); + expect(adapter.getProvider).not.toHaveBeenCalled(); + expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); + }, + ); + it("confirms the recorded provider is attached after sandbox identity is verified", async () => { const adapter = providerAdapter(recordedProviderId); const revalidateSandboxIdentity = vi.fn(); @@ -81,7 +110,7 @@ describe("native NVIDIA post-create provider verification", () => { ).resolves.toBeUndefined(); expect(revalidateSandboxIdentity).toHaveBeenCalledWith( - "attaching and verifying native NVIDIA provider for sandbox 'alpha'", + "attaching and verifying native hosted provider for sandbox 'alpha'", ); expect(adapter.listProviderAttachments).toHaveBeenCalledWith( expect.objectContaining({ sandboxName: "alpha" }), @@ -114,13 +143,90 @@ describe("native NVIDIA post-create provider verification", () => { expect(adapter.listProviderAttachments).toHaveBeenCalledTimes(2); }); - it("rejects a replaced provider before inspecting its sandbox attachments", async () => { + it("rejects an ownership receipt for a different selected native provider before gateway access", async () => { + const adapter = providerAdapter(recordedProviderId); + const boundary = nativeProviderBoundary(adapter, "nemoclaw-openai-api-v1"); + + await expect(boundary.runAfterVerifiedCreate?.(verifiedCreateContext())).rejects.toThrow( + /does not match the selected profile/u, + ); + expect(adapter.getProvider).not.toHaveBeenCalled(); + expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); + }); + + it("publishes and verifies the physical provider for a logical OpenAI selection", async () => { + const adapter = providerAdapter(recordedProviderId); + vi.mocked(adapter.getProvider).mockResolvedValue({ + ok: true, + value: { + name: "nemoclaw-openai-api-v1", + type: "nemoclaw-openai-inference-v1", + credentialKeys: ["OPENAI_API_KEY"], + configKeys: [], + revision: { id: recordedProviderId, resourceVersion: 1 }, + }, + }); + adapter.updateProvider = vi.fn(async () => ({ ok: true as const })); + vi.mocked(adapter.listProviderAttachments).mockResolvedValue({ + ok: true, + value: { names: ["nemoclaw-openai-api-v1"] }, + }); + const revalidateSandboxIdentity = vi.fn(); + const preparationInput = { + openshellDriver: "docker" as const, + inferenceProvider: "openai-api", + messagingProviders: [], + messagingProviderRequests: [], + extraProviders: [], + gatewayName: "nemoclaw", + }; + const boundary = createProviderEffectBoundary({ + deferred: false, + sandboxName: "alpha", + gatewayName: "nemoclaw", + expectedNativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: recordedProviderId, + }, + preparationInput, + preparationDeps: { + runOpenshell: vi.fn() as never, + providerAdapter: adapter, + cleanupCreateSources: vi.fn(), + }, + runVerifiedSandboxCreateEffects: null, + activateDeferredProviderEffects: null, + revalidateSandboxIdentityBeforeCreate: revalidateSandboxIdentity, + }); + + await boundary.publishBeforeCreate(); + expect(revalidateSandboxIdentity).toHaveBeenCalledOnce(); + expect(adapter.updateProvider).toHaveBeenCalledExactlyOnceWith({ + target: { kind: "named", gatewayName: "nemoclaw" }, + providerName: "nemoclaw-openai-api-v1", + credentials: [], + config: [], + }); + expect(boundary.runAfterVerifiedCreate).toBeTypeOf("function"); + await boundary.runAfterVerifiedCreate!(verifiedCreateContext(revalidateSandboxIdentity)); + expect(adapter.listProviderAttachments).toHaveBeenCalledWith( + expect.objectContaining({ sandboxName: "alpha" }), + ); + expect(preparationInput.inferenceProvider).toBe("openai-api"); + }); + + it("rejects a replaced provider before changing its sandbox attachments", async () => { const adapter = providerAdapter("99999999-2222-4333-8444-555555555555"); + adapter.attachProvider = vi.fn(); + adapter.detachProvider = vi.fn(); const boundary = nativeProviderBoundary(adapter); await expect(boundary.runAfterVerifiedCreate?.(verifiedCreateContext())).rejects.toThrow( /changed identity.*Recreate the sandbox/u, ); - expect(adapter.listProviderAttachments).not.toHaveBeenCalled(); + expect(adapter.attachProvider).not.toHaveBeenCalled(); + expect(adapter.detachProvider).not.toHaveBeenCalled(); }); }); diff --git a/src/lib/onboard/sandbox-create/orchestration.ts b/src/lib/onboard/sandbox-create/orchestration.ts index 8c917761415..a8f8a4c8ed1 100644 --- a/src/lib/onboard/sandbox-create/orchestration.ts +++ b/src/lib/onboard/sandbox-create/orchestration.ts @@ -86,9 +86,10 @@ import { } from "./identity-boundary"; import { publishAttachedProvidersBeforeDockerSandboxCreation, - usesNativeNvidiaProvider, + resolveProviderPreparationInput, + usesNativeHostedProvider, validateAttachedMessagingProvidersBeforeSandboxCreation, - verifyNativeNvidiaAttachmentAfterCreate, + verifyNativeHostedAttachmentAfterCreate, } from "./provider-publication"; import { materializeRebuildPolicyHandoff, @@ -400,16 +401,9 @@ export function selectRebuildCreatePolicy( livePolicyPath: policySourcePath, ...(policySource === undefined ? {} : { livePolicySource: policySource }), replacementPolicy: generatedPolicy, - requiredNetworkPolicyKeys: [ - ...requiredNetworkPolicyKeys, - ...(usesNativeNvidiaProvider(inferenceProvider) ? ["native_nvidia_inference"] : []), - ], - removedNetworkPolicyKeys: [ - ...removedNetworkPolicyKeys, - ...(inferenceProvider !== null && !usesNativeNvidiaProvider(inferenceProvider) - ? ["native_nvidia_inference"] - : []), - ], + requiredNetworkPolicyKeys, + removedNetworkPolicyKeys, + inferenceProvider, requiredNetworkPolicySources, authorizedCredentialBindingProviders, }); @@ -1424,7 +1418,7 @@ export function createProviderEffectBoundary(input: { readonly deferred: boolean; readonly sandboxName: string; readonly gatewayName: string; - readonly expectedNativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + readonly expectedNativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; readonly preparationInput: ProviderPreparationInput; readonly preparationDeps: ProviderPreparationDeps; readonly runVerifiedSandboxCreateEffects: import("../types").VerifiedSandboxCreateEffects | null; @@ -1433,45 +1427,55 @@ export function createProviderEffectBoundary(input: { | null; readonly revalidateSandboxIdentityBeforeCreate: () => void; }): ProviderEffectBoundary { + const preparationInput = resolveProviderPreparationInput(input.preparationInput); const validate = async () => validateAttachedMessagingProvidersBeforeSandboxCreation( - input.preparationInput, + preparationInput, input.preparationDeps, ); const publish = async () => - publishAttachedProvidersBeforeDockerSandboxCreation( - input.preparationInput, - input.preparationDeps, - ); - const attachAndVerifyNativeNvidiaProvider = async ( - context: VerifiedSandboxCreateEffectsContext, - ) => { - if (!usesNativeNvidiaProvider(input.preparationInput.inferenceProvider)) return; + publishAttachedProvidersBeforeDockerSandboxCreation(preparationInput, input.preparationDeps); + const verifyNativeHostedAttachment = async (context: VerifiedSandboxCreateEffectsContext) => { + if (!usesNativeHostedProvider(preparationInput.inferenceProvider)) return; + context.revalidateSandboxIdentity( - `attaching and verifying native NVIDIA provider for sandbox '${input.sandboxName}'`, + `attaching and verifying native hosted provider for sandbox '${input.sandboxName}'`, ); - await verifyNativeNvidiaAttachmentAfterCreate({ + await verifyNativeHostedAttachmentAfterCreate({ sandboxName: input.sandboxName, gatewayName: input.gatewayName, - inferenceProvider: input.preparationInput.inferenceProvider, - expected: input.expectedNativeNvidiaProviderAttachment, + inferenceProvider: preparationInput.inferenceProvider, + expected: input.expectedNativeHostedProviderAttachment, deps: input.preparationDeps, }); }; + const validateNativeHostedReceipt = async () => { + if ( + usesNativeHostedProvider(preparationInput.inferenceProvider) && + !input.expectedNativeHostedProviderAttachment + ) { + throw new Error( + `Sandbox '${input.sandboxName}' is missing its native hosted provider identity receipt.`, + ); + } + }; if (!input.deferred) { return { - validateBeforeCreate: validate, + validateBeforeCreate: async () => { + await validateNativeHostedReceipt(); + await validate(); + }, publishBeforeCreate: async () => { input.revalidateSandboxIdentityBeforeCreate(); await publish(); }, - runAfterVerifiedCreate: usesNativeNvidiaProvider(input.preparationInput.inferenceProvider) - ? attachAndVerifyNativeNvidiaProvider + runAfterVerifiedCreate: usesNativeHostedProvider(preparationInput.inferenceProvider) + ? verifyNativeHostedAttachment : undefined, }; } return { - validateBeforeCreate: async () => undefined, + validateBeforeCreate: validateNativeHostedReceipt, publishBeforeCreate: async () => undefined, runAfterVerifiedCreate: async (context) => { context.revalidateSandboxIdentity( @@ -1488,7 +1492,8 @@ export function createProviderEffectBoundary(input: { `publishing deferred providers for sandbox '${input.sandboxName}'`, ); await publish(); - await attachAndVerifyNativeNvidiaProvider(context); + await verifyNativeHostedAttachment(context); + context.revalidateSandboxIdentity( `attaching deferred providers to sandbox '${input.sandboxName}'`, ); @@ -3543,7 +3548,7 @@ export function createSandboxWithBaseImageResolution(runtime: SandboxCreateOrche deferred: createIntent?.deferSandboxEffectsUntilIdentityVerification === true, sandboxName, gatewayName: GATEWAY_NAME, - expectedNativeNvidiaProviderAttachment: resolvedCreateIntent.nativeNvidiaProviderAttachment, + expectedNativeHostedProviderAttachment: resolvedCreateIntent.nativeHostedProviderAttachment, preparationInput: providerPreparationInput, preparationDeps: providerPreparationDeps, runVerifiedSandboxCreateEffects, diff --git a/src/lib/onboard/sandbox-create/provider-publication.ts b/src/lib/onboard/sandbox-create/provider-publication.ts index ba011e54ea6..1a75b1042fb 100644 --- a/src/lib/onboard/sandbox-create/provider-publication.ts +++ b/src/lib/onboard/sandbox-create/provider-publication.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES } from "../../inference/native-hosted/profiles"; import type { SandboxCreateOrchestrationRuntime } from "../../onboard"; import type { OpenShellProviderAdapter, @@ -10,10 +11,8 @@ import { createCliOpenShellProviderAdapter } from "../../adapters/openshell/prov import type { OpenShellGatewayEndpointEnvironment } from "../../adapters/openshell/gateway-scope"; import { namedOpenShellGateway } from "../../adapters/openshell/sandbox-observer"; import { REPOSITORY_ROOT } from "../../core/repository-root"; -import { - ensureNativeNvidiaProviderAttached, - NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../../inference/native-nvidia"; +import { ensureNativeHostedProviderAttached } from "../../inference/native-hosted"; + import { messagingCredentialProviderProfilePath, MESSAGING_CREDENTIAL_PROVIDER_TYPE, @@ -64,24 +63,38 @@ function resolveProviderAdapter(deps: ProviderPreparationDeps): OpenShellProvide ); } -export function usesNativeNvidiaProvider(inferenceProvider: string | null): boolean { - return inferenceProvider === NVIDIA_HOSTED_NATIVE_PROVIDER; +/** Keep logical selection metadata outside the OpenShell publication boundary. */ +export function resolveProviderPreparationInput( + input: ProviderPreparationInput, +): ProviderPreparationInput { + const profile = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.logicalProvider === input.inferenceProvider, + ); + return { ...input, inferenceProvider: profile?.providerName ?? input.inferenceProvider }; } -export async function verifyNativeNvidiaAttachmentAfterCreate(input: { +export function usesNativeHostedProvider(inferenceProvider: string | null): boolean { + return NATIVE_HOSTED_PROFILES.some((profile) => profile.providerName === inferenceProvider); +} + +export async function verifyNativeHostedAttachmentAfterCreate(input: { readonly sandboxName: string; readonly gatewayName: string; readonly inferenceProvider: string | null; - readonly expected: SandboxEntry["nativeNvidiaProviderAttachment"]; + readonly expected: SandboxEntry["nativeHostedProviderAttachment"]; readonly deps: ProviderPreparationDeps; }): Promise { - if (!usesNativeNvidiaProvider(input.inferenceProvider)) return; + const profile = NATIVE_HOSTED_PROFILES.find( + (candidate) => candidate.providerName === input.inferenceProvider, + ); + if (!profile) return; if (!input.expected) { throw new Error( - `Sandbox '${input.sandboxName}' is missing its native NVIDIA provider identity receipt.`, + `Sandbox '${input.sandboxName}' is missing its native hosted provider identity receipt.`, ); } - await ensureNativeNvidiaProviderAttached({ + await ensureNativeHostedProviderAttached({ + profile, adapter: resolveProviderAdapter(input.deps), target: namedOpenShellGateway(input.gatewayName), sandboxName: input.sandboxName, diff --git a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts index faac085c290..abc7dda19fc 100644 --- a/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts +++ b/src/lib/onboard/sandbox-create/rebuild-policy-handoff.ts @@ -9,6 +9,7 @@ import { parseOpenShellPolicy, stripProviderComposedPolicies, } from "../../adapters/openshell/policy-boundary"; +import { NVIDIA_HOSTED_NATIVE_PROVIDER } from "../../inference/native-nvidia/contract"; import { isReviewedMessagingChannelPolicyUpgrade } from "../../messaging/channels/policy"; import { reconcileTeamsOutlookLoginCredentialBinding } from "../../policy/microsoft-login-credential-binding"; import { parseAndValidateSandboxPolicy } from "../../policy/sandbox-policy-validation"; @@ -314,6 +315,7 @@ export function mergeReplacementPolicyAccess( /** Materialize the single ephemeral policy input consumed by an explicit rebuild. */ export function materializeRebuildPolicyHandoff(input: { + readonly inferenceProvider?: string | null; readonly sandboxName?: string; readonly livePolicyPath: string; readonly livePolicySource?: string; @@ -330,8 +332,19 @@ export function materializeRebuildPolicyHandoff(input: { const merged = mergeReplacementPolicyAccess( liveSource, replacementSource, - input.requiredNetworkPolicyKeys, - input.removedNetworkPolicyKeys, + [ + ...(input.requiredNetworkPolicyKeys ?? []), + ...(input.inferenceProvider === NVIDIA_HOSTED_NATIVE_PROVIDER + ? ["native_nvidia_inference"] + : []), + ], + [ + ...(input.removedNetworkPolicyKeys ?? []), + ...(input.inferenceProvider != null && + input.inferenceProvider !== NVIDIA_HOSTED_NATIVE_PROVIDER + ? ["native_nvidia_inference"] + : []), + ], input.requiredNetworkPolicySources, input.sandboxName, ); diff --git a/src/lib/onboard/sandbox-registration.test.ts b/src/lib/onboard/sandbox-registration.test.ts index 44b092116d7..b3bb3c368e4 100644 --- a/src/lib/onboard/sandbox-registration.test.ts +++ b/src/lib/onboard/sandbox-registration.test.ts @@ -112,15 +112,15 @@ describe("buildCreatedSandboxRegistryEntry", () => { compatibleEndpointReasoningEffort: null, nimContainer: null, }, - nativeNvidiaProviderAttachment: attachment, + nativeHostedProviderAttachment: attachment, }), ); - expect(entry.nativeNvidiaProviderAttachment).toEqual(attachment); + expect(entry.nativeHostedProviderAttachment).toEqual(attachment); expect(() => buildCreatedSandboxRegistryEntry( createdRegistryEntryInput({ - nativeNvidiaProviderAttachment: { ...attachment, providerId: "" }, + nativeHostedProviderAttachment: { ...attachment, providerId: "" }, }), ), ).toThrow(/native NVIDIA provider attachment failed closed validation/u); diff --git a/src/lib/onboard/sandbox-registration.ts b/src/lib/onboard/sandbox-registration.ts index e67d28f3335..416f9d8496e 100644 --- a/src/lib/onboard/sandbox-registration.ts +++ b/src/lib/onboard/sandbox-registration.ts @@ -13,7 +13,7 @@ import { inferenceSelectionRegistryFields, normalizeInferenceSelection, } from "../inference/selection"; -import { normalizeNativeNvidiaProviderAttachment } from "../inference/native-nvidia/contract"; +import { normalizeNativeHostedProviderAttachment } from "../inference/native-hosted"; import { type WebSearchConfig, webSearchProviderForConfig } from "../inference/web-search"; import * as onboardSession from "../state/onboard-session"; import type { SandboxEntry, SandboxMessagingState } from "../state/registry"; @@ -75,7 +75,7 @@ export interface CreatedSandboxRegistryEntryInput { workload?: SandboxEntry["workload"]; hostLocalInferenceReceipt?: SandboxEntry["hostLocalInferenceReceipt"]; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; - nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; deferredN1xManagedVllmPreviewIntent?: true; toolDisclosure?: ToolDisclosure; observabilityEnabled?: boolean; @@ -214,10 +214,10 @@ export function buildCreatedSandboxRegistryEntry( const hostLocalInferenceProvenance = cloneSandboxHostLocalInferenceProvenance( input.hostLocalInferenceProvenance, ); - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - input.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + input.nativeHostedProviderAttachment, ); - if (input.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + if (input.nativeHostedProviderAttachment !== undefined && !nativeHostedProviderAttachment) { throw new RuntimeProviderSelectionError( "Sandbox native NVIDIA provider attachment failed closed validation.", ); @@ -271,7 +271,7 @@ export function buildCreatedSandboxRegistryEntry( workload, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(deferredN1xManagedVllmAccepted ? { deferredN1xManagedVllmAccepted: true as const } : {}), toolDisclosure: input.toolDisclosure ?? DEFAULT_TOOL_DISCLOSURE, observabilityEnabled: input.observabilityEnabled === true, @@ -347,10 +347,10 @@ export function prepareCreatedSandboxRegistration( input.hostLocalInferenceProvenance !== undefined ? input.hostLocalInferenceProvenance : pending?.hostLocalInferenceProvenance; - const pendingNativeNvidiaProviderAttachment = - input.nativeNvidiaProviderAttachment !== undefined - ? input.nativeNvidiaProviderAttachment - : pending?.nativeNvidiaProviderAttachment; + const pendingNativeHostedProviderAttachment = + input.nativeHostedProviderAttachment !== undefined + ? input.nativeHostedProviderAttachment + : pending?.nativeHostedProviderAttachment; const entry = buildCreatedSandboxRegistryEntry({ ...input, inferenceSelection: pendingRoute @@ -362,9 +362,9 @@ export function prepareCreatedSandboxRegistration( ...(pendingHostLocalInferenceProvenance === undefined ? {} : { hostLocalInferenceProvenance: pendingHostLocalInferenceProvenance }), - ...(pendingNativeNvidiaProviderAttachment === undefined + ...(pendingNativeHostedProviderAttachment === undefined ? {} - : { nativeNvidiaProviderAttachment: pendingNativeNvidiaProviderAttachment }), + : { nativeHostedProviderAttachment: pendingNativeHostedProviderAttachment }), }); if (input.portableLifecycle === true) { if (getRequestedSandboxAgentName(input.agent) !== "openclaw") { diff --git a/src/lib/onboard/setup-inference.test.ts b/src/lib/onboard/setup-inference.test.ts index 9a7be3bc9fa..ed35ea8f758 100644 --- a/src/lib/onboard/setup-inference.test.ts +++ b/src/lib/onboard/setup-inference.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; +import { NATIVE_HOSTED_PROFILES } from "../inference/native-hosted/profiles"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; import { setupOllamaLocalInference } from "./inference-providers/ollama-local"; import { @@ -189,7 +190,9 @@ describe("createProviderReviewDeps", () => { }); describe("native NVIDIA onboarding", () => { - it("reserves the logical route with an attached-provider receipt and no shared route mutation", async () => { + it.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "hermes-provider"), + )("records $label native inference without shared route mutation", async (profile) => { const importProviderProfile = vi.fn(async () => ({ ok: true as const })); const getProvider = vi .fn() @@ -200,9 +203,9 @@ describe("native NVIDIA onboarding", () => { .mockResolvedValueOnce({ ok: true, value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], configKeys: [], revision: { id: "provider-id", resourceVersion: 4 }, }, @@ -218,7 +221,7 @@ describe("native NVIDIA onboarding", () => { } as unknown as OpenShellProviderAdapter; const runOpenshell = vi.fn((_args: string[]) => ({ status: 0, stdout: "", stderr: "" })); const updateSandbox = vi.fn(() => true); - const setNativeNvidiaProviderAuthority = vi.fn(() => true); + const setNativeHostedProviderAuthority = vi.fn(); const verifyInferenceRoute = vi.fn(); const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); const setupInference = createSetupInference({ @@ -231,7 +234,7 @@ describe("native NVIDIA onboarding", () => { getGatewayName: () => "onboarding-gateway", runOpenshell, updateSandbox, - setNativeNvidiaProviderAuthority, + setNativeHostedProviderAuthority, getSandbox: () => null, upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute, @@ -239,7 +242,7 @@ describe("native NVIDIA onboarding", () => { isNonInteractive: () => true, hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, providerAdapter, - hydrateCredentialEnv: vi.fn(() => "host-only-nvidia-credential"), + hydrateCredentialEnv: vi.fn(() => "host-only-inference-credential"), redact: (value: string) => value, compactText: (value: string) => value, log: vi.fn(), @@ -253,9 +256,9 @@ describe("native NVIDIA onboarding", () => { setupInference( "alpha", "nvidia/nemotron-3-super-120b-a12b", - "nvidia-prod", - "https://integrate.api.nvidia.com/v1", - "NVIDIA_INFERENCE_API_KEY", + profile.logicalProvider, + profile.endpoint, + profile.credentialEnv, null, [], { revalidateSandboxIdentity: () => undefined }, @@ -269,13 +272,14 @@ describe("native NVIDIA onboarding", () => { ); expect(getProvider).toHaveBeenCalledWith({ target: { kind: "named", gatewayName: "onboarding-gateway" }, - providerName: "nemoclaw-nvidia-prod-v1", + providerName: profile.providerName, }); expect(createProvider).toHaveBeenCalledWith( expect.objectContaining({ target: { kind: "named", gatewayName: "onboarding-gateway" }, - name: "nemoclaw-nvidia-prod-v1", - credentials: [{ name: "NVIDIA_INFERENCE_API_KEY", value: "host-only-nvidia-credential" }], + name: profile.providerName, + credentials: [{ name: profile.credentialEnv, value: "host-only-inference-credential" }], + config: [], }), ); @@ -287,20 +291,20 @@ describe("native NVIDIA onboarding", () => { expect(updateSandbox).toHaveBeenCalledWith( "alpha", expect.objectContaining({ - provider: "nvidia-prod", + provider: profile.logicalProvider, model: "nvidia/nemotron-3-super-120b-a12b", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", + profileId: profile.profileId, + providerName: profile.providerName, providerId: "provider-id", }, }), ); - expect(setNativeNvidiaProviderAuthority).toHaveBeenCalledWith("onboarding-gateway", { + expect(setNativeHostedProviderAuthority).toHaveBeenCalledExactlyOnceWith("onboarding-gateway", { schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", + profileId: profile.profileId, + providerName: profile.providerName, providerId: "provider-id", }); }); @@ -351,8 +355,8 @@ describe("native NVIDIA onboarding", () => { runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), updateSandbox, getSandbox: () => null, - getNativeNvidiaProviderAuthority: () => undefined, - setNativeNvidiaProviderAuthority: () => { + getNativeHostedProviderAuthority: () => undefined, + setNativeHostedProviderAuthority: () => { throw new Error("state directory is read-only"); }, upsertProvider: vi.fn(async () => ({ ok: true })), @@ -392,14 +396,16 @@ describe("native NVIDIA onboarding", () => { expect(verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); }); - it("reuses a gateway-owned provider for a fresh second sandbox", async () => { + it.each( + NATIVE_HOSTED_PROFILES.filter((profile) => profile.logicalProvider !== "hermes-provider"), + )("reuses $label gateway credentials without an unauthenticated host smoke", async (profile) => { const importProviderProfile = vi.fn(async () => ({ ok: true as const })); const getProvider = vi.fn(async () => ({ ok: true, value: { - name: "nemoclaw-nvidia-prod-v1", - type: "nemoclaw-nvidia-inference-v1", - credentialKeys: ["NVIDIA_INFERENCE_API_KEY"], + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], configKeys: [], revision: { id: "provider-id", resourceVersion: 4 }, }, @@ -407,6 +413,9 @@ describe("native NVIDIA onboarding", () => { const createProvider = vi.fn(); const updateProvider = vi.fn(); const updateSandbox = vi.fn(() => true); + const verifyOnboardInferenceSmoke = vi.fn(async () => { + throw new Error("HTTP 401: Header of type authorization was missing"); + }); const setupInference = createSetupInference({ checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => @@ -418,15 +427,15 @@ describe("native NVIDIA onboarding", () => { runOpenshell: vi.fn(() => ({ status: 0, stdout: "", stderr: "" })), updateSandbox, getSandbox: () => null, - getNativeNvidiaProviderAuthority: () => ({ + getNativeHostedProviderAuthority: () => ({ schemaVersion: 1, - profileId: "nemoclaw-nvidia-inference-v1", - providerName: "nemoclaw-nvidia-prod-v1", + profileId: profile.profileId, + providerName: profile.providerName, providerId: "provider-id", }), upsertProvider: vi.fn(async () => ({ ok: true })), verifyInferenceRoute: vi.fn(), - verifyOnboardInferenceSmoke: vi.fn(async () => undefined), + verifyOnboardInferenceSmoke, isNonInteractive: () => true, hermesProviderAuth: { HERMES_PROVIDER_NAME: "hermes-provider" }, providerAdapter: { @@ -450,24 +459,24 @@ describe("native NVIDIA onboarding", () => { setupInference( "second", "nvidia/nemotron-3-super-120b-a12b", - "nvidia-prod", - "https://integrate.api.nvidia.com/v1", - "NVIDIA_INFERENCE_API_KEY", + profile.logicalProvider, + profile.endpoint, + profile.credentialEnv, null, [], { revalidateSandboxIdentity: () => undefined, - reuseGatewayCredentialWithoutLocalKey: true, }, ), ).resolves.toEqual({ ok: true }); + expect(verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); expect(createProvider).not.toHaveBeenCalled(); expect(updateProvider).not.toHaveBeenCalled(); expect(updateSandbox).toHaveBeenCalledWith( "second", expect.objectContaining({ - nativeNvidiaProviderAttachment: expect.objectContaining({ providerId: "provider-id" }), + nativeHostedProviderAttachment: expect.objectContaining({ providerId: "provider-id" }), }), ); }); diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index bc6d98c1bad..8bf8449fdf0 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -21,14 +21,15 @@ import { } from "../inference/gateway-route-mutation-lock"; import { getManagedVllmProviderBinding, shouldFrontOllamaWithProxy } from "../inference/local"; import { - ensureNativeNvidiaProvider, - isNativeNvidiaProvider, - NVIDIA_HOSTED_CREDENTIAL_ENV, - normalizeNativeNvidiaProviderAttachment, - persistNativeNvidiaProviderAuthority, - resolveGatewayNativeNvidiaProviderAuthority, - type NativeNvidiaProviderAttachment, -} from "../inference/native-nvidia"; + nativeHostedProfile, + ensureNativeHostedProvider, + persistNativeHostedProviderAuthority, + isNativeHostedProvider, + normalizeNativeHostedProviderAttachment, + resolveGatewayNativeHostedProviderAuthority, + type NativeHostedProviderAttachment, +} from "../inference/native-hosted"; + import { clearPendingOllamaModelCleanup, isLocalOllamaRouteOwner, @@ -237,8 +238,8 @@ export type SetupInferenceDeps = ProviderBranchDeps & { // by hand, so every read below must stay optional-chained. getSandbox?: typeof import("../state/registry").getSandbox; listSandboxes?: typeof import("../state/registry").listSandboxes; - getNativeNvidiaProviderAuthority?: typeof import("../state/registry").getNativeNvidiaProviderAuthority; - setNativeNvidiaProviderAuthority?: typeof import("../state/registry").setNativeNvidiaProviderAuthority; + getNativeHostedProviderAuthority?: typeof import("../state/registry").getNativeHostedProviderAuthority; + setNativeHostedProviderAuthority?: typeof import("../state/registry").setNativeHostedProviderAuthority; unloadOllamaModels?: (onlyModels: readonly string[]) => OllamaUnloadResult | void; withOllamaModelOwnershipLock?: typeof withOllamaModelOwnershipLock; withOllamaModelOwnershipTransaction?: typeof withOllamaModelOwnershipTransaction; @@ -681,7 +682,7 @@ export function createSetupInference( ); return deps.exitProcess(1); } - if (!isNativeNvidiaProvider(provider)) { + if (!isNativeHostedProvider(provider)) { const observedRoute = await deps.inferenceRouteObserver.observeInferenceRoute({ target: { kind: "named", gatewayName }, }); @@ -691,6 +692,7 @@ export function createSetupInference( ); return deps.exitProcess(1); } + const compatibility = deps.checkGatewayRouteCompatibility({ gatewayName, sandboxName, @@ -776,7 +778,8 @@ export function createSetupInference( | undefined; let hostLocalInferenceGatewayPortAuthority: number | undefined; let hostLocalInferenceRuntimeProviderId: string | undefined; - let nativeNvidiaProviderAttachment: NativeNvidiaProviderAttachment | undefined; + let nativeHostedProviderAttachment: NativeHostedProviderAttachment | undefined; + let nativeGatewayCredentialOnly = false; const reserveRoute = (name: string, selectedProvider: string, selectedModel: string) => { if (routeReserved) return true; revalidateSandboxIdentity?.("reserve the sandbox inference route"); @@ -795,7 +798,7 @@ export function createSetupInference( reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), - ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(hostLocalInferenceProvenance && hostLocalInferenceGatewayPortAuthority !== undefined ? { gatewayPort: hostLocalInferenceGatewayPortAuthority } : {}), @@ -934,8 +937,35 @@ export function createSetupInference( } const setupSelectedProvider = async (): Promise => { + const recordedSandbox = sandboxName ? deps.getSandbox?.(sandboxName) : null; + const recordedAttachment = normalizeNativeHostedProviderAttachment( + recordedSandbox?.nativeHostedProviderAttachment ?? + recordedSandbox?.nativeNvidiaProviderAttachment, + ); + if ( + recordedSandbox && + isNativeHostedProvider(recordedSandbox.provider) && + !recordedAttachment + ) { + throw new Error( + `Sandbox '${sandboxName}' predates native hosted provider attachments. Recreate this beta sandbox before using native hosted inference; NemoClaw does not migrate existing beta sandboxes automatically.`, + ); + } + const selectedNativeProfile = nativeHostedProfile(provider); + let providerAuthority = selectedNativeProfile + ? resolveGatewayNativeHostedProviderAuthority({ + profile: selectedNativeProfile, + gatewayAuthority: deps.getNativeHostedProviderAuthority?.( + gatewayName, + selectedNativeProfile.profileId, + ), + gatewayName, + recordedGatewayName: recordedSandbox?.gatewayName, + recordedAttachment, + }) + : undefined; if (provider === deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { - return inferenceProviders.setupHermesProviderInference( + const prepared = await inferenceProviders.setupHermesProviderInference( { sandboxName, model, @@ -944,6 +974,8 @@ export function createSetupInference( credentialEnv, hermesAuthMethod, hermesToolGateways, + nativeProvider: true, + expectedNativeProviderAttachment: providerAuthority, }, { ...commonDeps, @@ -962,53 +994,52 @@ export function createSetupInference( lookup: deps.lookup, }, ); + if (!("ok" in prepared) || !prepared.ok) return prepared; + providerAuthority = prepared.nativeHostedProviderAttachment ?? providerAuthority; } - if (isNativeNvidiaProvider(provider)) { - const resolvedCredentialEnv = credentialEnv || NVIDIA_HOSTED_CREDENTIAL_ENV; - const credentialValue = deps.hydrateCredentialEnv(resolvedCredentialEnv) || null; + if (isNativeHostedProvider(provider)) { + const profile = nativeHostedProfile(provider)!; + const resolvedCredentialEnv = credentialEnv || profile.credentialEnv; + const credentialValue = + provider === "hermes-provider" + ? null + : deps.hydrateCredentialEnv(resolvedCredentialEnv) || null; const providerAdapter = deps.providerAdapter; if (!providerAdapter) { - throw new Error("Native NVIDIA setup is missing its OpenShell provider adapter."); + throw new Error("Native hosted setup is missing its OpenShell provider adapter."); } - const recordedSandbox = sandboxName ? deps.getSandbox?.(sandboxName) : null; - const recordedAttachment = normalizeNativeNvidiaProviderAttachment( - recordedSandbox?.nativeNvidiaProviderAttachment, - ); - if ( - recordedSandbox && - isNativeNvidiaProvider(recordedSandbox.provider) && - !recordedAttachment - ) { - throw new Error( - `Sandbox '${sandboxName}' predates native NVIDIA provider attachments. Recreate this beta sandbox before using native NVIDIA inference; NemoClaw does not migrate existing beta sandboxes automatically.`, - ); - } - const providerAuthority = resolveGatewayNativeNvidiaProviderAuthority({ - gatewayName, - gatewayAuthority: deps.getNativeNvidiaProviderAuthority?.(gatewayName), - recordedAttachment, - }); - nativeNvidiaProviderAttachment = await ensureNativeNvidiaProvider({ + nativeHostedProviderAttachment = await ensureNativeHostedProvider({ + profile, + adapter: providerAdapter, target: { kind: "named", gatewayName }, credentialValue, reuseExistingCredential: options.reuseGatewayCredentialWithoutLocalKey === true, ...(providerAuthority ? { expected: providerAuthority } : {}), }); - if (deps.getNativeNvidiaProviderAuthority && deps.setNativeNvidiaProviderAuthority) { - await persistNativeNvidiaProviderAuthority({ + // The verified provider owns this credential. A direct host smoke + // would send no authorization; sandbox readiness probes the attachment. + nativeGatewayCredentialOnly = provider !== "hermes-provider" && !credentialValue; + const readAuthority = + deps.getNativeHostedProviderAuthority && + ((name: string) => deps.getNativeHostedProviderAuthority!(name, profile.profileId)); + const writeAuthority = deps.setNativeHostedProviderAuthority; + if (readAuthority && writeAuthority) { + await persistNativeHostedProviderAuthority({ adapter: providerAdapter, target: { kind: "named", gatewayName }, + profile, gatewayName, - receipt: nativeNvidiaProviderAttachment, + receipt: nativeHostedProviderAttachment, ...(providerAuthority ? { existing: providerAuthority } : {}), - readAuthority: deps.getNativeNvidiaProviderAuthority, - writeAuthority: deps.setNativeNvidiaProviderAuthority, + readAuthority, + writeAuthority, }); } else { - deps.setNativeNvidiaProviderAuthority?.(gatewayName, nativeNvidiaProviderAttachment); + writeAuthority?.(gatewayName, nativeHostedProviderAttachment); } + return null; } @@ -1190,12 +1221,12 @@ export function createSetupInference( try { const providerResult = await setupSelectedProvider(); if (providerResult) return providerResult; - if (!nativeNvidiaProviderAttachment) commonDeps.verifyInferenceRoute(provider, model); + if (!nativeHostedProviderAttachment) commonDeps.verifyInferenceRoute(provider, model); if (hostLocalRoute) { deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", ); - } else if (options.skipHostInferenceSmoke === true) { + } else if (nativeGatewayCredentialOnly || options.skipHostInferenceSmoke === true) { deps.log(" Reusing existing gateway credential; skipping host inference smoke."); } else { await deps.verifyOnboardInferenceSmoke({ @@ -1336,8 +1367,8 @@ export function createSetupInference( ); if (shouldLogSuccessfulRoute && "ok" in result) { deps.log( - isNativeNvidiaProvider(provider) - ? ` ✓ Native NVIDIA provider ready: ${provider} / ${model}` + isNativeHostedProvider(provider) + ? ` ✓ Native hosted provider ready: ${provider} / ${model}` : ` ✓ Inference route set: ${provider} / ${model}`, ); } diff --git a/src/lib/registry-recovery-seeded-paths.test.ts b/src/lib/registry-recovery-seeded-paths.test.ts index e7ad3069248..ddb395654c6 100644 --- a/src/lib/registry-recovery-seeded-paths.test.ts +++ b/src/lib/registry-recovery-seeded-paths.test.ts @@ -256,7 +256,7 @@ describe("recoverRegistryEntries seeded recovery paths", () => { }); it("blocks route mutation after seeded recovery persists a live row without route metadata (#6315)", async () => { - mockRegistryState.sandboxes.gamma = gammaEntry([]); + mockRegistryState.sandboxes.gamma = { ...gammaEntry([]), provider: "ollama-local" }; mockRegistryState.defaultSandbox = "gamma"; vi.mocked(captureOpenshell).mockReturnValue({ output: "recovered-live Ready", @@ -277,7 +277,7 @@ describe("recoverRegistryEntries seeded recovery paths", () => { }); await expect( runInferenceSet( - { provider: "openrouter", model: "nvidia/model-b", sandboxName: "gamma" }, + { provider: "ollama-local", model: "nvidia/model-b", sandboxName: "gamma" }, deps, ), ).rejects.toMatchObject({ diff --git a/src/lib/sandbox/build-context.ts b/src/lib/sandbox/build-context.ts index 33bb4727e3d..02016ca7fcc 100644 --- a/src/lib/sandbox/build-context.ts +++ b/src/lib/sandbox/build-context.ts @@ -193,6 +193,10 @@ function stageLegacySandboxBuildContext( path.join(rootDir, "src", "lib", "providerless-inference.ts"), path.join(buildCtx, "src", "lib", "providerless-inference.ts"), ); + fs.cpSync( + path.join(rootDir, "src/lib/inference/native-hosted/openrouter-headers.ts"), + path.join(buildCtx, "src/lib/inference/native-hosted/openrouter-headers.ts"), + ); stageManagedStartupRuntimeSources(rootDir, buildCtx); normalizeReadModesForDockerCopy(path.join(buildCtx, "src")); fs.rmSync(path.join(buildCtx, "nemoclaw", "node_modules"), { @@ -364,6 +368,10 @@ function stageOptimizedSandboxBuildContext( path.join(rootDir, "src", "lib", "providerless-inference.ts"), path.join(buildCtx, "src", "lib", "providerless-inference.ts"), ); + fs.cpSync( + path.join(rootDir, "src/lib/inference/native-hosted/openrouter-headers.ts"), + path.join(buildCtx, "src/lib/inference/native-hosted/openrouter-headers.ts"), + ); stageManagedStartupRuntimeSources(rootDir, buildCtx); normalizeReadModesForDockerCopy(path.join(buildCtx, "src")); fs.copyFileSync( diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index a6f6f43b45f..e86b5d1adac 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -79,6 +79,100 @@ it("clears a stale native NVIDIA attachment when reserving a shared route", asyn } }); +it("keeps gateway ownership without treating detached history as an active attachment", async () => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-hosted-authority-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + const nvidia = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "nvidia-owned-id", + }; + const openai = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "openai-owned-id", + }; + registry.registerSandbox({ + name: "alpha", + gatewayName: "nemoclaw", + gatewayPort: 8080, + provider: "openai-api", + model: "selected-model", + nativeHostedProviderAttachment: openai, + }); + registry.setNativeHostedProviderAuthority("nemoclaw", nvidia); + registry.setNativeHostedProviderAuthority("nemoclaw", openai); + const registryPath = path.join(home, ".nemoclaw", "sandboxes.json"); + const legacy = JSON.parse(await fs.readFile(registryPath, "utf8")); + legacy.sandboxes.alpha.nativeHostedProviderAuthorities = [nvidia, openai]; + await fs.writeFile(registryPath, JSON.stringify(legacy)); + vi.resetModules(); + const reloaded = await import("./registry"); + const authority = await import("./registry/native-nvidia-provider-authority"); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(openai.profileId, "nemoclaw"), + ).toEqual(["alpha"]); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "nemoclaw"), + ).toEqual([]); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(openai.profileId, "other-gateway"), + ).toEqual([]); + expect(reloaded.getSandbox("alpha")).toMatchObject({ + nativeHostedProviderAttachment: openai, + }); + reloaded.registerSandbox({ + ...reloaded.getSandbox("alpha")!, + name: "beta", + }); + reloaded.reserveSandboxInferenceRoute("alpha", { + provider: "ollama-local", + model: "local-model", + endpointUrl: "http://127.0.0.1:11434/v1", + credentialEnv: null, + preferredInferenceApi: "openai-completions", + gatewayName: "nemoclaw", + }); + expect(reloaded.getSandbox("alpha")?.nativeHostedProviderAttachment).toBeUndefined(); + expect(reloaded.getSandbox("alpha")).not.toHaveProperty("nativeHostedProviderAuthorities"); + expect(reloaded.getNativeHostedProviderAuthority("nemoclaw", nvidia.profileId)).toEqual(nvidia); + reloaded.updateSandbox("alpha", { pendingNativeHostedProviderDetach: nvidia }); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "nemoclaw"), + ).toEqual(["alpha"]); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "other-gateway"), + ).toEqual([]); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(openai.profileId, "nemoclaw"), + ).toEqual(["beta"]); + reloaded.updateSandbox("alpha", { pendingNativeHostedProviderDetach: undefined }); + expect( + authority.listNativeHostedProviderAttachmentSandboxNames(nvidia.profileId, "nemoclaw"), + ).toEqual([]); + reloaded.reserveSandboxInferenceRoute("beta", { + provider: "ollama-local", + model: "local-model", + endpointUrl: "http://127.0.0.1:11434/v1", + credentialEnv: null, + preferredInferenceApi: "openai-completions", + gatewayName: "nemoclaw-9090", + }); + expect(reloaded.getSandbox("beta")).not.toHaveProperty("nativeHostedProviderAuthorities"); + const saved = JSON.parse(await fs.readFile(registryPath, "utf8")); + expect(saved.sandboxes.alpha).not.toHaveProperty("nativeHostedProviderAuthorities"); + expect(reloaded.getNativeHostedProviderAuthority("nemoclaw", nvidia.profileId)).toEqual(nvidia); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } +}); + it("lists registered sandboxes that retain native NVIDIA provider ownership", async () => { const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-native-attachment-list-")); vi.stubEnv("HOME", home); diff --git a/src/lib/state/registry-normalization.test.ts b/src/lib/state/registry-normalization.test.ts index a334b690c8c..35abd78bcfd 100644 --- a/src/lib/state/registry-normalization.test.ts +++ b/src/lib/state/registry-normalization.test.ts @@ -39,6 +39,208 @@ afterEach(() => { }); describe("sandbox registry normalization", () => { + it("rejects malformed legacy hosted history without rewriting or promoting it", async () => { + const document = { + sandboxes: { + alpha: { + name: "alpha", + gatewayName: "nemoclaw", + provider: "ollama-local", + nativeHostedProviderAuthorities: [{ profileId: "nemoclaw-openai-inference-v1" }], + }, + }, + }; + const { home, registry } = await loadRegistryDocument(document); + expect(() => registry.getSandbox("alpha")).toThrow("Invalid native provider ownership receipt"); + expect( + JSON.parse(fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8")), + ).toEqual(document); + }); + + it("migrates legacy NVIDIA ownership alongside another hosted authority through the generic API", async () => { + const receipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "nvidia-owned", + } as const; + const { home, registry } = await loadRegistryDocument({ + sandboxes: {}, + nativeNvidiaProviderAuthorities: { first: receipt }, + }); + const migrated = registry.load(); + expect(migrated).not.toHaveProperty("nativeNvidiaProviderAuthorities"); + expect(registry.getNativeHostedProviderAuthority("first", receipt.profileId)).toEqual(receipt); + registry.save(migrated); + const disk = JSON.parse( + fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8"), + ); + expect(disk).not.toHaveProperty("nativeNvidiaProviderAuthorities"); + expect(disk.gatewayNativeHostedProviderAuthorities).toEqual({ first: [receipt] }); + const hostedReceipt = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "openai-owned", + }; + registry.setNativeHostedProviderAuthority("first", hostedReceipt); + expect(registry.getNativeHostedProviderAuthority("first", hostedReceipt.profileId)).toEqual( + hostedReceipt, + ); + expect(registry.load().gatewayNativeHostedProviderAuthorities?.first).toEqual([ + receipt, + hostedReceipt, + ]); + expect(() => + registry.setNativeHostedProviderAuthority("first", { ...receipt, providerId: "foreign" }), + ).toThrow("Conflicting native provider ownership receipts"); + expect( + registry.getNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"), + ).toEqual(receipt); + registry.clearNativeHostedProviderAuthority("first", receipt.profileId); + expect( + registry.getNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"), + ).toBeUndefined(); + registry.setNativeHostedProviderAuthority("first", receipt); + expect(registry.getNativeHostedProviderAuthority("first", receipt.profileId)).toEqual(receipt); + registry.clearNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"); + expect(registry.getNativeHostedProviderAuthority("first", hostedReceipt.profileId)).toEqual( + hostedReceipt, + ); + registry.clearNativeHostedProviderAuthority("first", hostedReceipt.profileId); + expect(registry.load().gatewayNativeHostedProviderAuthorities).toBeUndefined(); + }); + + it("refuses conflicting disk authority without rewriting its recovery evidence", async () => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "original", + }; + const document = { + sandboxes: {}, + nativeNvidiaProviderAuthorities: { first: receipt }, + gatewayNativeHostedProviderAuthorities: { + first: [{ ...receipt, providerId: "replacement" }], + }, + }; + const { home, registry } = await loadRegistryDocument(document); + expect(() => + registry.getNativeHostedProviderAuthority("first", "nemoclaw-nvidia-inference-v1"), + ).toThrow("Conflicting native provider ownership receipts"); + expect( + JSON.parse(fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8")), + ).toEqual(document); + }); + + it("retains hosted registration ownership per gateway and profile and refuses replacement", async () => { + const { registry } = await loadRegistryDocument({ sandboxes: {} }); + const openai = { + schemaVersion: 1 as const, + profileId: "nemoclaw-openai-inference-v1", + providerName: "nemoclaw-openai-api-v1", + providerId: "openai-owned", + }; + const anthropic = { + schemaVersion: 1 as const, + profileId: "nemoclaw-anthropic-inference-v1", + providerName: "nemoclaw-anthropic-prod-v1", + providerId: "anthropic-owned", + }; + registry.setNativeHostedProviderAuthority("first", openai); + registry.setNativeHostedProviderAuthority("first", anthropic); + registry.setNativeHostedProviderAuthority("second", { ...openai, providerId: "second-owned" }); + expect(registry.getNativeHostedProviderAuthority("first", openai.profileId)).toEqual(openai); + expect(registry.getNativeHostedProviderAuthority("first", anthropic.profileId)).toEqual( + anthropic, + ); + expect(() => + registry.setNativeHostedProviderAuthority("first", { ...openai, providerId: "foreign" }), + ).toThrow("Conflicting native provider ownership receipts"); + expect(registry.getNativeHostedProviderAuthority("first", openai.profileId)).toEqual(openai); + registry.registerSandbox({ + name: "retired", + gatewayName: "first", + provider: "ollama-local", + }); + registry.registerSandbox({ + name: "other", + gatewayName: "second", + provider: "ollama-local", + }); + registry.clearNativeHostedProviderAuthority("first", openai.profileId); + expect(registry.getSandbox("retired")).not.toHaveProperty("nativeHostedProviderAuthorities"); + expect(registry.getSandbox("other")).not.toHaveProperty("nativeHostedProviderAuthorities"); + expect(registry.getNativeHostedProviderAuthority("first", openai.profileId)).toBeUndefined(); + expect(registry.getNativeHostedProviderAuthority("first", anthropic.profileId)).toEqual( + anthropic, + ); + expect(registry.getNativeHostedProviderAuthority("second", openai.profileId)?.providerId).toBe( + "second-owned", + ); + }); + + it("reads Slice 1 NVIDIA receipts and persists the generalized field without losing identity (#12589)", async () => { + const receipt = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "original-provider-id", + }; + const { home, registry } = await loadRegistryDocument({ + sandboxes: { + alpha: { name: "alpha", provider: "nvidia-prod", nativeNvidiaProviderAttachment: receipt }, + }, + }); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual(receipt); + registry.updateSandbox("alpha", { model: "next-model" }); + const saved = JSON.parse( + fs.readFileSync(path.join(home, ".nemoclaw", "sandboxes.json"), "utf8"), + ); + expect(saved.sandboxes.alpha.nativeHostedProviderAttachment).toEqual(receipt); + expect(saved.sandboxes.alpha).not.toHaveProperty("nativeNvidiaProviderAttachment"); + registry.updateSandbox("alpha", { nativeHostedProviderAttachment: undefined }); + expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeHostedProviderAttachment"); + }); + + it("retains pending native cleanup through reload until confirmed removal (#12589)", async () => { + const pending = { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "old-provider", + }; + const registry = await loadRegistryWith({ + alpha: { + name: "alpha", + provider: "ollama-local", + pendingNativeHostedProviderDetach: pending, + }, + }); + registry.updateSandbox("alpha", { model: "next-model" }); + expect(registry.load().sandboxes.alpha.pendingNativeHostedProviderDetach).toEqual(pending); + registry.updateSandbox("alpha", { pendingNativeHostedProviderDetach: undefined }); + expect(registry.load().sandboxes.alpha).not.toHaveProperty("pendingNativeHostedProviderDetach"); + }); + + it("rejects a pending cleanup receipt with a foreign provider name (#12589)", async () => { + const registry = await loadRegistryWith({ + alpha: { + name: "alpha", + pendingNativeHostedProviderDetach: { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "foreign", + providerId: "old", + }, + }, + }); + expect(() => registry.getSandbox("alpha")).toThrow( + "Invalid pending native inference detach receipt", + ); + }); + it("persists only valid gateway-scoped native NVIDIA provider authorities", async () => { const receipt = { schemaVersion: 1 as const, @@ -73,26 +275,32 @@ describe("sandbox registry normalization", () => { }, }, nativeNvidiaProviderAuthorities: { - broken: { ...receipt, providerId: "" }, "nemoclaw-19080": receipt, }, }); - expect(registry.getNativeNvidiaProviderAuthority("broken")).toBeUndefined(); - expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toEqual(receipt); - registry.setNativeNvidiaProviderAuthority("nemoclaw-19081", { + expect( + registry.getNativeHostedProviderAuthority("broken", "nemoclaw-nvidia-inference-v1"), + ).toBeUndefined(); + expect( + registry.getNativeHostedProviderAuthority("nemoclaw-19080", "nemoclaw-nvidia-inference-v1"), + ).toEqual(receipt); + registry.setNativeHostedProviderAuthority("nemoclaw-19081", { ...receipt, providerId: "22222222-3333-4444-8555-666666666666", }); - expect(registry.load().nativeNvidiaProviderAuthorities).toEqual({ - "nemoclaw-19080": receipt, - "nemoclaw-19081": { ...receipt, providerId: "22222222-3333-4444-8555-666666666666" }, + expect(registry.load().gatewayNativeHostedProviderAuthorities).toEqual({ + "nemoclaw-19080": [receipt], + "nemoclaw-19081": [{ ...receipt, providerId: "22222222-3333-4444-8555-666666666666" }], }); - registry.clearNativeNvidiaProviderAuthority("nemoclaw-19080"); - expect(registry.getNativeNvidiaProviderAuthority("nemoclaw-19080")).toBeUndefined(); - expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeNvidiaProviderAuthority"); + registry.clearNativeHostedProviderAuthority("nemoclaw-19080", "nemoclaw-nvidia-inference-v1"); + expect( + registry.getNativeHostedProviderAuthority("nemoclaw-19080", "nemoclaw-nvidia-inference-v1"), + ).toBeUndefined(); + expect(registry.getSandbox("alpha")).not.toHaveProperty("nativeHostedProviderAuthorities"); expect(registry.getSandbox("beta")).not.toHaveProperty("nativeNvidiaProviderAuthority"); - expect(registry.getSandbox("beta")?.nativeNvidiaProviderAttachment).toEqual(receipt); + expect(registry.getSandbox("beta")?.nativeHostedProviderAttachment).toEqual(receipt); + expect(registry.getSandbox("gamma")).not.toHaveProperty("nativeHostedProviderAuthorities"); expect(registry.getSandbox("gamma")).not.toHaveProperty("nativeNvidiaProviderAuthority"); }); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 07f6b0bbf42..9fa4c5a6872 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -9,9 +9,10 @@ import { normalizeInferenceSelection, } from "../inference/selection"; import { - isNativeNvidiaProvider, normalizeNativeNvidiaProviderAttachment, -} from "../inference/native-nvidia"; + normalizeNativeHostedProviderAttachment, +} from "../inference/native-hosted"; + import { parseServingProfileProvenance } from "../inference/serving/profile-provenance"; import { normalizeToolDisclosure } from "../tool-disclosure"; import { @@ -69,11 +70,6 @@ export { listExtraProviders, removeExtraProvider, } from "./registry/extra-providers"; -export { - clearNativeNvidiaProviderAuthority, - getNativeNvidiaProviderAuthority, - setNativeNvidiaProviderAuthority, -} from "./registry/native-nvidia-provider-authority"; import { isDcodeAutoApprovalMode } from "../onboard/dcode-auto-approval"; import { cloneSandboxHostMounts, hasUnsafeHostMountTerminalText } from "./registry/host-mount"; @@ -485,14 +481,17 @@ export function registerSandbox( ); } } - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - entry.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment, ); - if (entry.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + if (entry.nativeHostedProviderAttachment !== undefined && !nativeHostedProviderAttachment) { throw new Error( "Cannot register a sandbox with an invalid native NVIDIA provider attachment", ); } + const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( + entry.nativeNvidiaProviderAttachment ?? nativeHostedProviderAttachment, + ); const registered: SandboxEntry = { name: entry.name, createdAt: entry.createdAt || new Date().toISOString(), @@ -543,6 +542,7 @@ export function registerSandbox( : undefined, ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), ...(nativeNvidiaProviderAttachment ? { nativeNvidiaProviderAttachment } : {}), lifecycleGeneration: entry.lifecycleGeneration, lifecycleLiveIdentityFingerprint: entry.lifecycleLiveIdentityFingerprint, @@ -594,6 +594,7 @@ type SandboxInferenceRouteReservation = Pick< reservationSessionId?: string; hostLocalInferenceReceipt?: string | null; hostLocalInferenceProvenance?: SandboxEntry["hostLocalInferenceProvenance"]; + nativeHostedProviderAttachment?: SandboxEntry["nativeHostedProviderAttachment"]; nativeNvidiaProviderAttachment?: SandboxEntry["nativeNvidiaProviderAttachment"]; }; @@ -636,12 +637,15 @@ export function reserveSandboxInferenceRoute( ) return false; const normalized = normalizeInferenceSelection(route); - const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( - route.nativeNvidiaProviderAttachment, + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment( + route.nativeHostedProviderAttachment, ); - if (route.nativeNvidiaProviderAttachment !== undefined && !nativeNvidiaProviderAttachment) { + if (route.nativeHostedProviderAttachment !== undefined && !nativeHostedProviderAttachment) { throw new Error("Cannot reserve invalid native NVIDIA provider attachment identity"); } + const nativeNvidiaProviderAttachment = normalizeNativeNvidiaProviderAttachment( + route.nativeNvidiaProviderAttachment ?? nativeHostedProviderAttachment, + ); const provenance = cloneSandboxHostLocalInferenceProvenance(route.hostLocalInferenceProvenance); if ( route.hostLocalInferenceProvenance !== undefined && @@ -700,8 +704,8 @@ export function reserveSandboxInferenceRoute( route.hostLocalInferenceProvenance ?? existing.hostLocalInferenceProvenance, ) && isDeepStrictEqual( - existing.nativeNvidiaProviderAttachment, - nativeNvidiaProviderAttachment ?? existing.nativeNvidiaProviderAttachment, + existing.nativeHostedProviderAttachment, + nativeHostedProviderAttachment ?? existing.nativeHostedProviderAttachment, ) && isDeepStrictEqual( normalizeInferenceSelection(existing), @@ -739,13 +743,20 @@ export function reserveSandboxInferenceRoute( endpointSource: normalized.endpointSource, credentialEnv: normalized.credentialEnv, preferredInferenceApi: normalized.preferredInferenceApi, - nativeNvidiaProviderAttachment: isNativeNvidiaProvider(normalized.provider) - ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) - : undefined, + nativeNvidiaProviderAttachment: + normalized.provider?.trim() === "nvidia-prod" + ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) + : undefined, ...(route.hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt: route.hostLocalInferenceReceipt } : {}), ...(provenance ? { hostLocalInferenceProvenance: provenance } : {}), + nativeHostedProviderAttachment: + nativeHostedProviderAttachment ?? + (existing?.gatewayName === route.gatewayName && existing?.provider === normalized.provider + ? existing.nativeHostedProviderAttachment + : undefined), + gatewayName: route.gatewayName, gatewayPort: route.gatewayPort ?? @@ -1048,3 +1059,9 @@ export function getConfiguredMessagingChannels(name: string): string[] { export function setChannelDisabled(name: string, channel: string, disabled: boolean): boolean { return setRegistryChannelDisabled(name, channel, disabled, { load, save, withLock }); } + +export { + getNativeHostedProviderAuthority, + setNativeHostedProviderAuthority, + clearNativeHostedProviderAuthority, +} from "./registry/native-nvidia-provider-authority"; diff --git a/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts b/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts index 23d620d846f..86d57042ada 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority-state.test.ts @@ -2,39 +2,49 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it } from "vitest"; -import { - applyNativeNvidiaProviderAuthority, - normalizeNativeNvidiaProviderAuthorities, - readNativeNvidiaProviderAuthority, - removeNativeNvidiaProviderAuthority, -} from "./native-nvidia-provider-authority-state"; +import { normalizeGatewayNativeHostedAuthorities } from "./native-nvidia-provider-authority-state"; const receipt = { schemaVersion: 1 as const, - profileId: "nemoclaw-nvidia-inference-v1" as const, - providerName: "nemoclaw-nvidia-prod-v1" as const, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", providerId: "11111111-2222-4333-8444-555555555555", }; -describe("native NVIDIA gateway provider authority", () => { - it("normalizes, reads, and removes gateway-scoped receipts", () => { - const state: { - nativeNvidiaProviderAuthorities?: Record; - } = {}; +describe("gateway native provider authority migration", () => { + it("merges legacy NVIDIA ownership into sorted gateway records without duplicating identities", () => { + expect( + normalizeGatewayNativeHostedAuthorities( + { zeta: [receipt] }, + { zeta: receipt, alpha: receipt }, + ), + ).toEqual({ alpha: [receipt], zeta: [receipt] }); + }); - expect(applyNativeNvidiaProviderAuthority(state, "nemoclaw-19080", receipt)).toBe(true); - expect(readNativeNvidiaProviderAuthority(state, "nemoclaw-19080")).toEqual(receipt); - expect(removeNativeNvidiaProviderAuthority(state, "nemoclaw-19080")).toBe(true); - expect(state.nativeNvidiaProviderAuthorities).toBeUndefined(); + it("migrates a valid gateway name that matches an inherited object property", () => { + expect(normalizeGatewayNativeHostedAuthorities(undefined, { constructor: receipt })).toEqual({ + constructor: [receipt], + }); }); - it("drops malformed receipts and sorts gateway keys", () => { - expect( - normalizeNativeNvidiaProviderAuthorities({ - zeta: receipt, - broken: { ...receipt, providerId: "" }, - alpha: receipt, - }), - ).toEqual({ alpha: receipt, zeta: receipt }); + it("refuses conflicting legacy and hosted identities", () => { + expect(() => + normalizeGatewayNativeHostedAuthorities( + { alpha: [{ ...receipt, providerId: "replacement" }] }, + { alpha: receipt }, + ), + ).toThrow("Conflicting native provider ownership receipts"); + }); + + it.each([ + null, + [], + "invalid", + { alpha: { ...receipt, providerId: "" } }, + { "../gateway": receipt }, + ])("refuses malformed legacy authority instead of dropping ownership: %j", (legacy) => { + expect(() => normalizeGatewayNativeHostedAuthorities(undefined, legacy)).toThrow( + "Invalid legacy native NVIDIA", + ); }); }); diff --git a/src/lib/state/registry/native-nvidia-provider-authority-state.ts b/src/lib/state/registry/native-nvidia-provider-authority-state.ts index 192a739f716..b910bb7fc53 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority-state.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority-state.ts @@ -1,68 +1,43 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia/contract"; import { - normalizeNativeNvidiaProviderAttachment, - type NativeNvidiaProviderAttachment, -} from "../../inference/native-nvidia"; + normalizeNativeHostedProviderAuthorities, + retainNativeHostedProviderAuthority, +} from "../../inference/native-hosted/authority"; +import type { NativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; import { isValidName } from "../../name-validation"; -export interface NativeNvidiaProviderAuthorityState { - nativeNvidiaProviderAuthorities?: Record; -} - -export function normalizeNativeNvidiaProviderAuthorities( +// Slice 1 receipts remain readable, but only the hosted map is runtime authority. +export function normalizeGatewayNativeHostedAuthorities( value: unknown, -): Record | undefined { - if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; - const normalized: Record = Object.create(null); - for (const [gatewayName, candidate] of Object.entries(value)) { - const receipt = normalizeNativeNvidiaProviderAttachment(candidate); - if (!isValidName(gatewayName) || !receipt) continue; - normalized[gatewayName] = receipt; - } - const sorted = Object.fromEntries( - Object.entries(normalized).sort(([left], [right]) => left.localeCompare(right)), + legacy: unknown = undefined, +): Record | undefined { + if (value === undefined && legacy === undefined) return undefined; + if (value !== undefined && (!value || typeof value !== "object" || Array.isArray(value))) + throw new Error("Invalid gateway native provider authorities"); + const entries = Object.entries(value ?? {}).map(([gatewayName, receipts]) => { + if (!isValidName(gatewayName)) throw new Error("Invalid native provider authority gateway"); + return [gatewayName, normalizeNativeHostedProviderAuthorities(receipts) ?? []] as const; + }); + const merged: Record = Object.assign( + Object.create(null), + Object.fromEntries(entries), ); - return Object.keys(sorted).length > 0 ? sorted : undefined; -} - -export function readNativeNvidiaProviderAuthority( - state: NativeNvidiaProviderAuthorityState, - gatewayName: string, -): NativeNvidiaProviderAttachment | undefined { - if (!isValidName(gatewayName)) return undefined; - return normalizeNativeNvidiaProviderAttachment( - state.nativeNvidiaProviderAuthorities?.[gatewayName], + if (legacy !== undefined) { + if (!legacy || typeof legacy !== "object" || Array.isArray(legacy)) + throw new Error("Invalid legacy native NVIDIA provider authorities"); + for (const [gatewayName, candidate] of Object.entries(legacy)) { + const receipt = normalizeNativeNvidiaProviderAttachment(candidate); + if (!isValidName(gatewayName) || !receipt) + throw new Error("Invalid legacy native NVIDIA provider authority"); + merged[gatewayName] = retainNativeHostedProviderAuthority(merged[gatewayName], receipt); + } + } + return Object.fromEntries( + Object.entries(merged).sort(([left], [right]) => left.localeCompare(right)), ); } -export function applyNativeNvidiaProviderAuthority( - state: NativeNvidiaProviderAuthorityState, - gatewayName: string, - receipt: NativeNvidiaProviderAttachment, -): boolean { - const normalized = normalizeNativeNvidiaProviderAttachment(receipt); - if (!isValidName(gatewayName) || !normalized) return false; - const previous = readNativeNvidiaProviderAuthority(state, gatewayName); - if (previous?.providerId === normalized.providerId) return false; - state.nativeNvidiaProviderAuthorities = { - ...(state.nativeNvidiaProviderAuthorities ?? {}), - [gatewayName]: normalized, - }; - return true; -} - -export function removeNativeNvidiaProviderAuthority( - state: NativeNvidiaProviderAuthorityState, - gatewayName: string, -): boolean { - if (!isValidName(gatewayName) || !state.nativeNvidiaProviderAuthorities?.[gatewayName]) { - return false; - } - const next = { ...state.nativeNvidiaProviderAuthorities }; - delete next[gatewayName]; - if (Object.keys(next).length > 0) state.nativeNvidiaProviderAuthorities = next; - else delete state.nativeNvidiaProviderAuthorities; - return true; -} +export { isValidName as isValidNativeProviderGateway }; diff --git a/src/lib/state/registry/native-nvidia-provider-authority.ts b/src/lib/state/registry/native-nvidia-provider-authority.ts index d22c746020d..928e23204b4 100644 --- a/src/lib/state/registry/native-nvidia-provider-authority.ts +++ b/src/lib/state/registry/native-nvidia-provider-authority.ts @@ -1,52 +1,98 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; import { - applyNativeNvidiaProviderAuthority, - readNativeNvidiaProviderAuthority, - removeNativeNvidiaProviderAuthority as applyRemoveNativeNvidiaProviderAuthority, -} from "./native-nvidia-provider-authority-state"; + normalizeNativeHostedProviderAttachment, + type NativeHostedProviderAttachment, +} from "../../inference/native-hosted/contract"; +import { + normalizeNativeHostedProviderAuthorities, + retainNativeHostedProviderAuthority, +} from "../../inference/native-hosted/authority"; +import { isValidNativeProviderGateway as isValidName } from "./native-nvidia-provider-authority-state"; + +import type { SandboxRegistry } from "./types"; import { withLock } from "./lock"; import { load, save } from "./persistence"; -export function getNativeNvidiaProviderAuthority( +export function getNativeHostedProviderAuthority( gatewayName: string, -): NativeNvidiaProviderAttachment | undefined { - return readNativeNvidiaProviderAuthority(load(), gatewayName); + profileId: string, +): NativeHostedProviderAttachment | undefined { + if (!isValidName(gatewayName)) return undefined; + return normalizeNativeHostedProviderAuthorities( + load().gatewayNativeHostedProviderAuthorities?.[gatewayName], + )?.find((receipt) => receipt.profileId === profileId); } -export function setNativeNvidiaProviderAuthority( +export function setNativeHostedProviderAuthority( gatewayName: string, - receipt: NativeNvidiaProviderAttachment, + receipt: NativeHostedProviderAttachment, ): void { + const normalized = normalizeNativeHostedProviderAttachment(receipt); + if (!isValidName(gatewayName) || !normalized) + throw new Error("Invalid native provider gateway authority"); withLock(() => { const data = load(); - const existing = readNativeNvidiaProviderAuthority(data, gatewayName); - if (existing?.providerId === receipt.providerId) return; - if (!applyNativeNvidiaProviderAuthority(data, gatewayName, receipt)) { - throw new Error("Cannot record invalid native NVIDIA gateway provider authority"); - } + const previous = data.gatewayNativeHostedProviderAuthorities?.[gatewayName]; + const retained = retainNativeHostedProviderAuthority(previous, normalized); + if (JSON.stringify(previous) === JSON.stringify(retained)) return; + data.gatewayNativeHostedProviderAuthorities = { + ...data.gatewayNativeHostedProviderAuthorities, + [gatewayName]: retained, + }; save(data); }); } -export function clearNativeNvidiaProviderAuthority(gatewayName: string): void { +export function clearNativeHostedProviderAuthority(gatewayName: string, profileId: string): void { + if (!isValidName(gatewayName)) return; withLock(() => { const data = load(); - if (!applyRemoveNativeNvidiaProviderAuthority(data, gatewayName)) return; - save(data); + if (removeHostedAuthority(data, gatewayName, profileId)) save(data); }); } -export function listNativeNvidiaProviderAttachmentSandboxNames( +function removeHostedAuthority( + data: SandboxRegistry, gatewayName: string, + profileId: string, +): boolean { + let changed = false; + const previous = data.gatewayNativeHostedProviderAuthorities?.[gatewayName]; + if (previous?.some((receipt) => receipt.profileId === profileId)) { + const next = { ...data.gatewayNativeHostedProviderAuthorities }; + const retained = previous.filter((receipt) => receipt.profileId !== profileId); + if (retained.length) next[gatewayName] = retained; + else delete next[gatewayName]; + if (Object.keys(next).length) data.gatewayNativeHostedProviderAuthorities = next; + else delete data.gatewayNativeHostedProviderAuthorities; + changed = true; + } + return changed; +} + +export function listNativeHostedProviderAttachmentSandboxNames( + profileId: string, + gatewayName?: string, ): readonly string[] { return Object.values(load().sandboxes) + .filter((sandbox) => !gatewayName || sandbox.gatewayName === gatewayName) .filter( (sandbox) => - sandbox.gatewayName === gatewayName && sandbox.nativeNvidiaProviderAttachment !== undefined, + sandbox.nativeHostedProviderAttachment?.profileId === profileId || + sandbox.nativeNvidiaProviderAttachment?.profileId === profileId || + sandbox.pendingNativeHostedProviderDetach?.profileId === profileId, ) .map((sandbox) => sandbox.name) .sort(); } + +export function listNativeNvidiaProviderAttachmentSandboxNames( + gatewayName?: string, +): readonly string[] { + return listNativeHostedProviderAttachmentSandboxNames( + "nemoclaw-nvidia-inference-v1", + gatewayName, + ); +} diff --git a/src/lib/state/registry/persistence.ts b/src/lib/state/registry/persistence.ts index 57358f362dc..841f0964e02 100644 --- a/src/lib/state/registry/persistence.ts +++ b/src/lib/state/registry/persistence.ts @@ -1,6 +1,9 @@ +import { normalizeGatewayNativeHostedAuthorities } from "./native-nvidia-provider-authority-state"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted/contract"; // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { normalizeNativeHostedProviderAuthorities } from "../../inference/native-hosted/authority"; import path from "node:path"; import { isObjectRecord } from "../../core/json-types"; import { GATEWAY_PORT } from "../../core/ports"; @@ -8,7 +11,6 @@ import { isDeferredN1xManagedVllmAcceptanceRoute } from "../../domain/sandbox/n1 import { parseServingProfileProvenance } from "../../inference/serving/profile-provenance"; import { readConfigFile, writeConfigFile } from "../config-io"; import { normalizeExtraProviders } from "../extra-providers"; -import { normalizeNativeNvidiaProviderAuthorities } from "./native-nvidia-provider-authority-state"; import { cloneSandboxMessagingState, serializeSandboxMessagingStateForDisk, @@ -125,9 +127,6 @@ export function save(data: SandboxRegistry): void { function normalizeRegistry(value: unknown): SandboxRegistry { const data = isObjectRecord(value) ? value : {}; const extraProviders = normalizeExtraProviders(data.extraProviders); - const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( - data.nativeNvidiaProviderAuthorities, - ); const sandboxes = Object.fromEntries( parseSandboxRegistryEntries(data.sandboxes).map(([name, entry]) => [ name, @@ -143,18 +142,17 @@ function normalizeRegistry(value: unknown): SandboxRegistry { ), sandboxes, }; + const hostedAuthorities = normalizeGatewayNativeHostedAuthorities( + data.gatewayNativeHostedProviderAuthorities, + Reflect.get(data, "nativeNvidiaProviderAuthorities"), + ); + if (hostedAuthorities) base.gatewayNativeHostedProviderAuthorities = hostedAuthorities; if (extraProviders) base.extraProviders = extraProviders; - if (nativeNvidiaProviderAuthorities) { - base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; - } return base; } function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { const extraProviders = normalizeExtraProviders(data.extraProviders); - const nativeNvidiaProviderAuthorities = normalizeNativeNvidiaProviderAuthorities( - data.nativeNvidiaProviderAuthorities, - ); const sandboxes = Object.fromEntries( Object.entries(data.sandboxes).map(([name, entry]) => [ name, @@ -173,14 +171,28 @@ function serializeRegistryForDisk(data: SandboxRegistry): SandboxRegistry { : reversibleRemoval.incrementDefaultSelectionRevision(currentDefaultSelectionRevision), sandboxes, }; + const hostedAuthorities = normalizeGatewayNativeHostedAuthorities( + data.gatewayNativeHostedProviderAuthorities, + Reflect.get(data, "nativeNvidiaProviderAuthorities"), + ); + if (hostedAuthorities) base.gatewayNativeHostedProviderAuthorities = hostedAuthorities; if (extraProviders) base.extraProviders = extraProviders; - if (nativeNvidiaProviderAuthorities) { - base.nativeNvidiaProviderAuthorities = nativeNvidiaProviderAuthorities; - } return base; } function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { + const rawAttachment = + entry.nativeHostedProviderAttachment ?? entry.nativeNvidiaProviderAttachment; + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); + if (rawAttachment !== undefined && !nativeHostedProviderAttachment) + throw new Error("Invalid native inference provider receipt"); + // Validate legacy history before discarding it; gateway receipts own durable authority. + normalizeNativeHostedProviderAuthorities(Reflect.get(entry, "nativeHostedProviderAuthorities")); + const pendingNativeHostedProviderDetach = normalizeNativeHostedProviderAttachment( + entry.pendingNativeHostedProviderDetach, + ); + if (entry.pendingNativeHostedProviderDetach !== undefined && !pendingNativeHostedProviderDetach) + throw new Error("Invalid pending native inference detach receipt"); const messaging = cloneSandboxMessagingState(entry.messaging); const workload = cloneSandboxWorkloadReceiptOrThrow(entry.workload, "load"); const hostLocalInferenceReceipt = cloneHostLocalInferenceReceiptOrThrow( @@ -199,6 +211,10 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { const deferredN1xManagedVllmAccepted = normalizeDeferredN1xManagedVllmAcceptance(entry, "load"); const policyEntry = normalizeSandboxPolicyAttribution(entry); const { + nativeNvidiaProviderAttachment: _legacyNativeNvidiaAttachment, + nativeHostedProviderAttachment: _nativeHostedAttachment, + nativeHostedProviderAuthorities: _nativeHostedProviderAuthorities, + pendingNativeHostedProviderDetach: _pendingNativeHostedProviderDetach, cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, workload: _workload, @@ -210,12 +226,15 @@ function normalizeSandboxEntryForRuntime(entry: SandboxEntry): SandboxEntry { mcp: _legacyMcp, ...rest } = policyEntry as SandboxEntry & { + nativeHostedProviderAuthorities?: unknown; cuaRuntimeReadiness?: unknown; nativeNvidiaProviderAuthority?: unknown; mcp?: unknown; }; return { ...rest, + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), + ...(pendingNativeHostedProviderDetach ? { pendingNativeHostedProviderDetach } : {}), ...(workload ? { workload } : {}), ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), ...(hostLocalInferenceProvenance ? { hostLocalInferenceProvenance } : {}), @@ -245,6 +264,18 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { livePhase?: string | null; providerCredentialHashes?: unknown; }; + const rawAttachment = + durable.nativeHostedProviderAttachment ?? durable.nativeNvidiaProviderAttachment; + const nativeHostedProviderAttachment = normalizeNativeHostedProviderAttachment(rawAttachment); + if (rawAttachment !== undefined && !nativeHostedProviderAttachment) + throw new Error("Invalid native inference provider receipt"); + // Validate legacy history before discarding it; gateway receipts own durable authority. + normalizeNativeHostedProviderAuthorities(Reflect.get(durable, "nativeHostedProviderAuthorities")); + const pendingNativeHostedProviderDetach = normalizeNativeHostedProviderAttachment( + durable.pendingNativeHostedProviderDetach, + ); + if (durable.pendingNativeHostedProviderDetach !== undefined && !pendingNativeHostedProviderDetach) + throw new Error("Invalid pending native inference detach receipt"); const messaging = serializeSandboxMessagingStateForDisk(durable.messaging); const workload = cloneSandboxWorkloadReceiptOrThrow(durable.workload, "save"); const hostLocalInferenceReceipt = cloneHostLocalInferenceReceiptOrThrow( @@ -263,6 +294,10 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { const deferredN1xManagedVllmAccepted = normalizeDeferredN1xManagedVllmAcceptance(durable, "save"); const policyEntry = normalizeSandboxPolicyAttribution(durable); const { + nativeNvidiaProviderAttachment: _legacyNativeNvidiaAttachment, + nativeHostedProviderAttachment: _nativeHostedAttachment, + nativeHostedProviderAuthorities: _nativeHostedProviderAuthorities, + pendingNativeHostedProviderDetach: _pendingNativeHostedProviderDetach, cuaRuntimeReadiness: _legacyCuaRuntimeReadiness, messaging: _messaging, workload: _workload, @@ -274,12 +309,15 @@ function serializeSandboxEntryForDisk(entry: SandboxEntry): SandboxEntry { mcp: _legacyMcp, ...rest } = policyEntry as SandboxEntry & { + nativeHostedProviderAuthorities?: unknown; cuaRuntimeReadiness?: unknown; nativeNvidiaProviderAuthority?: unknown; mcp?: unknown; }; return { ...rest, + ...(nativeHostedProviderAttachment ? { nativeHostedProviderAttachment } : {}), + ...(pendingNativeHostedProviderDetach ? { pendingNativeHostedProviderDetach } : {}), ...(rest.dashboardPort === 0 ? { dashboardPort: null } : {}), ...(workload ? { workload } : {}), ...(hostLocalInferenceReceipt !== undefined ? { hostLocalInferenceReceipt } : {}), diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 4ac16f5351b..3ce9cfa4809 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -4,7 +4,7 @@ import { isDeepStrictEqual } from "node:util"; import { normalizeInferenceSelection, type InferenceSelection } from "../../inference/selection"; -import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import { normalizeNativeHostedProviderAttachment } from "../../inference/native-hosted"; import { isWebSearchProvider } from "../../inference/web-search/provider"; import { normalizePendingSandboxCreateIdentity } from "./pending-create-identity"; import type { PendingSandboxCreateIdentity, SandboxEntry } from "./types"; @@ -22,6 +22,7 @@ const ROUTE_RESERVATION_KEYS = new Set([ "lifecycleLiveIdentityFingerprint", "model", "name", + "nativeHostedProviderAttachment", "nativeNvidiaProviderAttachment", "openshellDriver", "pendingRouteReservation", @@ -83,8 +84,8 @@ function validCarriedRouteMetadata(entry: SandboxEntry): boolean { return false; } if ( - entry.nativeNvidiaProviderAttachment !== undefined && - !normalizeNativeNvidiaProviderAttachment(entry.nativeNvidiaProviderAttachment) + entry.nativeHostedProviderAttachment !== undefined && + !normalizeNativeHostedProviderAttachment(entry.nativeHostedProviderAttachment) ) { return false; } diff --git a/src/lib/state/registry/types.ts b/src/lib/state/registry/types.ts index 6eb7f8131df..8ffe1ca88b9 100644 --- a/src/lib/state/registry/types.ts +++ b/src/lib/state/registry/types.ts @@ -2,7 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import type { InferenceSelection } from "../../inference/selection"; -import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; +import type { NativeNvidiaProviderAttachment } from "../../inference/native-nvidia/contract"; +import type { NativeHostedProviderAttachment } from "../../inference/native-hosted"; import type { ServingProfileProvenance } from "../../inference/serving/types"; import type { WebSearchProvider } from "../../inference/web-search"; import type { DcodeAutoApprovalMode } from "../../onboard/dcode-auto-approval"; @@ -134,6 +135,10 @@ export interface SandboxEntry extends Partial { /** Canonical provider-neutral receipt for an out-of-sandbox inference runtime. */ hostLocalInferenceReceipt?: string | null; /** Exact OpenShell provider identity attached for native NVIDIA hosted inference. */ + nativeHostedProviderAttachment?: NativeHostedProviderAttachment; + /** Previous native access retained until provider-switch cleanup is confirmed. */ + pendingNativeHostedProviderDetach?: NativeHostedProviderAttachment; + /** Legacy Slice 1 receipt; normalized when loaded. */ nativeNvidiaProviderAttachment?: NativeNvidiaProviderAttachment; /** Explicit hidden-lifecycle provenance; absence keeps llama.cpp on its legacy path. */ hostLocalInferenceProvenance?: SandboxHostLocalInferenceProvenance; @@ -235,5 +240,5 @@ export interface SandboxRegistry { defaultSelectionRevision?: number; extraProviders?: string[]; /** Exact NemoClaw-owned native NVIDIA provider identity for each OpenShell gateway. */ - nativeNvidiaProviderAuthorities?: Record; + gatewayNativeHostedProviderAuthorities?: Record; } diff --git a/src/lib/verify-deployment-inference-route.test.ts b/src/lib/verify-deployment-inference-route.test.ts index bbc4f4cde97..1750be08951 100644 --- a/src/lib/verify-deployment-inference-route.test.ts +++ b/src/lib/verify-deployment-inference-route.test.ts @@ -62,7 +62,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { it("fails the deployment when the models route returns HTTP 404 (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, - inferenceRouteContext: { provider: "openrouter-api" }, + inferenceRouteContext: { provider: "custom-shared-provider" }, }); expect(result.verification.inferenceRouteWorking).toBe(false); @@ -72,7 +72,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { it("names the unvalidated model catalog as the reason for a 404 (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, - inferenceRouteContext: { provider: "openrouter-api" }, + inferenceRouteContext: { provider: "custom-shared-provider" }, }); const inference = result.diagnostics.find((entry) => entry.link === "inference"); @@ -95,7 +95,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { it("keeps a credential-gated HTTP 401 models route healthy (#2342)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("401"), { ...NO_RETRY, - inferenceRouteContext: { provider: "openrouter-api" }, + inferenceRouteContext: { provider: "custom-shared-provider" }, }); expect(result.verification.inferenceRouteWorking).toBe(true); @@ -131,7 +131,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.verification.inferenceRouteWorking).toBe(false); }); - it("accepts the OpenRouter adapter 404 without an agent allowlist when inference succeeds (#12621)", async () => { + it("accepts native Deep Agents Code OpenRouter when an inference request succeeds", async () => { const result = await verifyDeployment( "my-sandbox", buildChain(), @@ -146,7 +146,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.healthy).toBe(true); }); - it("fails the OpenRouter adapter 404 when the inference request fails (#12621)", async () => { + it("fails native Deep Agents Code OpenRouter when the inference request fails", async () => { const result = await verifyDeployment( "my-sandbox", buildChain(), @@ -162,7 +162,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.verification.inferenceRouteWorking).toBe(false); }); - it("fails the OpenRouter adapter 404 when no invocation probe is wired (#12621)", async () => { + it("fails native Deep Agents Code OpenRouter when no invocation probe is wired", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, inferenceRouteContext: { provider: "openrouter-api" }, @@ -171,7 +171,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(result.verification.inferenceRouteWorking).toBe(false); }); - it("points a failed by-design 404 at the inference request, not the model catalog (#10543)", async () => { + it("reports the native provider credential and model when invocation fails", async () => { const result = await verifyDeployment( "my-sandbox", buildChain(), @@ -185,14 +185,15 @@ describe("verifyDeployment inference route model-catalog validation", () => { ); const inference = result.diagnostics.find((entry) => entry.link === "inference"); - expect(inference?.hint).toContain("serves no model catalog"); + expect(inference?.detail).toContain("HTTP 401"); + expect(inference?.hint).toContain("provider credential and model"); expect(inference?.hint).not.toContain("endpoint serves"); }); it("tells a plain 404 to make the model catalog available (#10543)", async () => { const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { ...NO_RETRY, - inferenceRouteContext: { provider: "compatible-endpoint" }, + inferenceRouteContext: { provider: "custom-shared-provider" }, }); const inference = result.diagnostics.find((entry) => entry.link === "inference"); @@ -200,6 +201,15 @@ describe("verifyDeployment inference route model-catalog validation", () => { expect(inference?.hint).toContain("/v1/models"); }); + it("rejects a catalog 404 for a custom shared provider (#10543)", async () => { + const result = await verifyDeployment("my-sandbox", buildChain(), makeModelsRouteDeps("404"), { + ...NO_RETRY, + inferenceRouteContext: { provider: "custom-shared-provider" }, + }); + + expect(result.verification.inferenceRouteWorking).toBe(false); + }); + it("gives a plain 404 the startup budget before failing it closed (#10543)", async () => { let modelsRouteCalls = 0; const deps = makeDeps({ @@ -215,7 +225,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { const result = await verifyDeployment("my-sandbox", buildChain(), deps, { retryDelaysMs: [1, 1, 1], sleep: async (_ms: number) => {}, - inferenceRouteContext: { provider: "compatible-endpoint" }, + inferenceRouteContext: { provider: "custom-shared-provider" }, }); expect(modelsRouteCalls).toBe(4); @@ -238,13 +248,13 @@ describe("verifyDeployment inference route model-catalog validation", () => { const result = await verifyDeployment("my-sandbox", buildChain(), deps, { retryDelaysMs: [1, 1, 1], sleep: async (_ms: number) => {}, - inferenceRouteContext: { provider: "compatible-endpoint" }, + inferenceRouteContext: { provider: "custom-shared-provider" }, }); expect(result.verification.inferenceRouteWorking).toBe(true); }); - it("spends no models-route retry budget on an expected OpenRouter 404 (#12621)", async () => { + it("never probes the shared models route for native Deep Agents Code OpenRouter", async () => { let modelsRouteCalls = 0; const deps = makeDeps({ executeSandboxCommand: async (_name: string, script: string) => { @@ -263,10 +273,10 @@ describe("verifyDeployment inference route model-catalog validation", () => { inferenceRouteContext: { provider: "openrouter-api" }, }); - expect(modelsRouteCalls).toBe(1); + expect(modelsRouteCalls).toBe(0); }); - it("runs the invocation probe once for an expected OpenRouter 404 (#12621)", async () => { + it("bounds failed native Deep Agents Code invocation retries by the startup budget", async () => { let invocationCalls = 0; const deps = makeModelsRouteDeps("404", { probeInferenceInvocation: async () => { @@ -281,7 +291,7 @@ describe("verifyDeployment inference route model-catalog validation", () => { inferenceRouteContext: { provider: "openrouter-api" }, }); - expect(invocationCalls).toBe(1); + expect(invocationCalls).toBe(4); }); it("fails closed when no provider and model were recorded for the sandbox (#10543)", async () => { diff --git a/src/lib/verify-deployment-openrouter-adapter.test.ts b/src/lib/verify-deployment-openrouter-adapter.test.ts index 13796abb1f4..3cdf55c853e 100644 --- a/src/lib/verify-deployment-openrouter-adapter.test.ts +++ b/src/lib/verify-deployment-openrouter-adapter.test.ts @@ -49,7 +49,7 @@ async function probeCatalog(baseUrl: string, statuses: number[]) { } describe("OpenRouter adapter deployment verification", () => { - it("accepts the real catalog 404 only while the real chat route serves inference (#12621)", async () => { + it("requires a successful OpenRouter chat request without probing the shared catalog (#12621)", async () => { let upstreamStatus = 200; const upstreamRequests: Array<{ method: string | undefined; url: string | undefined }> = []; const upstream = http.createServer((req, res) => { @@ -109,7 +109,7 @@ describe("OpenRouter adapter deployment verification", () => { expect(unavailable.verification.inferenceRouteWorking).toBe(false); expect(unavailable.healthy).toBe(false); - expect(catalogStatuses).toEqual([404, 404]); + expect(catalogStatuses).toEqual([]); expect(upstreamRequests).toEqual([ { method: "POST", url: "/api/v1/chat/completions" }, { method: "POST", url: "/api/v1/chat/completions" }, diff --git a/src/lib/verify-deployment.ts b/src/lib/verify-deployment.ts index 8f7ae84b1c7..f72fc538c31 100644 --- a/src/lib/verify-deployment.ts +++ b/src/lib/verify-deployment.ts @@ -30,7 +30,7 @@ import { isOpenRouterRuntimeAdapterModelsRoute404 } from "./inference/openrouter import { listMessagingChannelsWithoutCredentials } from "./messaging/channels"; import { retryUntilAsync } from "./core/retry"; -import { isNativeNvidiaProvider } from "./inference/native-nvidia"; +import { isNativeHostedProvider } from "./inference/native-hosted"; import { buildCustomOpenClawRuntimeFailureHints, classifyOpenClawRuntimeFailure, @@ -395,7 +395,7 @@ async function verifyInferenceRoute( sleep: (ms: number) => Promise, context: InferenceRouteContext, ): Promise { - if (isNativeNvidiaProvider(context.provider)) { + if (isNativeHostedProvider(context.provider)) { const invocation = await retryUntilAsync( async () => (await deps.probeInferenceInvocation?.()) ?? null, { @@ -407,18 +407,18 @@ async function verifyInferenceRoute( if (invocation?.ok) { return { status: "ok", - detail: "native NVIDIA inference served an agent request", + detail: "native hosted 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: `native hosted 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.", + "The sandbox-attached hosted provider could not serve the selected model. Confirm the " + + "provider credential and model, then re-run: nemoclaw status.", }; } const routeContext = toRouteHealthContext(context); @@ -923,7 +923,7 @@ export async function probeOnboardInferenceInvocation( provider, model, preferredInferenceApi: context.preferredInferenceApi, - ...(isNativeNvidiaProvider(provider) ? { nativeProvider: true } : {}), + ...(isNativeHostedProvider(provider) ? { nativeProvider: true } : {}), }); return result.ok ? { ok: true } : { ok: false, detail: result.detail }; } diff --git a/test/agents/deepagents/langchain-deepagents-code-config.test.ts b/test/agents/deepagents/langchain-deepagents-code-config.test.ts index 62e24d8cb30..9742a488756 100644 --- a/test/agents/deepagents/langchain-deepagents-code-config.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-config.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles"; import { type SpawnSyncReturns, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; @@ -86,9 +87,10 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).not.toMatch(/NVIDIA_API_KEY|OPENAI_API_KEY=|sk-/); }); - it("uses the attached-provider placeholder for native NVIDIA inference (#12558)", () => { + it("uses the issued credential environment for native NVIDIA inference (#12558)", () => { const config = runGenerator({ NEMOCLAW_INFERENCE_BASE_URL: "https://integrate.api.nvidia.com/v1", + NEMOCLAW_UPSTREAM_PROVIDER: "nvidia-prod", NEMOCLAW_MODEL: "nvidia/nemotron-3-ultra-550b-a55b", }); @@ -97,6 +99,40 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).not.toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); }); + it.each([ + ["openai-api", "https://api.openai.com/v1"], + ["anthropic-prod", "https://api.anthropic.com"], + ["gemini-api", "https://generativelanguage.googleapis.com/v1beta/openai"], + ["openrouter-api", "https://openrouter.ai/api/v1"], + ["hermes-provider", "https://inference-api.nousresearch.com/v1"], + ])("uses the issued credential environment for native %s (#12589)", (provider, endpoint) => { + const config = runGenerator({ + NEMOCLAW_UPSTREAM_PROVIDER: provider, + NEMOCLAW_INFERENCE_BASE_URL: endpoint, + }); + + expect(config).toContain(`base_url = "${endpoint}"`); + expect(config).toContain(`api_key_env = "${nativeHostedProfile(provider)!.credentialEnv}"`); + expect(config).not.toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); + }); + + it("selects the Anthropic Messages client for native Anthropic inference (#12589)", () => { + const config = runGenerator({ + NEMOCLAW_MODEL: "anthropic:claude-sonnet-4-5-20250929", + NEMOCLAW_UPSTREAM_PROVIDER: "anthropic-prod", + NEMOCLAW_INFERENCE_BASE_URL: "https://api.anthropic.com", + NEMOCLAW_INFERENCE_API: "anthropic-messages", + }); + + expect(config).toContain('default = "anthropic:claude-sonnet-4-5-20250929"'); + expect(config).toContain("[models.providers.anthropic]"); + expect(config).toContain('models = ["claude-sonnet-4-5-20250929"]'); + expect(config).toContain('api_key_env = "ANTHROPIC_API_KEY"'); + expect(config).toContain('base_url = "https://api.anthropic.com"'); + expect(config).not.toContain("[models.providers.openai"); + expect(config).not.toContain("use_responses_api"); + }); + it("keeps the legacy provider key when the renamed route variables are absent", () => { const config = runGenerator({ NEMOCLAW_PROVIDER_KEY: "legacy-route", @@ -125,6 +161,9 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).toContain('default = "openrouter:nvidia/nemotron-3-ultra-550b-a55b"'); expect(config).toContain("[models.providers.openrouter]"); + expect(config).toContain("[models.providers.openrouter.params.default_headers]"); + expect(config).toContain('"HTTP-Referer" = "https://www.nvidia.com/nemoclaw/"'); + expect(config).toContain('"X-OpenRouter-Title" = "NVIDIA NemoClaw"'); expect(config).toContain('models = ["nvidia/nemotron-3-ultra-550b-a55b"]'); expect(config).toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); expect(config).toContain('base_url = "https://inference.local/v1"'); @@ -146,6 +185,9 @@ describe("LangChain Deep Agents Code config generator", () => { expect(config).toContain('default = "openrouter:nvidia/nemotron-3-ultra-550b-a55b"'); expect(config).toContain("[models.providers.openrouter]"); + expect(config).toContain("[models.providers.openrouter.params.default_headers]"); + expect(config).toContain('"HTTP-Referer" = "https://www.nvidia.com/nemoclaw/"'); + expect(config).toContain('"X-OpenRouter-Title" = "NVIDIA NemoClaw"'); expect(config).toContain('api_key_env = "DEEPAGENTS_CODE_OPENAI_API_KEY"'); expect(config).toContain('base_url = "https://inference.local/v1"'); expect(config).toContain( diff --git a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts index b78cc302239..756ce785232 100644 --- a/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-direct-module-patch.test.ts @@ -482,48 +482,6 @@ check("disabled", False) ); }); - it.each(["openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", undefined])( - "maps the legacy native credential key only when a current binding exists [%#] (#12822)", - (placeholder) => { - const tempDir = createPatchedPackageFixture(); - const validation = String.raw` -import os -from deepagents_code import _nemoclaw_managed as managed -managed.assert_safe_runtime() -assert os.environ.get("NEMOCLAW_ATTACHED_PROVIDER_API_KEY") == (os.environ.get("NVIDIA_INFERENCE_API_KEY") or None) -managed._assert_safe_environment() -`; - const result = spawnSync("python3", ["-c", validation], { - env: { - PATH: process.env.PATH, - PYTHONPATH: tempDir, - NVIDIA_INFERENCE_API_KEY: placeholder, - NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "nemoclaw-openshell-provider", - }, - encoding: "utf8", - }); - expect(result.status, result.stderr).toBe(0); - }, - ); - - it("rejects a legacy placeholder that does not match the current native binding (#12822)", () => { - const tempDir = createPatchedPackageFixture(); - const result = spawnSync("python3", ["-m", "deepagents_code"], { - env: { - PATH: process.env.PATH, - PYTHONPATH: tempDir, - NVIDIA_INFERENCE_API_KEY: "openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", - NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "openshell:resolve:env:v2_NVIDIA_INFERENCE_API_KEY", - }, - encoding: "utf8", - }); - expect(result.status).not.toBe(0); - expect(result.stderr).toContain( - "runtime environment variable NEMOCLAW_ATTACHED_PROVIDER_API_KEY", - ); - expect(result.stdout).not.toContain("managed-posture-ok"); - }); - it.each([ "openshell:resolve:env:GITHUB_MCP_TOKEN", "openshell:resolve:env:v0_GITHUB_MCP_TOKEN", @@ -1178,9 +1136,30 @@ async def validate(): try: config._get_provider_kwargs("anthropic") except model_config.ModelConfigError as exc: - assert "managed inference providers" in str(exc) + assert "selected native Anthropic route" in str(exc) else: - raise AssertionError("non-managed model provider was allowed") + raise AssertionError("Anthropic was allowed on an unrelated managed route") + from deepagents_code import _nemoclaw_managed as managed_runtime + original_base_url = managed_runtime.managed_inference_base_url + original_api_key = managed_runtime.managed_inference_api_key + managed_runtime.managed_inference_base_url = lambda: "https://api.anthropic.com" + managed_runtime.managed_inference_api_key = lambda: "openshell:resolve:env:v1_ANTHROPIC_API_KEY" + try: + assert config._get_provider_kwargs("anthropic") == { + "api_key": "openshell:resolve:env:v1_ANTHROPIC_API_KEY", + "base_url": "https://api.anthropic.com", + } + selector._select_with_auth_check("anthropic:model", "anthropic") + assert selector.original_selection == ("anthropic:model", "anthropic") + try: + config._get_provider_kwargs("google_genai") + except model_config.ModelConfigError: + pass + else: + raise AssertionError("non-managed model provider was allowed") + finally: + managed_runtime.managed_inference_base_url = original_base_url + managed_runtime.managed_inference_api_key = original_api_key os.environ["LANGGRAPH_CLI_NO_ANALYTICS"] = "0" child_env = server._build_server_env() assert child_env["LANGGRAPH_NO_VERSION_CHECK"] == "true" diff --git a/test/agents/deepagents/langchain-deepagents-code-image.test.ts b/test/agents/deepagents/langchain-deepagents-code-image.test.ts index 0022c0bb8aa..4fa749941e0 100644 --- a/test/agents/deepagents/langchain-deepagents-code-image.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-image.test.ts @@ -239,6 +239,12 @@ describe("LangChain Deep Agents Code image contracts", () => { "COPY src/lib/inference/native-nvidia/contract.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-nvidia/contract.ts", ); expect(dockerfile).toContain("node /opt/nemoclaw-deepagents-code/generate-config.ts"); + expect(dockerfile).toContain( + "COPY src/lib/inference/native-hosted/profiles.ts /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts", + ); + expect(dockerfile).toContain( + "RUN chmod 444 /opt/nemoclaw-deepagents-code/src/lib/inference/native-hosted/profiles.ts", + ); expect(dockerfile).not.toContain("langchain-deepagents-code-sandbox-base:latest"); expect(dockerfile).toContain( 'timeout 10 env -i /usr/local/lib/nemoclaw/dcode-wrapper.sh -n ""', diff --git a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts index 9d636f91f7a..313d30ce47a 100644 --- a/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts +++ b/test/agents/deepagents/langchain-deepagents-code-managed-model-params.test.ts @@ -1,17 +1,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; import path from "node:path"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterAll, afterEach, describe, expect, it } from "vitest"; import { + cleanupCachedPatchedFixture, cleanupPackageFixtures, + createPatchedPackageFixture, createPackageFixture, patchFixture, } from "../../helpers/langchain-deepagents-code-patch-fixture"; afterEach(cleanupPackageFixtures); +afterAll(cleanupCachedPatchedFixture); const e2eProfileCheckPath = path.join( process.cwd(), @@ -104,7 +107,6 @@ from deepagents_code import config name = "NVIDIA_INFERENCE_API_KEY" for value in ( - "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", "openshell:resolve:env:v12_NVIDIA_INFERENCE_API_KEY", "openshell:resolve:env:s" + "a" * 64 + "_NVIDIA_INFERENCE_API_KEY", ): @@ -117,6 +119,7 @@ for value in ( assert resolved["base_url"] == "https://integrate.api.nvidia.com/v1" for value in ( + "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", "", "nvapi-" + "x" * 32, "nemoclaw-managed-inference", @@ -170,3 +173,99 @@ print("native-managed-constructor-placeholder-ok") expect(reportedResult).toBeGreaterThan(resolverContract); }); }); + +describe("native inference issued credentials", () => { + it.each(["openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", undefined])( + "maps the legacy native credential key only when a current binding exists [%#] (#12822)", + (placeholder) => { + const tempDir = createPatchedPackageFixture(); + const validation = String.raw` +import os +from deepagents_code import _nemoclaw_managed as managed +managed.assert_safe_runtime() +assert os.environ.get("NEMOCLAW_ATTACHED_PROVIDER_API_KEY") == (os.environ.get("NVIDIA_INFERENCE_API_KEY") or None) +managed._assert_safe_environment() +`; + const result = spawnSync("python3", ["-c", validation], { + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + NVIDIA_INFERENCE_API_KEY: placeholder, + NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "nemoclaw-openshell-provider", + }, + encoding: "utf8", + }); + expect(result.status, result.stderr).toBe(0); + }, + ); + + it("rejects a legacy placeholder that does not match the current native binding (#12822)", () => { + const tempDir = createPatchedPackageFixture(); + const result = spawnSync("python3", ["-m", "deepagents_code"], { + env: { + PATH: process.env.PATH, + PYTHONPATH: tempDir, + NVIDIA_INFERENCE_API_KEY: "openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY", + NEMOCLAW_ATTACHED_PROVIDER_API_KEY: "openshell:resolve:env:v2_NVIDIA_INFERENCE_API_KEY", + }, + encoding: "utf8", + }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain( + "runtime environment variable NEMOCLAW_ATTACHED_PROVIDER_API_KEY", + ); + expect(result.stdout).not.toContain("managed-posture-ok"); + }); + + it.each([ + ["nvidia-prod", "https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"], + ["openai-api", "https://api.openai.com/v1", "OPENAI_API_KEY"], + ["anthropic-prod", "https://api.anthropic.com", "ANTHROPIC_API_KEY"], + ["gemini-api", "https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"], + ["openrouter-api", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"], + ["hermes-provider", "https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY"], + ])("binds %s constructor credentials to the issued scoped handle", (provider, endpoint, key) => { + const tempDir = createPatchedPackageFixture(); + const result = spawnSync( + "python3", + [ + "-c", + ` +import os +from pathlib import Path +from deepagents_code import config, _nemoclaw_managed as managed +for name, value in [("managed-upstream-provider", ${JSON.stringify(provider)}), ("managed-inference-base-url", ${JSON.stringify(endpoint)})]: + target = Path(${JSON.stringify(tempDir)}) / name + target.chmod(0o644) + target.write_text(value + "\\n") + target.chmod(0o444) +key = ${JSON.stringify(key)} +for value in ["openshell:resolve:env:v42_" + key, "openshell:resolve:env:s" + "a" * 64 + "_" + key]: + os.environ[key] = value + assert config._get_provider_kwargs("openai")["api_key"] == value +for value in ["", "raw-secret-do-not-print", "openshell:resolve:env:" + key, "openshell:resolve:env:v42_OTHER_KEY"]: + os.environ[key] = value + try: + config._get_provider_kwargs("openai") + except RuntimeError as error: + assert str(error) == "Native inference requires an issued OpenShell credential handle" + else: + raise AssertionError("unsafe credential accepted") +del os.environ[key] +try: + config._get_provider_kwargs("openai") +except RuntimeError: + pass +else: + raise AssertionError("missing credential accepted") +`, + ], + { + env: { PATH: process.env.PATH, PYTHONPATH: tempDir }, + encoding: "utf8", + }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout + result.stderr).not.toContain("raw-secret-do-not-print"); + }); +}); diff --git a/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts b/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts index fc7106029bf..caafa1d82df 100644 --- a/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts +++ b/test/agents/hermes/hermes-external-supervisor-restart-patch.test.ts @@ -17,9 +17,14 @@ import types events = [] scenario = sys.argv[1] +import subprocess +def native_guard_run(argv, *, check): + events.append(["native-guard", argv[2:]]) + return types.SimpleNamespace(returncode={"invalid": 1, "unavailable": 2}.get(scenario, 0)) +subprocess.run = native_guard_run status = types.ModuleType("gateway.status") -status.get_running_pid = lambda: None if scenario == "missing" else 4321 +status.get_running_pid = lambda: None if scenario in ("missing", "invalid", "unavailable") else 4321 gateway = types.ModuleType("gateway") gateway.status = status sys.modules["gateway"] = gateway @@ -189,6 +194,36 @@ describe("Hermes external-supervisor restart patch", () => { } }); + it.each([ + ["invalid", 1], + ["unavailable", 2], + ] as const)( + "refuses missing-supervisor fallback when native validation is %s", + (scenario, status) => { + const { gatewayPath, temporaryRoot } = writeFixture(); + try { + expect(patch(gatewayPath).status).toBe(0); + const result = run(gatewayPath, scenario); + expect(result.status).toBe(status); + expect(lastJson(result.stdout).events).toContainEqual([ + "native-guard", + [ + "/usr/local/lib/nemoclaw/hermes-runtime-config-guard.py", + "native-inference-credential", + "--hermes-dir", + "/sandbox/.hermes", + "--hash-file", + "/etc/nemoclaw/hermes.config-hash", + ], + ]); + expect(lastJson(result.stdout).events).not.toContainEqual(["manual-stop"]); + expect(lastJson(result.stdout).events).not.toContainEqual(["manual-start", 0, false]); + } finally { + fs.rmSync(temporaryRoot, { recursive: true, force: true }); + } + }, + ); + it("fails instead of falling through when the supervised gateway does not exit", () => { const { gatewayPath, temporaryRoot } = writeFixture(); try { diff --git a/test/agents/hermes/hermes-managed-policy.test.ts b/test/agents/hermes/hermes-managed-policy.test.ts index cd8bcda4549..265d23437a5 100644 --- a/test/agents/hermes/hermes-managed-policy.test.ts +++ b/test/agents/hermes/hermes-managed-policy.test.ts @@ -155,3 +155,27 @@ describe("Hermes managed policy", () => { expect(patcher.status, patcher.stderr).toBe(0); }); }); + +describe("native inference credential references", () => { + it.each([ + ["nvidia-prod", "https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"], + ["openai-api", "https://api.openai.com/v1", "OPENAI_API_KEY"], + ["anthropic-prod", "https://api.anthropic.com", "ANTHROPIC_API_KEY"], + ["gemini-api", "https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"], + ["openrouter-api", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"], + ["hermes-provider", "https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY"], + ])("references issued runtime credentials in every %s route leaf", (provider, baseUrl, key) => { + const policy = buildHermesManagedPolicy( + { ...SETTINGS, upstreamProvider: provider, baseUrl }, + {}, + ); + const reference = "$" + "{" + key + "}"; + expect(policy.config.model?.api_key).toBe(reference); + expect(Object.values(policy.config.providers ?? {}).map((value) => value.api_key)).toEqual([ + reference, + ]); + expect(policy.config.custom_providers?.map((value) => value.api_key)).toEqual([reference]); + const result = loadWithPython(policy); + expect(result.status, result.stderr).toBe(0); + }); +}); diff --git a/test/agents/hermes/hermes-runtime-config-guard.test.ts b/test/agents/hermes/hermes-runtime-config-guard.test.ts index 9ebee8b67af..69c7503e69a 100644 --- a/test/agents/hermes/hermes-runtime-config-guard.test.ts +++ b/test/agents/hermes/hermes-runtime-config-guard.test.ts @@ -1190,3 +1190,44 @@ print(json.dumps(captured)) }); }); }); + +describe("native inference integrity anchor authority", () => { + it.each([ + [true, 0, false, "strict"], + [true, 1000, false, "compat"], + [true, null, false, "strict"], + [false, null, true, "compat"], + [false, null, false, "strict"], + ])("selects only the proven runtime anchor case %#", (direct, uid, supervised, expected) => { + const result = runPythonHarness(`${loadGuardModule} +import json, os, pathlib, tempfile, types +case = json.loads(${JSON.stringify(JSON.stringify({ direct, uid, supervised, expected }))}) +guard._pid1_is_nemoclaw_start = lambda: case["direct"] +guard._process_effective_uid = lambda _pid: case["uid"] +guard.pwd.getpwnam = lambda _name: types.SimpleNamespace(pw_uid=1000) +guard._openshell_supervised_nonroot_start_is_live = lambda *_args: case["supervised"] +with tempfile.TemporaryDirectory() as root: + home = pathlib.Path(root) + config = home / "config.yaml" + env = home / ".env" + strict = home / "strict" + compat = home / ".config-hash" + config.write_text(json.dumps({"model": {"api_key": "$" + "{OPENAI_API_KEY}"}})) + env.write_text("") + digest, _, _ = guard._hash_text(str(config), str(env)) + strict.write_text("invalid strict anchor") + compat.write_text(digest) + selected = str(compat) if case["expected"] == "compat" else str(strict) + assert guard._native_inference_hash_file(root, str(strict)) == selected + os.environ["OPENAI_API_KEY"] = "openshell:resolve:env:v42_OPENAI_API_KEY" + try: + guard.validate_native_inference_credential(root, str(strict)) + outcome = "compat" + except guard.UnsafePathError as error: + assert str(error) == "Native inference requires an intact managed route and an issued OpenShell credential handle" + outcome = "strict" + assert outcome == case["expected"] +`); + expect(result.status, result.stderr).toBe(0); + }); +}); diff --git a/test/agents/hermes/hermes-start.test.ts b/test/agents/hermes/hermes-start.test.ts index f922898c27c..5fea0529c1e 100644 --- a/test/agents/hermes/hermes-start.test.ts +++ b/test/agents/hermes/hermes-start.test.ts @@ -315,6 +315,7 @@ function runTirithExplicitCommandDispatch(mode: "non-root" | "root") { "ensure_hermes_runtime_api_server_key() { :; }", "refresh_hermes_runtime_config_hashes() { :; }", "refresh_hermes_provider_placeholders() { :; }", + "validate_hermes_native_inference_credential() { :; }", "configure_messaging_channels() { :; }", "prepare_hermes_nonroot_runtime() { prepare_tirith_marker_retry; }", "prepare_hermes_root_runtime() { prepare_tirith_marker_retry; }", @@ -371,6 +372,7 @@ function runHermesRootStartupMutableRootPreflight(initialMode = 0o750) { 'validate_hermes_runtime_env_secret_boundary() { printf "runtime-boundary mode=%s\\n" "$(dir_mode)"; }', 'migrate_legacy_hermes_dashboard_state() { printf "dashboard-migration mode=%s\\n" "$(dir_mode)"; }', "refresh_hermes_provider_placeholders() { :; }", + "validate_hermes_native_inference_credential() { :; }", "configure_messaging_channels() { :; }", 'retry_tirith_marker_if_needed() { printf "tirith-state=%s\\n" "$TIRITH_RETRY_MARKER_CLEARED"; }', "prepare_tirith_marker_retry() { TIRITH_RETRY_MARKER_CLEARED=0; retry_tirith_marker_if_needed; }", @@ -1118,6 +1120,7 @@ describe("agents/hermes/start.sh env secret boundary", () => { "ensure_hermes_runtime_api_server_key() { trace api-key; }", "validate_hermes_runtime_env_secret_boundary() { trace runtime-boundary; }", "refresh_hermes_provider_placeholders() { trace placeholders; }", + "validate_hermes_native_inference_credential() { trace native-credential; }", 'refresh_hermes_runtime_config_hashes() { trace "hashes:$1:${2:-preserve}"; hash_state=current; }', "configure_messaging_channels() { trace channels; }", "retry_tirith_marker_if_needed() { trace tirith; }", @@ -1142,6 +1145,7 @@ describe("agents/hermes/start.sh env secret boundary", () => { "hashes:compat:preserve", "channels", "tirith", + "native-credential", ]); }); it("rejects bare API-named raw values without printing the value", () => { diff --git a/test/agents/hermes/hermes-tirith-retry-finalization.test.ts b/test/agents/hermes/hermes-tirith-retry-finalization.test.ts index c47d27033df..a5ed38cc850 100644 --- a/test/agents/hermes/hermes-tirith-retry-finalization.test.ts +++ b/test/agents/hermes/hermes-tirith-retry-finalization.test.ts @@ -176,6 +176,7 @@ describe("agents/hermes/start.sh Tirith retry finalization", () => { "ensure_hermes_runtime_api_server_key() { :; }", "validate_hermes_env_secret_boundary() { :; }", "validate_hermes_runtime_env_secret_boundary() { :; }", + "validate_hermes_native_inference_credential() { :; }", "refresh_hermes_provider_placeholders() { :; }", "migrate_legacy_hermes_dashboard_state() { :; }", "configure_messaging_channels() { :; }", @@ -186,7 +187,7 @@ describe("agents/hermes/start.sh Tirith retry finalization", () => { "finalize_tirith_marker_retry", ]); - expect(run.result.status).toBe(0); + expect(run.result.status, run.result.stderr).toBe(0); expect(run.markerKind?.isFile()).toBe(true); expect(run.markerContent).toBe("download_failed"); }); diff --git a/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts b/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts index 93ffb7e611f..0b4ede29c0c 100644 --- a/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts +++ b/test/agents/hermes/hermes-wrapper-oneshot-routing.test.ts @@ -5,10 +5,12 @@ // These tests keep that retired compatibility surface on the native CLI path. import fs from "node:fs"; +import { spawnSync } from "node:child_process"; +import path from "node:path"; import { describe, expect, it } from "vitest"; -import { ADAPTER, canRun, runWrapper } from "../../helpers/hermes-wrapper-harness.ts"; +import { ADAPTER, WRAPPER, canRun, runWrapper } from "../../helpers/hermes-wrapper-harness.ts"; describe.skipIf(!canRun)("agents/hermes/hermes-wrapper.py native one-shot routing", () => { it("passes a resumed one-shot through to Hermes 0.21.3 unchanged (#5254)", () => { @@ -83,3 +85,91 @@ describe.skipIf(!canRun)("agents/hermes/hermes-wrapper.py native one-shot routin expect(run.stderr).toContain("invalid translation metadata"); }); }); + +describe("Hermes direct native inference credential guard", () => { + it("uses the current hashed route after switching and refuses unsafe handles before exec", () => { + const runtimeGuard = path.resolve("agents/hermes/runtime-config-guard.py"); + const result = spawnSync( + "python3", + [ + "-c", + String.raw` +import importlib.util, json, os, pathlib, subprocess, sys, tempfile +spec = importlib.util.spec_from_file_location("runtime_guard", sys.argv[1]) +guard = importlib.util.module_from_spec(spec) +sys.modules[spec.name] = guard +spec.loader.exec_module(guard) +with tempfile.TemporaryDirectory() as root: + home = pathlib.Path(root) + config = home / "config.yaml" + env = home / ".env" + hashes = home / "hashes" + marker = home / "invoked" + real = home / "hermes.real" + real.write_text("#!/bin/sh\ntouch " + str(marker) + "\n") + real.chmod(0o755) + env.write_text("") + script = "\n".join([ + "import importlib.util, sys", + "spec = importlib.util.spec_from_file_location('wrapper', sys.argv[1])", + "wrapper = importlib.util.module_from_spec(spec)", + "spec.loader.exec_module(wrapper)", + "wrapper._TRUSTED_PYTHON3 = (sys.executable,)", + "wrapper._resolve_real_hermes = lambda: sys.argv[2]", + "wrapper._resolve_cli_adapter = lambda: sys.argv[3]", + "wrapper._resolve_native_inference_guard = lambda: sys.argv[4]", + "wrapper._MANAGED_HERMES_HOME = sys.argv[5]", + "wrapper._NATIVE_INFERENCE_HASH_FILE = sys.argv[6]", + # Other owners exercise the gateway env boundary; isolate native route validation here. + "wrapper._run_gateway_env_file_guard = lambda _path: 0", + "wrapper._run_gateway_guard = lambda _path: 0", + "wrapper.os.geteuid = lambda: 1000", + "raise SystemExit(wrapper.main(sys.argv[7:]))", + ]) + command = [sys.executable, "-c", script, sys.argv[2], str(real), sys.argv[3], sys.argv[1], str(home), str(hashes)] + for key in ["NVIDIA_INFERENCE_API_KEY", "OPENAI_API_KEY"]: + config.write_text(json.dumps({"model": {"api_key": "$" + "{" + key + "}"}})) + hash_text, _, _ = guard._hash_text(str(config), str(env)) + hashes.write_text(hash_text) + for value, expected in [("openshell:resolve:env:v42_" + key, 0), ("openshell:resolve:env:s" + "a" * 64 + "_" + key, 0), ("", 1), ("raw-secret-do-not-print", 1), ("openshell:resolve:env:" + key, 1), ("openshell:resolve:env:v42_OTHER_KEY", 1)]: + marker.unlink(missing_ok=True) + run = subprocess.run(command + ["chat", "--query", "hello"], env={"PATH": os.environ["PATH"], key: value}, capture_output=True, text=True) + assert run.returncode == expected, run.stderr + assert marker.exists() == (expected == 0) + assert "raw-secret-do-not-print" not in run.stderr + missing = subprocess.run(command + ["chat", "--query", "hello"], env={"PATH": os.environ["PATH"]}, capture_output=True, text=True) + assert missing.returncode == 1 + help_run = subprocess.run(command + ["chat", "--help"], env={"PATH": os.environ["PATH"]}, capture_output=True, text=True) + assert help_run.returncode == 0, help_run.stderr + # Restoring a legitimate legacy home changes its hash before the supervised + # replacement's preparation transaction can refresh it. Restart only signals + # that supervisor; direct launch/chat must still refuse the stale snapshot. + config.write_text(json.dumps({"model": {"api_key": "sk-OPENSHELL-PROXY-REWRITE"}})) + for argv, expected in [(["gateway", "restart"], 0), (["gateway", "run"], 1), (["gateway", "restart", "--all"], 1), (["chat", "--query", "hello"], 1)]: + marker.unlink(missing_ok=True) + run = subprocess.run(command + argv, capture_output=True, text=True) + assert run.returncode == expected, run.stderr + assert marker.exists() == (expected == 0) + # The actual launch is admitted only after reconciliation seals the snapshot. + hash_text, _, _ = guard._hash_text(str(config), str(env)) + hashes.write_text(hash_text) + run = subprocess.run(command + ["gateway", "run"], capture_output=True, text=True) + assert run.returncode == 0, run.stderr + config.write_text("model: {api_key: raw-secret-do-not-print}") + hash_text, _, _ = guard._hash_text(str(config), str(env)) + hashes.write_text(hash_text) + marker.unlink(missing_ok=True) + run = subprocess.run(command + ["chat", "--query", "hello"], capture_output=True, text=True) + assert run.returncode == 1 + assert not marker.exists() + assert "raw-secret-do-not-print" not in run.stderr +`, + runtimeGuard, + WRAPPER, + ADAPTER, + ], + { encoding: "utf8", timeout: 15000 }, + ); + expect(result.status, result.stderr).toBe(0); + }); +}); diff --git a/test/agents/openclaw/runtime/nemoclaw-start-native-credentials.test.ts b/test/agents/openclaw/runtime/nemoclaw-start-native-credentials.test.ts new file mode 100644 index 00000000000..a4009a5aca6 --- /dev/null +++ b/test/agents/openclaw/runtime/nemoclaw-start-native-credentials.test.ts @@ -0,0 +1,38 @@ +// 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 { runRefresh } from "./provider-placeholder-refresh-fixture"; + +vi.setConfig({ maxConcurrency: 4 }); + +describe.concurrent("native inference credential placeholder refresh", () => { + it.each([ + "NVIDIA_INFERENCE_API_KEY", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GEMINI_API_KEY", + "OPENROUTER_API_KEY", + ])("keeps issued native %s handles in the environment", async (key) => { + const config = { models: { providers: { inference: { apiKey: `\${${key}}` } } } }; + const run = await runRefresh(config, { [key]: `openshell:resolve:env:v7_${key}` }, true); + expect(run.result.status).toBe(0); + expect(run.config).toEqual(config); + }); + + it.each(["", "raw-native-credential-canary", "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY"])( + "refuses a native runtime credential without issued identity %s", + async (value) => { + const config = { + models: { providers: { inference: { apiKey: "${NVIDIA_INFERENCE_API_KEY}" } } }, + }; + const run = await runRefresh(config, { NVIDIA_INFERENCE_API_KEY: value }, true); + expect(run.result.status).not.toBe(0); + expect(run.config).toEqual(config); + expect(run.result.stderr).toContain( + "Native inference requires an issued OpenShell credential handle", + ); + expect(run.result.stderr).not.toContain("raw-native-credential-canary"); + }, + ); +}); diff --git a/test/agents/openclaw/runtime/nemoclaw-start.test.ts b/test/agents/openclaw/runtime/nemoclaw-start.test.ts index 4cca048c5c1..847b30ddf18 100644 --- a/test/agents/openclaw/runtime/nemoclaw-start.test.ts +++ b/test/agents/openclaw/runtime/nemoclaw-start.test.ts @@ -7,10 +7,10 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; -import JSON5 from "json5"; import * as ts from "typescript"; import { describe, expect, it, vi } from "vitest"; import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; +import { runRefresh } from "./provider-placeholder-refresh-fixture"; import { createCanonicalCliFixture, setupLateCliFixture } from "./auto-pair-settlement-fixture"; const START_SCRIPT = path.join( @@ -41,17 +41,6 @@ const runCommand = promisify(execFile); // Concurrent process fixtures are independent, but keep their host load bounded. vi.setConfig({ maxConcurrency: 4 }); -function execFileResult(file, args, options) { - return new Promise((resolve) => - execFile(file, args, options, (error, stdout, stderr) => - resolve({ - status: Number(error?.code) || (error ? -1 : 0), - stdout, - stderr, - }), - ), - ); -} function runtimeShellEnvBlock(src: string): string { const start = src.indexOf("write_runtime_shell_env() {"); const end = src.indexOf("# cleanup_on_signal", start); @@ -2243,7 +2232,6 @@ describe("Slack secrets-on-disk tripwire (#2085)", () => { }); describe.concurrent("provider placeholder refresh (#4251)", () => { - const src = fs.readFileSync(START_SCRIPT, "utf-8"); const extraPlaceholderKeys = require( path.join( import.meta.dirname, @@ -2257,62 +2245,6 @@ describe.concurrent("provider placeholder refresh (#4251)", () => { const canonicalKeys: string[] = Array.from( extraPlaceholderKeys.canonicalPlaceholderKeys(), ).sort(); - async function runRefresh( - config: unknown, - env: Record = {}, - rootMode = false, - runtimePlan: unknown = { credentialBindings: [] }, - ) { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-provider-placeholders-")); - try { - const openclawDir = path.join(tmpDir, ".openclaw"); - const configPath = path.join(openclawDir, "openclaw.json"); - const handoffEnvPath = path.join(tmpDir, "handoff-env"); - const runtimePlanPath = path.join(tmpDir, "messaging-runtime-plan.json"); - const scriptPath = path.join(tmpDir, "run.sh"); - fs.mkdirSync(openclawDir, { recursive: true }); - fs.writeFileSync( - configPath, - `// Native OpenClaw JSON5\n${JSON.stringify(config, null, 2)}\n`, - ); - fs.writeFileSync(runtimePlanPath, JSON.stringify(runtimePlan)); - const fn = extractShellFunctionFromSource(src, "refresh_openclaw_provider_placeholders") - .replaceAll("/sandbox/.openclaw", openclawDir) - .replaceAll("/usr/local/share/nemoclaw/messaging-runtime-plan.json", runtimePlanPath) - .replaceAll("/usr/local/lib/node_modules/openclaw/node_modules/json5", JSON5_MODULE) - .replaceAll("/usr/local/bin/node", process.execPath); - fs.writeFileSync( - scriptPath, - [ - "#!/usr/bin/env bash", - "set -euo pipefail\nrefresh_openclaw_wechat_account_placeholder() { :; }", - ...(rootMode - ? [ - "id() { printf '0\\n'; }", - `STEP_DOWN_PREFIX_SANDBOX=(/bin/bash -c 'env >${JSON.stringify(handoffEnvPath)}; exec "$@"' sandbox-step-down)`, - extractShellFunctionFromSource(src, "run_openclaw_config_as_owner"), - ] - : ['run_openclaw_config_as_owner() { "$@"; }']), - fn, - "refresh_openclaw_provider_placeholders", - ].join("\n"), - { mode: 0o700 }, - ); - const result = await execFileResult("bash", [scriptPath], { - encoding: "utf-8", - env: { PATH: process.env.PATH || "", ...env }, - timeout: 5000, - }); - const updatedConfig = JSON5.parse(fs.readFileSync(configPath, "utf-8")); - const handoffEnv = fs.existsSync(handoffEnvPath) - ? fs.readFileSync(handoffEnvPath, "utf-8") - : ""; - return { config: updatedConfig, handoffEnv, result }; - } finally { - fs.rmSync(tmpDir, { recursive: true, force: true }); - } - } - function placeholderPlan(envKeys: string[]): string { return Buffer.from( JSON.stringify({ diff --git a/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts b/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts index fb26a4ae379..1561dcf6412 100644 --- a/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts +++ b/test/agents/openclaw/runtime/pi-candidate-runtime-artifacts.test.ts @@ -10,6 +10,7 @@ import { CANDIDATE_MANAGED_IMAGE_AGENTS, SHIPPED_MANAGED_IMAGE_AGENTS, } from "../../../../src/lib/onboard/managed-image/contract.ts"; +import { NATIVE_HOSTED_PROFILES } from "../../../../src/lib/inference/native-hosted/profiles.ts"; import { validateCandidateContract } from "../../../../tools/managed-images/validate-candidate-contract.mts"; import { readWorkflow, @@ -97,6 +98,28 @@ describe("Pi candidate contract validation", () => { }); }); +describe("Pi final-image credential boundary", () => { + const dockerfile = fs.readFileSync(path.join(root, "agents/pi/Dockerfile"), "utf8"); + const environmentGate = required( + dockerfile.match(/if env \| grep -Eq '[^']+'; then [\s\S]*?fi;/u)?.[0], + "Pi Dockerfile is missing its final-image credential environment gate", + ); + it.each([ + ...new Set([ + "NVIDIA_API_KEY", + ...NATIVE_HOSTED_PROFILES.map((profile) => profile.credentialEnv), + ]), + ])("rejects inherited %s before admitting the final image", (credential) => { + const result = spawnSync("bash", ["-c", environmentGate], { + encoding: "utf8", + env: { PATH: process.env.PATH, [credential]: "fake-inherited-secret" }, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("upstream provider credential is present"); + expect(result.stdout + result.stderr).not.toContain("fake-inherited-secret"); + }); +}); + describe("Pi managed model catalog generation", () => { function generate(env: Record): { home: string; @@ -112,6 +135,84 @@ describe("Pi managed model catalog generation", () => { return { home, status: result.status, stderr: result.stderr }; } + it.each([ + ["nvidia-prod", "https://integrate.api.nvidia.com/v1", "NVIDIA_INFERENCE_API_KEY"], + ["openai-api", "https://api.openai.com/v1", "OPENAI_API_KEY"], + ["gemini-api", "https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY"], + ["openrouter-api", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY"], + ["hermes-provider", "https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY"], + ])( + "resolves %s credentials at request time without baking secrets", + (provider, endpoint, key) => { + const { home, status, stderr } = generate({ + NEMOCLAW_MODEL: "selected", + NEMOCLAW_UPSTREAM_PROVIDER: provider, + NEMOCLAW_INFERENCE_BASE_URL: endpoint, + [key]: "raw-secret-do-not-copy", + }); + try { + expect(status, stderr).toBe(0); + const text = fs.readFileSync(path.join(home, ".pi/agent/models.json"), "utf8"); + expect(JSON.parse(text).providers.openshell.apiKey).toBe( + `!/usr/local/bin/node /opt/nemoclaw-pi/resolve-native-credential.ts ${key}`, + ); + expect(text).not.toContain("raw-secret-do-not-copy"); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }, + ); + + it("preserves OpenRouter attribution headers", () => { + const { home } = generate({ + NEMOCLAW_MODEL: "selected", + NEMOCLAW_UPSTREAM_PROVIDER: "openrouter-api", + NEMOCLAW_INFERENCE_BASE_URL: "https://openrouter.ai/api/v1", + }); + try { + const config = JSON.parse(fs.readFileSync(path.join(home, ".pi/agent/models.json"), "utf8")); + expect(config.providers.openshell.headers).toEqual({ + "HTTP-Referer": "https://www.nvidia.com/nemoclaw/", + "X-OpenRouter-Title": "NVIDIA NemoClaw", + }); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + }); + describe.each([ + "NVIDIA_INFERENCE_API_KEY", + "OPENAI_API_KEY", + "GEMINI_API_KEY", + "OPENROUTER_API_KEY", + ])("runtime resolver %s", (key) => { + it.each([ + ["revision", true], + ["stable", true], + ["missing", false], + ["raw", false], + ["canonical", false], + ["newline", false], + ] as const)("checks %s", (kind, valid) => { + const values = { + revision: `openshell:resolve:env:v42_${key}`, + stable: `openshell:resolve:env:s${"a".repeat(64)}_${key}`, + missing: "", + raw: "raw-secret-do-not-copy", + canonical: `openshell:resolve:env:${key}`, + newline: `openshell:resolve:env:v42_${key}\n`, + }; + const value = values[kind]; + const run = spawnSync( + process.execPath, + [path.join(root, "agents/pi/resolve-native-credential.ts"), key], + { encoding: "utf8", env: { PATH: process.env.PATH, [key]: value } }, + ); + expect(run.status).toBe(valid ? 0 : 1); + expect(run.stdout).toBe(valid ? value : ""); + expect(run.stderr).not.toContain("raw-secret-do-not-copy"); + }); + }); + it("writes an owner-only catalog that routes the managed model", () => { const { home, status, stderr } = generate({ NEMOCLAW_MODEL: "nvidia/nemotron-3-super-120b-a12b", diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh-fixture.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh-fixture.ts new file mode 100644 index 00000000000..7669f96113b --- /dev/null +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh-fixture.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFile } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import JSON5 from "json5"; +import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; + +const src = fs.readFileSync( + path.resolve(import.meta.dirname, "../../../../scripts/nemoclaw-start.sh"), + "utf-8", +); +const JSON5_MODULE = path.resolve(import.meta.dirname, "../../../../nemoclaw/node_modules/json5"); + +function execFileResult( + file: string, + args: string[], + options: { encoding: "utf-8"; env: NodeJS.ProcessEnv; timeout: number }, +) { + return new Promise<{ status: number; stdout: string; stderr: string }>((resolve) => + execFile(file, args, options, (error, stdout, stderr) => + resolve({ + status: Number(error?.code) || (error ? -1 : 0), + stdout, + stderr, + }), + ), + ); +} + +export async function runRefresh( + config: unknown, + env: Record = {}, + rootMode = false, + runtimePlan: unknown = { credentialBindings: [] }, +) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-provider-placeholders-")); + try { + const openclawDir = path.join(tmpDir, ".openclaw"); + const configPath = path.join(openclawDir, "openclaw.json"); + const handoffEnvPath = path.join(tmpDir, "handoff-env"); + const runtimePlanPath = path.join(tmpDir, "messaging-runtime-plan.json"); + const scriptPath = path.join(tmpDir, "run.sh"); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.writeFileSync(configPath, `// Native OpenClaw JSON5\n${JSON.stringify(config, null, 2)}\n`); + fs.writeFileSync(runtimePlanPath, JSON.stringify(runtimePlan)); + const fn = extractShellFunctionFromSource(src, "refresh_openclaw_provider_placeholders") + .replaceAll("/sandbox/.openclaw", openclawDir) + .replaceAll("/usr/local/share/nemoclaw/messaging-runtime-plan.json", runtimePlanPath) + .replaceAll("/usr/local/lib/node_modules/openclaw/node_modules/json5", JSON5_MODULE) + .replaceAll("/usr/local/bin/node", process.execPath); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail\nrefresh_openclaw_wechat_account_placeholder() { :; }", + ...(rootMode + ? [ + "id() { printf '0\\n'; }", + `STEP_DOWN_PREFIX_SANDBOX=(/bin/bash -c 'env >${JSON.stringify(handoffEnvPath)}; exec "$@"' sandbox-step-down)`, + extractShellFunctionFromSource(src, "run_openclaw_config_as_owner"), + ] + : ['run_openclaw_config_as_owner() { "$@"; }']), + fn, + "refresh_openclaw_provider_placeholders", + ].join("\n"), + { mode: 0o700 }, + ); + const result = await execFileResult("bash", [scriptPath], { + encoding: "utf-8", + env: { PATH: process.env.PATH || "", ...env }, + timeout: 5000, + }); + const updatedConfig = JSON5.parse(fs.readFileSync(configPath, "utf-8")); + const handoffEnv = fs.existsSync(handoffEnvPath) + ? fs.readFileSync(handoffEnvPath, "utf-8") + : ""; + return { config: updatedConfig, handoffEnv, result }; + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } +} diff --git a/test/automation/e2e/e2e-recommendations.test.ts b/test/automation/e2e/e2e-recommendations.test.ts index 37ea6320eae..ad37cdf06e2 100644 --- a/test/automation/e2e/e2e-recommendations.test.ts +++ b/test/automation/e2e/e2e-recommendations.test.ts @@ -136,6 +136,7 @@ describe("E2E recommendation normalizer", () => { "tools/advisors/risk-plan.mts", "tools/e2e/credential-free-tests.mts", "tools/e2e/execution-coverage.mts", + "tools/e2e/fixed-hosted-qualification.mts", "tools/e2e/full-e2e-timeout-contract.mts", "tools/e2e/gateway-runtime.mts", "tools/e2e/hermes-acp-owning-paths.mts", diff --git a/test/cli/connect-readiness.test.ts b/test/cli/connect-readiness.test.ts index 526969f7eb7..8ba2d9ca814 100644 --- a/test/cli/connect-readiness.test.ts +++ b/test/cli/connect-readiness.test.ts @@ -31,7 +31,7 @@ describe("CLI connect readiness", () => { alpha: { name: "alpha", model: "test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, @@ -51,7 +51,7 @@ describe("CLI connect readiness", () => { 'printf \'%s\\n\' "$*" >> "$marker_file"', 'if [ "$1" = "inference" ] && [ "$2" = "get" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: test-model'", " exit 0", "fi", diff --git a/test/cli/connect-terminal-agent.test.ts b/test/cli/connect-terminal-agent.test.ts index 63896bc3f82..6bcc80eed7a 100644 --- a/test/cli/connect-terminal-agent.test.ts +++ b/test/cli/connect-terminal-agent.test.ts @@ -20,6 +20,7 @@ describe("CLI dispatch for terminal agents", () => { writeSandboxRegistry(home, { ...launchReadinessRegistryFixture(), agent: "langchain-deepagents-code", + provider: "custom-shared-provider", }); fs.writeFileSync( path.join(localBin, "openshell"), @@ -36,7 +37,7 @@ describe("CLI dispatch for terminal agents", () => { " exit 0", "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', - " printf '%s\\n' 'Gateway inference:' ' Provider: nvidia-prod' ' Model: test-model'", + " printf '%s\\n' 'Gateway inference:' ' Provider: custom-shared-provider' ' Model: test-model'", " exit 0", "fi", 'if [ "$1" = "sandbox" ] && [ "$2" = "get" ] && { [ "$3" = "alpha" ] || [ "$5" = "alpha" ]; }; then', diff --git a/test/cli/doctor-gateway-token.test.ts b/test/cli/doctor-gateway-token.test.ts index 08341be0e93..7670d9ea53a 100644 --- a/test/cli/doctor-gateway-token.test.ts +++ b/test/cli/doctor-gateway-token.test.ts @@ -112,7 +112,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Creating\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); @@ -247,7 +247,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ' "sandbox list -g nemoclaw") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ]); writeDoctorSandboxRegistry(setup.home, "alpha", { openshellDriver: "kubernetes" }); @@ -447,7 +447,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ` "sandbox list -g nemoclaw") printf "NAME STATUS\\n${sandboxName} Ready\\n"; exit 0 ;;`, - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ], sandboxName, @@ -490,7 +490,7 @@ describe("CLI dispatch", () => { ' "status") printf "Server Status\\n\\n Gateway: nemoclaw\\n Status: Connected\\n"; exit 0 ;;', ' "gateway info -g nemoclaw") printf "Gateway: nemoclaw\\n"; exit 0 ;;', ` "sandbox list -g nemoclaw") printf "NAME STATUS\\n${sandboxName} Ready\\n"; exit 0 ;;`, - ' "inference get") printf "Provider: nvidia-prod\\nModel: test-model\\n"; exit 0 ;;', + ' "inference get") printf "Provider: custom-shared-provider\\nModel: test-model\\n"; exit 0 ;;', "esac", ], sandboxName, diff --git a/test/cli/helpers.ts b/test/cli/helpers.ts index 85fd55b13b9..783f0b148a9 100644 --- a/test/cli/helpers.ts +++ b/test/cli/helpers.ts @@ -378,6 +378,7 @@ export function writeDoctorSandboxRegistry( ): void { writeSandboxRegistry(home, sandboxName, { agent: "openclaw", + provider: "custom-shared-provider", openshellDriver: "docker", openshellVersion: "0.0.72", nemoclawVersion: "0.0.95", diff --git a/test/cli/launch-routing.test.ts b/test/cli/launch-routing.test.ts index d338b703611..159a6a17b3c 100644 --- a/test/cli/launch-routing.test.ts +++ b/test/cli/launch-routing.test.ts @@ -51,7 +51,11 @@ function createLaunchHarness(prefix: string, agent: string): LaunchHarness { const callArgvFile = path.join(home, "openshell-call-argv"); const execArgvFile = path.join(home, "openshell-exec-argv"); fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home, { ...launchReadinessRegistryFixture(), agent }); + writeSandboxRegistry(home, { + ...launchReadinessRegistryFixture(), + agent, + provider: "custom-shared-provider", + }); fs.writeFileSync( path.join(localBin, "openshell"), @@ -81,7 +85,7 @@ function createLaunchHarness(prefix: string, agent: string): LaunchHarness { "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: test-model'", " exit 0", "fi", diff --git a/test/cli/sandbox-status-json.test.ts b/test/cli/sandbox-status-json.test.ts index 965f8d8ee5f..16658ec088d 100644 --- a/test/cli/sandbox-status-json.test.ts +++ b/test/cli/sandbox-status-json.test.ts @@ -32,7 +32,7 @@ function createInferenceRouteStatusSetup(options: { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, sandboxName, { model: "nvidia/nemotron", - provider: "nvidia-prod", + provider: "compatible-endpoint", // These cases test only inference.local classification. Use the VM driver // so Docker post-reboot delivery recovery does not affect their assertions. openshellDriver: "vm", @@ -92,7 +92,7 @@ function createInferenceRouteStatusSetup(options: { ]), "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', - " echo 'Provider: nvidia-prod'", + " echo 'Provider: compatible-endpoint'", " echo 'Model: nvidia/nemotron'", " exit 0", "fi", @@ -262,7 +262,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) ]); }); - it("sandbox status --json reports a missing upstream credential as not probed when inference.local is reachable (#6192)", async () => { + it("sandbox status --json reports an unknown upstream endpoint as not probed when inference.local is reachable (#6192)", async () => { const { home, localBin, sandboxName } = createInferenceRouteStatusSetup({ routeOutput: "OK 200", upstreamHttpStatus: "000", @@ -400,7 +400,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) ); const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home, "alpha"); + writeSandboxRegistry(home, "alpha", { provider: "custom-shared-provider" }); fs.writeFileSync( path.join(localBin, "openshell"), [ @@ -432,7 +432,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-cli-sandbox-status-json-rpc-")); const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); - writeSandboxRegistry(home, "alpha"); + writeSandboxRegistry(home, "alpha", { provider: "custom-shared-provider" }); fs.writeFileSync( path.join(localBin, "openshell"), [ @@ -465,7 +465,7 @@ describe.concurrent("CLI sandbox status JSON output", testTimeoutOptions(20_000) expect(parsed.rpcIssue).toEqual({ kind: "protobuf_mismatch" }); expect(parsed.inferenceHealth).toBeNull(); expect(parsed.model).toBe("test-model"); - expect(parsed.provider).toBe("nvidia-prod"); + expect(parsed.provider).toBe("custom-shared-provider"); }); it("sandbox status --json reports found:false and exits 1 for unknown sandbox via canonical form", async () => { diff --git a/test/cli/sandbox-status-text.test.ts b/test/cli/sandbox-status-text.test.ts index d8d104a1afa..14672b8aeb7 100644 --- a/test/cli/sandbox-status-text.test.ts +++ b/test/cli/sandbox-status-text.test.ts @@ -84,7 +84,7 @@ describe.concurrent("CLI sandbox status text output", () => { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, "alpha", { agent: "missing-terminal-agent", - provider: "openai-api", + provider: "custom-shared-provider", model: "gpt-4o-mini", openshellDriver: "docker", }); @@ -101,7 +101,7 @@ describe.concurrent("CLI sandbox status text output", () => { "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: openai-api'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: gpt-4o-mini'", " exit 0", "fi", @@ -138,7 +138,7 @@ describe.concurrent("CLI sandbox status text output", () => { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, "dcode-station", { agent: "langchain-deepagents-code", - provider: "nvidia-prod", + provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b", openshellDriver: "docker", openshellVersion: "0.0.44", @@ -156,7 +156,7 @@ describe.concurrent("CLI sandbox status text output", () => { "fi", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: nvidia/nemotron-3-super-120b-a12b'", " exit 0", "fi", @@ -271,7 +271,7 @@ describe.concurrent("CLI sandbox status text output", () => { const localBin = path.join(home, "bin"); fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, "alpha", { - provider: "openai-api", + provider: "compatible-endpoint", model: "gpt-4o-mini", openshellDriver: "vm", }); @@ -285,7 +285,7 @@ describe.concurrent("CLI sandbox status text output", () => { "#!/usr/bin/env bash", 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", - " echo ' Provider: openai-api'", + " echo ' Provider: compatible-endpoint'", " echo ' Model: gpt-4o-mini'", " exit 0", "fi", @@ -312,7 +312,7 @@ describe.concurrent("CLI sandbox status text output", () => { expect(r.code).toBe(0); expect(r.out).not.toContain("Failure layer: docker_unreachable"); expect(r.out).toContain("Sandbox: alpha"); - expect(r.out).toContain("Provider: openai-api"); + expect(r.out).toContain("Provider: compatible-endpoint"); expect(r.out).toContain("Model: gpt-4o-mini"); expect(r.out).toContain("Inference: healthy (https://inference.local/v1/models)"); expect(r.out).toContain( @@ -682,7 +682,8 @@ describe.concurrent("CLI sandbox status text output", () => { 30000, ); - expect(r.code, r.out).toBe(gatewayState === "present" ? 1 : 0); + // An intentional stop does not require a live inference route or agent probe. + expect(r.code, r.out).toBe(0); expect(r.out).not.toContain("Failure layer:"); expect(r.out).toContain("Phase: Stopped"); expect(r.out).not.toContain("Phase: Provisioning"); @@ -706,6 +707,7 @@ describe.concurrent("CLI sandbox status text output", () => { expect(parsed.phase).toBe("Stopped"); expect(parsed.gatewayState).toBe(gatewayState); expect(parsed.failureLayer).toBeNull(); + expect(parsed.routeDrift).toBeNull(); }, ); }); diff --git a/test/cli/status-gateway-lifecycle.test.ts b/test/cli/status-gateway-lifecycle.test.ts index 5853d857d89..f617065b9c8 100644 --- a/test/cli/status-gateway-lifecycle.test.ts +++ b/test/cli/status-gateway-lifecycle.test.ts @@ -77,7 +77,7 @@ describe("CLI status gateway lifecycle process contracts", () => { fs.mkdirSync(localBin, { recursive: true }); writeSandboxRegistry(home, { model: "configured-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: true, }); fs.writeFileSync( @@ -97,7 +97,7 @@ describe("CLI status gateway lifecycle process contracts", () => { 'if [ "$1" = "inference" ] && [ "$2" = "get" ]; then', " echo 'Gateway inference:'", " echo", - " echo ' Provider: nvidia-prod'", + " echo ' Provider: custom-shared-provider'", " echo ' Model: live-model'", " exit 0", "fi", @@ -140,9 +140,9 @@ describe("CLI status gateway lifecycle process contracts", () => { expect(result.code).toBe(1); expect(result.out).toContain("Sandbox: alpha"); expect(result.out).toContain("Model: configured-model"); - expect(result.out).toContain("Provider: nvidia-prod"); + expect(result.out).toContain("Provider: custom-shared-provider"); expect(result.out).toContain( - "gateway inference route (nvidia-prod/live-model) differs from the recorded route for this sandbox (nvidia-prod/configured-model)", + "gateway inference route (custom-shared-provider/live-model) differs from the recorded route for this sandbox (custom-shared-provider/configured-model)", ); expect(result.out).toContain("Inference:"); expect(result.out).toContain("healthy"); diff --git a/test/credentials/rebuild-credential-preflight.test.ts b/test/credentials/rebuild-credential-preflight.test.ts index eb6eadae7c6..de97cae2f6a 100644 --- a/test/credentials/rebuild-credential-preflight.test.ts +++ b/test/credentials/rebuild-credential-preflight.test.ts @@ -51,6 +51,7 @@ function createFixture(opts: { providerRegistered = true, inferenceProbeHttpStatus = null, } = opts; + const observedProvider = provider; const sandboxName = "my-assistant"; const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-2273-")); tmpFixtures.push(tmpDir); @@ -221,11 +222,11 @@ if (a[0] === "provider" && a[1] === "get") { process.stderr.write("Error: provider '${provider}' not found\\n"); process.exit(1); } - process.stdout.write("Name: ${provider}\\nType: openai\\nCredential keys: ${credentialEnv}\\nConfig keys: OPENAI_BASE_URL\\n"); + process.stdout.write("Name: ${observedProvider}\\nType: openai\\nId: 11111111-2222-4333-8444-555555555555\\nResource version: 1\\nCredential keys: ${credentialEnv}\\nConfig keys: OPENAI_BASE_URL\\n"); process.exit(0); } if (a[0] === "provider" && a[1] === "list") { - process.stdout.write(${JSON.stringify(JSON.stringify(providerRegistered ? [{ name: provider, credential_keys: [credentialEnv], credential_expires_at_ms: { [credentialEnv]: opts.credentialExpiresAtMs } }] : []) + "\n")}); + process.stdout.write(${JSON.stringify(JSON.stringify(providerRegistered ? [{ name: observedProvider, credential_keys: [credentialEnv], credential_expires_at_ms: { [credentialEnv]: opts.credentialExpiresAtMs } }] : []) + "\n")}); process.exit(0); } if (a[0] === "provider") process.exit(0); diff --git a/test/e2e-runtime/nemoclaw-cli-recovery.test.ts b/test/e2e-runtime/nemoclaw-cli-recovery.test.ts index 306641a07fd..9fd33374714 100644 --- a/test/e2e-runtime/nemoclaw-cli-recovery.test.ts +++ b/test/e2e-runtime/nemoclaw-cli-recovery.test.ts @@ -34,14 +34,25 @@ describe("nemoclaw CLI runtime recovery", () => { "my-assistant": { name: "my-assistant", model: "nvidia/nemotron-3-super-120b-a12b", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, }), { mode: 0o600 }, ); - fs.writeFileSync(stateFile, JSON.stringify({ statusCalls: 0, sandboxGetCalls: 0 })); + // Recover the existing disconnected registration through the fallback CLI. + // A missing registration would require a real host gateway process. + fs.writeFileSync( + stateFile, + JSON.stringify({ + statusCalls: 0, + connected: false, + sandboxGetCalls: 0, + gatewaySelectCalls: 0, + gatewayStartCalls: 0, + }), + ); fs.writeFileSync( openshellPath, `#!${process.execPath} @@ -54,15 +65,23 @@ const state = JSON.parse(fs.readFileSync(statePath, "utf8")); if (args[0] === "status") { state.statusCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); - if (state.statusCalls === 1) { - process.stdout.write("Error: × No active gateway\\n"); + if (!state.connected) { + process.stdout.write("Gateway: nemoclaw\\nStatus: Disconnected\\n"); } else { process.stdout.write("Gateway: nemoclaw\\nStatus: Connected\\n"); } process.exit(0); } -if (args[0] === "gateway" && (args[1] === "start" || args[1] === "select")) { +if (args[0] === "gateway" && args[1] === "start") { + state.gatewayStartCalls += 1; + fs.writeFileSync(statePath, JSON.stringify(state)); + process.exit(1); +} + +if (args[0] === "gateway" && args[1] === "select") { + state.gatewaySelectCalls += 1; + state.connected = true; fs.writeFileSync(statePath, JSON.stringify(state)); process.exit(0); } @@ -76,6 +95,8 @@ if (args[0] === "sandbox" && args[1] === "get" && (args[2] === "my-assistant" || state.sandboxGetCalls += 1; fs.writeFileSync(statePath, JSON.stringify(state)); if (state.sandboxGetCalls === 1) { + state.connected = false; + fs.writeFileSync(statePath, JSON.stringify(state)); process.stdout.write("Error: × transport error\\n ╰─▶ Connection reset by peer (os error 104)\\n"); process.exit(1); } @@ -117,7 +138,10 @@ process.exit(0); ); assert.equal(result.status, 0, result.stderr); - assert.match(result.stdout, /Recovered NemoClaw gateway runtime via (start|select)/); + assert.match(result.stdout, /Recovered NemoClaw gateway runtime via select/); + const recoveredState = JSON.parse(fs.readFileSync(stateFile, "utf8")); + assert.ok(recoveredState.gatewaySelectCalls > 0); + assert.equal(recoveredState.gatewayStartCalls, 0); assert.match(result.stdout, /Phase: Ready/); }, ); diff --git a/test/e2e/README.md b/test/e2e/README.md index 8e85b6c8717..c125bf78c63 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1023,6 +1023,81 @@ completed onboarding session remains unchanged as historical onboarding evidence. Deterministic startup and action tests own the corresponding launch environment and session non-rewrite checks. +For explicit Slice 2 qualification, reuse this live owner with +`NEMOCLAW_SWITCH_PROVIDER` and a required `NEMOCLAW_SWITCH_MODEL` supported by that +provider. Use the canonical model ID returned by that vendor (a versioned ID +where supported): the existing raw/API checks require exact response-model +equality, so a rolling alias that returns a different model ID is unsuitable. +This manual selection does not change the scheduled catalogue's NVIDIA +or compatible-Anthropic scenarios. On an approved, disposable E2E host with a disposable gateway, supply the +selected credential through the existing environment/secret delivery boundary, +then invoke the existing runner (shown here for OpenAI; set the model separately): + +```bash +NEMOCLAW_SWITCH_PROVIDER=openai-api NEMOCLAW_RUN_LIVE_E2E=1 \ + npx tsx tools/e2e/live-vitest-invocation.mts run \ + --test-path test/e2e/live/hermes-inference-switch.test.ts +``` + +| Provider selection | Wire contract | Required environment credential | +| --- | --- | --- | +| `openai-api` | OpenAI chat completions, bearer key | `OPENAI_API_KEY` | +| `anthropic-prod` | Anthropic Messages, key and version header | `ANTHROPIC_API_KEY` | +| `gemini-api` | Existing OpenAI-compatible Gemini surface | `GEMINI_API_KEY` | +| `openrouter-api` | OpenAI-compatible with required Referer/Title headers | `OPENROUTER_API_KEY` | +| `hermes-provider` | OpenAI-compatible, manual Nous key registration | `NOUS_API_KEY` | + +These are application environment bindings, not approved GitHub repository secret +mappings. Credential provisioning and a supported account model remain external +prerequisites. Hermes Provider registers the manual Nous key once through +`credentials add`; only that command maps it into the profile's physical +`OPENAI_API_KEY` binding. The later switch consumes its owned registration. This scenario does not exercise OAuth acquisition. The unchanged OAuth device +flow and its native credential handoff retain their existing deterministic tests; +this migration does not introduce a separate live-login requirement. Do not run this owner against a personal or shared gateway: it pre-cleans and +tears down its sandbox and removes the named gateway registration. Sandbox +destroy only deletes sandbox-owned messaging/search providers; native inference +providers are shared gateway resources. Cleanup command success does not separately +prove deletion of each provider. After a failed registration/attachment, retain +and inspect the existing command artifacts and persisted ownership state before +reclaiming the disposable gateway; do not delete a provider by name alone. + +Fixed non-NVIDIA selections install against an authenticated local baseline fixture, +so an unrelated NVIDIA credential is unnecessary. The subsequent raw request, +Hermes API request, and Hermes CLI request still reach the selected real vendor; +a mock baseline is not evidence of vendor success. Select one scenario at a time +for each required protocol/credential shape; no provider-by-platform matrix or new +scheduled jobs are introduced. + +Trusted workflow qualification uses an explicitly selected target and a nonempty +`hosted_model` input. Select one of `hermes-fixed-bearer-inference-switch`, +`hermes-fixed-anthropic-inference-switch`, `hermes-fixed-openrouter-inference-switch`, +`openclaw-fixed-openai-inference-switch`, or +`openclaw-fixed-anthropic-inference-switch` through the existing E2E workflow's +`targets` input. Each selection runs on Docker and receives only its declared +provider credential. These targets are excluded from the default suite. The +trusted workflow revision must contain this selection and credential transport +before it can dispatch a candidate PR. Dispatch from `main`; arbitrary branch +dispatches are rejected, including an empty candidate checkout. PR selections +use the existing current-head/exact-base identity authorization. Before dispatch, +review the complete selected candidate diff: candidate test and CLI code can +read and use the selected provider key. This follows the existing manual PR E2E +trust contract, not a credential-isolated execution boundary. Record the candidate +and workflow SHAs and selected credential source; after failure inspect artifacts, +clean up retained resources, and rotate or revoke exposed credentials when necessary. +The workflow does not revoke provider keys. Approved credential provisioning and a canonical supported +model remain prerequisites. The existing manifest binds the candidate revision, +selected target, and switch artifacts to the workflow result. + +The existing `openclaw-inference-switch` owner also accepts `openai-api` and +`anthropic-prod` with an explicit `NEMOCLAW_SWITCH_MODEL`. These two selections +cover the native OpenAI-compatible and Anthropic Messages consumer paths. They +start from an authenticated local baseline, then supply only the selected +`OPENAI_API_KEY` or `ANTHROPIC_API_KEY` to the switch command. The existing +attachment, configuration, sandbox response, and gateway model-run checks prove +the native route. A native provider failure fails the target rather than skipping +qualification. Models must match the provider's response model ID. Local fixture +and support-test passes do not prove that either real provider succeeded. + ## Native plugin and package lifecycle Issue #11766 retired the dedicated `openclaw-plugin-runtime-exdev` workflow job diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index 608540e132e..5d9959cda99 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -1,15 +1,22 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { + resolveMaxTokensField, + resolveProbeReplyTokens, +} from "../../../src/lib/inference/max-tokens-field.ts"; +import { nativeInferenceProbeAuthScript } from "../../../src/lib/inference/probe/native-inference-probe-auth.ts"; import fs from "node:fs"; import http from "node:http"; import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; -import { resolveAgentInferenceApi } from "../../../src/lib/inference/config.ts"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; -import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts"; +import { + resolveAgentInferenceApi, + nativeHostedProfile, +} from "../../../src/lib/inference/config.ts"; +import { OPENROUTER_DEFAULT_HEADERS } from "../../../src/lib/inference/native-hosted/openrouter-headers.ts"; import { execTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; @@ -67,9 +74,36 @@ const USE_COMPATIBLE_HOSTED = process.env.NEMOCLAW_E2E_USE_HOSTED_INFERENCE === export const SWITCH_PROVIDER = process.env.NEMOCLAW_SWITCH_PROVIDER ?? PUBLIC_NVIDIA_SWITCH_PROVIDER; export const SWITCH_MODEL = process.env.NEMOCLAW_SWITCH_MODEL ?? PUBLIC_NVIDIA_SWITCH_MODEL; +// Explicit manual qualification reuses this owner; it does not add scheduled targets. +export function fixedHostedSwitchScenario(runtimeEnv: NodeJS.ProcessEnv = process.env) { + const provider = runtimeEnv.NEMOCLAW_SWITCH_PROVIDER; + if ( + !provider || + !["openai-api", "anthropic-prod", "gemini-api", "openrouter-api", "hermes-provider"].includes( + provider, + ) + ) + return null; + const model = runtimeEnv.NEMOCLAW_SWITCH_MODEL?.trim(); + if (!model) + throw new Error( + "Fixed hosted qualification requires NEMOCLAW_SWITCH_MODEL for the selected provider", + ); + const profile = nativeHostedProfile(provider)!; + return { + provider, + model, + credentialEnv: provider === "hermes-provider" ? "NOUS_API_KEY" : profile.credentialEnv, + protocol: provider === "anthropic-prod" ? "anthropic-messages" : "openai-completions", + manualRegistration: provider === "hermes-provider", + }; +} + export const SWITCH_API = process.env.NEMOCLAW_SWITCH_INFERENCE_API ?? "openai-completions"; export const RUNTIME_SWITCH_API = - resolveAgentInferenceApi("hermes", SWITCH_PROVIDER, SWITCH_API) ?? SWITCH_API; + SWITCH_PROVIDER === "anthropic-prod" + ? "anthropic-messages" + : (resolveAgentInferenceApi("hermes", SWITCH_PROVIDER, SWITCH_API) ?? SWITCH_API); const SWITCH_MOCK_PORT = Number.parseInt(process.env.NEMOCLAW_SWITCH_MOCK_PORT ?? "0", 10); const INSTALL_ATTEMPTS = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true" ? 3 : 1; export const PROXY_RESOLUTION_PROVIDER = "hermes-proxy-resolution-e2e"; @@ -232,7 +266,11 @@ export async function prepareProxyResolutionRoute({ }): Promise<{ model: string; requestOffset: number }> { const endpoint = mockBaseline?.baseUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL; - const model = mockBaseline ? PROXY_RESOLUTION_MODEL : SWITCH_MODEL; + const model = mockBaseline + ? PROXY_RESOLUTION_MODEL + : nativeHostedProfile(SWITCH_PROVIDER) && SWITCH_PROVIDER !== PUBLIC_NVIDIA_SWITCH_PROVIDER + ? hostedInstallModel() + : SWITCH_MODEL; const requestOffset = mockBaseline?.requests().length ?? 0; const registered = await host.command( @@ -304,7 +342,10 @@ export function parseHermesModelBlock(text: string): Record { return model; } -export function parseInferenceRoute(text: string): { provider: string; model: string } { +export function parseInferenceRoute(text: string): { + provider: string; + model: string; +} { const plain = stripAnsi(text); const provider = plain.match(/^\s*Provider:\s*(.*?)\s*$/mu)?.[1]?.trim() ?? ""; const model = plain.match(/^\s*Model:\s*(.*?)\s*$/mu)?.[1]?.trim() ?? ""; @@ -398,7 +439,10 @@ export async function runHermesPongWithRetry( return { outcome: "failed", failureClass: "deterministic" }; } if (value.passed) return { outcome: "passed" }; - return { outcome: "failed", failureClass: hermesProbeFailureClass(value.result) }; + return { + outcome: "failed", + failureClass: hermesProbeFailureClass(value.result), + }; }, }); if (execution.value) return execution.value.result; @@ -500,7 +544,10 @@ async function startMockAnthropicProvider(): Promise { - const payload = JSON.parse(raw || "{}") as { model?: unknown; stream?: unknown }; + const payload = JSON.parse(raw || "{}") as { + model?: unknown; + stream?: unknown; + }; const model = typeof payload.model === "string" ? payload.model : "mock-anthropic-model"; if (isOpenAiChatCompletions) { if (payload.stream === true) { @@ -534,7 +581,11 @@ async function startMockAnthropicProvider(): Promise Promise; - publicNvidiaApiKey?: string | null; + nativeProviderApiKey?: string | null; } = {}, ): Promise { const args = [ @@ -677,6 +739,37 @@ export async function runHermesInferenceSetWithRetry( ...compatibleMetadataArgs, ]; const evidenceArtifacts = options.artifacts; + const nativeProfile = nativeHostedProfile(SWITCH_PROVIDER); + const nativeCredential = options.nativeProviderApiKey; + const switchRedactionValues = [ + ...new Set([...redactionValues, ...(nativeCredential ? [nativeCredential] : [])]), + ]; + // Hermes Provider switching consumes an owned registration. Its logical manual + // key is NOUS_API_KEY; only this command receives the profile's physical binding. + if (SWITCH_PROVIDER === "hermes-provider") { + if (!nativeCredential) throw new Error("Hermes Provider qualification requires NOUS_API_KEY"); + const registered = await host.command( + "node", + [ + CLI, + "credentials", + "add", + "hermes-provider", + "--type", + "openai", + "--credential", + "OPENAI_API_KEY", + ], + { + artifactName: "hermes-provider-manual-registration", + env: env(undefined, { OPENAI_API_KEY: nativeCredential }), + redactionValues: switchRedactionValues, + timeoutMs: 180_000, + }, + ); + // An ambiguous registration must not be blindly repeated by switch retries. + if (registered.exitCode !== 0) return registered; + } return runInferenceSetWithRetry({ attempts: options.attempts ?? inferenceSetAttemptCount(process.env.NEMOCLAW_SWITCH_SET_ATTEMPTS), @@ -689,11 +782,11 @@ export async function runHermesInferenceSetWithRetry( artifactName: `hermes-inference-set-${attempt}`, env: env(undefined, { ...compatibleAnthropicSwitchEnv(options.compatibleBinding ?? null), - ...(options.publicNvidiaApiKey - ? { NVIDIA_INFERENCE_API_KEY: options.publicNvidiaApiKey } + ...(nativeCredential && nativeProfile && SWITCH_PROVIDER !== "hermes-provider" + ? { [nativeProfile.credentialEnv]: nativeCredential } : {}), }), - redactionValues, + redactionValues: switchRedactionValues, timeoutMs: 180_000, }), }); @@ -733,13 +826,27 @@ export function maybeAssertPidStable( beforePid && afterPid && assertStable(afterPid, beforePid); } -export function expectedBaseUrl(): string { - if (SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER) return NVIDIA_HOSTED_NATIVE_ENDPOINT; +export function expectedBaseUrl(provider = SWITCH_PROVIDER): string { + const profile = nativeHostedProfile(provider); + if (profile) return profile.endpoint; return RUNTIME_SWITCH_API === "anthropic-messages" ? "https://inference.local" : "https://inference.local/v1"; } +export function sandboxInferencePayload( + model = SWITCH_MODEL, + provider = SWITCH_PROVIDER, + api = RUNTIME_SWITCH_API, +): string { + const field = api === "anthropic-messages" ? "max_tokens" : resolveMaxTokensField(model); + return JSON.stringify({ + model, + messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], + [field]: Math.max(inferenceLocalMaxTokens(api), resolveProbeReplyTokens(provider)), + }); +} + export function inferenceLocalMaxTokens(api: string = RUNTIME_SWITCH_API): number { return api === "anthropic-messages" ? 32 : 100; } @@ -755,8 +862,13 @@ export function expectedApiMode(): string | undefined { // POSIX ERE character classes; support tests pin the accepted scalar shapes. export const API_KEY_SHAPE_PATTERN = `^[[:space:]]*api_key:[[:space:]]*("sk-[^"[:space:]]+"|'sk-[^'[:space:]]+'|sk-[^"'[:space:]]+)[[:space:]]*$`; -export function apiKeyShapeCommand(): string[] { - return ["grep", "-Eq", API_KEY_SHAPE_PATTERN, "/sandbox/.hermes/config.yaml"]; +export function apiKeyShapeCommand(provider = SWITCH_PROVIDER): string[] { + const profile = nativeHostedProfile(provider); + const reference = profile ? `\\$\\{${profile.credentialEnv}\\}` : null; + const pattern = reference + ? `^[[:space:]]*api_key:[[:space:]]*("${reference}"|'${reference}'|${reference})[[:space:]]*$` + : API_KEY_SHAPE_PATTERN; + return ["grep", "-Eq", pattern, "/sandbox/.hermes/config.yaml"]; } export async function apiKeyShape(sandbox: SandboxClient): Promise { @@ -775,7 +887,11 @@ export async function hashCheck( return await sandbox.execShell( SANDBOX_NAME, trustedSandboxShellScript(`sha256sum -c ${file} --status && echo OK`), - { artifactName: `hermes-${artifact}-hash-check`, env: env(), timeoutMs: 30_000 }, + { + artifactName: `hermes-${artifact}-hash-check`, + env: env(), + timeoutMs: 30_000, + }, ); } @@ -797,7 +913,10 @@ export function maybeAssertEnvHashStable( beforeHash && assertStable(afterHash, beforeHash); } -export function registryState(): { registry: Record; session: Record } { +export function registryState(): { + registry: Record; + session: Record; +} { return { registry: JSON.parse( fs.readFileSync(path.join(os.homedir(), ".nemoclaw", "sandboxes.json"), "utf8"), @@ -812,12 +931,18 @@ function quotePayload(payload: string): string { return payload.replace(/'/gu, `'\\''`); } -export function sandboxInferenceCommand(payload: string): string { - if (SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER) { - // The upstream URL is the managed route for an attached OpenShell - // provider. OpenShell authorizes this profile-scoped request and replaces - // the placeholder without exposing the provider credential to the sandbox. - return `${NATIVE_NVIDIA_AUTH_HEADER_SCRIPT}; curl -sS --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H "$AUTH_HEADER" -d '${quotePayload(payload)}'`; +export function sandboxInferenceCommand(payload: string, provider = SWITCH_PROVIDER): string { + const profile = nativeHostedProfile(provider); + if (profile) { + const anthropic = provider === "anthropic-prod"; + const endpoint = `${profile.endpoint}${anthropic ? "/v1/messages" : "/chat/completions"}`; + const auth = nativeInferenceProbeAuthScript(profile.credentialEnv, anthropic).join("; "); + const attributionHeaders = + provider === "openrouter-api" + ? OPENROUTER_DEFAULT_HEADERS.map(([name, value]) => ` -H '${name}: ${value}'`).join("") + : ""; + const versionHeader = anthropic ? " -H 'anthropic-version: 2023-06-01'" : ""; + return `${auth}; curl -sS --max-time 90 ${endpoint} -H 'Content-Type: application/json' -H "$AUTH_HEADER"${versionHeader}${attributionHeaders} -d '${quotePayload(payload)}'`; } return RUNTIME_SWITCH_API === "anthropic-messages" ? `curl -sS --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '${quotePayload(payload)}'` diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index c017315f0ad..f9582808357 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { testTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText } from "../fixtures/clients/index.ts"; @@ -28,11 +29,12 @@ import { hermesGatewayPid, hostedInstallModel, sandboxInferenceCommand, - inferenceLocalMaxTokens, + sandboxInferencePayload, installHermes, maybeAssertEnvHashStable, maybeAssertPidStable, mockAnthropicSwitchEnabled, + fixedHostedSwitchScenario, PROXY_FORBIDDEN_MARKERS, PROXY_RESOLUTION_PROVIDER, parseHermesModelBlock, @@ -51,9 +53,9 @@ import { strictHashPerms, } from "./hermes-inference-switch-helpers.ts"; import { - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, + expectedNativeSwitchAttachmentEvidence, PUBLIC_NVIDIA_SWITCH_PROVIDER, - readPublicNvidiaSwitchAttachmentEvidence, + readNativeSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; @@ -84,6 +86,7 @@ test( }, }, async ({ artifacts, cleanup, host, progress, runtimeProvider, sandbox, secrets }) => { + const fixedScenario = fixedHostedSwitchScenario(); await artifacts.target.declare({ id: "hermes-inference-switch", boundary: @@ -122,18 +125,19 @@ test( // OpenShell reaches this fixture from its gateway network namespace, where // the runner's loopback address is not routable. - const mockBaseline = mockAnthropicSwitchEnabled() - ? await startFakeOpenAiCompatibleServer({ - apiKey: MOCK_BASELINE_API_KEY, - chatContent: "PONG", - forbiddenMarkers: PROXY_FORBIDDEN_MARKERS, - host: "0.0.0.0", - model: MOCK_BASELINE_MODEL, - publicHost: "host.openshell.internal", - progress, - requireAuth: true, - }) - : undefined; + const mockBaseline = + fixedScenario || mockAnthropicSwitchEnabled() + ? await startFakeOpenAiCompatibleServer({ + apiKey: MOCK_BASELINE_API_KEY, + chatContent: "PONG", + forbiddenMarkers: PROXY_FORBIDDEN_MARKERS, + host: "0.0.0.0", + model: MOCK_BASELINE_MODEL, + publicHost: "host.openshell.internal", + progress, + requireAuth: true, + }) + : undefined; cleanup.trackDisposable("close Hermes inference switch baseline fixture", async () => { await artifacts.writeJson( "baseline-openai-compatible-requests.json", @@ -145,10 +149,15 @@ test( SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) : null; + const nativeProfile = nativeHostedProfile(SWITCH_PROVIDER); + const nativeProviderApiKey = nativeProfile + ? (publicApiKey ?? + secrets.required(fixedScenario?.credentialEnv ?? nativeProfile.credentialEnv)) + : null; const apiKey = mockBaseline ? MOCK_BASELINE_API_KEY : (publicApiKey ?? secrets.required("NVIDIA_INFERENCE_API_KEY")); - const redactionValues = [apiKey, publicApiKey].filter( + const redactionValues = [apiKey, publicApiKey, nativeProviderApiKey].filter( (value): value is string => typeof value === "string", ); const installEnv: NodeJS.ProcessEnv = { @@ -203,12 +212,10 @@ test( { artifacts, compatibleBinding: switchBinding, - publicNvidiaApiKey: publicApiKey, + nativeProviderApiKey, }, ); expect(switched.exitCode, resultText(switched)).toBe(0); - expect(resultText(switched)).not.toContain("writing the in-sandbox config failed"); - expect(resultText(switched)).toContain(`Inference route synced for '${SANDBOX_NAME}'`); switchBinding && (await expectOpenAiProvider( host, @@ -306,11 +313,11 @@ test( ); const state = registryState(); - const attachmentEvidence = await readPublicNvidiaSwitchAttachmentEvidence({ - artifactName: "hermes-native-nvidia-provider-attachment", + const attachmentEvidence = await readNativeSwitchAttachmentEvidence({ + artifactName: "hermes-native-provider-attachment", env: env(), logicalProvider: SWITCH_PROVIDER, - receipt: state.registry.sandboxes?.[SANDBOX_NAME]?.nativeNvidiaProviderAttachment, + receipt: state.registry.sandboxes?.[SANDBOX_NAME]?.nativeHostedProviderAttachment, sandbox, sandboxName: SANDBOX_NAME, }); @@ -326,9 +333,7 @@ test( ).toBe( [ "hermes", - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE - : null, + expectedNativeSwitchAttachmentEvidence(SWITCH_PROVIDER), SWITCH_MODEL, SWITCH_PROVIDER, ] @@ -336,13 +341,13 @@ test( .join("\n"), ); expect(state.session).toEqual(baselineSession); - const publicSwitch = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER; - const durableEndpointUrl = publicSwitch + const nativeSwitch = Boolean(nativeHostedProfile(SWITCH_PROVIDER)); + const durableEndpointUrl = nativeSwitch ? null : (switchEndpointUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL); - const durableCredentialEnv = publicSwitch + const durableCredentialEnv = nativeSwitch ? null : switchEndpointUrl ? "COMPATIBLE_ANTHROPIC_API_KEY" @@ -352,15 +357,15 @@ test( ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.credentialEnv).toBe(durableCredentialEnv); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.preferredInferenceApi).toBe( - publicSwitch ? null : RUNTIME_SWITCH_API, + SWITCH_PROVIDER === "anthropic-prod" + ? "anthropic-messages" + : nativeSwitch + ? null + : RUNTIME_SWITCH_API, ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.nimContainer).toBeNull(); progress.phase("exercise sandbox inference and Hermes API"); - const inferenceLocalPayload = JSON.stringify({ - model: SWITCH_MODEL, - messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], - max_tokens: inferenceLocalMaxTokens(), - }); + const inferenceLocalPayload = sandboxInferencePayload(); const inferenceLocal = await runHermesPongWithRetry({ expectedModel: SWITCH_MODEL, onEvidence: async (evidence) => { diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index c6b8f3f4a69..f44a7a66e0e 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -4,6 +4,9 @@ // Fixture and response helpers shared by the openclaw-inference-switch live // target and fast e2e-support tests without gating on NEMOCLAW_RUN_LIVE_E2E=1. +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; +import { nativeInferenceProbeAuthScript } from "../../../src/lib/inference/probe/native-inference-probe-auth.ts"; + import type { RetryFailureClass } from "../../../tools/e2e/retry-evidence.mts"; import { startFakeOpenAiCompatibleServer, @@ -188,3 +191,38 @@ export function mockBaselineInference(endpointUrl: string): BaselineInferenceCon }, }; } + +/** Fixed-provider proofs reuse the live switch owner with an explicit model. */ +export function fixedOpenClawSwitchScenario(env: NodeJS.ProcessEnv) { + const provider = env.NEMOCLAW_SWITCH_PROVIDER; + if (provider !== "openai-api" && provider !== "anthropic-prod") return null; + const model = env.NEMOCLAW_SWITCH_MODEL?.trim(); + if (!model) throw new Error("Fixed hosted qualification requires NEMOCLAW_SWITCH_MODEL"); + const profile = nativeHostedProfile(provider)!; + const inferenceApi = provider === "anthropic-prod" ? "anthropic-messages" : "openai-completions"; + if (env.NEMOCLAW_SWITCH_INFERENCE_API && env.NEMOCLAW_SWITCH_INFERENCE_API !== inferenceApi) + throw new Error("Fixed hosted qualification protocol does not match the selected provider"); + return { provider, model, inferenceApi, credentialEnv: profile.credentialEnv }; +} + +export function openClawSwitchRoute(provider: string | null, inferenceApi: string) { + const profile = nativeHostedProfile(provider); + return { + baseUrl: + profile?.endpoint ?? + (inferenceApi === "anthropic-messages" + ? "https://inference.local" + : "https://inference.local/v1"), + apiKey: profile ? `\${${profile.credentialEnv}}` : "unused", + }; +} + +export function openClawSwitchCurlCommand(provider: string, inferenceApi: string): string { + const profile = nativeHostedProfile(provider); + const endpoint = openClawSwitchRoute(provider, inferenceApi).baseUrl; + const anthropic = inferenceApi === "anthropic-messages"; + const auth = profile + ? nativeInferenceProbeAuthScript(profile.credentialEnv, anthropic).join("; ") + : ""; + return `${auth ? `${auth}; ` : ""}curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 ${endpoint}${anthropic ? "/v1/messages" : "/chat/completions"} -H 'Content-Type: application/json'${profile ? ' -H "$AUTH_HEADER"' : ""}${anthropic ? " -H 'anthropic-version: 2023-06-01'" : ""} --data-binary @/tmp/nemoclaw-switch-payload.json`; +} diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 055ad7f9cbe..d758053d894 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -16,8 +16,8 @@ import type { AddressInfo } from "node:net"; import os from "node:os"; import path from "node:path"; -import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; -import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts"; +import { resolveMaxTokensField } from "../../../src/lib/inference/max-tokens-field.ts"; +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; @@ -51,6 +51,9 @@ import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; import { runBoundedRetry } from "../../../tools/e2e/retry-evidence.mts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { + fixedOpenClawSwitchScenario, + openClawSwitchRoute, + openClawSwitchCurlCommand, agentReplyContainsToken, anthropicToolCount, classifyExhaustedPostSwitchEvidence, @@ -62,17 +65,22 @@ import { startMockOpenClawBaselineProvider, } from "./openclaw-inference-switch-helpers.ts"; import { - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, - readPublicNvidiaSwitchAttachmentEvidence, + readNativeSwitchAttachmentEvidence, + expectedNativeSwitchAttachmentEvidence, requirePublicNvidiaSwitchKey, } from "./public-nvidia-switch-provider.ts"; const SANDBOX_NAME = process.env.NEMOCLAW_SANDBOX_NAME ?? "e2e-oc-inf-switch"; const SWITCH_PROVIDER = process.env.NEMOCLAW_SWITCH_PROVIDER ?? PUBLIC_NVIDIA_SWITCH_PROVIDER; -const SWITCH_MODEL = process.env.NEMOCLAW_SWITCH_MODEL ?? PUBLIC_NVIDIA_SWITCH_MODEL; -const SWITCH_INFERENCE_API = process.env.NEMOCLAW_SWITCH_INFERENCE_API ?? "openai-completions"; +const FIXED_HOSTED_SWITCH = fixedOpenClawSwitchScenario(process.env); +const SWITCH_MODEL = + FIXED_HOSTED_SWITCH?.model ?? process.env.NEMOCLAW_SWITCH_MODEL ?? PUBLIC_NVIDIA_SWITCH_MODEL; +const SWITCH_INFERENCE_API = + process.env.NEMOCLAW_SWITCH_INFERENCE_API ?? + (SWITCH_PROVIDER === "anthropic-prod" ? "anthropic-messages" : "openai-completions"); +const SWITCH_PROFILE = nativeHostedProfile(SWITCH_PROVIDER); const SWITCH_MOCK_ANTHROPIC = process.env.NEMOCLAW_SWITCH_MOCK_ANTHROPIC ?? "0"; const SWITCH_MOCK_PORT = parsePortEnv("NEMOCLAW_SWITCH_MOCK_PORT", 0); const TEST_TIMEOUT_MS = testTimeout(75 * 60_000); @@ -136,7 +144,7 @@ interface SandboxRegistry { credentialEnv?: unknown; preferredInferenceApi?: unknown; nimContainer?: unknown; - nativeNvidiaProviderAttachment?: unknown; + nativeHostedProviderAttachment?: unknown; } >; } @@ -566,7 +574,9 @@ async function assertRegistryAndSession( default: expect(sandbox?.endpointUrl).toBeNull(); expect(sandbox?.credentialEnv).toBe(sandbox?.provider === SWITCH_PROVIDER ? null : undefined); - expect(sandbox?.preferredInferenceApi).toBeNull(); + expect(sandbox?.preferredInferenceApi).toBe( + SWITCH_PROVIDER === "anthropic-prod" ? "anthropic-messages" : null, + ); } const sessionPath = path.join(home, ".nemoclaw", "onboard-session.json"); @@ -583,27 +593,29 @@ async function assertRegistryAndSession( case "compatible-anthropic-endpoint": expect(session.preferredInferenceApi).toBe("anthropic-messages"); break; + case "openai-api": + case "anthropic-prod": case PUBLIC_NVIDIA_SWITCH_PROVIDER: expect( [ session.endpointUrl, session.credentialEnv, session.preferredInferenceApi, - await readPublicNvidiaSwitchAttachmentEvidence({ - artifactName: "native-nvidia-provider-attachment-after-switch", + await readNativeSwitchAttachmentEvidence({ + artifactName: "native-provider-attachment-after-switch", env: commandEnv(home), logicalProvider: SWITCH_PROVIDER, - receipt: sandbox?.nativeNvidiaProviderAttachment, + receipt: sandbox?.nativeHostedProviderAttachment, sandbox: options.sandbox, sandboxName: SANDBOX_NAME, }), ].join("\n"), ).toBe( [ - NVIDIA_HOSTED_NATIVE_ENDPOINT, - "NVIDIA_INFERENCE_API_KEY", - "openai-completions", - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, + SWITCH_PROFILE?.endpoint, + SWITCH_PROFILE?.credentialEnv, + SWITCH_INFERENCE_API, + expectedNativeSwitchAttachmentEvidence(SWITCH_PROVIDER), ].join("\n"), ); break; @@ -617,6 +629,7 @@ async function readAndAssertOpenClawConfig( model: string; inferenceApi: string; artifactName: string; + baseline?: boolean; }, ): Promise { const configResult = await sandbox.exec( @@ -637,14 +650,12 @@ async function readAndAssertOpenClawConfig( const selectedModel = provider?.models?.find((entry) => entry.id === expected.model); expect(config.agents?.defaults?.model?.primary).toBe(expectedPrimary); - expect(provider?.baseUrl).toBe( - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : expected.inferenceApi === "anthropic-messages" - ? "https://inference.local" - : "https://inference.local/v1", + const route = openClawSwitchRoute( + expected.baseline && FIXED_HOSTED_SWITCH ? null : SWITCH_PROVIDER, + expected.inferenceApi, ); - expect(provider?.apiKey).toBe("unused"); + expect(provider?.baseUrl).toBe(route.baseUrl); + expect(provider?.apiKey).toBe(route.apiKey); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; @@ -672,7 +683,10 @@ async function assertInitialOpenClawConfig( artifactName: string; }, ): Promise { - const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); + const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, { + ...expected, + baseline: true, + }); expect(selectedModel?.contextWindow).toBeUndefined(); expect(selectedModel?.maxTokens).toBeUndefined(); } @@ -734,20 +748,12 @@ async function checkSandboxInference( : { model: SWITCH_MODEL, messages: [{ role: "user", content: "Reply with exactly one word: PONG" }], - max_tokens: 100, + [resolveMaxTokensField(SWITCH_MODEL)]: 100, }; const payloadB64 = Buffer.from(JSON.stringify(payload), "utf8").toString("base64"); - const curlCommand = - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H "$AUTH_HEADER" --data-binary @/tmp/nemoclaw-switch-payload.json` - : SWITCH_INFERENCE_API === "anthropic-messages" - ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' --data-binary @/tmp/nemoclaw-switch-payload.json` - : `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data-binary @/tmp/nemoclaw-switch-payload.json`; + const curlCommand = openClawSwitchCurlCommand(SWITCH_PROVIDER, SWITCH_INFERENCE_API); const script = [ "set -u", - ...(SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? [NATIVE_NVIDIA_AUTH_HEADER_SCRIPT] - : []), "tmp=$(mktemp)", `printf '%s' ${shellQuote(payloadB64)} | base64 -d >/tmp/nemoclaw-switch-payload.json`, "set +e", @@ -827,7 +833,7 @@ async function checkSandboxInference( const lastFailure = execution.value?.lastFailure ?? "probe failed without a result"; if (execution.evidence.outcome === "exhausted") { const exhausted = classifyExhaustedPostSwitchEvidence({ - required: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, + required: Boolean(SWITCH_PROFILE), lastFailure, }); return exhausted.outcome === "failed" @@ -1040,7 +1046,7 @@ async function runOpenClawInferenceSetWithRetry( home: string, redactionValues: string[], switchBinding: CompatibleAnthropicSwitchBinding | null, - publicNvidiaApiKey: string | null, + nativeApiKey: string | null, artifacts: { writeJson(path: string, value: unknown): Promise }, ): Promise { const attempts = inferenceSetAttemptCount(process.env.NEMOCLAW_SWITCH_SET_ATTEMPTS); @@ -1084,7 +1090,9 @@ async function runOpenClawInferenceSetWithRetry( artifactName: `nemoclaw-inference-set-${attempt}`, env: { ...compatibleAnthropicSwitchEnv(switchBinding), - ...(publicNvidiaApiKey ? { NVIDIA_INFERENCE_API_KEY: publicNvidiaApiKey } : {}), + ...(nativeApiKey && SWITCH_PROFILE + ? { [SWITCH_PROFILE.credentialEnv]: nativeApiKey } + : {}), }, redactionValues, timeoutMs: COMMAND_TIMEOUT_MS, @@ -1149,7 +1157,8 @@ test( }); const useMockBaseline = - SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"; + FIXED_HOSTED_SWITCH || + (SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"); // OpenShell reaches this fixture from its gateway network namespace, where // the runner's loopback address is not routable. const baselineProvider: FakeOpenAiCompatibleServer | undefined = useMockBaseline @@ -1159,13 +1168,16 @@ test( SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) : null; + const nativeApiKey = SWITCH_PROFILE + ? (publicApiKey ?? secrets.required(SWITCH_PROFILE.credentialEnv)) + : null; const baseline = baselineProvider ? mockBaselineInference(baselineProvider.baseUrl) : requireHostedInferenceConfig({ required: (name) => publicApiKey ?? secrets.required(name), }); const apiKey = baseline.apiKey; - const redactionValues = [apiKey, publicApiKey].filter( + const redactionValues = [apiKey, publicApiKey, nativeApiKey].filter( (value): value is string => typeof value === "string", ); @@ -1222,7 +1234,7 @@ test( const providerValidationUnavailable = onboard.exitCode !== 0 && isExternalProviderValidationFailure(onboardText); const unavailable = classifyUnavailableInitialProviderEvidence({ - required: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, + required: Boolean(SWITCH_PROFILE), detail: onboardText, }); if (providerValidationUnavailable && unavailable.outcome === "skipped") { @@ -1281,7 +1293,7 @@ test( redactionValues, false, ); - const apiFamilyChanges = SWITCH_MOCK_ANTHROPIC === "1"; + const apiFamilyChanges = SWITCH_MOCK_ANTHROPIC === "1" || SWITCH_PROVIDER === "anthropic-prod"; expect(SWITCH_INFERENCE_API).toBe( apiFamilyChanges ? "anthropic-messages" : "openai-completions", ); @@ -1291,7 +1303,7 @@ test( home, redactionValues, switchBinding, - publicApiKey, + nativeApiKey, artifacts, ); expect(switchResult.exitCode, resultText(switchResult)).toBe(0); diff --git a/test/e2e/live/podman-cpu-lifecycle-artifacts.ts b/test/e2e/live/podman-cpu-lifecycle-artifacts.ts index 6d26c3d3d44..cf4a7a5cc1d 100644 --- a/test/e2e/live/podman-cpu-lifecycle-artifacts.ts +++ b/test/e2e/live/podman-cpu-lifecycle-artifacts.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import type { ContainerEngine } from "../../../src/lib/adapters/container-engine.ts"; +import type { ArtifactSink } from "../fixtures/artifacts.ts"; import path from "node:path"; import { pathToFileURL } from "node:url"; @@ -126,3 +128,19 @@ if (invokedPath && import.meta.url === pathToFileURL(path.resolve(invokedPath)). process.exitCode = 1; }); } + +/** Retain failed pull diagnostics through the canonical artifact redaction boundary. */ +export function writePodmanImagePullArtifact( + artifacts: ArtifactSink, + relativePath: string, + image: string, + result: ReturnType, +): Promise { + return artifacts.writeJson(relativePath, { + image, + status: result.status, + stdout: result.stdout, + stderr: result.stderr, + error: result.error?.message, + }); +} diff --git a/test/e2e/live/podman-portable-uninstall.test.ts b/test/e2e/live/podman-portable-uninstall.test.ts index b747b88f986..bf12b3d94a1 100644 --- a/test/e2e/live/podman-portable-uninstall.test.ts +++ b/test/e2e/live/podman-portable-uninstall.test.ts @@ -11,6 +11,7 @@ import { } from "../../../src/lib/adapters/podman"; import { portableDemoReceiptPath } from "../../../src/lib/onboard/experimental/portable-runtime-receipt-readiness"; import { expect, test } from "../fixtures/e2e-test.ts"; +import { writePodmanImagePullArtifact } from "./podman-cpu-lifecycle-artifacts.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; import { cleanupPodmanLifecycle, @@ -119,7 +120,7 @@ function writePortableUninstallSummary(artifactDir: string | undefined, uid: num test( "runs full portable uninstall before a clean socket restart and reinstall start (#9189)", { meta: { e2ePhases: E2E_PHASES }, timeout: 300_000 }, - async ({ progress, shellProbe }) => { + async ({ artifacts, progress, shellProbe }) => { progress.phase("pin the current-user Podman authority"); expect(process.platform).toBe("linux"); const uid = process.getuid?.() ?? -1; @@ -177,11 +178,21 @@ test( ); progress.phase("create receipt-owned and unrelated resources"); - expect( - [...imageWasPresent.keys()].every((image) => - Object.is(engine.capture(["pull", image]).status, 0), - ), - ).toBe(true); + const pullArtifacts: Array> = []; + const imagesPulled = [...imageWasPresent.keys()].every((image, index) => { + const pull = engine.capture(["pull", image]); + pullArtifacts.push( + writePodmanImagePullArtifact( + artifacts, + `podman-uninstall-image-pull-${index + 1}.json`, + image, + pull, + ), + ); + return pull.status === 0; + }); + await Promise.all(pullArtifacts); + expect(imagesPulled, "Pull fixture images; see image-pull artifacts").toBe(true); await runCommand(shellProbe, openshellBin, sandboxCreateArgs(), { artifactName: "podman-uninstall-create-sandbox", env: cliEnv, diff --git a/test/e2e/live/public-nvidia-switch-provider.ts b/test/e2e/live/public-nvidia-switch-provider.ts index c326df53df4..6a67ee769d0 100644 --- a/test/e2e/live/public-nvidia-switch-provider.ts +++ b/test/e2e/live/public-nvidia-switch-provider.ts @@ -1,12 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { - normalizeNativeNvidiaProviderAttachment, - NVIDIA_HOSTED_CREDENTIAL_ENV, - NVIDIA_HOSTED_NATIVE_PROFILE_ID, - NVIDIA_HOSTED_NATIVE_PROVIDER, -} from "../../../src/lib/inference/native-nvidia/index.ts"; +import { normalizeNativeHostedProviderAttachment } from "../../../src/lib/inference/native-hosted/contract.ts"; +import { nativeHostedProfile } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { parseCliOpenShellProviderMetadata } from "../../../src/lib/adapters/openshell/provider-metadata-cli.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; @@ -22,22 +18,40 @@ export function requirePublicNvidiaSwitchKey(value: string): string { return value; } -export async function readPublicNvidiaSwitchAttachmentEvidence(options: { +type AttachmentEvidenceOptions = { readonly artifactName: string; readonly env: NodeJS.ProcessEnv; readonly logicalProvider: string; readonly receipt: unknown; readonly sandbox: SandboxClient; readonly sandboxName: string; -}): Promise { +}; + +export async function readPublicNvidiaSwitchAttachmentEvidence( + options: AttachmentEvidenceOptions, +): Promise { if (options.logicalProvider !== PUBLIC_NVIDIA_SWITCH_PROVIDER) return null; - const receipt = normalizeNativeNvidiaProviderAttachment(options.receipt); + return readNativeSwitchAttachmentEvidence(options); +} + +export function expectedNativeSwitchAttachmentEvidence(provider: string): string | null { + const profile = nativeHostedProfile(provider); + if (!profile) return null; + return `provider-inspection=0;provider-name=match;provider-profile=match;provider-id=match;attachment-inspection=0;attached=true;schema=1;profile=${profile.profileId};provider=${profile.providerName}`; +} + +export async function readNativeSwitchAttachmentEvidence( + options: AttachmentEvidenceOptions, +): Promise { + const profile = nativeHostedProfile(options.logicalProvider); + if (!profile) return null; + const receipt = normalizeNativeHostedProviderAttachment(options.receipt); const providerRedactionValues = [ options.env.NVIDIA_API_KEY, - options.env[NVIDIA_HOSTED_CREDENTIAL_ENV], + options.env[profile.credentialEnv], ].filter((value): value is string => typeof value === "string" && value.length > 0); const provider = await options.sandbox.openshell( - ["provider", "get", "-g", "nemoclaw", NVIDIA_HOSTED_NATIVE_PROVIDER], + ["provider", "get", "-g", "nemoclaw", profile.providerName], { artifactName: `${options.artifactName}-provider-metadata`, captureLimitBytes: 16 * 1024, @@ -54,6 +68,7 @@ export async function readPublicNvidiaSwitchAttachmentEvidence(options: { { artifactName: options.artifactName, env: options.env, + redactionValues: providerRedactionValues, timeoutMs: 60_000, }, ); @@ -63,15 +78,15 @@ export async function readPublicNvidiaSwitchAttachmentEvidence(options: { `provider-profile=${ metadata?.type === receipt?.profileId && metadata?.credentialKeys.length === 1 && - metadata.credentialKeys[0] === NVIDIA_HOSTED_CREDENTIAL_ENV && + metadata.credentialKeys[0] === profile.credentialEnv && metadata.configKeys.length === 0 && - metadata.type === NVIDIA_HOSTED_NATIVE_PROFILE_ID + metadata.type === profile.profileId ? "match" : "mismatch" }`, `provider-id=${metadata?.revision?.id === receipt?.providerId ? "match" : "mismatch"}`, `attachment-inspection=${String(attachments.exitCode)}`, - `attached=${String(attachments.stdout.split(/\s+/u).includes(NVIDIA_HOSTED_NATIVE_PROVIDER))}`, + `attached=${String(attachments.stdout.split(/\s+/u).includes(profile.providerName))}`, `schema=${String(receipt?.schemaVersion ?? "missing")}`, `profile=${receipt?.profileId ?? "missing"}`, `provider=${receipt?.providerName ?? "missing"}`, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 00636d8d9a1..4219bda28c4 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -148,7 +148,9 @@ }, { "live": "test/e2e/live/podman-portable-uninstall.test.ts", + "liveSources": ["test/e2e/live/podman-cpu-lifecycle-artifacts.ts"], "fast": [ + "test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts", "src/lib/actions/uninstall/portable-runtime-cleanup.test.ts", "src/lib/actions/uninstall/run-plan-portable-runtime.test.ts", "src/lib/onboard/docker-driver-gateway-runtime.test.ts", @@ -779,6 +781,7 @@ "test/e2e/support/messaging-providers-installed-runtime-paths.test.ts", "test/e2e/support/messaging-providers-runtime-proofs.test.ts", "test/onboarding/onboard-messaging.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/runtime/messaging/messaging-build-applier.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts", @@ -863,6 +866,7 @@ "test/e2e/support/openclaw-discord-pairing-helpers.test.ts", "test/e2e/support/messaging-providers-runtime-proofs.test.ts", "test/onboarding/onboard-messaging.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", "test/e2e/support/e2e-clients.test.ts" ] diff --git a/test/e2e/support/fixed-hosted-qualification.test.ts b/test/e2e/support/fixed-hosted-qualification.test.ts new file mode 100644 index 00000000000..2a9b82a72b2 --- /dev/null +++ b/test/e2e/support/fixed-hosted-qualification.test.ts @@ -0,0 +1,279 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { runInNewContext } from "node:vm"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { readWorkflow, readYaml, type Workflow } from "../../helpers/e2e-workflow-contract"; +import { + FIXED_HOSTED_CREDENTIAL_PREDICATE, + validateStandardProfileWorkflowBoundary, +} from "../../../tools/e2e/standard-profile-workflow-boundary.mts"; +import { + FIXED_HOSTED_PLAN_SCRIPT, + FIXED_HOSTED_RUN_SCRIPT, + FIXED_HOSTED_QUALIFICATIONS, + validateFixedHostedSelection, +} from "../../../tools/e2e/fixed-hosted-qualification.mts"; +import { + buildE2eWorkflowPlan, + releaseRequiredWorkflowJobs, +} from "../../../tools/e2e/workflow-plan.mts"; +import { catalogueTargetsForChangedFiles } from "../../../tools/e2e/target-catalogue.mts"; + +const explicit = { + hostedModel: "approved/model", + eventName: "workflow_dispatch", +}; + +describe("fixed hosted qualification planning", () => { + it.each([ + ["", 0, true], + ["approved/model", 1, false], + ] as const)( + "rejects unrelated hosted model selections before native runtime planning [%s]", + (hostedModel, status, outputExists) => { + const workflow = readYaml(".github/workflows/e2e.yaml") as Workflow; + const script = workflow.jobs["generate-matrix"].steps?.find( + (step) => step.name === "Generate E2E target matrix", + )?.run; + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "native-runtime-plan-")); + try { + const output = path.join(directory, "output"); + const result = spawnSync("bash", ["-c", script!], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + JOBS: "native-runtime-qualification-producer", + TARGETS: "", + HOSTED_MODEL: hostedModel, + GITHUB_OUTPUT: output, + }, + }); + expect(result.status).toBe(status); + expect(fs.existsSync(output)).toBe(outputExists); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it.each(FIXED_HOSTED_QUALIFICATIONS)( + "selects only the requested protocol representative [$id]", + ({ id, agent }) => { + const plan = buildE2eWorkflowPlan({ targets: id }, explicit); + expect(plan.catalogueMatrices["fixed-hosted"]).toMatchObject([ + { id, agent_runtime: agent, runtime_provider: "docker" }, + ]); + expect(plan.catalogueMatrices["fixed-hosted"]).toHaveLength(1); + }, + ); + + it("keeps explicit qualification out of default, shared-change and release inventory", () => { + expect(buildE2eWorkflowPlan().catalogueMatrices["fixed-hosted"]).toEqual([]); + expect( + catalogueTargetsForChangedFiles(["tools/e2e/target-catalogue.mts"]).some( + (row) => row.profile === "fixed-hosted", + ), + ).toBe(false); + expect(releaseRequiredWorkflowJobs()).not.toContain("catalogue-fixed-hosted"); + expect( + buildE2eWorkflowPlan({ targets: "hermes-inference-switch" }).catalogueMatrices[ + "fixed-hosted" + ], + ).toEqual([]); + }); + + it("rejects missing models, automatic selection and mixed selections before planning work", () => { + const id = FIXED_HOSTED_QUALIFICATIONS[0].id; + expect(() => buildE2eWorkflowPlan({ targets: id })).toThrow(/manual/); + expect(() => buildE2eWorkflowPlan({ targets: id }, { eventName: "workflow_dispatch" })).toThrow( + /model/, + ); + expect(() => buildE2eWorkflowPlan({ targets: id }, { ...explicit, eventName: "push" })).toThrow( + /manual/, + ); + expect(() => + buildE2eWorkflowPlan({ targets: `${id},hermes-inference-switch` }, explicit), + ).toThrow(/one explicitly/); + expect(() => + buildE2eWorkflowPlan({ targets: id }, { ...explicit, gatewayRuntimes: ["podman"] }), + ).toThrow(/does not support/); + expect(() => validateFixedHostedSelection(["unknown"], "model", "workflow_dispatch")).toThrow( + /requires one/, + ); + expect(() => + buildE2eWorkflowPlan({ targets: id }, { ...explicit, hostedModel: "$(leak)" }), + ).toThrow(/model/); + }); + + it.each([ + ["direct main", "refs/heads/main", "", "false", "workflow_dispatch", true], + ["validated PR", "refs/heads/main", "candidate", "true", "workflow_dispatch", true], + ["arbitrary branch", "refs/heads/feature", "", "false", "workflow_dispatch", false], + [ + "branch with authorized PR", + "refs/heads/feature", + "candidate", + "true", + "workflow_dispatch", + false, + ], + ["unvalidated PR", "refs/heads/main", "candidate", "false", "workflow_dispatch", false], + ["automatic event", "refs/heads/main", "", "false", "push", false], + ])( + "guards fixed hosted credential delivery: %s", + (_label, ref, checkout, allowed, event, expected) => { + expect( + runInNewContext( + FIXED_HOSTED_CREDENTIAL_PREDICATE.replaceAll( + "needs.generate-matrix", + 'needs["generate-matrix"]', + ), + { + github: { repository: "NVIDIA/NemoClaw", ref, event_name: event }, + inputs: { checkout_sha: checkout }, + needs: { + "generate-matrix": { + outputs: { e2e_credentials_allowed: allowed }, + }, + }, + }, + ), + ).toBe(expected); + }, + ); + + it("rejects removing the fixed hosted trusted-main job gate", () => { + const workflow = readWorkflow(); + (workflow.jobs as Record)["catalogue-fixed-hosted"]!.if = + "${{ needs.generate-matrix.outputs.catalogue_fixed_hosted_matrix != '[]' }}"; + expect(validateStandardProfileWorkflowBoundary(workflow)).toContain( + "catalogue-fixed-hosted must use its generated catalogue matrix", + ); + }); + + it("rejects credential crossover in the trusted caller", () => { + const workflow = readWorkflow(); + (workflow.jobs as Record }>)[ + "catalogue-fixed-hosted" + ]!.secrets.HOSTED_PROVIDER_API_KEY = "${{ secrets.NVIDIA_API_KEY }}"; + expect(validateStandardProfileWorkflowBoundary(workflow)).toContain( + "catalogue-fixed-hosted must receive only its profile secrets", + ); + }); + + it("exports only the selected credential and removes the transport alias without logging values", () => { + const credential = "fake-selected-provider-key"; + const result = spawnSync( + "bash", + [ + "-c", + `set -euo pipefail +${FIXED_HOSTED_RUN_SCRIPT} +[[ "$OPENAI_API_KEY" == "fake-selected-provider-key" ]] +[[ -z "\${HOSTED_PROVIDER_API_KEY+x}" ]] +[[ -z "\${ANTHROPIC_API_KEY+x}" && -z "\${NOUS_API_KEY+x}" && -z "\${NVIDIA_API_KEY+x}" && -z "\${OPENROUTER_API_KEY+x}" ]] +[[ "$NEMOCLAW_SWITCH_MODEL" == "approved/model" ]] +`, + ], + { + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOSTED_CREDENTIAL_NAME: "OPENAI_API_KEY", + HOSTED_PROVIDER_API_KEY: credential, + HOSTED_MODEL: "approved/model", + }, + }, + ); + expect(result.status).toBe(0); + expect(result.stdout + result.stderr).not.toContain(credential); + const missing = spawnSync("bash", ["-c", `set -euo pipefail\n${FIXED_HOSTED_RUN_SCRIPT}`], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + HOSTED_CREDENTIAL_NAME: "OPENAI_API_KEY", + HOSTED_PROVIDER_API_KEY: "", + HOSTED_MODEL: "approved/model", + }, + }); + expect(missing.status).toBe(1); + expect(missing.stderr).toContain("Selected hosted provider credential is unavailable"); + }); + + it.each(FIXED_HOSTED_QUALIFICATIONS)( + "derives credentials before checkout without accepting candidate metadata [$id]", + (selection) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "fixed-hosted-plan-")); + try { + const output = path.join(directory, "outputs"); + const result = spawnSync( + "bash", + ["-c", `set -euo pipefail\nfail() { exit 17; }\n${FIXED_HOSTED_PLAN_SCRIPT}`], + { + encoding: "utf8", + env: { + PATH: process.env.PATH, + CATALOGUE_ID: selection.id, + TARGET_ID: `${selection.agent}-inference-switch`, + TEST_FILE: `test/e2e/live/${selection.agent}-inference-switch.test.ts`, + SHARD: selection.provider, + HOSTED_MODEL: "approved/model", + RUNTIME_PROVIDER: "docker", + GITHUB_OUTPUT: output, + HOSTED_CREDENTIAL_NAME: "ATTACKER_SECRET", + NEMOCLAW_SWITCH_PROVIDER: "attacker", + }, + }, + ); + expect(result.status).toBe(0); + expect(fs.readFileSync(output, "utf8")).toBe(`hosted_credential=${selection.credential}\n`); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it.each([ + { scenario: "target mismatch", override: { TARGET_ID: "hermes-e2e" } }, + { + scenario: "test file mismatch", + override: { TEST_FILE: "test/e2e/live/hermes-e2e.test.ts" }, + }, + { scenario: "shard mismatch", override: { SHARD: "nvidia-prod" } }, + { scenario: "missing model", override: { HOSTED_MODEL: "" } }, + { + scenario: "unsafe model", + override: { HOSTED_MODEL: "model\nATTACKER=value" }, + }, + { scenario: "unknown target", override: { CATALOGUE_ID: "unknown" } }, + ])("refuses invalid qualification metadata [$scenario]", ({ override }) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "fixed-hosted-denial-")); + try { + const result = spawnSync( + "bash", + ["-c", `set -euo pipefail\nfail() { exit 17; }\n${FIXED_HOSTED_PLAN_SCRIPT}`], + { + env: { + PATH: process.env.PATH, + CATALOGUE_ID: FIXED_HOSTED_QUALIFICATIONS[0].id, + TARGET_ID: "hermes-inference-switch", + TEST_FILE: "test/e2e/live/hermes-inference-switch.test.ts", + SHARD: "hermes-provider", + HOSTED_MODEL: "approved/model", + RUNTIME_PROVIDER: "docker", + GITHUB_OUTPUT: path.join(directory, "outputs"), + ...override, + }, + }, + ); + expect(result.status).toBe(17); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); +}); diff --git a/test/e2e/support/hermes-inference-switch-command-shape.test.ts b/test/e2e/support/hermes-inference-switch-command-shape.test.ts index 621a8ec39fb..04cb1bad062 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -5,7 +5,10 @@ import { spawnSync } from "node:child_process"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { resolveAgentInferenceApi } from "../../../src/lib/inference/config.ts"; +import { + resolveAgentInferenceApi, + nativeHostedProfile, +} from "../../../src/lib/inference/config.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { compatibleAnthropicSwitchBinding } from "../fixtures/compatible-anthropic-switch.ts"; @@ -14,6 +17,7 @@ import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { API_KEY_SHAPE_PATTERN, apiKeyShapeCommand, + expectedBaseUrl, cleanupHermesSwitch, compatibleAnthropicMetadataArgs, expectAuthenticatedBaselineInventoryRequest, @@ -41,6 +45,61 @@ import { } from "../live/public-nvidia-switch-provider.ts"; describe("Hermes inference switch command shape", () => { + it.each([ + ["openai-api", "https://api.openai.com/v1", "authorization: bearer", "/chat/completions"], + ["anthropic-prod", "https://api.anthropic.com", "x-api-key:", "/v1/messages"], + [ + "gemini-api", + "https://generativelanguage.googleapis.com/v1beta/openai", + "authorization: bearer", + "/chat/completions", + ], + [ + "openrouter-api", + "https://openrouter.ai/api/v1", + "authorization: bearer", + "/chat/completions", + ], + [ + "hermes-provider", + "https://inference-api.nousresearch.com/v1", + "authorization: bearer", + "/chat/completions", + ], + ])( + "uses native endpoint and issued credential authentication for %s probes", + (provider, endpoint, header, route) => { + expect(expectedBaseUrl(provider)).toBe(endpoint); + const command = sandboxInferenceCommand('{"model":"selected-model"}', provider); + expect(command).toContain(`${endpoint}${route}`); + expect(command.toLowerCase()).toContain(header); + expect(command).toContain('"$AUTH_HEADER"'); + expect(command).not.toContain("nemoclaw-openshell-provider"); + expect(command).not.toContain("inference.local"); + }, + ); + + it("includes the Anthropic protocol version", () => { + expect(sandboxInferenceCommand("{}", "anthropic-prod")).toContain( + "anthropic-version: 2023-06-01", + ); + }); + + it("preserves OpenRouter attribution headers", () => { + const command = sandboxInferenceCommand("{}", "openrouter-api"); + expect(command).toContain("-H 'HTTP-Referer: https://www.nvidia.com/nemoclaw/'"); + expect(command).toContain("-H 'X-OpenRouter-Title: NVIDIA NemoClaw'"); + }); + + it.each(["openai-api", "anthropic-prod", "gemini-api", "hermes-provider"])( + "omits OpenRouter attribution for %s", + (provider) => { + const command = sandboxInferenceCommand("{}", provider); + expect(command).not.toContain("HTTP-Referer:"); + expect(command).not.toContain("X-OpenRouter-Title:"); + }, + ); + afterEach(() => vi.unstubAllEnvs()); function matchesApiKeyShape(line: string): boolean { @@ -93,8 +152,8 @@ describe("Hermes inference switch command shape", () => { const command = sandboxInferenceCommand('{"model":"nvidia/test"}'); expect(command).toContain("https://integrate.api.nvidia.com/v1/chat/completions"); - expect(command).toContain('AUTH_HEADER="Authorization: Bearer ${NVIDIA_INFERENCE_API_KEY}"'); - expect(command).toContain(' -H "$AUTH_HEADER"'); + expect(command).toContain("NVIDIA_INFERENCE_API_KEY"); + expect(command).toContain('"$AUTH_HEADER"'); expect(command).not.toContain("nemoclaw-openshell-provider"); expect(command).not.toContain("inference.local"); }); @@ -156,12 +215,36 @@ describe("Hermes inference switch command shape", () => { }); it("uses direct single-line argv for the in-sandbox API-key probe", () => { - const command = apiKeyShapeCommand(); + const command = apiKeyShapeCommand("compatible-endpoint"); expect(command).toEqual(["grep", "-Eq", API_KEY_SHAPE_PATTERN, "/sandbox/.hermes/config.yaml"]); expect(command.every((argument) => !/[\r\n]/u.test(argument))).toBe(true); }); + it.each([ + "nvidia-prod", + "openai-api", + "anthropic-prod", + "gemini-api", + "openrouter-api", + "hermes-provider", + ])("accepts only the selected native credential reference for %s", (provider) => { + const pattern = apiKeyShapeCommand(provider)[2]!; + const credentialEnv = nativeHostedProfile(provider)!.credentialEnv; + const reference = "${" + credentialEnv + "}"; + const probe = (value: string) => + spawnSync("grep", ["-Eq", pattern], { + encoding: "utf8", + input: ` api_key: ${value}\n`, + }).status; + expect(probe(reference)).toBe(0); + expect(probe(`"${reference}"`)).toBe(0); + expect(probe(`'${reference}'`)).toBe(0); + expect(probe("sk-OPENSHELL-PROXY-REWRITE")).toBe(1); + expect(probe("${WRONG_API_KEY}")).toBe(1); + expect(probe(`${reference} trailing`)).toBe(1); + }); + it("accepts only complete sk-prefixed YAML scalars", () => { expect( [" api_key: sk-value", ' api_key: "sk-value"', " api_key: 'sk-value'"].every( @@ -199,7 +282,11 @@ describe("Hermes inference switch command shape", () => { stderr: "", stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n", }) - .mockResolvedValueOnce({ exitCode: 0, stderr: "", stdout: "route synced" }); + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "route synced", + }); await prepareProxyResolutionRoute({ apiKey: "hosted-key", @@ -310,7 +397,10 @@ describe("Hermes inference switch command shape", () => { }), ).toBe(false); expect( - mockAnthropicSwitchEnabled({ ...mockAnthropic, NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "0" }), + mockAnthropicSwitchEnabled({ + ...mockAnthropic, + NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "0", + }), ).toBe(false); expect(mockAnthropicSwitchEnabled({})).toBe(false); }); @@ -415,7 +505,11 @@ describe("Hermes inference switch command shape", () => { path: string; }> = []; const baseline = { requests: () => requests }; - const result = { exitCode: 0, stderr: "", stdout: "PONG\n" } as ShellProbeResult; + const result = { + exitCode: 0, + stderr: "", + stdout: "PONG\n", + } as ShellProbeResult; const authenticatedRequest = (model: string) => ({ auth: "ok", authorizationSent: true, @@ -462,7 +556,11 @@ describe("Hermes inference switch command shape", () => { failureClass: "transient-external", retryScheduled: true, }), - expect.objectContaining({ attempt: 2, outcome: "passed", retryScheduled: false }), + expect.objectContaining({ + attempt: 2, + outcome: "passed", + retryScheduled: false, + }), ], }), ); @@ -485,13 +583,22 @@ describe("Hermes inference switch command shape", () => { )( "does not accept or retry a CLI PONG with %s and %s", async (_routeState, message, accepted, failureClass) => { - const result = { exitCode: 0, stderr: message, stdout: "PONG\n" } as ShellProbeResult; + const result = { + exitCode: 0, + stderr: message, + stdout: "PONG\n", + } as ShellProbeResult; const run = vi.fn().mockResolvedValue(result); const delay = vi.fn().mockResolvedValue(undefined); const onEvidence = vi.fn().mockResolvedValue(undefined); await expect( - runHermesCliPongWithRetry({ accept: () => accepted, delay, onEvidence, run }), + runHermesCliPongWithRetry({ + accept: () => accepted, + delay, + onEvidence, + run, + }), ).resolves.toBe(result); expect(run).toHaveBeenCalledOnce(); expect(delay).not.toHaveBeenCalled(); @@ -644,7 +751,11 @@ describe("Hermes inference switch command shape", () => { stderr: "failed to verify inference endpoint: timeout", stdout: "", }) - .mockResolvedValueOnce({ exitCode: 0, stderr: "", stdout: "route synced" }); + .mockResolvedValueOnce({ + exitCode: 0, + stderr: "", + stdout: "route synced", + }); const writeJson = vi.fn().mockResolvedValue("inference-switch-retry-evidence.json"); await expect( @@ -665,20 +776,205 @@ describe("Hermes inference switch command shape", () => { it("passes the public NVIDIA credential only to the native provider switch", async () => { const command = vi.fn().mockResolvedValue({ exitCode: 0, stderr: "", stdout: "route synced" }); - await runHermesInferenceSetWithRetry( - { command } as unknown as HostCliClient, - ["nvapi-hosted-key"], - [], - { - attempts: 1, - publicNvidiaApiKey: "nvapi-hosted-key", - }, - ); + await runHermesInferenceSetWithRetry({ command } as unknown as HostCliClient, [], [], { + attempts: 1, + nativeProviderApiKey: "nvapi-hosted-key", + }); expect(command).toHaveBeenCalledOnce(); + expect(JSON.stringify(command.mock.calls[0]?.slice(0, 2))).not.toContain("nvapi-hosted-key"); expect(command.mock.calls[0]?.[2]).toMatchObject({ env: { NVIDIA_INFERENCE_API_KEY: "nvapi-hosted-key" }, redactionValues: ["nvapi-hosted-key"], }); }); }); + +describe("native provider switch credential isolation", () => { + it("selects native Anthropic Messages without a custom API override", async () => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "anthropic-prod"); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + expect(helpers.RUNTIME_SWITCH_API).toBe("anthropic-messages"); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); + }); + + it.each([ + ["openai-api", "OPENAI_API_KEY"], + ["anthropic-prod", "ANTHROPIC_API_KEY"], + ["gemini-api", "GEMINI_API_KEY"], + ["openrouter-api", "OPENROUTER_API_KEY"], + ])("passes only the selected credential binding for %s", async (provider, credentialEnv) => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", provider); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + const command = vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + const credential = "fixture-native-provider-credential"; + await helpers.runHermesInferenceSetWithRetry({ command } as unknown as HostCliClient, [], [], { + attempts: 1, + nativeProviderApiKey: credential, + }); + const [executable, args, options] = command.mock.calls[0]!; + expect(executable).toBe("node"); + expect(args).toContain(provider); + expect(args).not.toContain(credential); + expect(options.env[credentialEnv]).toBe(credential); + expect(Object.entries(options.env).filter(([, value]) => value === credential)).toEqual([ + [credentialEnv, credential], + ]); + expect(options.redactionValues).toContain(credential); + expect(command).toHaveBeenCalledOnce(); + + const proxyCommand = vi + .fn() + .mockResolvedValueOnce({ exitCode: 0, stdout: "created", stderr: "" }) + .mockResolvedValueOnce({ + exitCode: 0, + stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n", + stderr: "", + }) + .mockResolvedValueOnce({ + exitCode: 0, + stdout: "route synced", + stderr: "", + }); + const proxy = await helpers.prepareProxyResolutionRoute({ + apiKey: "fixture-baseline-key", + host: { command: proxyCommand } as unknown as HostCliClient, + mockBaseline: undefined, + redactionValues: [], + }); + expect(proxy.model).toBe(DEFAULT_HOSTED_INFERENCE_MODEL); + expect(proxyCommand.mock.calls[2]?.[1]).toEqual( + expect.arrayContaining(["--model", DEFAULT_HOSTED_INFERENCE_MODEL]), + ); + }); +}); + +describe("fixed hosted qualification selection", () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.resetModules(); + }); + + it.each([ + ["openai-api", "OPENAI_API_KEY", "openai-completions"], + ["anthropic-prod", "ANTHROPIC_API_KEY", "anthropic-messages"], + ["gemini-api", "GEMINI_API_KEY", "openai-completions"], + ["openrouter-api", "OPENROUTER_API_KEY", "openai-completions"], + ["hermes-provider", "NOUS_API_KEY", "openai-completions"], + ])( + "selects %s with an explicit vendor model and its logical credential", + async (provider, credentialEnv, protocol) => { + const { fixedHostedSwitchScenario } = + await import("../live/hermes-inference-switch-helpers.ts"); + expect(() => fixedHostedSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: provider })).toThrow( + "NEMOCLAW_SWITCH_MODEL", + ); + expect( + fixedHostedSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: provider, + NEMOCLAW_SWITCH_MODEL: "vendor-model", + }), + ).toEqual({ + provider, + model: "vendor-model", + credentialEnv, + protocol, + manualRegistration: provider === "hermes-provider", + }); + expect(fixedHostedSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod" })).toBeNull(); + expect( + fixedHostedSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", + }), + ).toBeNull(); + }, + ); + + it("registers the manual Hermes credential once before switching without a new key", async () => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "hermes-provider"); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + const command = vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + const credential = "manual-nous-fixture"; + await helpers.runHermesInferenceSetWithRetry({ command } as unknown as HostCliClient, [], [], { + attempts: 1, + nativeProviderApiKey: credential, + }); + expect(command).toHaveBeenCalledTimes(2); + const [executable, args, options] = command.mock.calls[0]!; + expect(executable).toBe("node"); + expect(args).toEqual([ + helpers.CLI, + "credentials", + "add", + "hermes-provider", + "--type", + "openai", + "--credential", + "OPENAI_API_KEY", + ]); + expect(args).not.toContain(credential); + expect(Object.entries(options.env).filter(([, value]) => value === credential)).toEqual([ + ["OPENAI_API_KEY", credential], + ]); + expect(options.redactionValues).toContain(credential); + expect(command.mock.calls[1]?.[1]).toContain("set"); + expect(command.mock.calls[1]?.[2].env.OPENAI_API_KEY).toBeUndefined(); + }); + + it("does not switch or retry after failed manual Hermes registration", async () => { + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "hermes-provider"); + vi.resetModules(); + const helpers = await import("../live/hermes-inference-switch-helpers.ts"); + const failure = { + exitCode: 1, + stdout: "", + stderr: "registration unavailable", + }; + const command = vi.fn().mockResolvedValue(failure); + expect( + await helpers.runHermesInferenceSetWithRetry( + { command } as unknown as HostCliClient, + [], + [], + { + attempts: 3, + nativeProviderApiKey: "manual-nous-fixture", + }, + ), + ).toBe(failure); + expect(command).toHaveBeenCalledOnce(); + expect(command.mock.calls[0]?.[2].redactionValues).toContain("manual-nous-fixture"); + expect(command.mock.calls[0]?.[1]).not.toContain("manual-nous-fixture"); + }); +}); + +it.each(["gpt-5.4", "gpt-6", "openai/o3"])( + "uses the shared raw probe token field for %s", + async (model) => { + const { sandboxInferencePayload } = await import("../live/hermes-inference-switch-helpers.ts"); + const payload = JSON.parse(sandboxInferencePayload(model, "openai-api", "openai-completions")); + expect(payload.model).toBe(model); + expect(payload.max_completion_tokens).toBe(100); + expect(payload).not.toHaveProperty("max_tokens"); + }, +); + +it("preserves Anthropic Messages and Gemini raw probe budgets", async () => { + const { sandboxInferencePayload } = await import("../live/hermes-inference-switch-helpers.ts"); + const anthropic = JSON.parse( + sandboxInferencePayload("vendor-model", "anthropic-prod", "anthropic-messages"), + ); + expect(anthropic.max_tokens).toBe(32); + expect(anthropic).not.toHaveProperty("max_completion_tokens"); + const gemini = JSON.parse( + sandboxInferencePayload("vendor-model", "gemini-api", "openai-completions"), + ); + expect(gemini.max_tokens).toBe(256); +}); diff --git a/test/e2e/support/native-nvidia-target-ownership.test.ts b/test/e2e/support/native-nvidia-target-ownership.test.ts index 2f168adc83b..a778d7fd8ca 100644 --- a/test/e2e/support/native-nvidia-target-ownership.test.ts +++ b/test/e2e/support/native-nvidia-target-ownership.test.ts @@ -8,7 +8,8 @@ import { catalogueTargetsForChangedFiles } from "../../../tools/e2e/target-catal describe("native NVIDIA target ownership", () => { it.each([ "src/lib/actions/inference-set.ts", - "src/lib/inference/native-nvidia/index.ts", + "src/lib/inference/native-nvidia/contract.ts", + "src/lib/inference/native-hosted/index.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "test/e2e/live/public-nvidia-switch-provider.ts", ])("selects both provider-switch targets when %s changes", (changedFile) => { diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index 2cdf8e0f5e6..a1658cbd551 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -6,6 +6,9 @@ import { describe, expect, it } from "vitest"; import { startTestProgress } from "../fixtures/progress.ts"; import { + fixedOpenClawSwitchScenario, + openClawSwitchRoute, + openClawSwitchCurlCommand, agentReplyContainsToken, anthropicToolCount, classifyExhaustedPostSwitchEvidence, @@ -291,3 +294,62 @@ describe("openclaw-inference-switch mock-Anthropic baseline", () => { expect(baseline.env.NEMOCLAW_ENDPOINT_URL).toBe("http://10.0.0.5:9000/v1"); }); }); + +describe("native OpenClaw switch qualification", () => { + it.each([ + [ + "openai-api", + "openai-completions", + "OPENAI_API_KEY", + "https://api.openai.com/v1", + "/chat/completions", + "Authorization: Bearer ", + ], + [ + "anthropic-prod", + "anthropic-messages", + "ANTHROPIC_API_KEY", + "https://api.anthropic.com", + "/v1/messages", + "x-api-key: ", + ], + ])( + "selects the native protocol and issued credential for %s", + (provider, inferenceApi, credentialEnv, baseUrl, suffix, auth) => { + expect( + fixedOpenClawSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: provider, + NEMOCLAW_SWITCH_MODEL: " selected-model ", + }), + ).toEqual({ provider, model: "selected-model", inferenceApi, credentialEnv }); + expect(openClawSwitchRoute(provider, inferenceApi)).toEqual({ + baseUrl, + apiKey: `\${${credentialEnv}}`, + }); + const command = openClawSwitchCurlCommand(provider, inferenceApi); + expect(command).toContain(baseUrl + suffix); + expect(command).toContain(auth); + expect(command).toContain(`_${credentialEnv}$`); + expect(command).not.toContain("inference.local"); + expect(() => fixedOpenClawSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: provider })).toThrow( + "NEMOCLAW_SWITCH_MODEL", + ); + expect(() => + fixedOpenClawSwitchScenario({ + NEMOCLAW_SWITCH_PROVIDER: provider, + NEMOCLAW_SWITCH_MODEL: "selected-model", + NEMOCLAW_SWITCH_INFERENCE_API: "wrong-api", + }), + ).toThrow("protocol"); + }, + ); + it("keeps the authenticated mock baseline on its own shared route", () => { + expect(openClawSwitchRoute(null, "openai-completions")).toEqual({ + baseUrl: "https://inference.local/v1", + apiKey: "unused", + }); + expect( + fixedOpenClawSwitchScenario({ NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint" }), + ).toBeNull(); + }); +}); diff --git a/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts b/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts index 5adc25a45e3..65faa3a56b1 100644 --- a/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts +++ b/test/e2e/support/podman-cpu-lifecycle-artifacts.test.ts @@ -18,7 +18,11 @@ import { PODMAN_SANDBOX_WORKSPACE, PODMAN_SANDBOX_WORKSPACE_LABEL, } from "../../../src/lib/onboard/runtime-provider/podman-lifecycle.ts"; -import { sanitizePodmanInspectArtifact } from "../live/podman-cpu-lifecycle-artifacts.ts"; +import { ArtifactSink } from "../fixtures/artifacts.ts"; +import { + writePodmanImagePullArtifact, + sanitizePodmanInspectArtifact, +} from "../live/podman-cpu-lifecycle-artifacts.ts"; import { captureFailureContainerDiagnostics } from "../live/podman-cpu-lifecycle-helpers.ts"; const SECRET = "nvapi-this-must-not-reach-artifacts"; @@ -133,3 +137,28 @@ describe("Podman CPU proof artifact sanitization", () => { } }); }); + +it("retains failed image pull metadata without exposing credentials", async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "podman-pull-artifact-")); + try { + const sink = new ArtifactSink(root); + const image = "docker.io/library/ubuntu@sha256:fixture"; + const file = await writePodmanImagePullArtifact(sink, "failed-pull.json", image, { + status: 1, + stdout: `NVIDIA_API_KEY=${SECRET}`, + stderr: `download failed NVIDIA_API_KEY=${SECRET}`, + error: new Error(`NVIDIA_API_KEY=${SECRET}`), + }); + const raw = fs.readFileSync(file, "utf8"); + expect(JSON.parse(raw)).toMatchObject({ + image, + status: 1, + stderr: expect.stringContaining("download failed"), + error: expect.any(String), + }); + expect(raw).not.toContain(SECRET); + expect(raw).toContain(""); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/test/e2e/support/public-nvidia-switch-provider.test.ts b/test/e2e/support/public-nvidia-switch-provider.test.ts index 58010957ecf..60e04866d3c 100644 --- a/test/e2e/support/public-nvidia-switch-provider.test.ts +++ b/test/e2e/support/public-nvidia-switch-provider.test.ts @@ -1,10 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { NATIVE_HOSTED_PROFILES } from "../../../src/lib/inference/native-hosted/profiles.ts"; import { describe, expect, it, vi } from "vitest"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { + expectedNativeSwitchAttachmentEvidence, + readNativeSwitchAttachmentEvidence, PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, PUBLIC_NVIDIA_SWITCH_MODEL, PUBLIC_NVIDIA_SWITCH_PROVIDER, @@ -123,3 +126,75 @@ describe("public NVIDIA inference switch provider", () => { ); }); }); + +describe("native hosted switch attachment evidence", () => { + it.each(NATIVE_HOSTED_PROFILES)( + "binds $logicalProvider metadata to its receipt and selected sandbox", + async (profile) => { + const credential = "fixture-credential-must-be-redacted"; + const receipt = { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "revision-1", + }; + const metadata = [ + `Name: ${profile.providerName}`, + "Id: revision-1", + `Type: ${profile.profileId}`, + "Resource version: 1", + `Credential keys: ${profile.credentialEnv}`, + "Config keys: ", + ].join("\n"); + const openshell = vi.fn().mockImplementation(async (args: string[]) => ({ + exitCode: 0, + stderr: "", + stdout: args[0] === "provider" ? metadata : profile.providerName, + })); + const options = { + artifactName: "native-attachment", + env: { [profile.credentialEnv]: credential }, + logicalProvider: profile.logicalProvider, + receipt, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "selected-sandbox", + }; + expect(await readNativeSwitchAttachmentEvidence(options)).toBe( + expectedNativeSwitchAttachmentEvidence(profile.logicalProvider), + ); + expect(openshell).toHaveBeenNthCalledWith( + 2, + ["sandbox", "provider", "list", "-g", "nemoclaw", "selected-sandbox"], + expect.objectContaining({ redactionValues: [credential] }), + ); + expect( + await readNativeSwitchAttachmentEvidence({ + ...options, + receipt: { ...receipt, providerId: "different-revision" }, + }), + ).toContain("provider-id=mismatch"); + expect(await readNativeSwitchAttachmentEvidence({ ...options, receipt: undefined })).not.toBe( + expectedNativeSwitchAttachmentEvidence(profile.logicalProvider), + ); + openshell + .mockResolvedValueOnce({ exitCode: 0, stdout: metadata, stderr: "" }) + .mockResolvedValueOnce({ exitCode: 0, stdout: "unrelated-provider", stderr: "" }); + expect(await readNativeSwitchAttachmentEvidence(options)).toContain("attached=false"); + }, + ); + + it("leaves custom provider coverage with its existing owner", async () => { + const openshell = vi.fn(); + expect( + await readNativeSwitchAttachmentEvidence({ + artifactName: "custom", + env: {}, + logicalProvider: "custom-provider", + receipt: undefined, + sandbox: { openshell } as unknown as SandboxClient, + sandboxName: "selected-sandbox", + }), + ).toBeNull(); + expect(openshell).not.toHaveBeenCalled(); + }); +}); diff --git a/test/e2e/support/standard-profile-workflow-boundary.test.ts b/test/e2e/support/standard-profile-workflow-boundary.test.ts index f01f1d47642..cf5ec468bb9 100644 --- a/test/e2e/support/standard-profile-workflow-boundary.test.ts +++ b/test/e2e/support/standard-profile-workflow-boundary.test.ts @@ -288,7 +288,7 @@ describe("standard E2E execution profile", () => { }); expect(valid.status, valid.stderr).toBe(0); expect(fs.readFileSync(githubOutput, "utf8")).toBe( - "artifact_directory=e2e-artifacts/live/hermes-inference-switch/anthropic\n" + + "hosted_credential=\nartifact_directory=e2e-artifacts/live/hermes-inference-switch/anthropic\n" + "upload_name=e2e-hermes-inference-switch-anthropic-podman\n", ); expect(fs.readFileSync(githubEnvironment, "utf8")).toBe( diff --git a/test/e2e/support/workflow-plan-test-assertions.ts b/test/e2e/support/workflow-plan-test-assertions.ts index 4e29c6bbf20..637278e84da 100644 --- a/test/e2e/support/workflow-plan-test-assertions.ts +++ b/test/e2e/support/workflow-plan-test-assertions.ts @@ -14,6 +14,7 @@ export function expectedWorkflowPlanCiOutput( `matrix=${JSON.stringify(plan.matrix)}`, `test_matrix=${JSON.stringify(plan.testMatrix)}`, `catalogue_standard_matrix=${JSON.stringify(plan.catalogueMatrices.standard)}`, + `catalogue_fixed_hosted_matrix=${JSON.stringify(plan.catalogueMatrices["fixed-hosted"])}`, `catalogue_nvidia_api_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-api"])}`, `catalogue_nvidia_inference_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-inference"])}`, `catalogue_github_read_matrix=${JSON.stringify(plan.catalogueMatrices["github-read"])}`, diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 723461af9db..f557b8bd838 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -79,14 +79,16 @@ describe("E2E workflow plan", () => { expect(plan.testMatrix).toEqual( credentialFreeTestMatrix(discoverCredentialFreeTests(), ["docker"]), ); - expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength(E2E_TARGET_CATALOGUE.length); + expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength( + E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired).length, + ); expect( plan.coverageMatrix.reduce>((counts, row) => { counts[row.source] = (counts[row.source] ?? 0) + 1; return counts; }, {}), ).toEqual({ - catalogue: E2E_TARGET_CATALOGUE.length, + catalogue: E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired).length, "typed-registry": 3, "shared-e2e": 1, "retained-workflow": 14, @@ -699,6 +701,7 @@ describe("E2E workflow plan", () => { "nvidia-api": false, "nvidia-inference": false, "github-read": false, + "fixed-hosted": false, }); }); @@ -974,7 +977,9 @@ describe("E2E workflow plan", () => { { changedFiles: [".github/workflows/e2e-standard-profile.yaml"] }, ); - expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength(E2E_TARGET_CATALOGUE.length); + expect(Object.values(plan.catalogueMatrices).flat()).toHaveLength( + E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired).length, + ); expect(plan.selectedJobs).toEqual(["jetson-nvmap-gpu"]); expect(plan.matrix).toEqual([]); expect(plan.testMatrix).toEqual([]); @@ -982,7 +987,7 @@ describe("E2E workflow plan", () => { it("selects every catalogue target when its shared installer changes", () => { expect(catalogueTargetsForChangedFiles(["scripts/install-openshell.sh"])).toEqual( - E2E_TARGET_CATALOGUE, + E2E_TARGET_CATALOGUE.filter((target) => target.releaseRequired), ); }); @@ -1154,6 +1159,7 @@ describe("E2E workflow plan", () => { "nvidia-api": [], "nvidia-inference": [], "github-read": [], + "fixed-hosted": [], }, coverageMatrix: [], selectedJobs: ["jetson-nvmap-gpu"], diff --git a/test/generation/agent-variant-docs.test.ts b/test/generation/agent-variant-docs.test.ts index 29e374c9b9c..ab263ddef87 100644 --- a/test/generation/agent-variant-docs.test.ts +++ b/test/generation/agent-variant-docs.test.ts @@ -109,7 +109,7 @@ describe("agent variant docs", () => { const sourcePath = "manage-sandboxes/recover-rebuild-sandboxes.mdx"; const pageSource = readFileSync(path.join(repoRoot, "docs", sourcePath), "utf8"); const render = (variant: "openclaw" | "hermes" | "deepagents") => - renderAgentVariantPage(pageSource, variant, { sourcePath }); + renderAgentVariantPage(pageSource, variant, { sourcePath }).replace(/\s+/g, " "); const gatewayStartRepair = "The `start` command repairs the agent runtime and host-side port forwards."; const gatewayStartSuccess = diff --git a/test/generation/generate-hermes-config.test.ts b/test/generation/generate-hermes-config.test.ts index aa00de9c610..1e164180b4d 100644 --- a/test/generation/generate-hermes-config.test.ts +++ b/test/generation/generate-hermes-config.test.ts @@ -253,6 +253,33 @@ function copyConfigGeneratorFixture(fixtureRoot: string): string { path.join(import.meta.dirname, "../..", "src", "lib", "providerless-inference.ts"), path.join(fixtureRoot, "src", "lib", "providerless-inference.ts"), ); + fs.mkdirSync(path.join(fixtureRoot, "src", "lib", "inference", "native-hosted"), { + recursive: true, + }); + fs.copyFileSync( + path.join( + import.meta.dirname, + "../..", + "src", + "lib", + "inference", + "native-hosted", + "openrouter-headers.ts", + ), + path.join(fixtureRoot, "src", "lib", "inference", "native-hosted", "openrouter-headers.ts"), + ); + fs.copyFileSync( + path.join( + import.meta.dirname, + "../..", + "src", + "lib", + "inference", + "native-hosted", + "profiles.ts", + ), + path.join(fixtureRoot, "src", "lib", "inference", "native-hosted", "profiles.ts"), + ); return fixtureScriptPath; } diff --git a/test/generation/generate-openclaw-config-llamacpp-compat.test.ts b/test/generation/generate-openclaw-config-llamacpp-compat.test.ts index d3ce4b6b9d0..e286ab1db16 100644 --- a/test/generation/generate-openclaw-config-llamacpp-compat.test.ts +++ b/test/generation/generate-openclaw-config-llamacpp-compat.test.ts @@ -37,3 +37,14 @@ describe("managed llama.cpp OpenClaw compatibility", () => { expect(model.compat?.toolSchemaProfile).toBeUndefined(); }); }); + +describe("managed OpenRouter attribution", () => { + it("adds static attribution only for OpenRouter requests", () => { + const config = buildLlamaCppConfig("openrouter-api"); + expect(config.models.providers.inference.headers).toEqual({ + "HTTP-Referer": "https://www.nvidia.com/nemoclaw/", + "X-OpenRouter-Title": "NVIDIA NemoClaw", + }); + expect(buildLlamaCppConfig("gemini-api").models.providers.inference.headers).toBeUndefined(); + }); +}); diff --git a/test/generation/generate-openclaw-native-credential.test.ts b/test/generation/generate-openclaw-native-credential.test.ts new file mode 100644 index 00000000000..d7cb58f6029 --- /dev/null +++ b/test/generation/generate-openclaw-native-credential.test.ts @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { beforeEach, afterEach, describe, expect, it } from "vitest"; +import { buildConfig } from "../../scripts/generate-openclaw-config.mts"; +import { NATIVE_HOSTED_PROFILES } from "../../src/lib/inference/native-hosted/profiles"; +import { baseOpenClawGenerationEnv, buildOpenClawTestEnv } from "../helpers/openclaw-env-fixture"; +let home: string; +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "native-openclaw-config-")); +}); +afterEach(() => rmSync(home, { recursive: true, force: true })); +function buildConfigDirect(overrides: Record) { + return buildConfig(buildOpenClawTestEnv(home, baseOpenClawGenerationEnv(), overrides)) as { + models: { providers: { inference: { apiKey: string } } }; + }; +} +describe("native OpenClaw credential generation", () => { + it.each(NATIVE_HOSTED_PROFILES)( + "generates only a workload env reference for $label native endpoint", + (profile) => { + const env = { + NEMOCLAW_UPSTREAM_PROVIDER: profile.logicalProvider, + NEMOCLAW_INFERENCE_PROVIDER_ID: "inference", + NEMOCLAW_INFERENCE_BASE_URL: profile.endpoint, + [profile.credentialEnv]: "raw-value-must-not-enter-config", + }; + const config = buildConfigDirect(env); + expect(config.models.providers.inference.apiKey).toBe(`\${${profile.credentialEnv}}`); + expect(JSON.stringify(config)).not.toContain("raw-value-must-not-enter-config"); + expect( + buildConfigDirect({ ...env, NEMOCLAW_INFERENCE_BASE_URL: "https://inference.local/v1" }) + .models.providers.inference.apiKey, + ).toBe("unused"); + }, + ); +}); diff --git a/test/generation/providerless-agent-config.test.ts b/test/generation/providerless-agent-config.test.ts index b7230219aac..44430541bd1 100644 --- a/test/generation/providerless-agent-config.test.ts +++ b/test/generation/providerless-agent-config.test.ts @@ -149,7 +149,7 @@ const expectConfigured: Record void> = { hermes(config) { expect(config.model.default).toBe("fixture/model"); expect(config.model.provider).toBe("custom"); - expect(config.model.api_key).toBe("sk-OPENSHELL-PROXY-REWRITE"); + expect(config.model.api_key).toBe("${NVIDIA_INFERENCE_API_KEY}"); }, }; type InferenceSetCalls = ReturnType["calls"]; @@ -268,7 +268,7 @@ describe.each(["openclaw", "hermes"])("providerless %s configuration", (a ), ).toBe(false); }); - it("leaves generated configuration absent when the later route update fails", async () => { + it("leaves generated configuration absent when native provider attachment fails", async () => { const generated = generate(agent, dockerEnvironment(agent)); expect(generated.result.status, generated.result.stderr).toBe(0); const config = generated.read(); @@ -276,7 +276,10 @@ describe.each(["openclaw", "hermes"])("providerless %s configuration", (a config, entry: { name: "alpha", agent, provider: null, model: null }, target: agent === "hermes" ? HERMES_TARGET : OPENCLAW_TARGET, - openshellStatus: 1, + }); + deps.providerAdapter.attachProvider = async () => ({ + ok: false, + error: { kind: "command", reason: "not_found", message: "sandbox missing" }, }); await expect( runInferenceSet( diff --git a/test/helpers/credentials-provider-adapter.ts b/test/helpers/credentials-provider-adapter.ts new file mode 100644 index 00000000000..eac4891dc86 --- /dev/null +++ b/test/helpers/credentials-provider-adapter.ts @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../../src/lib/adapters/openshell/provider-adapter"; + +export function providerAdapter( + overrides: Partial = {}, +): OpenShellProviderAdapter { + const listProviders: OpenShellProviderAdapter["listProviders"] = async () => ({ + ok: true, + value: { names: [] }, + }); + const createProvider: OpenShellProviderAdapter["createProvider"] = async () => ({ + ok: true, + }); + const getProvider: OpenShellProviderAdapter["getProvider"] = async (request) => ({ + ok: true, + value: { name: request.providerName, type: "generic", credentialKeys: [], configKeys: [] }, + }); + const updateProvider: OpenShellProviderAdapter["updateProvider"] = async () => ({ + ok: true, + }); + const importProviderProfile: OpenShellProviderAdapter["importProviderProfile"] = async () => ({ + ok: true, + }); + const inspectProviderProfile: OpenShellProviderAdapter["inspectProviderProfile"] = async () => ({ + ok: true, + value: { credentialKeys: [] }, + }); + const deleteProvider: OpenShellProviderAdapter["deleteProvider"] = async () => ({ + ok: true, + }); + const detachProvider: OpenShellProviderAdapter["detachProvider"] = async () => ({ + ok: true, + value: { changed: true }, + }); + const attachProvider: OpenShellProviderAdapter["attachProvider"] = async () => ({ ok: true }); + const listProviderAttachments: OpenShellProviderAdapter["listProviderAttachments"] = + async () => ({ ok: true, value: { names: [] } }); + const configureProviderRefresh: OpenShellProviderAdapter["configureProviderRefresh"] = + async () => ({ ok: true }); + const getProviderRefreshStatus: OpenShellProviderAdapter["getProviderRefreshStatus"] = + async () => ({ ok: true, value: { status: "refreshed" } }); + return { + ensureProviderPolicyComposition: vi.fn< + OpenShellProviderAdapter["ensureProviderPolicyComposition"] + >(async () => ({ ok: true, value: undefined })), + listProviders: vi.fn(listProviders), + createProvider: vi.fn(createProvider), + getProvider: vi.fn(getProvider), + updateProvider: vi.fn(updateProvider), + importProviderProfile: vi.fn(importProviderProfile), + inspectProviderProfile: vi.fn(inspectProviderProfile), + deleteProvider: vi.fn(deleteProvider), + detachProvider: vi.fn(detachProvider), + attachProvider: vi.fn(attachProvider), + listProviderAttachments: vi.fn(listProviderAttachments), + configureProviderRefresh: vi.fn(configureProviderRefresh), + getProviderRefreshStatus: vi.fn(getProviderRefreshStatus), + ...overrides, + }; +} diff --git a/test/helpers/onboard-script-mocks-openshell-capture.test.ts b/test/helpers/onboard-script-mocks-openshell-capture.test.ts index 1c43a99ea81..c29d02fe269 100644 --- a/test/helpers/onboard-script-mocks-openshell-capture.test.ts +++ b/test/helpers/onboard-script-mocks-openshell-capture.test.ts @@ -1,6 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import { nativeHostedProviderProfilePath } from "../../src/lib/inference/native-hosted"; +import { nativeHostedProfile } from "../../src/lib/inference/native-hosted/profiles"; +import { + exportedProviderProfileMatchesContract, + parseCheckedInProviderProfileContract, +} from "../../src/lib/adapters/openshell/provider-profile"; import { createRequire } from "node:module"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -192,3 +199,49 @@ describe("mockStructuredOpenShellCaptureFromRunner", () => { ).toBe(""); }); }); + +it.each(["attached", "prepared"])( + "exports only the created sandbox's %s native profile on its gateway", + (mode) => { + const profile = nativeHostedProfile("nvidia-prod")!; + const fixture = createCreatedSandboxFixture({ + gatewayName: "nemoclaw-test", + nativeHostedProfileId: mode === "prepared" ? profile.profileId : undefined, + }); + const command = [ + "openshell", + "provider", + "profile", + "-g", + "nemoclaw-test", + "export", + profile.profileId, + "--output", + "json", + ]; + expect(fixture.run(command)).toBeNull(); + fixture.create( + mode === "attached" + ? [...exactCreateCommand, "--provider", profile.providerName] + : exactCreateCommand, + ); + const exported = fixture.run(command)!; + const contract = parseCheckedInProviderProfileContract( + fs.readFileSync(nativeHostedProviderProfilePath(profile), "utf8"), + )!; + expect(exported.status).toBe(0); + expect(exportedProviderProfileMatchesContract(String(exported.stdout), contract)).toBe(true); + expect( + fixture.run(command.map((arg) => (arg === "nemoclaw-test" ? "other-gateway" : arg))), + ).toBeNull(); + expect( + fixture.run( + command.map((arg) => (arg === profile.profileId ? "nemoclaw-openai-inference-v1" : arg)), + ), + ).toBeNull(); + expect(fixture.run([...command, "--unexpected"])).toBeNull(); + expect( + fixture.run(command.map((arg) => (arg === profile.profileId ? "nemoclaw-mcp-v1" : arg))), + ).toBeNull(); + }, +); diff --git a/test/helpers/onboard-script-mocks.cjs b/test/helpers/onboard-script-mocks.cjs index dc33e9bec54..4428ec0166a 100644 --- a/test/helpers/onboard-script-mocks.cjs +++ b/test/helpers/onboard-script-mocks.cjs @@ -228,6 +228,13 @@ function mockNvidiaProviderGetRun(command, gatewayName) { const request = parseNamedProviderGet(command, gatewayName); if (request === null) return null; if (request.error) return request.error; + if (request.providerName === "nemoclaw-nvidia-prod-v1") { + return { + status: 0, + stdout: + "Name: nemoclaw-nvidia-prod-v1\nType: nemoclaw-nvidia-inference-v1\nCredential keys: NVIDIA_INFERENCE_API_KEY\nConfig keys: \nId: provider-revision-1\nResource version: 1\n", + }; + } if (request.providerName !== "nvidia-prod") return null; return { status: 0, @@ -304,6 +311,7 @@ function createStatefulMessagingProviderRunner({ commands, initialProviders = [], createdSandbox = null, + nativeNvidiaProvider = false, }) { const providers = new Map( initialProviders.map(([name, type, credential]) => [name, { type, credential }]), @@ -325,6 +333,10 @@ function createStatefulMessagingProviderRunner({ const sandboxResult = createdSandbox?.run(command) ?? null; if (sandboxResult !== null) return sandboxResult; + if (nativeNvidiaProvider && args.at(-1) === "nemoclaw-nvidia-prod-v1") { + const nativeProvider = mockNvidiaProviderGetRun(command, "nemoclaw"); + if (nativeProvider !== null) return nativeProvider; + } const providerAction = providerIndex >= 0 ? args[providerIndex + 1] : null; if (providerAction === "profile") { const profileActionIndex = providerIndex + 2; @@ -382,6 +394,12 @@ function createStatefulMessagingProviderRunner({ : { status: 1, stderr: `provider '${name}' not found` }; } if (providerAction === "update") { + const nativeUpdateArgs = exactOpenShellArgs(command); + if ( + nativeNvidiaProvider && + nativeUpdateArgs?.join(" ") === "provider update -g nemoclaw nemoclaw-nvidia-prod-v1" + ) + return { status: 0 }; const name = providerNameAfterAction(args, providerIndex); const credentialIndex = args.indexOf("--credential"); const credential = credentialIndex >= 0 ? args[credentialIndex + 1] : null; @@ -529,7 +547,7 @@ function mockOnboardRunCapture(command, options = {}) { function exactOpenShellArgs(command) { const args = Array.isArray(command) ? command.map(String) : []; - const verbs = new Set(["gateway", "policy", "sandbox"]); + const verbs = new Set(["gateway", "policy", "sandbox", "provider"]); if (verbs.has(args[0])) return args; if (args.length > 1 && verbs.has(args[1])) return args.slice(1); if ( @@ -635,6 +653,7 @@ function createCreatedSandboxFixture(options = {}) { return nonces[0]; }; + let attachedProviders = []; const isCreated = () => state.lifecycleState === "created"; const observe = (command, allowPublishedUnscopedGet) => { const details = commandDetails(command); @@ -656,6 +675,16 @@ function createCreatedSandboxFixture(options = {}) { ? `Name: ${state.sandboxName}\nId: ${state.sandboxId}\nPhase: ${state.phase}\n` : ""; } + if ( + action === "provider" && + args[args.indexOf("sandbox") + 2] === "list" && + gatewayName === state.gatewayName && + args.at(-1) === state.sandboxName + ) { + return isCreated() + ? `NAME TYPE CREDENTIAL_KEYS CONFIG_KEYS\n${attachedProviders.map((name) => `${name} ${name === "nemoclaw-nvidia-prod-v1" ? "nemoclaw-nvidia-inference-v1" : "fixture-provider"} 1 0`).join("\n")}\n` + : ""; + } if (action !== "list") return null; const selectorIndex = args.indexOf("--selector"); @@ -702,6 +731,38 @@ function createCreatedSandboxFixture(options = {}) { const capture = (command) => observe(command, false); const run = (command) => { + const args = exactOpenShellArgs(command); + if (args?.[0] === "provider" && args[1] === "profile") { + const { NATIVE_HOSTED_PROFILES } = require( + path.resolve(__dirname, "../../src/lib/inference/native-hosted/profiles.ts"), + ); + const profile = NATIVE_HOSTED_PROFILES.find( + (candidate) => + (attachedProviders.includes(candidate.providerName) || + options.nativeHostedProfileId === candidate.profileId) && + args[5] === candidate.profileId, + ); + if ( + isCreated() && + profile && + args.length === 8 && + args[2] === "-g" && + args[3] === state.gatewayName && + args[4] === "export" && + args[6] === "--output" && + args[7] === "json" + ) { + const { nativeHostedProviderProfilePath } = require( + path.resolve(__dirname, "../../src/lib/inference/native-hosted/index.ts"), + ); + const source = require("node:fs").readFileSync( + nativeHostedProviderProfilePath(profile), + "utf8", + ); + return { status: 0, stdout: JSON.stringify(require("yaml").parse(source)), stderr: "" }; + } + return null; + } const output = observe(command, true); if (output === null) return null; if (output === "") { @@ -727,6 +788,9 @@ function createCreatedSandboxFixture(options = {}) { if (state.lifecycleState !== "absent") { throw new Error("Created sandbox fixture cannot create a deleted sandbox."); } + attachedProviders = details.args.flatMap((arg, index) => + arg === "--provider" ? [details.args[index + 1]] : [], + ); state.createAttemptNonce = createAttemptNonce; state.ownerScopedIdentityObserved = false; assertState(); @@ -747,6 +811,9 @@ function createCreatedSandboxFixture(options = {}) { throw new Error("Created sandbox fixture can recreate only a deleted sandbox."); } const createAttemptNonce = nonceFromCreateCommand(command); + attachedProviders = commandDetails(command).args.flatMap((arg, index, args) => + arg === "--provider" ? [args[index + 1]] : [], + ); state.generation += 1; const replacementFingerprint = sandboxIdentity.fingerprintOpenShellSandboxId(initialSandboxId); state.sandboxId = `sbx-recreated-${state.generation}-${replacementFingerprint}`; @@ -801,11 +868,54 @@ function createCreatedSandboxFixture(options = {}) { }); } +// Direct-create tests bypass the onboarding machine, which normally supplies this +// receipt to the real create-plan resolver from the inference reservation. +function installNativeHostedCreateIntentFixture(sandboxName, profile) { + const owner = require( + path.resolve(__dirname, "../../src/lib/onboard/sandbox-create-intent-resolution.ts"), + ); + const createResolver = owner.createSandboxCreateIntentResolver; + owner.createSandboxCreateIntentResolver = (...args) => { + const resolver = createResolver(...args); + const resolvePortableLifecycle = resolver.resolvePortableLifecycle; + resolver.resolvePortableLifecycle = (input, options) => + resolvePortableLifecycle( + input.sandboxName === sandboxName && + input.inferenceProvider === profile.logicalProvider && + input.nativeHostedProviderAttachment === undefined && + !options.resolvedIntent + ? { + ...input, + inferenceProvider: profile.providerName, + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: profile.profileId, + providerName: profile.providerName, + providerId: "provider-revision-1", + }, + } + : input, + options, + ); + return resolver; + }; +} + function installVerifiedSandboxCreateFixture(registry, options) { const sandboxName = options.sandboxName; const gatewayName = options.gatewayName || "nemoclaw"; const gatewayPort = options.gatewayPort || 8080; mockStructuredOpenShellCaptureFromRunner({ gatewayName, gatewayPort, sandboxName }); + if ( + (options.nativeNvidiaCreateIntent === true && options.provider === "nvidia-prod") || + options.nativeHostedCreateIntent === true + ) { + const { nativeHostedProfile } = require( + path.resolve(__dirname, "../../src/lib/inference/native-hosted/profiles.ts"), + ); + const profile = nativeHostedProfile(options.provider); + if (profile) installNativeHostedCreateIntentFixture(sandboxName, profile); + } const sessionId = options.sessionId || "integration-fixture-session"; const selection = { provider: options.provider, diff --git a/test/helpers/onboard-split-context.ts b/test/helpers/onboard-split-context.ts index 2afd238e83a..b1530e2a509 100644 --- a/test/helpers/onboard-split-context.ts +++ b/test/helpers/onboard-split-context.ts @@ -3,6 +3,9 @@ import assert from "node:assert/strict"; import path from "node:path"; +import { vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../../src/lib/adapters/openshell/provider-adapter"; +import { nativeHostedProfile } from "../../src/lib/inference/native-hosted/profiles"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { createDirectSetupInferenceHarnessFactory } from "../support/setup-inference-test-harness.js"; @@ -100,3 +103,53 @@ export const repoRoot = path.join(import.meta.dirname, "../.."); export const onboardScriptMocksPath = JSON.stringify( path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), ); + +/** Stateful native provider transport, isolated from the developer gateway. */ +export function createNativeSetupProviderAdapter( + provider: string, + initiallyPresent = true, + providerId = "fixture-native-id", +) { + const profile = nativeHostedProfile(provider)!; + let present = initiallyPresent; + const unexpected = async (): Promise => { + throw new Error("Unexpected provider operation"); + }; + const adapter = { + ensureProviderPolicyComposition: vi.fn< + OpenShellProviderAdapter["ensureProviderPolicyComposition"] + >(async () => ({ ok: true, value: undefined })), + importProviderProfile: vi.fn(() => ({ + ok: true, + })), + getProvider: vi.fn(async ({ providerName }) => { + assert.equal(providerName, profile.providerName); + return present + ? { + ok: true, + value: { + name: profile.providerName, + type: profile.profileId, + credentialKeys: [profile.credentialEnv], + configKeys: [], + revision: { id: providerId, resourceVersion: 1 }, + }, + } + : { ok: false, error: { kind: "command", reason: "not_found", message: "not found" } }; + }), + createProvider: vi.fn(async () => { + present = true; + return { ok: true }; + }), + updateProvider: vi.fn(async () => ({ ok: true })), + listProviders: unexpected, + inspectProviderProfile: unexpected, + deleteProvider: unexpected, + detachProvider: unexpected, + attachProvider: unexpected, + listProviderAttachments: unexpected, + configureProviderRefresh: unexpected, + getProviderRefreshStatus: unexpected, + } satisfies OpenShellProviderAdapter; + return adapter; +} diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index 499878927eb..3d39374756a 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -85,6 +85,7 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ "test/onboarding/onboard-extra-provider-reconciliation.test.ts", "test/onboarding/onboard-fresh-create-identity.test.ts", "test/onboarding/onboard-installer-restore-intent.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/onboarding/onboard-messaging.test.ts", "test/onboarding/onboard-prepared-build-context.test.ts", "test/onboarding/onboard-reservation-recreate.test.ts", diff --git a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts index 251ed4de5a7..89df3a0ba6e 100644 --- a/test/onboarding/onboard-build-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-build-recreate-credential-reuse.test.ts @@ -60,12 +60,14 @@ EOF exit 0 fi if [ "$1" = "provider" ] && [ "$2" = "profile" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ] && [ "$5" = "export" ]; then + cat <<'EOF' {"id":"nemoclaw-nvidia-inference-v1","credentials":[{"name":"api_key","env_vars":["NVIDIA_INFERENCE_API_KEY"],"required":true,"auth_style":"bearer","header_name":"authorization","query_param":""}],"endpoints":[{"host":"integrate.api.nvidia.com","port":443,"protocol":"rest","enforcement":"enforce","rules":[{"allow":{"method":"GET","path":"/v1/models"}},{"allow":{"method":"POST","path":"/v1/chat/completions"}}]}],"binaries":["/usr/local/bin/node","/usr/bin/node","/opt/hermes/.venv/bin/python","/opt/hermes/.venv/bin/python3","/opt/venv/bin/python3","/usr/local/bin/curl","/usr/bin/curl"],"inference_capable":true} EOF exit 0 fi if [ "$1" = "provider" ] && [ "$2" = "get" ] && [ "$3" = "-g" ] && [ "$4" = "nemoclaw" ] && [ "$5" = "nemoclaw-nvidia-prod-v1" ]; then + cat <<'EOF' Name: nemoclaw-nvidia-prod-v1 Id: provider-id @@ -127,6 +129,7 @@ const registry = require(${registryPath}); // ownership evidence because another sandbox can use the same provider name. registry.registerSandbox({ name: "rg-test-noninter", + gatewayName: "nemoclaw", provider: "nvidia-prod", model: "nvidia/llama-3.3-nemotron-super-49b-v1", nativeNvidiaProviderAttachment: { diff --git a/test/onboarding/onboard-custom-dockerfile.test.ts b/test/onboarding/onboard-custom-dockerfile.test.ts index ed0b1251006..cb9d3682b26 100644 --- a/test/onboarding/onboard-custom-dockerfile.test.ts +++ b/test/onboarding/onboard-custom-dockerfile.test.ts @@ -238,11 +238,10 @@ runner.run = (command, opts = {}) => { commands.push({ command: normalized, env: opts.env || null }); const profileResult = fixtureMocks.mockManagedEndpointlessProviderProfileRun(command); if (profileResult !== null) return profileResult; - if (normalized.endsWith("provider get -g nemoclaw openai-api")) { + if (normalized.endsWith("provider get -g nemoclaw nemoclaw-openai-api-v1")) { return { - status: 1, - stdout: "", - stderr: "provider 'openai-api' not found", + status: 0, + stdout: "Name: nemoclaw-openai-api-v1\nType: nemoclaw-openai-inference-v1\nCredential keys: OPENAI_API_KEY\nConfig keys: \nId: provider-revision-1\nResource version: 1\n", }; } const sandboxResult = createdSandbox.run(command); @@ -263,6 +262,7 @@ runner.runCapture = (command) => { }; fixtureMocks.mockDockerSandboxLifecycleReleaseFromRunner(); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeHostedCreateIntent: true, sandboxName: "my-assistant", provider: "openai-api", model: "gpt-5.4", diff --git a/test/onboarding/onboard-extra-provider-reconciliation.test.ts b/test/onboarding/onboard-extra-provider-reconciliation.test.ts index 4f349ab19df..aa8be43687d 100644 --- a/test/onboarding/onboard-extra-provider-reconciliation.test.ts +++ b/test/onboarding/onboard-extra-provider-reconciliation.test.ts @@ -56,6 +56,7 @@ registry.addExtraProvider("brave-search"); registry.addExtraProvider("custom-provider"); registry.addExtraProvider("my-slack-bridge"); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -232,8 +233,10 @@ const createReservedSandbox = () => { "provider get -g nemoclaw custom-provider", "provider get -g nemoclaw my-slack-bridge", "provider get -g nemoclaw my-slack-bridge", - "provider get -g nemoclaw nvidia-prod", - "provider get -g nemoclaw nvidia-prod", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", + "provider get -g nemoclaw nemoclaw-nvidia-prod-v1", "provider get -g nemoclaw tavily-search", ].sort(), ); diff --git a/test/onboarding/onboard-fresh-create-identity.test.ts b/test/onboarding/onboard-fresh-create-identity.test.ts index ec2f1eeabe2..b95d5f1683d 100644 --- a/test/onboarding/onboard-fresh-create-identity.test.ts +++ b/test/onboarding/onboard-fresh-create-identity.test.ts @@ -513,6 +513,7 @@ managedWorkloadOnboard.createManagedStateVolumeOnboardLifecycle = (input, deps = } const durableGetSandbox = registry.getSandbox.bind(registry); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", gatewayName: ${JSON.stringify(gatewayName)}, gatewayPort: ${String(gatewayPort)}, @@ -988,7 +989,7 @@ if (${JSON.stringify( assert.equal("policyAuthority" in payload.registeredSandbox, false); assert.equal("policyCreationReceipt" in payload.registeredSandbox, false); assert.match(payload.createCommand, /--policy \S+/u); - assert.match(payload.createCommand, /--provider nvidia-prod/u); + assert.match(payload.createCommand, /--provider nemoclaw-nvidia-prod-v1/u); }; const assertProviderlessApfCreation = () => { assertProviderlessInference(); diff --git a/test/onboarding/onboard-fsm-live-slices.test.ts b/test/onboarding/onboard-fsm-live-slices.test.ts index dde2ef04c11..b2451543463 100644 --- a/test/onboarding/onboard-fsm-live-slices.test.ts +++ b/test/onboarding/onboard-fsm-live-slices.test.ts @@ -290,12 +290,8 @@ if (scenario.mode === "active-cancellation") { ); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0); } -if (scenario.mode === "dashboard-spawn-failure") { - require(${gatewayServicePath}).hasOpenShellGatewayUserService = () => false; -} -if (scenario.mode.startsWith("wsl-vllm-")) { - require(${gatewayServicePath}).hasOpenShellGatewayUserService = () => false; -} +// Every slice probe owns a simulated standalone gateway, independent of host services. +require(${gatewayServicePath}).hasOpenShellGatewayUserService = () => false; const dashboardScenario = scenario.mode.startsWith("dashboard-"); // Slice dispatch uses fixture gateway bindings and must not observe host listeners. require(${JSON.stringify(path.join(repoRoot, "src", "lib", "onboard", "preflight.ts"))}) diff --git a/test/onboarding/onboard-hermes-portable-provider-publication.test.ts b/test/onboarding/onboard-hermes-portable-provider-publication.test.ts index 858a20d1f74..96ebd81b3e1 100644 --- a/test/onboarding/onboard-hermes-portable-provider-publication.test.ts +++ b/test/onboarding/onboard-hermes-portable-provider-publication.test.ts @@ -37,9 +37,27 @@ type ProviderBoundaryResult = { result: string; }; +const expectedProfileCheck = [ + "provider", + "profile", + "-g", + "nemoclaw", + "export", + "nemoclaw-nvidia-inference-v1", + "--output", + "json", +]; +const expectedAttachmentCalls = [ + expectedProfileCheck, + ["provider", "list", "-g", "nemoclaw", "my-assistant"], + expectedProfileCheck, + ["provider", "get", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ["provider", "list", "-g", "nemoclaw", "my-assistant"], +]; const expectedProviderCalls = [ - ["provider", "get", "-g", "nemoclaw", "nvidia-prod"], - ["provider", "update", "-g", "nemoclaw", "nvidia-prod"], + ["provider", "get", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ["provider", "update", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ...expectedAttachmentCalls, ]; function shellQuote(value: string): string { @@ -141,6 +159,7 @@ const createdSandbox = fixtureMocks.createCreatedSandboxFixture({ sandboxName, sandboxId: "sbx-hermes-provider-boundary", gatewayName, + nativeHostedProfileId: inferenceProvider === "nvidia-prod" ? "nemoclaw-nvidia-inference-v1" : undefined, }); createdSandbox.installRuntimeObservation(); @@ -152,11 +171,15 @@ runner.run = (command) => { if (providerArgs) providerCalls.push(providerArgs); const providerGet = fixtureMocks.mockNvidiaProviderGetRun(command, gatewayName); if (providerGet !== null) return providerGet; - if (text === "provider update -g nemoclaw nvidia-prod") { + const providerList = text === "provider list -g nemoclaw my-assistant" + ? { status: 0, stdout: "NAME TYPE CREDENTIAL_KEYS CONFIG_KEYS\n" + + "nemoclaw-nvidia-prod-v1 nemoclaw-nvidia-inference-v1 1 0\n" } + : null; + if (text === "provider update -g nemoclaw nemoclaw-nvidia-prod-v1") { events.push("provider:update"); return { status: 0, stdout: "" }; } - return createdSandbox.run(command) ?? { status: 0, stdout: "" }; + return providerList ?? createdSandbox.run(command) ?? { status: 0, stdout: "" }; }; runner.runCapture = (command) => { const captured = createdSandbox.capture(command); @@ -178,6 +201,7 @@ const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, gatewayName, agentName: portableMode ? "hermes" : "langchain-deepagents-code", provider: inferenceProvider, + nativeNvidiaCreateIntent: !portableMode, model: "gpt-5.4", }); if (!portableMode) { @@ -290,6 +314,7 @@ require.cache[sandboxGpuCreateFlowId].exports = { input.createRequest.source.reference, "--name", input.createRequest.sandboxName, + ...(input.createRequest.providers ?? []).flatMap((provider) => ["--provider", provider]), ...Object.entries(input.createRequest.labels ?? {}).flatMap(([name, value]) => [ "--label", name + "=" + value, @@ -355,6 +380,12 @@ const { resolveSandboxGpuConfig } = require(${modulePath("onboard/sandbox-gpu-mo basePolicyPath: ${JSON.stringify(path.join(repoRoot, "agents/hermes/policy-additions.yaml"))}, sandboxName, inferenceProvider, + nativeHostedProviderAttachment: inferenceProvider === "nvidia-prod" ? { + schemaVersion: 1, + profileId: "nemoclaw-nvidia-inference-v1", + providerName: "nemoclaw-nvidia-prod-v1", + providerId: "provider-revision-1", + } : undefined, channels: [], enabledChannels: [], disabledChannelNames: new Set(), @@ -424,7 +455,9 @@ describe("sandbox-create provider publication branches", () => { "carries the real Portable caller request through the receipt-owned lifecycle adapter (#12119)", { timeout: 60_000 }, async () => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-real-boundary-")); + const tmpDir = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-real-boundary-")), + ); const executablePath = path.join(tmpDir, "openshell"); const statePath = path.join(tmpDir, "sandbox-created"); const invocationPath = path.join(tmpDir, "openshell-invocations.log"); @@ -839,7 +872,10 @@ describe("sandbox-create provider publication branches", () => { const payload = runProviderBoundary("ordinary-resume"); assert.equal(payload.result, "my-assistant"); - assert.deepEqual(payload.providerCalls, expectedProviderCalls); + assert.deepEqual(payload.providerCalls, [ + ...expectedProviderCalls, + ...expectedAttachmentCalls, + ]); assert.equal(payload.portableTransactions, 0); assert.match(payload.firstError ?? "", /registry publication/u); assert.equal(payload.gpuCreateCalls, 2); diff --git a/test/onboarding/onboard-inference-failure-paths.test.ts b/test/onboarding/onboard-inference-failure-paths.test.ts index 1c8f8083869..bc18d059af4 100644 --- a/test/onboarding/onboard-inference-failure-paths.test.ts +++ b/test/onboarding/onboard-inference-failure-paths.test.ts @@ -113,11 +113,20 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:1", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:1"); - expect(harness.errors).toEqual([" Unsupported provider configuration: openai-api"]); + expect(harness.errors).toEqual([" Unsupported provider configuration: compatible-endpoint"]); expect(exitProcess).toHaveBeenCalledOnce(); expect(exitProcess).toHaveBeenCalledWith(1); expect(setupBedrockRuntimeInference).not.toHaveBeenCalled(); @@ -142,18 +151,27 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:1", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:1"); expect(setupBedrockRuntimeInference).toHaveBeenCalledOnce(); - expect(hydrateCredentialEnv).toHaveBeenCalledWith("OPENAI_API_KEY"); + expect(hydrateCredentialEnv).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); expect(upsertProvider).not.toHaveBeenCalled(); expect(promptValidationRecovery).not.toHaveBeenCalled(); expect(exitProcess).toHaveBeenCalledOnce(); expect(exitProcess).toHaveBeenCalledWith(1); expect(harness.errors).toEqual([ - " A host credential is required to configure provider 'openai-api'.", + " A host credential is required to configure provider 'compatible-endpoint'.", ]); expectNoPostFailureSideEffects(harness); }); @@ -179,19 +197,28 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:23", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:23"); expect(setupBedrockRuntimeInference).toHaveBeenCalledOnce(); - expect(hydrateCredentialEnv).toHaveBeenCalledWith("OPENAI_API_KEY"); + expect(hydrateCredentialEnv).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); expect(upsertProvider).toHaveBeenCalledOnce(); expect(upsertProvider).toHaveBeenCalledWith( - "openai-api", + "compatible-endpoint", "openai", - "OPENAI_API_KEY", + "COMPATIBLE_API_KEY", expect.any(String), - { OPENAI_API_KEY: "openai-secret" }, + { COMPATIBLE_API_KEY: "openai-secret" }, "nemoclaw", { revalidateSandboxIdentity: expect.any(Function) }, ); @@ -227,9 +254,18 @@ describe("setupInference dependency failures", () => { }, }); - await expect(harness.setupInference("test-box", "gpt-test", "openai-api")).rejects.toThrow( - "EXIT_CALLED:37", - ); + await expect( + harness.setupInference( + "test-box", + "gpt-test", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, + ), + ).rejects.toThrow("EXIT_CALLED:37"); expect(setupBedrockRuntimeInference).toHaveBeenCalledOnce(); expect(upsertProvider).toHaveBeenCalledOnce(); @@ -240,7 +276,7 @@ describe("setupInference dependency failures", () => { expect(harness.errors.join("\n")).toContain("route failed"); expect(harness.errors.join("\n")).not.toContain(NVIDIA_REDACTION_CANARY); expectNoPostFailureSideEffects(harness, [ - "inference set -g nemoclaw --no-verify --provider openai-api --model gpt-test", + "inference set -g nemoclaw --no-verify --provider compatible-endpoint --model gpt-test --timeout 180", ]); }); @@ -860,7 +896,7 @@ describe("setupInference dependency failures", () => { ]); }); - it("uses an injected Hermes DNS lookup before rejecting an unpinnable HTTPS endpoint", async () => { + it("rejects noncanonical native Hermes endpoints before DNS lookup", async () => { const exitProcess = createInjectedExit(); const lookup = vi.fn>(async () => [ { address: "8.8.8.8", family: 4 }, @@ -874,9 +910,9 @@ describe("setupInference dependency failures", () => { "hermes-provider", "https://api.public.example.test/v1", ), - ).rejects.toThrow("DNS-backed HTTPS URLs are not supported"); + ).rejects.toThrow("native inference requires its canonical endpoint"); - expect(lookup).toHaveBeenCalledWith("api.public.example.test", { all: true }); + expect(lookup).not.toHaveBeenCalled(); expect(exitProcess).not.toHaveBeenCalled(); expectNoPostFailureSideEffects(harness); }); diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 4e4c4bf15b0..46fa583241b 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import { createNativeSetupProviderAdapter } from "../helpers/onboard-split-context"; import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { @@ -38,13 +39,10 @@ function expectCommandsTargetOnly(commands: Array<{ command: string }>): void { } describe("onboarding inference gateway scope", () => { - it("targets a non-default gateway for provider creation, route apply, and verification", async () => { + it("targets a non-default gateway for native provider creation and verification", async () => { await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { - const harness = createHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" ? { status: 1 } : undefined, - }); - + const providerAdapter = createNativeSetupProviderAdapter("openai-api", false); + const harness = createHarness({ overrides: { providerAdapter } }); await expect( harness.setupInference( "test-box", @@ -57,14 +55,25 @@ describe("onboarding inference gateway scope", () => { { gatewayName: GATEWAY }, ), ).resolves.toEqual({ ok: true }); - - expect(harness.commands.map(({ command }) => command)).toEqual([ - `provider get -g ${GATEWAY} openai-api`, - `provider create -g ${GATEWAY} --name openai-api --type openai --credential OPENAI_API_KEY --config OPENAI_BASE_URL=https://api.openai.com/v1`, - `inference set -g ${GATEWAY} --no-verify --provider openai-api --model gpt-test`, - ]); - expect(harness.verifyInferenceRoute).toHaveBeenCalledWith(GATEWAY, "openai-api", "gpt-test"); - expectCommandsTargetOnly(harness.commands); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + nativeHostedProviderAttachment: expect.objectContaining({ + providerName: "nemoclaw-openai-api-v1", + providerId: "fixture-native-id", + }), + gatewayName: GATEWAY, + }), + ); + expect(providerAdapter.createProvider).toHaveBeenCalledOnce(); + const targetRequest = expect.objectContaining({ + target: { kind: "named", gatewayName: GATEWAY }, + }); + expect(providerAdapter.importProviderProfile.mock.calls).toEqual([[targetRequest]]); + expect(providerAdapter.getProvider.mock.calls).toEqual([[targetRequest], [targetRequest]]); + expect(providerAdapter.createProvider.mock.calls).toEqual([[targetRequest]]); + expect(harness.commands).toEqual([]); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); }); }); diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index 1ca897f922f..0cd7ebcf308 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { createNativeProviderCommandRuntime } from "../support/native-provider-command-runtime"; import { describe, expect, it, vi } from "vitest"; import { @@ -20,6 +21,7 @@ import { bedrockRuntimeOnboard, type CommandEntry, createDirectSetupInferenceHarness, + createNativeSetupProviderAdapter, parseStdoutJson, stripMessagingEnv, } from "../helpers/onboard-split-context"; @@ -28,29 +30,19 @@ import { withProcessEnv, } from "../support/setup-inference-test-harness.js"; -const HERMES_OAUTH_PROVIDER_METADATA = [ - "Name: hermes-provider", +const COMPATIBLE_PROVIDER_METADATA = [ + "Name: compatible-endpoint", "Type: openai", - "Credential keys: OPENAI_API_KEY", + "Credential keys: COMPATIBLE_API_KEY", "Config keys: OPENAI_BASE_URL", "", ].join("\n"); -const HERMES_API_KEY_PROVIDER_METADATA = [ - "Name: hermes-provider", - "Type: openai", - "Credential keys: NOUS_API_KEY", - "Config keys: OPENAI_BASE_URL", - "", -].join("\n"); - -const OPENAI_API_PROVIDER_METADATA = [ - "Name: openai-api", - "Type: openai", - "Credential keys: OPENAI_API_KEY", - "Config keys: OPENAI_BASE_URL", - "", -].join("\n"); +const { + run: hermesNativeCommand, + profileJson: HERMES_NATIVE_PROFILE_JSON, + metadata: HERMES_API_KEY_PROVIDER_METADATA, +} = createNativeProviderCommandRuntime("hermes-provider", true); describe("onboard helpers", () => { it("reuses a registered Hermes Provider without re-collecting host credentials", async () => { @@ -61,30 +53,42 @@ describe("onboard helpers", () => { }, async () => { const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: HERMES_OAUTH_PROVIDER_METADATA, stderr: "" } - : undefined, - overrides: { isNonInteractive: () => true }, + runOpenshell: hermesNativeCommand, + overrides: { + isNonInteractive: () => true, + providerAdapter: createNativeSetupProviderAdapter( + "hermes-provider", + true, + "11111111-2222-4333-8444-555555555555", + ), + getSandbox: () => ({ + name: "test-box", + gatewayName: "nemoclaw", + provider: "hermes-provider", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }), + }, }); await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", "hermes-provider", - "https://8.8.8.8/v1", + "https://inference-api.nousresearch.com/v1", "OPENAI_API_KEY", "oauth", ); const commands = harness.commands; - assert.equal(commands.length, 3); + assert.equal(commands.length, 2); assert.equal(commands[0].command, "provider list -g nemoclaw"); - assert.equal(commands[1].command, "provider get -g nemoclaw hermes-provider"); - assert.match( - commands[2].command, - /inference set -g nemoclaw --no-verify --provider hermes-provider/, - ); + assert.equal(commands[1].command, "provider get -g nemoclaw nemoclaw-hermes-provider-v1"); + assert.ok(!commands.some((entry) => entry.command.startsWith("inference set"))); assert.ok(!commands.some((entry) => entry.command.startsWith("gateway select"))); assert.ok(!commands.some((entry) => /provider (create|update)/.test(entry.command))); assert.ok(!commands.some((entry) => entry.env?.NOUS_API_KEY || entry.env?.OPENAI_API_KEY)); @@ -240,6 +244,7 @@ describe("onboard helpers", () => { ); fs.mkdirSync(fakeBin, { recursive: true }); + fs.writeFileSync(inferenceCommandLogPath, ""); writeOkOpenshell(fakeBin, { inferenceRoute: { gatewayName: "nemoclaw", @@ -314,7 +319,6 @@ const prompts = []; const registryUpdates = []; const done = new Error("INFERENCE_STEP_DONE"); let inferenceSessionSnapshot = null; -const hermesApiKeyProviderMetadata = ${JSON.stringify(HERMES_API_KEY_PROVIDER_METADATA)}; delete process.env.NEMOCLAW_NON_INTERACTIVE; delete process.env.NEMOCLAW_SANDBOX_NAME; @@ -338,9 +342,10 @@ try { runner.run = (command, opts = {}) => { const normalized = _n(command); commands.push({ command: normalized, env: opts.env || null }); - const providerGet = "provider get -g nemoclaw hermes-provider"; - if (normalized === providerGet || normalized.endsWith(" " + providerGet)) { - return { status: 0, stdout: hermesApiKeyProviderMetadata, stderr: "" }; + if (normalized.includes("settings get")) return { status: 0, stdout: JSON.stringify({ scope: "global", settings: { providers_v2_enabled: "true" } }), stderr: "" }; + if (normalized.includes("provider profile") && normalized.includes("export")) return { status: 0, stdout: ${JSON.stringify(HERMES_NATIVE_PROFILE_JSON)}, stderr: "" }; + if (normalized.includes("provider get") && normalized.includes("nemoclaw-hermes-provider-v1")) { + return { status: 0, stdout: ${JSON.stringify(HERMES_API_KEY_PROVIDER_METADATA)}, stderr: "" }; } return { status: 0, stdout: "", stderr: "" }; }; @@ -363,10 +368,12 @@ registry.getSandbox = (name) => name === "hermes-resume" ? { name, + gatewayName: "nemoclaw", gpuEnabled: false, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", hermesToolGateways: [], + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-hermes-inference-v1", providerName: "nemoclaw-hermes-provider-v1", providerId: "11111111-2222-4333-8444-555555555555" }, } : null; registry.reserveSandboxInferenceRoute = (name, updates) => { @@ -379,6 +386,7 @@ registry.removeSandbox = () => true; credentials.prompt = async (question) => { prompts.push(String(question)); if (String(question).includes("Sandbox name")) return "hermes-resume"; + if (String(question).includes("Choose [1]")) return "1"; return "yes"; }; @@ -441,7 +449,7 @@ const resumeSession = onboardSession.createSession({ sandboxName: null, provider: "hermes-provider", model: "moonshotai/kimi-k2.6", - endpointUrl: "https://8.8.8.8/v1", + endpointUrl: "https://inference-api.nousresearch.com/v1", credentialEnv: "NOUS_API_KEY", hermesAuthMethod: "api_key", hermesToolGateways: [], @@ -505,17 +513,16 @@ const { onboard } = require(${onboardPath}); }); assert.equal(result.status, 0, result.stderr); - const inferenceCommands = fs.readFileSync(inferenceCommandLogPath, "utf8").trim().split("\n"); - assert.ok( - inferenceCommands.includes("inference get -g nemoclaw"), - `expected a scoped inference read, received ${JSON.stringify(inferenceCommands)}`, - ); + const inferenceCommands = fs + .readFileSync(inferenceCommandLogPath, "utf8") + .trim() + .split("\n") + .filter(Boolean); assert.ok( - inferenceCommands.some((command) => - /inference set -g nemoclaw --no-verify --provider hermes-provider/.test(command), - ), - `expected a scoped asynchronous inference set, received ${JSON.stringify(inferenceCommands)}`, + !inferenceCommands.some((command) => command.startsWith("inference set")), + `native Hermes must not mutate the shared route: ${JSON.stringify(inferenceCommands)}`, ); + assert.deepEqual(inferenceCommands, [], "native resume must not consult the shared route"); assert.doesNotMatch( `${result.stderr}\n${result.stdout}`, /Hermes Provider requires a sandbox name/, @@ -531,6 +538,14 @@ const { onboard } = require(${onboardPath}); payload.prompts.some((question) => question.includes("Sandbox name")), "resume should prompt for the missing sandbox name before Hermes inference reconciliation", ); + assert.ok( + payload.commands.some( + (entry) => entry.command.includes("provider profile") && entry.command.includes("export"), + ), + "resume should reconcile native inference", + ); + assert.ok(!payload.commands.some((entry) => entry.command.includes("inference set"))); + assert.ok(!payload.commands.some((entry) => /provider (create|update)/.test(entry.command))); assert.equal( payload.inferenceSessionSandboxName, @@ -557,36 +572,48 @@ const { onboard } = require(${onboardPath}); }, async () => { const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.join(" ") === "provider get -g nemoclaw hermes-provider" - ? { status: 0, stdout: HERMES_OAUTH_PROVIDER_METADATA, stderr: "" } - : undefined, - overrides: { isNonInteractive: () => true }, + runOpenshell: hermesNativeCommand, + overrides: { + isNonInteractive: () => true, + providerAdapter: createNativeSetupProviderAdapter( + "hermes-provider", + true, + "11111111-2222-4333-8444-555555555555", + ), + getSandbox: () => ({ + name: "test-box", + gatewayName: "nemoclaw", + provider: "hermes-provider", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-hermes-inference-v1", + providerName: "nemoclaw-hermes-provider-v1", + providerId: "11111111-2222-4333-8444-555555555555", + }, + }), + }, }); await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", "hermes-provider", - "https://8.8.8.8/v1", + "https://inference-api.nousresearch.com/v1", "NOUS_API_KEY", "api_key", ); const update = harness.commands.find((entry) => - /provider update -g nemoclaw hermes-provider/.test(entry.command), + /provider update -g nemoclaw nemoclaw-hermes-provider-v1/.test(entry.command), ); assert.ok(update); - assert.match(update.command, /--credential NOUS_API_KEY/); - assert.equal(update.env?.NOUS_API_KEY, "nous-host-secret"); + assert.match(update.command, /--credential OPENAI_API_KEY/); + assert.equal(update.env?.OPENAI_API_KEY, "nous-host-secret"); assert.ok( !harness.commands.some((entry) => /nous-host-secret/.test(entry.command)), "shell credential value must not appear in argv", ); - assert.match( - harness.commands.at(-1)?.command || "", - /inference set -g nemoclaw --no-verify --provider hermes-provider/, - ); + assert.ok(!harness.commands.some((entry) => entry.command.startsWith("inference set"))); }, ); }); @@ -929,15 +956,10 @@ const { isOpenclawReady } = require(${onboardPath}); } }); - it("uses native Anthropic provider creation without embedding the secret in argv", async () => { + it("creates the native Anthropic profile provider without changing the shared route", async () => { await withProcessEnv({ ANTHROPIC_API_KEY: "sk-ant-TEST-NOT-A-REAL-VALUE" }, async () => { - const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 1, stdout: "", stderr: "" } - : undefined, - }); - + const providerAdapter = createNativeSetupProviderAdapter("anthropic-prod", false); + const harness = createDirectSetupInferenceHarness({ overrides: { providerAdapter } }); await harness.setupInference( "test-box", "claude-sonnet-4-5", @@ -945,52 +967,62 @@ const { isOpenclawReady } = require(${onboardPath}); "https://api.anthropic.com", "ANTHROPIC_API_KEY", ); - - const commands = harness.commands; - assert.equal(commands.length, 3); - assert.match(commands[0].command, /^provider get -g nemoclaw /); - assert.match(commands[1].command, /^provider create -g nemoclaw /); - assert.match(commands[1].command, /--type anthropic/); - assert.match(commands[1].command, /--credential ANTHROPIC_API_KEY/); - assert.doesNotMatch(commands[1].command, /sk-ant-TEST-NOT-A-REAL-VALUE/); - assert.match(commands[2].command, /^inference set -g nemoclaw /); - assert.match(commands[2].command, /--provider anthropic-prod/); + expect(providerAdapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + name: "nemoclaw-anthropic-prod-v1", + type: "nemoclaw-anthropic-inference-v1", + credentials: [{ name: "ANTHROPIC_API_KEY", value: "sk-ant-TEST-NOT-A-REAL-VALUE" }], + config: [], + }), + ); + expect(harness.commands).toEqual([]); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + nativeHostedProviderAttachment: expect.objectContaining({ + providerId: "fixture-native-id", + }), + }), + ); }); }); it("updates OpenAI-compatible providers without passing an unsupported --type flag", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" } + ? { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" } : undefined, }); await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, ); const commands = harness.commands; assert.equal(commands.length, 3); assert.match(commands[0].command, /^provider get -g nemoclaw /); - assert.match(commands[1].command, /^provider update -g nemoclaw openai-api/); + assert.match(commands[1].command, /^provider update -g nemoclaw compatible-endpoint/); assert.doesNotMatch(commands[1].command, /--type/); assert.match(commands[2].command, /^inference set -g nemoclaw --no-verify/); }); }); it("re-prompts for credentials when openshell inference set fails with authorization errors", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-bad" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-bad" }, async () => { const commandRouter = createDirectCommandRouter([ { name: "provider-get", matches: (command) => command.startsWith("provider get"), results: [ - { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }, - { status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }, + { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" }, + { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" }, ], }, { @@ -1003,7 +1035,7 @@ const { isOpenclawReady } = require(${onboardPath}); runOpenshell: commandRouter.runOpenshell, overrides: { promptValidationRecovery: async () => { - process.env.OPENAI_API_KEY = "sk-good"; + process.env.COMPATIBLE_API_KEY = "sk-good"; return "retry"; }, }, @@ -1013,30 +1045,33 @@ const { isOpenclawReady } = require(${onboardPath}); await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, ); } finally { error.mockRestore(); } - assert.equal(process.env.OPENAI_API_KEY, "sk-good"); + assert.equal(process.env.COMPATIBLE_API_KEY, "sk-good"); assert.equal(commandRouter.callCount("inference-set"), 2); const providerEnvs = harness.commands .filter((entry) => entry.command.includes("provider")) - .map((entry) => entry.env?.OPENAI_API_KEY) + .map((entry) => entry.env?.COMPATIBLE_API_KEY) .filter(Boolean); assert.deepEqual(providerEnvs, ["sk-bad", "sk-good"]); }); }); it("returns control to provider selection when inference apply recovery chooses back", async () => { - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const commandRouter = createDirectCommandRouter([ { name: "provider-get", matches: (command) => command.startsWith("provider get"), - results: [{ status: 0, stdout: OPENAI_API_PROVIDER_METADATA, stderr: "" }], + results: [{ status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" }], }, { name: "inference-set", @@ -1054,9 +1089,12 @@ const { isOpenclawReady } = require(${onboardPath}); result = await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", - "https://api.openai.com/v1", - "OPENAI_API_KEY", + "compatible-endpoint", + "https://api.example.test/v1", + "COMPATIBLE_API_KEY", + null, + [], + { preferredInferenceApi: "openai-completions" }, ); } finally { error.mockRestore(); @@ -1432,6 +1470,7 @@ describe("re-onboard Ollama GPU release (#9110)", () => { expect(events).toEqual([ "lock-enter", "read-prior-route", + "read-prior-route", "ownership-lock-enter", "peer-scan", "unload", diff --git a/test/onboarding/onboard-installer-restore-intent.test.ts b/test/onboarding/onboard-installer-restore-intent.test.ts index b67993f3b5d..f3a8fe73701 100644 --- a/test/onboarding/onboard-installer-restore-intent.test.ts +++ b/test/onboarding/onboard-installer-restore-intent.test.ts @@ -122,6 +122,7 @@ const sourceEntry = fixtureMocks.sandboxLifecycleFixture({ toolDisclosure: "progressive", }); const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-messaging-reuse.test.ts b/test/onboarding/onboard-messaging-reuse.test.ts new file mode 100644 index 00000000000..eef952e3d94 --- /dev/null +++ b/test/onboarding/onboard-messaging-reuse.test.ts @@ -0,0 +1,126 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { beforeEach, describe, it, vi } from "vitest"; +import { parseMessagingFixturePayload as parseStdoutJson } from "../helpers/messaging-plan-fixtures"; +import { runBoundedOnboardScriptAsync } from "../helpers/onboard-child-process-harness"; +import { writeOkOpenshell } from "../helpers/onboard-openshell-fixture"; + +type CommandEntry = { command: string }; +const repoRoot = path.join(import.meta.dirname, "../.."); +const onboardScriptMocksPath = JSON.stringify( + path.join(repoRoot, "test", "helpers", "onboard-script-mocks.cjs"), +); +beforeEach(() => { + vi.stubEnv("NEMOCLAW_TEST_MANAGED_IMAGE_CATALOG", "1"); + vi.stubEnv("NEMOCLAW_TEST_FORWARD_SERVICE_FIXTURE", "1"); + vi.stubEnv("NEMOCLAW_SANDBOX_PREBUILD", "1"); +}); +describe("onboard messaging reuse", () => { + it.sequential( + "reuses sandbox without refreshing unselected ambient messaging providers (#10277)", + { + timeout: 60_000, + }, + async (context) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-reuse-providers-")); + const fakeBin = path.join(tmpDir, "bin"); + const scriptPath = path.join(tmpDir, "reuse-with-providers.js"); + const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); + const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); + const registryPath = JSON.stringify( + path.join(repoRoot, "src", "lib", "state", "registry.ts"), + ); + + fs.mkdirSync(fakeBin, { recursive: true }); + writeOkOpenshell(fakeBin); + + const script = String.raw` +const runner = require(${runnerPath}); +const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); +const registry = require(${registryPath}); +const fixtureMocks = require(${onboardScriptMocksPath}); + +// This test owns a simulated standalone gateway, not the host service installation. +fixtureMocks.mockStandaloneGatewayTeardownAuthority(); +const commands = []; +const existingSandbox = fixtureMocks.createCreatedSandboxFixture({ lifecycleState: "created" }); existingSandbox.installRuntimeObservation(); +const messagingProviderRunner = require(${onboardScriptMocksPath}).createStatefulMessagingProviderRunner({ + commands, + createdSandbox: existingSandbox, + initialProviders: [ + ["my-assistant-discord-bridge", "nemoclaw-mcp-v1", "DISCORD_BOT_TOKEN"], + ["my-assistant-slack-bridge", "nemoclaw-mcp-v1", "SLACK_BOT_TOKEN"], + ["my-assistant-slack-app", "nemoclaw-mcp-v1", "SLACK_APP_TOKEN"], + ], +}); +runner.run = messagingProviderRunner; +runner.runCapture = (command) => { + const sandboxCapture = existingSandbox.capture(command); + if (sandboxCapture !== null) return sandboxCapture; + // All messaging providers already exist in gateway + if (_n(command).includes("provider get")) return "Provider: exists"; + if (_n(command).includes("forward list")) return "SANDBOX BIND PORT PID STATUS"; + return ""; +}; +registry.getSandbox = () => fixtureMocks.sandboxLifecycleFixture( + { name: "my-assistant", toolDisclosure: "progressive" }, + { sandboxId: existingSandbox.state.sandboxId }, +); +const { createSandbox } = require(${onboardPath}); + +(async () => { + process.env.OPENSHELL_GATEWAY = "nemoclaw"; + process.env.DISCORD_BOT_TOKEN = "test-discord-token"; + process.env.SLACK_BOT_TOKEN = "xoxb-test-slack-token"; + process.env.SLACK_APP_TOKEN = "xapp-test-slack-token"; + const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); + console.log(JSON.stringify({ sandboxName, commands })); +})().catch((error) => { + console.error(error); + process.exit(1); +}); +`; + fs.writeFileSync(scriptPath, script); + + const result = await runBoundedOnboardScriptAsync(scriptPath, { + context, + env: { + ...process.env, + HOME: tmpDir, + PATH: `${fakeBin}:${process.env.PATH || ""}`, + NEMOCLAW_NON_INTERACTIVE: "1", + }, + }); + + assert.equal(result.status, 0, result.stderr); + const payload = parseStdoutJson(result.stdout); + + assert.equal(payload.sandboxName, "my-assistant", "should reuse existing sandbox"); + assert.ok( + payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox create")), + "should NOT recreate sandbox when providers already exist in gateway", + ); + assert.ok( + payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox delete")), + "should NOT delete sandbox when providers already exist in gateway", + ); + + // Existing gateway providers do not select messaging for this onboarding request. + const providerUpserts = payload.commands.filter((entry: CommandEntry) => + /provider (?:create|update|delete)\b.*my-assistant-(?:discord-bridge|slack-bridge|slack-app)\b/u.test( + entry.command, + ), + ); + assert.equal( + providerUpserts.length, + 0, + "should not refresh ambient messaging providers without a selected channel plan", + ); + }, + ); +}); diff --git a/test/onboarding/onboard-messaging.test.ts b/test/onboarding/onboard-messaging.test.ts index 92871d0b571..66ba4ad33a7 100644 --- a/test/onboarding/onboard-messaging.test.ts +++ b/test/onboarding/onboard-messaging.test.ts @@ -81,7 +81,7 @@ const { EventEmitter } = require("node:events"); const fs = require("node:fs"); const commands = []; const createdSandbox = fixtureMocks.createCreatedSandboxFixture({ sandboxName: "my-assistant" }); createdSandbox.installRuntimeObservation(); -runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox }); +runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox, nativeNvidiaProvider: true }); runner.runCapture = (command) => { const sandboxCapture = createdSandbox.capture(command); if (sandboxCapture !== null) return sandboxCapture; @@ -100,6 +100,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -355,7 +356,7 @@ const nonSlackMessagingEnvKeys = [ const commands = []; let registeredSandbox = null; const createdSandbox = fixtureMocks.createCreatedSandboxFixture({ sandboxName: "my-assistant" }); createdSandbox.installRuntimeObservation(); -runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox }); +runner.run = fixtureMocks.createStatefulMessagingProviderRunner({ commands, createdSandbox, nativeNvidiaProvider: true }); runner.runCapture = (command) => { const sandboxCapture = createdSandbox.capture(command); if (sandboxCapture !== null) return sandboxCapture; @@ -376,6 +377,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -728,6 +730,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -887,6 +890,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1056,6 +1060,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1235,105 +1240,6 @@ const { createSandbox } = require(${onboardPath}); }, ); - it.sequential( - "reuses sandbox without refreshing unselected ambient messaging providers (#10277)", - { - timeout: 60_000, - }, - async (context) => { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-onboard-reuse-providers-")); - const fakeBin = path.join(tmpDir, "bin"); - const scriptPath = path.join(tmpDir, "reuse-with-providers.js"); - const onboardPath = JSON.stringify(path.join(repoRoot, "src", "lib", "onboard.ts")); - const runnerPath = JSON.stringify(path.join(repoRoot, "src", "lib", "runner.ts")); - const registryPath = JSON.stringify( - path.join(repoRoot, "src", "lib", "state", "registry.ts"), - ); - - fs.mkdirSync(fakeBin, { recursive: true }); - writeOkOpenshell(fakeBin); - - const script = String.raw` -const runner = require(${runnerPath}); -const _n = (c) => (Array.isArray(c) ? c.join(" ") : String(c)).replace(/'/g, ""); -const registry = require(${registryPath}); -const fixtureMocks = require(${onboardScriptMocksPath}); - -const commands = []; -const existingSandbox = fixtureMocks.createCreatedSandboxFixture({ lifecycleState: "created" }); existingSandbox.installRuntimeObservation(); -const messagingProviderRunner = require(${onboardScriptMocksPath}).createStatefulMessagingProviderRunner({ - commands, - createdSandbox: existingSandbox, - initialProviders: [ - ["my-assistant-discord-bridge", "nemoclaw-mcp-v1", "DISCORD_BOT_TOKEN"], - ["my-assistant-slack-bridge", "nemoclaw-mcp-v1", "SLACK_BOT_TOKEN"], - ["my-assistant-slack-app", "nemoclaw-mcp-v1", "SLACK_APP_TOKEN"], - ], -}); -runner.run = messagingProviderRunner; -runner.runCapture = (command) => { - const sandboxCapture = existingSandbox.capture(command); - if (sandboxCapture !== null) return sandboxCapture; - // All messaging providers already exist in gateway - if (_n(command).includes("provider get")) return "Provider: exists"; - if (_n(command).includes("forward list")) return "SANDBOX BIND PORT PID STATUS"; - return ""; -}; -registry.getSandbox = () => fixtureMocks.sandboxLifecycleFixture( - { name: "my-assistant", toolDisclosure: "progressive" }, - { sandboxId: existingSandbox.state.sandboxId }, -); -const { createSandbox } = require(${onboardPath}); - -(async () => { - process.env.OPENSHELL_GATEWAY = "nemoclaw"; - process.env.DISCORD_BOT_TOKEN = "test-discord-token"; - process.env.SLACK_BOT_TOKEN = "xoxb-test-slack-token"; - process.env.SLACK_APP_TOKEN = "xapp-test-slack-token"; - const sandboxName = await createSandbox(null, "gpt-5.4", "nvidia-prod", null, "my-assistant"); - console.log(JSON.stringify({ sandboxName, commands })); -})().catch((error) => { - console.error(error); - process.exit(1); -}); -`; - fs.writeFileSync(scriptPath, script); - - const result = await runBoundedOnboardScriptAsync(scriptPath, { - context, - env: { - ...process.env, - HOME: tmpDir, - PATH: `${fakeBin}:${process.env.PATH || ""}`, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - }); - - assert.equal(result.status, 0, result.stderr); - const payload = parseStdoutJson(result.stdout); - - assert.equal(payload.sandboxName, "my-assistant", "should reuse existing sandbox"); - assert.ok( - payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox create")), - "should NOT recreate sandbox when providers already exist in gateway", - ); - assert.ok( - payload.commands.every((entry: CommandEntry) => !entry.command.includes("sandbox delete")), - "should NOT delete sandbox when providers already exist in gateway", - ); - - // Existing gateway providers do not select messaging for this onboarding request. - const providerUpserts = payload.commands.filter((entry: CommandEntry) => - entry.command.includes("provider update"), - ); - assert.equal( - providerUpserts.length, - 0, - "should not refresh ambient messaging providers without a selected channel plan", - ); - }, - ); - it( "filters messaging providers to only enabledChannels when provided", { @@ -1375,6 +1281,7 @@ const createdSandbox = fixtureMocks.createCreatedSandboxFixture(); createdSandbo runner.run = require(${onboardScriptMocksPath}).createStatefulMessagingProviderRunner({ commands, createdSandbox, + nativeNvidiaProvider: true, }); runner.runCapture = (command) => { const createdIdentity = createdSandbox.capture(command); @@ -1391,6 +1298,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1531,6 +1439,7 @@ registry.updateSandbox = () => true; registry.setDefault = () => true; registry.removeSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-openrouter-inference.test.ts b/test/onboarding/onboard-openrouter-inference.test.ts index fbd0bdcf340..676639e1af2 100644 --- a/test/onboarding/onboard-openrouter-inference.test.ts +++ b/test/onboarding/onboard-openrouter-inference.test.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import assert from "node:assert/strict"; import { describe, expect, it, vi } from "vitest"; +import { createNativeSetupProviderAdapter } from "../helpers/onboard-split-context"; import type { SetupInference, SetupInferenceDeps } from "../../src/lib/onboard/setup-inference.js"; import { createDirectSetupInferenceHarnessFactory, @@ -18,35 +18,18 @@ const openrouterRuntimeOnboard = const createDirectSetupInferenceHarness = createDirectSetupInferenceHarnessFactory( onboard.createSetupInference, ); -const OPENROUTER_PROVIDER_METADATA = - "Name: openrouter-api\nType: openai\nCredential keys: OPENROUTER_API_KEY\nConfig keys: OPENAI_BASE_URL\n"; - describe("OpenRouter onboarding inference setup", () => { - it("configures OpenRouter through the runtime header adapter (#5826)", async () => { + it("configures fixed OpenRouter without the runtime header adapter (#12589)", async () => { await withProcessEnv({ OPENROUTER_API_KEY: "sk-or-test" }, async () => { - const ensureAdapter = vi.fn(async () => ({ - baseUrl: "http://host.openshell.internal:11437/v1", - localBaseUrl: "http://127.0.0.1:11437/v1", - credentialEnv: "OPENROUTER_API_KEY", - logPath: "/tmp/openrouter-runtime-adapter.log", - })); - const setupOpenRouterRuntimeInference = - openrouterRuntimeOnboard.setupOpenRouterRuntimeInference; + const providerAdapter = createNativeSetupProviderAdapter("openrouter-api", false); + const setupOpenRouterRuntimeInference = vi.fn(async () => ({ handled: false as const })); const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: OPENROUTER_PROVIDER_METADATA } - : undefined, overrides: { isNonInteractive: () => true, - openrouterRuntimeOnboard: { - setupOpenRouterRuntimeInference: ( - input: Parameters[0], - ) => setupOpenRouterRuntimeInference({ ...input, ensureAdapter }), - }, + providerAdapter, + openrouterRuntimeOnboard: { setupOpenRouterRuntimeInference }, }, }); - await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", @@ -54,36 +37,39 @@ describe("OpenRouter onboarding inference setup", () => { "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY", ); - - expect(ensureAdapter).toHaveBeenCalledWith({ authorizationToken: "sk-or-test" }); - const commands = harness.commands.map(({ command }) => command); - expect(commands).toEqual([ - "provider get -g nemoclaw openrouter-api", - "provider update -g nemoclaw openrouter-api --credential OPENROUTER_API_KEY --config OPENAI_BASE_URL=http://host.openshell.internal:11437/v1", - "inference set -g nemoclaw --no-verify --provider openrouter-api --model moonshotai/kimi-k2.6 --timeout 180", - ]); - assert.equal(harness.commands[1].env?.OPENROUTER_API_KEY, "sk-or-test"); - assert.ok( - !commands.some((command) => command.includes("sk-or-test")), - "OpenRouter key must not appear in argv", + expect(providerAdapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + name: "nemoclaw-openrouter-api-v1", + type: "nemoclaw-openrouter-inference-v1", + credentials: [{ name: "OPENROUTER_API_KEY", value: "sk-or-test" }], + config: [], + }), ); - expect(harness.verifyInferenceRoute).toHaveBeenCalledWith( - "nemoclaw", - "openrouter-api", - "moonshotai/kimi-k2.6", + expect(setupOpenRouterRuntimeInference).not.toHaveBeenCalled(); + expect(harness.commands).toEqual([]); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); + expect(harness.verifyOnboardInferenceSmoke).toHaveBeenCalledWith( + expect.objectContaining({ + provider: "openrouter-api", + model: "moonshotai/kimi-k2.6", + endpointUrl: "https://openrouter.ai/api/v1", + credentialEnv: "OPENROUTER_API_KEY", + }), ); - expect(harness.verifyOnboardInferenceSmoke).toHaveBeenCalledWith({ - provider: "openrouter-api", - model: "moonshotai/kimi-k2.6", - endpointUrl: "http://127.0.0.1:11437/v1", - credentialEnv: "OPENROUTER_API_KEY", - forceOpenAiLike: true, - }); - assert.deepEqual(harness.errors, []); - assert.deepEqual(harness.logs, [ - " OpenRouter Runtime adapter ready: sandbox route http://host.openshell.internal:11437/v1, host log /tmp/openrouter-runtime-adapter.log", - " ✓ Inference route set: openrouter-api / moonshotai/kimi-k2.6", - ]); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + provider: "openrouter-api", + endpointUrl: "https://openrouter.ai/api/v1", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "fixture-native-id", + }, + }), + ); + expect(harness.errors).toEqual([]); }); }); @@ -183,31 +169,28 @@ describe("OpenRouter onboarding inference setup", () => { expect(log).not.toHaveBeenCalledWith(expect.stringContaining("Inference route set")); }); - it("updates OpenRouter adapter config while reusing a gateway-held credential (#5826)", async () => { + it("reuses the gateway-held native OpenRouter credential without updating it (#12589)", async () => { await withProcessEnv({ OPENROUTER_API_KEY: undefined }, async () => { - const ensureAdapter = vi.fn(async () => ({ - baseUrl: "http://host.openshell.internal:11437/v1", - localBaseUrl: "http://127.0.0.1:11437/v1", - credentialEnv: "OPENROUTER_API_KEY", - logPath: "/tmp/openrouter-runtime-adapter.log", - })); - const setupOpenRouterRuntimeInference = - openrouterRuntimeOnboard.setupOpenRouterRuntimeInference; + const providerAdapter = createNativeSetupProviderAdapter("openrouter-api"); + const setupOpenRouterRuntimeInference = vi.fn(async () => ({ handled: false as const })); const harness = createDirectSetupInferenceHarness({ - runOpenshell: (args) => - args.slice(0, 2).join(" ") === "provider get" - ? { status: 0, stdout: OPENROUTER_PROVIDER_METADATA } - : undefined, overrides: { isNonInteractive: () => true, - openrouterRuntimeOnboard: { - setupOpenRouterRuntimeInference: ( - input: Parameters[0], - ) => setupOpenRouterRuntimeInference({ ...input, ensureAdapter }), - }, + providerAdapter, + getSandbox: () => ({ + name: "test-box", + gatewayName: "nemoclaw", + provider: "openrouter-api", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "fixture-native-id", + }, + }), + openrouterRuntimeOnboard: { setupOpenRouterRuntimeInference }, }, }); - await harness.setupInference( "test-box", "moonshotai/kimi-k2.6", @@ -221,20 +204,26 @@ describe("OpenRouter onboarding inference setup", () => { skipHostInferenceSmoke: true, }, ); - - expect(ensureAdapter).toHaveBeenCalledWith({ authorizationToken: null }); - expect(harness.commands.map(({ command }) => command)).toEqual([ - "provider get -g nemoclaw openrouter-api", - "provider update -g nemoclaw openrouter-api --config OPENAI_BASE_URL=http://host.openshell.internal:11437/v1", - "inference set -g nemoclaw --no-verify --provider openrouter-api --model moonshotai/kimi-k2.6 --timeout 180", - ]); - expect(harness.commands[2].env?.OPENROUTER_API_KEY).toBeUndefined(); + expect(providerAdapter.getProvider).toHaveBeenCalledWith( + expect.objectContaining({ providerName: "nemoclaw-openrouter-api-v1" }), + ); + expect(providerAdapter.createProvider).not.toHaveBeenCalled(); + expect(providerAdapter.updateProvider).not.toHaveBeenCalled(); + expect(setupOpenRouterRuntimeInference).not.toHaveBeenCalled(); + expect(harness.commands).toEqual([]); + expect(harness.verifyInferenceRoute).not.toHaveBeenCalled(); expect(harness.verifyOnboardInferenceSmoke).not.toHaveBeenCalled(); - expect(harness.logs).toEqual([ - " OpenRouter Runtime adapter ready: sandbox route http://host.openshell.internal:11437/v1, host log /tmp/openrouter-runtime-adapter.log", - " Reusing existing gateway credential; skipping host inference smoke.", - " ✓ Inference route set: openrouter-api / moonshotai/kimi-k2.6", - ]); + expect(harness.updateSandbox).toHaveBeenCalledWith( + "test-box", + expect.objectContaining({ + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: "nemoclaw-openrouter-inference-v1", + providerName: "nemoclaw-openrouter-api-v1", + providerId: "fixture-native-id", + }, + }), + ); expect(harness.errors).toEqual([]); }); }); diff --git a/test/onboarding/onboard-prepared-build-context.test.ts b/test/onboarding/onboard-prepared-build-context.test.ts index 65f8354510c..26c6bae1e97 100644 --- a/test/onboarding/onboard-prepared-build-context.test.ts +++ b/test/onboarding/onboard-prepared-build-context.test.ts @@ -91,6 +91,7 @@ createdSandbox.installRuntimeObservation(); const commands = []; const registerCalls = []; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName, provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b", diff --git a/test/onboarding/onboard-reservation-recreate.test.ts b/test/onboarding/onboard-reservation-recreate.test.ts index d6e597d8aff..d732abfe261 100644 --- a/test/onboarding/onboard-reservation-recreate.test.ts +++ b/test/onboarding/onboard-reservation-recreate.test.ts @@ -228,6 +228,7 @@ const removeSandbox = (name) => { }; registry.removeSandbox = removeSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -480,6 +481,7 @@ if (mode === "seed") { } const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: null, model: null, diff --git a/test/onboarding/onboard-sandbox-build.test.ts b/test/onboarding/onboard-sandbox-build.test.ts index 33a7788adcc..8b9734785a6 100644 --- a/test/onboarding/onboard-sandbox-build.test.ts +++ b/test/onboarding/onboard-sandbox-build.test.ts @@ -129,6 +129,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -386,6 +387,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "hermes-sandbox", provider: "nvidia-prod", model: "gpt-5.4", @@ -607,6 +609,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -724,6 +727,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -844,6 +848,7 @@ runner.runCapture = (command) => { return ""; }; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-sandbox-recreation.test.ts b/test/onboarding/onboard-sandbox-recreation.test.ts index f402cd84175..b2e994d87e9 100644 --- a/test/onboarding/onboard-sandbox-recreation.test.ts +++ b/test/onboarding/onboard-sandbox-recreation.test.ts @@ -193,6 +193,7 @@ runner.run = (command, opts = {}) => { const getSandbox = () => registeredSandbox || sourceSandbox; registry.getSandbox = getSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -366,6 +367,7 @@ runner.run = (command) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -550,6 +552,7 @@ runner.run = (command) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -711,6 +714,7 @@ runner.run = (command) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1069,6 +1073,7 @@ runner.runFile = (file, args = [], opts = {}) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", @@ -1230,6 +1235,7 @@ runner.run = (command, opts = {}) => { }, { sandboxId: createdSandbox.state.sandboxId }); registry.getSandbox = () => sourceSandbox; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard-terminal-dashboard.test.ts b/test/onboarding/onboard-terminal-dashboard.test.ts index 00ade5e9a3d..175b2403c7f 100644 --- a/test/onboarding/onboard-terminal-dashboard.test.ts +++ b/test/onboarding/onboard-terminal-dashboard.test.ts @@ -188,7 +188,7 @@ registry.getSandbox = () => name: sandboxName, gpuEnabled: false, agent: "langchain-deepagents-code", - nativeNvidiaProviderAttachment: { + nativeHostedProviderAttachment: { schemaVersion: 1, profileId: "nemoclaw-nvidia-inference-v1", providerName: "nemoclaw-nvidia-prod-v1", @@ -212,6 +212,7 @@ registry.removeSandbox = () => true; const createFixture = scenario === "create" ? fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName, provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index 3933eb71b99..32618ddc620 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -668,26 +668,28 @@ startGateway(null).catch((error) => { assert.equal(evidence.parentCredentialUnchanged, true); }); - it("uses the OpenShell 0.0.116 provider path without a compatibility-profile mutation", () => { + it("keeps the custom OpenShell 0.0.116 provider path without a compatibility-profile mutation", () => { const { commands } = runProductionSetupInferenceCredentialBoundary({ - credentialEnv: "OPENAI_API_KEY", + preferredInferenceApi: "openai-completions", + credentialEnv: "COMPATIBLE_API_KEY", credentialValue: "sk-TEST-NOT-A-REAL-VALUE", endpointUrl: "https://api.openai.com/v1", model: "gpt-5.4", - provider: "openai-api", + provider: "compatible-endpoint", }); const commandSequence = commands.map(({ argv }) => argv.join(" ")); assert.equal(commandSequence[0], "inference get -g nemoclaw"); - assert.equal(commandSequence[1], "provider get -g nemoclaw openai-api"); + assert.equal(commandSequence[1], "provider get -g nemoclaw compatible-endpoint"); + assert.ok( commandSequence.some((command) => - /^provider update -g nemoclaw openai-api(?: |$)/.test(command), + /^provider update -g nemoclaw compatible-endpoint(?: |$)/.test(command), ), ); assert.ok( commandSequence.some((command) => - /^inference set -g nemoclaw --no-verify --provider openai-api --model gpt-5\.4(?: |$)/.test( + /^inference set -g nemoclaw --no-verify --provider compatible-endpoint --model gpt-5\.4(?: |$)/.test( command, ), ), @@ -840,19 +842,19 @@ const { createSandbox } = require(${onboardPath}); ok: true, value: { state: "configured", - route: { provider: "openai-api", model: "gpt-5.4" }, + route: { provider: "compatible-endpoint", model: "gpt-5.4" }, }, }), }); - await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { + await withProcessEnv({ COMPATIBLE_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { status: 0, stdout: - "Name: openai-api\nType: openai\nCredential keys: OPENAI_API_KEY\nConfig keys: OPENAI_BASE_URL\n", + "Name: compatible-endpoint\nType: openai\nCredential keys: COMPATIBLE_API_KEY\nConfig keys: OPENAI_BASE_URL\n", stderr: "", } : undefined, @@ -862,12 +864,12 @@ const { createSandbox } = require(${onboardPath}); await harness.setupInference( "test-box", "gpt-5.4", - "openai-api", + "compatible-endpoint", "https://api.openai.com/v1", - "OPENAI_API_KEY", + "COMPATIBLE_API_KEY", ); - assert.equal(harness.commands[0].command, "provider get -g nemoclaw openai-api"); + assert.equal(harness.commands[0].command, "provider get -g nemoclaw compatible-endpoint"); assert.equal(harness.commands.length, 3); }); }); diff --git a/test/package-contract/cli/credentials-cli-command.test.ts b/test/package-contract/cli/credentials-cli-command.test.ts index 702a58f0802..9b7d18487b8 100644 --- a/test/package-contract/cli/credentials-cli-command.test.ts +++ b/test/package-contract/cli/credentials-cli-command.test.ts @@ -336,7 +336,7 @@ describe("credentials oclif commands", () => { expect(runOpenshell).not.toHaveBeenCalled(); }); - it("deletes a provider credential with --yes", async () => { + it("deletes only the explicit native NVIDIA provider credential with --yes", async () => { const calls = installRuntimeBridge({ runOpenshell: (args, opts) => { calls.push({ args, opts }); @@ -345,11 +345,13 @@ describe("credentials oclif commands", () => { }); const { CredentialsResetCommand } = loadCommands(); - const output = await captureOutput(() => CredentialsResetCommand.run(["nvidia-prod", "--yes"])); + const output = await captureOutput(() => + CredentialsResetCommand.run(["nemoclaw-nvidia-prod-v1", "--yes"]), + ); - expect(calls).toEqual([ - { - args: ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + expect(calls).toEqual( + ["nemoclaw-nvidia-prod-v1"].map((providerName) => ({ + args: ["provider", "delete", "-g", "nemoclaw", providerName], opts: { env: expect.any(Object), ignoreError: true, @@ -358,12 +360,51 @@ describe("credentials oclif commands", () => { suppressOutput: true, timeout: 30_000, }, - }, - ]); + })), + ); expect(output.stdout).toContain("Removed provider 'nvidia-prod'"); expect(output.stdout).toContain("Rerun 'nemoclaw onboard'"); }); + it.each(["present", "absent"])( + "checks the legacy identity before logical reset when %s", + async (state) => { + const responses = [ + state === "absent" + ? { status: 1, stderr: "Error: provider 'nvidia-prod' not found" } + : { + status: 0, + stdout: + "Name: nvidia-prod\nId: 11111111-2222-4333-8444-555555555555\nType: nvidia\nResource version: 7\nCredential keys: NVIDIA_API_KEY\nConfig keys: ", + }, + { status: 0 }, + ]; + const calls = installRuntimeBridge({ + runOpenshell: (args, opts) => { + calls.push({ args, opts }); + return responses.shift()!; + }, + }); + const { CredentialsResetCommand } = loadCommands(); + const output = await captureOutput(() => + state === "present" + ? expectExitCode(() => CredentialsResetCommand.run(["nvidia-prod", "--yes"]), 1) + : CredentialsResetCommand.run(["nvidia-prod", "--yes"]), + ); + expect(calls.map((call) => call.args)).toEqual( + state === "present" + ? [["provider", "get", "-g", "nemoclaw", "nvidia-prod"]] + : [ + ["provider", "get", "-g", "nemoclaw", "nvidia-prod"], + ["provider", "delete", "-g", "nemoclaw", "nemoclaw-nvidia-prod-v1"], + ], + ); + expect(state === "present" ? output.stderr : output.stdout).toContain( + state === "present" ? "ownership conflict" : "Removed provider 'nvidia-prod'", + ); + }, + ); + it("rejects per-sandbox messaging bridge names for credential reset", async () => { installRuntimeBridge(); const { CredentialsResetCommand } = loadCommands(); diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts index a98fde899aa..6d7766c5c09 100644 --- a/test/repository/vitest-watch-triggers.test.ts +++ b/test/repository/vitest-watch-triggers.test.ts @@ -122,6 +122,7 @@ describe("Vitest opaque-input watch triggers", () => { "test/onboarding/onboard-extra-provider-reconciliation.test.ts", "test/onboarding/onboard-fresh-create-identity.test.ts", "test/onboarding/onboard-installer-restore-intent.test.ts", + "test/onboarding/onboard-messaging-reuse.test.ts", "test/onboarding/onboard-messaging.test.ts", "test/onboarding/onboard-prepared-build-context.test.ts", "test/onboarding/onboard-reservation-recreate.test.ts", diff --git a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts index 9a8bdbf7fda..355c78b9580 100644 --- a/test/runtime/gateway/gateway-state-reconcile-2276.test.ts +++ b/test/runtime/gateway/gateway-state-reconcile-2276.test.ts @@ -186,8 +186,12 @@ if (args[0] === "inference" && args[1] === "get") { } if (args[0] === "provider" && args[1] === "get") { - process.stdout.write("Name: nvidia-prod\\nType: nvidia\\nCredential keys: NVIDIA_INFERENCE_API_KEY\\nConfig keys: \\n"); - process.exit(0); + if (args.at(-1) === "nvidia-prod") { + process.stdout.write("Name: nvidia-prod\\nType: openai\\nId: 11111111-2222-4333-8444-555555555555\\nResource version: 1\\nCredential keys: NVIDIA_INFERENCE_API_KEY\\nConfig keys: OPENAI_BASE_URL\\n"); + process.exit(0); + } + process.stderr.write("Error: provider '" + args.at(-1) + "' not found\\n"); + process.exit(1); } if (args[0] === "provider" && args[1] === "list") { @@ -195,6 +199,14 @@ if (args[0] === "provider" && args[1] === "list") { process.exit(0); } +if (args[0] === "settings" && args[1] === "get") { + process.stdout.write(JSON.stringify({ + scope: "global", + settings: { providers_v2_enabled: "true" }, + })); + process.exit(0); +} + if (args.includes("forward") && args.includes("list")) { process.stderr.write("No active forwards.\\n"); process.exit(0); diff --git a/test/runtime/gateway/recover-port-forward.test.ts b/test/runtime/gateway/recover-port-forward.test.ts index a20102341f6..b1bae917ab6 100644 --- a/test/runtime/gateway/recover-port-forward.test.ts +++ b/test/runtime/gateway/recover-port-forward.test.ts @@ -149,7 +149,7 @@ async function setupFixture(opts: { name: sandboxName, ...launchReadinessRegistryFixture(), model: "nvidia/test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, dashboardPort: Number(port), }, @@ -316,7 +316,7 @@ if (args[0] === "policy" && args[1] === "get") { if (args[0] === "inference" && args[1] === "get") { process.stdout.write( - "Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n", + "Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n", ); process.exit(0); } diff --git a/test/runtime/sandbox/reboot-identity-drift.test.ts b/test/runtime/sandbox/reboot-identity-drift.test.ts index f0b03ccee7a..d840f640a88 100644 --- a/test/runtime/sandbox/reboot-identity-drift.test.ts +++ b/test/runtime/sandbox/reboot-identity-drift.test.ts @@ -51,7 +51,7 @@ function setupFixture(sandboxName: string, mode: "healthy" | "identity_drift" | [sandboxName]: { name: sandboxName, model: "nvidia/test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, @@ -139,7 +139,7 @@ if (args[0] === "policy" && args[1] === "get") { } if (args[0] === "inference" && args[1] === "get") { - process.stdout.write("Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n"); + process.stdout.write("Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n"); process.exit(0); } @@ -233,7 +233,7 @@ if (args[0] === "policy" && args[1] === "get") { } if (args[0] === "inference" && args[1] === "get") { - process.stdout.write("Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n"); + process.stdout.write("Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n"); process.exit(0); } diff --git a/test/runtime/sandbox/sandbox-build-context.test.ts b/test/runtime/sandbox/sandbox-build-context.test.ts index cca13b95e9e..a5b6dbcc2ce 100644 --- a/test/runtime/sandbox/sandbox-build-context.test.ts +++ b/test/runtime/sandbox/sandbox-build-context.test.ts @@ -263,6 +263,7 @@ describe("sandbox build context staging", () => { ); writeFixture(path.join("src", "lib", "tool-disclosure.ts")); writeFixture(path.join("src", "lib", "providerless-inference.ts")); + writeFixture("src/lib/inference/native-hosted/openrouter-headers.ts"); for (const relativePath of [ "extra-agents-validation.ts", path.join("core", "json-types.ts"), diff --git a/test/runtime/sandbox/sandbox-stuck-recovery.test.ts b/test/runtime/sandbox/sandbox-stuck-recovery.test.ts index 9785bca6509..9bfb4e921a6 100644 --- a/test/runtime/sandbox/sandbox-stuck-recovery.test.ts +++ b/test/runtime/sandbox/sandbox-stuck-recovery.test.ts @@ -35,7 +35,7 @@ function setupFixture(sandboxName: string, phase: string) { [sandboxName]: { name: sandboxName, model: "nvidia/test-model", - provider: "nvidia-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, }, @@ -83,7 +83,7 @@ if (args[0] === "policy" && args[1] === "get") { } if (args[0] === "inference" && args[1] === "get") { - process.stdout.write("Gateway inference:\\n Provider: nvidia-prod\\n Model: nvidia/test-model\\n"); + process.stdout.write("Gateway inference:\\n Provider: custom-shared-provider\\n Model: nvidia/test-model\\n"); process.exit(0); } diff --git a/test/sandbox-connect-inference/auto-pair-approval.test.ts b/test/sandbox-connect-inference/auto-pair-approval.test.ts index 16311aa0021..960de31e35c 100644 --- a/test/sandbox-connect-inference/auto-pair-approval.test.ts +++ b/test/sandbox-connect-inference/auto-pair-approval.test.ts @@ -32,10 +32,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-pass-sb", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); @@ -76,10 +76,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-pass-pol", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); @@ -143,10 +143,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-tmp-tamper", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); const maliciousPolicy = [ @@ -193,10 +193,10 @@ describe("sandbox connect auto-pair approval pass (#4263)", () => { { name: "approval-tolerant", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, - "anthropic-prod", + "custom-shared-provider", "claude-sonnet-4-20250514", ); diff --git a/test/sandbox-connect-inference/route-swap-repair.test.ts b/test/sandbox-connect-inference/route-swap-repair.test.ts index bce30aa0aa2..537c4715e82 100644 --- a/test/sandbox-connect-inference/route-swap-repair.test.ts +++ b/test/sandbox-connect-inference/route-swap-repair.test.ts @@ -8,6 +8,23 @@ import { testTimeoutOptions } from "../helpers/timeouts"; import { isHostWsl, runConnect, setupFixture } from "./helpers"; describe("sandbox connect inference route swap (#1248)", () => { + it( + "refuses a legacy hosted selection without an attachment receipt", + testTimeoutOptions(20_000), + () => { + const { tmpDir, stateFile, sandboxName } = setupFixture( + { name: "my-sandbox", model: "gpt-4o", provider: "openai-api", gpuEnabled: false }, + "openai-api", + "gpt-4o", + ); + const result = runConnect(tmpDir, sandboxName); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("Recreate the sandbox to restore native inference"); + const state = JSON.parse(fs.readFileSync(stateFile, "utf-8")); + expect(state.inferenceSetCalls).toEqual([]); + }, + ); + it( "swaps inference route when live route does not match sandbox provider", testTimeoutOptions(20_000), @@ -16,7 +33,7 @@ describe("sandbox connect inference route swap (#1248)", () => { { name: "my-sandbox", model: "claude-sonnet-4-20250514", - provider: "anthropic-prod", + provider: "custom-shared-provider", gpuEnabled: false, }, "nvidia-prod", @@ -34,7 +51,7 @@ describe("sandbox connect inference route swap (#1248)", () => { "nemoclaw", "--no-verify", "--provider", - "anthropic-prod", + "custom-shared-provider", "--model", "claude-sonnet-4-20250514", ]); @@ -42,7 +59,9 @@ describe("sandbox connect inference route swap (#1248)", () => { // Override must be loud (#3726), not a silent status-style line. const combined = (result.stdout || "") + (result.stderr || ""); expect(combined).toContain("differs from the recorded route"); - expect(combined).toContain("Aligning the gateway to anthropic-prod/claude-sonnet-4-20250514"); + expect(combined).toContain( + "Aligning the gateway to custom-shared-provider/claude-sonnet-4-20250514", + ); }, ); diff --git a/test/security/shellquote-sandbox.test.ts b/test/security/shellquote-sandbox.test.ts index fc3f00be56f..8e4e4f67213 100644 --- a/test/security/shellquote-sandbox.test.ts +++ b/test/security/shellquote-sandbox.test.ts @@ -118,7 +118,7 @@ runner.run = (command, opts = {}) => { stderr: Buffer.alloc(0), }; } - return createdSandbox.run(command) ?? { status: 0 }; + return fixtureMocks.mockNvidiaProviderGetRun(command, "nemoclaw") ?? createdSandbox.run(command) ?? { status: 0 }; }; runner.runFile = (file, args = [], opts = {}) => { commands.push({ type: "runFile", file, args, command: asText([file, ...args]), env: opts.env || null }); @@ -157,6 +157,7 @@ registry.registerSandbox = () => true; registry.removeSandbox = () => true; registry.updateSandbox = () => true; const createFixture = fixtureMocks.installVerifiedSandboxCreateFixture(registry, { + nativeNvidiaCreateIntent: true, sandboxName: "my-assistant", provider: "nvidia-prod", model: "gpt-5.4", diff --git a/test/support/connect-flow-test-harness.ts b/test/support/connect-flow-test-harness.ts index ca94625f81e..0cac84a0a67 100644 --- a/test/support/connect-flow-test-harness.ts +++ b/test/support/connect-flow-test-harness.ts @@ -73,7 +73,7 @@ export type ConnectHarness = { requalifyPortableAgentAuthoritySpy: MockInstance; qualifyHermesPortableAcceptedReadinessAuthoritySpy: MockInstance; inspectPortableReceiptDispositionSpy: MockInstance; - verifyNativeNvidiaProviderAttachmentSpy: MockInstance; + verifyNativeHostedProviderAttachmentSpy: MockInstance; nativeInferenceInvocationSpy: MockInstance; registryUpdateSpy: MockInstance; registryEntries: SandboxEntry[]; @@ -251,7 +251,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne const sandboxSession = requireDist("../../src/lib/state/sandbox-session.js"); const vmDnsMonkeypatch = requireDist("../../src/lib/actions/sandbox/vm-dns-monkeypatch.js"); const launchReadiness = requireDist("../../src/lib/actions/sandbox/launch-readiness.js"); - const nativeNvidia = requireDist("../../src/lib/inference/native-nvidia/index.js"); + const nativeHosted = requireDist("../../src/lib/inference/native-hosted/index.js"); const inferenceRouteHealth = requireDist( "../../src/lib/actions/sandbox/inference-route-health.js", ); @@ -459,8 +459,8 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne const publishLaunchReadinessSpy = vi .spyOn(launchReadiness, "publishLaunchReadiness") .mockResolvedValue(options.readinessPublicationResult ?? { kind: "published" }); - const verifyNativeNvidiaProviderAttachmentSpy = vi - .spyOn(nativeNvidia, "verifyNativeNvidiaProviderAttachment") + const verifyNativeHostedProviderAttachmentSpy = vi + .spyOn(nativeHosted, "verifyNativeHostedProviderAttachment") .mockImplementation(async (...args: unknown[]) => (args[0] as { expected: unknown }).expected); const nativeInferenceInvocationSpy = vi .spyOn(inferenceRouteHealth, "runSandboxInferenceInvocationProbe") @@ -757,7 +757,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne provider: options.agentName === "hermes" ? "ollama-local" : null, model: options.agentName === "hermes" ? "qwen3-vl:4b" : null, ...(options.agentName === "langchain-deepagents-code" - ? { provider: "nvidia-prod", model: "nvidia/nemotron-3-super-120b-a12b" } + ? { provider: "custom-shared-provider", model: "nvidia/nemotron-3-super-120b-a12b" } : {}), lifecycleLiveIdentityFingerprint: portableDisposition.kind === "hermes" @@ -896,7 +896,7 @@ export function createConnectHarness(options: ConnectHarnessOptions = {}): Conne requalifyPortableAgentAuthoritySpy, qualifyHermesPortableAcceptedReadinessAuthoritySpy, inspectPortableReceiptDispositionSpy, - verifyNativeNvidiaProviderAttachmentSpy, + verifyNativeHostedProviderAttachmentSpy, nativeInferenceInvocationSpy, registryUpdateSpy, registryEntries, diff --git a/test/support/native-provider-command-runtime.ts b/test/support/native-provider-command-runtime.ts new file mode 100644 index 00000000000..9c630a2d67f --- /dev/null +++ b/test/support/native-provider-command-runtime.ts @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { parse as parseYaml } from "yaml"; +import { nativeHostedProfile } from "../../src/lib/inference/native-hosted/profiles"; + +/** Shared CLI boundary fixture for native onboarding and credential handoff. */ +export function createNativeProviderCommandRuntime( + logicalProvider: string, + initiallyExists = false, +) { + const profile = nativeHostedProfile(logicalProvider); + if (!profile) throw new Error(`Unknown native fixture provider: ${logicalProvider}`); + const profileJson = JSON.stringify( + parseYaml( + fs.readFileSync( + path.join( + import.meta.dirname, + "../../managed-inference/provider-profiles", + `${profile.profileId}.yaml`, + ), + "utf8", + ), + ), + ); + const metadata = [ + `Name: ${profile.providerName}`, + `Type: ${profile.profileId}`, + "Id: 11111111-2222-4333-8444-555555555555", + "Resource version: 1", + `Credential keys: ${profile.credentialEnv}`, + "Config keys: ", + ].join("\n"); + let exists = initiallyExists; + const run = (args: string[]) => { + if (args[0] === "settings" && args[1] === "get") { + const output = JSON.stringify({ + scope: "global", + settings: { providers_v2_enabled: "true" }, + }); + return { status: 0, output, stdout: output, stderr: "" }; + } + if (args[0] !== "provider") return undefined; + if (args[1] === "profile") + return { status: 0, output: profileJson, stdout: profileJson, stderr: "" }; + if (args[1] === "list") + return { + status: 0, + output: JSON.stringify( + exists ? [{ name: profile.providerName, credential_keys: [profile.credentialEnv] }] : [], + ), + stdout: JSON.stringify( + exists ? [{ name: profile.providerName, credential_keys: [profile.credentialEnv] }] : [], + ), + stderr: "", + }; + if (args[1] === "get") + return exists + ? { status: 0, output: metadata, stdout: metadata, stderr: "" } + : { status: 1, output: "provider not found", stdout: "", stderr: "provider not found" }; + if (args[1] === "create") exists = true; + return { status: 0, output: "", stdout: "", stderr: "" }; + }; + return { run, profileJson, metadata }; +} diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index 35cf3b6e2a0..1abfba115ae 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -12,6 +12,7 @@ import { type SetupInferenceDeps, } from "../../src/lib/onboard/setup-inference.js"; import { redact } from "../../src/lib/security/redact.js"; +import type { NativeHostedProviderAttachment } from "../../src/lib/inference/native-hosted/contract"; const onboardProviderHelpers = require("../../src/lib/onboard/providers") as { upsertProvider: ( @@ -130,6 +131,7 @@ export type ProductionSetupInferenceBoundaryResult = { export function runProductionSetupInferenceCredentialBoundary(options: { credentialEnv: string; credentialValue: string; + preferredInferenceApi?: string; endpointUrl?: string | null; model: string; provider: string; @@ -187,6 +189,9 @@ const setupCredentialBefore = process.env[credentialEnv] || null; ${JSON.stringify(options.provider)}, ${JSON.stringify(options.endpointUrl ?? null)}, credentialEnv, + null, + [], + { preferredInferenceApi: ${JSON.stringify(options.preferredInferenceApi ?? null)} }, ); fs.writeFileSync( ${JSON.stringify(setupResultPath)}, @@ -326,6 +331,7 @@ export function createDirectSetupInferenceHarnessFactory( createSetupInference: CreateSetupInference, ) { return function createDirectSetupInferenceHarness(options: DirectSetupHarnessOptions = {}) { + const hostedAuthorities = new Map(); const commands: DirectCommandEntry[] = []; const errors: string[] = []; const logs: string[] = []; @@ -487,6 +493,11 @@ export function createDirectSetupInferenceHarnessFactory( // #9110: neutralize the GPU-release seams so harness consumers backed by // the production defaults never read the developer's real registry or // curl a live Ollama daemon. + getNativeHostedProviderAuthority: (gateway, profile) => + hostedAuthorities.get(`${gateway}/${profile}`), + setNativeHostedProviderAuthority: (gateway, receipt) => { + hostedAuthorities.set(`${gateway}/${receipt.profileId}`, receipt); + }, getSandbox: () => null, listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), unloadOllamaModels, diff --git a/tools/e2e/fixed-hosted-qualification.mts b/tools/e2e/fixed-hosted-qualification.mts new file mode 100644 index 00000000000..dd9e6aa0bc0 --- /dev/null +++ b/tools/e2e/fixed-hosted-qualification.mts @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Explicit protocol/credential representatives, not a vendor/platform matrix. +export const FIXED_HOSTED_QUALIFICATIONS = [ + { + id: "hermes-fixed-bearer-inference-switch", + sandboxName: "e2e-hm-bearer", + agent: "hermes", + provider: "hermes-provider", + credential: "NOUS_API_KEY", + protocol: "openai-completions", + }, + { + id: "hermes-fixed-anthropic-inference-switch", + sandboxName: "e2e-hm-anthropic", + agent: "hermes", + provider: "anthropic-prod", + credential: "ANTHROPIC_API_KEY", + protocol: "anthropic-messages", + }, + { + id: "hermes-fixed-openrouter-inference-switch", + sandboxName: "e2e-hm-openrouter", + agent: "hermes", + provider: "openrouter-api", + credential: "OPENROUTER_API_KEY", + protocol: "openai-completions", + }, + { + id: "openclaw-fixed-openai-inference-switch", + sandboxName: "e2e-oc-openai", + agent: "openclaw", + provider: "openai-api", + credential: "OPENAI_API_KEY", + protocol: "openai-completions", + }, + { + id: "openclaw-fixed-anthropic-inference-switch", + sandboxName: "e2e-oc-anthropic", + agent: "openclaw", + provider: "anthropic-prod", + credential: "ANTHROPIC_API_KEY", + protocol: "anthropic-messages", + }, +] as const; + +export function fixedHostedQualification(id: string) { + return FIXED_HOSTED_QUALIFICATIONS.find((row) => row.id === id); +} + +export function validateFixedHostedModel(model: string): void { + if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$/u.test(model)) { + throw new Error( + "Fixed hosted qualification requires an explicit model ID without whitespace or shell syntax", + ); + } +} + +export function validateFixedHostedSelection( + ids: readonly string[], + model: string, + event: string, +): void { + const selected = ids.filter((id) => fixedHostedQualification(id)); + if (selected.length === 0) { + if (model !== "") + throw new Error("hosted_model requires one fixed hosted qualification target"); + return; + } + if (event !== "workflow_dispatch" || ids.length !== 1) { + throw new Error("Fixed hosted qualification requires one explicitly selected manual target"); + } + validateFixedHostedModel(model); +} + +// Executed by the trusted reusable workflow before candidate checkout. No candidate +// metadata chooses the credential name, provider, protocol, or model validation. +export const FIXED_HOSTED_PLAN_SCRIPT = `hosted_credential="" +case "$CATALOGUE_ID" in +${FIXED_HOSTED_QUALIFICATIONS.map((row) => ` ${row.id}) [[ "$TARGET_ID" == "${row.agent}-inference-switch" && "$TEST_FILE" == "test/e2e/live/${row.agent}-inference-switch.test.ts" && "$SHARD" == "${row.provider}" ]] || fail "fixed hosted identity"; hosted_credential=${row.credential} ;;`).join("\n")} + *) [[ -z "\${HOSTED_MODEL:-}" ]] || fail "unexpected hosted model" ;; +esac +if [[ -n "$hosted_credential" ]]; then + [[ "$RUNTIME_PROVIDER" == "docker" ]] || fail "fixed hosted runtime" + [[ "$HOSTED_MODEL" =~ ^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,255}$ ]] || fail "hosted model" +fi +printf 'hosted_credential=%s\n' "$hosted_credential" >>"$GITHUB_OUTPUT"`; + +export const FIXED_HOSTED_RUN_SCRIPT = `if [[ -n "$HOSTED_CREDENTIAL_NAME" ]]; then + [[ -n "$HOSTED_PROVIDER_API_KEY" ]] || { echo "::error::Selected hosted provider credential is unavailable" >&2; exit 1; } + printf -v "$HOSTED_CREDENTIAL_NAME" '%s' "$HOSTED_PROVIDER_API_KEY" + export "$HOSTED_CREDENTIAL_NAME" + export NEMOCLAW_SWITCH_MODEL="$HOSTED_MODEL" +fi +unset HOSTED_PROVIDER_API_KEY`; diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 1ca2494b1f7..11f9fac8635 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -1009,6 +1009,7 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): } for (const jobName of [ "catalogue-standard", + "catalogue-fixed-hosted", "catalogue-nvidia-api", "catalogue-nvidia-inference", "catalogue-github-read", @@ -1112,6 +1113,7 @@ const STOCK_ONBOARDING_JOBS = [ const STOCK_ONBOARDING_CATALOGUE_JOBS = [ "catalogue-standard", + "catalogue-fixed-hosted", "catalogue-nvidia-api", "catalogue-nvidia-inference", "catalogue-github-read", diff --git a/tools/e2e/pre-candidate-workflow-contract.mts b/tools/e2e/pre-candidate-workflow-contract.mts index 3d40ec7bb33..81b7c1060b0 100644 --- a/tools/e2e/pre-candidate-workflow-contract.mts +++ b/tools/e2e/pre-candidate-workflow-contract.mts @@ -61,6 +61,7 @@ export const PRE_CANDIDATE_STEP_ENV: Readonly `\${{ ${TRUSTED_CALLER_CREDENTIAL_PREDICATE} && secrets.${name} || '' }}`; +export const FIXED_HOSTED_CREDENTIAL_PREDICATE = + "github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true')"; +const FIXED_HOSTED_CALLER_SECRET = + "${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') && (matrix.id == 'hermes-fixed-bearer-inference-switch' && secrets.NOUS_API_KEY || matrix.id == 'hermes-fixed-openrouter-inference-switch' && secrets.OPENROUTER_API_KEY || matrix.id == 'openclaw-fixed-openai-inference-switch' && secrets.OPENAI_API_KEY || (matrix.id == 'hermes-fixed-anthropic-inference-switch' || matrix.id == 'openclaw-fixed-anthropic-inference-switch') && secrets.ANTHROPIC_API_KEY || '') || '' }}"; const SKILL_AGENT_UPLOAD_PATH = `${[ "e2e-artifacts/live/skill-agent/evidence-manifest.json", "e2e-artifacts/live/skill-agent/*/artifact-summary.json", @@ -47,6 +55,14 @@ const SKILL_AGENT_UPLOAD_PATH = `${[ "e2e-artifacts/live/skill-agent/*/shell/*.stderr.txt", ].join("\n")}\n`; const PROFILE_JOBS = { + "fixed-hosted": { + job: "catalogue-fixed-hosted", + matrix: "catalogue_fixed_hosted_matrix", + credentialBoundary: "Selected fixed hosted provider", + secrets: ["DOCKERHUB_TOKEN", "DOCKERHUB_USERNAME", "HOSTED_PROVIDER_API_KEY"], + githubToken: false, + maxParallel: undefined, + }, standard: { job: "catalogue-standard", matrix: "catalogue_standard_matrix", @@ -152,7 +168,8 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi } const matrixOutput = `needs.generate-matrix.outputs.${contract.matrix}`; if ( - job.if !== `\${{ ${matrixOutput} != '[]' }}` || + job.if !== + `\${{ ${matrixOutput} != '[]'${profile === "fixed-hosted" ? ` && ${FIXED_HOSTED_CREDENTIAL_PREDICATE}` : ""} }}` || record(record(job.strategy).matrix).include !== `\${{ fromJSON(${matrixOutput}) }}` ) { errors.push(`${contract.job} must use its generated catalogue matrix`); @@ -202,16 +219,28 @@ function validateProfileCallers(errors: string[], workflow: WorkflowRecord): voi shard: "${{ matrix.shard }}", artifact_layout: "${{ matrix.artifact_layout }}", trusted_main: - "${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/main') && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }}", + profile === "fixed-hosted" + ? `\${{ ${FIXED_HOSTED_CREDENTIAL_PREDICATE} }}` + : "${{ github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || github.ref == 'refs/heads/main') && (inputs.checkout_sha == '' || needs.generate-matrix.outputs.e2e_credentials_allowed == 'true') }}", })) { if (withInputs[name] !== expected) { errors.push(`${contract.job} must pass ${name} from the catalogue matrix`); } } + if (profile === "fixed-hosted" && withInputs.hosted_model !== "${{ inputs.hosted_model }}") + errors.push("fixed hosted profile must pass the explicit model input"); const callerSecrets = record(job.secrets); if ( Object.keys(callerSecrets).sort().join(",") !== [...contract.secrets].sort().join(",") || - contract.secrets.some((name) => callerSecrets[name] !== guardedCallerSecret(name)) + contract.secrets.some( + (name) => + callerSecrets[name] !== + (name === "HOSTED_PROVIDER_API_KEY" + ? FIXED_HOSTED_CALLER_SECRET + : profile === "fixed-hosted" + ? `\${{ ${FIXED_HOSTED_CREDENTIAL_PREDICATE} && secrets.${name} || '' }}` + : guardedCallerSecret(name)), + ) ) { errors.push(`${contract.job} must receive only its profile secrets`); } @@ -222,6 +251,16 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi const triggers = record(profile.on ?? profile[true as unknown as string]); const call = record(triggers.workflow_call); const inputs = record(call.inputs); + const hostedModelInput = record(inputs.hosted_model); + if ( + hostedModelInput.required !== false || + hostedModelInput.type !== "string" || + hostedModelInput.default !== "" + ) + errors.push("fixed hosted model must be an optional explicit string input"); + const requiredCallInputs = Object.fromEntries( + Object.entries(inputs).filter(([name]) => name !== "hosted_model"), + ); const requiredInputs = { candidate_repository: "string", candidate_sha: "string", @@ -258,7 +297,8 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi trusted_main: "boolean", }; if ( - Object.keys(inputs).sort().join(",") !== Object.keys(requiredInputs).sort().join(",") || + Object.keys(requiredCallInputs).sort().join(",") !== + Object.keys(requiredInputs).sort().join(",") || Object.entries(requiredInputs).some( ([name, type]) => record(inputs[name]).required !== true || record(inputs[name]).type !== type, @@ -267,6 +307,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi errors.push("standard E2E profile must require its exact execution-plan inputs"); } const acceptedSecrets = [ + "HOSTED_PROVIDER_API_KEY", "DOCKERHUB_TOKEN", "DOCKERHUB_USERNAME", "NVIDIA_API_KEY", @@ -277,7 +318,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi Object.keys(declaredSecrets).sort().join(",") !== acceptedSecrets.sort().join(",") || acceptedSecrets.some((name) => record(declaredSecrets[name]).required !== false) ) { - errors.push("standard E2E profile must accept only its four optional profile secrets"); + errors.push("standard E2E profile must accept only its reviewed optional profile secrets"); } if (record(profile.permissions).contents !== "read") { errors.push("standard E2E profile permissions must be contents: read"); @@ -390,6 +431,7 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi ENV: "/dev/null", EXECUTION_ID: "${{ inputs.execution_id }}", GITHUB_WORKSPACE_VALUE: "${{ github.workspace }}", + HOSTED_MODEL: "${{ inputs.hosted_model }}", HOST_PACKAGES: "${{ inputs.host_packages }}", HOST_PREPARATION: "${{ inputs.host_preparation }}", INSTALL_MODE: "${{ inputs.install_mode }}", @@ -399,7 +441,8 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi TARGET_ID: "${{ inputs.target_id }}", TEST_FILE: "${{ inputs.test_file }}", }) || - executionPlanFragments.some((fragment) => !executionPlanRun.includes(fragment)) + executionPlanFragments.some((fragment) => !executionPlanRun.includes(fragment)) || + !executionPlanRun.includes(FIXED_HOSTED_PLAN_SCRIPT) ) { errors.push( "standard E2E profile must derive validated execution paths before candidate checkout", @@ -661,6 +704,11 @@ function validateProfileWorkflow(errors: string[], profile: WorkflowRecord): voi !String(execute?.run).includes( 'npx tsx tools/e2e/target-catalogue.mts run "$CATALOGUE_ID" "$TEST_FILE"', ) || + !String(execute?.run).includes(FIXED_HOSTED_RUN_SCRIPT) || + executeEnv.HOSTED_PROVIDER_API_KEY !== + "${{ inputs.trusted_main && secrets.HOSTED_PROVIDER_API_KEY || '' }}" || + executeEnv.HOSTED_CREDENTIAL_NAME !== "${{ steps.execution_plan.outputs.hosted_credential }}" || + executeEnv.HOSTED_MODEL !== "${{ inputs.hosted_model }}" || executeEnv.INSTALL_MODE !== "${{ inputs.install_mode }}" || executeEnv.CATALOGUE_ID !== "${{ inputs.catalogue_id }}" || executeEnv.TEST_FILE !== "${{ inputs.test_file }}" || diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index a8c6a166460..dec62e46de6 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -31,7 +31,10 @@ import { import { SANDBOX_SURVIVAL_TARGET_TIMEOUT_MINUTES } from "./sandbox-survival-timeout-contract.mts"; import { normalizeE2eSelectorId } from "./selector-aliases.mts"; +import { FIXED_HOSTED_QUALIFICATIONS } from "./fixed-hosted-qualification.mts"; + export const E2E_EXECUTION_PROFILES = [ + "fixed-hosted", "standard", "nvidia-api", "nvidia-inference", @@ -305,6 +308,8 @@ const PI_IMAGE_SOURCE_OWNING_PATHS = [ "scripts/security/patches/perl-5.44.0-net-ping-capability-tests.patch", "scripts/security/patches/python3.13-htmlparser-cve-2026-15308.patch", "scripts/upgrade-bundled-npm.mts", + "src/lib/inference/native-hosted/profiles.ts", + "src/lib/inference/native-hosted/openrouter-headers.ts", "tools/mcp-tool-discovery-runtime/reviewed-runtime-bundle/managed-startup-direct-image-runtime.bundle", ] as const; @@ -907,8 +912,9 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ runnerComparison: true, shard: "native-nvidia", owningPaths: [ + "src/lib/inference/native-hosted/index.ts", "src/lib/actions/inference-set.ts", - "src/lib/inference/native-nvidia/index.ts", + "src/lib/inference/native-nvidia/contract.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "test/e2e/live/public-nvidia-switch-provider.ts", ], @@ -1192,7 +1198,8 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: true, exposeCliBin: true, owningPaths: [ - "src/lib/inference/native-nvidia/index.ts", + "src/lib/inference/native-hosted/index.ts", + "src/lib/inference/native-nvidia/contract.ts", "managed-inference/provider-profiles/nemoclaw-nvidia-inference-v1.yaml", "src/lib/actions/inference-set.ts", "src/lib/onboard.ts", @@ -1630,6 +1637,33 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ restoreCli: false, exposeCliBin: false, }), + ...FIXED_HOSTED_QUALIFICATIONS.map((selection) => ({ + ...target(selection.id, { + displayName: `Inference: ${selection.agent} switches to ${selection.provider}`, + agentRuntime: selection.agent, + environmentOrInferenceEndpoint: `Ubuntu; native ${selection.provider} inference`, + profile: "fixed-hosted", + targetId: `${selection.agent}-inference-switch`, + testFile: `test/e2e/live/${selection.agent}-inference-switch.test.ts`, + timeoutMinutes: selection.agent === "openclaw" ? 90 : 55, + installMode: selection.agent === "openclaw" ? "none" : "authenticated", + installNonInteractive: true, + restoreCli: true, + exposeCliBin: true, + hostPreparation: selection.agent === "hermes" ? "hermes-swap" : "none", + shard: selection.provider, + gatewayRuntimes: ["docker"], + environment: { + ...nonInteractive, + NEMOCLAW_AGENT: selection.agent, + NEMOCLAW_SWITCH_PROVIDER: selection.provider, + NEMOCLAW_SWITCH_INFERENCE_API: selection.protocol, + NEMOCLAW_SANDBOX_NAME: selection.sandboxName, + OPENSHELL_GATEWAY: "nemoclaw", + }, + }), + releaseRequired: false, + })), ] as const; export const E2E_CATALOGUE_SHARED_PATHS = [ @@ -1831,13 +1865,15 @@ export function catalogueTargetsForChangedFiles( ): E2eCatalogueTarget[] { const files = [...new Set(changedFiles)]; if (files.some((file) => E2E_CATALOGUE_SHARED_PATHS.some((owner) => pathMatches(file, owner)))) { - return [...E2E_TARGET_CATALOGUE]; + return E2E_TARGET_CATALOGUE.filter((entry) => entry.profile !== "fixed-hosted"); } - return E2E_TARGET_CATALOGUE.filter((entry) => - files.some( - (file) => - file === entry.testFile || entry.owningPaths.some((owner) => pathMatches(file, owner)), - ), + return E2E_TARGET_CATALOGUE.filter( + (entry) => + entry.profile !== "fixed-hosted" && + files.some( + (file) => + file === entry.testFile || entry.owningPaths.some((owner) => pathMatches(file, owner)), + ), ); } diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 3fa8673d216..5f51c3593eb 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -262,6 +262,7 @@ const MATRIX_ROUTED_JOB_RUNNER_EXPRESSIONS = { } as const; const CATALOGUE_ROUTED_JOB_NAMES = [ "catalogue-standard", + "catalogue-fixed-hosted", "catalogue-nvidia-api", "catalogue-nvidia-inference", "catalogue-github-read", @@ -2651,7 +2652,7 @@ const PRE_CANDIDATE_RUN_SHA256: Readonly> = { "ee0b2e6c6aa4552b228bd1cc3ba4e1f9cd72701c30b81f7d5fbf9bc011fb51c7", "Authorize Launchable E2E maintainer dispatch": "bbf442a006b47016eda56133eb400a48c6931c55364c1220b84327b5ffd6f171", - "Generate E2E target matrix": "7b250c79a05973c6bc2f904195c174ddd6ffee80c62a2ff3362d7362e075b0ef", + "Generate E2E target matrix": "ad7b0daa0cbe086c843f27ed29df84791262a564187085eedd5d1d9c574e2c87", }; function requirePreCandidateEnvironment( diff --git a/tools/e2e/workflow-plan.mts b/tools/e2e/workflow-plan.mts index a6b2ce9443d..899ce99e5ab 100644 --- a/tools/e2e/workflow-plan.mts +++ b/tools/e2e/workflow-plan.mts @@ -1,3 +1,4 @@ +import { validateFixedHostedSelection } from "./fixed-hosted-qualification.mts"; // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 @@ -80,6 +81,8 @@ export type E2eWorkflowPlan = { }; type WorkflowPlanOptions = { + hostedModel?: string; + eventName?: string; changedFiles?: readonly string[]; gatewayRuntimes?: readonly E2eGatewayRuntime[]; }; @@ -97,6 +100,7 @@ const INFERENCE_MODES = new Set(["mock", "internal-nvidia", "public-nvidia"]); const CATALOGUE_JOB_BY_PROFILE: Record = { standard: "catalogue-standard", "nvidia-api": "catalogue-nvidia-api", + "fixed-hosted": "catalogue-fixed-hosted", "nvidia-inference": "catalogue-nvidia-inference", "github-read": "catalogue-github-read", }; @@ -443,6 +447,7 @@ function emptyCatalogueMatrices(): Record 0 || targets.length > 0) { const selectedIds = new Set([...jobs, ...targets]); const selectedCatalogueTargets = E2E_TARGET_CATALOGUE.filter( - (target) => selectedIds.has(target.id) || selectedIds.has(target.targetId), + (target) => + selectedIds.has(target.id) || + (target.profile !== "fixed-hosted" && selectedIds.has(target.targetId)), ); const unsupportedCatalogueTarget = selectedCatalogueTargets.find( (target) => e2eRuntimeProviders(target.gatewayRuntimes, gatewayRuntimes).length === 0, @@ -824,7 +836,9 @@ export function buildE2eWorkflowPlan( ...riskJobIds, ]); const selectedCatalogueTargets = E2E_TARGET_CATALOGUE.filter( - (target) => selectedCatalogueIds.has(target.id) || selectedCatalogueIds.has(target.targetId), + (target) => + target.profile !== "fixed-hosted" && + (selectedCatalogueIds.has(target.id) || selectedCatalogueIds.has(target.targetId)), ); const unresolvedRiskJobIds = riskJobIds.filter((id) => { const workflowJob = inventory.targetToJob.get(id) ?? id; @@ -876,7 +890,10 @@ export function buildE2eWorkflowPlan( gatewayRuntimes, matrix: buildLiveTargetMatrix([], gatewayRuntimes), testMatrix, - catalogueMatrices: catalogueMatrices(E2E_TARGET_CATALOGUE, gatewayRuntimes), + catalogueMatrices: catalogueMatrices( + E2E_TARGET_CATALOGUE.filter((target) => target.profile !== "fixed-hosted"), + gatewayRuntimes, + ), selectedJobs, runtimeProvidersByJob: runtimeProvidersByJob( inventory, @@ -1139,6 +1156,11 @@ export function writeE2eWorkflowPlanCiOutput( selectors: WorkflowPlanSelectors, environment: NodeJS.ProcessEnv = process.env, ): void { + validateFixedHostedSelection( + [...selectorIds(selectors.jobs, "jobs"), ...selectorIds(selectors.targets, "targets")], + environment.HOSTED_MODEL ?? "", + environment.EVENT_NAME ?? "", + ); const inferenceMode = environment.INFERENCE_MODE ?? ""; if (!INFERENCE_MODES.has(inferenceMode)) { throw new Error(`Invalid inference_mode: ${inferenceMode}`); @@ -1154,7 +1176,12 @@ export function writeE2eWorkflowPlanCiOutput( ); const hasPlannerSelectors = Boolean(selectors.jobs || selectors.targets); const changedFiles = hasPlannerSelectors ? undefined : changedFilesFromEnvironment(environment); - const planned = buildE2eWorkflowPlan(selectors, { changedFiles, gatewayRuntimes }); + const planned = buildE2eWorkflowPlan(selectors, { + changedFiles, + gatewayRuntimes, + hostedModel: environment.HOSTED_MODEL, + eventName: environment.EVENT_NAME, + }); const plan = validateE2eWorkflowPlan(planned); const expectedHermes = expectedHermesSelection(selectors); if (!changedFiles && plan.hermesSelected !== expectedHermes) { @@ -1169,6 +1196,7 @@ export function writeE2eWorkflowPlanCiOutput( `matrix=${JSON.stringify(plan.matrix)}`, `test_matrix=${JSON.stringify(plan.testMatrix)}`, `catalogue_standard_matrix=${JSON.stringify(plan.catalogueMatrices.standard)}`, + `catalogue_fixed_hosted_matrix=${JSON.stringify(plan.catalogueMatrices["fixed-hosted"])}`, `catalogue_nvidia_api_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-api"])}`, `catalogue_nvidia_inference_matrix=${JSON.stringify(plan.catalogueMatrices["nvidia-inference"])}`, `catalogue_github_read_matrix=${JSON.stringify(plan.catalogueMatrices["github-read"])}`,