diff --git a/agents/hermes/managed_policy.py b/agents/hermes/managed_policy.py index f6945e347a7..2aa3ac14277 100644 --- a/agents/hermes/managed_policy.py +++ b/agents/hermes/managed_policy.py @@ -10,12 +10,15 @@ import re import stat from pathlib import Path -from urllib.parse import urlsplit +from urllib.parse import unquote, urlsplit MANAGED_POLICY_PATH = Path("/usr/local/share/nemoclaw/hermes-managed-policy.json") MANAGED_POLICY_SCHEMA_VERSION = 3 HERMES_PROXY_REWRITE_SENTINEL = "sk-OPENSHELL-PROXY-REWRITE" NVIDIA_INFERENCE_PLACEHOLDER = "${NVIDIA_INFERENCE_API_KEY}" +NVIDIA_SCOPED_CREDENTIAL_HANDLE = re.compile( + r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY" +) class ManagedPolicyError(Exception): @@ -162,10 +165,29 @@ def load_managed_policy(path: Path = MANAGED_POLICY_PATH) -> dict: _ = url.port except (TypeError, ValueError): raise ManagedPolicyError("managed policy model.base_url is invalid") from None + if ( + not native_nvidia + and url.scheme.lower() == "https" + and unquote(url.hostname or "").lower().rstrip(".") + == "integrate.api.nvidia.com" + and url.port in (None, 443) + ): + raise ManagedPolicyError( + "Native NVIDIA inference requires https://integrate.api.nvidia.com/v1." + ) 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) - if api_key != expected_key and (hosted_placeholder is None or api_key != hosted_placeholder): + scoped_nvidia_handle = ( + native_nvidia + and isinstance(api_key, str) + and NVIDIA_SCOPED_CREDENTIAL_HANDLE.fullmatch(api_key) is not None + ) + if ( + api_key != expected_key + and (hosted_placeholder is None or api_key != hosted_placeholder) + and not scoped_nvidia_handle + ): raise ManagedPolicyError( "managed policy model.api_key must use an OpenShell credential placeholder or proxy rewrite sentinel " "matching its route" diff --git a/docs/inference/switch-providers.mdx b/docs/inference/switch-providers.mdx index 0bcd9a9b137..c0809662722 100644 --- a/docs/inference/switch-providers.mdx +++ b/docs/inference/switch-providers.mdx @@ -70,8 +70,16 @@ Run `$$nemoclaw doctor --fix`, then retry the agent turn. -For Hermes, NemoClaw updates the native `/sandbox/.hermes/config.yaml`, including the model, base URL, API-family mode, and OpenShell proxy API-key placeholder. -The gateway, CLI, TUI, and Web Dashboard all read that shared configuration; a normal runtime route change does not rebuild or restart Hermes. +For Hermes, NemoClaw updates the native `/sandbox/.hermes/config.yaml`, including the model, base URL, API-family mode, and managed API-key value. +`inference.local` uses the OpenShell proxy rewrite sentinel. +Generated NVIDIA Build configuration uses `${NVIDIA_INFERENCE_API_KEY}` for supervisor expansion. +A live switch to NVIDIA Build writes the newly attached provider's scoped OpenShell credential reference. +These values do not expose the raw provider credential. +The gateway, CLI, TUI, and Web Dashboard all read that shared configuration. +Changes between shared routes do not rebuild or restart Hermes. +A switch to or from a native hosted provider restarts the Hermes gateway after configuration sync, including a live NVIDIA Build switch. +Active agent requests can be interrupted during the restart. +If the restart fails, the route and configuration remain committed. Run `$$nemoclaw gateway restart` to apply the switch. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 689d218b0c2..4f5d806b16f 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3619,7 +3619,18 @@ Switch the active inference provider or model for a NemoClaw-managed OpenClaw sa -Switch the active inference provider or model for a NemoClaw-managed Hermes sandbox. For NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider, the command attaches or updates the selected sandbox's native provider. Custom endpoints and local providers retain their existing shared OpenShell route. It then patches the selected running agent config to match the selected inference path, recomputes the config hash, and updates the NemoClaw registry. It is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. For Hermes, the patch updates the shared native `/sandbox/.hermes/config.yaml` (`model.default`, `model.base_url`, `model.provider: custom`, API-family mode when needed, and the OpenShell proxy API-key placeholder) and does not rebuild or restart the gateway. The gateway, CLI, TUI, and Web Dashboard read that same configuration. Keeping the placeholder preserves dashboard and API authentication after provider switches. Under the `nemohermes` alias, the command uses the registered Hermes sandbox when exactly one exists; otherwise pass `--sandbox ` to target one explicitly. +Switch the active inference provider or model for a NemoClaw-managed Hermes sandbox. +For NVIDIA Endpoints, OpenAI, Anthropic, Gemini, OpenRouter, and Hermes Provider, the command attaches or updates the selected sandbox's native provider. +Custom endpoints and local providers retain their existing shared OpenShell route. +It then patches the shared native `/sandbox/.hermes/config.yaml`, recomputes the config hash, and updates the NemoClaw registry. +Changes between shared routes do not rebuild or restart Hermes. +A switch to or from a native hosted provider restarts the Hermes gateway after configuration sync, including a live NVIDIA Endpoints switch. +Active agent requests can be interrupted during the restart. +If the restart fails, the route and configuration remain committed. Run `$$nemoclaw gateway restart` to apply the switch. + +Shared routes use the OpenShell proxy API-key placeholder. On a live NVIDIA Endpoints switch, NemoClaw writes the newly attached provider's scoped OpenShell credential reference into the Hermes config. Other native hosted providers use their managed credential placeholders. None of these values is a raw provider credential. The gateway, CLI, TUI, and Web Dashboard read the same configuration. + +The command is also available in sandbox-first form as `$$nemoclaw inference set --provider --model `. Under the `nemohermes` alias, it uses the registered Hermes sandbox when exactly one exists; otherwise pass `--sandbox ` to target one explicitly. diff --git a/docs/security/credential-storage.mdx b/docs/security/credential-storage.mdx index 6fbf5bdbb83..4d242c6979f 100644 --- a/docs/security/credential-storage.mdx +++ b/docs/security/credential-storage.mdx @@ -28,7 +28,10 @@ Those files should contain resolver placeholders, not live provider credentials. For managed tools and messaging, NemoClaw keeps host-side auth in OpenShell providers or host brokers and writes placeholder values into `/sandbox/.hermes/config.yaml`, `/sandbox/.hermes/.env`, and process environment entries visible to the sandbox. Hermes startup rejects raw secret-shaped values in those sandbox-visible surfaces. The managed Hermes wrapper reads that token from `/sandbox/.hermes/.env` and supplies it only through the dashboard process environment. -The shared native inference configuration uses the OpenShell proxy rewrite sentinel instead of raw provider credentials. +For `inference.local`, Hermes stores the OpenShell proxy rewrite sentinel in its native inference configuration. +Generated NVIDIA Build configuration uses `${NVIDIA_INFERENCE_API_KEY}` for supervisor expansion. +A live switch to NVIDIA Build writes the newly attached provider's scoped OpenShell credential reference into the native configuration. +These values do not expose the raw provider credential. NemoClaw manages Deep Agents Code provider credentials through the same OpenShell provider boundary. diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 2b7eda0b7a6..adff049d2db 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -74,6 +74,26 @@ clear_managed_inference_credentials() { printf '%s\n' '[SECURITY] Native NVIDIA inference requires https://integrate.api.nvidia.com/v1.' >&2 return 1 fi + if ! is_managed_inference_route; then + # Parse noncanonical routes in a child without either provider credential. + local parsed_host_status=0 + env -i PATH="$PATH" NEMOCLAW_INFERENCE_BASE_URL="${NEMOCLAW_INFERENCE_BASE_URL:-}" node -e ' + try { + const url = new URL(process.env.NEMOCLAW_INFERENCE_BASE_URL); + if (url.protocol === "https:" && + url.hostname.replace(/\.+$/, "") === "integrate.api.nvidia.com" && + url.port === "") process.exit(42); + } catch {} + ' || parsed_host_status=$? + if [ "$parsed_host_status" -eq 42 ]; then + unset NVIDIA_API_KEY NVIDIA_INFERENCE_API_KEY + printf '%s\n' '[SECURITY] Native NVIDIA inference requires https://integrate.api.nvidia.com/v1.' >&2 + return 1 + fi + if [ "$parsed_host_status" -ne 0 ]; then + return "$parsed_host_status" + fi + fi if is_managed_inference_route; then unset NVIDIA_API_KEY if ! [[ "${NVIDIA_INFERENCE_API_KEY:-}" =~ ^openshell:resolve:env:(v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$ ]]; then diff --git a/src/lib/actions/inference-set-hermes-run.test.ts b/src/lib/actions/inference-set-hermes-run.test.ts index 9f5f4771209..858ebe9ea9d 100644 --- a/src/lib/actions/inference-set-hermes-run.test.ts +++ b/src/lib/actions/inference-set-hermes-run.test.ts @@ -12,6 +12,7 @@ vi.mock("../onboard/experimental/portable-agent-lifecycle", async (importOrigina assertHermesPortableCommandUnavailable: portableMocks.assertUnavailable, })); import { HERMES_PROXY_REWRITE_SENTINEL } from "../hermes-managed-route"; +import { NVIDIA_HOSTED_NATIVE_PROVIDER } from "../inference/native-nvidia/contract"; import type { ConfigObject } from "../security/credential-filter"; import { runInferenceSet } from "./inference-set"; import { baseSession, createDeps, HERMES_TARGET } from "../../../test/helpers/inference-set"; @@ -21,6 +22,79 @@ describe("runInferenceSet Hermes routing", () => { portableMocks.assertUnavailable.mockReset(); }); + it("reads the attached native handle before publishing a Hermes switch", async () => { + const config: ConfigObject = { model: { default: "local-model", provider: "custom" } }; + const deps = createDeps({ + config, + entry: { name: "hermes", agent: "hermes", provider: "vllm-local", model: "local-model" }, + defaultSandbox: "hermes", + target: HERMES_TARGET, + session: baseSession({ agent: "hermes", sandboxName: "hermes" }), + }); + await runInferenceSet( + { + provider: "nvidia-prod", + model: "nvidia/test-model", + sandboxName: "hermes", + noVerify: true, + }, + deps, + ); + expect(deps.calls.readNativeNvidiaCredentialHandle).toHaveBeenCalledWith("hermes", "nemoclaw"); + expect(config.model).toMatchObject({ + api_key: "openshell:resolve:env:v1_NVIDIA_INFERENCE_API_KEY", + }); + expect(deps.calls.writeSandboxConfig).toHaveBeenCalledOnce(); + }); + + it("leaves the Hermes config unchanged when the attached handle is unavailable", async () => { + const config: ConfigObject = { model: { default: "local-model", provider: "custom" } }; + const deps = createDeps({ + config, + entry: { name: "hermes", agent: "hermes", provider: "vllm-local", model: "local-model" }, + defaultSandbox: "hermes", + target: HERMES_TARGET, + session: baseSession({ agent: "hermes", sandboxName: "hermes" }), + readNativeNvidiaCredentialHandle: async () => { + throw new Error("provider-bound handle unavailable"); + }, + }); + const attachProvider = vi.spyOn(deps.providerAdapter, "attachProvider"); + const detachProvider = vi.spyOn(deps.providerAdapter, "detachProvider"); + await expect( + runInferenceSet( + { + provider: "nvidia-prod", + model: "nvidia/test-model", + sandboxName: "hermes", + noVerify: true, + }, + deps, + ), + ).rejects.toThrow("provider-bound handle unavailable"); + expect(config.model).toEqual({ default: "local-model", provider: "custom" }); + expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled(); + expect(deps.calls.updateSandbox).not.toHaveBeenCalled(); + expect(attachProvider).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "hermes", + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }), + ); + expect(detachProvider).toHaveBeenCalledWith( + expect.objectContaining({ + sandboxName: "hermes", + providerName: NVIDIA_HOSTED_NATIVE_PROVIDER, + }), + ); + await expect( + deps.providerAdapter.listProviderAttachments({ + target: { kind: "named", gatewayName: "nemoclaw" }, + sandboxName: "hermes", + }), + ).resolves.toEqual({ ok: true, value: { names: [] } }); + }); + it("rejects schema-5 before OpenShell or registry mutation (#9203)", async () => { portableMocks.assertUnavailable.mockImplementation(() => { throw new Error("schema-5 rejected"); diff --git a/src/lib/actions/inference-set-patch-hermes.test.ts b/src/lib/actions/inference-set-patch-hermes.test.ts index eaacb06d420..7966719d370 100644 --- a/src/lib/actions/inference-set-patch-hermes.test.ts +++ b/src/lib/actions/inference-set-patch-hermes.test.ts @@ -25,6 +25,62 @@ describe("patchHermesInferenceConfig", () => { }); }); + it("uses the attached provider handle on every Hermes native credential path", () => { + const config: ConfigObject = {}; + const handle = "openshell:resolve:env:v12_NVIDIA_INFERENCE_API_KEY"; + patchHermesInferenceConfig( + config, + "nvidia-prod", + "nvidia/test-model", + null, + undefined, + undefined, + true, + handle, + ); + expect(config).toMatchObject({ + model: { api_key: handle }, + providers: { "nvidia-prod": { api_key: handle } }, + custom_providers: [{ api_key: handle }], + }); + expect(() => + patchHermesInferenceConfig( + {}, + "nvidia-prod", + "nvidia/test-model", + null, + undefined, + undefined, + true, + "nvapi-raw", + ), + ).toThrow(/provider-bound credential handle/u); + expect(() => + patchHermesInferenceConfig( + {}, + "nvidia-prod", + "nvidia/test-model", + null, + undefined, + undefined, + true, + "", + ), + ).toThrow(/provider-bound credential handle/u); + expect(() => + patchHermesInferenceConfig( + {}, + "vllm-local", + "local-model", + null, + undefined, + undefined, + true, + handle, + ), + ).toThrow(/provider-bound credential handle/u); + }); + it("updates the complete Hermes route for the selected provider", () => { const config: ConfigObject = { model: { diff --git a/src/lib/actions/inference-set-provider.test.ts b/src/lib/actions/inference-set-provider.test.ts index adb9d91f9ea..a1000c0c5c1 100644 --- a/src/lib/actions/inference-set-provider.test.ts +++ b/src/lib/actions/inference-set-provider.test.ts @@ -1,20 +1,213 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; import { describe, expect, it, vi } from "vitest"; import type { OpenShellProviderAdapter, OpenShellProviderMetadata, } from "../adapters/openshell/provider-adapter"; +import { captureSanitizedResolvedOpenshellAsync } from "../adapters/openshell/sanitized-capture"; +import { SANDBOX_EXEC_STARTED_MARKER } from "../adapters/sandbox/sandbox-exec-output"; +import { NATIVE_NVIDIA_SCOPED_HANDLE_READ_SCRIPT } from "../inference-credential"; import { assertInferenceSetProviderOwnership, prepareInferenceSetProviderBinding, + readNativeNvidiaCredentialHandle, } from "./inference-set-provider"; import type { HttpsPinProviderBinding } from "./inference-set-route-containment"; +vi.mock("../adapters/openshell/sanitized-capture", async (importOriginal) => ({ + ...(await importOriginal()), + captureSanitizedResolvedOpenshellAsync: vi.fn(), +})); + const PROVIDER_ID = "11111111-2222-4333-8444-555555555555"; const TARGET = { kind: "named", gatewayName: "nemoclaw" } as const; +function markerFromCommand(args: string[]): string { + const marker = args + .at(-1) + ?.match(new RegExp(`${SANDBOX_EXEC_STARTED_MARKER}_[0-9a-f]{32}`, "u"))?.[0]; + expect(marker).toBeDefined(); + return marker ?? ""; +} + +describe("native NVIDIA credential handle boundary", () => { + it("emits a fixed pending signal without printing a missing or raw credential", () => { + const missing = spawnSync("sh", ["-c", NATIVE_NVIDIA_SCOPED_HANDLE_READ_SCRIPT], { + encoding: "utf8", + env: { NVIDIA_INFERENCE_API_KEY: "" }, + }); + expect(missing.status).toBe(75); + expect(missing.stdout).toBe(""); + expect(missing.stderr).toBe("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\n"); + + const raw = spawnSync("sh", ["-c", NATIVE_NVIDIA_SCOPED_HANDLE_READ_SCRIPT], { + encoding: "utf8", + env: { NVIDIA_INFERENCE_API_KEY: "raw-test-secret" }, + }); + expect(raw.status).toBe(1); + expect(raw.stdout).toBe(""); + expect(raw.stderr).toBe(""); + }); + + it.each([ + "openshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY", + `openshell:resolve:env:s${"a".repeat(64)}_NVIDIA_INFERENCE_API_KEY`, + ])("reads only the scoped handle %s from a sanitized sandbox exec", async (handle) => { + const capture = vi.mocked(captureSanitizedResolvedOpenshellAsync); + capture.mockImplementationOnce(async (args) => { + const stdout = `${markerFromCommand(args)}\n${handle}\n`; + return { status: 0, output: stdout, stdout, stderr: "" }; + }); + + await expect(readNativeNvidiaCredentialHandle("hermes-sandbox", "gateway-a")).resolves.toBe( + handle, + ); + expect(capture).toHaveBeenCalledExactlyOnceWith( + [ + "sandbox", + "exec", + "--name", + "hermes-sandbox", + "-g", + "gateway-a", + "--", + "sh", + "-c", + expect.stringContaining(NATIVE_NVIDIA_SCOPED_HANDLE_READ_SCRIPT), + ], + { + ignoreError: true, + includeStderr: true, + includeStreams: true, + outputLimitBytes: 512, + timeout: 30_000, + }, + ); + capture.mockClear(); + }); + + it.each(["stdout", "stderr"])( + "reads a framed scoped handle from the %s stream", + async (stream) => { + const handle = "openshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY"; + const capture = vi.mocked(captureSanitizedResolvedOpenshellAsync); + capture.mockImplementationOnce(async (args) => { + const framed = `stdout: ${markerFromCommand(args)}\nstdout: ${handle}\n`; + return { + status: 0, + output: framed, + stdout: stream === "stdout" ? framed : "OpenShell preamble\n", + stderr: stream === "stderr" ? framed : "", + }; + }); + + await expect(readNativeNvidiaCredentialHandle("hermes-sandbox", "gateway-a")).resolves.toBe( + handle, + ); + capture.mockClear(); + }, + ); + + it("waits for a newly attached provider handle only when OpenShell reports it pending", async () => { + const capture = vi.mocked(captureSanitizedResolvedOpenshellAsync); + const sleep = vi.fn(async () => undefined); + const handle = "openshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY"; + capture.mockImplementationOnce(async (args) => ({ + status: 75, + output: "", + stdout: `${markerFromCommand(args)}\n`, + stderr: "NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\n", + })); + capture.mockImplementationOnce(async (args) => { + const stdout = `${markerFromCommand(args)}\n${handle}\n`; + return { status: 0, output: stdout, stdout, stderr: "" }; + }); + + await expect( + readNativeNvidiaCredentialHandle("hermes-sandbox", "gateway-a", { sleep }), + ).resolves.toBe(handle); + expect(sleep).toHaveBeenCalledExactlyOnceWith(2_000); + expect(capture).toHaveBeenCalledTimes(2); + expect(markerFromCommand(capture.mock.calls[0]?.[0] ?? [])).not.toBe( + markerFromCommand(capture.mock.calls[1]?.[0] ?? []), + ); + capture.mockClear(); + }); + + it("stops after ten explicitly pending read-only probes", async () => { + const capture = vi.mocked(captureSanitizedResolvedOpenshellAsync); + const sleep = vi.fn(async () => undefined); + capture.mockImplementation(async (args) => ({ + status: 75, + output: "", + stdout: `${markerFromCommand(args)}\n`, + stderr: "NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\n", + })); + + await expect( + readNativeNvidiaCredentialHandle("hermes-sandbox", "gateway-a", { sleep }), + ).rejects.toThrow("OpenShell did not expose a provider-bound NVIDIA credential handle"); + expect(capture).toHaveBeenCalledTimes(10); + expect(sleep).toHaveBeenCalledTimes(9); + capture.mockReset(); + }); + + it("does not retry a non-pending credential probe failure", async () => { + const capture = vi.mocked(captureSanitizedResolvedOpenshellAsync); + const sleep = vi.fn(async () => undefined); + capture.mockImplementationOnce(async (args) => ({ + status: 75, + output: "", + stdout: `${markerFromCommand(args)}\n`, + stderr: "unrelated execution failure", + })); + + await expect( + readNativeNvidiaCredentialHandle("hermes-sandbox", "gateway-a", { sleep }), + ).rejects.toThrow("OpenShell did not expose a provider-bound NVIDIA credential handle"); + expect(capture).toHaveBeenCalledOnce(); + expect(sleep).not.toHaveBeenCalled(); + capture.mockClear(); + }); + + it.each([ + [1, "openshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY", ""], + [0, "sk-raw-secret", ""], + [0, "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", ""], + [0, "openshell:resolve:env:v7_OPENAI_API_KEY", ""], + [0, "openshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY extra", ""], + [0, "", "openshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY"], + ])("rejects invalid capture status %s and stdout %s", async (status, stdout, stderr) => { + const capture = vi.mocked(captureSanitizedResolvedOpenshellAsync); + capture.mockImplementationOnce(async (args) => { + const markedStdout = `${markerFromCommand(args)}\n${stdout}`; + return { status, output: `${markedStdout}${stderr}`, stdout: markedStdout, stderr }; + }); + + await expect(readNativeNvidiaCredentialHandle("hermes-sandbox", "gateway-a")).rejects.toThrow( + "OpenShell did not expose a provider-bound NVIDIA credential handle", + ); + capture.mockClear(); + }); + + it("rejects duplicate marker boundaries even when one contains a valid handle", async () => { + const capture = vi.mocked(captureSanitizedResolvedOpenshellAsync); + capture.mockImplementationOnce(async (args) => { + const marker = markerFromCommand(args); + const stdout = `${marker}\nopenshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY\n`; + return { status: 0, output: stdout, stdout, stderr: `stdout: ${marker}\n` }; + }); + + await expect(readNativeNvidiaCredentialHandle("hermes-sandbox", "gateway-a")).rejects.toThrow( + "OpenShell did not expose a provider-bound NVIDIA credential handle", + ); + capture.mockClear(); + }); +}); + function binding(overrides: Partial = {}): HttpsPinProviderBinding { return { baseUrl: "http://host.openshell.internal:11438/route/route-a/v1", diff --git a/src/lib/actions/inference-set-provider.ts b/src/lib/actions/inference-set-provider.ts index 0874fe03874..895b2668c46 100644 --- a/src/lib/actions/inference-set-provider.ts +++ b/src/lib/actions/inference-set-provider.ts @@ -13,8 +13,19 @@ import type { OpenShellProviderMetadata, } from "../adapters/openshell/provider-adapter"; import { createCliOpenShellProviderAdapter } from "../adapters/openshell/provider-adapter-cli"; +import { captureSanitizedResolvedOpenshellAsync } from "../adapters/openshell/sanitized-capture"; +import { + buildSandboxExecMarkedCommand, + createSandboxExecMarker, + extractSandboxExecCommandStdoutFromStreams, +} from "../adapters/sandbox/sandbox-exec-output"; import { namedOpenShellGateway } from "../adapters/openshell/sandbox-observer"; import { retryUntilAsync } from "../core/retry"; +import { + NATIVE_NVIDIA_SCOPED_HANDLE_PATTERN, + NATIVE_NVIDIA_SCOPED_HANDLE_READ_SCRIPT, +} from "../inference-credential"; +import { NVIDIA_HOSTED_LOGICAL_PROVIDER } from "../inference/native-nvidia/contract"; import { matchesGatewayProviderBinding } from "../onboard/gateway-provider-metadata"; import { assertHermesPortableCommandUnavailable } from "../onboard/experimental/portable-agent-lifecycle"; import { @@ -41,6 +52,85 @@ export function createDefaultInferenceSetProviderAdapter(): OpenShellProviderAda return createCliOpenShellProviderAdapter(); } +export async function readNativeNvidiaCredentialHandle( + sandboxName: string, + gatewayName: string, + deps: { sleep: (milliseconds: number) => Promise } = { + sleep: sleepInferenceSetRouteConvergence, + }, +): Promise { + const failure = () => + new InferenceSetError( + `OpenShell did not expose a provider-bound NVIDIA credential handle to sandbox '${sandboxName}'. The inference route was not changed.`, + ); + try { + // OpenShell can confirm an attachment before a fresh exec receives its + // environment. This is a read-only probe, so retry only its explicit + // pending signal; never retry invalid handles or ambiguous exec failures. + const result = await retryUntilAsync( + async () => { + const marker = createSandboxExecMarker(); + const capture = await captureSanitizedResolvedOpenshellAsync( + [ + "sandbox", + "exec", + "--name", + sandboxName, + "-g", + gatewayName, + "--", + "sh", + "-c", + buildSandboxExecMarkedCommand(NATIVE_NVIDIA_SCOPED_HANDLE_READ_SCRIPT, marker), + ], + { + ignoreError: true, + includeStderr: true, + includeStreams: true, + outputLimitBytes: 512, + timeout: 30_000, + }, + ); + return { capture, marker }; + }, + { + accept: ({ capture }) => + capture.error !== undefined || + Boolean(capture.signal) || + capture.status !== 75 || + !String(capture.stderr ?? "").includes("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING"), + retryDelaysMs: Array(9).fill(2_000), + sleep: deps.sleep, + }, + ); + const handle = extractSandboxExecCommandStdoutFromStreams(result.capture, result.marker); + if ( + result.capture.status !== 0 || + handle === null || + !NATIVE_NVIDIA_SCOPED_HANDLE_PATTERN.test(handle) + ) { + throw failure(); + } + return handle; + } catch { + // Never include captured output or an OpenShell diagnostic in this error. + throw failure(); + } +} + +export async function readHermesNativeNvidiaCredentialHandleIfNeeded(options: { + agentName: string; + provider: string; + sandboxName: string; + gatewayName: string; + read: (sandboxName: string, gatewayName: string) => Promise; +}): Promise { + if (options.agentName !== "hermes" || options.provider !== NVIDIA_HOSTED_LOGICAL_PROVIDER) { + return undefined; + } + return await options.read(options.sandboxName, options.gatewayName); +} + export type InferenceSetSandboxRouteProbe = ( input: SandboxInferenceInvocationInput, ) => Promise; diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts index 9e4ec0895e3..cb2b42d4a74 100644 --- a/src/lib/actions/inference-set.ts +++ b/src/lib/actions/inference-set.ts @@ -93,6 +93,8 @@ import { completeInferenceSetTelemetry, probeInferenceSetSandboxRouteUntilConverged, providerCommitMayHaveChangedBinding, + readHermesNativeNvidiaCredentialHandleIfNeeded, + readNativeNvidiaCredentialHandle, type RuntimeProviderBundleRegistry, RuntimeProviderSelectionError, requireInferenceSetRuntimeAuthority, @@ -217,6 +219,7 @@ export interface InferenceSetDeps extends InferenceGatewayRestartDeps { resolveContextWindowForModel: (provider: string, model: string) => number | null; rewriteConfigUrlsWithDnsPinning: (value: ConfigValue) => Promise; resolveCredentialValue: (credentialEnv: string) => string; + readNativeNvidiaCredentialHandle: (sandboxName: string, gatewayName: string) => Promise; ensureHttpsPinRuntimeAdapter: EnsureHttpsPinRuntimeAdapterFn; revokeHttpsPinRuntimeAdapterRoute: (routeId: string) => Promise; probeSandboxRoute: InferenceSetSandboxRouteProbe; @@ -351,6 +354,7 @@ function defaultDeps(): InferenceSetDeps { resolveContextWindowForModel, rewriteConfigUrlsWithDnsPinning, resolveCredentialValue: (credentialEnv) => process.env[credentialEnv] ?? "", + readNativeNvidiaCredentialHandle, ensureHttpsPinRuntimeAdapter: (options) => { if (!options.discoverAllowedSourceCidrs) { throw new Error("HTTPS Pin Runtime adapter is missing runtime-provider network authority."); @@ -840,6 +844,7 @@ export function patchHermesInferenceConfig( contextWindow?: number, nativeEndpointUrl?: string, nativeProvider = true, + nativeCredentialHandle?: string, ): { changed: boolean; route: SandboxInferenceConfig } { const before = JSON.stringify(config); const route = getSandboxInferenceConfig( @@ -855,6 +860,7 @@ export function patchHermesInferenceConfig( upstreamProvider: provider, inferenceApi: route.inferenceApi, contextWindow, + nativeCredentialHandle, }); return { changed: before !== JSON.stringify(config), route }; @@ -1473,6 +1479,7 @@ async function runInferenceSetWithoutHostLock( let providerMutation: Awaited> | null = null; let assertProviderCurrentBeforeSelection: (() => Promise) | null = null; + let nativeNvidiaCredentialHandle: string | undefined; let nativeProviderAttachment: NativeProviderAttachment | undefined; let nativeAttachmentChanged = false; let nativeRegistryCommitted = false; @@ -1519,6 +1526,13 @@ async function runInferenceSetWithoutHostLock( }); nativeProviderAttachment = nativeSelection.attachment; nativeAttachmentChanged = nativeSelection.attachmentChanged; + nativeNvidiaCredentialHandle = await readHermesNativeNvidiaCredentialHandleIfNeeded({ + agentName, + provider, + sandboxName, + gatewayName: preparedRoute.gatewayName, + read: deps.readNativeNvidiaCredentialHandle, + }); const providerBinding = httpsPinProviderBinding ?? directProviderBinding; if (providerBinding) { providerMutation = await prepareInferenceSetProviderBinding({ @@ -1790,6 +1804,7 @@ async function runInferenceSetWithoutHostLock( contextWindow, nativeSelection.endpointUrl, selectingNative, + nativeNvidiaCredentialHandle, ); } else { // Recompute the context window for the model being switched to, so it does diff --git a/src/lib/hermes-managed-route.ts b/src/lib/hermes-managed-route.ts index f6c81dd14d4..7544ced2757 100644 --- a/src/lib/hermes-managed-route.ts +++ b/src/lib/hermes-managed-route.ts @@ -2,7 +2,11 @@ // SPDX-License-Identifier: Apache-2.0 import { nativeHostedAgentConfig } from "./inference/native-provider/agent-config.ts"; -import { managedInferenceApiKey } from "./inference-credential.ts"; +import { + NATIVE_NVIDIA_SCOPED_HANDLE_PATTERN, + managedInferenceApiKey, + NVIDIA_INFERENCE_PLACEHOLDER, +} from "./inference-credential.ts"; // Shared inference routing replaces this sentinel at egress. Native NVIDIA // routing instead expands the supervisor-issued environment handle. @@ -43,6 +47,7 @@ export type HermesManagedRoute = { upstreamProvider: string; inferenceApi: string; contextWindow?: number | null; + nativeCredentialHandle?: string; }; function isObjectRecord(value: unknown): value is Record { @@ -80,9 +85,19 @@ export function applyHermesManagedRoute( route: HermesManagedRoute, ): asserts config is Record & HermesManagedRouting { const nativeHosted = nativeHostedAgentConfig(route.upstreamProvider, route.baseUrl); - const apiKey = nativeHosted + let apiKey = nativeHosted ? `\${${nativeHosted.credentialEnv}}` : managedInferenceApiKey(route.baseUrl, HERMES_PROXY_REWRITE_SENTINEL); + if (route.nativeCredentialHandle !== undefined) { + if ( + route.upstreamProvider !== "nvidia-prod" || + apiKey !== NVIDIA_INFERENCE_PLACEHOLDER || + !NATIVE_NVIDIA_SCOPED_HANDLE_PATTERN.test(route.nativeCredentialHandle) + ) { + throw new Error("Hermes native NVIDIA route requires a provider-bound credential handle."); + } + apiKey = route.nativeCredentialHandle; + } const providerName = route.upstreamProvider || "nemoclaw-inference"; const providerKey = hermesProviderKey(providerName); const apiMode = hermesApiMode(route.inferenceApi); diff --git a/src/lib/inference-credential.ts b/src/lib/inference-credential.ts index c0f173031ab..5a641dce6ca 100644 --- a/src/lib/inference-credential.ts +++ b/src/lib/inference-credential.ts @@ -7,6 +7,12 @@ // static resolver alias has no provider identity and is rejected by the // endpoint-bound native provider. export const NVIDIA_INFERENCE_PLACEHOLDER = "${NVIDIA_INFERENCE_API_KEY}"; +export const NATIVE_NVIDIA_SCOPED_HANDLE_PATTERN = + /^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$/u; + +// Emit only a provider-bound handle. A raw credential can never reach stdout. +export const NATIVE_NVIDIA_SCOPED_HANDLE_READ_SCRIPT = + 'if [ -z "${NVIDIA_INFERENCE_API_KEY:-}" ]; then printf "%s\\n" NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING >&2; exit 75; fi; printf "%s" "$NVIDIA_INFERENCE_API_KEY" | LC_ALL=C grep -E "^openshell:resolve:env:(v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY$"'; export function managedInferenceApiKey( baseUrl: string, @@ -21,5 +27,18 @@ export function managedInferenceApiKey( if (/^https:\/\/integrate\.api\.nvidia\.com(?::(?:0*443)?)?(?:[/?#]|(?![\s\S]))/u.test(route)) { throw new Error("Native NVIDIA inference requires https://integrate.api.nvidia.com/v1."); } + let parsed: URL; + try { + parsed = new URL(baseUrl); + } catch { + return fallback; + } + if ( + parsed.protocol === "https:" && + parsed.hostname.replace(/\.+$/u, "") === "integrate.api.nvidia.com" && + parsed.port === "" + ) { + throw new Error("Native NVIDIA inference requires https://integrate.api.nvidia.com/v1."); + } return fallback; } diff --git a/test/agents/hermes/hermes-managed-policy.test.ts b/test/agents/hermes/hermes-managed-policy.test.ts index ada60983568..7483a3b7c79 100644 --- a/test/agents/hermes/hermes-managed-policy.test.ts +++ b/test/agents/hermes/hermes-managed-policy.test.ts @@ -174,6 +174,36 @@ describe("Hermes managed policy", () => { }, ); + it.each([ + "openshell:resolve:env:v7_NVIDIA_INFERENCE_API_KEY", + `openshell:resolve:env:s${"a".repeat(64)}_NVIDIA_INFERENCE_API_KEY`, + ])("accepts a provider-bound native NVIDIA credential handle %s", (apiKey) => { + const policy = buildHermesManagedPolicy( + { ...SETTINGS, baseUrl: NATIVE_NVIDIA_URLS[0], upstreamProvider: "nvidia-prod" }, + {}, + ); + policy.config.model!.api_key = apiKey; + const result = loadWithPython(policy); + expect(result.status, result.stderr).toBe(0); + }); + + it.each([ + "openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", + "openshell:resolve:env:v7_OPENAI_API_KEY", + "openshell:resolve:env:v123456789012345678901_NVIDIA_INFERENCE_API_KEY", + `openshell:resolve:env:s${"A".repeat(64)}_NVIDIA_INFERENCE_API_KEY`, + "sk-raw-policy-credential", + ])("rejects an invalid native NVIDIA credential handle %s", (apiKey) => { + const policy = buildHermesManagedPolicy( + { ...SETTINGS, baseUrl: NATIVE_NVIDIA_URLS[0], upstreamProvider: "nvidia-prod" }, + {}, + ); + policy.config.model!.api_key = apiKey; + const result = loadWithPython(policy); + expect(result.status).toBe(1); + expect(result.stderr).not.toContain(apiKey); + }); + it.each(INVALID_NATIVE_NVIDIA_URLS)( "rejects ambiguous native NVIDIA routing at %j", (baseUrl) => { diff --git a/test/e2e/live/hermes-inference-switch-helpers.ts b/test/e2e/live/hermes-inference-switch-helpers.ts index 7ca841017e5..31d45ba6d10 100644 --- a/test/e2e/live/hermes-inference-switch-helpers.ts +++ b/test/e2e/live/hermes-inference-switch-helpers.ts @@ -106,6 +106,15 @@ export function mockAnthropicSwitchEnabled(runtimeEnv: NodeJS.ProcessEnv = proce ); } +export function useLocalHermesInferenceBaseline( + runtimeEnv: NodeJS.ProcessEnv = process.env, +): boolean { + return ( + (runtimeEnv.NEMOCLAW_SWITCH_PROVIDER ?? SWITCH_PROVIDER) === PUBLIC_NVIDIA_SWITCH_PROVIDER || + mockAnthropicSwitchEnabled(runtimeEnv) + ); +} + export function expectAuthenticatedBaselineInventoryRequest( baseline: Pick | undefined, ): void { @@ -762,12 +771,14 @@ export function expectedApiMode(): string | undefined { // This live lane runs on ubuntu-latest and intentionally uses GNU grep's // POSIX ERE character classes; support tests pin the accepted scalar shapes. export const API_KEY_SHAPE_PATTERN = `^[[:space:]]*api_key:[[:space:]]*("sk-[^"[:space:]]+"|'sk-[^'[:space:]]+'|sk-[^"'[:space:]]+)[[:space:]]*$`; +const NVIDIA_REFERENCE = + "openshell:resolve:env:(v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY"; +export const NVIDIA_API_KEY_SHAPE_PATTERN = `^[[:space:]]*api_key:[[:space:]]*("${NVIDIA_REFERENCE}"|'${NVIDIA_REFERENCE}'|${NVIDIA_REFERENCE})[[:space:]]*$`; export function apiKeyShapeCommand(provider: string = SWITCH_PROVIDER): string[] { - const nativeReference = String.raw`\$\{NVIDIA_INFERENCE_API_KEY\}`; const pattern = provider === PUBLIC_NVIDIA_SWITCH_PROVIDER - ? `^[[:space:]]*api_key:[[:space:]]*("${nativeReference}"|'${nativeReference}'|${nativeReference})[[:space:]]*$` + ? NVIDIA_API_KEY_SHAPE_PATTERN : API_KEY_SHAPE_PATTERN; return ["grep", "-Eq", pattern, "/sandbox/.hermes/config.yaml"]; } diff --git a/test/e2e/live/hermes-inference-switch.test.ts b/test/e2e/live/hermes-inference-switch.test.ts index f89f06afe60..c29fd70be77 100644 --- a/test/e2e/live/hermes-inference-switch.test.ts +++ b/test/e2e/live/hermes-inference-switch.test.ts @@ -32,7 +32,6 @@ import { installHermes, maybeAssertEnvHashStable, parseHermesGatewayPid, - mockAnthropicSwitchEnabled, PROXY_FORBIDDEN_MARKERS, PROXY_RESOLUTION_PROVIDER, parseHermesModelBlock, @@ -49,6 +48,7 @@ import { SWITCH_MODEL, SWITCH_PROVIDER, strictHashPerms, + useLocalHermesInferenceBaseline, } from "./hermes-inference-switch-helpers.ts"; import { PUBLIC_NVIDIA_SWITCH_ATTACHMENT_EVIDENCE, @@ -122,7 +122,7 @@ test( // OpenShell reaches this fixture from its gateway network namespace, where // the runner's loopback address is not routable. - const mockBaseline = mockAnthropicSwitchEnabled() + const mockBaseline = useLocalHermesInferenceBaseline() ? await startFakeOpenAiCompatibleServer({ apiKey: MOCK_BASELINE_API_KEY, chatContent: "PONG", @@ -193,7 +193,6 @@ test( }); const baselineState = registryState(); const baselineSession = structuredClone(baselineState.session); - const baselineRegistry = structuredClone(baselineState.registry.sandboxes?.[SANDBOX_NAME]); const switchBinding = await prepareCompatibleAnthropicSwitchBinding(host, cleanup); const switchEndpointUrl = switchBinding?.endpointUrl ?? null; switchBinding && redactionValues.push(switchBinding.credentialValue); @@ -252,12 +251,16 @@ test( model: SWITCH_MODEL, }); - const config = await sandbox.exec(SANDBOX_NAME, ["cat", "/sandbox/.hermes/config.yaml"], { - artifactName: "hermes-config-yaml", - env: env(), - redactionValues, - timeoutMs: 30_000, - }); + const config = await sandbox.exec( + SANDBOX_NAME, + ["sed", "/^[[:space:]]*api_key:/d", "/sandbox/.hermes/config.yaml"], + { + artifactName: "hermes-config-yaml", + env: env(), + redactionValues, + timeoutMs: 30_000, + }, + ); expect(config.exitCode, resultText(config)).toBe(0); const model = parseHermesModelBlock(config.stdout); expect(model.default).toBe(SWITCH_MODEL); @@ -347,12 +350,12 @@ test( expect(state.session).toEqual(baselineSession); const publicSwitch = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER; const durableEndpointUrl = publicSwitch - ? baselineRegistry?.endpointUrl + ? null : (switchEndpointUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL); const durableCredentialEnv = publicSwitch - ? baselineRegistry?.credentialEnv + ? null : switchEndpointUrl ? "COMPATIBLE_ANTHROPIC_API_KEY" : "COMPATIBLE_API_KEY"; @@ -361,7 +364,7 @@ test( ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.credentialEnv).toBe(durableCredentialEnv); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.preferredInferenceApi).toBe( - publicSwitch ? baselineRegistry?.preferredInferenceApi : RUNTIME_SWITCH_API, + publicSwitch ? null : RUNTIME_SWITCH_API, ); expect(state.registry.sandboxes?.[SANDBOX_NAME]?.nimContainer).toBeNull(); progress.phase("exercise sandbox inference and Hermes API"); diff --git a/test/e2e/support/hermes-inference-switch-command-shape.test.ts b/test/e2e/support/hermes-inference-switch-command-shape.test.ts index 9b319f318dd..f138a6afb46 100644 --- a/test/e2e/support/hermes-inference-switch-command-shape.test.ts +++ b/test/e2e/support/hermes-inference-switch-command-shape.test.ts @@ -13,6 +13,7 @@ import { DEFAULT_HOSTED_INFERENCE_MODEL } from "../fixtures/hosted-inference.ts" import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { API_KEY_SHAPE_PATTERN, + NVIDIA_API_KEY_SHAPE_PATTERN, apiKeyShapeCommand, cleanupHermesSwitch, compatibleAnthropicMetadataArgs, @@ -25,6 +26,7 @@ import { inferenceLocalMaxTokens, installHermes, mockAnthropicSwitchEnabled, + useLocalHermesInferenceBaseline, openAiSurfaceEndpointUrl, openshellGatewayName, parseInferenceRoute, @@ -110,9 +112,9 @@ describe("Hermes inference switch command shape", () => { return import("../live/hermes-inference-switch-helpers.ts"); } - function matchesApiKeyShape(line: string): boolean { + function matchesApiKeyShape(line: string, pattern: string = API_KEY_SHAPE_PATTERN): boolean { return ( - spawnSync("grep", ["-Eq", API_KEY_SHAPE_PATTERN], { + spawnSync("grep", ["-Eq", pattern], { encoding: "utf8", input: `${line}\n`, }).status === 0 @@ -224,27 +226,24 @@ describe("Hermes inference switch command shape", () => { it("uses direct single-line argv for the in-sandbox API-key probe", () => { const command = apiKeyShapeCommand("compatible-anthropic-endpoint"); + const nativeCommand = apiKeyShapeCommand(PUBLIC_NVIDIA_SWITCH_PROVIDER); expect(command).toEqual(["grep", "-Eq", API_KEY_SHAPE_PATTERN, "/sandbox/.hermes/config.yaml"]); - expect(command.every((argument) => !/[\r\n]/u.test(argument))).toBe(true); - }); - - it("accepts only the native NVIDIA credential reference on the native route", () => { - const [command, ...args] = apiKeyShapeCommand(PUBLIC_NVIDIA_SWITCH_PROVIDER); - const matches = (input: string) => - spawnSync(command, args.slice(0, -1), { input, encoding: "utf8" }).status === 0; - expect(matches(" api_key: ${NVIDIA_INFERENCE_API_KEY}\n")).toBe(true); - expect(matches(' api_key: "${NVIDIA_INFERENCE_API_KEY}"\n')).toBe(true); - expect(matches(" api_key: '${NVIDIA_INFERENCE_API_KEY}'\n")).toBe(true); - expect(matches(" api_key: sk-OPENSHELL-PROXY-REWRITE\n")).toBe(false); - expect(matches(" api_key: nvapi-raw-fixture-key\n")).toBe(false); - expect(matches(" api_key: ${NVIDIA_INFERENCE_API_KEY} trailing\n")).toBe(false); + expect(nativeCommand).toEqual([ + "grep", + "-Eq", + NVIDIA_API_KEY_SHAPE_PATTERN, + "/sandbox/.hermes/config.yaml", + ]); + expect([...command, ...nativeCommand].every((argument) => !/[\r\n]/u.test(argument))).toBe( + true, + ); }); it("accepts only complete sk-prefixed YAML scalars", () => { expect( - [" api_key: sk-value", ' api_key: "sk-value"', " api_key: 'sk-value'"].every( - matchesApiKeyShape, + [" api_key: sk-value", ' api_key: "sk-value"', " api_key: 'sk-value'"].every((line) => + matchesApiKeyShape(line), ), ).toBe(true); expect( @@ -253,7 +252,27 @@ describe("Hermes inference switch command shape", () => { " api_key: sk-value trailing", ' api_key: "sk-value', ' api_key: sk-value"', - ].some(matchesApiKeyShape), + ].some((line) => matchesApiKeyShape(line)), + ).toBe(false); + }); + + it("accepts only a provider-bound reference for a native NVIDIA switch", () => { + const reference = "openshell:resolve:env:v1_NVIDIA_INFERENCE_API_KEY"; + expect( + [` api_key: ${reference}`, ` api_key: "${reference}"`, ` api_key: '${reference}'`].every( + (line) => matchesApiKeyShape(line, NVIDIA_API_KEY_SHAPE_PATTERN), + ), + ).toBe(true); + expect( + [ + " api_key: sk-OPENSHELL-PROXY-REWRITE", + " api_key: nvapi-raw-key", + " api_key: ${NVIDIA_INFERENCE_API_KEY}", + " api_key: openshell:resolve:env:NVIDIA_INFERENCE_API_KEY", + ` api_key: ${reference} trailing`, + ` api_key: "${reference}`, + ` api_key: ${reference}"`, + ].some((line) => matchesApiKeyShape(line, NVIDIA_API_KEY_SHAPE_PATTERN)), ).toBe(false); }); @@ -410,7 +429,7 @@ describe("Hermes inference switch command shape", () => { ).toThrow(); }); - it("enables local baseline inference only for the mock Anthropic lane", () => { + it("recognizes only the requested mock Anthropic switch", () => { const mockAnthropic = { NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", @@ -429,6 +448,20 @@ describe("Hermes inference switch command shape", () => { expect(mockAnthropicSwitchEnabled({})).toBe(false); }); + it("uses an authenticated local baseline before native NVIDIA or mock Anthropic switches", () => { + expect(useLocalHermesInferenceBaseline({ NEMOCLAW_SWITCH_PROVIDER: "nvidia-prod" })).toBe(true); + expect( + useLocalHermesInferenceBaseline({ + NEMOCLAW_SWITCH_PROVIDER: "compatible-anthropic-endpoint", + NEMOCLAW_SWITCH_INFERENCE_API: "anthropic-messages", + NEMOCLAW_SWITCH_MOCK_ANTHROPIC: "1", + }), + ).toBe(true); + expect( + useLocalHermesInferenceBaseline({ NEMOCLAW_SWITCH_PROVIDER: "compatible-endpoint" }), + ).toBe(false); + }); + it("does not retry a successful Hermes response from the wrong model", async () => { const probeResult = (stdout: string): ShellProbeResult => ({ exitCode: 0, stdout, stderr: "" }) as ShellProbeResult; diff --git a/test/fixtures/native-nvidia-inference-urls.ts b/test/fixtures/native-nvidia-inference-urls.ts index af0303ac997..c20e92b96e1 100644 --- a/test/fixtures/native-nvidia-inference-urls.ts +++ b/test/fixtures/native-nvidia-inference-urls.ts @@ -13,6 +13,10 @@ export const INVALID_NATIVE_NVIDIA_URLS = [ "https://integrate.api.nvidia.com/./v1", "https://integrate.api.nvidia.com/x/../v1", "https://integrate.api.nvidia.com/%2e/v1", + "https://%69ntegrate.api.nvidia.com/v1", + "https://user@integrate.api.nvidia.com/v1", + "https://integrate.api.nvidia.com./v1", + "https://integrate.api.nvidia.com../v1", "https://integrate.api.nvidia.com/V1", "https://integrate.api.nvidia.com//v1", "https://integrate.api.nvidia.com/v1?", diff --git a/test/generation/providerless-agent-config.test.ts b/test/generation/providerless-agent-config.test.ts index ca9e7ebc2fa..baf1206bceb 100644 --- a/test/generation/providerless-agent-config.test.ts +++ b/test/generation/providerless-agent-config.test.ts @@ -148,6 +148,14 @@ const expectConfigured: Record void> = { expect(config.model.api_key).toBe("${NVIDIA_INFERENCE_API_KEY}"); }, }; +const expectManagedConfigured: Record void> = { + openclaw: expectConfigured.openclaw, + hermes(config) { + expect(config.model.default).toBe("fixture/model"); + expect(config.model.provider).toBe("custom"); + expect(config.model.api_key).toBe("openshell:resolve:env:v1_NVIDIA_INFERENCE_API_KEY"); + }, +}; type InferenceSetCalls = ReturnType["calls"]; const expectCommitted: Record void> = { openclaw(calls) { @@ -256,7 +264,7 @@ describe.each(["openclaw", "hermes"])("providerless %s configuration", (a deps, ); expect(result.inSandboxConfigSynced).toBe(true); - expectConfigured[agent](config); + expectManagedConfigured[agent](config); expectCommitted[agent](deps.calls); expect( deps.calls.captureOpenshell.mock.calls.some( diff --git a/test/helpers/inference-set.ts b/test/helpers/inference-set.ts index 456d7feecb7..161827eedb9 100644 --- a/test/helpers/inference-set.ts +++ b/test/helpers/inference-set.ts @@ -279,6 +279,7 @@ export function createDeps(options: { prepareRunOpenshell?: () => void; rewriteConfigUrlsWithDnsPinning?: (value: ConfigValue) => Promise; resolveCredentialValue?: InferenceSetDeps["resolveCredentialValue"]; + readNativeNvidiaCredentialHandle?: InferenceSetDeps["readNativeNvidiaCredentialHandle"]; ensureHttpsPinRuntimeAdapter?: EnsureHttpsPinRuntimeAdapterFn; revokeHttpsPinRuntimeAdapterRoute?: InferenceSetDeps["revokeHttpsPinRuntimeAdapterRoute"]; probeSandboxRoute?: InferenceSetDeps["probeSandboxRoute"]; @@ -305,6 +306,7 @@ export function createDeps(options: { prepareRunOpenshell: ReturnType; rewriteConfigUrlsWithDnsPinning: ReturnType; resolveCredentialValue: ReturnType; + readNativeNvidiaCredentialHandle: ReturnType; ensureHttpsPinRuntimeAdapter: ReturnType; revokeHttpsPinRuntimeAdapterRoute: ReturnType; probeSandboxRoute: ReturnType; @@ -356,6 +358,10 @@ export function createDeps(options: { options.resolveCredentialValue ?? ((credentialEnv: string) => process.env[credentialEnv] ?? "test-credential-value"), ), + readNativeNvidiaCredentialHandle: vi.fn( + options.readNativeNvidiaCredentialHandle ?? + (async () => "openshell:resolve:env:v1_NVIDIA_INFERENCE_API_KEY"), + ), ensureHttpsPinRuntimeAdapter: vi.fn( options.ensureHttpsPinRuntimeAdapter ?? (async () => ({ @@ -479,6 +485,7 @@ export function createDeps(options: { resolveContextWindowForModel: calls.resolveContextWindowForModel, rewriteConfigUrlsWithDnsPinning: calls.rewriteConfigUrlsWithDnsPinning, resolveCredentialValue: calls.resolveCredentialValue, + readNativeNvidiaCredentialHandle: calls.readNativeNvidiaCredentialHandle, ensureHttpsPinRuntimeAdapter: calls.ensureHttpsPinRuntimeAdapter as unknown as EnsureHttpsPinRuntimeAdapterFn, revokeHttpsPinRuntimeAdapterRoute: