diff --git a/agents/hermes/managed_policy.py b/agents/hermes/managed_policy.py index 2aa3ac14277..0025d1f3e1d 100644 --- a/agents/hermes/managed_policy.py +++ b/agents/hermes/managed_policy.py @@ -66,7 +66,7 @@ def _native_hosted_placeholder(config: dict, base_url: str) -> str | None: return None url = urlsplit(base_url) if ( - url.scheme != "https" + url.scheme not in {"http", "https"} or not url.hostname or url.username or url.password @@ -75,6 +75,18 @@ def _native_hosted_placeholder(config: dict, base_url: str) -> str | None: or re.search(r"[\\\s]", base_url) ): return None + custom_credentials = { + "compatible-endpoint": "COMPATIBLE_API_KEY", + "compatible-anthropic-endpoint": "COMPATIBLE_ANTHROPIC_API_KEY", + } + custom_credential = custom_credentials.get(provider.strip()) + if custom_credential is not None: + # Match nativeHostedAgentConfig, including the HTTP Bedrock adapter route. + if url.hostname in {"inference.local", "localhost", "127.0.0.1", "::1"}: + return None + return "${" + custom_credential + "}" + if url.scheme != "https": + return None if provider.strip() == "hermes-provider": # Match the authenticated endpoint contract in canonicalHermesNativeEndpoint. if ( @@ -177,7 +189,7 @@ def load_managed_policy(path: Path = MANAGED_POLICY_PATH) -> dict: ) expected_key = NVIDIA_INFERENCE_PLACEHOLDER if native_nvidia else HERMES_PROXY_REWRITE_SENTINEL api_key = policy_value(config, "model.api_key") - hosted_placeholder = None if native_nvidia else _native_hosted_placeholder(config, base_url) + hosted_placeholder = _native_hosted_placeholder(config, base_url) scoped_nvidia_handle = ( native_nvidia and isinstance(api_key, str) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 677e3acad01..0c425289028 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -35,8 +35,8 @@ "throwGuards": 526, "objectFieldAssertions": 258, "assertionPoints": 3244, - "generatedProbeBlocks": 208, - "generatedProbeConditions": 720 + "generatedProbeBlocks": 209, + "generatedProbeConditions": 721 }, "fileMetricOrder": [ "directExpectCalls", @@ -46,545 +46,83 @@ "transitiveGeneratedProbeBlocks" ], "files": { - "test/e2e/live/agent-turn-latency.test.ts": [ - 15, - 15, - 15, - 26, - 1 - ], - "test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts": [ - 11, - 33, - 12, - 55, - 4 - ], - "test/e2e/live/bootstrap-install-smoke.test.ts": [ - 0, - 0, - 14, - 29, - 3 - ], - "test/e2e/live/brave-search.test.ts": [ - 5, - 10, - 5, - 10, - 1 - ], - "test/e2e/live/brev-workspace-cleanup.test.ts": [ - 0, - 0, - 0, - 1, - 0 - ], - "test/e2e/live/channels-add-remove.test.ts": [ - 40, - 90, - 40, - 92, - 0 - ], - "test/e2e/live/channels-stop-start.test.ts": [ - 0, - 0, - 26, - 99, - 9 - ], - "test/e2e/live/cloud-onboard.test.ts": [ - 22, - 24, - 22, - 24, - 1 - ], - "test/e2e/live/common-egress-agent.test.ts": [ - 25, - 61, - 27, - 70, - 5 - ], - "test/e2e/live/concurrent-gateway-ports.test.ts": [ - 27, - 36, - 27, - 36, - 6 - ], - "test/e2e/live/cron-preflight-inference-local.test.ts": [ - 3, - 8, - 3, - 8, - 0 - ], - "test/e2e/live/dashboard-remote-bind.test.ts": [ - 16, - 14, - 16, - 16, - 3 - ], - "test/e2e/live/deferred-onboarding.test.ts": [ - 12, - 14, - 12, - 14, - 0 - ], - "test/e2e/live/dgx-express.test.ts": [ - 35, - 45, - 46, - 64, - 3 - ], - "test/e2e/live/double-onboard.test.ts": [ - 42, - 47, - 42, - 47, - 0 - ], - "test/e2e/live/external-gateway-health.test.ts": [ - 4, - 5, - 4, - 11, - 0 - ], - "test/e2e/live/full-e2e.test.ts": [ - 27, - 30, - 28, - 60, - 7 - ], - "test/e2e/live/gpu-double-onboard.test.ts": [ - 21, - 24, - 21, - 24, - 0 - ], - "test/e2e/live/gpu-e2e.test.ts": [ - 36, - 44, - 69, - 90, - 3 - ], - "test/e2e/live/hermes-discord.test.ts": [ - 10, - 22, - 17, - 61, - 14 - ], - "test/e2e/live/hermes-e2e.test.ts": [ - 82, - 93, - 112, - 127, - 3 - ], - "test/e2e/live/hermes-gpu-startup.test.ts": [ - 19, - 27, - 59, - 84, - 12 - ], - "test/e2e/live/hermes-inference-switch.test.ts": [ - 46, - 52, - 57, - 75, - 1 - ], - "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [ - 4, - 25, - 4, - 25, - 4 - ], - "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [ - 16, - 23, - 16, - 23, - 3 - ], - "test/e2e/live/hermes-slack-e2e.test.ts": [ - 0, - 0, - 29, - 87, - 14 - ], - "test/e2e/live/inference-routing-provider-smoke.test.ts": [ - 27, - 40, - 38, - 59, - 1 - ], - "test/e2e/live/inference-routing.test.ts": [ - 48, - 70, - 60, - 108, - 15 - ], - "test/e2e/live/issue-4434-tui-unreachable-inference.test.ts": [ - 28, - 32, - 28, - 32, - 0 - ], - "test/e2e/live/issue-4462-scope-upgrade-approval.test.ts": [ - 8, - 18, - 8, - 18, - 0 - ], - "test/e2e/live/issue-9880-staging-launchable.test.ts": [ - 0, - 0, - 0, - 0, - 0 - ], - "test/e2e/live/jetson-nvmap-gpu.test.ts": [ - 37, - 50, - 37, - 50, - 4 - ], - "test/e2e/live/launch-readiness-lease-acceptance.test.ts": [ - 6, - 6, - 6, - 10, - 6 - ], - "test/e2e/live/launchable-smoke.test.ts": [ - 14, - 29, - 14, - 29, - 3 - ], - "test/e2e/live/llama-cpp-generic-gpu.test.ts": [ - 17, - 35, - 33, - 61, - 2 - ], - "test/e2e/live/managed-image-activation-e2e.test.ts": [ - 0, - 0, - 13, - 28, - 0 - ], - "test/e2e/live/managed-image-multiarch-startup.test.ts": [ - 1, - 1, - 1, - 7, - 0 - ], - "test/e2e/live/managed-image-protected-runtime.test.ts": [ - 0, - 0, - 39, - 76, - 15 - ], - "test/e2e/live/mcp-bridge.test.ts": [ - 39, - 138, - 193, - 518, - 46 - ], - "test/e2e/live/messaging-compatible-endpoint.test.ts": [ - 13, - 19, - 13, - 28, - 2 - ], - "test/e2e/live/messaging-providers.test.ts": [ - 0, - 11, - 6, - 51, - 11 - ], - "test/e2e/live/model-router-provider-routed-inference.test.ts": [ - 1, - 2, - 1, - 2, - 0 - ], - "test/e2e/live/native-runtime-qualification-case.test.ts": [ - 0, - 0, - 9, - 84, - 0 - ], - "test/e2e/live/network-policy.test.ts": [ - 18, - 19, - 18, - 19, - 1 - ], - "test/e2e/live/ollama-auth-proxy.test.ts": [ - 21, - 29, - 21, - 29, - 0 - ], - "test/e2e/live/onboard-policy-preset-sequencing.test.ts": [ - 7, - 7, - 7, - 7, - 1 - ], - "test/e2e/live/onboard-repair.test.ts": [ - 22, - 26, - 22, - 26, - 0 - ], - "test/e2e/live/onboard-resume.test.ts": [ - 59, - 63, - 59, - 63, - 0 - ], - "test/e2e/live/openclaw-discord-pairing.test.ts": [ - 13, - 20, - 28, - 86, - 10 - ], - "test/e2e/live/openclaw-inference-switch.test.ts": [ - 44, - 50, - 45, - 51, - 1 - ], - "test/e2e/live/openclaw-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 - ], - "test/e2e/live/openshell-gateway-auth-source-contract.test.ts": [ - 0, - 0, - 16, - 28, - 2 - ], - "test/e2e/live/openshell-gateway-upgrade.test.ts": [ - 6, - 15, - 6, - 26, - 6 - ], - "test/e2e/live/overlayfs-autofix.test.ts": [ - 22, - 25, - 22, - 28, - 2 - ], - "test/e2e/live/pi-agent-qualification.test.ts": [ - 29, - 36, - 29, - 52, - 4 - ], - "test/e2e/live/podman-cpu-lifecycle.test.ts": [ - 35, - 57, - 48, - 92, - 1 - ], - "test/e2e/live/podman-portable-uninstall.test.ts": [ - 37, - 36, - 50, - 71, - 3 - ], - "test/e2e/live/portable-cpu-delegation-proof.test.ts": [ - 0, - 22, - 0, - 22, - 0 - ], - "test/e2e/live/portable-profile-rootless-linux.test.ts": [ - 0, - 72, - 0, - 78, - 2 - ], - "test/e2e/live/rebuild-hermes.test.ts": [ - 2, - 8, - 9, - 47, - 6 - ], - "test/e2e/live/rebuild-openclaw.test.ts": [ - 2, - 7, - 2, - 26, - 1 - ], - "test/e2e/live/registry-targets.test.ts": [ - 2, - 4, - 5, - 24, - 0 - ], - "test/e2e/live/sandbox-operations.test.ts": [ - 2, - 11, - 9, - 50, - 6 - ], - "test/e2e/live/sandbox-rlimits-connect.test.ts": [ - 1, - 1, - 1, - 1, - 0 - ], - "test/e2e/live/sandbox-survival.test.ts": [ - 4, - 11, - 4, - 11, - 0 - ], - "test/e2e/live/sessions-agents-cli.test.ts": [ - 19, - 28, - 20, - 31, - 0 - ], - "test/e2e/live/skill-agent.test.ts": [ - 7, - 9, - 8, - 10, - 0 - ], - "test/e2e/live/snapshot-commands.test.ts": [ - 5, - 5, - 5, - 5, - 0 - ], - "test/e2e/live/spark-install.test.ts": [ - 11, - 13, - 11, - 15, - 6 - ], - "test/e2e/live/state-backup-restore.test.ts": [ - 1, - 5, - 1, - 5, - 0 - ], - "test/e2e/live/telegram-injection.test.ts": [ - 19, - 28, - 26, - 67, - 12 - ], - "test/e2e/live/token-rotation.test.ts": [ - 28, - 36, - 28, - 36, - 2 - ], - "test/e2e/live/tunnel-lifecycle.test.ts": [ - 0, - 0, - 8, - 17, - 4 - ], - "test/e2e/live/whatsapp-qr-compact.test.ts": [ - 29, - 35, - 29, - 35, - 1 - ], - "test/e2e/live/windows-mxc-openclaw-process-container.test.ts": [ - 7, - 11, - 7, - 73, - 4 - ] + "test/e2e/live/agent-turn-latency.test.ts": [15,15,15,26,1], + "test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts": [11,33,12,55,4], + "test/e2e/live/bootstrap-install-smoke.test.ts": [0,0,14,29,3], + "test/e2e/live/brave-search.test.ts": [5,10,5,10,1], + "test/e2e/live/brev-workspace-cleanup.test.ts": [0,0,0,1,0], + "test/e2e/live/channels-add-remove.test.ts": [40,90,40,92,0], + "test/e2e/live/channels-stop-start.test.ts": [0,0,26,99,9], + "test/e2e/live/cloud-onboard.test.ts": [22,24,22,24,1], + "test/e2e/live/common-egress-agent.test.ts": [25,61,27,70,5], + "test/e2e/live/concurrent-gateway-ports.test.ts": [27,36,27,36,6], + "test/e2e/live/cron-preflight-inference-local.test.ts": [3,8,3,8,0], + "test/e2e/live/dashboard-remote-bind.test.ts": [16,14,16,16,3], + "test/e2e/live/deferred-onboarding.test.ts": [12,14,12,14,0], + "test/e2e/live/dgx-express.test.ts": [35,45,46,64,3], + "test/e2e/live/double-onboard.test.ts": [42,47,42,47,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,8], + "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,22,17,61,14], + "test/e2e/live/hermes-e2e.test.ts": [82,93,112,127,3], + "test/e2e/live/hermes-gpu-startup.test.ts": [19,27,59,84,12], + "test/e2e/live/hermes-inference-switch.test.ts": [46,52,57,75,1], + "test/e2e/live/hermes-root-entrypoint-smoke.test.ts": [4,25,4,25,4], + "test/e2e/live/hermes-sandbox-secret-boundary.test.ts": [16,23,16,23,3], + "test/e2e/live/hermes-slack-e2e.test.ts": [0,0,29,87,14], + "test/e2e/live/inference-routing-provider-smoke.test.ts": [27,40,38,59,1], + "test/e2e/live/inference-routing.test.ts": [48,70,60,108,15], + "test/e2e/live/issue-4434-tui-unreachable-inference.test.ts": [28,32,28,32,0], + "test/e2e/live/issue-4462-scope-upgrade-approval.test.ts": [8,18,8,18,0], + "test/e2e/live/issue-9880-staging-launchable.test.ts": [0,0,0,0,0], + "test/e2e/live/jetson-nvmap-gpu.test.ts": [37,50,37,50,4], + "test/e2e/live/launch-readiness-lease-acceptance.test.ts": [6,6,6,10,6], + "test/e2e/live/launchable-smoke.test.ts": [14,29,14,29,3], + "test/e2e/live/llama-cpp-generic-gpu.test.ts": [17,35,33,61,2], + "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,13,28,0], + "test/e2e/live/managed-image-multiarch-startup.test.ts": [1,1,1,7,0], + "test/e2e/live/managed-image-protected-runtime.test.ts": [0,0,39,76,15], + "test/e2e/live/mcp-bridge.test.ts": [39,138,193,518,46], + "test/e2e/live/messaging-compatible-endpoint.test.ts": [13,19,13,28,2], + "test/e2e/live/messaging-providers.test.ts": [0,11,6,51,11], + "test/e2e/live/model-router-provider-routed-inference.test.ts": [1,2,1,2,0], + "test/e2e/live/native-runtime-qualification-case.test.ts": [0,0,9,84,0], + "test/e2e/live/network-policy.test.ts": [18,19,18,19,1], + "test/e2e/live/ollama-auth-proxy.test.ts": [21,29,21,29,0], + "test/e2e/live/onboard-policy-preset-sequencing.test.ts": [7,7,7,7,1], + "test/e2e/live/onboard-repair.test.ts": [22,26,22,26,0], + "test/e2e/live/onboard-resume.test.ts": [59,63,59,63,0], + "test/e2e/live/openclaw-discord-pairing.test.ts": [13,20,28,86,10], + "test/e2e/live/openclaw-inference-switch.test.ts": [44,50,45,51,1], + "test/e2e/live/openclaw-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], + "test/e2e/live/openshell-gateway-auth-source-contract.test.ts": [0,0,16,28,2], + "test/e2e/live/openshell-gateway-upgrade.test.ts": [6,15,6,26,6], + "test/e2e/live/overlayfs-autofix.test.ts": [22,25,22,28,2], + "test/e2e/live/pi-agent-qualification.test.ts": [29,36,29,52,4], + "test/e2e/live/podman-cpu-lifecycle.test.ts": [35,57,48,92,1], + "test/e2e/live/podman-portable-uninstall.test.ts": [37,36,50,71,3], + "test/e2e/live/portable-cpu-delegation-proof.test.ts": [0,22,0,22,0], + "test/e2e/live/portable-profile-rootless-linux.test.ts": [0,72,0,78,2], + "test/e2e/live/rebuild-hermes.test.ts": [2,8,9,47,6], + "test/e2e/live/rebuild-openclaw.test.ts": [2,7,2,26,1], + "test/e2e/live/registry-targets.test.ts": [2,4,5,24,0], + "test/e2e/live/sandbox-operations.test.ts": [2,11,9,50,6], + "test/e2e/live/sandbox-rlimits-connect.test.ts": [1,1,1,1,0], + "test/e2e/live/sandbox-survival.test.ts": [4,11,4,11,0], + "test/e2e/live/sessions-agents-cli.test.ts": [19,28,20,31,0], + "test/e2e/live/skill-agent.test.ts": [7,9,8,10,0], + "test/e2e/live/snapshot-commands.test.ts": [5,5,5,5,0], + "test/e2e/live/spark-install.test.ts": [11,13,11,15,6], + "test/e2e/live/state-backup-restore.test.ts": [1,5,1,5,0], + "test/e2e/live/telegram-injection.test.ts": [19,28,26,67,12], + "test/e2e/live/token-rotation.test.ts": [28,36,28,36,2], + "test/e2e/live/tunnel-lifecycle.test.ts": [0,0,8,17,4], + "test/e2e/live/whatsapp-qr-compact.test.ts": [29,35,29,35,1], + "test/e2e/live/windows-mxc-openclaw-process-container.test.ts": [7,11,7,73,4] } } } diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index c641f864aed..75bc4b1ad25 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.", "schemaVersion": 1, "exceptions": [ { @@ -43,6 +43,10 @@ "pullRequest": 13055, "changeSha256": "d0435766039881c9598d3740f650e3bffdbace9f5a3f29fdc70238522c521f79" }, + { + "pullRequest": 13201, + "changeSha256": "c5311b6d098e8d67b414e6bdf128f9a47afa88cc7342ff0989ad04601a3c313a" + }, { "pullRequest": 13064, "changeSha256": "68c1ed04adc264f0030f864b9a3e9d4f51fe352c9da9e41d000eac6d20206cb8" diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index 54c61dba0bc..516ed0cc966 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:cfdeae93e0f8ae802a6e0fc9e8e68f2bcaf1fb6f45ec16791a995229a75391bb", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:cfdeae93e0f8ae802a6e0fc9e8e68f2bcaf1fb6f45ec16791a995229a75391bb", + "digest": "sha256:428530c256fd5b76014fd2561aed153ef759f4fb23d4c7d0f42304e0b37e989d", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:428530c256fd5b76014fd2561aed153ef759f4fb23d4c7d0f42304e0b37e989d", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "b1302d38f8b3b084a884fa0efcf17ff9251f697d", + "revision": "19f521416a5dbb62ac9fa169e5f03eb817c72297", "release": "v0.1.0", - "cohort": "ghrun-38769032420-1" + "cohort": "ghrun-38826692761-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 df73cd3d28d..bca82d559e5 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:1cb6c6ee7622ba870f14fef62e353c1e422a18597cc0701d942e0fbbde800fa1", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:1cb6c6ee7622ba870f14fef62e353c1e422a18597cc0701d942e0fbbde800fa1", + "digest": "sha256:cb7292a4aabf56a85d75d47015fffc583d437c0ee26941df79359a12734fac27", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:cb7292a4aabf56a85d75d47015fffc583d437c0ee26941df79359a12734fac27", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "b1302d38f8b3b084a884fa0efcf17ff9251f697d", + "revision": "19f521416a5dbb62ac9fa169e5f03eb817c72297", "release": "v0.1.0", - "cohort": "ghrun-38769032420-1" + "cohort": "ghrun-38826692761-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index eb8620d1992..0d8e266004f 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -909,30 +909,42 @@ nvidia = inputs["nvidia"] refreshed = set() native_refreshed = False -# Restored native handles belong to the sandbox/provider revision that issued -# them. Refresh the exact inference field before the final gateway start. -# Accept only scoped runtime handles for the matching endpoint and key; leave -# user-managed credentials unchanged. +# Persisted native handles belong to the provider revision that issued them. +# Refresh only inference credentials before OpenClaw starts. Raw values and +# unrelated fields must not cross this boundary. models = config.get("models") if isinstance(config, dict) else None providers = models.get("providers") if isinstance(models, dict) else None -native = providers.get("inference") if isinstance(providers, dict) else None -native_keys = { - nvidia["endpoint"]: nvidia["credentialEnv"], - openrouter["endpoint"]: openrouter["credentialEnv"], +fixed_native_endpoints = { + nvidia["credentialEnv"]: nvidia["endpoint"], + openrouter["credentialEnv"]: openrouter["endpoint"], } -endpoint = native.get("baseUrl") if isinstance(native, dict) else None -key = native_keys.get(endpoint.rstrip("/")) if isinstance(endpoint, str) else None -if key: - scoped = re.compile(rf"^{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{key}$") +for provider_key in ("inference", "openai", "anthropic"): + native = providers.get(provider_key) if isinstance(providers, dict) else None + if not isinstance(native, dict): + continue saved = native.get("apiKey") + scoped = re.fullmatch( + rf"{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_([A-Z][A-Z0-9_]*)", + saved if isinstance(saved, str) else "", + ) + if not scoped: + continue + key = scoped.group(1) + expected_endpoint = fixed_native_endpoints.get(key) + if expected_endpoint: + endpoint = native.get("baseUrl") + if ( + provider_key != "inference" + or not isinstance(endpoint, str) + or endpoint.rstrip("/") != expected_endpoint + ): + continue state = runtime_state(key) current = state.get("value", "") if ( - isinstance(saved, str) - and scoped.fullmatch(saved) - and state.get("kind") == "placeholder" + state.get("kind") == "placeholder" and isinstance(current, str) - and scoped.fullmatch(current) + and re.fullmatch(rf"{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{re.escape(key)}", current) and saved != current ): native["apiKey"] = current diff --git a/src/lib/actions/credentials/reset-native-hosted.test.ts b/src/lib/actions/credentials/reset-native-hosted.test.ts index fbe4a5ae6c6..60872d5046b 100644 --- a/src/lib/actions/credentials/reset-native-hosted.test.ts +++ b/src/lib/actions/credentials/reset-native-hosted.test.ts @@ -7,6 +7,7 @@ import { HOSTED_NATIVE_PROVIDERS, hostedNativeProvider, } from "../../inference/native-provider/hosted"; +import { customNativeProvider } from "../../inference/native-provider/custom"; import { resetNativeHostedProvider } from "./reset-native-hosted"; const target = { kind: "named", gatewayName: "gateway" } as const; @@ -14,13 +15,20 @@ const absent = { ok: false, error: { kind: "command", reason: "not_found", message: "absent" }, } as const; -function fixture(provider = "openai-api") { - const definition = hostedNativeProvider(provider)!; +function fixture(provider = "openai-api", custom?: ReturnType) { + const definition = custom ?? hostedNativeProvider(provider)!; const receipt = { schemaVersion: 1 as const, profileId: definition.profileId, providerName: definition.providerName, providerId: "owned-id", + ...(definition.custom + ? { + custom: definition.custom, + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + } + : {}), }; const metadata = { name: definition.providerName, @@ -154,3 +162,32 @@ describe("native hosted credential reset", () => { expect(f.clear).not.toHaveBeenCalled(); }); }); + +it("removes only an unreferenced custom provider selected by its owned name", async () => { + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const f = fixture(definition.logicalProvider, definition); + expect( + ( + await resetNativeHostedProvider(definition.providerName, target, f.adapter, { + ...f.deps, + listNativeHostedProviderAttachmentSandboxNames: () => ["alpha"], + }) + )?.exitCode, + ).toBe(1); + expect(f.remove).not.toHaveBeenCalled(); + f.get.mockResolvedValueOnce({ ok: true, value: f.metadata }).mockResolvedValueOnce(absent); + expect( + (await resetNativeHostedProvider(definition.providerName, target, f.adapter, f.deps))?.exitCode, + ).toBe(0); + expect(f.remove).toHaveBeenCalledExactlyOnceWith({ + target, + providerName: definition.providerName, + }); + expect(f.clear).toHaveBeenCalledWith("gateway", f.receipt); +}); diff --git a/src/lib/actions/inference-get.test.ts b/src/lib/actions/inference-get.test.ts index 3815adce33d..e5352424e88 100644 --- a/src/lib/actions/inference-get.test.ts +++ b/src/lib/actions/inference-get.test.ts @@ -5,6 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import { describe, expect, it, vi } from "vitest"; +import { customNativeProvider } from "../inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS } from "../inference/native-provider/hosted"; import { nativeLocalIdentity, type NativeLocalBinding } from "../inference/native-local/contract"; import { buildHttpsPinRouteBaseUrl } from "../inference/https-pin-runtime"; @@ -1214,7 +1215,21 @@ describe("runInferenceGet", () => { }); describe("native hosted inference get", () => { - it.each(HOSTED_NATIVE_PROVIDERS)( + it.each([ + ...HOSTED_NATIVE_PROVIDERS.map((definition) => ({ + ...definition, + endpointUrl: undefined, + allowedIps: undefined, + custom: undefined, + })), + customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "CUSTOM_KEY", + allowedIps: ["8.8.8.8"], + }), + ])( "reports $logicalProvider from the selected sandbox rather than the shared route", async (definition) => { const deps = createDeps(configuredRoute("ollama-local", "other-sandbox-model")); @@ -1227,6 +1242,9 @@ describe("native hosted inference get", () => { profileId: definition.profileId, providerName: definition.providerName, providerId: "owned-provider-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, }, }); await expect(runInferenceGet({ sandboxName: "alpha", quiet: true }, deps)).resolves.toEqual({ diff --git a/src/lib/actions/inference-get.ts b/src/lib/actions/inference-get.ts index 2b66a29175e..b9a2b724029 100644 --- a/src/lib/actions/inference-get.ts +++ b/src/lib/actions/inference-get.ts @@ -313,19 +313,21 @@ export async function runInferenceGet( const selectedSandbox = selectedSandboxName ? (deps.getSandbox ?? getKnownSandboxTarget)(selectedSandboxName) : null; - if ( + const nativeAttachment = selectedSandbox && selectedSandbox.nativeLocalProviderAttachment === undefined && - recordedNativeProviderAttachment(selectedSandbox) - ) { + recordedNativeProviderAttachment(selectedSandbox); + if (selectedSandbox && nativeAttachment) { const payload: InferenceGetResult = { provider: selectedSandbox.provider ?? null, model: selectedSandbox.model ?? null, endpointUrl: + nativeAttachment.endpointUrl ?? hostedNativeProvider( selectedSandbox.provider, selectedSandbox.nativeHostedProviderAttachment?.endpointUrl, - )?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT, + )?.endpoint ?? + NVIDIA_HOSTED_NATIVE_ENDPOINT, }; if (!options.quiet) { if (options.json) { diff --git a/src/lib/actions/inference-set-native-hosted.test.ts b/src/lib/actions/inference-set-native-hosted.test.ts index fd23215b1fe..ce715c76080 100644 --- a/src/lib/actions/inference-set-native-hosted.test.ts +++ b/src/lib/actions/inference-set-native-hosted.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; +import { customNativeProvider } from "../inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS, hostedNativeProvider } from "../inference/native-provider/hosted"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; import { fixedNativeProvider } from "../inference/native-provider/fixed"; @@ -92,7 +93,7 @@ function fixture(extraDefinitions: ReturnType[] = [ deps.getNativeHostedProviderAuthority = (gateway, provider) => authorities.get(`${gateway}/${provider}`); deps.setNativeHostedProviderAuthority = (gateway, provider, receipt) => { - authorities.set(`${gateway}/${provider}`, receipt); + authorities.set(`${gateway}/${receipt.custom ? receipt.providerName : provider}`, receipt); }; return { deps, calls, attached, authorities, entry }; } @@ -514,3 +515,102 @@ describe("Hermes native gateway credential refresh", () => { }, ); }); + +describe("custom native inference selection", () => { + const custom = customNativeProvider({ + provider: "compatible-endpoint", + api: "openai-completions", + endpointUrl: "https://8.8.8.8/team/v1", + credentialEnv: "COMPATIBLE_API_KEY", + allowedIps: ["8.8.8.8"], + }); + const replacement = customNativeProvider({ + ...custom.custom, + endpointUrl: "https://1.1.1.1/team/v1", + allowedIps: ["1.1.1.1"], + }); + it("switches a native sandbox, reuses its key for model changes and preserves rebuild authority", async () => { + const { deps, calls, entry, attached } = fixture([custom, replacement]); + await runInferenceSet({ provider: "openai-api", model: "first-model" }, deps); + await runInferenceSet( + { + provider: "compatible-endpoint", + model: "custom-model", + endpointUrl: custom.endpoint, + inferenceApi: custom.api, + }, + deps, + ); + expect(entry.endpointUrl).toBe(custom.endpoint); + expect(entry.nativeHostedProviderAttachment?.custom).toEqual(custom.custom); + expect([...attached.get("alpha")!]).toEqual([custom.providerName]); + expect([...attached.get("beta")!]).toEqual(["unrelated-provider"]); + deps.resolveCredentialValue = () => ""; + await runInferenceSet({ provider: "compatible-endpoint", model: "second-model" }, deps); + expect(calls.updateProvider).not.toHaveBeenCalled(); + expect(entry.model).toBe("second-model"); + expect(JSON.stringify(deps.calls.setOpenClawConfigValues.mock.calls)).toContain( + custom.endpoint, + ); + const previous = structuredClone(entry); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "third-model", + endpointUrl: replacement.endpoint, + inferenceApi: replacement.api, + }, + deps, + ), + ).rejects.toThrow("A new credential is required"); + expect(entry).toEqual(previous); + expect([...attached.get("alpha")!]).toEqual([custom.providerName]); + expect(deps.inferenceRouteObserver.observeInferenceRoute).not.toHaveBeenCalled(); + }); + it("restores the prior attachment if a changed custom endpoint fails sandbox verification", async () => { + const { deps, calls, entry, attached, authorities } = fixture([custom, replacement]); + await runInferenceSet({ provider: "openai-api", model: "first-model" }, deps); + await runInferenceSet( + { + provider: "compatible-endpoint", + model: "custom-model", + endpointUrl: custom.endpoint, + inferenceApi: custom.api, + }, + deps, + ); + const previous = structuredClone(entry); + const attach = calls.attachProvider.getMockImplementation()!; + calls.attachProvider.mockImplementation(async (request) => { + const conflicting = + request.providerName === custom.providerName + ? replacement.providerName + : custom.providerName; + expect(attached.get(request.sandboxName)).not.toContain(conflicting); + return attach(request); + }); + deps.calls.probeSandboxRoute.mockResolvedValue({ + ok: false, + detail: "endpoint refused", + httpStatus: 401, + }); + await expect( + runInferenceSet( + { + provider: "compatible-endpoint", + model: "third-model", + endpointUrl: replacement.endpoint, + inferenceApi: replacement.api, + }, + deps, + ), + ).rejects.toThrow(); + expect(entry).toEqual(previous); + expect([...attached.get("alpha")!]).toEqual([custom.providerName]); + expect([...attached.get("beta")!]).toEqual(["unrelated-provider"]); + expect(authorities.get(`nemoclaw/${replacement.providerName}`)?.providerId).toBe( + `id-${replacement.providerName}`, + ); + }); +}); diff --git a/src/lib/actions/inference-set-route-containment.ts b/src/lib/actions/inference-set-route-containment.ts index 3319c39c9ed..c2718f5ec74 100644 --- a/src/lib/actions/inference-set-route-containment.ts +++ b/src/lib/actions/inference-set-route-containment.ts @@ -496,6 +496,7 @@ export async function finalizeInferenceSetRoute(options: { resolveCredentialValue: (credentialEnv: string) => string; ensureHttpsPinRuntimeAdapter: EnsureHttpsPinRuntimeAdapterFn; effectiveInferenceApi?: string | null; + nativeProvider?: boolean; }): Promise<{ registryMetadata: RegistryInferenceMetadata; explicitPreferredInferenceApi: string | null; @@ -504,6 +505,25 @@ export async function finalizeInferenceSetRoute(options: { routeImpactWarning: string | null; }> { const { prepared } = options; + if (options.nativeProvider) { + const metadata = prepared.preliminaryExplicitMetadata ?? prepared.preliminaryRegistryMetadata; + return { + registryMetadata: { + ...metadata, + ...(prepared.preliminaryExplicitSourceEndpointUrl + ? { + endpointUrl: prepared.preliminaryExplicitSourceEndpointUrl, + endpointSource: "inference-set" as const, + } + : {}), + }, + explicitPreferredInferenceApi: + prepared.preliminaryExplicitMetadata?.preferredInferenceApi ?? null, + directProviderBinding: null, + httpsPinProviderBinding: null, + routeImpactWarning: null, + }; + } if (!prepared.preliminaryExplicitMetadata) { return { registryMetadata: prepared.preliminaryRegistryMetadata, diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index cb2b42d4a74..dfad3661534 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -63,6 +63,7 @@ import { prepareNativeTransitionAuthority, prepareNativeSelection, isNativeInferenceSelection, + usesNativeConfigByDefault, rollbackNativeSelection, detachPreviousNativeBeforePublish, restorePreviousNativeAfterFailedPublish, @@ -733,7 +734,7 @@ export function patchOpenClawInferenceConfig( reasoningEffort: ReasoningEffortRequest = { effort: null, explicit: false }, inheritPrimaryReplyBudget = true, nativeEndpointUrl?: string, - nativeProvider = true, + nativeProvider = usesNativeConfigByDefault(provider, nativeEndpointUrl), ): { changed: boolean; route: SandboxInferenceConfig } { const before = JSON.stringify(config); const route = getSandboxInferenceConfig( @@ -843,7 +844,7 @@ export function patchHermesInferenceConfig( preferredInferenceApi: string | null = null, contextWindow?: number, nativeEndpointUrl?: string, - nativeProvider = true, + nativeProvider = usesNativeConfigByDefault(provider, nativeEndpointUrl), nativeCredentialHandle?: string, ): { changed: boolean; route: SandboxInferenceConfig } { const before = JSON.stringify(config); @@ -1076,8 +1077,10 @@ async function assertHermesCompatibleAnthropicOpenAiProvider( httpsPinProviderBinding: { providerType: "openai" | "anthropic"; } | null = null, + nativeProvider = false, ): Promise { if ( + nativeProvider || agentName !== "hermes" || provider !== "compatible-anthropic-endpoint" || isBedrockRuntimeEndpoint(endpointUrl) @@ -1306,6 +1309,7 @@ async function runInferenceSetWithoutHostLock( httpsPinProviderBinding, routeImpactWarning, } = await finalizeInferenceSetRoute({ + nativeProvider: selectingNative, prepared: preparedRoute, sandboxName, provider, @@ -1396,6 +1400,7 @@ async function runInferenceSetWithoutHostLock( registryMetadata.endpointUrl ?? null, deps, httpsPinProviderBinding ?? directProviderBinding, + selectingNative, ); // Read the in-sandbox config *before* mutating the gateway route or registry. @@ -1522,6 +1527,20 @@ async function runInferenceSetWithoutHostLock( expectedAttachment: nativeProviderAuthority, gatewayName: preparedRoute.gatewayName, sandboxName, + endpointUrl: registryMetadata.endpointUrl, + credentialEnv: registryMetadata.credentialEnv, + inferenceApi: preMutationInferenceApi, + beforeAttach: async (receipt) => { + previousNativeDetached = await detachPreviousNativeBeforePublish({ + selectingNative, + selectedProvider: provider, + selectedAttachment: receipt, + previousAttachment: previousNativeAttachment, + gatewayName: preparedRoute.gatewayName, + sandboxName, + deps, + }); + }, deps, }); nativeProviderAttachment = nativeSelection.attachment; @@ -1690,9 +1709,10 @@ async function runInferenceSetWithoutHostLock( // Removing previous native access is a security gate for publishing another // route. Do not commit the non-native registry/config while the sandbox can // still use the credential-bearing attached provider. - previousNativeDetached = await detachPreviousNativeBeforePublish({ + previousNativeDetached ||= await detachPreviousNativeBeforePublish({ selectingNative, selectedProvider: provider, + selectedAttachment: nativeProviderAttachment, previousAttachment: previousNativeAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, @@ -1725,7 +1745,9 @@ async function runInferenceSetWithoutHostLock( }), ...(openClawConfigSyncPending ? { openClawConfigSyncPending: true as const } : {}), ...nativeSelectionRegistryFields(nativeProviderAttachment, previousNativeDetached), - ...(nativeSelection.endpointUrl ? { endpointUrl: nativeSelection.endpointUrl } : {}), + ...(nativeSelection.endpointUrl && !nativeProviderAttachment?.custom + ? { endpointUrl: nativeSelection.endpointUrl } + : {}), }); if ( !deps.updateSandbox( @@ -1958,19 +1980,21 @@ async function runInferenceSetWithoutHostLock( expectedGatewayName, ); if (error instanceof OpenClawInferenceConfigSyncError) throw error; - await restorePreviousNativeAfterFailedPublish({ - detached: previousNativeDetached, - committed: previousNativeDetachCommitted, - previousAttachment: previousNativeAttachment, + // Custom endpoints share an injection environment name. Remove the failed + // selection before restoring access so the provider composition cannot collide. + await rollbackNativeSelection({ + attachmentChanged: nativeAttachmentChanged, + registryCommitted: nativeRegistryCommitted, + attachment: nativeProviderAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, error, deps, }); - await rollbackNativeSelection({ - attachmentChanged: nativeAttachmentChanged, - registryCommitted: nativeRegistryCommitted, - attachment: nativeProviderAttachment, + await restorePreviousNativeAfterFailedPublish({ + detached: previousNativeDetached, + committed: previousNativeDetachCommitted, + previousAttachment: previousNativeAttachment, gatewayName: preparedRoute.gatewayName, sandboxName, error, diff --git a/src/lib/actions/inference-set/native.ts b/src/lib/actions/inference-set/native.ts index 1ea2a0a4ffa..0ae5726bf76 100644 --- a/src/lib/actions/inference-set/native.ts +++ b/src/lib/actions/inference-set/native.ts @@ -20,9 +20,18 @@ import { import { hostedNativeProvider, usesNativeHermesEndpoint, + isCustomHostedProvider, + customNativeCredentialEnv, } from "../../inference/native-provider/hosted"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import type { SandboxEntry } from "../../state/registry"; +import { prepareCustomNativeProvider } from "../../inference/native-provider/custom-setup"; +import { isHostedCustomEndpoint } from "../../inference/native-provider/custom"; + +/** Preserve shared-route config unless a custom native endpoint is explicit. */ +export function usesNativeConfigByDefault(provider: string, nativeEndpointUrl?: string): boolean { + return !isCustomHostedProvider(provider) || Boolean(nativeEndpointUrl); +} export function isNativeInferenceSelection( provider: string, @@ -31,6 +40,11 @@ export function isNativeInferenceSelection( gatewayName: string, deps: InferenceSetDeps, ): boolean { + if (isCustomHostedProvider(provider)) { + const endpoint = endpointUrl ?? (entry.provider === provider ? entry.endpointUrl : undefined); + if (!endpoint || !recordedNativeProviderAttachment(entry)) return false; + return isHostedCustomEndpoint(provider, endpoint); + } if (!fixedNativeProvider(provider)) return false; if (provider !== "hermes-provider") return true; const authority = @@ -73,6 +87,10 @@ export function resolveNativeSelectionAuthority(input: { deps: InferenceSetDeps; }): NativeProviderAttachment | undefined { if (!input.selectingNative) return undefined; + if (isCustomHostedProvider(input.provider)) + return input.previousAttachment?.custom?.provider === input.provider + ? input.previousAttachment + : undefined; const fixed = fixedNativeProvider(input.provider); if (!fixed) return undefined; const previous = @@ -114,7 +132,9 @@ export function nativeSelectionRegistryFields( ? { nativeNvidiaProviderAttachment: nvidia } : { nativeHostedProviderAttachment: attachment, - credentialEnv: fixedNativeProviderForAttachment(attachment).credentialEnv, + credentialEnv: + attachment.custom?.credentialEnv ?? + fixedNativeProviderForAttachment(attachment).credentialEnv, }), }; } @@ -143,6 +163,10 @@ export async function prepareNativeSelection(input: { expectedAttachment?: NativeProviderAttachment; gatewayName: string; sandboxName: string; + endpointUrl?: string | null; + credentialEnv?: string | null; + inferenceApi?: string | null; + beforeAttach?: (receipt: NativeProviderAttachment) => Promise; deps: InferenceSetDeps; }): Promise<{ attachment?: NativeProviderAttachment; @@ -150,6 +174,44 @@ export async function prepareNativeSelection(input: { endpointUrl?: string; }> { if (!input.selectingNative) return { attachmentChanged: false }; + if (isCustomHostedProvider(input.provider)) { + if ( + !input.deps.getNativeHostedProviderAuthority || + !input.deps.setNativeHostedProviderAuthority + ) + throw new InferenceSetError("Native hosted provider ownership storage is unavailable"); + const credentialEnv = input.credentialEnv || customNativeCredentialEnv(input.provider); + const receipt = await prepareCustomNativeProvider({ + gatewayName: input.gatewayName, + provider: input.provider, + endpointUrl: input.endpointUrl || "", + api: + input.inferenceApi || + (input.provider === "compatible-anthropic-endpoint" + ? "anthropic-messages" + : "openai-completions"), + credentialEnv, + credentialValue: input.deps.resolveCredentialValue(credentialEnv) || null, + adapter: input.deps.providerAdapter, + recordedAttachment: input.expectedAttachment, + readAuthority: input.deps.getNativeHostedProviderAuthority, + writeAuthority: input.deps.setNativeHostedProviderAuthority, + }); + await input.beforeAttach?.(receipt); + const attached = await nativeProviderLifecycle( + fixedNativeProviderForAttachment(receipt), + ).ensureNativeProviderAttached({ + adapter: input.deps.providerAdapter, + target: { kind: "named", gatewayName: input.gatewayName }, + sandboxName: input.sandboxName, + expected: receipt, + }); + return { + attachment: attached.receipt, + attachmentChanged: attached.changed, + endpointUrl: receipt.endpointUrl, + }; + } const definition = input.expectedAttachment ? fixedNativeProviderForAttachment(input.expectedAttachment) : fixedNativeProvider(input.provider); @@ -226,6 +288,7 @@ export async function rollbackNativeSelection(input: { export async function detachPreviousNativeBeforePublish(input: { selectingNative: boolean; selectedProvider: string; + selectedAttachment?: NativeProviderAttachment; previousAttachment?: NativeProviderAttachment; gatewayName: string; sandboxName: string; @@ -233,7 +296,13 @@ export async function detachPreviousNativeBeforePublish(input: { }): Promise { if (!input.previousAttachment) return false; const previous = fixedNativeProviderForAttachment(input.previousAttachment); - if (input.selectingNative && input.selectedProvider === previous.logicalProvider) return false; + if ( + input.selectingNative && + (input.selectedAttachment + ? input.selectedAttachment.providerName === input.previousAttachment.providerName + : !input.previousAttachment.custom && input.selectedProvider === previous.logicalProvider) + ) + return false; await nativeProviderLifecycle(previous).detachNativeProvider({ adapter: input.deps.providerAdapter, target: { kind: "named", gatewayName: input.gatewayName }, diff --git a/src/lib/actions/sandbox/inference-invocation-probe.test.ts b/src/lib/actions/sandbox/inference-invocation-probe.test.ts index 182c9219468..d4b028e5e50 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.test.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.test.ts @@ -5,6 +5,7 @@ import { SandboxCommandTransportError } from "../../adapters/sandbox/command-tra import { spawnSync } from "node:child_process"; import { getChatCompletionsProbePayload } from "../../inference/openai-probe-models"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; +import { nativeLocalIdentity } from "../../inference/native-local/contract"; import { existsSync, mkdtempSync, @@ -16,7 +17,7 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { describe, expect, it, vi } from "vitest"; +import { assert, describe, expect, it, vi } from "vitest"; import { isNvcfFunctionNotFoundForAccount } from "../../inference/nvcf-model-access"; import { @@ -755,6 +756,73 @@ it("gives native Ultra readiness the same reasoning budget as host onboarding", }); describe("native hosted inference probe credential boundary", () => { + it.each([ + [ + "compatible-endpoint", + "COMPATIBLE_API_KEY", + "openai-completions", + "https://custom.example/team/v1", + "/chat/completions", + "Authorization: Bearer", + ], + [ + "compatible-endpoint", + "COMPATIBLE_API_KEY", + "openai-responses", + "https://custom.example/team/v1", + "/responses", + "Authorization: Bearer", + ], + [ + "compatible-anthropic-endpoint", + "COMPATIBLE_ANTHROPIC_API_KEY", + "anthropic-messages", + "https://custom.example/team", + "/v1/messages", + "x-api-key:", + ], + ])("uses the custom %s %s %s binding", (provider, env, api, endpoint, suffix, header) => { + const placeholder = `openshell:resolve:env:v123_${env}`; + const result = runProbeCommandWithBody( + "200", + "{}", + tmpdir(), + { + ...input, + provider, + preferredInferenceApi: api, + nativeProvider: true, + nativeEndpointUrl: endpoint, + }, + { [env]: placeholder }, + ); + expect(result.argv.at(-1)).toBe(endpoint + suffix); + expect(result.argv).toContain(`${header} ${placeholder}`); + expect(result.stdout).toBe("200\n{}"); + }); + + it.each([true, false])( + "gives conditional legacy DNS guidance only for a shared route (native=%s)", + async (nativeProvider) => { + const result = await probeSandboxInferenceInvocation( + { + ...input, + nativeProvider, + ...(nativeProvider ? { nativeEndpointUrl: "https://custom.example/v1" } : {}), + }, + { execute: vi.fn(async () => ({ status: 6, stdout: "curl-error:6\n", stderr: "" })) }, + ); + expect(result.ok).toBe(false); + assert(result.ok === false); + expect(result.detail.includes("If that route is no longer available")).toBe(!nativeProvider); + expect(result.endpoint).toBe( + nativeProvider + ? "https://custom.example/v1/chat/completions" + : "https://inference.local/v1/chat/completions", + ); + }, + ); + it.each([ [ "openai-api", @@ -870,3 +938,42 @@ describe("native hosted inference probe credential boundary", () => { expect(result.stderr).toBe(""); }); }); + +it.each([true, undefined])( + "uses a native local attachment without custom hosted authority (native=%s) (#13195)", + async (nativeProvider) => { + const binding = { + provider: "compatible-endpoint", + endpointUrl: "http://host.openshell.internal:8000/v1", + credentialEnv: "NEMOCLAW_LOCAL_INFERENCE_TOKEN", + authMode: "authenticated", + gatewayName: "nemoclaw", + sandboxName: input.sandboxName, + } as const; + const selected = { + ...input, + agentName: "langchain-deepagents-code", + nativeProvider, + nativeLocalProviderAttachment: { + ...binding, + ...nativeLocalIdentity(binding), + schemaVersion: 1 as const, + providerId: "fixture-local-provider", + }, + }; + const placeholder = "openshell:resolve:env:v123_NEMOCLAW_LOCAL_INFERENCE_TOKEN"; + const body = '{"choices":[{"message":{"content":"OK"}}]}'; + const result = runProbeCommandWithBody("200", body, tmpdir(), selected, { + NEMOCLAW_LOCAL_INFERENCE_TOKEN: placeholder, + }); + expect(result.argv.at(-1)).toBe(binding.endpointUrl + "/chat/completions"); + expect(result.argv).toContain(`Authorization: Bearer ${placeholder}`); + expect( + await probeSandboxInferenceInvocation(selected, { + commandExecutor: { + runBuffered: async () => bufferedResult(0, result.stdout, ""), + }, + }), + ).toEqual({ ok: true }); + }, +); diff --git a/src/lib/actions/sandbox/inference-invocation-probe.ts b/src/lib/actions/sandbox/inference-invocation-probe.ts index d41ede7231f..3577a75280b 100644 --- a/src/lib/actions/sandbox/inference-invocation-probe.ts +++ b/src/lib/actions/sandbox/inference-invocation-probe.ts @@ -1,9 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { nativeHostedAuthHeaderScript } from "../../inference/native-provider/contract"; import { NATIVE_LOCAL_AUTH_HEADER_SCRIPT } from "../../inference/native-local/agent-config"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../inference/native-nvidia/contract"; -import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { + hostedNativeProvider, + customNativeCredentialEnv, + isCustomHostedProvider, +} from "../../inference/native-provider/hosted"; import { nativeHostedAgentConfig } from "../../inference/native-provider/agent-config"; import { SandboxCommandTransportError } from "../../adapters/sandbox/command-transport"; import type { @@ -85,6 +90,25 @@ export const INFERENCE_INVOCATION_REQUEST_TIMEOUT_SECONDS = 90; export const READINESS_INFERENCE_INVOCATION_TIMEOUT_MS = 95_000; const INFERENCE_INVOCATION_MAX_RESPONSE_BYTES = 64 * 1024; +function nativeProbeDefinition(input: SandboxInferenceInvocationInput) { + if (input.nativeLocalProviderAttachment) return undefined; + if (input.nativeProvider && isCustomHostedProvider(input.provider)) { + if (!input.nativeEndpointUrl) + throw new Error("Custom native inference probe is missing its endpoint"); + return { + logicalProvider: input.provider, + endpoint: input.nativeEndpointUrl, + credentialEnv: customNativeCredentialEnv(input.provider), + api: + input.preferredInferenceApi ?? + (input.provider === "compatible-anthropic-endpoint" + ? "anthropic-messages" + : "openai-completions"), + }; + } + return hostedNativeProvider(input.provider, input.nativeEndpointUrl); +} + /** Build the protocol-specific request used to verify sandbox inference. */ function buildProbeRequest(input: SandboxInferenceInvocationInput): { endpoint: string; @@ -105,11 +129,11 @@ function buildProbeRequest(input: SandboxInferenceInvocationInput): { input.provider, input.preferredInferenceApi, input.nativeProvider ?? Boolean(local), - local?.endpointUrl ?? null, + local?.endpointUrl ?? input.nativeEndpointUrl ?? null, input.agentName, ); const useNativeNvidia = input.nativeProvider === true && isNativeNvidiaProvider(input.provider); - const hosted = hostedNativeProvider(input.provider, input.nativeEndpointUrl); + const hosted = nativeProbeDefinition(input); const nativeHosted = input.nativeProvider === true ? hosted : undefined; if (input.nativeProvider === true && !useNativeNvidia && !nativeHosted && !local) { throw new Error("Unsupported native inference probe selection"); @@ -176,20 +200,6 @@ export function resolveSandboxInferenceInvocationEndpoint( return buildProbeRequest(input).endpoint; } -/** Accept only an OpenShell-issued placeholder, never a host credential. */ -function nativeHostedAuthHeaderScript(provider: string): string { - const definition = hostedNativeProvider(provider); - if (!definition) throw new Error("Unsupported native hosted inference probe"); - const env = definition.credentialEnv; - const value = "${" + env + ":-}"; - const header = definition.api === "anthropic-messages" ? "x-api-key:" : "Authorization: Bearer"; - return [ - `case "${value}" in *[!a-zA-Z0-9:_]*) exit 2 ;; esac`, - `printf '%s' "${value}" | LC_ALL=C grep -Eq '^openshell:resolve:env:((v[0-9]{1,20}|s[a-f0-9]{64})_)?${env}$' || exit 2`, - `AUTH_HEADER="${header} ${value}"`, - ].join("; "); -} - export function buildSandboxInferenceInvocationCommand( input: SandboxInferenceInvocationInput, ): string { @@ -198,16 +208,13 @@ export function buildSandboxInferenceInvocationCommand( const useNativeLocal = Boolean( normalizeNativeLocalProviderAttachment(input.nativeLocalProviderAttachment), ); - const nativeHosted = - input.nativeProvider === true - ? hostedNativeProvider(input.provider, input.nativeEndpointUrl) - : undefined; + const nativeHosted = input.nativeProvider === true ? nativeProbeDefinition(input) : undefined; const nativeAuth = useNativeNvidia ? NATIVE_NVIDIA_AUTH_HEADER_SCRIPT : useNativeLocal ? NATIVE_LOCAL_AUTH_HEADER_SCRIPT : nativeHosted - ? nativeHostedAuthHeaderScript(nativeHosted.logicalProvider) + ? nativeHostedAuthHeaderScript(nativeHosted) : undefined; const headerArgs = ["Content-Type: application/json", ...request.headers] @@ -330,7 +337,9 @@ export async function probeSandboxInferenceInvocation( input.preferredInferenceApi, input.nativeProvider ?? Boolean(input.nativeLocalProviderAttachment), normalizeNativeLocalProviderAttachment(input.nativeLocalProviderAttachment)?.endpointUrl ?? + input.nativeEndpointUrl ?? null, + input.agentName, ).inferenceApi; if (httpStatus !== null && validateInferenceResponseBody(inferenceApi, body).ok) { return { ok: true }; @@ -351,12 +360,18 @@ export async function probeSandboxInferenceInvocation( const detail = httpStatus ? `sandbox inference invocation probe returned HTTP ${httpStatus}` : `sandbox inference invocation probe exited with status ${result.status}`; + const legacyDnsFailure = + input.nativeProvider !== true && + result.stdout.split("\n").some((line) => line.trim() === "curl-error:6") && + new URL(resolveSandboxInferenceInvocationEndpoint(input)).hostname === "inference.local"; return { ok: false, detail: httpStatus === "404" && nvcfFunctionNotFound ? `${detail}: ${nvcfFunctionNotFoundMessage(input.model).replace(/\.$/, "")}` - : detail, + : legacyDnsFailure + ? `${detail}. The legacy inference route could not be resolved. If that route is no longer available, recreate this sandbox to use native inference.` + : detail, httpStatus: httpStatus ? Number.parseInt(httpStatus, 10) : null, endpoint: resolveSandboxInferenceInvocationEndpoint(input), }; diff --git a/src/lib/actions/sandbox/inference-route-health.test.ts b/src/lib/actions/sandbox/inference-route-health.test.ts index d08c9ac4145..2ea3e29f6f3 100644 --- a/src/lib/actions/sandbox/inference-route-health.test.ts +++ b/src/lib/actions/sandbox/inference-route-health.test.ts @@ -446,3 +446,19 @@ describe("transient inference invocation failures", () => { expect(isTransientInferenceInvocationFailure(null)).toBe(false); }); }); + +it("offers conditional recreation guidance when the legacy route cannot be reached", () => { + const health = buildSandboxInferenceRouteHealth( + { + ok: false, + endpoint: "https://inference.local/v1/models", + httpStatus: 0, + detail: "Inference gateway is unreachable.", + }, + null, + null, + { provider: "compatible-endpoint", model: "selected" }, + ); + expect(health.ok).toBe(false); + expect(health.detail).toContain("If this legacy route is no longer available"); +}); diff --git a/src/lib/actions/sandbox/inference-route-health.ts b/src/lib/actions/sandbox/inference-route-health.ts index 91578ce6964..d9fe85ddecf 100644 --- a/src/lib/actions/sandbox/inference-route-health.ts +++ b/src/lib/actions/sandbox/inference-route-health.ts @@ -9,6 +9,7 @@ import { verifyNativeLocalProviderAttachment } from "../../inference/native-loca import type { SandboxEntry } from "../../state/registry/types"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { hostedNativeProviderForAttachment } from "../../inference/native-provider/hosted-attachment"; import { fixedNativeProvider, fixedNativeProviderForAttachment, @@ -451,7 +452,13 @@ export function buildSandboxInferenceRouteHealth( subprobes: providerHealthDiagnostics(providerHealth, invocation?.ok === true), }; } - const definition = fixedNativeProvider(context.provider); + const definition = + fixedNativeProvider(context.provider) ?? + (context.nativeProvider && + (context.provider === "compatible-endpoint" || + context.provider === "compatible-anthropic-endpoint") + ? { logicalProvider: context.provider, label: "custom hosted" } + : undefined); if ((context.nativeProvider || context.nativeNvidia) && definition) { const endpoint = invocation && !invocation.ok && invocation.endpoint @@ -535,6 +542,13 @@ export function buildSandboxInferenceRouteHealth( detail: `Could not probe ${endpoint} from inside the sandbox.`, }; } + if ( + !routeHealth.ok && + gateway?.httpStatus === 0 && + new URL(endpoint).hostname === "inference.local" + ) + routeHealth.detail += + " If this legacy route is no longer available, recreate the sandbox to use native inference."; const subprobes = [...(routeHealth.subprobes ?? []), ...diagnostics]; return subprobes.length > 0 ? { ...routeHealth, subprobes } : routeHealth; } @@ -576,7 +590,11 @@ export function readNativeStatusSelection(entry: SandboxEntry | null | undefined failure = "Recorded native provider ownership is invalid; no inference request was sent."; } const local = entry?.nativeLocalProviderAttachment !== undefined; - const definition = local ? null : hostedNativeProvider(entry?.provider, attachment?.endpointUrl); + const definition = local + ? null + : attachment + ? hostedNativeProviderForAttachment(attachment) + : hostedNativeProvider(entry?.provider); return { attachment, failure, diff --git a/src/lib/actions/sandbox/rebuild-credential-preflight.ts b/src/lib/actions/sandbox/rebuild-credential-preflight.ts index b1975bbcfc6..db51828c7f7 100644 --- a/src/lib/actions/sandbox/rebuild-credential-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-credential-preflight.ts @@ -211,16 +211,18 @@ export async function preflightRebuildCredentials( return false; } if (nativeAttachment) { - const nativeCredentialEnv = fixedNativeProviderForAttachment(nativeAttachment).credentialEnv; + const definition = fixedNativeProviderForAttachment(nativeAttachment); + const nativeCredentialEnv = definition.credentialEnv; if ( !(await checkRebuildGatewayProviderOrBail(rebuildProvider, nativeCredentialEnv, log, bail, { nativeAttachment, })) ) return false; + const sourceCredentialEnv = definition.custom?.credentialEnv ?? nativeCredentialEnv; return preflightRebuildHostCredential( - { ...sb, credentialEnv: nativeCredentialEnv }, - rebuildOnboardDependencies.hydrateCredentialEnv(nativeCredentialEnv), + { ...sb, credentialEnv: sourceCredentialEnv }, + rebuildOnboardDependencies.hydrateCredentialEnv(sourceCredentialEnv), bail, ); } diff --git a/src/lib/actions/sandbox/rebuild-provider-preflight.ts b/src/lib/actions/sandbox/rebuild-provider-preflight.ts index 9bb14405451..cd6dcc64c94 100644 --- a/src/lib/actions/sandbox/rebuild-provider-preflight.ts +++ b/src/lib/actions/sandbox/rebuild-provider-preflight.ts @@ -514,7 +514,11 @@ export async function checkRebuildGatewayCredentialReuseOrBail( console.error( ` ${_RD}Rebuild preflight failed:${R} cannot safely reuse the recorded gateway credential.`, ); - console.error(` ${rebuildCredentialReuseCondition(decision.condition)}`); + console.error( + ` ${rebuildCredentialReuseCondition( + decision.kind === "reject" ? decision.condition : "gateway-provider-identity", + )}`, + ); console.error(" Export the provider credential to use normal validation and upsert."); console.error(" Sandbox is untouched — no data was lost."); bail("Unsafe gateway credential reuse"); diff --git a/src/lib/actions/sandbox/rebuild-resume-config.ts b/src/lib/actions/sandbox/rebuild-resume-config.ts index 56a59458aa5..aeeaadbe161 100644 --- a/src/lib/actions/sandbox/rebuild-resume-config.ts +++ b/src/lib/actions/sandbox/rebuild-resume-config.ts @@ -262,11 +262,13 @@ export function prepareRebuildResumeConfig( return null; } if (hostedDefinition) { - const expectedEndpoint = hostedDefinition.endpoint; + const expectedEndpoint = hostedDefinition.custom?.endpointUrl ?? hostedDefinition.endpoint; if ( (sb.endpointUrl && sb.endpointUrl.replace(/\/+$/, "") !== expectedEndpoint.replace(/\/+$/, "")) || - (sb.credentialEnv && sb.credentialEnv !== hostedDefinition.credentialEnv) + (sb.credentialEnv && + sb.credentialEnv !== + (hostedDefinition.custom?.credentialEnv ?? hostedDefinition.credentialEnv)) ) { bail( "Native provider selection does not match recorded credential or endpoint; sandbox is untouched", @@ -283,6 +285,7 @@ export function prepareRebuildResumeConfig( return null; } const credentialEnv = + hostedDefinition?.custom?.credentialEnv ?? hostedDefinition?.credentialEnv ?? getRebuildCredentialEnvFromRegistry( trustedSelection.provider, 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 01b935ad25a..b00f917e64e 100644 --- a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -962,7 +962,7 @@ describe("collectSandboxStatusSnapshot inference route health", () => { expect(delayInferenceRecoveryProbe).toHaveBeenCalledOnce(); expect(snapshot.inferenceHealth).toMatchObject({ ok: false, - detail: brokenRoute.detail, + detail: expect.stringContaining(brokenRoute.detail), failureLabel: "unreachable", }); }); diff --git a/src/lib/adapters/config/live-export-source.test.ts b/src/lib/adapters/config/live-export-source.test.ts index fcbc924868d..e9d10fcc8d8 100644 --- a/src/lib/adapters/config/live-export-source.test.ts +++ b/src/lib/adapters/config/live-export-source.test.ts @@ -8,13 +8,21 @@ import { expectExportRefusal, } from "../../../../test/support/config-export-harness"; import fs from "node:fs"; -import { HOSTED_NATIVE_PROVIDERS } from "../../inference/native-provider/hosted"; +import { + HOSTED_NATIVE_PROVIDERS, + type HostedProviderDefinition, +} from "../../inference/native-provider/hosted"; import { nativeProviderLifecycle } from "../../inference/native-provider"; +import { BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL } from "../../inference/bedrock-runtime"; +import { + customNativeProvider, + boundCustomNativeProfile, +} from "../../inference/native-provider/custom"; import { parseCheckedInProviderProfileContract } from "../openshell/provider-profile"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; import { getSandboxEntryInference } from "../../state/registry-entry-view"; import { createHash } from "node:crypto"; -import { describe, expect, it, vi } from "vitest"; +import { assert, describe, expect, it, vi } from "vitest"; import YAML from "yaml"; import { managedBraveProfile, @@ -152,12 +160,14 @@ function mockNativeNvidiaSource(profileWorkspace = "default") { }); } -function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[number]) { +function mockNativeHostedSource(definition: HostedProviderDefinition) { const route = resolveManagedStartupInferenceRoute( "openclaw", definition.logicalProvider, "model-a", definition.api, + true, + definition.endpointUrl, ); const startup = buildManagedStartupProfile({ ...startupInput, @@ -175,14 +185,21 @@ function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[num const native = { ...entry, provider: definition.logicalProvider, - endpointUrl: definition.endpoint, - credentialEnv: definition.credentialEnv, + endpointUrl: definition.custom?.endpointUrl ?? definition.endpoint, + credentialEnv: definition.custom?.credentialEnv ?? definition.credentialEnv, preferredInferenceApi: definition.api, nativeHostedProviderAttachment: { schemaVersion: 1 as const, profileId: definition.profileId, providerName: definition.providerName, providerId: "native-provider-id", + ...(definition.custom + ? { + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + } + : {}), }, workload: { ...entry.workload, @@ -210,12 +227,18 @@ function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[num }), }, }); + const profilePath = nativeProviderLifecycle(definition).nativeProviderProfilePath(); const contract = parseCheckedInProviderProfileContract( - fs.readFileSync(nativeProviderLifecycle(definition).nativeProviderProfilePath(), "utf8"), + definition.custom + ? boundCustomNativeProfile(definition, profilePath) + : fs.readFileSync(profilePath, "utf8"), )!; const credential = contract.boundary.credentials[0]; const endpoint = contract.boundary.endpoints[0] as { host: string; + port: number; + allowed_ips?: string[]; + tls?: string; rules: { allow: { method: string; path: string } }[]; }; const base = managedBraveProfile(); @@ -236,6 +259,9 @@ function mockNativeHostedSource(definition: (typeof HOSTED_NATIVE_PROVIDERS)[num { ...base.endpoints[0], host: endpoint.host, + port: endpoint.port, + allowedIps: endpoint.allowed_ips ?? [], + tls: endpoint.tls ?? "", access: "", rules: endpoint.rules.map((rule) => ({ allow: { @@ -796,23 +822,80 @@ describe("live export snapshot reader", () => { }, ); - it.each( - HOSTED_NATIVE_PROVIDERS.filter((definition) => definition.logicalProvider !== "gemini-api"), - )("exports native $label without reading shared routing or secret values", async (definition) => { - const { readCredential } = mockNativeHostedSource(definition); - const { result, writeStdout } = 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: definition.endpoint, - api: definition.api, - credential: { env: definition.credentialEnv }, - }); - expect(readCredential).not.toHaveBeenCalled(); - expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); - expect(yaml).not.toContain(readFailureCanary); - }); + it.each([ + ...HOSTED_NATIVE_PROVIDERS.filter((definition) => definition.logicalProvider !== "gemini-api"), + ...[ + ["compatible-endpoint", "openai-completions", "https://custom.example/team/v1"], + ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example/team"], + ["compatible-anthropic-endpoint", "openai-completions", "https://custom.example/team"], + ["compatible-anthropic-endpoint", "openai-responses", "https://custom.example/team"], + ].map(([provider, api, endpointUrl]) => + customNativeProvider({ + provider, + api, + endpointUrl, + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }), + ), + customNativeProvider({ + provider: "compatible-anthropic-endpoint", + api: "openai-completions", + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + credentialEnv: "TEAM_KEY", + allowedIps: [], + adapterEndpointUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, + }), + ])( + "exports native $label without reading shared routing or secret values", + async (definition: HostedProviderDefinition) => { + const { readCredential } = mockNativeHostedSource(definition); + const { result, writeStdout } = 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: definition.custom?.endpointUrl ?? definition.endpoint, + api: definition.api, + credential: { env: definition.custom?.credentialEnv ?? definition.credentialEnv }, + }); + expect(readCredential).not.toHaveBeenCalled(); + expect(captureSanitizedResolvedOpenshell).not.toHaveBeenCalled(); + expect(yaml).not.toContain(readFailureCanary); + }, + ); + + it.each(["selected", "runtime", "both"] as const)( + "rejects custom native export when the %s endpoint changes", + async (changed) => { + const definition = customNativeProvider({ + provider: "compatible-anthropic-endpoint", + api: "openai-completions", + endpointUrl: "https://custom.example/team", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + mockNativeHostedSource(definition); + const observed = await createLiveExportSnapshotReader().read("alpha"); + assert(observed.kind === "observed" && observed.inference.endpointEvidence); + const { endpointEvidence: evidence, ...inference } = observed.inference; + const result = await observeStableExportSource("alpha", { + read: async () => ({ + ...observed, + inference: { + ...inference, + endpoint: changed === "runtime" ? inference.endpoint : "https://drift.example/v1", + endpointEvidence: { + ...evidence, + endpoint: changed === "selected" ? evidence.endpoint : "https://drift.example/v1", + }, + }, + }), + }); + expect(result).toMatchObject({ ok: false }); + }, + ); it("rejects native hosted export when the sandbox attaches an unrelated provider", async () => { mockNativeHostedSource(HOSTED_NATIVE_PROVIDERS[0]); diff --git a/src/lib/adapters/config/live-export-source.ts b/src/lib/adapters/config/live-export-source.ts index 334c3e27fea..ed53519a299 100644 --- a/src/lib/adapters/config/live-export-source.ts +++ b/src/lib/adapters/config/live-export-source.ts @@ -201,6 +201,7 @@ async function readProviderEvidence( ? { nativeHostedEndpoint: nativeReceipt.endpointUrl, nativeHostedAllowedIps: nativeReceipt.allowedIps, + nativeHostedCustom: nativeReceipt.custom, } : {}), configKeys: [configKey], diff --git a/src/lib/adapters/openshell/native-hosted-profile-response.test.ts b/src/lib/adapters/openshell/native-hosted-profile-response.test.ts index 2889136c345..bbdd6439e94 100644 --- a/src/lib/adapters/openshell/native-hosted-profile-response.test.ts +++ b/src/lib/adapters/openshell/native-hosted-profile-response.test.ts @@ -7,19 +7,30 @@ import { managedBraveProfile } from "../../../../test/fixtures/openshell-provide import { hostedNativeProvider, HOSTED_NATIVE_PROVIDERS, + type HostedProviderDefinition, } from "../../inference/native-provider/hosted"; import { nativeProviderLifecycle } from "../../inference/native-provider"; +import { + customNativeProvider, + boundCustomNativeProfile, +} from "../../inference/native-provider/custom"; import { parseCheckedInProviderProfileContract } from "./provider-profile"; import { isManagedNativeHostedProfileResponse } from "./native-hosted-profile-response"; -function response(definition: (typeof HOSTED_NATIVE_PROVIDERS)[number]) { +function response(definition: HostedProviderDefinition) { + const profilePath = nativeProviderLifecycle(definition).nativeProviderProfilePath(); const contract = parseCheckedInProviderProfileContract( - fs.readFileSync(nativeProviderLifecycle(definition).nativeProviderProfilePath(), "utf8"), + definition.custom + ? boundCustomNativeProfile(definition, profilePath) + : fs.readFileSync(profilePath, "utf8"), )!; const base = managedBraveProfile(); const credential = contract.boundary.credentials[0]; const endpoint = contract.boundary.endpoints[0] as { host: string; + port: number; + tls?: string; + allowed_ips?: string[]; rules: { allow: { method: string; path: string } }[]; }; return { @@ -39,6 +50,9 @@ function response(definition: (typeof HOSTED_NATIVE_PROVIDERS)[number]) { { ...base.endpoints[0], host: endpoint.host, + port: endpoint.port, + tls: endpoint.tls ?? "", + allowedIps: endpoint.allowed_ips ?? [], access: "", rules: endpoint.rules.map((rule) => ({ allow: { @@ -115,6 +129,83 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label profile read boundary", (d }); }); +it.each([ + ["compatible-endpoint", "openai-completions", "http://custom.example/team/v1", ["8.8.8.8"]], + ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1", ["8.8.8.8"]], + [ + "compatible-anthropic-endpoint", + "anthropic-messages", + "https://custom.example/team", + ["10.0.0.8"], + ], +] as const)( + "verifies custom %s %s against its complete binding", + (provider, api, endpointUrl, allowedIps) => { + const definition = customNativeProvider({ + provider, + api, + endpointUrl, + allowedIps, + credentialEnv: "TEAM_KEY", + }); + const value = response(definition); + const read = (observed: unknown, binding = definition.custom) => + isManagedNativeHostedProfileResponse( + observed, + definition.profileId, + definition.endpointUrl, + definition.allowedIps, + binding, + ); + expect(read(value)).toBe(value); + expect( + read({ + profile: { + ...value.profile, + endpoints: [ + { + ...value.profile.endpoints[0], + tls: endpointUrl.startsWith("https:") ? "" : "terminate", + }, + ], + }, + }), + ).toBeUndefined(); + expect( + read(value, { ...definition.custom!, credentialEnv: "DIFFERENT_SOURCE" }), + ).toBeUndefined(); + expect( + read({ + profile: { + ...value.profile, + endpoints: [{ ...value.profile.endpoints[0], allowedIps: ["1.1.1.1"] }], + }, + }), + ).toBeUndefined(); + expect( + read({ + profile: { + ...value.profile, + credentials: [{ ...value.profile.credentials[0], envVars: ["TEAM_KEY"] }], + }, + }), + ).toBeUndefined(); + expect( + read({ + profile: { + ...value.profile, + endpoints: [ + { + ...value.profile.endpoints[0], + rules: [...value.profile.endpoints[0].rules, value.profile.endpoints[0].rules[0]], + }, + ], + }, + }), + ).toBeUndefined(); + }, +); + it("requires the exact public IP restriction on a Hermes bound profile", () => { const endpointUrl = "https://staging.nous.example/v1"; const definition = hostedNativeProvider("hermes-provider", endpointUrl)!; diff --git a/src/lib/adapters/openshell/native-hosted-profile-response.ts b/src/lib/adapters/openshell/native-hosted-profile-response.ts index 8d7b7e7d112..e95bfe1fc84 100644 --- a/src/lib/adapters/openshell/native-hosted-profile-response.ts +++ b/src/lib/adapters/openshell/native-hosted-profile-response.ts @@ -2,6 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import { requireHermesPublicPins } from "../../inference/native-provider/hermes-pins"; +import { + customNativeProvider, + type CustomNativeBinding, +} from "../../inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS, type HostedProviderDefinition, @@ -14,12 +18,18 @@ import { export type HostedNativeProfileId = | (typeof HOSTED_NATIVE_PROVIDERS)[number]["profileId"] + | `nemoclaw-custom-${string}-v1` | `nemoclaw-hermes-inference-${string}-v1`; export function hostedNativeProfile( profileId: string, endpointUrl?: string, + custom?: CustomNativeBinding, ): HostedProviderDefinition | undefined { + if (custom) { + const bound = customNativeProvider(custom); + return bound.profileId === profileId && bound.endpoint === endpointUrl ? bound : undefined; + } if (endpointUrl) { const bound = hostedNativeProvider("hermes-provider", endpointUrl); return bound?.profileId === profileId ? bound : undefined; @@ -31,23 +41,29 @@ export function hostedNativeProfileBoundary( profileId: string, endpointUrl?: string, allowedIps?: readonly string[], + custom?: CustomNativeBinding, ): NativeProfileBoundary | undefined { - const definition = hostedNativeProfile(profileId, endpointUrl); + const definition = hostedNativeProfile(profileId, endpointUrl, custom); if (!definition) return undefined; const endpoint = new URL(definition.endpoint); - const prefix = - definition.api === "anthropic-messages" ? "/v1" : endpoint.pathname.replace(/\/+$/, ""); + const base = endpoint.pathname.replace(/\/+$/, ""); + const prefix = definition.api === "anthropic-messages" ? `${custom ? base : ""}/v1` : base; let paths = ["chat/completions"]; if (definition.api === "anthropic-messages") paths = ["messages", "messages/count_tokens"]; + else if (custom && definition.api === "openai-responses") paths = ["responses"]; else if (definition.logicalProvider === "openai-api") paths.push("responses"); + let pins: readonly string[] | undefined; + if (custom) pins = definition.allowedIps ?? []; + else if (definition.endpointUrl) pins = requireHermesPublicPins(allowedIps); return { profileId: definition.profileId as HostedNativeProfileId, - ...(definition.endpointUrl ? { allowedIps: requireHermesPublicPins(allowedIps) } : {}), + ...(pins ? { allowedIps: pins } : {}), + ...(custom && endpoint.protocol === "https:" ? { tls: "terminate" as const } : {}), credentialEnv: definition.credentialEnv, authStyle: definition.api === "anthropic-messages" ? "header" : "bearer", headerName: definition.api === "anthropic-messages" ? "x-api-key" : "authorization", - host: endpoint.hostname, - port: Number(endpoint.port || 443), + host: endpoint.hostname.replace(/^\[|\]$/gu, ""), + port: Number(endpoint.port || (endpoint.protocol === "https:" ? 443 : 80)), rules: [ { method: "GET", path: `${prefix}/models` }, ...paths.map((path) => ({ method: "POST" as const, path: `${prefix}/${path}` })), @@ -60,10 +76,11 @@ export function isManagedNativeHostedProfileResponse( profileId: string, endpointUrl?: string, allowedIps?: readonly string[], + custom?: CustomNativeBinding, ) { let boundary; try { - boundary = hostedNativeProfileBoundary(profileId, endpointUrl, allowedIps); + boundary = hostedNativeProfileBoundary(profileId, endpointUrl, allowedIps, custom); } catch { return undefined; } diff --git a/src/lib/adapters/openshell/native-inference-profile-response.ts b/src/lib/adapters/openshell/native-inference-profile-response.ts index b79d34f0b27..7a0d18f1db4 100644 --- a/src/lib/adapters/openshell/native-inference-profile-response.ts +++ b/src/lib/adapters/openshell/native-inference-profile-response.ts @@ -21,6 +21,7 @@ export type NativeProfileBoundary = Readonly<{ headerName: string; host: string; port?: number; + tls?: "terminate"; allowedIps?: readonly string[]; binaries?: readonly string[]; rules: readonly Readonly<{ method: "GET" | "POST"; path: string }>[]; @@ -103,7 +104,7 @@ function nativeEndpoint(value: unknown, expected: NativeProfileBoundary): boolea endpoint.port === (expected.port ?? 443) && emptyArray(endpoint.ports) && endpoint.protocol === "rest" && - endpoint.tls === "" && + endpoint.tls === (expected.tls ?? "") && endpoint.enforcement === "enforce" && endpoint.access === "" && Array.isArray(rules) && diff --git a/src/lib/adapters/openshell/native-nvidia-profile-response.ts b/src/lib/adapters/openshell/native-nvidia-profile-response.ts index 53aab3a1c83..7823b9b34f3 100644 --- a/src/lib/adapters/openshell/native-nvidia-profile-response.ts +++ b/src/lib/adapters/openshell/native-nvidia-profile-response.ts @@ -17,6 +17,7 @@ export type NativeProfileBoundary = Readonly<{ headerName: string; host: string; port?: number; + tls?: "terminate"; allowedIps?: readonly string[]; rules: readonly Readonly<{ method: "GET" | "POST"; path: string }>[]; }>; @@ -98,7 +99,7 @@ function nativeEndpoint(value: unknown, expected: NativeProfileBoundary): boolea endpoint.port === (expected.port ?? 443) && emptyArray(endpoint.ports) && endpoint.protocol === "rest" && - endpoint.tls === "" && + endpoint.tls === (expected.tls ?? "") && endpoint.enforcement === "enforce" && endpoint.access === "" && Array.isArray(rules) && diff --git a/src/lib/adapters/openshell/providers.ts b/src/lib/adapters/openshell/providers.ts index 56b299c2b4e..d1481a8a4dc 100644 --- a/src/lib/adapters/openshell/providers.ts +++ b/src/lib/adapters/openshell/providers.ts @@ -56,6 +56,7 @@ type ProfileContract = kind: "native-local"; binding: Parameters[1] & { profileId: string }; }; +type CustomNativeBinding = import("../../inference/native-provider/custom").CustomNativeBinding; export type Provider = Readonly< Pick & { @@ -84,6 +85,7 @@ export interface Providers { profileContract?: ProfileContract; nativeHostedEndpoint?: string; nativeHostedAllowedIps?: readonly string[]; + nativeHostedCustom?: CustomNativeBinding; }>, ): Promise; } @@ -118,7 +120,8 @@ async function readManagedProfile( ): Promise | null> { const profileId = profileContract === "native-hosted" - ? hostedNativeProfile(providerType, request.nativeHostedEndpoint)?.profileId + ? hostedNativeProfile(providerType, request.nativeHostedEndpoint, request.nativeHostedCustom) + ?.profileId : managedProfileId(profileContract); if ( providerType !== profileId || @@ -145,6 +148,7 @@ async function readManagedProfile( providerType, request.nativeHostedEndpoint, request.nativeHostedAllowedIps, + request.nativeHostedCustom, ); } @@ -182,6 +186,7 @@ function validateManagedProfileResponse( providerType: string, nativeHostedEndpoint?: string, nativeHostedAllowedIps?: readonly string[], + nativeHostedCustom?: CustomNativeBinding, ): NonNullable { if (typeof profileContract === "object") return validateNativeManagedProfileResponse( @@ -199,6 +204,7 @@ function validateManagedProfileResponse( providerType, nativeHostedEndpoint, nativeHostedAllowedIps, + nativeHostedCustom, ); } const { profile } = readValue( @@ -229,12 +235,14 @@ function validateNativeHostedManagedProfileResponse( providerType: string, nativeHostedEndpoint?: string, nativeHostedAllowedIps?: readonly string[], + nativeHostedCustom?: CustomNativeBinding, ): NonNullable { const validated = isManagedNativeHostedProfileResponse( response, providerType, nativeHostedEndpoint, nativeHostedAllowedIps, + nativeHostedCustom, ); if ( !validated || @@ -254,11 +262,13 @@ function managedInferenceEndpointFor( managedProfile: Provider["managedProfile"], contract: ProfileContract | undefined, nativeHostedEndpoint?: string, + nativeHostedCustom?: CustomNativeBinding, ): string | undefined { if (typeof contract === "object") return contract.binding.endpointUrl; return managedProfile?.id === NVIDIA_HOSTED_NATIVE_PROFILE_ID ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : hostedNativeProfile(managedProfile?.id ?? "", nativeHostedEndpoint)?.endpoint; + : hostedNativeProfile(managedProfile?.id ?? "", nativeHostedEndpoint, nativeHostedCustom) + ?.endpoint; } async function readProfileEvidence( @@ -297,6 +307,7 @@ async function readProfileEvidence( managedProfile, request.profileContract, request.nativeHostedEndpoint, + request.nativeHostedCustom, ); return { ...(builtinInferenceEndpoint === undefined ? {} : { builtinInferenceEndpoint }), diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 6f561ad77a0..8c47abb297e 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([ - "001bc67c3e46cb7916709dd159f230abdf6f52dd74dc0573b4eb7d089e6c6984", - "239043cc0620eb5110d45e830a8b6a9da11bb4ee875023468d44e9a4f2ab6739", + "900cc0ed35229b30cb7dfe7852dfc8a03433d0b742eb977192f82673f871a6fe", + "af27661bb60b1483d45468d5bc82ae7b2907a23006dee0cbfa660fd77b9094e4", ]), }); diff --git a/src/lib/core/provider-endpoint.ts b/src/lib/core/provider-endpoint.ts new file mode 100644 index 00000000000..42e240c8e0b --- /dev/null +++ b/src/lib/core/provider-endpoint.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { MAX_CANONICAL_ENDPOINT_LENGTH } from "./endpoint-url-safety.ts"; + +export function stripEndpointSuffix(pathname = "", suffixes: string[] = []): string { + for (const suffix of suffixes) { + if (pathname === suffix) return ""; + if (pathname.endsWith(suffix)) { + return pathname.slice(0, -suffix.length); + } + } + return pathname; +} + +export type EndpointFlavor = "anthropic" | "openai"; + +export function normalizeProviderBaseUrl( + value: string | URL | null | undefined, + flavor: EndpointFlavor, +): string { + const raw = String(value || "").trim(); + if (!raw) return ""; + + try { + const url = new URL(raw); + url.search = ""; + url.hash = ""; + const suffixes = + flavor === "anthropic" + ? ["/v1/messages", "/v1/models", "/v1", "/messages", "/models"] + : ["/responses", "/chat/completions", "/completions", "/models"]; + let pathname = stripEndpointSuffix(url.pathname.replace(/\/+$/, ""), suffixes); + pathname = pathname.replace(/\/+$/, ""); + url.pathname = pathname || "/"; + return url.pathname === "/" ? url.origin : `${url.origin}${url.pathname}`; + } catch { + return raw.replace(/[?#].*$/, "").replace(/\/+$/, ""); + } +} + +/** Return the bounded canonical form of a credential-free HTTP(S) provider endpoint. */ +export function canonicalEndpoint( + value: string | null | undefined, + flavor: EndpointFlavor, +): string | null { + const raw = typeof value === "string" ? value.trim() : ""; + if (!raw || raw.length > MAX_CANONICAL_ENDPOINT_LENGTH) return null; + try { + const parsed = new URL(raw); + if ( + (parsed.protocol !== "http:" && parsed.protocol !== "https:") || + parsed.username || + parsed.password + ) { + return null; + } + return normalizeProviderBaseUrl(parsed, flavor); + } catch { + return null; + } +} diff --git a/src/lib/core/url-utils.ts b/src/lib/core/url-utils.ts index 4c297fc4c6f..70f64592a61 100644 --- a/src/lib/core/url-utils.ts +++ b/src/lib/core/url-utils.ts @@ -6,70 +6,17 @@ * formatting helpers used across the CLI. */ -import { MAX_CANONICAL_ENDPOINT_LENGTH } from "./endpoint-url-safety.ts"; +export { + stripEndpointSuffix, + normalizeProviderBaseUrl, + canonicalEndpoint, + type EndpointFlavor, +} from "./provider-endpoint.ts"; export function compactText(value = ""): string { return String(value).replace(/\s+/g, " ").trim(); } -export function stripEndpointSuffix(pathname = "", suffixes: string[] = []): string { - for (const suffix of suffixes) { - if (pathname === suffix) return ""; - if (pathname.endsWith(suffix)) { - return pathname.slice(0, -suffix.length); - } - } - return pathname; -} - -export type EndpointFlavor = "anthropic" | "openai"; - -export function normalizeProviderBaseUrl( - value: string | URL | null | undefined, - flavor: EndpointFlavor, -): string { - const raw = String(value || "").trim(); - if (!raw) return ""; - - try { - const url = new URL(raw); - url.search = ""; - url.hash = ""; - const suffixes = - flavor === "anthropic" - ? ["/v1/messages", "/v1/models", "/v1", "/messages", "/models"] - : ["/responses", "/chat/completions", "/completions", "/models"]; - let pathname = stripEndpointSuffix(url.pathname.replace(/\/+$/, ""), suffixes); - pathname = pathname.replace(/\/+$/, ""); - url.pathname = pathname || "/"; - return url.pathname === "/" ? url.origin : `${url.origin}${url.pathname}`; - } catch { - return raw.replace(/[?#].*$/, "").replace(/\/+$/, ""); - } -} - -/** Return the bounded canonical form of a credential-free HTTP(S) provider endpoint. */ -export function canonicalEndpoint( - value: string | null | undefined, - flavor: EndpointFlavor, -): string | null { - const raw = typeof value === "string" ? value.trim() : ""; - if (!raw || raw.length > MAX_CANONICAL_ENDPOINT_LENGTH) return null; - try { - const parsed = new URL(raw); - if ( - (parsed.protocol !== "http:" && parsed.protocol !== "https:") || - parsed.username || - parsed.password - ) { - return null; - } - return normalizeProviderBaseUrl(parsed, flavor); - } catch { - return null; - } -} - export function isLoopbackHostname(hostname = ""): boolean { const normalized = String(hostname || "") .trim() diff --git a/src/lib/domain/config/export-source-test-fixture.ts b/src/lib/domain/config/export-source-test-fixture.ts index 531cfe90ba7..0a225045d99 100644 --- a/src/lib/domain/config/export-source-test-fixture.ts +++ b/src/lib/domain/config/export-source-test-fixture.ts @@ -518,6 +518,7 @@ export function compatibleSnapshot( "compatible-endpoint", "gpt-5", "openai-completions", + false, ); const input = { ...base, diff --git a/src/lib/domain/config/verify-export-source.ts b/src/lib/domain/config/verify-export-source.ts index 038026ecded..05e7ff996fd 100644 --- a/src/lib/domain/config/verify-export-source.ts +++ b/src/lib/domain/config/verify-export-source.ts @@ -7,7 +7,10 @@ import { cloneAndDeepFreeze } from "../../core/immutable"; import { resolveManagedStartupInferenceRoute } from "../../inference/gateway/route-contract"; import { normalizeInferenceSelection } from "../../inference/selection"; import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; -import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { + hostedNativeProvider, + isCustomHostedProvider, +} from "../../inference/native-provider/hosted"; import { fixedNativeProviderForAttachment } from "../../inference/native-provider/fixed"; import { BUILD_ENDPOINT_URL } from "../../inference/provider-models"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../inference/native-nvidia/contract"; @@ -575,7 +578,10 @@ function deepAgentsObservability( } function exportUsesNativeInference(entry: ObservedExportRegistry): boolean { - return !hostedNativeProvider(entry.provider) || Boolean(nativeExportReceipt(entry)); + return ( + (!hostedNativeProvider(entry.provider) && !isCustomHostedProvider(entry.provider)) || + Boolean(nativeExportReceipt(entry)) + ); } function exportRouteEndpoint(entry: ObservedExportRegistry): string | undefined { @@ -923,6 +929,35 @@ function receiptEndpointUrl(receipt: ReturnType): st : undefined; } +function expectedManagedEndpointRoute( + snapshot: QualifiedExportSnapshot, + receipt: NonNullable>, +) { + const definition = fixedNativeProviderForAttachment(receipt); + const identity = [ + receipt.profileId, + receipt.providerName, + receipt.providerId, + definition.logicalProvider, + ]; + if (receipt.custom) { + return [ + ...identity, + receipt.custom.api, + receipt.custom.endpointUrl, + receipt.endpointUrl, + receipt.custom.credentialEnv, + ]; + } + const hosted = hostedNativeProvider(snapshot.registry.provider, receipt.endpointUrl); + const endpoint = hosted?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT; + const api = + hosted?.logicalProvider === "openai-api" && snapshot.inference.api === "openai-responses" + ? "openai-responses" + : (hosted?.api ?? "openai-completions"); + return [...identity, api, endpoint, endpoint, definition.credentialEnv]; +} + function managedEndpointEvidenceMatchesRoute( snapshot: QualifiedExportSnapshot, evidence: NonNullable & { @@ -931,14 +966,7 @@ function managedEndpointEvidenceMatchesRoute( ): boolean { const { inference } = snapshot; const receipt = nativeExportReceipt(snapshot.registry); - if (!receipt) return false; - const definition = fixedNativeProviderForAttachment(receipt); - const hosted = hostedNativeProvider(snapshot.registry.provider, receiptEndpointUrl(receipt)); - const endpoint = hosted?.endpoint ?? NVIDIA_HOSTED_NATIVE_ENDPOINT; - const api = - hosted?.logicalProvider === "openai-api" && inference.api === "openai-responses" - ? "openai-responses" - : (hosted?.api ?? "openai-completions"); + if (!receipt || "provider" in receipt) return false; return isDeepStrictEqual( [ evidence.source.profileId, @@ -950,16 +978,7 @@ function managedEndpointEvidenceMatchesRoute( evidence.endpoint, inference.credentialEnv, ], - [ - receipt.profileId, - receipt.providerName, - receipt.providerId, - definition.logicalProvider, - api, - endpoint, - endpoint, - definition.credentialEnv, - ], + expectedManagedEndpointRoute(snapshot, receipt), ); } @@ -1367,6 +1386,15 @@ function expectedEndpointProviderName(snapshot: QualifiedExportSnapshot): string return nativeExportReceipt(snapshot.registry)?.providerName ?? snapshot.inference.provider; } +function endpointEvidenceMatchesExportEndpoint(snapshot: QualifiedExportSnapshot): boolean { + const { inference } = snapshot; + // Managed profiles can transform the selected endpoint. Both endpoints must + // still match their independently verified receipt fields. + if (inference.endpointEvidence?.source.kind === "managed-profile") + return endpointEvidenceMatchesRoute(snapshot); + return inference.endpointEvidence?.endpoint === inference.endpoint; +} + function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFinding[] { const { inference, sandbox, gateway } = snapshot; const evidence = inference.endpointEvidence; @@ -1393,7 +1421,7 @@ function validateEndpointEvidence(snapshot: QualifiedExportSnapshot): ExportFind "The live inference endpoint evidence is invalid or unsafe.", ), ); - if (evidence.endpoint !== inference.endpoint) + if (!endpointEvidenceMatchesExportEndpoint(snapshot)) findings.push( finding( "spec.inferenceProviders[].endpoint", diff --git a/src/lib/inference/config.ts b/src/lib/inference/config.ts index c568a1f9f33..0bbff0d1aa1 100644 --- a/src/lib/inference/config.ts +++ b/src/lib/inference/config.ts @@ -19,6 +19,12 @@ import { LLAMA_CPP_PROVIDER_NAME, } from "./llama-cpp/contract"; import { hostedNativeProvider, usesNativeHermesEndpoint } from "./native-provider/hosted"; +import { isCustomHostedProvider, resolveCustomNativeApi } from "./native-provider/hosted"; +import { + isBedrockRuntimeEndpoint, + BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, +} from "./bedrock-runtime"; +import { getCompatibleAnthropicOpenAiSurfaceBaseUrl } from "./anthropic/openai-surface"; import { nativeOpenClawProviderKey } from "./native-provider/fixed"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "./native-nvidia"; import type { ManagedLlamaCppOwnership } from "./llama-cpp/managed-state"; @@ -340,7 +346,12 @@ export function getSandboxInferenceConfig( nativeEndpointUrl?: string | null, agentName?: string | null, ): SandboxInferenceConfig { - let providerKey: string = nativeOpenClawProviderKey(provider) ?? MANAGED_PROVIDER_ID; + const nativeCustom = + nativeProvider === true && + isCustomHostedProvider(provider) && + !usesNativeLocalInference(provider, nativeEndpointUrl); + const selectedApi = resolveCustomNativeApi(provider, preferredInferenceApi, nativeCustom); + let providerKey: string = nativeOpenClawProviderKey(provider, selectedApi) ?? MANAGED_PROVIDER_ID; let primaryModelRef: string; const useNativeProvider = nativeProvider ?? @@ -348,8 +359,17 @@ export function getSandboxInferenceConfig( const hostedNative = useNativeProvider ? hostedNativeProvider(provider, nativeEndpointUrl) : undefined; - let inferenceBaseUrl = hostedNative?.endpoint ?? INFERENCE_ROUTE_URL; - let inferenceApi = preferredInferenceApi || "openai-completions"; + let customEndpoint = nativeCustom ? nativeEndpointUrl : undefined; + if (nativeCustom && !customEndpoint) + throw new Error("Native custom inference is missing its recorded endpoint"); + if (customEndpoint && provider === "compatible-anthropic-endpoint") + customEndpoint = isBedrockRuntimeEndpoint(customEndpoint) + ? BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL + : selectedApi && selectedApi !== "anthropic-messages" + ? getCompatibleAnthropicOpenAiSurfaceBaseUrl(customEndpoint) + : customEndpoint; + let inferenceBaseUrl = customEndpoint ?? hostedNative?.endpoint ?? INFERENCE_ROUTE_URL; + let inferenceApi = selectedApi || "openai-completions"; // Providers without a /v1/responses endpoint must never be configured with the // Responses API. On a provider switch the runtime API resolves to null and the // caller falls back to the persisted (shared "inference") provider api, which @@ -367,7 +387,11 @@ export function getSandboxInferenceConfig( break; case "anthropic-prod": case "compatible-anthropic-endpoint": - if (provider === "compatible-anthropic-endpoint" && inferenceApi === "openai-completions") { + if ( + provider === "compatible-anthropic-endpoint" && + (inferenceApi === "openai-completions" || + (nativeCustom && inferenceApi === "openai-responses")) + ) { providerKey = MANAGED_PROVIDER_ID; primaryModelRef = `${MANAGED_PROVIDER_ID}/${model}`; inferenceCompat = { @@ -375,9 +399,9 @@ export function getSandboxInferenceConfig( }; break; } - if (provider === "compatible-anthropic-endpoint") providerKey = "anthropic"; + providerKey = "anthropic"; primaryModelRef = `anthropic/${model}`; - inferenceBaseUrl = hostedNative?.endpoint ?? "https://inference.local"; + inferenceBaseUrl = customEndpoint ?? hostedNative?.endpoint ?? "https://inference.local"; inferenceApi = "anthropic-messages"; break; case "gemini-api": diff --git a/src/lib/inference/native-provider/agent-config.ts b/src/lib/inference/native-provider/agent-config.ts index 6199c490fe4..86939a3df04 100644 --- a/src/lib/inference/native-provider/agent-config.ts +++ b/src/lib/inference/native-provider/agent-config.ts @@ -1,12 +1,30 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { hostedNativeProvider } from "./hosted.ts"; +import { + hostedNativeProvider, + customNativeCredentialEnv, + isCustomHostedProvider, +} from "./hosted.ts"; export { hostedNativeProvider }; /** Public configuration only. Never read the host's provider credential here. */ export function nativeHostedAgentConfig(provider: string | null | undefined, baseUrl: string) { + if (isCustomHostedProvider(provider) && new URL(baseUrl).hostname !== "inference.local") { + const endpoint = new URL(baseUrl); + if ( + !["https:", "http:"].includes(endpoint.protocol) || + endpoint.username || + endpoint.password || + endpoint.search || + endpoint.hash + ) + throw new Error("Invalid native custom inference endpoint"); + if (["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname)) return undefined; + const credentialEnv = customNativeCredentialEnv(provider!); + return { credentialEnv, apiKey: `openshell:resolve:env:${credentialEnv}` }; + } if (!hostedNativeProvider(provider)) return undefined; // Existing shared-route selections keep their original configuration until explicitly changed. if (new URL(baseUrl).hostname === "inference.local") return undefined; diff --git a/src/lib/inference/native-provider/contract.ts b/src/lib/inference/native-provider/contract.ts index 1134c47a06a..733c0189e40 100644 --- a/src/lib/inference/native-provider/contract.ts +++ b/src/lib/inference/native-provider/contract.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { isDeepStrictEqual } from "node:util"; +import type { CustomNativeBinding } from "./custom"; export type NativeProviderAttachment< ProfileId extends string = string, @@ -11,10 +12,11 @@ export type NativeProviderAttachment< profileId: ProfileId; providerName: ProviderName; providerId: string; - /** Present only for Hermes endpoints returned by authenticated login. */ + /** Exact sandbox-facing endpoint for a dynamically bound provider. */ endpointUrl?: string; - /** Exact public destination addresses for an authenticated Hermes endpoint. */ + /** Exact admitted destination addresses for a dynamically bound provider. */ allowedIps?: readonly string[]; + custom?: CustomNativeBinding; }>; export type NativeProviderDefinition< @@ -27,8 +29,9 @@ export type NativeProviderDefinition< providerName: ProviderName; credentialEnv: string; endpointUrl?: string; - /** Exact public destination addresses for an authenticated Hermes endpoint. */ + /** Exact admitted destination addresses for a dynamically bound provider. */ allowedIps?: readonly string[]; + custom?: CustomNativeBinding; }>; /** Keep only the exact profile/name binding and immutable provider identity. */ @@ -36,7 +39,7 @@ export function normalizeNativeProviderAttachment

, - "profileId" | "providerName" | "endpointUrl" | "allowedIps" + "profileId" | "providerName" | "endpointUrl" | "allowedIps" | "custom" >, ): NativeProviderAttachment | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; @@ -47,6 +50,7 @@ export function normalizeNativeProviderAttachment

NativeProviderAttachment | undefined; + writeAuthority: (gateway: string, provider: string, receipt: NativeProviderAttachment) => void; + onCredentialPersisted?: (credentialEnv: string, value: string) => void; +}): Promise { + if (unsafeEndpointUrlViolation(input.endpointUrl) || /%2f|%5c|%2e/iu.test(input.endpointUrl)) + throw new Error("Custom native inference requires a valid credential-free HTTP(S) endpoint"); + const api = input.api === "responses" ? "openai-responses" : input.api; + const endpointUrl = normalizeProviderBaseUrl( + input.endpointUrl, + input.provider === "compatible-anthropic-endpoint" ? "anthropic" : "openai", + ); + const classified = + input.provider === "compatible-anthropic-endpoint" + ? classifyCustomAnthropicEndpoint(input.endpointUrl) + : undefined; + const bedrock = classified?.kind === "bedrock-runtime" ? classified : undefined; + const previous = input.recordedAttachment + ? requireHostedProviderAttachment(input.recordedAttachment, input.provider) + : undefined; + const sameBinding = + previous?.custom && + previous.custom.endpointUrl === endpointUrl && + previous.custom.api === api && + previous.custom.credentialEnv === input.credentialEnv; + const admitted = + sameBinding || bedrock + ? undefined + : await assertEndpointResolvesPublic(endpointUrl, input.lookup, { + trustedPrivateHosts: + input.trustedPrivateHosts ?? parseTrustedPrivateInferenceHostsFromEnv(process.env), + }); + if (admitted && !admitted.ok) + throw new Error(`Custom native endpoint admission failed: ${admitted.reason}`); + const definition = customNativeProvider({ + provider: input.provider, + endpointUrl, + api, + credentialEnv: input.credentialEnv, + allowedIps: sameBinding + ? previous.custom!.allowedIps + : admitted?.ok + ? admitted.addresses?.length + ? admitted.addresses + : [new URL(endpointUrl).hostname.replace(/^\[|\]$/gu, "")] + : [], + ...(bedrock ? { adapterEndpointUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL } : {}), + } satisfies Omit & { provider: string; api: string }); + const lifecycle = nativeProviderLifecycle(definition); + const expected = lifecycle.resolveGatewayNativeProviderAuthority({ + gatewayName: input.gatewayName, + gatewayAuthority: input.readAuthority(input.gatewayName, definition.providerName), + recordedAttachment: sameBinding ? previous : undefined, + }); + // A credential key name alone cannot authorize reuse at a different endpoint or API. + if (!input.credentialValue && !expected && !(bedrock && hasBedrockRuntimeAwsAuthEnv())) + throw new Error( + `A new credential is required for this endpoint and API. Set ${input.credentialEnv} and retry. No provider was changed.`, + ); + const target = { kind: "named", gatewayName: input.gatewayName } as const; + let credentialValue = expected ? null : input.credentialValue; + if (bedrock && !expected) { + // Reject profile collisions before the existing adapter can start a process. + await lifecycle.requireNativeProviderProfileBoundary(input.adapter, target); + const transport = await (input.ensureBedrockAdapter ?? ensureBedrockRuntimeAdapter)({ + classification: bedrock, + compatibleCredential: input.credentialValue, + }); + if (transport.baseUrl !== definition.endpointUrl) + throw new Error("Bedrock adapter endpoint does not match native provider authority"); + credentialValue = expected ? null : transport.token; + } + const receipt = await lifecycle.ensureNativeProvider({ + adapter: input.adapter, + target, + // Model changes and rebuilds reuse verified ownership without rotating credentials. + credentialValue, + ...(expected ? { expected } : {}), + }); + await lifecycle.persistNativeProviderAuthority({ + adapter: input.adapter, + target, + gatewayName: input.gatewayName, + receipt, + ...(expected ? { existing: expected } : {}), + readAuthority: (gateway) => input.readAuthority(gateway, definition.providerName), + writeAuthority: (gateway, authority) => + input.writeAuthority(gateway, input.provider, authority), + }); + // Reuse does not prove that an ambient legacy value was stored. Bedrock + // stores an adapter token, so its source credential is not retired here. + if (!expected && !bedrock && credentialValue) + input.onCredentialPersisted?.(input.credentialEnv, credentialValue); + return receipt; +} diff --git a/src/lib/inference/native-provider/custom.test.ts b/src/lib/inference/native-provider/custom.test.ts new file mode 100644 index 00000000000..2012c9d753c --- /dev/null +++ b/src/lib/inference/native-provider/custom.test.ts @@ -0,0 +1,453 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import YAML from "yaml"; +import { describe, expect, it, vi } from "vitest"; +import type { OpenShellProviderAdapter } from "../../adapters/openshell/provider-adapter"; +import type { NativeProviderAttachment } from "./contract"; +import { boundCustomNativeProfile, customNativeProvider } from "./custom"; +import { recordedNativeProviderAttachment } from "./recorded-selection"; +import { prepareCustomNativeProvider, usesCustomNativeOnboarding } from "./custom-setup"; +import { requireHostedProviderAttachment } from "./hosted-attachment"; +import { buildNativeHostedSandboxPolicy } from "./network-policy"; +import { nativeProviderLifecycle } from "./index"; +import { getSandboxInferenceConfig } from "../config"; +import { nativeHostedAgentConfig } from "./agent-config"; +import { createResumeProviderShim } from "../../onboard/machine/resume-provider-shim"; +import { BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL } from "../bedrock-runtime"; + +const binding = { + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/team/v1", + api: "openai-completions", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], +} as const; + +function harness() { + let present = false; + let receipt: NativeProviderAttachment | undefined; + let definition = customNativeProvider(binding); + const attachments = new Map([["other", ["unrelated-provider"]]]); + const adapter = { + importProviderProfile: vi.fn( + async ({ profilePath }) => { + const profile = YAML.parse(fs.readFileSync(profilePath, "utf8")); + expect(profile.id).toBe(definition.profileId); + return { ok: true }; + }, + ), + ensureProviderPolicyComposition: vi.fn(async () => ({ ok: true, value: undefined })), + getProvider: vi.fn(async () => + present + ? { + ok: true, + value: { + name: definition.providerName, + type: definition.profileId, + credentialKeys: [definition.credentialEnv], + configKeys: [], + revision: { id: "identity", resourceVersion: 1 }, + }, + } + : { ok: false, error: { kind: "command", reason: "not_found", message: "absent" } }, + ), + createProvider: vi.fn(async () => { + present = true; + return { ok: true }; + }), + updateProvider: vi.fn(), + listProviderAttachments: vi.fn( + async ({ sandboxName }) => ({ + ok: true, + value: { names: [...(attachments.get(sandboxName) ?? [])] }, + }), + ), + attachProvider: vi.fn( + async ({ sandboxName, providerName }) => { + attachments.set(sandboxName, [...(attachments.get(sandboxName) ?? []), providerName]); + return { ok: true }; + }, + ), + detachProvider: vi.fn( + async ({ sandboxName, providerName }) => { + attachments.set( + sandboxName, + (attachments.get(sandboxName) ?? []).filter((name) => name !== providerName), + ); + return { ok: true, value: { changed: true } }; + }, + ), + }; + const lookup = vi.fn(async () => [{ address: "8.8.8.8", family: 4 }]); + const writeAuthority = vi.fn( + (_gateway: string, _provider: string, value: NativeProviderAttachment) => { + receipt = value; + }, + ); + const input = { + gatewayName: "gateway", + provider: binding.provider, + endpointUrl: binding.endpointUrl, + api: binding.api, + credentialEnv: binding.credentialEnv, + credentialValue: "synthetic-host-secret", + lookup, + adapter: adapter as unknown as OpenShellProviderAdapter, + readAuthority: (_gateway: string, name: string) => + receipt?.providerName === name ? receipt : undefined, + writeAuthority, + }; + return { + adapter, + input, + lookup, + writeAuthority, + attachments, + select: (value: Parameters[0]) => { + definition = customNativeProvider(value); + }, + }; +} + +describe("custom native endpoint ownership", () => { + it.each([ + ["compatible-endpoint", "openai-completions", "/team/v1/chat/completions"], + ["compatible-endpoint", "openai-responses", "/team/v1/responses"], + ["compatible-anthropic-endpoint", "anthropic-messages", "/team/v1/messages"], + ["compatible-anthropic-endpoint", "openai-completions", "/team/v1/chat/completions"], + ["compatible-anthropic-endpoint", "openai-responses", "/team/v1/responses"], + ])( + "binds %s %s to the same agent, profile and health destination", + (provider, api, requestPath) => { + const endpointUrl = + provider === "compatible-endpoint" ? binding.endpointUrl : "https://custom.example/team"; + const definition = customNativeProvider({ ...binding, endpointUrl, provider, api }); + const profile = YAML.parse( + boundCustomNativeProfile( + definition, + nativeProviderLifecycle(definition).nativeProviderProfilePath(), + ), + ); + expect(profile.endpoints[0]).toMatchObject({ + host: "custom.example", + port: 443, + allowed_ips: binding.allowedIps, + enforcement: "enforce", + rules: expect.arrayContaining([{ allow: { method: "POST", path: requestPath } }]), + }); + expect( + profile.endpoints[0].rules.every( + (rule: { allow: { path: string } }) => !rule.allow.path.includes("*"), + ), + ).toBe(true); + expect(profile.binaries).not.toContain("*"); + expect(profile.credentials[0].env_vars).toEqual([definition.credentialEnv]); + const config = getSandboxInferenceConfig("selected-model", provider, api, true, endpointUrl); + expect(config.inferenceBaseUrl).toBe(definition.endpointUrl); + expect(config.inferenceApi).toBe(api); + expect(config.primaryModelRef).toBe( + `${api === "anthropic-messages" ? "anthropic" : "inference"}/selected-model`, + ); + expect(nativeHostedAgentConfig(provider, config.inferenceBaseUrl)?.apiKey).toBe( + `openshell:resolve:env:${definition.credentialEnv}`, + ); + }, + ); + + it.each([ + ["compatible-endpoint", "openai-completions", "https://custom.example/team/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example/team"], + ])( + "uses the native %s default API when selection is omitted (#13195)", + (provider, api, endpointUrl) => { + const definition = customNativeProvider({ ...binding, provider, api, endpointUrl }); + const config = getSandboxInferenceConfig("selected-model", provider, null, true, endpointUrl); + expect(config).toMatchObject({ + inferenceApi: definition.api, + inferenceBaseUrl: definition.endpointUrl, + primaryModelRef: `${api === "anthropic-messages" ? "anthropic" : "inference"}/selected-model`, + }); + }, + ); + + it("keeps endpoint, API, credential source and pin authorities distinct", () => { + const names = [ + binding, + { ...binding, endpointUrl: "https://other.example/team/v1" }, + { ...binding, api: "openai-responses" }, + { ...binding, credentialEnv: "OTHER_KEY" }, + { ...binding, allowedIps: ["1.1.1.1"] }, + ].map((value) => customNativeProvider(value).providerName); + expect(new Set(names).size).toBe(names.length); + }); + + it.each([ + "ftp://custom.example/v1", + "https://user:secret@custom.example/v1", + "https://custom.example/v1?key=secret", + "https://custom.example/v1#fragment", + "https://custom.example/%2e%2e/v1", + "https://inference.local/v1", + "https://127.0.0.1/v1", + ])("rejects unsafe endpoint %s before resource mutation", async (endpointUrl) => { + const h = harness(); + await expect(prepareCustomNativeProvider({ ...h.input, endpointUrl })).rejects.toThrow(); + expect(h.adapter.importProviderProfile).not.toHaveBeenCalled(); + expect(h.adapter.createProvider).not.toHaveBeenCalled(); + }); + + it("rejects a private DNS answer and missing API credentials before import", async () => { + const h = harness(); + await expect( + prepareCustomNativeProvider({ + ...h.input, + lookup: async () => [{ address: "169.254.169.254" }], + }), + ).rejects.toThrow("admission failed"); + await expect( + prepareCustomNativeProvider({ ...h.input, credentialValue: null }), + ).rejects.toThrow("A new credential is required"); + await expect(prepareCustomNativeProvider({ ...h.input, api: "unsupported" })).rejects.toThrow( + "Invalid custom", + ); + expect(h.adapter.importProviderProfile).not.toHaveBeenCalled(); + }); + + it.each([ + ["https://custom.example/team/v1", ["10.0.0.8"], ["custom.example"]], + ["https://8.8.8.8/team/v1", ["8.8.8.8"], []], + ] as const)( + "admits exact pins for %s without widening the host", + async (endpointUrl, addresses, trustedPrivateHosts) => { + const h = harness(); + h.select({ ...binding, endpointUrl, allowedIps: addresses }); + const result = await prepareCustomNativeProvider({ + ...h.input, + endpointUrl, + trustedPrivateHosts, + lookup: async () => addresses.map((address) => ({ address })), + }); + const policy = YAML.parse( + buildNativeHostedSandboxPolicy("network_policies: {}", result.providerName, result), + ); + expect(policy.network_policies.native_hosted_inference.endpoints[0].allowed_ips).toEqual( + addresses, + ); + }, + ); + + it("reuses verified credentials without rotating them, even when a host key is present", async () => { + const h = harness(); + const onCredentialPersisted = vi.fn(); + const first = await prepareCustomNativeProvider({ ...h.input, onCredentialPersisted }); + expect(onCredentialPersisted).toHaveBeenCalledExactlyOnceWith( + binding.credentialEnv, + "synthetic-host-secret", + ); + onCredentialPersisted.mockClear(); + const second = await prepareCustomNativeProvider({ + ...h.input, + recordedAttachment: first, + credentialValue: "another-host-key", + onCredentialPersisted, + lookup: async () => { + throw new Error("Do not re-resolve admitted pins"); + }, + }); + expect(second).toEqual(first); + expect(onCredentialPersisted).not.toHaveBeenCalled(); + expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); + expect(h.adapter.updateProvider).not.toHaveBeenCalled(); + expect(JSON.stringify(h.writeAuthority.mock.calls)).not.toContain("synthetic-host-secret"); + expect(fs.existsSync(h.adapter.importProviderProfile.mock.calls[0][0].profilePath)).toBe(false); + await expect( + prepareCustomNativeProvider({ + ...h.input, + recordedAttachment: first, + credentialValue: null, + api: "openai-responses", + }), + ).rejects.toThrow("A new credential is required"); + expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); + }); + + it("reuses recorded authority after resume without a session credential (#13195)", async () => { + const h = harness(); + const first = await prepareCustomNativeProvider(h.input); + const replaceNamedCredential = vi.fn(async () => "unexpected"); + const shim = createResumeProviderShim({ + getSandbox: () => ({ nativeHostedProviderAttachment: first }), + isNonInteractive: () => true, + providerExistsInGateway: vi.fn(() => false), + isRoutedInferenceProvider: () => false, + replaceNamedCredential, + }); + const recovery = await shim.ensureResumeProviderReady( + h.input.gatewayName, + binding.provider, + null, + undefined, + { sandboxName: "alpha", endpointUrl: binding.endpointUrl }, + ); + const onCredentialPersisted = vi.fn(); + const resumed = await prepareCustomNativeProvider({ + ...h.input, + recordedAttachment: first, + credentialEnv: recovery.credentialEnv!, + credentialValue: null, + onCredentialPersisted, + }); + expect(resumed).toEqual(first); + expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); + expect(h.adapter.updateProvider).not.toHaveBeenCalled(); + expect(replaceNamedCredential).not.toHaveBeenCalled(); + expect(onCredentialPersisted).not.toHaveBeenCalled(); + }); + + it("does not retire a credential when authority persistence fails", async () => { + const h = harness(); + const onCredentialPersisted = vi.fn(); + await expect( + prepareCustomNativeProvider({ + ...h.input, + onCredentialPersisted, + writeAuthority: () => { + throw new Error("authority write failed"); + }, + }), + ).rejects.toThrow("authority write failed"); + expect(onCredentialPersisted).not.toHaveBeenCalled(); + }); + + it("rejects profile collisions before provider or attachment changes", async () => { + const h = harness(); + h.adapter.importProviderProfile.mockResolvedValue({ + ok: false, + error: { kind: "command", reason: "profile_incompatible", message: "collision" }, + }); + await expect(prepareCustomNativeProvider(h.input)).rejects.toThrow("conflicts"); + expect(h.adapter.createProvider).not.toHaveBeenCalled(); + expect(h.adapter.attachProvider).not.toHaveBeenCalled(); + }); + + it("observes an ambiguous create once and changes access only on the selected sandbox", async () => { + const h = harness(); + const create = h.adapter.createProvider.getMockImplementation()!; + h.adapter.createProvider.mockImplementation(async (request) => { + await create(request); + return { ok: false, error: { kind: "timeout", message: "timeout" } } as Awaited< + ReturnType + >; + }); + const receipt = await prepareCustomNativeProvider(h.input); + const lifecycle = nativeProviderLifecycle(customNativeProvider(binding)); + const operation = { + adapter: h.input.adapter, + target: { kind: "named", gatewayName: "gateway" } as const, + sandboxName: "selected", + expected: receipt, + }; + await lifecycle.ensureNativeProviderAttached(operation); + expect(h.attachments.get("selected")).toEqual([receipt.providerName]); + expect(h.attachments.get("other")).toEqual(["unrelated-provider"]); + await lifecycle.detachNativeProvider(operation); + expect(h.attachments.get("selected")).toEqual([]); + expect(h.attachments.get("other")).toEqual(["unrelated-provider"]); + expect(h.adapter.createProvider).toHaveBeenCalledTimes(1); + }); + + it("keeps existing shared routes and rejects mismatched durable native selection", async () => { + expect(usesCustomNativeOnboarding(binding.provider, binding.endpointUrl, "alpha", {})).toBe( + false, + ); + expect(usesCustomNativeOnboarding(binding.provider, binding.endpointUrl, "alpha", null)).toBe( + true, + ); + expect( + usesCustomNativeOnboarding(binding.provider, "http://127.0.0.1:8080/v1", "alpha", null), + ).toBe(false); + const h = harness(); + const receipt = await prepareCustomNativeProvider(h.input); + expect( + recordedNativeProviderAttachment({ + provider: binding.provider, + endpointUrl: binding.endpointUrl, + credentialEnv: binding.credentialEnv, + preferredInferenceApi: binding.api, + nativeHostedProviderAttachment: receipt, + }), + ).toEqual(receipt); + expect(() => + recordedNativeProviderAttachment({ + provider: binding.provider, + preferredInferenceApi: "openai-responses", + nativeHostedProviderAttachment: receipt, + }), + ).toThrow("does not match"); + }); + + it("rejects altered receipts and unsafe recorded pins", async () => { + const h = harness(); + const receipt = await prepareCustomNativeProvider(h.input); + expect(() => + requireHostedProviderAttachment( + { ...receipt, endpointUrl: "https://other.example/v1" }, + binding.provider, + ), + ).toThrow(); + }); + + it.each([[[]], [["127.0.0.1"]], [["169.254.169.254"]], [["0.0.0.0/0"]]])( + "rejects unsafe recorded pins %j", + (allowedIps) => { + expect(() => customNativeProvider({ ...binding, allowedIps })).toThrow(); + }, + ); + + it("keeps Bedrock AWS credentials in the existing adapter and injects only its token", async () => { + const h = harness(); + const onCredentialPersisted = vi.fn(); + const bedrock = { + ...binding, + provider: "compatible-anthropic-endpoint", + endpointUrl: "https://bedrock-runtime.us-east-1.amazonaws.com", + allowedIps: [], + adapterEndpointUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, + }; + h.select(bedrock); + const ensureBedrockAdapter = vi.fn(async () => ({ + baseUrl: BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, + token: "synthetic-adapter-token", + })) as unknown as NonNullable< + Parameters[0]["ensureBedrockAdapter"] + >; + const receipt = await prepareCustomNativeProvider({ + ...h.input, + provider: bedrock.provider, + endpointUrl: bedrock.endpointUrl, + ensureBedrockAdapter, + onCredentialPersisted, + }); + expect(h.adapter.createProvider).toHaveBeenCalledWith( + expect.objectContaining({ + credentials: [{ name: "COMPATIBLE_ANTHROPIC_API_KEY", value: "synthetic-adapter-token" }], + }), + ); + expect(receipt.endpointUrl).toBe(BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL); + await prepareCustomNativeProvider({ + ...h.input, + provider: bedrock.provider, + endpointUrl: bedrock.endpointUrl, + credentialValue: null, + recordedAttachment: receipt, + ensureBedrockAdapter, + }); + expect(ensureBedrockAdapter).toHaveBeenCalledTimes(1); + expect(h.adapter.updateProvider).not.toHaveBeenCalled(); + expect(JSON.stringify(receipt)).not.toContain("synthetic-"); + expect(h.lookup).not.toHaveBeenCalled(); + expect(onCredentialPersisted).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/inference/native-provider/custom.ts b/src/lib/inference/native-provider/custom.ts new file mode 100644 index 00000000000..d5a990ea77b --- /dev/null +++ b/src/lib/inference/native-provider/custom.ts @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import { isIP } from "node:net"; +import os from "node:os"; +import path from "node:path"; +import YAML from "yaml"; +import { + MAX_CANONICAL_ENDPOINT_LENGTH, + unsafeEndpointUrlViolation, +} from "../../core/endpoint-url-safety"; +import { normalizeProviderBaseUrl } from "../../core/provider-endpoint"; +import type { NativeProviderDefinition } from "./contract"; +import { nativeHostedAgentConfig } from "./agent-config"; +import { isPrivateIp, isLoopbackHostname } from "../../private-networks"; +import { + isOperatorTrustablePrivateIp, + isOpenShellManagedHost, +} from "../../security/trusted-private-endpoint"; +import { + isBedrockRuntimeEndpoint, + BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, +} from "../bedrock-runtime"; +import { getCompatibleAnthropicOpenAiSurfaceBaseUrl } from "../anthropic/openai-surface"; + +export type CustomNativeBinding = Readonly<{ + provider: "compatible-endpoint" | "compatible-anthropic-endpoint"; + endpointUrl: string; + api: "openai-completions" | "openai-responses" | "anthropic-messages"; + /** Host credential lookup name, never its value. */ + credentialEnv: string; + allowedIps: readonly string[]; + /** Existing Bedrock adapter transport; AWS credentials remain in its host process. */ + adapterEndpointUrl?: string; +}>; + +/** Hosted selections exclude the existing loopback and managed bridge routes. */ +export function isHostedCustomEndpoint( + provider: string, + endpointUrl: string | null | undefined, +): boolean { + if ( + (provider !== "compatible-endpoint" && provider !== "compatible-anthropic-endpoint") || + !endpointUrl + ) + return false; + const host = new URL(endpointUrl).hostname; + return !isLoopbackHostname(host) && !isOpenShellManagedHost(host); +} + +export function isCustomNativeProviderName(name: string): boolean { + return /^nemoclaw-custom-[a-f0-9]{32}-v1$/u.test(name); +} + +/** Validate persisted shape without granting DNS or credential authority. */ +export function customNativeProvider(value: unknown): NativeProviderDefinition & { + endpoint: string; + api: CustomNativeBinding["api"]; + custom: CustomNativeBinding; +} { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Missing custom native provider binding"); + const binding = value as CustomNativeBinding; + if ( + (binding.provider !== "compatible-endpoint" && + binding.provider !== "compatible-anthropic-endpoint") || + !["openai-completions", "openai-responses", "anthropic-messages"].includes(binding.api) || + (binding.provider === "compatible-endpoint" && binding.api === "anthropic-messages") || + !/^[A-Z_][A-Z0-9_]*$/u.test(binding.credentialEnv ?? "") || + typeof binding.endpointUrl !== "string" || + binding.endpointUrl.length > MAX_CANONICAL_ENDPOINT_LENGTH || + unsafeEndpointUrlViolation(binding.endpointUrl) || + /%2f|%5c|%2e/iu.test(binding.endpointUrl) + ) + throw new Error("Invalid custom native provider binding"); + const endpoint = new URL(binding.endpointUrl); + if (isOpenShellManagedHost(endpoint.hostname) || isLoopbackHostname(endpoint.hostname)) + throw new Error("Custom hosted native inference requires a hosted endpoint"); + const canonical = normalizeProviderBaseUrl( + binding.endpointUrl, + binding.provider === "compatible-anthropic-endpoint" ? "anthropic" : "openai", + ); + if (canonical !== binding.endpointUrl) throw new Error("Custom native endpoint is not canonical"); + const bedrock = + binding.provider === "compatible-anthropic-endpoint" && isBedrockRuntimeEndpoint(canonical); + const adapter = binding.adapterEndpointUrl ? new URL(binding.adapterEndpointUrl) : undefined; + if ( + bedrock !== Boolean(adapter) || + (adapter && + (binding.api !== "openai-completions" || + binding.adapterEndpointUrl !== BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL)) + ) + throw new Error("Invalid native Bedrock adapter binding"); + if ( + !Array.isArray(binding.allowedIps) || + (!bedrock && binding.allowedIps.length === 0) || + (bedrock && binding.allowedIps.length !== 0) || + binding.allowedIps.some( + (address) => + typeof address !== "string" || + !isIP(address) || + address.includes("%") || + (isPrivateIp(address) && !isOperatorTrustablePrivateIp(address)), + ) || + new Set(binding.allowedIps).size !== binding.allowedIps.length + ) + throw new Error("Custom native inference requires exact destination addresses"); + const custom: CustomNativeBinding = { + provider: binding.provider, + endpointUrl: canonical, + api: binding.api, + credentialEnv: binding.credentialEnv, + allowedIps: [...binding.allowedIps].sort(), + ...(adapter ? { adapterEndpointUrl: binding.adapterEndpointUrl } : {}), + }; + const suffix = createHash("sha256").update(JSON.stringify(custom)).digest("hex").slice(0, 32); + const nativeEndpoint = + custom.adapterEndpointUrl ?? + (custom.provider === "compatible-anthropic-endpoint" && custom.api !== "anthropic-messages" + ? getCompatibleAnthropicOpenAiSurfaceBaseUrl(canonical) + : canonical); + return { + logicalProvider: custom.provider, + label: "custom hosted", + profileId: `nemoclaw-custom-${suffix}-v1`, + providerName: `nemoclaw-custom-${suffix}-v1`, + credentialEnv: nativeHostedAgentConfig(custom.provider, nativeEndpoint)!.credentialEnv, + endpointUrl: nativeEndpoint, + endpoint: nativeEndpoint, + ...(custom.allowedIps.length ? { allowedIps: custom.allowedIps } : {}), + api: custom.api, + custom, + }; +} + +/** Bind the existing executable and credential boundary to one selected API. */ +export function boundCustomNativeProfile( + definition: NativeProviderDefinition, + templatePath: string, +): string { + const expected = customNativeProvider(definition.custom); + if ( + expected.profileId !== definition.profileId || + expected.providerName !== definition.providerName + ) + throw new Error("Custom native provider identity does not match its binding"); + const anthropic = expected.api === "anthropic-messages"; + const profile = YAML.parse(fs.readFileSync(templatePath, "utf8")); + const endpoint = new URL(expected.endpoint); + const prefix = endpoint.pathname.replace(/\/+$/u, ""); + const apiPrefix = anthropic ? `${prefix}/v1` : prefix; + const requestPath = anthropic + ? "messages" + : expected.api === "openai-responses" + ? "responses" + : "chat/completions"; + profile.id = expected.profileId; + profile.display_name = "NemoClaw Custom Hosted Inference"; + profile.description = "Native inference for one validated sandbox endpoint and API"; + profile.credentials[0].env_vars = [expected.credentialEnv]; + profile.endpoints = [ + { + host: endpoint.hostname.replace(/^\[|\]$/gu, ""), + port: Number(endpoint.port || (endpoint.protocol === "https:" ? 443 : 80)), + ...(expected.allowedIps ? { allowed_ips: expected.allowedIps } : {}), + protocol: "rest", + ...(endpoint.protocol === "https:" ? { tls: "terminate" } : {}), + enforcement: "enforce", + rules: [ + { allow: { method: "GET", path: `${apiPrefix}/models` } }, + { allow: { method: "POST", path: `${apiPrefix}/${requestPath}` } }, + ...(anthropic + ? [{ allow: { method: "POST", path: `${apiPrefix}/messages/count_tokens` } }] + : []), + ], + }, + ]; + return YAML.stringify(profile); +} + +export async function withCustomNativeProfile( + definition: NativeProviderDefinition, + use: (profilePath: string) => Promise | T, + templatePath: string, +): Promise { + const source = boundCustomNativeProfile(definition, templatePath); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-profile-")); + try { + const profilePath = path.join(directory, `${definition.profileId}.yaml`); + fs.writeFileSync(profilePath, source, { mode: 0o600 }); + return await use(profilePath); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} diff --git a/src/lib/inference/native-provider/fixed.ts b/src/lib/inference/native-provider/fixed.ts index 24b512e0468..9c67e7b2bbd 100644 --- a/src/lib/inference/native-provider/fixed.ts +++ b/src/lib/inference/native-provider/fixed.ts @@ -27,10 +27,14 @@ export function fixedNativeProvider( : hostedNativeProvider(provider); } -/** OpenClaw provider key for an attached fixed native provider. */ +/** OpenClaw provider key for a native provider and its selected API. */ export function nativeOpenClawProviderKey( provider: string | null | undefined, + inferenceApi?: string | null, ): "openai" | "anthropic" | "inference" | undefined { + if (provider === "compatible-endpoint") return "inference"; + if (provider === "compatible-anthropic-endpoint") + return inferenceApi === "anthropic-messages" ? "anthropic" : "inference"; const definition = fixedNativeProvider(provider); if (!definition) return undefined; if (definition.logicalProvider === "openai-api") return "openai"; diff --git a/src/lib/inference/native-provider/hosted-attachment.ts b/src/lib/inference/native-provider/hosted-attachment.ts index b24558de2fd..854130a919f 100644 --- a/src/lib/inference/native-provider/hosted-attachment.ts +++ b/src/lib/inference/native-provider/hosted-attachment.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { requireHermesPublicPins } from "./hermes-pins"; +import { customNativeProvider, isCustomNativeProviderName } from "./custom"; import { normalizeNativeProviderAttachment, type NativeProviderAttachment } from "./contract"; import { HOSTED_NATIVE_PROVIDERS, @@ -14,6 +15,14 @@ export function hostedNativeProviderForAttachment( ): HostedProviderDefinition | undefined { if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; const receipt = value as Record; + if (receipt.custom !== undefined) { + try { + const definition = customNativeProvider(receipt.custom); + return normalizeNativeProviderAttachment(value, definition) ? definition : undefined; + } catch { + return undefined; + } + } for (const fixed of HOSTED_NATIVE_PROVIDERS) { let definition: HostedProviderDefinition; try { @@ -59,7 +68,8 @@ export function requireHostedProviderAttachment( export function isNativeHostedProviderName(name: string | null | undefined): boolean { return ( !!name && - (HOSTED_NATIVE_PROVIDERS.some((definition) => definition.providerName === name) || + (isCustomNativeProviderName(name) || + HOSTED_NATIVE_PROVIDERS.some((definition) => definition.providerName === name) || /^nemoclaw-hermes-[a-f0-9]{20}-v1$/u.test(name)) ); } diff --git a/src/lib/inference/native-provider/hosted.ts b/src/lib/inference/native-provider/hosted.ts index 288a82f3241..f796637f6a1 100644 --- a/src/lib/inference/native-provider/hosted.ts +++ b/src/lib/inference/native-provider/hosted.ts @@ -5,10 +5,33 @@ import { createHash } from "node:crypto"; import { type NativeProviderAttachment, type NativeProviderDefinition } from "./contract.ts"; +export function isCustomHostedProvider(provider: string | null | undefined): boolean { + return provider === "compatible-endpoint" || provider === "compatible-anthropic-endpoint"; +} + +/** Resolve the native binding and agent configuration from the same API selection. */ +export function resolveCustomNativeApi( + provider: string | null | undefined, + preferredApi: string | null | undefined, + nativeProvider: boolean, +): string | null { + if (!nativeProvider || !isCustomHostedProvider(provider)) return preferredApi ?? null; + return ( + preferredApi || + (provider === "compatible-anthropic-endpoint" ? "anthropic-messages" : "openai-completions") + ); +} + +export function customNativeCredentialEnv(provider: string): string { + if (provider === "compatible-endpoint") return "COMPATIBLE_API_KEY"; + if (provider === "compatible-anthropic-endpoint") return "COMPATIBLE_ANTHROPIC_API_KEY"; + throw new Error("Unsupported custom hosted provider"); +} + export type HostedProviderDefinition = NativeProviderDefinition & Readonly<{ endpoint: string; - api: "openai-completions" | "anthropic-messages"; + api: "openai-completions" | "openai-responses" | "anthropic-messages"; }>; /** Existing fixed hosted selections only; custom and local endpoints have separate owners. */ diff --git a/src/lib/inference/native-provider/index.ts b/src/lib/inference/native-provider/index.ts index 7ca75fd2eeb..4956efe9af3 100644 --- a/src/lib/inference/native-provider/index.ts +++ b/src/lib/inference/native-provider/index.ts @@ -3,6 +3,7 @@ import path from "node:path"; import { withHermesNativeProfile } from "./hermes-profile"; +import { withCustomNativeProfile } from "./custom"; import type { OpenShellGatewayTarget, @@ -40,7 +41,7 @@ export class NativeProviderLifecycle { - const imported = this.definition.endpointUrl - ? await withHermesNativeProfile(this.definition, (boundPath) => - adapter.importProviderProfile({ target, profilePath: boundPath }), + const imported = this.definition.custom + ? await withCustomNativeProfile( + this.definition, + (boundPath) => adapter.importProviderProfile({ target, profilePath: boundPath }), + profilePath, ) - : await adapter.importProviderProfile({ target, profilePath }); + : this.definition.endpointUrl + ? await withHermesNativeProfile(this.definition, (boundPath) => + adapter.importProviderProfile({ target, profilePath: boundPath }), + ) + : await adapter.importProviderProfile({ target, profilePath }); if (imported.ok) return; const collision = imported.error.kind === "command" && imported.error.reason === "profile_incompatible"; @@ -123,6 +130,7 @@ export class NativeProviderLifecycle console.log(message), }); if (bedrockSelection.action === "retry-selection") { - console.log(" Returning to provider selection."); - console.log(""); + console.log(" Returning to provider selection.\n"); return "retry-selection"; } if (bedrockSelection.action === "selected") { @@ -2052,6 +2051,7 @@ async function handleRemoteProviderSelection( }, { resolveProviderCredential, + getSandbox: registry.getSandbox, readRecordedInferenceRoute: (name) => readRecordedInferenceRoute(name, args.recoverySessionId), readRecordedProviderEndpoints, @@ -2266,66 +2266,65 @@ function getSetupNimDeps(): SetupNimDeps { } const setupNim = setupNimFlow.createSetupNim(getSetupNimDeps()); // ── Step 4: Inference provider ─────────────────────────────────── -function getSetupInferenceDeps(): SetupInferenceDeps { - return { - checkGatewayRouteCompatibility, - withGatewayRouteMutationLock: gatewayRouteMutationLock.withGatewayRouteMutationLock, - withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, - step, - getGatewayName: () => GATEWAY_NAME, - runOpenshell, - inferenceRouteMutator, - inferenceRouteObserver, - upsertProvider, - verifyInferenceRoute, - verifyOnboardInferenceSmoke, - isNonInteractive, - updateSandbox: registry.reserveSandboxInferenceRoute, - getSandbox: registry.getSandbox, - listSandboxes: registry.listSandboxes, - unloadOllamaModels, - hermesProviderAuth, - getHermesToolGatewayBroker, - ...onboardProviders.setupInferenceProviderDeps(runOpenshell), - normalizeHermesAuthMethod, - resolveHermesNousApiKey, - checkHermesProviderStoreReachable, - hermesAuthMethodLabel, - hermesConstants: { - HERMES_NOUS_API_KEY_CREDENTIAL_ENV, - HERMES_AUTH_METHOD_API_KEY, - HERMES_AUTH_METHOD_OAUTH, - }, - requireValue, - redact, - compactText, - REMOTE_PROVIDER_CONFIG, - hydrateCredentialEnv, - promptValidationRecovery, - classifyApplyFailure, - localInferenceTimeoutSecs: LOCAL_INFERENCE_TIMEOUT_SECS, - bedrockRuntimeOnboard, - openrouterRuntimeOnboard, - validateLocalProvider, - getLocalProviderHealthCheck, - getLocalProviderBaseUrl, - run, - vllmLocalCredentialEnv: VLLM_LOCAL_CREDENTIAL_ENV, - shouldFrontOllamaWithProxy, - ensureOllamaAuthProxy, - isProxyHealthy, - getOllamaProxyToken, - persistAndProbeOllamaProxy, - localInference, - ollamaProxyCredentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, - isRoutedInferenceProvider, - reconcileModelRouter, - routedInference, - log: (message: string) => console.log(message), - error: (message: string) => console.error(message), - exitProcess: (code: number): never => process.exit(code), - }; -} +const getSetupInferenceDeps = (): SetupInferenceDeps => ({ + checkGatewayRouteCompatibility, + withGatewayRouteMutationLock: gatewayRouteMutationLock.withGatewayRouteMutationLock, + withSandboxMutationLock: sandboxMutationLock.withSandboxMutationLock, + step, + getGatewayName: () => GATEWAY_NAME, + runOpenshell, + inferenceRouteMutator, + inferenceRouteObserver, + upsertProvider, + recordMigratedProviderCredential: registration.recordMigratedProviderCredential, + verifyInferenceRoute, + verifyOnboardInferenceSmoke, + isNonInteractive, + updateSandbox: registry.reserveSandboxInferenceRoute, + getSandbox: registry.getSandbox, + listSandboxes: registry.listSandboxes, + unloadOllamaModels, + hermesProviderAuth, + getHermesToolGatewayBroker, + ...onboardProviders.setupInferenceProviderDeps(runOpenshell), + normalizeHermesAuthMethod, + resolveHermesNousApiKey, + checkHermesProviderStoreReachable, + hermesAuthMethodLabel, + hermesConstants: { + HERMES_NOUS_API_KEY_CREDENTIAL_ENV, + HERMES_AUTH_METHOD_API_KEY, + HERMES_AUTH_METHOD_OAUTH, + }, + requireValue, + redact, + compactText, + REMOTE_PROVIDER_CONFIG, + hydrateCredentialEnv, + promptValidationRecovery, + classifyApplyFailure, + localInferenceTimeoutSecs: LOCAL_INFERENCE_TIMEOUT_SECS, + bedrockRuntimeOnboard, + openrouterRuntimeOnboard, + validateLocalProvider, + getLocalProviderHealthCheck, + getLocalProviderBaseUrl, + run, + vllmLocalCredentialEnv: VLLM_LOCAL_CREDENTIAL_ENV, + shouldFrontOllamaWithProxy, + ensureOllamaAuthProxy, + isProxyHealthy, + getOllamaProxyToken, + persistAndProbeOllamaProxy, + localInference, + ollamaProxyCredentialEnv: OLLAMA_PROXY_CREDENTIAL_ENV, + isRoutedInferenceProvider, + reconcileModelRouter, + routedInference, + log: (message: string) => console.log(message), + error: (message: string) => console.error(message), + exitProcess: (code: number): never => process.exit(code), +}); export type SetupInferenceDeps = import("./onboard/setup-inference").SetupInferenceDeps; export type SetupInference = import("./onboard/setup-inference").SetupInference; function createSetupInference(overrides: Partial = {}): SetupInference { @@ -2915,6 +2914,7 @@ async function runOnboard(opts: OnboardOptions = {}): Promise { import("./resources-cmd").ResourceProfile >({ resumeProvider: { + getSandbox: registry.getSandbox, isNonInteractive, isRoutedInferenceProvider, providerExistsInGateway, diff --git a/src/lib/onboard/compatible-endpoint-smoke-native.test.ts b/src/lib/onboard/compatible-endpoint-smoke-native.test.ts new file mode 100644 index 00000000000..65c2637a4b2 --- /dev/null +++ b/src/lib/onboard/compatible-endpoint-smoke-native.test.ts @@ -0,0 +1,140 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it, vi } from "vitest"; +import { NativeProviderLifecycle } from "../inference/native-provider"; +import { customNativeProvider } from "../inference/native-provider/custom"; +import type { NativeProviderAttachment } from "../inference/native-provider/contract"; +import type { SandboxEntry } from "../state/registry"; +import type { OpenShellSandboxBufferedCommandRequest } from "../adapters/openshell/sandbox-command"; +import { + writeFakeCurl, + writeSmokeConfig, +} from "./__test-helpers__/compatible-endpoint-smoke-helpers"; +import { createCompatibleEndpointSmoke } from "./compatible-endpoint-smoke"; + +describe("native compatible endpoint smoke", () => { + it.each(["onboard", "rebuild"] as const)( + "verifies the recorded native route and restored config during %s (#13195)", + async (operation) => { + const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "native-compatible-smoke-")); + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/team/v1", + api: "openai-completions", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const attachment: NativeProviderAttachment = { + schemaVersion: 1, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "native-identity", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }; + const selection: SandboxEntry = { + name: "native-smoke", + gatewayName: "test-gateway", + provider: "compatible-endpoint", + model: "test-model", + endpointUrl: definition.custom!.endpointUrl, + credentialEnv: "TEAM_KEY", + preferredInferenceApi: "openai-completions", + nativeHostedProviderAttachment: attachment, + }; + const verify = vi + .spyOn(NativeProviderLifecycle.prototype, "verifyNativeProviderAttachment") + .mockResolvedValue(attachment); + const exit = vi.spyOn(process, "exit").mockImplementation(() => { + throw new Error("smoke failed"); + }); + try { + const configPath = writeSmokeConfig(tmp, "test-model"); + const config = JSON.parse(fs.readFileSync(configPath, "utf8")); + config.models.providers.inference.baseUrl = definition.endpointUrl; + config.models.providers.inference.api = "openai-completions"; + config.models.providers.inference.apiKey = "openshell:resolve:env:v7_COMPATIBLE_API_KEY"; + fs.writeFileSync(configPath, JSON.stringify(config)); + const { binDir, callFile } = writeFakeCurl( + tmp, + `printf '%s' '{"choices":[{"message":{"content":"OK"}}]}'`, + ); + const executor = { + runBuffered: vi.fn(async (request: OpenShellSandboxBufferedCommandRequest) => { + const script = request.command[2]!.replaceAll( + "/sandbox/.openclaw/openclaw.json", + configPath, + ); + const result = spawnSync("sh", ["-c", script], { + encoding: "utf8", + env: { + PATH: `${binDir}:${process.env.PATH}`, + COMPATIBLE_API_KEY: "openshell:resolve:env:v7_COMPATIBLE_API_KEY", + }, + }); + return { + outcome: { kind: "completed" as const, exitCode: result.status ?? 1 }, + stdout: result.stdout, + stderr: result.stderr, + }; + }), + }; + const run = vi.fn(); + const smoke = createCompatibleEndpointSmoke( + run, + executor, + (value) => value, + () => selection, + ); + const invoke = () => + operation === "rebuild" + ? smoke.verifyRebuilt({ + ...selection, + provider: "compatible-endpoint", + model: "test-model", + sandboxName: selection.name, + environment: {}, + gatewayName: selection.gatewayName!, + }) + : smoke.verify({ + sandboxName: selection.name, + provider: "compatible-endpoint", + model: "test-model", + }); + await invoke(); + expect(verify).toHaveBeenCalledWith( + expect.objectContaining({ + expected: attachment, + sandboxName: selection.name, + target: { kind: "named", gatewayName: "test-gateway" }, + }), + ); + expect(fs.readFileSync(callFile, "utf8")).toBe("1"); + expect(run).not.toHaveBeenCalled(); + expect(executor.runBuffered.mock.calls[0]![0].target).toEqual({ + kind: "named", + gatewayName: "test-gateway", + }); + + config.models.providers.inference.baseUrl = "https://inference.local/v1"; + fs.writeFileSync(configPath, JSON.stringify(config)); + await expect(invoke()).rejects.toThrow(/smoke failed|verification failed/); + expect(fs.readFileSync(callFile, "utf8")).toBe("1"); + + selection.endpointUrl = "https://other.example/v1"; + await expect(invoke()).rejects.toThrow("Recorded custom native selection does not match"); + expect(executor.runBuffered).toHaveBeenCalledTimes(2); + } finally { + verify.mockRestore(); + exit.mockRestore(); + fs.rmSync(tmp, { recursive: true, force: true }); + } + }, + ); +}); diff --git a/src/lib/onboard/compatible-endpoint-smoke.test.ts b/src/lib/onboard/compatible-endpoint-smoke.test.ts index 8153d1f4882..b2ae61413ba 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.test.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.test.ts @@ -14,11 +14,6 @@ import { writeSmokeConfig, } from "./__test-helpers__/compatible-endpoint-smoke-helpers"; -vi.mock("../inference/config", () => ({ - INFERENCE_ROUTE_URL: "https://inference.local/v1", - MANAGED_PROVIDER_ID: "inference", -})); - import { createCompatibleEndpointSmoke, buildCompatibleEndpointSandboxSmokeCommand, diff --git a/src/lib/onboard/compatible-endpoint-smoke.ts b/src/lib/onboard/compatible-endpoint-smoke.ts index f8ddeb10d8c..17564467b9c 100644 --- a/src/lib/onboard/compatible-endpoint-smoke.ts +++ b/src/lib/onboard/compatible-endpoint-smoke.ts @@ -8,6 +8,12 @@ import { } from "../inference/native-local/contract"; import { verifyNativeLocalProviderAttachment } from "../inference/native-local/profile"; import type { StdioOptions } from "node:child_process"; +import type { SandboxEntry } from "../state/registry"; +import { recordedNativeProviderAttachment } from "../inference/native-provider/recorded-selection"; +import { fixedNativeProviderForAttachment } from "../inference/native-provider/fixed"; +import { nativeHostedAgentConfig } from "../inference/native-provider/agent-config"; +import { nativeProviderLifecycle } from "../inference/native-provider"; +import { probeSandboxInferenceInvocation } from "../actions/sandbox/inference-invocation-probe"; import type { OpenShellSandboxBufferedCommandExecutor } from "../adapters/openshell/sandbox-command"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; import { shellQuote } from "../core/shell-quote"; @@ -116,6 +122,7 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { endpointUrl?: string | null; credentialEnv?: string | null; messagingChannels?: string[] | null; + registeredSelection?: SandboxEntry | null; agent?: CompatibleEndpointSmokeAgent; /** Force the provider-neutral inference.local proof for any supported agent. */ forceCanonicalRoute?: boolean; @@ -168,6 +175,73 @@ export async function verifyCompatibleEndpointSandboxSmoke(options: { }; }, }); + const selection = options.registeredSelection; + const native = + selection && !forceCanonicalRoute + ? recordedNativeProviderAttachment({ + ...selection, + provider: options.provider, + endpointUrl: options.endpointUrl ?? selection.endpointUrl, + credentialEnv: options.credentialEnv ?? selection.credentialEnv, + }) + : undefined; + if (native && selection) { + if (selection.model !== options.model) { + throw new Error("Compatible endpoint verification does not match the registered model."); + } + const nativeTarget = selection.gatewayName + ? { kind: "named" as const, gatewayName: selection.gatewayName } + : target; + await nativeProviderLifecycle( + fixedNativeProviderForAttachment(native), + ).verifyNativeProviderAttachment({ + adapter, + target: nativeTarget, + sandboxName: options.sandboxName, + expected: native, + }); + const configCheck = buildCompatibleEndpointConfigSmokeScript(options.model, { + baseUrl: native.endpointUrl!, + credentialEnv: nativeHostedAgentConfig(options.provider, native.endpointUrl!)!.credentialEnv, + api: native.custom?.api, + }); + const result = await probeSandboxInferenceInvocation( + { + sandboxName: options.sandboxName, + provider: options.provider, + model: options.model, + preferredInferenceApi: native.custom?.api ?? selection.preferredInferenceApi ?? null, + nativeProvider: true, + nativeEndpointUrl: native.endpointUrl, + }, + { + execute: async (_name, command, timeout) => { + const completed = await options.sandboxCommandExecutor.runBuffered({ + sandboxName: options.sandboxName, + target: nativeTarget, + command: ["sh", "-c", `set -eu\n{\n${configCheck}\n} >/dev/null\n${command}`], + timeoutMilliseconds: timeout, + }); + return completed.outcome.kind === "completed" + ? { + status: completed.outcome.exitCode, + stdout: completed.stdout, + stderr: completed.stderr, + } + : null; + }, + }, + ); + if (!result.ok) { + console.error(` Compatible endpoint sandbox smoke check failed: ${result.detail}.`); + fail(1); + } + options.beforeSuccess?.(); + console.log( + " ✓ Compatible endpoint responds through its attached native provider inside the sandbox", + ); + return; + } if (local) await verifyNativeLocalProviderAttachment({ adapter, @@ -254,7 +328,7 @@ export function createCompatibleEndpointSmoke( ) => ReturnType, sandboxCommandExecutor: OpenShellSandboxBufferedCommandExecutor, redact: (value: string) => string, - getSandbox: typeof import("../state/registry").getSandbox, + getSandbox: (name: string) => SandboxEntry | null | undefined, ) { type SmokeOptions = Parameters[0]; const nativeSelection = ( @@ -276,6 +350,7 @@ export function createCompatibleEndpointSmoke( ): Promise { return verifyCompatibleEndpointSandboxSmoke({ ...options, + registeredSelection: getSandbox(options.sandboxName), ...nativeSelection(options), runOpenshell: run, sandboxCommandExecutor, @@ -294,6 +369,7 @@ export function createCompatibleEndpointSmoke( const { environment, gatewayName, ...selection } = options; return verifyCompatibleEndpointSandboxSmoke({ ...selection, + registeredSelection: getSandbox(selection.sandboxName), ...nativeSelection(selection), onFailure: (exitCode) => { throw new Error(`Compatible endpoint verification failed (exit ${exitCode}).`); @@ -313,6 +389,63 @@ export function createCompatibleEndpointSmoke( }; } +/** Check the agent configuration before sending a request through the selected route. */ +export function buildCompatibleEndpointConfigSmokeScript( + model: string, + options: { configPath?: string; baseUrl?: string; credentialEnv?: string; api?: string } = {}, +): string { + return `python3 - ${shellQuote(options.configPath ?? "/sandbox/.openclaw/openclaw.json")} ${shellQuote(model)} ${shellQuote(options.baseUrl ?? INFERENCE_ROUTE_URL)} ${shellQuote(options.credentialEnv ?? "")} ${shellQuote(options.api ?? "")} <<'PYCFG' +import json +import sys + +path = sys.argv[1] +model = sys.argv[2] +base_url = sys.argv[3] +credential_env = sys.argv[4] +api_key = "unused" +if credential_env: + import os + import re + api_key = os.environ.get(credential_env, "") + if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_" + re.escape(credential_env), api_key): + print("native inference credential reference is missing or invalid", file=sys.stderr) + sys.exit(1) + +def die(message): + print(message, file=sys.stderr) + sys.exit(1) + +try: + with open(path, "r", encoding="utf-8") as f: + cfg = json.load(f) +except Exception as exc: + die("could not read openclaw.json: %s" % exc) + +providers = cfg.get("models", {}).get("providers", {}) +if not isinstance(providers, dict): + die("openclaw.json models.providers is not an object") +if "deepinfra" in providers: + die("openclaw.json contains a direct deepinfra provider; expected managed inference provider") + +provider = providers.get("${MANAGED_PROVIDER_ID}") +if not isinstance(provider, dict): + die("openclaw.json missing models.providers.${MANAGED_PROVIDER_ID}") +if provider.get("baseUrl") != base_url: + die("models.providers.${MANAGED_PROVIDER_ID}.baseUrl does not match the selected route") +if sys.argv[5] and provider.get("api") != sys.argv[5]: + die("models.providers.${MANAGED_PROVIDER_ID}.api does not match the selected route") +if provider.get("apiKey") != api_key: + die("models.providers.${MANAGED_PROVIDER_ID}.apiKey must match the selected non-secret placeholder") + +primary = cfg.get("agents", {}).get("defaults", {}).get("model", {}).get("primary") +expected_primary = "${MANAGED_PROVIDER_ID}/" + model +if primary != expected_primary: + die("agents.defaults.model.primary is %r; expected %r" % (primary, expected_primary)) + +print("OPENCLAW_CONFIG_OK") +PYCFG`; +} + /** * Builds the shell script that runs inside the sandbox to confirm OpenClaw is * routed through NemoClaw's managed inference provider and can receive assistant @@ -351,44 +484,7 @@ SMOKE_ATTEMPTS=${attempts} SMOKE_REQUEST_TIMEOUT_SECONDS=${COMPATIBLE_ENDPOINT_SMOKE_REQUEST_TIMEOUT_SECONDS} SMOKE_RETRY_DELAY_SECONDS=${retryDelaySeconds} -python3 - "$CONFIG" "$MODEL" <<'PYCFG' -import json -import sys - -path = sys.argv[1] -model = sys.argv[2] - -def die(message): - print(message, file=sys.stderr) - sys.exit(1) - -try: - with open(path, "r", encoding="utf-8") as f: - cfg = json.load(f) -except Exception as exc: - die("could not read openclaw.json: %s" % exc) - -providers = cfg.get("models", {}).get("providers", {}) -if not isinstance(providers, dict): - die("openclaw.json models.providers is not an object") -if "deepinfra" in providers: - die("openclaw.json contains a direct deepinfra provider; expected managed inference provider") - -provider = providers.get("${MANAGED_PROVIDER_ID}") -if not isinstance(provider, dict): - die("openclaw.json missing models.providers.${MANAGED_PROVIDER_ID}") -if provider.get("baseUrl") != "${INFERENCE_ROUTE_URL}": - die("models.providers.${MANAGED_PROVIDER_ID}.baseUrl is %r; expected ${INFERENCE_ROUTE_URL}" % provider.get("baseUrl")) -if provider.get("apiKey") != "unused": - die("models.providers.${MANAGED_PROVIDER_ID}.apiKey must remain the non-secret placeholder 'unused'") - -primary = cfg.get("agents", {}).get("defaults", {}).get("model", {}).get("primary") -expected_primary = "${MANAGED_PROVIDER_ID}/" + model -if primary != expected_primary: - die("agents.defaults.model.primary is %r; expected %r" % (primary, expected_primary)) - -print("OPENCLAW_CONFIG_OK") -PYCFG +${buildCompatibleEndpointConfigSmokeScript(model, { configPath })} payload_file="$(mktemp)" response_file="$(mktemp)" diff --git a/src/lib/onboard/credential-provider-registration.ts b/src/lib/onboard/credential-provider-registration.ts index 2998823e699..4281e0feb96 100644 --- a/src/lib/onboard/credential-provider-registration.ts +++ b/src/lib/onboard/credential-provider-registration.ts @@ -239,6 +239,22 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg const refreshReceipts = new Map(); const gatewayRunner = (gatewayName = deps.getGatewayName()) => createGatewayScopedOpenshellRunner(deps.runOpenshell, gatewayName); + function recordMigratedProviderCredential( + name: string, + credentialEnv: string, + persistedValue: string | null, + revalidateSandboxIdentity?: (operation: string) => void, + ): void { + // Retire only the staged value actually written, including declared aliases. + const migrationKeys = stagedMigrationKeys(credentialEnv, deps.stagedLegacyValues); + if (migrationKeys.length === 0) return; + revalidateSandboxIdentity?.(`record migrated credential for provider ${JSON.stringify(name)}`); + for (const key of migrationKeys) { + if (persistedValue === deps.stagedLegacyValues.get(key)) deps.migratedLegacyKeys.add(key); + else deps.migratedLegacyKeys.delete(key); + } + } + async function upsertProvider( name: string, type: string, @@ -257,26 +273,17 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg gatewayRunner(gatewayName), options, ); - if (result.ok && credentialEnv) { - // The legacy file can carry the value under an alias of the canonical - // credential env (NVIDIA_API_KEY for NVIDIA_INFERENCE_API_KEY), which - // resolveProviderCredential resolves transparently. Account the alias - // too, or the staged key never looks migrated and the plaintext file - // survives an onboard that used it (#10373). - const migrationKeys = stagedMigrationKeys(credentialEnv, deps.stagedLegacyValues); - if (migrationKeys.length > 0) { - options.revalidateSandboxIdentity?.( - `record migrated credential for provider ${JSON.stringify(name)}`, - ); - const upsertedValue = env[credentialEnv] ?? deps.getCredential(credentialEnv); - for (const key of migrationKeys) { - if (upsertedValue === deps.stagedLegacyValues.get(key)) { - deps.migratedLegacyKeys.add(key); - } else { - deps.migratedLegacyKeys.delete(key); - } - } - } + if ( + result.ok && + credentialEnv && + stagedMigrationKeys(credentialEnv, deps.stagedLegacyValues).length > 0 + ) { + recordMigratedProviderCredential( + name, + credentialEnv, + env[credentialEnv] ?? deps.getCredential(credentialEnv), + options.revalidateSandboxIdentity, + ); } return result; } @@ -487,6 +494,7 @@ export function createCredentialProviderRegistration(deps: CredentialProviderReg } return { + recordMigratedProviderCredential, inspectGatewayCredential, providerMatchesGatewayCredential, applyMessagingProviders, diff --git a/src/lib/onboard/machine/handlers/provider-inference.test.ts b/src/lib/onboard/machine/handlers/provider-inference.test.ts index d40d241b882..38ded54f286 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.test.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.test.ts @@ -308,6 +308,8 @@ describe("handleProviderInferenceState", () => { "nemoclaw", "compatible-endpoint", "COMPATIBLE_API_KEY", + undefined, + { sandboxName: "mcp-rebuild", endpointUrl: "https://compatible.example.test/v1" }, ); expect(calls.complete).toHaveBeenCalledWith( "provider_selection", @@ -450,7 +452,13 @@ describe("handleProviderInferenceState", () => { expect(calls.setupNim).not.toHaveBeenCalled(); expect(calls.setupInference).not.toHaveBeenCalled(); - expect(calls.recoverProvider).toHaveBeenCalledWith("nemoclaw", "ollama-local", null); + expect(calls.recoverProvider).toHaveBeenCalledWith( + "nemoclaw", + "ollama-local", + null, + undefined, + { sandboxName: null, endpointUrl: null }, + ); expect(calls.skipped).toHaveBeenCalledWith("provider_selection", "ollama-local / llama3.1"); expect(calls.recordSkip).toHaveBeenCalledWith("provider_selection", { reason: "resume", @@ -878,41 +886,46 @@ describe("handleProviderInferenceState", () => { expect(calls.repairEvent).not.toHaveBeenCalledWith("state.repair.completed", expect.anything()); }); - it("reruns inference setup when resumed provider recovery forces recreation", async () => { - const session = createSession({ - provider: "compatible-endpoint", - model: "custom-model", - credentialEnv: null, - }); - session.steps.provider_selection.status = "complete"; - const { deps, calls } = createDeps({ - isInferenceRouteReady: vi.fn(() => true), - ensureResumeProviderReady: vi.fn(async () => ({ - forceInferenceSetup: true, - credentialEnv: "COMPATIBLE_API_KEY", - })), - }); - calls.complete.mockResolvedValue(session); + it.each([false, true])( + "reruns resumed provider setup with native custom recovery %s", + async (nativeCustomSetup) => { + const session = createSession({ + provider: "compatible-endpoint", + model: "custom-model", + credentialEnv: null, + }); + session.steps.provider_selection.status = "complete"; + const { deps, calls } = createDeps({ + isInferenceRouteReady: vi.fn(() => true), + ensureResumeProviderReady: vi.fn(async () => ({ + forceInferenceSetup: true, + credentialEnv: "COMPATIBLE_API_KEY", + nativeCustomSetup, + })), + }); + calls.complete.mockResolvedValue(session); - await handleProviderInferenceState({ - ...baseOptions(deps, session), - resume: true, - sandboxName: "my-assistant", - }); + await handleProviderInferenceState({ + ...baseOptions(deps, session), + resume: true, + sandboxName: "my-assistant", + ...(nativeCustomSetup ? { selectedMessagingChannels: ["telegram"] } : {}), + }); - expect(calls.setupNim).not.toHaveBeenCalled(); - expect(calls.hydrate).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); - expect(calls.setupInference).toHaveBeenCalledWith( - "my-assistant", - "custom-model", - "compatible-endpoint", - null, - "COMPATIBLE_API_KEY", - null, - [], - setupOptions(session), - ); - }); + expect(calls.setupNim).not.toHaveBeenCalled(); + expect(calls.hydrate).toHaveBeenCalledWith("COMPATIBLE_API_KEY"); + expect(calls.setupInference).toHaveBeenCalledWith( + "my-assistant", + "custom-model", + "compatible-endpoint", + null, + "COMPATIBLE_API_KEY", + null, + [], + setupOptions(session), + ); + }, + ); it("forces canonical setup for a preflighted provider even if a matching route appears (#6114)", async () => { const session = createSession({ diff --git a/src/lib/onboard/machine/handlers/provider-inference.ts b/src/lib/onboard/machine/handlers/provider-inference.ts index eb7586c8324..149d7c9c5f6 100644 --- a/src/lib/onboard/machine/handlers/provider-inference.ts +++ b/src/lib/onboard/machine/handlers/provider-inference.ts @@ -278,7 +278,12 @@ export interface ProviderInferenceStateOptions { provider: string | null | undefined, credentialEnv: string | null | undefined, revalidateSandboxIdentity?: (operation: string) => void, - ): Promise<{ forceInferenceSetup: boolean; credentialEnv: string | null }>; + selection?: { sandboxName: string | null; endpointUrl: string | null }, + ): Promise<{ + forceInferenceSetup: boolean; + credentialEnv: string | null; + nativeCustomSetup?: boolean; + }>; ensureManagedLlamaCppResumeReady( provider: string | null | undefined, sandboxName: string | null | undefined, @@ -970,8 +975,10 @@ function shouldRefreshCompatibleEndpointRouteForMessaging( selectedMessagingChannels: string[], session: Session | null, agent: unknown, + nativeCustomSetup: boolean | undefined, ): boolean { return ( + !nativeCustomSetup && provider === "compatible-endpoint" && agentName(agent) === "openclaw" && hasActiveMessagingChannels(selectedMessagingChannels, session) @@ -1566,7 +1573,13 @@ export async function handleProviderInferenceState({ sandboxName, deps.ensureManagedLlamaCppResumeReady, ); - const recovery = await deps.ensureResumeProviderReady(gatewayName, provider, credentialEnv); + const recovery = await deps.ensureResumeProviderReady( + gatewayName, + provider, + credentialEnv, + undefined, + { sandboxName: reusableResumeSandboxName, endpointUrl }, + ); forceInferenceSetup ||= recovery.forceInferenceSetup; credentialEnv = recovery.credentialEnv; // Rebuild may be resuming a legacy session whose step marker was never @@ -1624,6 +1637,7 @@ export async function handleProviderInferenceState({ selectedMessagingChannels, session, agent, + recovery.nativeCustomSetup, ) ) { if (!hydratedCredential) { diff --git a/src/lib/onboard/machine/resume-provider-shim.test.ts b/src/lib/onboard/machine/resume-provider-shim.test.ts index 3c33eb3f0c5..36f592d568d 100644 --- a/src/lib/onboard/machine/resume-provider-shim.test.ts +++ b/src/lib/onboard/machine/resume-provider-shim.test.ts @@ -7,6 +7,7 @@ vi.mock("../../credentials/store", () => ({ resolveProviderCredential: vi.fn(() => null), })); +import { customNativeProvider } from "../../inference/native-provider/custom"; import { createResumeProviderShim } from "./resume-provider-shim"; describe("createResumeProviderShim", () => { @@ -92,3 +93,165 @@ describe("createResumeProviderShim", () => { ).rejects.toBe(ownershipConflict); }); }); + +it.each([ + ["native", "TEAM_KEY"], + ["native", null], + ["reservation", "TEAM_KEY"], + ["reservation", null], + ["legacy", "TEAM_KEY"], +] as const)( + "routes %s custom resume through its owning credential recovery", + async (state, credentialEnv) => { + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const recorded = + state === "native" + ? { + nativeHostedProviderAttachment: { + schemaVersion: 1 as const, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "owned-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }, + } + : { pendingRouteReservation: state === "reservation" }; + const providerExistsInGateway = vi.fn(() => true); + const replaceNamedCredential = vi.fn(async () => "unexpected"); + const shim = createResumeProviderShim({ + getSandbox: (name) => { + expect(name).toBe("alpha"); + return recorded; + }, + isNonInteractive: () => true, + providerExistsInGateway, + isRoutedInferenceProvider: () => false, + replaceNamedCredential, + }); + const result = await shim.ensureResumeProviderReady( + "gateway-west", + "compatible-endpoint", + credentialEnv, + undefined, + { sandboxName: "alpha", endpointUrl: "https://custom.example/v1" }, + ); + expect(result).toEqual( + state === "legacy" + ? { forceInferenceSetup: false, credentialEnv: "TEAM_KEY" } + : { + forceInferenceSetup: true, + credentialEnv: + credentialEnv ?? (state === "native" ? "TEAM_KEY" : "COMPATIBLE_API_KEY"), + nativeCustomSetup: true, + }, + ); + expect(providerExistsInGateway.mock.calls).toEqual( + state === "legacy" ? [["compatible-endpoint", "gateway-west"]] : [], + ); + expect(replaceNamedCredential).not.toHaveBeenCalled(); + }, +); + +function nativeResumeHarness(provider: "compatible-endpoint" | "compatible-anthropic-endpoint") { + const definition = customNativeProvider({ + provider, + endpointUrl: + provider === "compatible-endpoint" ? "https://custom.example/v1" : "https://custom.example", + api: provider === "compatible-endpoint" ? "openai-completions" : "anthropic-messages", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const attachment = { + schemaVersion: 1 as const, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "owned-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }; + const providerExistsInGateway = vi.fn(() => true); + const replaceNamedCredential = vi.fn(async () => "unexpected"); + const shim = createResumeProviderShim({ + getSandbox: () => ({ nativeHostedProviderAttachment: attachment }), + isNonInteractive: () => true, + providerExistsInGateway, + isRoutedInferenceProvider: () => false, + replaceNamedCredential, + }); + return { attachment, shim, providerExistsInGateway, replaceNamedCredential }; +} + +it.each(["compatible-endpoint", "compatible-anthropic-endpoint"] as const)( + "recovers the validated %s credential binding for an equivalent endpoint (#13195)", + async (provider) => { + const h = nativeResumeHarness(provider); + const result = await h.shim.ensureResumeProviderReady( + "gateway-west", + provider, + undefined, + undefined, + { sandboxName: "alpha", endpointUrl: h.attachment.custom.endpointUrl + "/" }, + ); + expect(result).toEqual({ + forceInferenceSetup: true, + credentialEnv: "TEAM_KEY", + nativeCustomSetup: true, + }); + expect(h.providerExistsInGateway).not.toHaveBeenCalled(); + expect(h.replaceNamedCredential).not.toHaveBeenCalled(); + }, +); + +it("preserves an explicitly selected credential instead of the recorded binding (#13195)", async () => { + const h = nativeResumeHarness("compatible-endpoint"); + const result = await h.shim.ensureResumeProviderReady( + "gateway-west", + "compatible-endpoint", + "NEW_TEAM_KEY", + undefined, + { sandboxName: "alpha", endpointUrl: h.attachment.custom.endpointUrl }, + ); + expect(result.credentialEnv).toBe("NEW_TEAM_KEY"); + expect(h.replaceNamedCredential).not.toHaveBeenCalled(); +}); + +it.each([ + ["compatible-endpoint", "https://different.example/v1", "COMPATIBLE_API_KEY"], + ["compatible-anthropic-endpoint", "https://custom.example/v1", "COMPATIBLE_ANTHROPIC_API_KEY"], +])( + "does not inherit a credential binding for changed %s at %s (#13195)", + async (provider, endpointUrl, expected) => { + const h = nativeResumeHarness("compatible-endpoint"); + const result = await h.shim.ensureResumeProviderReady( + "gateway-west", + provider, + null, + undefined, + { sandboxName: "alpha", endpointUrl }, + ); + expect(result.credentialEnv).toBe(expected); + expect(h.replaceNamedCredential).not.toHaveBeenCalled(); + }, +); + +it("rejects an altered native attachment before recovering its credential binding (#13195)", async () => { + const h = nativeResumeHarness("compatible-endpoint"); + h.attachment.profileId = "altered-profile"; + await expect( + h.shim.ensureResumeProviderReady("gateway-west", "compatible-endpoint", null, undefined, { + sandboxName: "alpha", + endpointUrl: h.attachment.custom.endpointUrl, + }), + ).rejects.toThrow("Invalid native hosted provider attachment"); + expect(h.providerExistsInGateway).not.toHaveBeenCalled(); + expect(h.replaceNamedCredential).not.toHaveBeenCalled(); +}); diff --git a/src/lib/onboard/machine/resume-provider-shim.ts b/src/lib/onboard/machine/resume-provider-shim.ts index 5380eecc80e..77b3c46ab3f 100644 --- a/src/lib/onboard/machine/resume-provider-shim.ts +++ b/src/lib/onboard/machine/resume-provider-shim.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 import { runOpenshell } from "../../adapters/openshell/runtime"; +import { + recordedCustomCredentialEnv, + usesCustomNativeOnboarding, +} from "../../inference/native-provider/custom-setup"; import { D, R } from "../../cli/terminal-style"; import { isBedrockRuntimeEndpoint } from "../../inference/bedrock-runtime"; import { DEFAULT_ROUTE_CREDENTIAL_ENV } from "../../inference/config"; @@ -19,9 +23,11 @@ import { const onboardProviders = require("../providers") as { REMOTE_PROVIDER_CONFIG: ResumeProviderRecoveryDeps["remoteProviderConfig"]; getProviderLabel: ResumeProviderRecoveryDeps["getProviderLabel"]; + getRemoteProviderConfigForName(name: string): { credentialEnv: string } | null; }; export type ResumeProviderShimDeps = { + getSandbox?: (name: string) => Parameters[3]; isNonInteractive: ResumeProviderRecoveryDeps["isNonInteractive"]; providerExistsInGateway(name: string, gatewayName: string): boolean | Promise; isRoutedInferenceProvider: ResumeProviderRecoveryDeps["isRoutedInferenceProvider"]; @@ -50,7 +56,32 @@ export function createResumeProviderShim(deps: ResumeProviderShimDeps) { provider: string | null | undefined, credentialEnv: string | null | undefined, revalidateSandboxIdentity?: (operation: string) => void, + selection?: { sandboxName: string | null; endpointUrl: string | null }, ): Promise { + const recorded = + provider && selection?.sandboxName ? deps.getSandbox?.(selection.sandboxName) : undefined; + if ( + provider && + selection?.sandboxName && + deps.getSandbox && + usesCustomNativeOnboarding(provider, selection.endpointUrl, selection.sandboxName, recorded) + ) { + // Setup verifies the endpoint-bound receipt and live resource identity. + // Looking up the logical name here would demand a key before that check. + return { + forceInferenceSetup: true, + credentialEnv: + credentialEnv || + recordedCustomCredentialEnv( + provider, + selection.endpointUrl, + recorded?.nativeHostedProviderAttachment, + ) || + onboardProviders.getRemoteProviderConfigForName(provider)?.credentialEnv || + null, + nativeCustomSetup: true, + }; + } return ensureResumeProviderReadyImpl(provider, credentialEnv, { remoteProviderConfig: onboardProviders.REMOTE_PROVIDER_CONFIG, defaultRouteCredentialEnv: DEFAULT_ROUTE_CREDENTIAL_ENV, diff --git a/src/lib/onboard/managed-workload/onboard-orchestration.ts b/src/lib/onboard/managed-workload/onboard-orchestration.ts index b11f5bf7a2d..11eaf241d0e 100644 --- a/src/lib/onboard/managed-workload/onboard-orchestration.ts +++ b/src/lib/onboard/managed-workload/onboard-orchestration.ts @@ -423,7 +423,9 @@ export function createManagedWorkloadOnboardRuntime( selectedModel, selectedProvider, inferenceApi, - input.nativeProvider ?? true, + input.nativeLocalProviderAttachment && !nativeLocalProviderAttachment + ? false + : (input.nativeProvider ?? true), endpointUrl, input.agentName, ); diff --git a/src/lib/onboard/openclaw-setup.test.ts b/src/lib/onboard/openclaw-setup.test.ts index f2023c05ea4..3210e1c23f1 100644 --- a/src/lib/onboard/openclaw-setup.test.ts +++ b/src/lib/onboard/openclaw-setup.test.ts @@ -415,6 +415,7 @@ describe("restored native OpenClaw inference fields", () => { const writeValues = vi.fn(); const identity = vi.fn(); const write = createOpenclawInferenceRouteWriter({ + readInferenceSelection: () => ({ nativeProvider: false }), readOpenclawConfig: () => config, patchOpenclawInferenceConfig: patchOpenClawInferenceConfig, writeOpenclawInferenceConfigNatively: (name, patched, route, gateway) => diff --git a/src/lib/onboard/recovered-provider-reuse.test.ts b/src/lib/onboard/recovered-provider-reuse.test.ts index 0cfc9961d00..bf593392184 100644 --- a/src/lib/onboard/recovered-provider-reuse.test.ts +++ b/src/lib/onboard/recovered-provider-reuse.test.ts @@ -54,6 +54,30 @@ describe("assessRecoveredProviderCredentialReuse", () => { }); }); + it("defers native credential verification without trusting legacy provider metadata", () => { + expect( + assessRecoveredProviderCredentialReuse({ + ...completeRecovery, + nativeCustom: true, + gatewayProvider: null, + endpointIdentity: { + ...completeRecovery.endpointIdentity, + otherRecorded: ["https://other.example/v1"], + }, + }), + ).toEqual({ kind: "verify-native-credential", preferredInferenceApi: "openai-completions" }); + expect( + assessRecoveredProviderCredentialReuse({ + ...completeRecovery, + nativeCustom: true, + endpointIdentity: { + ...completeRecovery.endpointIdentity, + recovered: "https://other.example/v1", + }, + }), + ).toMatchObject({ kind: "reject", condition: "endpoint-identity" }); + }); + it.each( Array.from([[], ["WRONG_BASE_URL"], ["OPENAI_BASE_URL", "EXTRA_FLAG"]], (value) => [value]), )( diff --git a/src/lib/onboard/recovered-provider-reuse.ts b/src/lib/onboard/recovered-provider-reuse.ts index 9a6d91bd453..ee1f9bb0482 100644 --- a/src/lib/onboard/recovered-provider-reuse.ts +++ b/src/lib/onboard/recovered-provider-reuse.ts @@ -3,6 +3,7 @@ import { canonicalEndpoint, type EndpointFlavor } from "../core/url-utils"; import { isBedrockRuntimeEndpoint } from "../inference/bedrock-runtime"; +import { usesCustomNativeOnboarding } from "../inference/native-provider/custom-setup"; import { isSafeModelId } from "../validation"; import type { GatewayProviderMetadata } from "./gateway-provider-metadata"; import type { RecordedInferenceRoute } from "./provider-recovery"; @@ -37,6 +38,7 @@ export type RecoveredProviderReuseRejectCondition = export type RecoveredProviderReuseDecision = | { kind: "validate-host-credential" } | { kind: "reuse-gateway-credential"; preferredInferenceApi: string } + | { kind: "verify-native-credential"; preferredInferenceApi: string } | { kind: "reject"; condition: RecoveredProviderReuseRejectCondition; reason: string }; type EndpointIdentity = { @@ -67,6 +69,7 @@ type RecoveredProviderSelection = { }; type RecoveredProviderSelectionDeps = { + getSandbox?: (name: string) => Parameters[3]; resolveProviderCredential(name: string): string | null; readRecordedInferenceRoute(sandboxName: string | null): RecordedInferenceRoute | null; readRecordedProviderEndpoints( @@ -112,6 +115,7 @@ export function assessRecoveredProviderCredentialReuse(options: { expectedCredentialEnv: string; gatewayProvider: GatewayProviderMetadata | null; endpointIdentity?: EndpointIdentity; + nativeCustom?: boolean; }): RecoveredProviderReuseDecision { if (options.hostCredentialAvailable) return { kind: "validate-host-credential" }; if (!options.recoveredFromSandbox) { @@ -148,6 +152,26 @@ export function assessRecoveredProviderCredentialReuse(options: { reason: "the recovered inference API is missing or unsupported", }; } + if (options.nativeCustom) { + const endpoint = options.endpointIdentity; + const selected = endpoint && canonicalEndpoint(endpoint.selected, endpoint.flavor); + if ( + !selected || + endpoint?.routeSource !== "registry" || + selected !== canonicalEndpoint(endpoint.recovered, endpoint.flavor) + ) + return { + kind: "reject", + condition: "endpoint-identity", + reason: "the recovered endpoint identity is missing or incompatible", + }; + // Selection can defer host validation, but only provider setup can verify + // the endpoint-bound receipt and current OpenShell resource identity. + return { + kind: "verify-native-credential", + preferredInferenceApi: options.recoveredPreferredInferenceApi as string, + }; + } const gatewayProvider = options.gatewayProvider; // #6294: an OpenAI-only agent coerced onto openai-completions registers the // compatible-anthropic-endpoint provider as type=openai (OPENAI_BASE_URL), @@ -259,6 +283,15 @@ export function resolveRecoveredProviderCredentialReuse( : selected.key === "anthropicCompatible" ? "anthropic" : null; + const nativeCustom = Boolean( + deps.getSandbox && + usesCustomNativeOnboarding( + state.provider, + state.endpointUrl, + options.sandboxName, + options.sandboxName ? deps.getSandbox(options.sandboxName) : null, + ), + ); const decision = assessRecoveredProviderCredentialReuse({ hostCredentialAvailable: false, recoveredFromSandbox, @@ -270,14 +303,17 @@ export function resolveRecoveredProviderCredentialReuse( recoveredPreferredInferenceApi: recoveredRoute?.preferredInferenceApi, expectedProviderType: remoteConfig.providerType, expectedCredentialEnv: selectedCredentialEnv, - gatewayProvider: deps.readGatewayProviderMetadata(state.provider), + gatewayProvider: nativeCustom ? null : deps.readGatewayProviderMetadata(state.provider), + nativeCustom, endpointIdentity: customFlavor ? { flavor: customFlavor, routeSource: recoveredRoute?.source ?? null, selected: state.endpointUrl, recovered: recoveredRoute?.endpointUrl, - otherRecorded: deps.readRecordedProviderEndpoints(state.provider, options.sandboxName), + otherRecorded: nativeCustom + ? [] + : deps.readRecordedProviderEndpoints(state.provider, options.sandboxName), } : undefined, }); @@ -294,7 +330,9 @@ export function resolveRecoveredProviderCredentialReuse( state.reuseGatewayCredentialWithoutLocalKey = true; state.preferredInferenceApi = decision.preferredInferenceApi; deps.note( - ` Reusing existing gateway credential for '${state.provider}'; skipping direct endpoint validation.`, + decision.kind === "verify-native-credential" + ? " Checking for a matching endpoint-bound credential during provider setup; a new credential may be required." + : ` Reusing existing gateway credential for '${state.provider}'; skipping direct endpoint validation.`, ); return true; } diff --git a/src/lib/onboard/resume-provider-recovery.ts b/src/lib/onboard/resume-provider-recovery.ts index 841610a0e75..f20e066f86a 100644 --- a/src/lib/onboard/resume-provider-recovery.ts +++ b/src/lib/onboard/resume-provider-recovery.ts @@ -48,6 +48,8 @@ export type ResumeProviderRecoveryDeps = { }; export type ResumeProviderRecoveryResult = { + /** Route recovery through native setup; this is not evidence of credential ownership. */ + nativeCustomSetup?: boolean; forceInferenceSetup: boolean; credentialEnv: string | null; }; diff --git a/src/lib/onboard/setup-inference-route-containment.test.ts b/src/lib/onboard/setup-inference-route-containment.test.ts index 7b70e78e97e..5f67f7f2728 100644 --- a/src/lib/onboard/setup-inference-route-containment.test.ts +++ b/src/lib/onboard/setup-inference-route-containment.test.ts @@ -358,6 +358,9 @@ describe("onboard shared gateway route containment", () => { }); const verifyOnboardInferenceSmoke = vi.fn(); const setupInference = createSetupInference({ + getSandbox: () => ({ name: "sandbox-a", provider: "compatible-endpoint" }), + localInference: { loadPendingOllamaModelCleanup: () => [] }, + withOllamaModelOwnershipLock: (operation: () => unknown) => operation(), checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true as const })), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), @@ -586,6 +589,7 @@ describe("onboard shared gateway route containment", () => { checkGatewayRouteCompatibility: ( request: Parameters[0], ) => checkGatewayRouteCompatibility({ ...request, sandboxes: [peer] }), + getSandbox: () => ({ name: "new-custom", provider: "compatible-endpoint" }), withSandboxMutationLock: async (_name: string, operation: () => Promise | T) => await operation(), withGatewayRouteMutationLock: async (_name: string, operation: () => Promise | T) => @@ -1142,7 +1146,7 @@ describe("onboard shared gateway route containment", () => { providerName: "compatible-endpoint", providerType: "openai", credentialEnv: "COMPATIBLE_API_KEY", - endpointUrl: "https://public-name.example/v1", + endpointUrl: "http://host.openshell.internal:1234/v1", helpUrl: null, modelMode: "input", defaultModel: "new-model", @@ -1175,7 +1179,7 @@ describe("onboard shared gateway route containment", () => { "alpha", "new-model", selectedProvider, - selectedProvider === "vllm-local" ? null : "https://public-name.example/v1", + selectedProvider === "vllm-local" ? null : "http://host.openshell.internal:1234/v1", selectedProvider === "vllm-local" ? null : "COMPATIBLE_API_KEY", null, [], diff --git a/src/lib/onboard/setup-inference.ts b/src/lib/onboard/setup-inference.ts index db197944955..691aa61d987 100644 --- a/src/lib/onboard/setup-inference.ts +++ b/src/lib/onboard/setup-inference.ts @@ -17,9 +17,15 @@ import { import { hostedNativeProvider, usesNativeHermesEndpoint, + customNativeCredentialEnv, + resolveCustomNativeApi, } from "../inference/native-provider/hosted"; import { requireHostedProviderAttachment } from "../inference/native-provider/hosted-attachment"; -import { prepareHostedNativeProvider } from "../inference/native-provider/setup"; +import { + prepareHostedNativeProvider, + prepareCustomNativeProvider, + usesCustomNativeOnboarding, +} from "../inference/native-provider/setup"; import type { NativeProviderAttachment } from "../inference/native-provider/contract"; import type { OpenShellGatewayLifecycle } from "../adapters/openshell/gateway-lifecycle"; import { canonicalEndpoint } from "../core/url-utils"; @@ -227,6 +233,12 @@ type ProviderBranchDeps = Pick< Pick; export type SetupInferenceDeps = ProviderBranchDeps & { + recordMigratedProviderCredential?: ( + name: string, + credentialEnv: string, + persistedValue: string, + revalidateSandboxIdentity?: (operation: string) => void, + ) => void; requireNativeProviderPolicy?: typeof requireNativeProviderPolicy; /** Injectable resolver for resumed custom-endpoint SSRF preflight tests. */ resolveEndpointHost?: EndpointDnsLookupFn; @@ -746,8 +758,8 @@ function resolveHostedSelection(input: { deps: SetupInferenceDeps; }) { const { provider, endpointUrl, sandboxName, gatewayName, deps } = input; - const recordedSandbox = - provider === "hermes-provider" && sandboxName ? deps.getSandbox?.(sandboxName) : null; + const recordedSandbox = sandboxName ? deps.getSandbox?.(sandboxName) : null; + const custom = usesCustomNativeOnboarding(provider, endpointUrl, sandboxName, recordedSandbox); const authority = provider === "hermes-provider" ? ((recordedSandbox?.provider === provider @@ -760,9 +772,12 @@ function resolveHostedSelection(input: { : undefined; return { authority, + recordedSandbox, + custom, selected: - Boolean(hostedNativeProvider(provider)) && - (provider !== "hermes-provider" || usesNativeHermesEndpoint(endpointUrl, authority)), + custom || + (Boolean(hostedNativeProvider(provider)) && + (provider !== "hermes-provider" || usesNativeHermesEndpoint(endpointUrl, authority))), }; } @@ -1090,14 +1105,17 @@ export function createSetupInference( ); return deps.exitProcess(1); } - const { authority: hermesAuthority, selected: nativeHostedSelection } = - resolveHostedSelection({ - provider, - endpointUrl, - sandboxName, - gatewayName, - deps, - }); + const { + authority: hermesAuthority, + selected: nativeHostedSelection, + custom: nativeCustomSelection, + recordedSandbox, + } = resolveHostedSelection({ provider, endpointUrl, sandboxName, gatewayName, deps }); + const selectedInferenceApi = resolveCustomNativeApi( + provider, + options.preferredInferenceApi, + nativeCustomSelection, + ); if ( !(await gatewayRouteCompatible({ provider, @@ -1106,7 +1124,7 @@ export function createSetupInference( credentialEnv, gatewayName, sandboxName, - preferredInferenceApi: options.preferredInferenceApi, + preferredInferenceApi: selectedInferenceApi, nativeHostedSelection, selectingNativeLocal, deps, @@ -1227,7 +1245,7 @@ export function createSetupInference( endpointUrl: nativeHostedEndpoint ?? hostLocalRoute?.applicationBaseUrl ?? endpointUrl, endpointSource: hostLocalRoute ? "inference-set" : endpointSource, credentialEnv: nativeHostedCredentialEnv ?? credentialEnv, - preferredInferenceApi: options.preferredInferenceApi ?? null, + preferredInferenceApi: selectedInferenceApi, gatewayName, reservationSessionId: options.reservationSessionId, hostLocalInferenceReceipt, @@ -1438,6 +1456,47 @@ export function createSetupInference( } const setupSelectedProvider = async (): Promise => { + if (nativeCustomSelection) { + if ( + !deps.providerAdapter || + !deps.getNativeHostedProviderAuthority || + !deps.setNativeHostedProviderAuthority + ) + throw new Error( + "Native custom setup is missing its provider adapter or ownership store.", + ); + const selectedCredentialEnv = credentialEnv || customNativeCredentialEnv(provider); + const credentialValue = deps.hydrateCredentialEnv(selectedCredentialEnv) || null; + nativeHostedProviderAttachment = await prepareCustomNativeProvider({ + gatewayName, + provider, + endpointUrl: endpointUrl!, + api: selectedInferenceApi!, + credentialEnv: selectedCredentialEnv, + credentialValue, + adapter: deps.providerAdapter, + recordedAttachment: + recordedSandbox?.provider === provider + ? recordedSandbox.nativeHostedProviderAttachment + : undefined, + lookup: endpointPinnedAddresses + ? async () => endpointPinnedAddresses!.map((address) => ({ address })) + : deps.resolveEndpointHost, + trustedPrivateHosts: deps.trustedPrivateEndpointHosts, + readAuthority: deps.getNativeHostedProviderAuthority, + writeAuthority: deps.setNativeHostedProviderAuthority, + onCredentialPersisted: (env, value) => { + deps.recordMigratedProviderCredential?.( + provider, + env, + value, + revalidateSandboxIdentity, + ); + }, + }); + retainedNativeHostedCredential = !credentialValue; + return null; + } const hosted = hostedNativeProvider(provider); if (hosted && provider !== deps.hermesProviderAuth.HERMES_PROVIDER_NAME) { const prepared = await prepareSelectedHostedProvider({ @@ -1571,7 +1630,7 @@ export function createSetupInference( allowLegacyRecordedNoAuthEndpoint: options.allowLegacyRecordedNoAuthEndpoint === true, skipHostInferenceSmoke: options.skipHostInferenceSmoke === true, - preferredInferenceApi: options.preferredInferenceApi ?? null, + preferredInferenceApi: selectedInferenceApi, pinnedAddresses: endpointPinnedAddresses, trustedPrivateCapability: endpointTrustedPrivateCapability, capabilityCache: options.inferenceCapabilityCache, @@ -1762,6 +1821,10 @@ export function createSetupInference( deps.log( " Deferring inference.local smoke to the sandbox runtime after sandbox readiness.", ); + } else if (nativeHostedProviderAttachment?.custom) { + deps.log( + " Custom native inference will be verified from the sandbox using its selected API.", + ); } else if (options.skipHostInferenceSmoke === true || retainedNativeHostedCredential) { deps.log(" Reusing existing gateway credential; skipping host inference smoke."); } else { diff --git a/src/lib/onboard/setup-native-hosted.test.ts b/src/lib/onboard/setup-native-hosted.test.ts index 2fa021dec7e..7c258cee7dc 100644 --- a/src/lib/onboard/setup-native-hosted.test.ts +++ b/src/lib/onboard/setup-native-hosted.test.ts @@ -3,7 +3,11 @@ import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter } from "../adapters/openshell/provider-adapter"; -import { HOSTED_NATIVE_PROVIDERS } from "../inference/native-provider/hosted"; +import { customNativeProvider } from "../inference/native-provider/custom"; +import { + HOSTED_NATIVE_PROVIDERS, + type HostedProviderDefinition, +} from "../inference/native-provider/hosted"; import { createSetupInference, type SetupInferenceDeps } from "./setup-inference"; vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ @@ -11,13 +15,47 @@ vi.mock("./sandbox-lifecycle", async (importOriginal) => ({ releaseAbandonedRouteReservation: vi.fn(() => false), })); -describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => { - it.each(["explicit", "omitted"])("uses %s native endpoint (#12589)", async (endpointMode) => { +const providers: HostedProviderDefinition[] = [ + ...HOSTED_NATIVE_PROVIDERS, + ...[ + ["compatible-endpoint", "openai-completions", "https://custom.example/v1"], + ["compatible-endpoint", "openai-responses", "https://custom.example/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example"], + ["compatible-anthropic-endpoint", "openai-completions", "https://custom.example"], + ["compatible-anthropic-endpoint", "openai-responses", "https://custom.example"], + ].map(([provider, api, endpointUrl]) => + customNativeProvider({ + provider, + api, + endpointUrl, + credentialEnv: "HOST_KEY", + allowedIps: ["8.8.8.8"], + }), + ), +]; + +describe.each(providers)("native $label onboarding", (provider) => { + const endpointModes = provider.custom + ? [ + "explicit", + "previous-provider", + ...(provider.api === + (provider.logicalProvider === "compatible-anthropic-endpoint" + ? "anthropic-messages" + : "openai-completions") + ? ["default-api"] + : []), + ] + : ["explicit", "omitted"]; + it.each(endpointModes)("uses %s native endpoint (#12589)", async (endpointMode) => { const receipt = { schemaVersion: 1, profileId: provider.profileId, providerName: provider.providerName, providerId: "identity", + ...(provider.endpointUrl ? { endpointUrl: provider.endpointUrl } : {}), + ...(provider.allowedIps ? { allowedIps: provider.allowedIps } : {}), + ...(provider.custom ? { custom: provider.custom } : {}), } as const; const getProvider = vi .fn() @@ -49,6 +87,7 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => const verifyOnboardInferenceSmoke = vi.fn(async () => undefined); const updateSandbox = vi.fn(() => true); const writeAuthority = vi.fn(); + const recordMigratedProviderCredential = vi.fn(); const setup = createSetupInference({ checkGatewayRouteCompatibility: vi.fn(() => ({ ok: true })), withSandboxMutationLock: async (_name: string, fn: () => T | Promise) => await fn(), @@ -58,10 +97,27 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => getGatewayName: () => "gateway", runOpenshell, updateSandbox, + localInference: { loadPendingOllamaModelCleanup: () => [] }, + withOllamaModelOwnershipLock: (operation: () => unknown) => operation(), getNativeHostedProviderAuthority: () => undefined, setNativeHostedProviderAuthority: writeAuthority, - getSandbox: () => null, + getSandbox: () => + endpointMode === "previous-provider" + ? { + name: "alpha", + provider: "openai-api", + pendingRouteReservation: true, + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: HOSTED_NATIVE_PROVIDERS[0].profileId, + providerName: HOSTED_NATIVE_PROVIDERS[0].providerName, + providerId: "previous-provider-id", + }, + } + : null, + resolveEndpointHost: async () => [{ address: "8.8.8.8", family: 4 }], upsertProvider: vi.fn(), + recordMigratedProviderCredential, verifyInferenceRoute, verifyOnboardInferenceSmoke, isNonInteractive: () => true, @@ -115,11 +171,14 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => "alpha", "supported-model", provider.logicalProvider, - endpointMode === "explicit" ? provider.endpoint : null, - provider.credentialEnv, + endpointMode !== "omitted" ? (provider.custom?.endpointUrl ?? provider.endpoint) : null, + provider.custom?.credentialEnv ?? provider.credentialEnv, null, [], - { revalidateSandboxIdentity: () => undefined }, + { + revalidateSandboxIdentity: () => undefined, + preferredInferenceApi: endpointMode === "default-api" ? null : provider.api, + }, ), ).resolves.toMatchObject({ ok: true }); expect(createProvider).toHaveBeenCalledExactlyOnceWith( @@ -129,16 +188,29 @@ describe.each(HOSTED_NATIVE_PROVIDERS)("native $label onboarding", (provider) => type: provider.profileId, }), ); + expect(recordMigratedProviderCredential.mock.calls).toEqual( + provider.custom + ? [ + [ + provider.logicalProvider, + provider.custom.credentialEnv, + "host-secret", + expect.any(Function), + ], + ] + : [], + ); expect(writeAuthority).toHaveBeenCalledWith("gateway", provider.logicalProvider, receipt); expect(updateSandbox).toHaveBeenCalledWith( "alpha", expect.objectContaining({ nativeHostedProviderAttachment: receipt, provider: provider.logicalProvider, + preferredInferenceApi: provider.api, }), ); expect(verifyOnboardInferenceSmoke.mock.calls).toEqual( - provider.logicalProvider === "hermes-provider" + provider.logicalProvider === "hermes-provider" || provider.custom ? [] : [ [ diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index d2e480016ab..c3c7ab3af10 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -229,12 +229,112 @@ describe("composeSandboxConfigBody", () => { }); it.each([ - { value: undefined, expectedStatus: 75 }, - { value: "nvapi-do-not-write", expectedStatus: 1 }, - { value: "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", expectedStatus: 1 }, + [ + "compatible-endpoint", + "inference", + "COMPATIBLE_API_KEY", + "http://10.1.1.225:8123/v1", + "openai-completions", + ], + [ + "compatible-endpoint", + "inference", + "COMPATIBLE_API_KEY", + "https://fixture.example/v1", + "openai-responses", + ], + [ + "compatible-anthropic-endpoint", + "inference", + "COMPATIBLE_ANTHROPIC_API_KEY", + "https://fixture.example/openai/v1", + "openai-completions", + ], + [ + "compatible-anthropic-endpoint", + "inference", + "COMPATIBLE_ANTHROPIC_API_KEY", + "https://fixture.example/openai/v1", + "openai-responses", + ], + [ + "compatible-anthropic-endpoint", + "anthropic", + "COMPATIBLE_ANTHROPIC_API_KEY", + "https://fixture.example", + "anthropic-messages", + ], + ["openai-api", "openai", "OPENAI_API_KEY", "https://api.openai.com/v1", "openai-completions"], + [ + "anthropic-prod", + "anthropic", + "ANTHROPIC_API_KEY", + "https://api.anthropic.com", + "anthropic-messages", + ], + [ + "hermes-provider", + "inference", + "OPENAI_API_KEY", + "https://hermes.example/v1", + "openai-completions", + ], ])( - "refuses invalid native NVIDIA handle $value before config mutation", - ({ value, expectedStatus }) => { + "materializes %s native credentials at %s from %s before the atomic config write", + (logicalProvider, provider, key, baseUrl, api) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-config-")); + try { + fs.writeFileSync(path.join(directory, "openclaw"), '#!/bin/sh\ncat "$4"\n', { + mode: 0o700, + }); + const canonical = `openshell:resolve:env:${key}`; + const headers = { "X-NemoClaw-Upstream-Provider": logicalProvider }; + const handle = `openshell:resolve:env:s${"a".repeat(64)}_${key}`; + const updates = [ + { dotpath: "agents.defaults.model.primary", value: `${provider}/model-a` }, + { + dotpath: `models.providers.${provider}`, + value: { baseUrl, api, headers, apiKey: canonical, models: [{ id: "model-a" }] }, + }, + { dotpath: "channels.telegram.botToken", value: canonical }, + ]; + const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", updates); + const command = invocation.args.slice(invocation.args.indexOf("--") + 1); + const result = spawnSync(command[0]!, command.slice(1), { + input: invocation.input, + encoding: "utf8", + timeout: 5_000, + env: { ...process.env, PATH: `${directory}:${process.env.PATH ?? ""}`, [key]: handle }, + }); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([ + { path: updates[0]!.dotpath, value: updates[0]!.value }, + { + path: updates[1]!.dotpath, + value: { baseUrl, api, headers, apiKey: handle, models: [{ id: "model-a" }] }, + }, + { path: updates[2]!.dotpath, value: canonical }, + ]); + expect(invocation.input).not.toContain(handle); + expect(invocation.args.join(" ")).not.toContain(handle); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it.each( + [ + { value: undefined, expectedStatus: 75 }, + { value: "nvapi-do-not-write", expectedStatus: 1 }, + { value: "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", expectedStatus: 1 }, + { value: "openshell:resolve:env:v43_OTHER_API_KEY", expectedStatus: 1 }, + ].flatMap((scenario) => + ["NVIDIA_INFERENCE_API_KEY", "COMPATIBLE_API_KEY"].map((key) => ({ ...scenario, key })), + ), + )( + "refuses invalid native $key handle $value before config mutation", + ({ value, expectedStatus, key }) => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-config-")); try { fs.writeFileSync(path.join(directory, "openclaw"), '#!/bin/sh\ncat "$4"\n', { @@ -243,7 +343,18 @@ describe("composeSandboxConfigBody", () => { const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", [ { dotpath: "models.providers.inference", - value: { baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, apiKey: NVIDIA_INFERENCE_PLACEHOLDER }, + value: { + baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + apiKey: + key === "NVIDIA_INFERENCE_API_KEY" + ? NVIDIA_INFERENCE_PLACEHOLDER + : `openshell:resolve:env:${key}`, + api: "openai-completions", + headers: { + "X-NemoClaw-Upstream-Provider": + key === "NVIDIA_INFERENCE_API_KEY" ? "nvidia-prod" : "compatible-endpoint", + }, + }, }, ]); const command = invocation.args.slice(invocation.args.indexOf("--") + 1); @@ -254,7 +365,7 @@ describe("composeSandboxConfigBody", () => { env: { ...process.env, PATH: `${directory}:${process.env.PATH ?? ""}`, - NVIDIA_INFERENCE_API_KEY: value, + [key]: value, }, }); expect(failed.status).toBe(expectedStatus); @@ -403,7 +514,54 @@ describe("composeSandboxConfigBody", () => { ).toThrow("Native provider config path does not match its identity"); }); - it("keeps compatible endpoint resolver placeholders outside hosted handle pinning (#13040)", () => { + it.each([ + { + label: "credential from another provider", + patch: { apiKey: "openshell:resolve:env:ANTHROPIC_API_KEY" }, + }, + { + label: "endpoint with embedded credentials", + patch: { baseUrl: "https://user:secret@fixture.example/v1" }, + }, + { label: "endpoint with a query", patch: { baseUrl: "https://fixture.example/v1?key=secret" } }, + ])("rejects custom native $label before config mutation (#13195)", ({ patch }) => { + expect(() => + buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.inference", + value: { + baseUrl: "https://fixture.example/v1", + api: "openai-completions", + apiKey: "openshell:resolve:env:COMPATIBLE_API_KEY", + headers: { "X-NemoClaw-Upstream-Provider": "compatible-endpoint" }, + ...patch, + }, + }, + ]), + ).toThrow(); + }); + + it("rejects a custom native path mismatch or ambiguous batch before config mutation (#13195)", () => { + const update = { + dotpath: "models.providers.anthropic", + value: { + baseUrl: "https://fixture.example", + api: "anthropic-messages", + apiKey: "openshell:resolve:env:COMPATIBLE_ANTHROPIC_API_KEY", + headers: { "X-NemoClaw-Upstream-Provider": "compatible-anthropic-endpoint" }, + }, + }; + expect(() => + buildOpenClawNativeConfigBatchInvocation("alpha", [ + { ...update, dotpath: "models.providers.inference" }, + ]), + ).toThrow("Native provider config path does not match its identity"); + expect(() => buildOpenClawNativeConfigBatchInvocation("alpha", [update, update])).toThrow( + "Expected one native provider config update", + ); + }); + + it("keeps shared-route compatible endpoint placeholders outside native handle pinning (#13040, #13195)", () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-compatible-config-")); try { fs.writeFileSync(path.join(directory, "openclaw"), '#!/bin/sh\ncat "$4"\n', { @@ -413,7 +571,7 @@ describe("composeSandboxConfigBody", () => { { dotpath: "models.providers.inference", value: { - baseUrl: "https://compatible.example/v1", + baseUrl: "https://inference.local/v1", apiKey: "openshell:resolve:env:COMPATIBLE_API_KEY", headers: { "X-NemoClaw-Upstream-Provider": "compatible-endpoint" }, }, diff --git a/src/lib/sandbox/openclaw-native-config.ts b/src/lib/sandbox/openclaw-native-config.ts index 6accfc9424f..58eee502240 100644 --- a/src/lib/sandbox/openclaw-native-config.ts +++ b/src/lib/sandbox/openclaw-native-config.ts @@ -133,7 +133,12 @@ function nativeProviderHandleUpdate(updates: readonly OpenClawConfigUpdate[]) { return false; const headers = isConfigObject(value.headers) ? value.headers : {}; const provider = headers["X-NemoClaw-Upstream-Provider"]; - return typeof provider === "string" && Boolean(fixedNativeProvider(provider)); + return ( + typeof provider === "string" && + (Boolean(fixedNativeProvider(provider)) || + (typeof value.baseUrl === "string" && + Boolean(nativeHostedAgentConfig(provider, value.baseUrl)))) + ); }); if (matching.length === 0) return undefined; if (matching.length !== 1) throw new Error("Expected one native provider config update"); @@ -175,7 +180,10 @@ function nativeProviderHandleUpdate(updates: readonly OpenClawConfigUpdate[]) { : typeof provider === "string" ? provider : null; - const providerKey = nativeOpenClawProviderKey(logicalProvider); + const providerKey = nativeOpenClawProviderKey( + logicalProvider, + typeof value.api === "string" ? value.api : null, + ); if (!providerKey) throw new Error("Native provider identity does not match its credential placeholder"); const expectedPath = `models.providers.${providerKey}`; diff --git a/src/lib/state/registry-native-provider-attachment.test.ts b/src/lib/state/registry-native-provider-attachment.test.ts index ad8f57041b0..898b1cf4ba4 100644 --- a/src/lib/state/registry-native-provider-attachment.test.ts +++ b/src/lib/state/registry-native-provider-attachment.test.ts @@ -197,3 +197,59 @@ it("lists registered sandboxes that retain native NVIDIA provider ownership", as vi.unstubAllEnvs(); } }); + +it.each([ + ["unchanged binding", {}, true], + ["model change", { model: "model-b" }, true], + ["endpoint change", { endpointUrl: "https://other.example/v1" }, false], + ["API change", { preferredInferenceApi: "openai-responses" }, false], + ["credential change", { credentialEnv: "OTHER_KEY" }, false], + ["gateway change", { gatewayName: "other-gateway" }, false], +] as const)( + "preserves custom native reservation authority only for its binding: %s", + async (_label, changes, retained) => { + const home = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-custom-reservation-")); + vi.stubEnv("HOME", home); + vi.resetModules(); + try { + const registry = await import("./registry"); + const { customNativeProvider } = await import("../inference/native-provider/custom"); + const route = { + provider: "compatible-endpoint", + model: "model-a", + endpointUrl: "https://custom.example/v1", + credentialEnv: "COMPATIBLE_API_KEY", + preferredInferenceApi: "openai-completions", + gatewayName: "nemoclaw", + }; + const definition = customNativeProvider({ + provider: route.provider, + endpointUrl: route.endpointUrl, + credentialEnv: route.credentialEnv, + api: route.preferredInferenceApi, + allowedIps: ["8.8.8.8"], + }); + const receipt = { + schemaVersion: 1 as const, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "owned-provider-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }; + registry.registerSandbox({ + name: "alpha", + ...route, + nativeHostedProviderAttachment: receipt, + }); + expect(registry.reserveSandboxInferenceRoute("alpha", { ...route, ...changes })).toBe(true); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual( + retained ? receipt : undefined, + ); + } finally { + await fs.rm(home, { recursive: true, force: true }); + vi.unstubAllEnvs(); + } + }, +); diff --git a/src/lib/state/registry.ts b/src/lib/state/registry.ts index 7e0033cdde0..fe31aefa34d 100644 --- a/src/lib/state/registry.ts +++ b/src/lib/state/registry.ts @@ -809,6 +809,7 @@ export function reserveSandboxInferenceRoute( nativeHostedProviderAttachment, normalized.provider, existing ?? undefined, + { ...normalized, gatewayName: route.gatewayName }, ), nativeNvidiaProviderAttachment: isNativeNvidiaProvider(normalized.provider) ? (nativeNvidiaProviderAttachment ?? existing?.nativeNvidiaProviderAttachment) diff --git a/src/lib/state/registry/native-hosted-provider-authority.test.ts b/src/lib/state/registry/native-hosted-provider-authority.test.ts index 39702678bfa..ea498b37ee0 100644 --- a/src/lib/state/registry/native-hosted-provider-authority.test.ts +++ b/src/lib/state/registry/native-hosted-provider-authority.test.ts @@ -9,6 +9,7 @@ import { HOSTED_NATIVE_PROVIDERS, hostedNativeProvider, } from "../../inference/native-provider/hosted"; +import { customNativeProvider } from "../../inference/native-provider/custom"; import { normalizeNativeHostedProviderAuthorities } from "./native-provider-authority-state"; const openai = { @@ -199,3 +200,65 @@ it("retains independent Hermes ownership across authenticated endpoint changes ( await fs.rm(temporaryHome, { recursive: true, force: true }); } }); + +it("persists custom endpoint ownership through reservation, registration and a model update", async () => { + const temporaryHome = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-custom-authority-")); + vi.stubEnv("HOME", temporaryHome); + vi.resetModules(); + try { + const registry = await import("../registry"); + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-responses", + credentialEnv: "TEAM_KEY", + allowedIps: ["8.8.8.8"], + }); + const receipt = { + schemaVersion: 1 as const, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "custom-identity", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }; + registry.setNativeHostedProviderAuthority("gateway", definition.logicalProvider, receipt); + expect(registry.getNativeHostedProviderAuthority("gateway", definition.providerName)).toEqual( + receipt, + ); + expect( + registry.getNativeHostedProviderAuthority("other", definition.providerName), + ).toBeUndefined(); + registry.registerSandbox({ + name: "alpha", + gatewayName: "gateway", + provider: definition.logicalProvider, + model: "first", + nativeHostedProviderAttachment: receipt, + }); + registry.reserveSandboxInferenceRoute("alpha", { + gatewayName: "gateway", + provider: definition.logicalProvider, + model: "first", + credentialEnv: "TEAM_KEY", + endpointUrl: definition.custom.endpointUrl, + preferredInferenceApi: definition.custom.api, + nativeHostedProviderAttachment: receipt, + }); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual(receipt); + registry.updateSandbox("alpha", { model: "second" }); + expect(registry.getSandbox("alpha")?.nativeHostedProviderAttachment).toEqual(receipt); + expect(registry.getSandbox("alpha")?.model).toBe("second"); + expect( + (await import("./native-provider-authority")).listNativeHostedProviderAttachmentSandboxNames( + "gateway", + definition.providerName, + ), + ).toEqual(["alpha"]); + } finally { + vi.unstubAllEnvs(); + vi.resetModules(); + await fs.rm(temporaryHome, { recursive: true, force: true }); + } +}); diff --git a/src/lib/state/registry/native-provider-authority.ts b/src/lib/state/registry/native-provider-authority.ts index bd880ac83fc..006b458545a 100644 --- a/src/lib/state/registry/native-provider-authority.ts +++ b/src/lib/state/registry/native-provider-authority.ts @@ -10,6 +10,8 @@ import { import { isDeepStrictEqual } from "node:util"; import type { NativeProviderAttachment } from "../../inference/native-provider/contract"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; +import { isCustomNativeProviderName } from "../../inference/native-provider/custom"; +import { normalizeHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; import { requireHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; import { readNativeHostedGatewayAuthorities } from "./native-provider-authority-state"; import { withLock } from "./lock"; @@ -61,6 +63,10 @@ export function getNativeHostedProviderAuthority( provider: string, endpointUrl?: string | null, ): NativeProviderAttachment | undefined { + if (isCustomNativeProviderName(provider)) + return normalizeHostedProviderAttachment( + readNativeHostedGatewayAuthorities(load(), gatewayName)?.[provider], + ); if (!hostedNativeProvider(provider)) return undefined; const authorities = readNativeHostedGatewayAuthorities(load(), gatewayName); const current = requireHostedProviderAttachment(authorities?.[provider], provider); @@ -83,15 +89,16 @@ export function setNativeHostedProviderAuthority( const state = load(); const authorities = state.nativeHostedProviderAuthorities ?? {}; const gateway = authorities[gatewayName] ?? {}; - if (isDeepStrictEqual(gateway[provider], normalized)) return; + const authorityKey = normalized.custom ? normalized.providerName : provider; + if (isDeepStrictEqual(gateway[authorityKey], normalized)) return; state.nativeHostedProviderAuthorities = { ...authorities, [gatewayName]: { ...gateway, - ...(gateway[provider] && gateway[provider].providerName !== normalized.providerName - ? { [gateway[provider].providerName]: gateway[provider] } + ...(gateway[authorityKey] && gateway[authorityKey].providerName !== normalized.providerName + ? { [gateway[authorityKey].providerName]: gateway[authorityKey] } : {}), - [provider]: normalized, + [authorityKey]: normalized, }, }; save(state); diff --git a/src/lib/state/registry/route-reservation.ts b/src/lib/state/registry/route-reservation.ts index 5e15eebd258..b4eacac03a5 100644 --- a/src/lib/state/registry/route-reservation.ts +++ b/src/lib/state/registry/route-reservation.ts @@ -9,6 +9,7 @@ import { import { isDeepStrictEqual } from "node:util"; import { normalizeInferenceSelection, type InferenceSelection } from "../../inference/selection"; +import { recordedNativeProviderAttachment } from "../../inference/native-provider/recorded-selection"; import { hostedNativeProvider } from "../../inference/native-provider/hosted"; import { requireHostedProviderAttachment } from "../../inference/native-provider/hosted-attachment"; import { normalizeNativeNvidiaProviderAttachment } from "../../inference/native-nvidia"; @@ -419,12 +420,35 @@ export function nativeHostedReservationAttachment( value: unknown, provider: string | null | undefined, previous?: SandboxEntry, + selection?: Pick< + SandboxEntry, + "provider" | "endpointUrl" | "credentialEnv" | "preferredInferenceApi" | "gatewayName" + >, ) { const receipt = requireHostedProviderAttachment(value, provider); - return hostedNativeProvider(provider) - ? (receipt ?? - (previous && previous.provider === provider - ? previous.nativeHostedProviderAttachment - : undefined)) - : undefined; + if (receipt) return receipt; + if (!previous || previous.provider !== provider) return undefined; + const retained = requireHostedProviderAttachment( + previous.nativeHostedProviderAttachment, + provider, + ); + if (retained?.custom) { + if ( + !selection?.endpointUrl || + !selection.credentialEnv || + !selection.preferredInferenceApi || + selection.gatewayName !== previous.gatewayName + ) + return undefined; + try { + return recordedNativeProviderAttachment({ + ...selection, + nativeHostedProviderAttachment: retained, + }); + } catch { + // A changed binding needs new authority from provider setup. + return undefined; + } + } + return hostedNativeProvider(provider) ? retained : undefined; } diff --git a/test/agents/hermes/hermes-managed-policy.test.ts b/test/agents/hermes/hermes-managed-policy.test.ts index 7483a3b7c79..3e73fde1388 100644 --- a/test/agents/hermes/hermes-managed-policy.test.ts +++ b/test/agents/hermes/hermes-managed-policy.test.ts @@ -16,6 +16,8 @@ import { HERMES_MANAGED_POLICY_SCHEMA_VERSION, } from "../../../agents/hermes/config/managed-policy.ts"; +import { BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL } from "../../../src/lib/inference/bedrock-runtime"; + import { HOSTED_NATIVE_PROVIDERS } from "../../../src/lib/inference/native-provider/hosted"; const READER_PATH = path.join( @@ -101,6 +103,38 @@ describe("Hermes managed policy", () => { }, ); + it.each([ + ["compatible-endpoint", "https://hosted.example:8443/inference/v1", "COMPATIBLE_API_KEY"], + ["compatible-endpoint", "https://integrate.api.nvidia.com/v1", "COMPATIBLE_API_KEY"], + ["compatible-endpoint", "http://10.20.30.40:8080/v1", "COMPATIBLE_API_KEY"], + [ + "compatible-anthropic-endpoint", + "https://anthropic.example/v1", + "COMPATIBLE_ANTHROPIC_API_KEY", + ], + [ + "compatible-anthropic-endpoint", + BEDROCK_RUNTIME_ADAPTER_OPENAI_BASE_URL, + "COMPATIBLE_ANTHROPIC_API_KEY", + ], + ])( + "loads a generated custom policy for %s at %s (#13195)", + (provider, baseUrl, credentialEnv) => { + const policy = buildHermesManagedPolicy( + { ...SETTINGS, baseUrl, upstreamProvider: provider }, + {}, + ); + expect(policy.config.model?.api_key).toBe(`\${${credentialEnv}}`); + const result = loadWithPython(policy); + expect(result.status, result.stderr).toBe(0); + + policy.config.model!.api_key = "synthetic-raw-credential"; + const rejected = loadWithPython(policy); + expect(rejected.status).toBe(1); + expect(rejected.stderr).not.toContain("synthetic-raw-credential"); + }, + ); + it("accepts the Hermes credential reference at an authenticated endpoint", () => { const policy = buildHermesManagedPolicy( { @@ -121,6 +155,15 @@ describe("Hermes managed policy", () => { ["openai-api", "https://api.openai.com:8443/v1", "${OPENAI_API_KEY}"], ["openai-api", "https://api.openai.com.example/v1", "${OPENAI_API_KEY}"], ["custom", "https://api.openai.com/v1", "${OPENAI_API_KEY}"], + ["compatible-endpoint", "https://hosted.example/v1", "${COMPATIBLE_ANTHROPIC_API_KEY}"], + ["compatible-anthropic-endpoint", "https://hosted.example/v1", "${COMPATIBLE_API_KEY}"], + ["compatible-endpoint", "https://inference.local/v1", "${COMPATIBLE_API_KEY}"], + ["compatible-endpoint", "http://localhost/v1", "${COMPATIBLE_API_KEY}"], + ["compatible-endpoint", "http://127.0.0.1/v1", "${COMPATIBLE_API_KEY}"], + ["compatible-endpoint", "http://[::1]/v1", "${COMPATIBLE_API_KEY}"], + ["compatible-endpoint", "https://do-not-echo@hosted.example/v1", "${COMPATIBLE_API_KEY}"], + ["compatible-endpoint", "https://hosted.example/v1?do-not-echo", "${COMPATIBLE_API_KEY}"], + ["compatible-endpoint", "https://hosted.example/v1#do-not-echo", "${COMPATIBLE_API_KEY}"], ["hermes-provider", "https://authenticated-hermes.example/v1", "${GEMINI_API_KEY}"], ["hermes-provider", "https://inference.local/v1", "${OPENAI_API_KEY}"], ["hermes-provider", "https://localhost/v1", "${OPENAI_API_KEY}"], diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts index 451a6dd9781..3846a950bfa 100644 --- a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts @@ -177,6 +177,78 @@ os.fsync = sync_or_fail` }, ); + it.each( + [false, true].flatMap((rootMode) => + [ + { provider: "inference", key: "COMPATIBLE_API_KEY", endpoint: "http://10.1.1.225:8123/v1" }, + { + provider: "anthropic", + key: "COMPATIBLE_ANTHROPIC_API_KEY", + endpoint: "https://fixture.example", + }, + { provider: "openai", key: "OPENAI_API_KEY", endpoint: "https://api.openai.com/v1" }, + ].map((route) => ({ ...route, rootMode })), + ), + )( + "refreshes only the persisted $provider credential on restart (root=$rootMode)", + async ({ provider, key, endpoint, rootMode }) => { + const saved = `openshell:resolve:env:v42_${key}`; + const current = `openshell:resolve:env:s${"a".repeat(64)}_${key}`; + const run = await runRefresh( + { + models: { + providers: { + [provider]: { baseUrl: endpoint, apiKey: saved }, + unrelated: { baseUrl: endpoint, apiKey: saved }, + }, + }, + channels: { telegram: { botToken: saved } }, + }, + { [key]: current }, + rootMode, + ); + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers[provider].apiKey).toBe(current); + expect(run.config.models.providers.unrelated.apiKey).toBe(saved); + expect(run.config.channels.telegram.botToken).toBe(saved); + }, + ); + + it.each( + [false, true].flatMap((rootMode) => + [ + "", + "raw-do-not-copy", + "openshell:resolve:env:v43_OTHER_API_KEY", + "openshell:resolve:env:COMPATIBLE_API_KEY", + ].map((runtime) => ({ runtime, rootMode })), + ), + )( + "keeps the saved custom credential when the runtime handle is invalid (root=$rootMode, runtime=$runtime)", + async ({ runtime, rootMode }) => { + const saved = "openshell:resolve:env:v42_COMPATIBLE_API_KEY"; + const run = await runRefresh( + { + models: { + providers: { + inference: { + baseUrl: "https://fixture.example/v1", + apiKey: saved, + }, + }, + }, + }, + { COMPATIBLE_API_KEY: runtime }, + rootMode, + ); + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers.inference.apiKey).toBe(saved); + expect(JSON.stringify(run.config)).not.toContain("raw-do-not-copy"); + expect(run.result.stderr).not.toContain("raw-do-not-copy"); + expect(run.handoffEnv).not.toContain("raw-do-not-copy"); + }, + ); + it.each([ ["https://integrate.api.nvidia.com/v1/", "NVIDIA_INFERENCE_API_KEY"], ["https://openrouter.ai/api/v1/", "OPENROUTER_API_KEY"], diff --git a/test/credentials/credential-migration-reconciliation.test.ts b/test/credentials/credential-migration-reconciliation.test.ts index 83542b97e0c..c5817c91147 100644 --- a/test/credentials/credential-migration-reconciliation.test.ts +++ b/test/credentials/credential-migration-reconciliation.test.ts @@ -404,3 +404,50 @@ describe("legacy credential reconciliation", () => { } }); }); + +it.each([true, false])( + "retires only the persisted native credential value (matches=%s)", + async (matches) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "native-credential-migration-")); + const legacy = path.join(directory, ".nemoclaw", "credentials.json"); + fs.mkdirSync(path.dirname(legacy), { recursive: true }); + fs.writeFileSync(legacy, JSON.stringify({ COMPATIBLE_API_KEY: LEGACY_SECRET }), { + mode: 0o600, + }); + try { + await withProcessEnv({ HOME: directory, COMPATIBLE_API_KEY: undefined }, async () => { + const stagedKeys = stageLegacyCredentialsToEnv(); + const stagedValues = new Map(stagedKeys.map((key) => [key, process.env[key] ?? ""])); + const migrated = new Set(); + const revalidate = vi.fn(); + const registration = createCredentialProviderRegistration({ + root: directory, + getGatewayName: () => "gateway", + getCredential: () => null, + runOpenshell: vi.fn(), + updateSession: vi.fn(), + stagedLegacyValues: stagedValues, + migratedLegacyKeys: migrated, + }); + registration.recordMigratedProviderCredential( + "compatible-endpoint", + "COMPATIBLE_API_KEY", + matches ? LEGACY_SECRET : "different-persisted-key", + revalidate, + ); + expect(revalidate).toHaveBeenCalledTimes(1); + await finalizeMigration(stagedKeys, migrated, stagedValues); + expect(fs.existsSync(legacy)).toBe(!matches); + const retainedCredentials = fs + .readdirSync(path.dirname(legacy)) + .filter((name) => name === "credentials.json") + .map((name) => + JSON.parse(fs.readFileSync(path.join(path.dirname(legacy), name), "utf8")), + ); + expect(retainedCredentials).toEqual(matches ? [] : [{ COMPATIBLE_API_KEY: LEGACY_SECRET }]); + }); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, +); diff --git a/test/e2e/README.md b/test/e2e/README.md index af165234705..777266aa730 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -834,6 +834,10 @@ Custom Dockerfile onboarding uses the existing startup and pairing settlement ch restarting the native gateway for the initial inference route, as external-image onboarding does. The target requires onboarding to create the selected model without those limits, then preserves that native configuration through restart and rebuild. The OpenClaw native NVIDIA and mock Anthropic switch variants start with an authenticated local OpenAI-compatible fixture. +The Anthropic variant starts on a native OpenAI-compatible route, then switches to a native Anthropic endpoint. +Both endpoints use the runner's private address through the existing explicit private-host trust setting. +Its mock rejects a missing or incorrect credential, and the existing sandbox request and OpenClaw model run must both succeed. +The config probe validates the scoped Anthropic credential reference inside the sandbox before redaction. The native NVIDIA destination uses the public endpoint and its public credential only after switching. Route assertions use JSON fields so terminal column alignment does not affect the result. Hermes native installation uses the public NVIDIA provider before its same-provider model switch. @@ -1042,8 +1046,9 @@ The report also groups repeated observable outcomes. Those rows are retained onl ## Full E2E inference availability `live/full-e2e.test.ts` owns the live sandbox arithmetic probe. -Source installs use `inference.local`; the Brev Launchable uses the native NVIDIA endpoint -with its supervisor-issued credential handle. The test verifies the native provider attachment +Source installs use the recorded custom native endpoint when present, or retain the legacy fixture route. +The Brev Launchable uses the native NVIDIA endpoint. Native routes use supervisor-issued credential handles. +The test verifies the native provider attachment on the declared gateway and retains that route across its temporary native model edit. The live boundary proves attachment, credential resolution, and a real inference response. The support tests own route selection, command encoding, credential rejection, and model-edit configuration. diff --git a/test/e2e/e2e-cloud-experimental/checks/02-inference-local-http.sh b/test/e2e/e2e-cloud-experimental/checks/02-inference-local-http.sh index c66d4927af9..2c6fd8139f1 100755 --- a/test/e2e/e2e-cloud-experimental/checks/02-inference-local-http.sh +++ b/test/e2e/e2e-cloud-experimental/checks/02-inference-local-http.sh @@ -2,7 +2,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # -# Case: inside sandbox, https://inference.local responds (HTTP 200). +# Case: the selected inference route responds inside the sandbox (HTTP 200). # Pattern aligned with test-full-e2e.sh (ssh via openshell sandbox ssh-config). set -euo pipefail @@ -24,9 +24,16 @@ TIMEOUT_CMD="" command -v timeout >/dev/null 2>&1 && TIMEOUT_CMD="timeout 90" command -v gtimeout >/dev/null 2>&1 && TIMEOUT_CMD="gtimeout 90" -# GET /v1/models — lightweight 200 check (no API key in curl; gateway routes inference) +# GET /v1/models verifies the selected route using only a sandbox credential placeholder. ssh_host="openshell-${SANDBOX_NAME}.default" -curl_inner='curl -sS -o /dev/null -w "%{http_code}" --max-time 60 https://inference.local/v1/models' +inference_url="${NEMOCLAW_E2E_CLOUD_INFERENCE_URL:-https://inference.local/v1}" +printf -v models_url '%q' "${inference_url%/}/models" +curl_inner="curl -sS -o /dev/null -w '%{http_code}' --max-time 60 ${models_url}" +if [ "${NEMOCLAW_E2E_CLOUD_NATIVE_INFERENCE:-0}" = "1" ]; then + # Validate the reference in the remote sandbox, where the variables are expanded. + # shellcheck disable=SC2016 + curl_inner='case "${COMPATIBLE_API_KEY:-}" in *[!a-zA-Z0-9:_]*) exit 2 ;; esac; printf "%s" "${COMPATIBLE_API_KEY:-}" | LC_ALL=C grep -Eq "^openshell:resolve:env:((v[0-9]{1,20}|s[a-f0-9]{64})_)?COMPATIBLE_API_KEY$" || exit 2; '"${curl_inner}"' -H "Authorization: Bearer ${COMPATIBLE_API_KEY}"' +fi set +e # stderr from ssh can include host-key noise; curl -w code should be the only stdout line @@ -44,7 +51,7 @@ set -e http_code="$(echo "$http_code" | tr -d '\r' | tail -n 1)" [ "$ssh_rc" -eq 0 ] || die "ssh/curl failed (exit $ssh_rc): ${http_code:0:200}" -[ "$http_code" = "200" ] || die "expected HTTP 200 from https://inference.local/v1/models, got '${http_code}'" +[ "$http_code" = "200" ] || die "expected HTTP 200 from the selected inference models endpoint, got '${http_code}'" printf '%s\n' "02-inference-local-http: OK (HTTP 200 on /v1/models)" exit 0 diff --git a/test/e2e/fixtures/hermes-config-export-live.ts b/test/e2e/fixtures/hermes-config-export-live.ts index 0e3dcb2e3f7..237cf0dceec 100644 --- a/test/e2e/fixtures/hermes-config-export-live.ts +++ b/test/e2e/fixtures/hermes-config-export-live.ts @@ -356,8 +356,11 @@ export async function verifyHermesConfigExportLive( (diagnostic) => { if (!expectsMessagingRefusal) return diagnostic === expectedDiagnostic; const lines = diagnostic.split("\n"); + const categories = /^Config export failed \(([^)]+)\)\.$/ + .exec(lines[0] ?? "")?.[1] + ?.split(", "); return ( - lines[0] === "Config export failed (unsupported)." && + categories?.includes("unsupported") === true && expectedRefusals.every((refusal) => lines.includes(refusal)) ); }, diff --git a/test/e2e/fixtures/inference-adapter.ts b/test/e2e/fixtures/inference-adapter.ts index 8b5838094e7..5b7229622f8 100644 --- a/test/e2e/fixtures/inference-adapter.ts +++ b/test/e2e/fixtures/inference-adapter.ts @@ -2,6 +2,12 @@ // SPDX-License-Identifier: Apache-2.0 import { randomBytes } from "node:crypto"; +import { nativeHostedAuthHeaderScript } from "../../../src/lib/inference/native-provider/contract.ts"; +import { + NATIVE_NVIDIA_AUTH_HEADER_SCRIPT, + NVIDIA_HOSTED_LOGICAL_PROVIDER, + NVIDIA_HOSTED_NATIVE_ENDPOINT, +} from "../../../src/lib/inference/native-nvidia/contract.ts"; import type { ArtifactSink } from "./artifacts.ts"; import { buildAvailabilityProbeEnv } from "./availability-env.ts"; @@ -456,3 +462,39 @@ export async function createE2EInferenceAdapter( } export { DEFAULT_HOSTED_INFERENCE_MODEL as DEFAULT_INTERNAL_NVIDIA_MODEL }; + +/** Build the in-sandbox chat request without exposing a host credential. */ +export function buildSandboxInferenceChatCommand( + requestBody: string, + logicalProvider: string, + endpointUrl?: string, +): [string, ...string[]] { + const nativeCustom = logicalProvider === "compatible-endpoint" && endpointUrl; + if (logicalProvider === NVIDIA_HOSTED_LOGICAL_PROVIDER || nativeCustom) { + const auth = nativeCustom + ? nativeHostedAuthHeaderScript({ + credentialEnv: "COMPATIBLE_API_KEY", + api: "openai-completions", + }) + : NATIVE_NVIDIA_AUTH_HEADER_SCRIPT; + return [ + "bash", + "-c", + `${auth}; exec curl -fsS --max-time 90 "$1" -H 'Content-Type: application/json' -H "$AUTH_HEADER" --data-raw "$2"`, + "full-e2e-native-inference", + `${(nativeCustom ? endpointUrl : NVIDIA_HOSTED_NATIVE_ENDPOINT).replace(/\/+$/u, "")}/chat/completions`, + requestBody, + ]; + } + return [ + "curl", + "-fsS", + "--max-time", + "90", + "https://inference.local/v1/chat/completions", + "-H", + "Content-Type: application/json", + "--data-raw", + requestBody, + ]; +} diff --git a/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts b/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts index 47742e2a2ee..9efbfedefcb 100644 --- a/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts +++ b/test/e2e/live/bedrock-runtime-compatible-anthropic.test.ts @@ -815,7 +815,7 @@ async function assertNoBedrockLeaks(options: { } test( - "bedrock runtime compatible Anthropic endpoint routes through managed inference.local", + "bedrock runtime compatible Anthropic endpoint routes through an attached native provider", { timeout: TEST_TIMEOUT_MS, meta: { @@ -892,7 +892,7 @@ test( "the selected runtime, python3, source CLI, and OpenShell are available", "bedrock-runtime.us-east-1.amazonaws.com maps to the host fake endpoint", "non-interactive anthropicCompatible onboarding completes for OpenClaw and Hermes", - "the selected agent-native runtime path returns PONG through inference.local", + "the selected agent-native runtime path returns PONG through its native Bedrock adapter provider", "fake Bedrock Runtime endpoint observes authenticated Converse traffic", "the OpenClaw path observes authenticated ConverseStream traffic", "bounded sandbox credential, config, environment, and process-argument probes contain no forbidden Bedrock values", diff --git a/test/e2e/live/cloud-onboard.test.ts b/test/e2e/live/cloud-onboard.test.ts index 7869ebb50e2..921bd80951d 100644 --- a/test/e2e/live/cloud-onboard.test.ts +++ b/test/e2e/live/cloud-onboard.test.ts @@ -4,6 +4,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import type { SandboxEntry } from "../../../src/lib/state/registry/types.ts"; +import { recordedNativeProviderAttachment } from "../../../src/lib/inference/native-provider/recorded-selection.ts"; +import { readRegistrySandboxEntry } from "../fixtures/phases/state-validation.ts"; import { execTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText, shellQuote } from "../fixtures/clients/command.ts"; @@ -177,7 +180,7 @@ test( "explicit corporate CA source is baked and merged with OpenShell trust inside the sandbox", "validated compatible-endpoint reasoning reaches the authenticated runtime handoff and OpenClaw model metadata", "installed CLI creates a non-empty diagnostics archive for the registered sandbox", - "cloud split checks cover inference.local, security leak checks, and Landlock/read-only behavior", + "cloud split checks cover the selected inference route, security leak checks, and Landlock/read-only behavior", "cleanup verifies sandbox removal", ], }); @@ -264,7 +267,12 @@ test( .split(/\r?\n/) .map((line) => line.trim()) .filter((line) => /^[a-zA-Z][a-zA-Z0-9_-]*$/.test(line)); - expect(providerNames).toContain(hosted.providerName); + const registered = readRegistrySandboxEntry(SANDBOX_NAME, { + registryPath: path.join(testHome, ".nemoclaw", "sandboxes.json"), + }) as unknown as SandboxEntry; + const nativeRoute = recordedNativeProviderAttachment(registered); + const expectedGatewayProvider = nativeRoute?.providerName ?? hosted.providerName; + expect(providerNames).toContain(expectedGatewayProvider); expect(providerNames).not.toContain("OPENSHELL_GATEWAY"); expect(providerNames).not.toContain("NODE_OPTIONS"); @@ -350,6 +358,8 @@ test( env: testEnv({ ...hosted.env, CLOUD_EXPERIMENTAL_MODEL: hosted.model, + NEMOCLAW_E2E_CLOUD_INFERENCE_URL: nativeRoute?.endpointUrl, + NEMOCLAW_E2E_CLOUD_NATIVE_INFERENCE: nativeRoute ? "1" : "0", COMPATIBLE_API_KEY: hosted.apiKey, NEMOCLAW_E2E_CLOUD_API_KEY_ENV: "COMPATIBLE_API_KEY", REPO: REPO_ROOT, @@ -374,7 +384,7 @@ test( status: "passed", credentialMigration: { legacyFileRemoved: !fs.existsSync(legacyFile), - migratedProviderRegistered: providerNames.includes(hosted.providerName), + migratedProviderRegistered: providerNames.includes(expectedGatewayProvider), tamperedKeysExcluded: !providerNames.includes("OPENSHELL_GATEWAY") && !providerNames.includes("NODE_OPTIONS"), }, diff --git a/test/e2e/live/full-e2e-inference-probe.ts b/test/e2e/live/full-e2e-inference-probe.ts index 59eb34b9b00..f75e6b13d61 100644 --- a/test/e2e/live/full-e2e-inference-probe.ts +++ b/test/e2e/live/full-e2e-inference-probe.ts @@ -1,14 +1,19 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { parseCliOpenShellProviderMetadata } from "../../../src/lib/adapters/openshell/provider-metadata-cli.ts"; +import { hostedNativeProviderForAttachment } from "../../../src/lib/inference/native-provider/hosted-attachment.ts"; +import { getSandboxInferenceConfig } from "../../../src/lib/inference/config.ts"; +import type { SandboxEntry } from "../../../src/lib/state/registry/types.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import { + PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, + readPublicNvidiaSwitchAttachmentEvidence, +} from "./public-nvidia-switch-provider.ts"; + import { runBoundedRetry, type RetryEvidence } from "../../../tools/e2e/retry-evidence.mts"; import { resolveMaxTokensField } from "../../../src/lib/inference/max-tokens-field.ts"; -import { - NATIVE_NVIDIA_AUTH_HEADER_SCRIPT, - NVIDIA_HOSTED_LOGICAL_PROVIDER, - NVIDIA_HOSTED_NATIVE_ENDPOINT, -} from "../../../src/lib/inference/native-nvidia/contract.ts"; import { containsAnswer, containsToolCallStructure } from "../../helpers/e2e-answer-assertions.ts"; const ARITHMETIC_PROMPT = "What is 6 multiplied by 7? Reply with only the integer, no extra words."; @@ -23,32 +28,6 @@ const EVIDENCE_MODEL_LIMIT_BYTES = 512; const EVIDENCE_FINISH_REASON_LIMIT_BYTES = 128; const TRUNCATION_SUFFIX = "...[truncated]"; -export function buildFullE2eSandboxInferenceCommand( - requestBody: string, - logicalProvider: string, -): [string, ...string[]] { - if (logicalProvider === NVIDIA_HOSTED_LOGICAL_PROVIDER) { - return [ - "bash", - "-c", - `${NATIVE_NVIDIA_AUTH_HEADER_SCRIPT}; exec curl -fsS --max-time 90 "$1" -H 'Content-Type: application/json' -H "$AUTH_HEADER" --data-raw "$2"`, - "full-e2e-native-inference", - `${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions`, - requestBody, - ]; - } - return [ - "curl", - "-fsS", - "--max-time", - "90", - "https://inference.local/v1/chat/completions", - "-H", - "Content-Type: application/json", - "--data-raw", - requestBody, - ]; -} const USAGE_TOTAL_FIELDS = ["prompt_tokens", "completion_tokens", "total_tokens"] as const; const USAGE_DETAIL_FIELDS = [ "audio_tokens", @@ -341,3 +320,106 @@ export function fullE2eInferenceProbeEvidence { + const receipt = input.entry?.nativeHostedProviderAttachment; + if (receipt?.custom) { + const definition = hostedNativeProviderForAttachment(receipt); + if (!definition) return { ok: false, detail: "Invalid custom native ownership" }; + const options = { + env: input.env, + redactionValues: input.redactionValues, + timeoutMs: 60_000, + captureLimitBytes: 16 * 1024, + }; + const gateway = input.entry?.gatewayName || input.env.OPENSHELL_GATEWAY || "nemoclaw"; + const provider = await input.sandbox.openshell( + ["provider", "get", "-g", gateway, receipt.providerName], + { ...options, artifactName: "phase-3-native-custom-provider-metadata" }, + ); + const attachments = await input.sandbox.openshell( + ["sandbox", "provider", "list", "-g", gateway, input.sandboxName], + { ...options, artifactName: "phase-3-native-custom-provider-attachment" }, + ); + const metadata = + provider.exitCode === 0 ? parseCliOpenShellProviderMetadata(provider.stdout) : null; + const route = getSandboxInferenceConfig( + input.model, + input.logicalProvider, + receipt.custom.api, + true, + receipt.endpointUrl, + ); + // Inspect the selected agent's real configuration inside the sandbox. + // Keep credential references out of retained command output. + const agent = await input.sandbox.exec( + input.sandboxName, + [ + "node", + "-e", + [ + 'const config = JSON.parse(require("node:fs").readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', + 'const assert = require("node:assert/strict");', + "const expected = JSON.parse(process.argv[1]);", + "const provider = config.models?.providers?.[expected.providerKey];", + 'assert.equal(config.agents?.defaults?.model?.primary, expected.primaryModelRef, "selected model mismatch");', + 'assert.equal(provider?.baseUrl, expected.endpoint, "selected endpoint mismatch");', + 'assert.equal(provider?.api, expected.api, "selected API mismatch");', + 'assert.ok(provider?.models?.some(model => model.id === expected.model), "selected model is absent");', + "const handle = process.env[expected.credentialEnv];", + 'assert.ok(new RegExp("^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_" + expected.credentialEnv + "$").test(handle ?? "") && provider?.apiKey === handle, "selected credential reference mismatch");', + 'process.stdout.write("selected agent route verified");', + ].join(" "), + JSON.stringify({ + providerKey: route.providerKey, + primaryModelRef: route.primaryModelRef, + endpoint: route.inferenceBaseUrl, + api: route.inferenceApi, + model: input.model, + credentialEnv: definition.credentialEnv, + }), + ], + { ...options, artifactName: "phase-3-native-custom-agent-route" }, + ); + const ok = + metadata?.name === receipt.providerName && + metadata.type === receipt.profileId && + metadata.revision?.id === receipt.providerId && + metadata.configKeys.length === 0 && + metadata.credentialKeys.length === 1 && + metadata.credentialKeys[0] === definition.credentialEnv && + attachments.exitCode === 0 && + attachments.stdout.split(/\s+/u).includes(receipt.providerName) && + agent.exitCode === 0 && + agent.stdout === "selected agent route verified"; + return { + ok, + detail: `Custom native provider ownership, attachment and selected agent route: ${ok ? "verified" : "mismatch"}`, + }; + } + const native = await readPublicNvidiaSwitchAttachmentEvidence({ + artifactName: "phase-3-native-nvidia-provider-attachment", + env: input.env, + logicalProvider: input.logicalProvider, + receipt: input.entry?.nativeNvidiaProviderAttachment, + sandbox: input.sandbox, + sandboxName: input.sandboxName, + }); + if (native !== null) + return { ok: native === PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, detail: native }; + const route = await input.sandbox.openshell(["inference", "get"], { + artifactName: "phase-3-openshell-inference-get", + env: input.env, + timeoutMs: 60_000, + }); + return { ok: route.exitCode === 0 && route.stdout.includes(input.model), detail: route.stdout }; +} diff --git a/test/e2e/live/full-e2e-native-model.ts b/test/e2e/live/full-e2e-native-model.ts index 01c4eef8b6d..73f939cc2a9 100644 --- a/test/e2e/live/full-e2e-native-model.ts +++ b/test/e2e/live/full-e2e-native-model.ts @@ -26,7 +26,12 @@ export async function withNativeModelCleanup( // The preceding sandbox inference turn qualifies this model and route. A new // provider name makes a gateway that ignores the native edit distinguishable. -export function buildNativeModelRestartFixture(model: string, logicalProvider?: string) { +export function buildNativeModelRestartFixture( + model: string, + logicalProvider?: string, + endpointUrl?: string, +) { + const nativeCustom = logicalProvider === "compatible-endpoint" && endpointUrl; const nativeNvidia = logicalProvider === NVIDIA_HOSTED_LOGICAL_PROVIDER; const provider = `nemoclaw-e2e-native-${randomUUID()}`; const primary = `${provider}/${model}`; @@ -38,8 +43,16 @@ export function buildNativeModelRestartFixture(model: string, logicalProvider?: models: { providers: { [provider]: { - baseUrl: nativeNvidia ? NVIDIA_HOSTED_NATIVE_ENDPOINT : "https://inference.local/v1", - apiKey: nativeNvidia ? "${NVIDIA_INFERENCE_API_KEY}" : "unused", + baseUrl: nativeCustom + ? endpointUrl + : nativeNvidia + ? NVIDIA_HOSTED_NATIVE_ENDPOINT + : "https://inference.local/v1", + apiKey: nativeCustom + ? "${COMPATIBLE_API_KEY}" + : nativeNvidia + ? "${NVIDIA_INFERENCE_API_KEY}" + : "unused", api: "openai-completions", models: [{ id: model, name: model }], }, diff --git a/test/e2e/live/full-e2e.test.ts b/test/e2e/live/full-e2e.test.ts index 1a2ec62b668..f6453c33e8f 100644 --- a/test/e2e/live/full-e2e.test.ts +++ b/test/e2e/live/full-e2e.test.ts @@ -3,6 +3,7 @@ import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; import fs from "node:fs"; +import { buildSandboxInferenceChatCommand } from "../fixtures/inference-adapter.ts"; import os from "node:os"; import path from "node:path"; import { shellQuote } from "../../../src/lib/core/shell-quote.ts"; @@ -47,7 +48,7 @@ import { } from "../fixtures/openclaw-agent-output.ts"; import { buildOpenClawFirstTurnLatencyEvidence } from "./agent-turn-latency-helpers.ts"; import { - buildFullE2eSandboxInferenceCommand, + readFullE2eInferenceRoute, FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES, fullE2eInferenceProbeEvidence, runFullE2eInferenceProbe, @@ -72,10 +73,6 @@ import { agentReplyContainsToken, parseOpenClawGatewayModelRun, } from "./openclaw-inference-switch-helpers.ts"; -import { - PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, - readPublicNvidiaSwitchAttachmentEvidence, -} from "./public-nvidia-switch-provider.ts"; import { createCliOpenShellGatewayReuseObserver } from "../../../src/lib/adapters/openshell/gateway-reuse-cli.ts"; import type { OpenShellGatewayReuseObservation } from "../../../src/lib/adapters/openshell/gateway-reuse.ts"; @@ -439,6 +436,7 @@ async function runOpenClawLaunchTurns(input: { host: HostCliClient; model: string; logicalProvider: string; + endpointUrl?: string; redactionValues: string[]; sandbox: SandboxClient; }): Promise { @@ -479,7 +477,11 @@ sha256sum /sandbox/.bashrc /sandbox/.profile > /tmp/nemoclaw-e2e-profiles.sha256 timeoutMs: 30_000, }, ); - const nativeModel = buildNativeModelRestartFixture(input.model, input.logicalProvider); + const nativeModel = buildNativeModelRestartFixture( + input.model, + input.logicalProvider, + input.endpointUrl, + ); const editNativeModel = await input.sandbox.exec( SANDBOX_NAME, ["/usr/bin/env", "HOME=/sandbox", "/usr/local/bin/openclaw", "config", "patch", "--stdin"], @@ -1210,30 +1212,17 @@ test( }, ); - const nativeAttachment = await readPublicNvidiaSwitchAttachmentEvidence({ - artifactName: "phase-3-native-nvidia-provider-attachment", - env: env(), - logicalProvider: hosted.providerName, - receipt: getSandbox(SANDBOX_NAME)?.nativeNvidiaProviderAttachment, + const nativeEndpointUrl = getSandbox(SANDBOX_NAME)?.nativeHostedProviderAttachment?.endpointUrl; + const inferenceRoute = await readFullE2eInferenceRoute({ sandbox, sandboxName: SANDBOX_NAME, + entry: getSandbox(SANDBOX_NAME), + logicalProvider: hosted.providerName, + model: hosted.model, + env: env(), + redactionValues, }); - const inference = - nativeAttachment === null - ? await sandbox.openshell(["inference", "get"], { - artifactName: "phase-3-openshell-inference-get", - env: env(), - timeoutMs: 60_000, - }) - : null; - expect( - inference !== null - ? inference.exitCode === 0 && resultText(inference).includes(hosted.model) - : nativeAttachment === PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, - inference !== null - ? resultText(inference) - : (nativeAttachment ?? "missing native attachment"), - ).toBe(true); + expect(inferenceRoute.ok, inferenceRoute.detail).toBe(true); const policy = await sandbox.openshell(["policy", "get", "--full", SANDBOX_NAME], { artifactName: "phase-3-openshell-policy-get", @@ -1266,7 +1255,11 @@ test( run: (availabilityAttempt) => sandbox.exec( SANDBOX_NAME, - buildFullE2eSandboxInferenceCommand(attempt.requestBody, hosted.providerName), + buildSandboxInferenceChatCommand( + attempt.requestBody, + hosted.providerName, + nativeEndpointUrl, + ), { artifactName: `${attempt.artifactName}-availability-${availabilityAttempt}`, captureLimitBytes: FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES, @@ -1316,6 +1309,7 @@ test( host, model: hosted.model, logicalProvider: hosted.providerName, + endpointUrl: nativeEndpointUrl, redactionValues, sandbox, }) @@ -1403,7 +1397,11 @@ test( run: (availabilityAttempt) => sandbox.exec( SANDBOX_NAME, - buildFullE2eSandboxInferenceCommand(attempt.requestBody, hosted.providerName), + buildSandboxInferenceChatCommand( + attempt.requestBody, + hosted.providerName, + nativeEndpointUrl, + ), { artifactName: `retained-${attempt.artifactName}-availability-${availabilityAttempt}`, captureLimitBytes: FULL_E2E_INFERENCE_CAPTURE_LIMIT_BYTES, diff --git a/test/e2e/live/hermes-e2e.test.ts b/test/e2e/live/hermes-e2e.test.ts index f4b240216a5..6e48d9c0274 100644 --- a/test/e2e/live/hermes-e2e.test.ts +++ b/test/e2e/live/hermes-e2e.test.ts @@ -5,6 +5,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; +import type { SandboxEntry } from "../../../src/lib/state/registry/types.ts"; +import { recordedNativeProviderAttachment } from "../../../src/lib/inference/native-provider/recorded-selection.ts"; +import { buildSandboxInferenceChatCommand } from "../fixtures/inference-adapter.ts"; import { HERMES_E2E_TEST_TIMEOUT_MS } from "../../../tools/e2e/hermes-timeout-contract.mts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; @@ -873,21 +876,17 @@ test( ).toBe(false); expectPong(`${inference.mode} direct chat`, directChat); + const chatSelection = registryEntry(SANDBOX_NAME) as unknown as SandboxEntry; + const chatAttachment = recordedNativeProviderAttachment(chatSelection); const sandboxChat = await sandbox.exec( SANDBOX_NAME, - [ - "curl", - "-fsS", - "--max-time", - "90", - "-H", - "Content-Type: application/json", - "--data-raw", + buildSandboxInferenceChatCommand( chatPayload(inference.model, "Reply with exactly one word: PONG", 1024), - "https://inference.local/v1/chat/completions", - ], + chatSelection.provider!, + chatAttachment?.endpointUrl, + ), { - artifactName: "phase-5-inference-local-chat", + artifactName: "phase-5-selected-route-chat", env: commandEnv(), timeoutMs: 120_000, }, @@ -895,7 +894,7 @@ test( expect(sandboxChat.exitCode, resultText(sandboxChat)).toBe(0); const sandboxChatJson = JSON.parse(sandboxChat.stdout) as unknown; expect(exhaustedReasoningBudget(sandboxChatJson)).toBe(false); - expectPong("Hermes sandbox inference.local chat", sandboxChatJson); + expectPong("Hermes sandbox selected-route chat", sandboxChatJson); progress.phase("read logs and validate Hermes configuration integrity"); // Phase 6: host CLI diagnostics and configuration integrity. diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts index a8fd0acb24a..9a6aaf87226 100644 --- a/test/e2e/live/openclaw-inference-switch-helpers.ts +++ b/test/e2e/live/openclaw-inference-switch-helpers.ts @@ -158,13 +158,14 @@ export const MOCK_BASELINE_MODEL = "openclaw-switch-baseline-model"; export function startMockOpenClawBaselineProvider( progress: FakeOpenAiCompatibleServerOptions["progress"], + publicHost = "host.openshell.internal", ) { return startFakeOpenAiCompatibleServer({ apiKey: MOCK_BASELINE_API_KEY, chatContent: "PONG", host: "0.0.0.0", model: MOCK_BASELINE_MODEL, - publicHost: "host.openshell.internal", + publicHost, progress, requireAuth: true, }); @@ -213,23 +214,25 @@ export async function readOpenClawConfig( timeoutMs: number; artifactName: string; nativeNvidia?: boolean; + nativeCustomApi?: string; }, ): Promise { return sandbox.exec( sandboxName, - options.nativeNvidia + options.nativeNvidia || options.nativeCustomApi ? [ "node", "-e", [ 'const fs = require("node:fs");', 'const config = JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', - "const provider = config.models?.providers?.inference;", + `const provider = config.models?.providers?.${options.nativeCustomApi === "anthropic-messages" ? "anthropic" : "inference"};`, // A fresh exec receives the newly attached provider handle. Keep // both values inside the sandbox because ShellProbe redacts the // credential-shaped config field before returning stdout. - "const handle = process.env.NVIDIA_INFERENCE_API_KEY;", - 'require("node:assert/strict").ok(/^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$/.test(handle ?? "") && provider?.apiKey === handle, "native credential reference mismatch");', + `const credentialEnv = ${JSON.stringify(options.nativeCustomApi ? (options.nativeCustomApi === "anthropic-messages" ? "COMPATIBLE_ANTHROPIC_API_KEY" : "COMPATIBLE_API_KEY") : "NVIDIA_INFERENCE_API_KEY")};`, + "const handle = process.env[credentialEnv];", + 'require("node:assert/strict").ok(new RegExp("^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_" + credentialEnv + "$").test(handle ?? "") && provider?.apiKey === handle, "native credential reference mismatch");', "delete provider.apiKey;", "process.stdout.write(JSON.stringify(config));", ].join(" "), diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index bca85809f7a..7e3a6c738cb 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -17,6 +17,8 @@ import os from "node:os"; import path from "node:path"; import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts"; +import { nativeHostedAuthHeaderScript } from "../../../src/lib/inference/native-provider/contract.ts"; +import { discoverHostAddress } from "../fixtures/host-address.ts"; import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; @@ -76,6 +78,7 @@ const SWITCH_PROVIDER = process.env.NEMOCLAW_SWITCH_PROVIDER ?? PUBLIC_NVIDIA_SW 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 SWITCH_MOCK_ANTHROPIC = process.env.NEMOCLAW_SWITCH_MOCK_ANTHROPIC ?? "0"; +const SWITCH_NATIVE_CUSTOM = process.env.NEMOCLAW_SWITCH_NATIVE_CUSTOM === "1"; const SWITCH_MOCK_PORT = parsePortEnv("NEMOCLAW_SWITCH_MOCK_PORT", 0); const TEST_TIMEOUT_MS = testTimeout(75 * 60_000); const INSTALL_TIMEOUT_MS = execTimeout(30 * 60_000); @@ -168,7 +171,7 @@ interface MockAnthropicRequest { } function proveMockBaselineAuthentication( - baseline: Pick | undefined, + baseline: Pick | undefined, sandbox: SandboxClient, home: string, artifacts: { writeJson(path: string, value: unknown): Promise }, @@ -179,7 +182,7 @@ function proveMockBaselineAuthentication( } async function proveSelectedMockBaselineAuthentication( - baseline: Pick, + baseline: Pick, sandbox: SandboxClient, home: string, artifacts: { writeJson(path: string, value: unknown): Promise }, @@ -196,7 +199,9 @@ async function proveSelectedMockBaselineAuthentication( const probe = await sandboxShell( sandbox, home, - `curl -fsS --max-time 60 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null`, + SWITCH_NATIVE_CUSTOM + ? `${nativeHostedAuthHeaderScript({ credentialEnv: "COMPATIBLE_API_KEY", api: "openai-completions" })}; curl -fsS --max-time 60 ${shellQuote(`${baseline.baseUrl}/chat/completions`)} -H "$AUTH_HEADER" -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null` + : `curl -fsS --max-time 60 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data ${shellQuote(JSON.stringify(payload))} >/dev/null`, { artifactName: "baseline-explicit-authenticated-inference-post", timeoutMs: 90_000, @@ -388,7 +393,12 @@ function closeServer(server: Server): Promise { }); } -async function startMockAnthropicProvider(): Promise { +async function startMockAnthropicProvider(host: HostCliClient): Promise { + const nativeHost = SWITCH_NATIVE_CUSTOM + ? (await discoverHostAddress(host, "native-anthropic-endpoint-address")).address + : undefined; + let binding: CompatibleAnthropicSwitchBinding; + const requests: MockAnthropicRequest[] = []; const server = http.createServer((req, res) => { const url = new URL(req.url ?? "/", "http://mock.local"); @@ -403,8 +413,13 @@ async function startMockAnthropicProvider(): Promise { jsonResponse(res, 200, { data: [{ id: "mock-anthropic-model" }] }); return; } - if (req.method !== "POST" || url.pathname !== "/v1/messages") { - jsonResponse(res, 404, { error: "not found", path: url.pathname }); + const invalidCredential = + SWITCH_NATIVE_CUSTOM && req.headers["x-api-key"] !== binding.credentialValue; + if (req.method !== "POST" || url.pathname !== "/v1/messages" || invalidCredential) { + jsonResponse(res, invalidCredential ? 401 : 404, { + error: "request rejected", + path: url.pathname, + }); return; } @@ -495,8 +510,12 @@ async function startMockAnthropicProvider(): Promise { throw new Error("mock Anthropic provider did not expose a TCP port"); } const port = (address as AddressInfo).port; + const endpointUrl = nativeHost + ? `http://${nativeHost}:${port}` + : compatibleAnthropicMockEndpointUrl(port); + binding = compatibleAnthropicSwitchBinding(endpointUrl); return { - endpointUrl: compatibleAnthropicMockEndpointUrl(port), + endpointUrl, requests: () => requests, close: () => closeServer(server), }; @@ -610,10 +629,12 @@ async function readAndAssertOpenClawConfig( inferenceApi: string; artifactName: string; nativeNvidia?: boolean; + nativeCustomEndpoint?: string; }, ): Promise { const configResult = await readOpenClawConfig(sandbox, SANDBOX_NAME, { nativeNvidia: expected.nativeNvidia, + nativeCustomApi: expected.nativeCustomEndpoint ? expected.inferenceApi : undefined, artifactName: expected.artifactName, env: commandEnv(home), timeoutMs: COMMAND_TIMEOUT_MS, @@ -628,13 +649,16 @@ async function readAndAssertOpenClawConfig( expect(config.agents?.defaults?.model?.primary).toBe(expectedPrimary); expect(provider?.baseUrl).toBe( - expected.nativeNvidia - ? NVIDIA_HOSTED_NATIVE_ENDPOINT - : expected.inferenceApi === "anthropic-messages" - ? "https://inference.local" - : "https://inference.local/v1", + expected.nativeCustomEndpoint ?? + (expected.nativeNvidia + ? NVIDIA_HOSTED_NATIVE_ENDPOINT + : expected.inferenceApi === "anthropic-messages" + ? "https://inference.local" + : "https://inference.local/v1"), + ); + expect(provider?.apiKey).toBe( + expected.nativeNvidia || expected.nativeCustomEndpoint ? undefined : "unused", ); - expect(provider?.apiKey).toBe(expected.nativeNvidia ? undefined : "unused"); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; @@ -648,6 +672,7 @@ async function assertOpenClawConfig( inferenceApi: string; artifactName: string; nativeNvidia?: boolean; + nativeCustomEndpoint?: string; }, ): Promise { const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); @@ -666,6 +691,7 @@ async function assertInitialOpenClawConfig( inferenceApi: string; artifactName: string; nativeNvidia?: boolean; + nativeCustomEndpoint?: string; }, ): Promise { const selectedModel = await readAndAssertOpenClawConfig(sandbox, home, expected); @@ -719,6 +745,7 @@ async function checkSandboxInference( sandbox: SandboxClient, artifacts: ArtifactSink, home: string, + nativeCustomEndpoint?: string, ): Promise<"ok" | { skipped: string }> { const payload = SWITCH_INFERENCE_API === "anthropic-messages" @@ -733,17 +760,25 @@ async function checkSandboxInference( max_tokens: 100, }; const payloadB64 = Buffer.from(JSON.stringify(payload), "utf8").toString("base64"); - const curlCommand = - SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER + const curlCommand = nativeCustomEndpoint + ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 ${shellQuote(`${nativeCustomEndpoint}/v1/messages`)} -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -H "$AUTH_HEADER" --data-binary @/tmp/nemoclaw-switch-payload.json` + : SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 ${NVIDIA_HOSTED_NATIVE_ENDPOINT}/chat/completions -H 'Content-Type: application/json' -H "$AUTH_HEADER" --data-binary @/tmp/nemoclaw-switch-payload.json` : SWITCH_INFERENCE_API === "anthropic-messages" ? `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/messages -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' --data-binary @/tmp/nemoclaw-switch-payload.json` : `curl -sS -o "$tmp" -w '%{http_code}' --max-time 90 https://inference.local/v1/chat/completions -H 'Content-Type: application/json' --data-binary @/tmp/nemoclaw-switch-payload.json`; const script = [ "set -u", - ...(SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? [NATIVE_NVIDIA_AUTH_HEADER_SCRIPT] - : []), + ...(nativeCustomEndpoint + ? [ + nativeHostedAuthHeaderScript({ + credentialEnv: "COMPATIBLE_ANTHROPIC_API_KEY", + api: "anthropic-messages", + }), + ] + : 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", @@ -962,6 +997,7 @@ exit "$rc" } async function runInitialRouteLifecycle(options: { + nativeCustomEndpoint?: string; artifacts: ArtifactSink; baselineProvider?: Pick; home: string; @@ -976,6 +1012,7 @@ async function runInitialRouteLifecycle(options: { model: options.model, inferenceApi: "openai-completions", artifactName: `read-openclaw-initial-route-${artifactSuffix}`, + nativeCustomEndpoint: options.nativeCustomEndpoint, }); await checkOpenClawGatewayInference( options.host, @@ -1080,6 +1117,12 @@ async function runOpenClawInferenceSetWithRetry( artifactName: `nemoclaw-inference-set-${attempt}`, env: { ...compatibleAnthropicSwitchEnv(switchBinding), + ...(SWITCH_NATIVE_CUSTOM && switchBinding + ? { + NEMOCLAW_TRUSTED_PRIVATE_INFERENCE_HOSTS: new URL(switchBinding.endpointUrl) + .hostname, + } + : {}), ...(publicNvidiaApiKey ? { NVIDIA_INFERENCE_API_KEY: publicNvidiaApiKey } : {}), }, redactionValues, @@ -1153,8 +1196,11 @@ test( (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 nativeBaselineHost = SWITCH_NATIVE_CUSTOM + ? (await discoverHostAddress(host, "native-baseline-endpoint-address")).address + : undefined; const baselineProvider: FakeOpenAiCompatibleServer | undefined = useMockBaseline - ? await startMockOpenClawBaselineProvider(progress) + ? await startMockOpenClawBaselineProvider(progress, nativeBaselineHost) : undefined; cleanup.trackDisposable("close baseline inference provider", async () => { await baselineProvider?.close(); @@ -1209,6 +1255,9 @@ test( artifactName: "onboard-custom-image-openclaw-inference-switch", env: commandEnv(home, { ...baseline.env, + ...(nativeBaselineHost + ? { NEMOCLAW_TRUSTED_PRIVATE_INFERENCE_HOSTS: nativeBaselineHost } + : {}), NEMOCLAW_RECREATE_SANDBOX: "1", }), redactionValues, @@ -1243,6 +1292,7 @@ test( false, ); await runInitialRouteLifecycle({ + nativeCustomEndpoint: nativeBaselineHost ? baseline.endpointUrl : undefined, artifacts, baselineProvider, home, @@ -1255,7 +1305,7 @@ test( progress.phase("prepare the switched provider and endpoint"); if (SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1") { - mockProvider = await startMockAnthropicProvider(); + mockProvider = await startMockAnthropicProvider(host); await artifacts.writeJson("mock-anthropic-provider.json", { endpointUrl: mockProvider.endpointUrl, }); @@ -1322,11 +1372,17 @@ test( inferenceApi: SWITCH_INFERENCE_API, artifactName: "read-openclaw-config-after-inference-switch", nativeNvidia: SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER, + nativeCustomEndpoint: SWITCH_NATIVE_CUSTOM ? switchBinding!.endpointUrl : undefined, }); await assertRegistryAndSession(home, { mockProvider, sandbox }); progress.phase("prove sandbox and OpenClaw gateway inference"); - const inference = await checkSandboxInference(sandbox, artifacts, home); + const inference = await checkSandboxInference( + sandbox, + artifacts, + home, + SWITCH_NATIVE_CUSTOM ? switchBinding!.endpointUrl : undefined, + ); if (inference !== "ok") { await artifacts.target.complete({ id: "openclaw-inference-switch", diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 357ecc8c03e..ba0c41505a2 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -490,6 +490,7 @@ "test/e2e/fixtures/admin-approval-connect.sh" ], "fast": [ + "src/lib/inference/native-provider/custom.test.ts", "test/e2e/support/bedrock-runtime-compatible-anthropic-leaks.test.ts", "test/e2e/support/bedrock-runtime-compatible-anthropic-progress.test.ts", "test/e2e/support/e2e-cleanup-resources.test.ts", diff --git a/test/e2e/support/full-e2e-inference-probe.test.ts b/test/e2e/support/full-e2e-inference-probe.test.ts index 8340bda5f59..2a47f4ed600 100644 --- a/test/e2e/support/full-e2e-inference-probe.test.ts +++ b/test/e2e/support/full-e2e-inference-probe.test.ts @@ -4,12 +4,17 @@ import { describe, expect, it, vi } from "vitest"; import { execFileSync, spawnSync } from "node:child_process"; import fs from "node:fs"; +import { buildSandboxInferenceChatCommand } from "../fixtures/inference-adapter.ts"; import os from "node:os"; import path from "node:path"; +import assert from "node:assert/strict"; +import { runInNewContext } from "node:vm"; +import { customNativeProvider } from "../../../src/lib/inference/native-provider/custom.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { buildFullE2eInferenceRequest, - buildFullE2eSandboxInferenceCommand, + readFullE2eInferenceRoute, FULL_E2E_INFERENCE_EVIDENCE_LIMIT_BYTES, type FullE2eInferenceAttemptInput, fullE2eInferenceProbeEvidence, @@ -32,35 +37,150 @@ function completion(content: string, finishReason = "stop"): string { }); } +it.each([ + ["owned-id", "none", true], + ["different-id", "none", false], + ["owned-id", "endpoint", false], + ["owned-id", "api", false], + ["owned-id", "credential", false], + ["owned-id", "model", false], +] as const)( + "checks custom native provider identity %s and agent drift %s on the recorded gateway", + async (observedId, drift, expected) => { + const definition = customNativeProvider({ + provider: "compatible-endpoint", + endpointUrl: "https://custom.example/v1", + api: "openai-completions", + credentialEnv: "SOURCE_KEY", + allowedIps: ["8.8.8.8"], + }); + const openshell = vi + .fn() + .mockResolvedValueOnce({ + exitCode: 0, + stdout: [ + `Name: ${definition.providerName}`, + `Id: ${observedId}`, + `Type: ${definition.profileId}`, + "Resource version: 1", + "Credential keys: COMPATIBLE_API_KEY", + "Config keys: ", + ].join("\n"), + }) + .mockResolvedValueOnce({ exitCode: 0, stdout: definition.providerName }); + const handle = "openshell:resolve:env:v3_COMPATIBLE_API_KEY"; + const config = { + agents: { + defaults: { + model: { primary: drift === "model" ? "inference/other" : "inference/selected-model" }, + }, + }, + models: { + providers: { + inference: { + baseUrl: drift === "endpoint" ? "https://wrong.example/v1" : definition.endpoint, + api: drift === "api" ? "openai-responses" : definition.api, + apiKey: drift === "credential" ? "raw-secret" : handle, + models: [{ id: "selected-model" }], + }, + }, + }, + }; + const exec = vi.fn(async (_name, command) => { + let stdout = ""; + try { + runInNewContext(command[2], { + require: (name: string) => + name === "node:fs" ? { readFileSync: () => JSON.stringify(config) } : assert, + process: { + argv: ["node", command[3]], + env: { COMPATIBLE_API_KEY: handle }, + stdout: { + write: (value: string) => { + stdout += value; + }, + }, + }, + }); + return { exitCode: 0, stdout }; + } catch { + return { exitCode: 1, stdout }; + } + }); + const result = await readFullE2eInferenceRoute({ + sandbox: { openshell, exec } as unknown as SandboxClient, + sandboxName: "alpha", + logicalProvider: definition.logicalProvider, + model: "selected-model", + env: {}, + redactionValues: ["synthetic-key"], + entry: { + name: "alpha", + gatewayName: "recorded-gateway", + nativeHostedProviderAttachment: { + schemaVersion: 1, + profileId: definition.profileId, + providerName: definition.providerName, + providerId: "owned-id", + endpointUrl: definition.endpointUrl, + allowedIps: definition.allowedIps, + custom: definition.custom, + }, + }, + }); + expect(result.ok).toBe(expected); + expect(exec).toHaveBeenCalledExactlyOnceWith( + "alpha", + expect.any(Array), + expect.objectContaining({ artifactName: "phase-3-native-custom-agent-route" }), + ); + expect(openshell.mock.calls.map(([args]) => args)).toEqual([ + ["provider", "get", "-g", "recorded-gateway", definition.providerName], + ["sandbox", "provider", "list", "-g", "recorded-gateway", "alpha"], + ]); + expect(openshell).toHaveBeenNthCalledWith( + 1, + expect.any(Array), + expect.objectContaining({ redactionValues: ["synthetic-key"], captureLimitBytes: 16 * 1024 }), + ); + }, +); + describe("full E2E sandbox inference probe", () => { - it("uses the sandbox's native NVIDIA handle and preserves the request as data", () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), "full-e2e-native-probe-")); - try { - fs.writeFileSync(path.join(directory, "curl"), '#!/bin/sh\nprintf "%s\\n" "$@"\n', { - mode: 0o700, - }); - const body = JSON.stringify({ prompt: 'literal $(exit 99) "quote"' }); - const [command, ...args] = buildFullE2eSandboxInferenceCommand(body, "nvidia-prod"); - const handle = "openshell:resolve:env:v3_NVIDIA_INFERENCE_API_KEY"; - const env = { PATH: `${directory}:/usr/bin:/bin`, NVIDIA_INFERENCE_API_KEY: handle }; - const result = execFileSync(command, args, { env, encoding: "utf8" }); - expect(result.split("\n")).toEqual([ - "-fsS", - "--max-time", - "90", - "https://integrate.api.nvidia.com/v1/chat/completions", - "-H", - "Content-Type: application/json", - "-H", - `Authorization: Bearer ${handle}`, - "--data-raw", - body, - "", - ]); - } finally { - fs.rmSync(directory, { recursive: true, force: true }); - } - }); + it.each([ + ["nvidia-prod", "NVIDIA_INFERENCE_API_KEY", "https://integrate.api.nvidia.com/v1"], + ["compatible-endpoint", "COMPATIBLE_API_KEY", "https://custom.example/team/v1"], + ])( + "uses the sandbox native %s handle and preserves the request as data", + (provider, credentialEnv, endpointUrl) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "full-e2e-native-probe-")); + try { + fs.writeFileSync(path.join(directory, "curl"), '#!/bin/sh\nprintf "%s\\n" "$@"\n', { + mode: 0o700, + }); + const body = JSON.stringify({ prompt: 'literal $(exit 99) "quote"' }); + const [command, ...args] = buildSandboxInferenceChatCommand(body, provider, endpointUrl); + const handle = `openshell:resolve:env:v3_${credentialEnv}`; + const env = { PATH: `${directory}:/usr/bin:/bin`, [credentialEnv]: handle }; + const result = execFileSync(command, args, { env, encoding: "utf8" }); + expect(result.split("\n")).toEqual([ + "-fsS", + "--max-time", + "90", + `${endpointUrl}/chat/completions`, + "-H", + "Content-Type: application/json", + "-H", + `Authorization: Bearer ${handle}`, + "--data-raw", + body, + "", + ]); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); it.each(["", "nvapi-raw-key", "$(exit 99)"])( "rejects the invalid native credential %j before invoking curl", @@ -75,7 +195,7 @@ describe("full E2E sandbox inference probe", () => { mode: 0o700, }, ); - const [, ...args] = buildFullE2eSandboxInferenceCommand("{}", "nvidia-prod"); + const [, ...args] = buildSandboxInferenceChatCommand("{}", "nvidia-prod"); const denied = spawnSync("/bin/bash", args, { env: { PATH: `${directory}:/usr/bin:/bin`, @@ -95,7 +215,7 @@ describe("full E2E sandbox inference probe", () => { ); it("retains the credential-free local probe for a compatible provider", () => { - expect(buildFullE2eSandboxInferenceCommand("{}", "compatible-endpoint")).toEqual([ + expect(buildSandboxInferenceChatCommand("{}", "compatible-endpoint")).toEqual([ "curl", "-fsS", "--max-time", diff --git a/test/e2e/support/full-e2e-native-model.test.ts b/test/e2e/support/full-e2e-native-model.test.ts index 56097d6afef..252a9a12334 100644 --- a/test/e2e/support/full-e2e-native-model.test.ts +++ b/test/e2e/support/full-e2e-native-model.test.ts @@ -98,3 +98,17 @@ it("reports the last cleanup failure when verification and both cleanup steps fa withNativeModelCleanup(fail(errors[0]), fail(errors[1]), fail(errors[2])), ).rejects.toBe(errors[2]); }); + +it("retains a custom native endpoint and opaque credential reference through a model edit", () => { + const fixture = buildNativeModelRestartFixture( + "team/model", + "compatible-endpoint", + "https://custom.example/team/v1", + ); + expect(JSON.parse(fixture.patch).models.providers[fixture.provider]).toMatchObject({ + baseUrl: "https://custom.example/team/v1", + apiKey: "${COMPATIBLE_API_KEY}", + api: "openai-completions", + models: [{ id: "team/model", name: "team/model" }], + }); +}); diff --git a/test/e2e/support/hermes-config-export-live.test.ts b/test/e2e/support/hermes-config-export-live.test.ts index 9941407dd28..d566df80f1b 100644 --- a/test/e2e/support/hermes-config-export-live.test.ts +++ b/test/e2e/support/hermes-config-export-live.test.ts @@ -452,62 +452,71 @@ describe("Hermes config export live evidence", () => { }, ); - it("accepts messaging refusal alongside other unsupported export findings", async () => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - gatewayName: "nemoclaw", - messaging: { schemaVersion: 1, plan: { channels: [] } }, - workload: { kind: "managed-image", reference: IMAGE_REF }, + it.each(["unsupported", "unsupported, policy-not-representable"])( + "accepts messaging refusal with %s export findings", + async (categories) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + gatewayName: "nemoclaw", + messaging: { schemaVersion: 1, plan: { channels: [] } }, + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, }, - }, - }); - mocks.command.mockResolvedValue({ - exitCode: 2, - stdout: "", - stderr: [ - "Config export failed (unsupported).", - "V1 export does not support messaging.", - "The sandbox provider attachments do not match its supported configuration.", - "The managed startup profile is not the canonical profile supported by v1 export.", - ].join("\n"), - }); + }); + mocks.command.mockResolvedValue({ + exitCode: 2, + stdout: "", + stderr: [ + `Config export failed (${categories}).`, + "V1 export does not support messaging.", + "The sandbox provider attachments do not match its supported configuration.", + "The managed startup profile is not the canonical profile supported by v1 export.", + ].join("\n"), + }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); - expect(mocks.writeJson).toHaveBeenCalledWith( - "hermes-config-export-live-evidence.json", - expect.objectContaining({ - refusalCategory: "unsupported", - refusalDiagnosticMatches: true, - }), - ); - }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: true }); + expect(mocks.writeJson).toHaveBeenCalledWith( + "hermes-config-export-live-evidence.json", + expect.objectContaining({ + refusalCategory: "unsupported", + refusalDiagnosticMatches: true, + }), + ); + }, + ); - it("rejects other unsupported findings without the messaging refusal", async () => { - mocks.load.mockReturnValue({ - sandboxes: { - hermes: { - credentialEnv: "NVIDIA_API_KEY", - endpointUrl: "https://integrate.api.nvidia.com/v1", - gatewayName: "nemoclaw", - messaging: { schemaVersion: 1, plan: { channels: [] } }, - workload: { kind: "managed-image", reference: IMAGE_REF }, + it.each([ + { + categories: "unsupported", + refusal: "The sandbox provider attachments do not match its supported configuration.", + }, + { categories: "policy-not-representable", refusal: "V1 export does not support messaging." }, + ])( + "rejects messaging export evidence missing the expected category or refusal ($categories)", + async ({ categories, refusal }) => { + mocks.load.mockReturnValue({ + sandboxes: { + hermes: { + credentialEnv: "NVIDIA_API_KEY", + endpointUrl: "https://integrate.api.nvidia.com/v1", + gatewayName: "nemoclaw", + messaging: { schemaVersion: 1, plan: { channels: [] } }, + workload: { kind: "managed-image", reference: IMAGE_REF }, + }, }, - }, - }); - mocks.command.mockResolvedValue({ - exitCode: 2, - stdout: "", - stderr: [ - "Config export failed (unsupported).", - "The sandbox provider attachments do not match its supported configuration.", - ].join("\n"), - }); + }); + mocks.command.mockResolvedValue({ + exitCode: 2, + stdout: "", + stderr: [`Config export failed (${categories}).`, refusal].join("\n"), + }); - await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: false }); - }); + await expect(runEnabledFixture()).resolves.toEqual({ checked: true, passed: false }); + }, + ); it.each(["http", "https"])("accepts the exact Podman %s export refusal", async (scheme) => { mocks.load.mockReturnValue({ diff --git a/test/e2e/support/inference-adapter.test.ts b/test/e2e/support/inference-adapter.test.ts index 9a03ba91016..83b9fe2c10f 100644 --- a/test/e2e/support/inference-adapter.test.ts +++ b/test/e2e/support/inference-adapter.test.ts @@ -21,6 +21,18 @@ import { } from "../fixtures/inference-adapter.ts"; import { startTestProgress } from "../fixtures/progress.ts"; +// Protected image qualification imports the fixture before CLI artifacts exist. +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + const readFileSync = new Proxy(actual.readFileSync, { + apply(target, thisArg, args) { + expect(String(args[0])).not.toMatch(/\/dist\/managed-inference\/catalog\.json$/u); + return Reflect.apply(target, thisArg, args); + }, + }); + return { ...actual, readFileSync, default: { ...actual, readFileSync } }; +}); + const adapters: E2EInferenceAdapter[] = []; const NOOP_PROGRESS = startTestProgress( "inference adapter support", diff --git a/test/e2e/support/inference-switch-workflow-boundary.test.ts b/test/e2e/support/inference-switch-workflow-boundary.test.ts index 0bdd99864b2..5aca04a077b 100644 --- a/test/e2e/support/inference-switch-workflow-boundary.test.ts +++ b/test/e2e/support/inference-switch-workflow-boundary.test.ts @@ -5,11 +5,57 @@ import { describe, expect, it } from "vitest"; import { catalogueTarget, + catalogueTargetsForChangedFiles, E2E_TARGET_CATALOGUE, validateE2eTargetCatalogue, } from "../../../tools/e2e/target-catalogue.mts"; +import { buildE2eWorkflowPlan } from "../../../tools/e2e/workflow-plan.mts"; describe("inference-switch catalogue boundary", () => { + it.each([ + "src/lib/inference/native-provider/contract.ts", + "src/lib/inference/native-provider/custom-setup.ts", + "src/lib/inference/native-provider/custom.ts", + "src/lib/inference/native-provider/hosted.ts", + "src/lib/onboard/setup-inference.ts", + "src/lib/actions/inference-set/native.ts", + "src/lib/actions/inference-set.ts", + "test/e2e/live/openclaw-inference-switch-helpers.ts", + "test/e2e/live/openclaw-inference-switch.test.ts", + ])("selects native Anthropic switch coverage when %s changes (#13195)", (changedFile) => { + const targetId = "openclaw-compatible-anthropic-inference-switch"; + expect(catalogueTargetsForChangedFiles([changedFile]).map((target) => target.id)).toContain( + targetId, + ); + const plan = buildE2eWorkflowPlan( + {}, + { changedFiles: [changedFile], gatewayRuntimes: ["docker", "podman"] }, + ); + expect( + plan.catalogueMatrices.standard + .filter((row) => row.id === targetId) + .map((row) => row.execution_id) + .sort(), + ).toEqual([ + "openclaw-compatible-anthropic-inference-switch-anthropic-docker", + "openclaw-compatible-anthropic-inference-switch-anthropic-podman", + ]); + }); + + it("omits native Anthropic switch coverage for unrelated changes (#13195)", () => { + const changedFiles = ["src/lib/cli/public-display-defaults.ts"]; + const targetId = "openclaw-compatible-anthropic-inference-switch"; + expect(catalogueTargetsForChangedFiles(changedFiles).map((target) => target.id)).not.toContain( + targetId, + ); + const plan = buildE2eWorkflowPlan({}, { changedFiles, gatewayRuntimes: ["docker", "podman"] }); + expect( + Object.values(plan.catalogueMatrices) + .flat() + .map((row) => row.id), + ).not.toContain(targetId); + }); + it.each([{ scenario: "OpenClaw" }, { scenario: "Hermes" }])( "keeps both agents on their reviewed provider-switch contracts [$scenario]", ({ scenario }) => { @@ -48,6 +94,19 @@ describe("inference-switch catalogue boundary", () => { }, ); + it("selects native Anthropic through the existing trusted selector (#13195)", () => { + expect(catalogueTarget("openclaw-compatible-anthropic-inference-switch")).toMatchObject({ + targetId: "openclaw-inference-switch", + profile: "standard", + testFile: "test/e2e/live/openclaw-inference-switch.test.ts", + shard: "anthropic", + environment: { + NEMOCLAW_SWITCH_NATIVE_CUSTOM: "1", + NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", + }, + }); + }); + it("keeps canonical compatible Anthropic switch targets for both agents", () => { expect(catalogueTarget("openclaw-compatible-anthropic-inference-switch")).toMatchObject({ targetId: "openclaw-inference-switch", diff --git a/test/e2e/support/openclaw-inference-switch-baseline.test.ts b/test/e2e/support/openclaw-inference-switch-baseline.test.ts index 5b89318ced2..7ad2cbc9ecb 100644 --- a/test/e2e/support/openclaw-inference-switch-baseline.test.ts +++ b/test/e2e/support/openclaw-inference-switch-baseline.test.ts @@ -22,11 +22,15 @@ afterEach(async () => { vi.unstubAllEnvs(); }); -async function loadNativeSwitchRun() { +async function loadNativeSwitchRun(nativeCustom = false) { vi.resetModules(); captured.test.mockClear(); - vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); - vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", "0"); + vi.stubEnv( + "NEMOCLAW_SWITCH_PROVIDER", + nativeCustom ? "compatible-anthropic-endpoint" : "nvidia-prod", + ); + vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", nativeCustom ? "1" : "0"); + vi.stubEnv("NEMOCLAW_SWITCH_NATIVE_CUSTOM", nativeCustom ? "1" : "0"); const exists = fs.existsSync; vi.spyOn(fs, "existsSync").mockImplementation((file) => String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), @@ -43,49 +47,64 @@ async function loadNativeSwitchRun() { return { progress, run }; } -it("keeps the public NVIDIA key out of the native switch baseline", async () => { - const { progress, run } = await loadNativeSwitchRun(); - const result = { exitCode: 0, stdout: "", stderr: "" }; - const stop = new Error("onboarding captured"); - const nemoclaw = vi.fn( - async (_args: string[], _options: { env: NodeJS.ProcessEnv; redactionValues: string[] }) => { - throw stop; - }, - ); - const required = vi.fn((name: string) => { - expect(name).toBe("NVIDIA_API_KEY"); - return "nvapi-public-fixture-key"; - }); - await expect( - run({ - artifacts: { target: { declare: vi.fn() } }, - cleanup: { - trackDisposable: (_name: string, dispose: () => unknown) => disposables.push(dispose), - trackGateway: vi.fn(), - trackSandbox: vi.fn(), +it.each([false, true])( + "selects the authenticated baseline with native custom=%s", + async (nativeCustom) => { + const { progress, run } = await loadNativeSwitchRun(nativeCustom); + const result = { exitCode: 0, stdout: "", stderr: "" }; + const stop = new Error("onboarding captured"); + const nemoclaw = vi.fn( + async (_args: string[], _options: { env: NodeJS.ProcessEnv; redactionValues: string[] }) => { + throw stop; }, - host: { nemoclaw, command: vi.fn(async () => result) }, - progress, - runtimeProvider: { requireAvailable: vi.fn() }, - sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, - secrets: { required }, - }), - ).rejects.toBe(stop); - expect(required).toHaveBeenCalledExactlyOnceWith("NVIDIA_API_KEY"); - const args = nemoclaw.mock.calls[0]![0]; - const customDockerfile = args[args.indexOf("--from") + 1]; - expect(fs.readFileSync(customDockerfile, "utf8")).toContain("ARG NEMOCLAW_MESSAGING_PLAN_B64="); - const options = nemoclaw.mock.calls[0]![1]; - const environment = options.env; - expect(environment.NEMOCLAW_PROVIDER).toBe("custom"); - expect(environment.NEMOCLAW_ENDPOINT_URL).toMatch(/^http:\/\/host\.openshell\.internal:\d+\/v1$/); - expect(environment.NEMOCLAW_MODEL).toBe("openclaw-switch-baseline-model"); - expect(environment.COMPATIBLE_API_KEY).toBe("openclaw-switch-baseline-credential"); - expect(environment.NVIDIA_INFERENCE_API_KEY).toBeUndefined(); - expect(environment.NVIDIA_API_KEY).toBeUndefined(); - expect(options.redactionValues).toContain("nvapi-public-fixture-key"); - expect(options.redactionValues).toContain("openclaw-switch-baseline-credential"); -}); + ); + const required = vi.fn((name: string) => { + expect(name).toBe("NVIDIA_API_KEY"); + return "nvapi-public-fixture-key"; + }); + await expect( + run({ + artifacts: { target: { declare: vi.fn() } }, + cleanup: { + trackDisposable: (_name: string, dispose: () => unknown) => disposables.push(dispose), + trackGateway: vi.fn(), + trackSandbox: vi.fn(), + }, + host: { + nemoclaw, + command: vi.fn(async (_cmd, _args, options) => + options?.artifactName === "native-baseline-endpoint-address" + ? { ...result, stdout: "route 10.20.30.40" } + : result, + ), + }, + progress, + runtimeProvider: { requireAvailable: vi.fn() }, + sandbox: { openshell: vi.fn(async () => result), cleanupSandbox: vi.fn() }, + secrets: { required }, + }), + ).rejects.toBe(stop); + expect(required.mock.calls).toEqual(nativeCustom ? [] : [["NVIDIA_API_KEY"]]); + const args = nemoclaw.mock.calls[0]![0]; + const customDockerfile = args[args.indexOf("--from") + 1]; + expect(fs.readFileSync(customDockerfile, "utf8")).toContain("ARG NEMOCLAW_MESSAGING_PLAN_B64="); + const options = nemoclaw.mock.calls[0]![1]; + const environment = options.env; + expect(environment.NEMOCLAW_PROVIDER).toBe("custom"); + expect(new URL(environment.NEMOCLAW_ENDPOINT_URL!).hostname).toBe( + nativeCustom ? "10.20.30.40" : "host.openshell.internal", + ); + expect(environment.NEMOCLAW_TRUSTED_PRIVATE_INFERENCE_HOSTS).toBe( + nativeCustom ? "10.20.30.40" : undefined, + ); + expect(environment.NEMOCLAW_MODEL).toBe("openclaw-switch-baseline-model"); + expect(environment.COMPATIBLE_API_KEY).toBe("openclaw-switch-baseline-credential"); + expect(environment.NVIDIA_INFERENCE_API_KEY).toBeUndefined(); + expect(environment.NVIDIA_API_KEY).toBeUndefined(); + expect(options.redactionValues.includes("nvapi-public-fixture-key")).toBe(!nativeCustom); + expect(options.redactionValues).toContain("openclaw-switch-baseline-credential"); + }, +); it.each([ { diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts index 26b0e226db5..da681e3fdfb 100644 --- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts +++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts @@ -341,6 +341,7 @@ async function probeOpenClawConfig( inferenceApi: string; artifactName: string; nativeNvidia?: boolean; + nativeCustomEndpoint?: string; }, ) { const result = await readOpenClawConfig(sandbox, "switch-test", { @@ -348,6 +349,7 @@ async function probeOpenClawConfig( env: { HOME: home }, timeoutMs: 1000, nativeNvidia: expected.nativeNvidia, + nativeCustomApi: expected.nativeCustomEndpoint ? expected.inferenceApi : undefined, }); expect(result.exitCode).toBe(0); const config = JSON.parse(result.stdout); @@ -355,7 +357,9 @@ async function probeOpenClawConfig( const provider = config.models.providers[providerKey]; expect(config.agents.defaults.model.primary).toBe(`${providerKey}/${expected.model}`); expect(provider.api).toBe(expected.inferenceApi); - expect(provider.apiKey).toBe(expected.nativeNvidia ? undefined : "unused"); + expect(provider.apiKey).toBe( + expected.nativeNvidia || expected.nativeCustomEndpoint ? undefined : "unused", + ); const model = provider.models.find((entry: { id: string }) => entry.id === expected.model); expect( expected.inferenceApi === "anthropic-messages" @@ -382,7 +386,12 @@ function sandboxForOpenClawConfig(config: object, handle = scopedNativeHandle) { .map((arg) => arg.replaceAll("/sandbox/.openclaw/openclaw.json", configPath)), { encoding: "utf8", - env: { ...process.env, NVIDIA_INFERENCE_API_KEY: handle }, + env: { + ...process.env, + NVIDIA_INFERENCE_API_KEY: handle, + COMPATIBLE_ANTHROPIC_API_KEY: handle, + COMPATIBLE_API_KEY: handle, + }, stdio: ["pipe", "pipe", "pipe"], }, ), @@ -421,6 +430,55 @@ it("checks the actual switched Anthropic model budget", async () => { }); }); +it.each([ + ["anthropic-messages", true], + ["anthropic-messages", false], + ["openai-completions", true], + ["openai-completions", false], +] as const)( + "checks native custom %s credentials before redaction (valid=%s)", + async (api, valid) => { + const model = "mock-anthropic-model"; + const endpoint = "http://10.20.30.40:3000"; + const provider = + api === "anthropic-messages" ? "compatible-anthropic-endpoint" : "compatible-endpoint"; + const providerKey = api === "anthropic-messages" ? "anthropic" : "inference"; + const credentialEnv = + api === "anthropic-messages" ? "COMPATIBLE_ANTHROPIC_API_KEY" : "COMPATIBLE_API_KEY"; + const handle = `openshell:resolve:env:v7_${credentialEnv}`; + const config: any = {}; + patchOpenClawInferenceConfig( + config, + provider, + model, + api, + undefined, + provider, + { effort: null, explicit: false }, + false, + endpoint, + true, + ); + config.models.providers[providerKey].apiKey = valid ? handle : "synthetic-raw-credential"; + const result = probeOpenClawConfig( + sandboxForOpenClawConfig(config, handle) as never, + "/tmp/switch-home", + { + model, + inferenceApi: api, + artifactName: "native-anthropic-config", + nativeCustomEndpoint: endpoint, + }, + ); + await expect( + result.then( + () => true, + () => false, + ), + ).resolves.toBe(valid); + }, +); + it.each([ "unused", "nvapi-fixture-secret", diff --git a/test/generation/generate-native-hosted-config.test.ts b/test/generation/generate-native-hosted-config.test.ts index 1cc8df35240..e3e424317d7 100644 --- a/test/generation/generate-native-hosted-config.test.ts +++ b/test/generation/generate-native-hosted-config.test.ts @@ -4,10 +4,27 @@ import { describe, expect, it } from "vitest"; import { buildConfig } from "../../scripts/generate-openclaw-config.mts"; import { applyHermesManagedRoute } from "../../src/lib/hermes-managed-route"; +import { customNativeProvider } from "../../src/lib/inference/native-provider/custom"; import { HOSTED_NATIVE_PROVIDERS } from "../../src/lib/inference/native-provider/hosted"; import { baseOpenClawGenerationEnv } from "../helpers/openclaw-env-fixture"; -describe.each(HOSTED_NATIVE_PROVIDERS)("native $label agent configuration", (provider) => { +describe.each([ + ...HOSTED_NATIVE_PROVIDERS, + ...[ + ["compatible-endpoint", "openai-completions", "https://custom.example/team/v1"], + ["compatible-endpoint", "openai-responses", "https://custom.example/team/v1"], + ["compatible-anthropic-endpoint", "anthropic-messages", "https://custom.example/team"], + ["compatible-anthropic-endpoint", "openai-completions", "https://custom.example/team"], + ].map(([provider, api, endpointUrl]) => + customNativeProvider({ + provider, + api, + endpointUrl, + credentialEnv: "HOST_KEY", + allowedIps: ["8.8.8.8"], + }), + ), +])("native $label agent configuration", (provider) => { it("renders OpenClaw credentials as placeholders and keeps the native protocol (#12589)", () => { const config = buildConfig({ ...baseOpenClawGenerationEnv(), diff --git a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts index a4234926077..e5f6e24ca99 100644 --- a/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts +++ b/test/onboarding/onboard-anthropic-compatible-openai-agent.test.ts @@ -104,6 +104,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: providerAbsentRunner, overrides: { probeOpenAiLikeEndpoint }, }); @@ -135,6 +136,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV), overrides: { probeOpenAiLikeEndpoint }, }); @@ -158,6 +160,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, ["test-box"]), overrides: { probeOpenAiLikeEndpoint }, }); @@ -182,6 +185,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 const exitProcess = createInjectedExit(); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: createStaleAnthropicProviderRunner(PROVIDER, CREDENTIAL_ENV, [ "other-box", "test-box", @@ -218,6 +222,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 message: "POST /v1/chat/completions returned 404", })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: providerAbsentRunner, overrides: { probeOpenAiLikeEndpoint, exitProcess, isNonInteractive: () => true }, }); @@ -242,6 +247,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 vi.stubEnv(CREDENTIAL_ENV, "hub-secret"); const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: providerAbsentRunner, overrides: { probeOpenAiLikeEndpoint }, }); @@ -261,6 +267,7 @@ describe("compatible-anthropic-endpoint registration for OpenAI-only agents (#62 it("skips the surface probe on keyless gateway-credential reuse", async () => { const probeOpenAiLikeEndpoint = vi.fn(() => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: commandStubs({ "provider get": { status: 0 } }), overrides: { probeOpenAiLikeEndpoint }, }); diff --git a/test/onboarding/onboard-inference-failure-paths.test.ts b/test/onboarding/onboard-inference-failure-paths.test.ts index 8d13b5367a0..bffa3d77338 100644 --- a/test/onboarding/onboard-inference-failure-paths.test.ts +++ b/test/onboarding/onboard-inference-failure-paths.test.ts @@ -603,6 +603,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -640,6 +641,7 @@ describe("setupInference dependency failures", () => { }); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { exitProcess, upsertProvider, @@ -675,6 +677,7 @@ describe("setupInference dependency failures", () => { }); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -714,6 +717,7 @@ describe("setupInference dependency failures", () => { message: "Bedrock provider registration failed", })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -751,6 +755,7 @@ describe("setupInference dependency failures", () => { message: "Bedrock provider registration failed without status", })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, overrides: { isNonInteractive: () => true, exitProcess, @@ -784,6 +789,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "inference set" ? { status: 37, stdout: "", stderr: "route denied" } @@ -825,6 +831,7 @@ describe("setupInference dependency failures", () => { const ensureAdapter = vi.fn(async () => successfulBedrockAdapter()); const upsertProvider = vi.fn(async () => ({ ok: true })); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "inference set" ? { status: null, stdout: "", stderr: "" } diff --git a/test/onboarding/onboard-inference-gateway-scope.test.ts b/test/onboarding/onboard-inference-gateway-scope.test.ts index 8272ec7c07a..41b6630936b 100644 --- a/test/onboarding/onboard-inference-gateway-scope.test.ts +++ b/test/onboarding/onboard-inference-gateway-scope.test.ts @@ -258,6 +258,7 @@ describe("onboarding inference gateway scope", () => { }, ]); const harness = createHarness({ + legacyCustomRoute: true, runOpenshell: commandRouter.runOpenshell, overrides: { probeOpenAiLikeEndpoint: vi.fn(() => ({ ok: true })), diff --git a/test/onboarding/onboard-inference-reconciliation.test.ts b/test/onboarding/onboard-inference-reconciliation.test.ts index a4dc57230d2..f05c9e41aec 100644 --- a/test/onboarding/onboard-inference-reconciliation.test.ts +++ b/test/onboarding/onboard-inference-reconciliation.test.ts @@ -109,6 +109,7 @@ describe("onboard helpers", () => { })); const setupBedrockRuntimeInference = bedrockRuntimeOnboard.setupBedrockRuntimeInference; const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.join(" ") === "provider get -g nemoclaw compatible-anthropic-endpoint" ? { status: 1, stdout: "", stderr: "" } @@ -957,6 +958,7 @@ const { isOpenclawReady } = require(${onboardPath}); it("updates OpenAI-compatible providers without passing an unsupported --type flag", async () => { await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { status: 0, stdout: COMPATIBLE_PROVIDER_METADATA, stderr: "" } @@ -997,6 +999,7 @@ const { isOpenclawReady } = require(${onboardPath}); }, ]); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: commandRouter.runOpenshell, overrides: { promptValidationRecovery: async () => { @@ -1042,6 +1045,7 @@ const { isOpenclawReady } = require(${onboardPath}); }, ]); const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: commandRouter.runOpenshell, overrides: { promptValidationRecovery: async () => "selection" }, }); @@ -1426,15 +1430,20 @@ describe("re-onboard Ollama GPU release (#9110)", () => { } // A serialized re-onboard can neither replace the row under the read nor // select the captured model before this cleanup runs. - expect(events).toEqual([ + expect(events.filter((event) => event !== "read-prior-route")).toEqual([ "lock-enter", - "read-prior-route", "ownership-lock-enter", "peer-scan", "unload", "ownership-lock-exit", "lock-exit", ]); + const priorReads = events.flatMap((event, index) => + event === "read-prior-route" ? [index] : [], + ); + expect(priorReads.length).toBeGreaterThan(0); + expect(Math.min(...priorReads)).toBeGreaterThan(events.indexOf("lock-enter")); + expect(Math.max(...priorReads)).toBeLessThan(events.indexOf("ownership-lock-enter")); }); it("skips the release when the route returns to selection (#9110)", async () => { diff --git a/test/onboarding/onboard-inference-smoke.test.ts b/test/onboarding/onboard-inference-smoke.test.ts index 703f3aadb9b..75ae93d1463 100644 --- a/test/onboarding/onboard-inference-smoke.test.ts +++ b/test/onboarding/onboard-inference-smoke.test.ts @@ -121,6 +121,7 @@ process.env.BROKEN_API_KEY = "test-key"; const { createSetupInference } = require(${onboardPath}); const setupInference = createSetupInference({ + getSandbox: () => ({ name: "test-sandbox", provider: "compatible-endpoint" }), resolveEndpointHost: async () => [{ address: "93.184.216.34", family: 4 }], }); diff --git a/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts b/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts index b5697e7e5a3..c51383effdb 100644 --- a/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts +++ b/test/onboarding/onboard-remote-recreate-credential-reuse.test.ts @@ -18,7 +18,7 @@ const REPO_ROOT = path.join(import.meta.dirname, "../.."); describe("onboard recovered remote-provider credential reuse", () => { it( - "re-applies an exact compatible route without exporting or directly validating its gateway credential", + "re-applies a registered legacy route and requires a new credential after its authority is removed", testTimeoutOptions(90_000), () => { const workspace = createOnboardProcessWorkspace("nemoclaw-remote-recreate-", { @@ -103,8 +103,11 @@ if (process.env.NEMOCLAW_TEST_CONFLICTING_ENDPOINT === "1") { credentialEnv: "COMPATIBLE_API_KEY", }); } -registry.removeSandbox("recovered-custom"); -const { setupNim, setupInference } = require(${onboardPath}); +if (process.env.NEMOCLAW_TEST_RECREATE === "1") registry.removeSandbox("recovered-custom"); +const { setupNim, createSetupInference } = require(${onboardPath}); +const setupInference = createSetupInference({ + resolveEndpointHost: async () => [{ address: "8.8.8.8", family: 4 }], +}); (async () => { const selected = await setupNim(null, "recovered-custom", null, true, { @@ -192,6 +195,22 @@ const { setupNim, setupInference } = require(${onboardPath}); assert.ok(!openshellLog.includes("OPENAI_BASE_URL="), openshellLog); assert.ok(!openshellLog.includes("--credential"), openshellLog); + fs.writeFileSync(openshellLogPath, ""); + const recreateResult = runOnboardProcess([scriptPath], { + env: scenarioEnv({ NEMOCLAW_TEST_RECREATE: "1" }), + timeoutMs: 80_000, + }); + assert.notEqual(recreateResult.status, 0, recreateResult.output); + assert.match( + recreateResult.output, + /A new credential is required for this endpoint and API/, + ); + assert.doesNotMatch(recreateResult.output, /Reusing existing gateway credential/); + assert.doesNotMatch( + fs.readFileSync(openshellLogPath, "utf8"), + /provider (create|update)|inference set/, + ); + fs.writeFileSync(openshellLogPath, ""); const overrideResult = runOnboardProcess([scriptPath], { env: scenarioEnv({ diff --git a/test/onboarding/onboard.test.ts b/test/onboarding/onboard.test.ts index edbd7264578..1c634135b7e 100644 --- a/test/onboarding/onboard.test.ts +++ b/test/onboarding/onboard.test.ts @@ -845,6 +845,7 @@ const { createSandbox } = require(${onboardPath}); await withProcessEnv({ OPENAI_API_KEY: "sk-TEST-NOT-A-REAL-VALUE" }, async () => { const harness = createDirectSetupInferenceHarness({ + legacyCustomRoute: true, runOpenshell: (args) => args.slice(0, 2).join(" ") === "provider get" ? { diff --git a/test/support/setup-inference-test-harness.ts b/test/support/setup-inference-test-harness.ts index fa4a61eb342..d572b279d53 100644 --- a/test/support/setup-inference-test-harness.ts +++ b/test/support/setup-inference-test-harness.ts @@ -52,6 +52,8 @@ export type DirectRunStubResult = { }; export type DirectSetupHarnessOptions = { + /** Exercise an existing custom sandbox's shared inference route. */ + legacyCustomRoute?: boolean; runOpenshell?: ( args: string[], options: DirectRunOptions, @@ -383,6 +385,7 @@ export function createDirectSetupInferenceHarnessFactory( createSetupInference: CreateSetupInference, ) { return function createDirectSetupInferenceHarness(options: DirectSetupHarnessOptions = {}) { + let legacySandbox: ReturnType> = null; const commands: DirectCommandEntry[] = []; const errors: string[] = []; const logs: string[] = []; @@ -544,7 +547,7 @@ 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. - getSandbox: () => null, + getSandbox: () => legacySandbox, listSandboxes: () => ({ sandboxes: [], defaultSandbox: null }), unloadOllamaModels, withOllamaModelOwnershipLock: (operation) => operation(), @@ -571,6 +574,9 @@ export function createDirectSetupInferenceHarnessFactory( hermesToolGateways, inferenceOptions = {}, ) => { + if (options.legacyCustomRoute && sandboxName) { + legacySandbox = { name: sandboxName, provider, model, endpointUrl, credentialEnv }; + } const nativeLocal = usesNativeLocalInference(provider, endpointUrl); const operation = () => (nativeLocal ? setupNativeInference : setupInferenceWithoutPolicyAuthority)( diff --git a/tools/e2e/target-catalogue.mts b/tools/e2e/target-catalogue.mts index b0e43a50312..b7a298a9e84 100644 --- a/tools/e2e/target-catalogue.mts +++ b/tools/e2e/target-catalogue.mts @@ -1294,6 +1294,9 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ shard: "anthropic", owningPaths: [ "src/lib/actions/inference-set.ts", + "src/lib/actions/inference-set/native.ts", + "src/lib/inference/native-provider/", + "src/lib/onboard/setup-inference.ts", "test/e2e/live/openclaw-inference-switch-helpers.ts", ], environment: { @@ -1305,6 +1308,7 @@ export const E2E_TARGET_CATALOGUE: readonly E2eCatalogueTarget[] = [ NEMOCLAW_SWITCH_MODEL: "mock-anthropic-model", NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + NEMOCLAW_SWITCH_NATIVE_CUSTOM: "1", OPENSHELL_GATEWAY: "nemoclaw", }, }),