diff --git a/ci/source-architecture-budget.json b/ci/source-architecture-budget.json index f9a7d548779..d25d6e5282b 100644 --- a/ci/source-architecture-budget.json +++ b/ci/source-architecture-budget.json @@ -6,7 +6,7 @@ "src/lib/actions/sandbox/mcp-bridge-contracts.ts": 24, "src/lib/actions/sandbox/process-recovery.ts": 12, "src/lib/adapters/docker/index.ts": 40, - "src/lib/adapters/openshell/client.ts": 17, + "src/lib/adapters/openshell/client.ts": 18, "src/lib/adapters/openshell/command-argv.ts": 17, "src/lib/adapters/openshell/resolve.ts": 22, "src/lib/adapters/openshell/runtime.ts": 41, @@ -19,7 +19,7 @@ "src/lib/cli/terminal-style.ts": 37, "src/lib/core/json-types.ts": 32, "src/lib/core/ports.ts": 87, - "src/lib/core/shell-quote.ts": 20, + "src/lib/core/shell-quote.ts": 21, "src/lib/core/url-utils.ts": 22, "src/lib/core/wait.ts": 30, "src/lib/credentials/store.ts": 44, @@ -57,7 +57,7 @@ "src/lib/onboard/sandbox-gpu-create-run-attempt.ts": 18, "src/lib/onboard/machine/handlers/sandbox.ts": 21, "src/lib/policy/index.ts": 22, - "src/lib/sandbox/config.ts": 18, + "src/lib/sandbox/config.ts": 17, "scripts/checks/run-managed-image-openshell-e2e.ts": 18 } }, diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 56b034bfd93..2b7eda0b7a6 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -877,6 +877,32 @@ parsed = subprocess.run( config = json.loads(parsed.stdout) refreshed = set() +native_refreshed = False + +# A native NVIDIA handle persisted by the host-side config batch belongs to +# the provider revision that issued it. After a supervisor restart, only the +# current revision is available, so replace that exact config field before +# OpenClaw starts. Never copy a raw value or rewrite config for other providers. +models = config.get("models") if isinstance(config, dict) else None +providers = models.get("providers") if isinstance(models, dict) else None +native = providers.get("inference") if isinstance(providers, dict) else None +if isinstance(native, dict) and native.get("baseUrl") == "https://integrate.api.nvidia.com/v1": + key = "NVIDIA_INFERENCE_API_KEY" + scoped = re.compile(rf"^{re.escape(prefix)}(?:v[0-9]{{1,20}}|s[a-f0-9]{{64}})_{key}$") + saved = native.get("apiKey") + state = runtime_state(key) + current = state.get("value", "") + if ( + isinstance(saved, str) + and scoped.fullmatch(saved) + and state.get("kind") == "placeholder" + and isinstance(current, str) + and scoped.fullmatch(current) + and saved != current + ): + native["apiKey"] = current + refreshed.add(key) + native_refreshed = True # Match each canonical placeholder only as an exact token. The OpenShell # placeholder grammar is "openshell:resolve:env:[A-Za-z_][A-Za-z0-9_]*", @@ -1005,7 +1031,7 @@ def walk_for_warnings(value, path): walk_for_warnings(updated, []) -if updated != config: +if updated != config or native_refreshed: with open(config_file, "w", encoding="utf-8") as f: json.dump(updated, f, indent=2) f.write("\n") diff --git a/src/lib/inference-credential.ts b/src/lib/inference-credential.ts index 3348d9706e5..c0f173031ab 100644 --- a/src/lib/inference-credential.ts +++ b/src/lib/inference-credential.ts @@ -1,9 +1,11 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// Both agents expand this reference from the supervisor-issued, scoped -// OpenShell handle at config load. A static resolver alias has no provider -// identity and is rejected by the endpoint-bound native provider. +// The initial agent config expands this reference from the supervisor-issued, +// scoped OpenShell handle. An OpenClaw inference switch materializes that handle +// in its fresh sandbox exec before restarting the older gateway process. A +// 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 function managedInferenceApiKey( diff --git a/src/lib/sandbox/compose-sandbox-config-body.test.ts b/src/lib/sandbox/compose-sandbox-config-body.test.ts index 4978e9ceba0..fa843358c3f 100644 --- a/src/lib/sandbox/compose-sandbox-config-body.test.ts +++ b/src/lib/sandbox/compose-sandbox-config-body.test.ts @@ -2,7 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import type { OpenShellRuntimeSelection } from "../adapters/openshell/runtime-selection"; +import { NVIDIA_INFERENCE_PLACEHOLDER } from "../inference-credential"; +import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../inference/native-nvidia/contract"; import YAML from "yaml"; const { @@ -10,6 +16,7 @@ const { buildOpenClawNativeConfigSetInvocation, composeSandboxConfigBody, hermesConfigAllowsPrivateUrls, + runOpenClawNativeConfigBatchUntilHandleReady, writeSandboxConfig, } = require("./config") as { buildOpenClawNativeConfigBatchInvocation: ( @@ -34,6 +41,12 @@ const { }, ) => string; hermesConfigAllowsPrivateUrls: (config: Record) => boolean; + runOpenClawNativeConfigBatchUntilHandleReady: ( + nativeNvidiaUpdate: boolean, + run: () => { status: number; stderr: string; error?: Error; signal?: string }, + wait?: (ms: number) => void, + warn?: (message: string) => void, + ) => void; writeSandboxConfig: ( sandboxName: string, target: typeof OPENCLAW_TARGET, @@ -144,6 +157,161 @@ describe("composeSandboxConfigBody", () => { ]); }); + it("gives a newly attached native NVIDIA handle to OpenClaw without exposing the raw key", () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-native-config-")); + try { + const executable = path.join(directory, "openclaw"); + fs.writeFileSync(executable, '#!/bin/sh\ncat "$4"\n', { mode: 0o700 }); + const invocation = buildOpenClawNativeConfigBatchInvocation("alpha", [ + { dotpath: "agents.defaults.model.primary", value: "inference/nvidia/model-a" }, + { + dotpath: "models.providers.inference", + value: { + baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + apiKey: NVIDIA_INFERENCE_PLACEHOLDER, + api: "openai-completions", + models: [{ id: "nvidia/model-a" }], + }, + }, + ]); + const command = invocation.args.slice(invocation.args.indexOf("--") + 1); + const handle = "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY"; + const run = (value: string | undefined) => + spawnSync(command[0]!, command.slice(1), { + input: invocation.input, + encoding: "utf8", + timeout: 5_000, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH ?? ""}`, + ...(value === undefined + ? { NVIDIA_INFERENCE_API_KEY: undefined } + : { NVIDIA_INFERENCE_API_KEY: value }), + }, + }); + + const success = run(handle); + expect(success.status, `${success.error?.message ?? ""} ${success.stderr}`).toBe(0); + const batch = JSON.parse(success.stdout) as Array<{ path: string; value: unknown }>; + expect(batch).toEqual([ + { path: "agents.defaults.model.primary", value: "inference/nvidia/model-a" }, + { + path: "models.providers.inference", + value: { + baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, + apiKey: handle, + api: "openai-completions", + models: [{ id: "nvidia/model-a" }], + }, + }, + ]); + expect(invocation.input).not.toContain(handle); + expect(invocation.args.join(" ")).not.toContain(handle); + expect(invocation.input).toContain(NVIDIA_INFERENCE_PLACEHOLDER); + expect(invocation.input).toContain(NVIDIA_HOSTED_NATIVE_ENDPOINT); + + const wrongEndpoint = buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.inference", + value: { + baseUrl: "https://other.example/v1", + apiKey: NVIDIA_INFERENCE_PLACEHOLDER, + }, + }, + ]); + const wrongCommand = wrongEndpoint.args.slice(wrongEndpoint.args.indexOf("--") + 1); + const refused = spawnSync(wrongCommand[0]!, wrongCommand.slice(1), { + input: wrongEndpoint.input, + encoding: "utf8", + timeout: 5_000, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH ?? ""}`, + NVIDIA_INFERENCE_API_KEY: handle, + }, + }); + expect(refused.status).not.toBe(0); + expect(refused.stdout).toBe(""); + } 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 }, + ])( + "refuses invalid native NVIDIA handle $value before config mutation", + ({ value, expectedStatus }) => { + 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 invocation = buildOpenClawNativeConfigBatchInvocation("alpha", [ + { + dotpath: "models.providers.inference", + value: { baseUrl: NVIDIA_HOSTED_NATIVE_ENDPOINT, apiKey: NVIDIA_INFERENCE_PLACEHOLDER }, + }, + ]); + const command = invocation.args.slice(invocation.args.indexOf("--") + 1); + const failed = spawnSync(command[0]!, command.slice(1), { + input: invocation.input, + encoding: "utf8", + timeout: 5_000, + env: { + ...process.env, + PATH: `${directory}:${process.env.PATH ?? ""}`, + NVIDIA_INFERENCE_API_KEY: value, + }, + }); + expect(failed.status).toBe(expectedStatus); + expect(failed.stdout).toBe(""); + expect(failed.stderr).not.toContain("nvapi-do-not-write"); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, + ); + + it("retries only a missing newly attached handle before OpenClaw mutates config", () => { + const pending = { status: 75, stderr: "NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\n" }; + const succeeded = { status: 0, stderr: "" }; + const run = vi.fn().mockReturnValueOnce(pending).mockReturnValueOnce(succeeded); + const wait = vi.fn(); + const warn = vi.fn(); + + runOpenClawNativeConfigBatchUntilHandleReady(true, run, wait, warn); + expect(run).toHaveBeenCalledTimes(2); + expect(wait).toHaveBeenCalledExactlyOnceWith(2_000); + expect(warn).toHaveBeenCalledExactlyOnceWith( + "Native NVIDIA provider handle pending; config attempt 1/10", + ); + + const exhaustedRun = vi.fn().mockReturnValue(pending); + const exhaustedWait = vi.fn(); + expect(() => + runOpenClawNativeConfigBatchUntilHandleReady(true, exhaustedRun, exhaustedWait, vi.fn()), + ).toThrow("Native OpenClaw config command failed after 10 attempt(s)"); + expect(exhaustedRun).toHaveBeenCalledTimes(10); + expect(exhaustedWait).toHaveBeenCalledTimes(9); + }); + + it.each([ + { status: 75, stderr: "unrelated failure" }, + { status: 1, stderr: "NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING" }, + { status: 1, stderr: "Native NVIDIA provider handle is unavailable or invalid" }, + ])("does not retry other native config failures: $status $stderr", (result) => { + const failedRun = vi.fn().mockReturnValue(result); + const wait = vi.fn(); + expect(() => + runOpenClawNativeConfigBatchUntilHandleReady(true, failedRun, wait, vi.fn()), + ).toThrow("Native OpenClaw config command failed after 1 attempt(s)"); + expect(failedRun).toHaveBeenCalledOnce(); + expect(wait).not.toHaveBeenCalled(); + }); + it("pins native writes to the supplied gateway instead of the ambient selection (#11764)", () => { vi.stubEnv("OPENSHELL_GATEWAY", "other-gateway"); const invocation = buildOpenClawNativeConfigSetInvocation( diff --git a/src/lib/sandbox/config.ts b/src/lib/sandbox/config.ts index 556857e076a..da969ee5684 100644 --- a/src/lib/sandbox/config.ts +++ b/src/lib/sandbox/config.ts @@ -57,9 +57,13 @@ const { serializeConfig, }: typeof import("./config-format") = require("./config-format"); const { - OPENSHELL_OPERATION_TIMEOUT_MS, -}: typeof import("../adapters/openshell/timeouts") = require("../adapters/openshell/timeouts"); -const { redactFull }: typeof import("../security/redact") = require("../security/redact"); + buildOpenClawNativeConfigBatchInvocation, + buildOpenClawNativeConfigSetInvocation, + executeOpenClawNativeConfigBatch, + executeOpenClawNativeConfigSet, + runOpenClawNativeConfigBatchUntilHandleReady, + runOpenClawNativeConfigCommand, +}: typeof import("./openclaw-native-config") = require("./openclaw-native-config"); const { loadSandboxCredentialRoute, loadRotateTokenSession, @@ -69,6 +73,8 @@ const { type ConfigObject = import("../security/credential-filter").ConfigObject; type ConfigValue = import("../security/credential-filter").ConfigValue; +import type { OpenClawConfigUpdate } from "./openclaw-native-config"; +export type { OpenClawConfigUpdate } from "./openclaw-native-config"; const { runOpenshellCommand, captureOpenshellCommand } = require("../adapters/openshell/client"); function parseJson(text: string): T { @@ -611,89 +617,6 @@ function recomputeSandboxConfigHash(sandboxName: string, target: AgentConfigTarg privilegedSandboxExec(sandboxName, ["sh", "-c", script]); } -function runOpenClawNativeConfigCommand( - sandboxName: string, - args: string[], - gateway?: string | OpenShellRuntimeSelection, -): void { - validateName(sandboxName, "sandbox name"); - const result = captureOpenshellCommand( - getOpenshellBinary(), - [ - ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), - "sandbox", - "exec", - "--name", - sandboxName, - "--env", - "HOME=/sandbox", - "--", - "openclaw", - "config", - ...args, - ], - { - ...(!gateway || typeof gateway === "string" - ? {} - : { - env: buildSelectedOpenShellSubprocessEnv(gateway), - replaceEnv: true, - }), - ignoreError: true, - includeStreams: true, - maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }, - ); - if (!result.error && !result.signal && result.status === 0) return; - const detail = redactFull(result.error?.message || result.stderr?.trim() || "command failed"); - throw new Error(`Native OpenClaw config command failed: ${detail}`); -} - -function buildOpenClawNativeConfigSetInvocation( - sandboxName: string, - dotpath: string, - value: ConfigValue, - gateway?: string | OpenShellRuntimeSelection, -) { - return buildOpenClawNativeConfigBatchInvocation(sandboxName, [{ dotpath, value }], gateway); -} - -export interface OpenClawConfigUpdate { - dotpath: string; - value: ConfigValue; -} - -function buildOpenClawNativeConfigBatchInvocation( - sandboxName: string, - updates: readonly OpenClawConfigUpdate[], - gateway?: string | OpenShellRuntimeSelection, -) { - return { - ...(!gateway || typeof gateway === "string" - ? {} - : { - env: buildSelectedOpenShellSubprocessEnv(gateway), - replaceEnv: true, - }), - args: [ - ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), - "sandbox", - "exec", - "--name", - sandboxName, - "--env", - "HOME=/sandbox", - "--", - "sh", - "-c", - 'umask 077; file=$(mktemp /tmp/nemoclaw-openclaw-config.XXXXXX) || exit $?; trap \'rm -f "$file"\' EXIT; cat >"$file" || exit $?; openclaw config set --batch-file "$file"', - "nemoclaw-openclaw-config-set-batch", - ], - input: JSON.stringify(updates.map(({ dotpath, value }) => ({ path: dotpath, value }))), - }; -} - function setOpenClawConfigValue( sandboxName: string, dotpath: string, @@ -702,24 +625,16 @@ function setOpenClawConfigValue( ): void { validateName(sandboxName, "sandbox name"); const validation = validateConfigDotpath(dotpath); - if (!validation.ok) { + if (!validation.ok) throw new Error(`Invalid OpenClaw config key '${dotpath}': ${validation.reason}.`); - } - const invocation = buildOpenClawNativeConfigSetInvocation(sandboxName, dotpath, value, gateway); - const result = runOpenshellCommand(getOpenshellBinary(), invocation.args, { - env: invocation.env, - replaceEnv: invocation.replaceEnv, - ignoreError: true, - input: invocation.input, - maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, - stdio: ["pipe", "pipe", "pipe"], - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }); - if (!result.error && !result.signal && result.status === 0) return; - const detail = redactFull( - result.error?.message || String(result.stderr ?? "").trim() || "command failed", + executeOpenClawNativeConfigSet( + getOpenshellBinary(), + CONFIG_CAPTURE_MAX_BUFFER, + sandboxName, + dotpath, + value, + gateway, ); - throw new Error(`Native OpenClaw config command failed: ${detail}`); } function setOpenClawConfigValues( @@ -728,30 +643,20 @@ function setOpenClawConfigValues( gateway?: string | OpenShellRuntimeSelection, ): void { validateName(sandboxName, "sandbox name"); - if (updates.length === 0) { + if (updates.length === 0) throw new Error("Native OpenClaw config update requires at least one value."); - } for (const { dotpath } of updates) { const validation = validateConfigDotpath(dotpath); - if (!validation.ok) { + if (!validation.ok) throw new Error(`Invalid OpenClaw config key '${dotpath}': ${validation.reason}.`); - } } - const invocation = buildOpenClawNativeConfigBatchInvocation(sandboxName, updates, gateway); - const result = runOpenshellCommand(getOpenshellBinary(), invocation.args, { - env: invocation.env, - replaceEnv: invocation.replaceEnv, - ignoreError: true, - input: invocation.input, - maxBuffer: CONFIG_CAPTURE_MAX_BUFFER, - stdio: ["pipe", "pipe", "pipe"], - timeout: OPENSHELL_OPERATION_TIMEOUT_MS, - }); - if (!result.error && !result.signal && result.status === 0) return; - const detail = redactFull( - result.error?.message || String(result.stderr ?? "").trim() || "command failed", + executeOpenClawNativeConfigBatch( + getOpenshellBinary(), + CONFIG_CAPTURE_MAX_BUFFER, + sandboxName, + updates, + gateway, ); - throw new Error(`Native OpenClaw config command failed: ${detail}`); } function unsetOpenClawConfigValue( @@ -760,10 +665,16 @@ function unsetOpenClawConfigValue( gateway?: string | OpenShellRuntimeSelection, ): void { const validation = validateConfigDotpath(dotpath); - if (!validation.ok) { + if (!validation.ok) throw new Error(`Invalid OpenClaw config key '${dotpath}': ${validation.reason}.`); - } - runOpenClawNativeConfigCommand(sandboxName, ["unset", dotpath], gateway); + validateName(sandboxName, "sandbox name"); + runOpenClawNativeConfigCommand( + getOpenshellBinary(), + CONFIG_CAPTURE_MAX_BUFFER, + sandboxName, + ["unset", dotpath], + gateway, + ); } // --------------------------------------------------------------------------- @@ -1361,6 +1272,7 @@ export { resolveAgentConfig, restartSandboxAgentAfterConfigSet, rewriteConfigUrlsWithDnsPinning, + runOpenClawNativeConfigBatchUntilHandleReady, setOpenClawConfigValue, setOpenClawConfigValues, setDotpath, diff --git a/src/lib/sandbox/openclaw-native-config.ts b/src/lib/sandbox/openclaw-native-config.ts new file mode 100644 index 00000000000..a72da9a2cd1 --- /dev/null +++ b/src/lib/sandbox/openclaw-native-config.ts @@ -0,0 +1,235 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// Host-side OpenClaw native config commands and scoped NVIDIA handle materialization. + +import type { OpenShellRuntimeSelection } from "../adapters/openshell/client"; +import type { ConfigValue } from "../security/credential-filter"; +const { + buildSelectedOpenShellSubprocessEnv, + captureOpenshellCommand, + runOpenshellCommand, +}: typeof import("../adapters/openshell/client") = require("../adapters/openshell/client"); +const { + OPENSHELL_OPERATION_TIMEOUT_MS, +}: typeof import("../adapters/openshell/timeouts") = require("../adapters/openshell/timeouts"); +const { shellQuote }: typeof import("../core/shell-quote") = require("../core/shell-quote"); +const { + NVIDIA_INFERENCE_PLACEHOLDER, +}: typeof import("../inference-credential") = require("../inference-credential"); +const { + NVIDIA_HOSTED_NATIVE_ENDPOINT, +}: typeof import("../inference/native-nvidia/contract") = require("../inference/native-nvidia/contract"); +const { + isConfigObject, +}: typeof import("../security/credential-filter") = require("../security/credential-filter"); +const { redactFull }: typeof import("../security/redact") = require("../security/redact"); + +export function runOpenClawNativeConfigCommand( + binary: string, + maxBuffer: number, + sandboxName: string, + args: string[], + gateway?: string | OpenShellRuntimeSelection, +): void { + const result = captureOpenshellCommand( + binary, + [ + ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), + "sandbox", + "exec", + "--name", + sandboxName, + "--env", + "HOME=/sandbox", + "--", + "openclaw", + "config", + ...args, + ], + { + ...(!gateway || typeof gateway === "string" + ? {} + : { + env: buildSelectedOpenShellSubprocessEnv(gateway), + replaceEnv: true, + }), + ignoreError: true, + includeStreams: true, + maxBuffer, + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }, + ); + if (!result.error && !result.signal && result.status === 0) return; + const detail = redactFull(result.error?.message || result.stderr?.trim() || "command failed"); + throw new Error(`Native OpenClaw config command failed: ${detail}`); +} + +export function buildOpenClawNativeConfigSetInvocation( + sandboxName: string, + dotpath: string, + value: ConfigValue, + gateway?: string | OpenShellRuntimeSelection, +) { + return buildOpenClawNativeConfigBatchInvocation(sandboxName, [{ dotpath, value }], gateway); +} + +export interface OpenClawConfigUpdate { + dotpath: string; + value: ConfigValue; +} + +// A provider attached after sandbox creation appears in fresh OpenShell exec +// processes, but not in the existing OpenClaw gateway's environment. The +// gateway restart replaces that process image with its old environment. Pin +// the supervisor-issued handle in the native config batch before restarting; +// the actual credential remains outside the sandbox and endpoint-bound. +const materializeNativeNvidiaHandle = [ + "import json, os, re, sys", + 'handle = os.environ.get("NVIDIA_INFERENCE_API_KEY", "")', + "if not handle:", + ' sys.stderr.write("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING\\n")', + " raise SystemExit(75)", + 'if not re.fullmatch(r"openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_NVIDIA_INFERENCE_API_KEY", handle):', + ' raise SystemExit("Native NVIDIA provider handle is unavailable or invalid")', + 'with open(sys.argv[1], "r+", encoding="utf-8") as stream:', + " updates = json.load(stream)", + " if not isinstance(updates, list):", + ' raise SystemExit("Invalid OpenClaw config batch")', + " matched = 0", + " for update in updates:", + ' if not isinstance(update, dict) or update.get("path") != "models.providers.inference":', + " continue", + ' provider = update.get("value")', + ' if not isinstance(provider, dict) or provider.get("apiKey") != sys.argv[3]:', + " continue", + ' if provider.get("baseUrl") != sys.argv[2]:', + ' raise SystemExit("Native NVIDIA provider endpoint does not match")', + ' provider["apiKey"] = handle', + " matched += 1", + " if matched != 1:", + ' raise SystemExit("Expected one native NVIDIA provider config update")', + " stream.seek(0)", + ' json.dump(updates, stream, separators=(",", ":"))', + " stream.truncate()", +].join("\n"); +export function buildOpenClawNativeConfigBatchInvocation( + sandboxName: string, + updates: readonly OpenClawConfigUpdate[], + gateway?: string | OpenShellRuntimeSelection, +) { + const nativeNvidiaUpdate = updates.some( + ({ dotpath, value }) => + dotpath === "models.providers.inference" && + isConfigObject(value) && + value.apiKey === NVIDIA_INFERENCE_PLACEHOLDER, + ); + const materializeCommand = nativeNvidiaUpdate + ? `python3 -c ${shellQuote(materializeNativeNvidiaHandle)} "$file" ${shellQuote(NVIDIA_HOSTED_NATIVE_ENDPOINT)} ${shellQuote(NVIDIA_INFERENCE_PLACEHOLDER)} || exit $?; ` + : ""; + return { + nativeNvidiaUpdate, + ...(!gateway || typeof gateway === "string" + ? {} + : { + env: buildSelectedOpenShellSubprocessEnv(gateway), + replaceEnv: true, + }), + args: [ + ...(gateway ? ["-g", typeof gateway === "string" ? gateway : gateway.gatewayName] : []), + "sandbox", + "exec", + "--name", + sandboxName, + "--env", + "HOME=/sandbox", + "--", + "sh", + "-c", + `umask 077; file=$(mktemp /tmp/nemoclaw-openclaw-config.XXXXXX) || exit $?; trap 'rm -f "$file"' EXIT; cat >"$file" || exit $?; ${materializeCommand}openclaw config set --batch-file "$file"`, + "nemoclaw-openclaw-config-set-batch", + ], + input: JSON.stringify(updates.map(({ dotpath, value }) => ({ path: dotpath, value }))), + }; +} + +export function executeOpenClawNativeConfigSet( + binary: string, + maxBuffer: number, + sandboxName: string, + dotpath: string, + value: ConfigValue, + gateway?: string | OpenShellRuntimeSelection, +): void { + const invocation = buildOpenClawNativeConfigSetInvocation(sandboxName, dotpath, value, gateway); + const result = runOpenshellCommand(binary, invocation.args, { + env: invocation.env, + replaceEnv: invocation.replaceEnv, + ignoreError: true, + input: invocation.input, + maxBuffer, + stdio: ["pipe", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + if (!result.error && !result.signal && result.status === 0) return; + const detail = redactFull( + result.error?.message || String(result.stderr ?? "").trim() || "command failed", + ); + throw new Error(`Native OpenClaw config command failed: ${detail}`); +} + +export function executeOpenClawNativeConfigBatch( + binary: string, + maxBuffer: number, + sandboxName: string, + updates: readonly OpenClawConfigUpdate[], + gateway?: string | OpenShellRuntimeSelection, +): void { + const invocation = buildOpenClawNativeConfigBatchInvocation(sandboxName, updates, gateway); + runOpenClawNativeConfigBatchUntilHandleReady(invocation.nativeNvidiaUpdate, () => + runOpenshellCommand(binary, invocation.args, { + env: invocation.env, + replaceEnv: invocation.replaceEnv, + ignoreError: true, + input: invocation.input, + maxBuffer, + stdio: ["pipe", "pipe", "pipe"], + timeout: OPENSHELL_OPERATION_TIMEOUT_MS, + }), + ); +} + +type NativeConfigBatchResult = Pick< + ReturnType, + "error" | "signal" | "status" | "stderr" +>; + +export function runOpenClawNativeConfigBatchUntilHandleReady( + nativeNvidiaUpdate: boolean, + run: () => NativeConfigBatchResult, + wait: (ms: number) => void = (ms) => + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms), + warn: (message: string) => void = console.warn, +): void { + // OpenShell 0.0.116 attach can confirm desired state before a fresh process + // receives the new environment. This retry is owned by native inference and + // applies only when the materializer exited before OpenClaw changed config. + const maxAttempts = nativeNvidiaUpdate ? 10 : 1; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + const result = run(); + if (!result.error && !result.signal && result.status === 0) return; + const handlePending = + !result.error && + !result.signal && + result.status === 75 && + String(result.stderr ?? "").includes("NEMOCLAW_NATIVE_PROVIDER_HANDLE_PENDING"); + if (handlePending && attempt < maxAttempts) { + warn(`Native NVIDIA provider handle pending; config attempt ${attempt}/${maxAttempts}`); + wait(2_000); + continue; + } + const detail = redactFull( + result.error?.message || String(result.stderr ?? "").trim() || "command failed", + ); + throw new Error(`Native OpenClaw config command failed after ${attempt} attempt(s): ${detail}`); + } +} diff --git a/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts new file mode 100644 index 00000000000..c99aa6eadeb --- /dev/null +++ b/test/agents/openclaw/runtime/provider-placeholder-refresh.test.ts @@ -0,0 +1,154 @@ +// @ts-nocheck +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFile } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import JSON5 from "json5"; +import { describe, expect, it, vi } from "vitest"; +import { extractShellFunctionFromSource } from "../../../helpers/shell-source"; + +const START_SCRIPT = path.resolve(import.meta.dirname, "../../../../scripts/nemoclaw-start.sh"); +const JSON5_MODULE = path.resolve(import.meta.dirname, "../../../../nemoclaw/node_modules/json5"); + +vi.setConfig({ maxConcurrency: 4 }); + +function execFileResult(file, args, options) { + return new Promise((resolve) => + execFile(file, args, options, (error, stdout, stderr) => + resolve({ + status: Number(error?.code) || (error ? -1 : 0), + stdout, + stderr, + }), + ), + ); +} + +describe.concurrent("native NVIDIA handle refresh", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + async function runRefresh( + config: unknown, + env: Record = {}, + rootMode = false, + runtimePlan: unknown = { credentialBindings: [] }, + ) { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-provider-placeholders-")); + try { + const openclawDir = path.join(tmpDir, ".openclaw"); + const configPath = path.join(openclawDir, "openclaw.json"); + const handoffEnvPath = path.join(tmpDir, "handoff-env"); + const runtimePlanPath = path.join(tmpDir, "messaging-runtime-plan.json"); + const scriptPath = path.join(tmpDir, "run.sh"); + fs.mkdirSync(openclawDir, { recursive: true }); + fs.writeFileSync( + configPath, + `// Native OpenClaw JSON5\n${JSON.stringify(config, null, 2)}\n`, + ); + fs.writeFileSync(runtimePlanPath, JSON.stringify(runtimePlan)); + const fn = extractShellFunctionFromSource(src, "refresh_openclaw_provider_placeholders") + .replaceAll("/sandbox/.openclaw", openclawDir) + .replaceAll("/usr/local/share/nemoclaw/messaging-runtime-plan.json", runtimePlanPath) + .replaceAll("/usr/local/lib/node_modules/openclaw/node_modules/json5", JSON5_MODULE) + .replaceAll("/usr/local/bin/node", process.execPath); + fs.writeFileSync( + scriptPath, + [ + "#!/usr/bin/env bash", + "set -euo pipefail\nrefresh_openclaw_wechat_account_placeholder() { :; }", + ...(rootMode + ? [ + "id() { printf '0\\n'; }", + `STEP_DOWN_PREFIX_SANDBOX=(/bin/bash -c 'env >${JSON.stringify(handoffEnvPath)}; exec "$@"' sandbox-step-down)`, + extractShellFunctionFromSource(src, "run_openclaw_config_as_owner"), + ] + : ['run_openclaw_config_as_owner() { "$@"; }']), + fn, + "refresh_openclaw_provider_placeholders", + ].join("\n"), + { mode: 0o700 }, + ); + const result = await execFileResult("bash", [scriptPath], { + encoding: "utf-8", + env: { PATH: process.env.PATH || "", ...env }, + timeout: 5000, + }); + const updatedConfig = JSON5.parse(fs.readFileSync(configPath, "utf-8")); + const handoffEnv = fs.existsSync(handoffEnvPath) + ? fs.readFileSync(handoffEnvPath, "utf-8") + : ""; + return { config: updatedConfig, handoffEnv, result }; + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + } + + it.each([false, true])( + "refreshes a persisted native NVIDIA handle after provider revision and supervisor restart (root=%s)", + async (rootMode) => { + const oldHandle = "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY"; + const currentHandle = "openshell:resolve:env:v43_NVIDIA_INFERENCE_API_KEY"; + const run = await runRefresh( + { + models: { + providers: { + inference: { + baseUrl: "https://integrate.api.nvidia.com/v1", + apiKey: oldHandle, + }, + }, + }, + channels: { telegram: { botToken: oldHandle } }, + }, + { NVIDIA_INFERENCE_API_KEY: currentHandle }, + rootMode, + ); + + expect(run.result.status, run.result.stderr).toBe(0); + expect(run.config.models.providers.inference.apiKey).toBe(currentHandle); + expect(run.config.channels.telegram.botToken).toBe(oldHandle); + expect(run.result.stderr).toContain( + "Refreshed provider placeholders from OpenShell runtime env: NVIDIA_INFERENCE_API_KEY", + ); + }, + ); + + it.each([ + { + reason: "raw credential in root environment", + endpoint: "https://integrate.api.nvidia.com/v1", + runtime: "nvapi-raw-secret", + rootMode: true, + }, + { + reason: "different endpoint", + endpoint: "https://example.com/v1", + runtime: "openshell:resolve:env:v43_NVIDIA_INFERENCE_API_KEY", + rootMode: false, + }, + { + reason: "missing runtime handle", + endpoint: "https://integrate.api.nvidia.com/v1", + runtime: "", + rootMode: false, + }, + ])( + "keeps a persisted native NVIDIA handle when refresh has $reason", + async ({ endpoint, runtime, rootMode }) => { + const saved = "openshell:resolve:env:v42_NVIDIA_INFERENCE_API_KEY"; + const run = await runRefresh( + { models: { providers: { inference: { baseUrl: endpoint, apiKey: saved } } } }, + runtime ? { NVIDIA_INFERENCE_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("nvapi-raw-secret"); + expect(run.result.stderr).not.toContain("nvapi-raw-secret"); + expect(run.handoffEnv).not.toContain("nvapi-raw-secret"); + }, + ); +}); diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts index 27f910e2528..906ab828665 100644 --- a/test/e2e/live/openclaw-inference-switch.test.ts +++ b/test/e2e/live/openclaw-inference-switch.test.ts @@ -227,10 +227,6 @@ async function proveSelectedMockBaselineAuthentication( ).toContainEqual(expectedRequest); } -function stripAnsi(value: string): string { - return value.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g, ""); -} - function parsePortEnv(name: string, fallback: number): number { const raw = process.env[name]; if (!raw) return fallback; @@ -534,7 +530,7 @@ async function openclawGatewayPid(sandbox: SandboxClient, home: string): Promise } async function getRouteOutput(host: HostCliClient, home: string): Promise { - return runNemoclaw(host, home, ["inference", "get"], { + return runNemoclaw(host, home, ["inference", "get", "--json"], { artifactName: "nemoclaw-inference-get-after-switch", timeoutMs: COMMAND_TIMEOUT_MS, }); @@ -622,7 +618,24 @@ async function readAndAssertOpenClawConfig( ): Promise { const configResult = await sandbox.exec( SANDBOX_NAME, - ["cat", "/sandbox/.openclaw/openclaw.json"], + expected.nativeNvidia + ? [ + "node", + "-e", + [ + 'const fs = require("node:fs");', + 'const config = JSON.parse(fs.readFileSync("/sandbox/.openclaw/openclaw.json", "utf8"));', + "const provider = config.models?.providers?.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");', + "delete provider.apiKey;", + "process.stdout.write(JSON.stringify(config));", + ].join(" "), + ] + : ["cat", "/sandbox/.openclaw/openclaw.json"], { artifactName: expected.artifactName, env: commandEnv(home), @@ -645,7 +658,7 @@ async function readAndAssertOpenClawConfig( ? "https://inference.local" : "https://inference.local/v1", ); - expect(provider?.apiKey).toBe(expected.nativeNvidia ? "${NVIDIA_INFERENCE_API_KEY}" : "unused"); + expect(provider?.apiKey).toBe(expected.nativeNvidia ? undefined : "unused"); expect(provider?.api).toBe(expected.inferenceApi); expect(selectedModel?.name).toBe(expectedPrimary); return selectedModel; @@ -1156,12 +1169,16 @@ test( }); const useMockBaseline = - SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"; + SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER || + (SWITCH_PROVIDER === "compatible-anthropic-endpoint" && SWITCH_MOCK_ANTHROPIC === "1"); // OpenShell reaches this fixture from its gateway network namespace, where // the runner's loopback address is not routable. const baselineProvider: FakeOpenAiCompatibleServer | undefined = useMockBaseline ? await startMockOpenClawBaselineProvider(progress) : undefined; + cleanup.trackDisposable("close baseline inference provider", async () => { + await baselineProvider?.close(); + }); const publicApiKey = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER ? requirePublicNvidiaSwitchKey(secrets.required("NVIDIA_API_KEY")) @@ -1187,9 +1204,6 @@ test( cleanup.trackDisposable("close switched Anthropic provider", async () => { await mockProvider?.close(); }); - cleanup.trackDisposable("close baseline inference provider", async () => { - await baselineProvider?.close(); - }); const customDockerfile = writeCustomOpenClawDockerfile(home); cleanup.trackGateway(host, "nemoclaw", { artifactName: "cleanup-openshell-gateway-destroy-openclaw-inference-switch", @@ -1321,9 +1335,9 @@ test( progress.phase("inspect route configuration and recorded state"); const route = await getRouteOutput(host, home); expect(route.exitCode, resultText(route)).toBe(0); - const plainRoute = stripAnsi(resultText(route)); - expect(plainRoute).toContain(`Provider: ${SWITCH_PROVIDER}`); - expect(plainRoute).toContain(`Model: ${SWITCH_MODEL}`); + const routeState = JSON.parse(route.stdout) as { provider?: unknown; model?: unknown }; + expect(routeState.provider).toBe(SWITCH_PROVIDER); + expect(routeState.model).toBe(SWITCH_MODEL); await assertOpenClawConfig(sandbox, home, { model: SWITCH_MODEL, inferenceApi: SWITCH_INFERENCE_API, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 03d57850631..fa6d9162978 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -849,6 +849,7 @@ "test/e2e/support/e2e-clients.test.ts", "test/e2e/support/inference-switch-workflow-boundary.test.ts", "test/e2e/support/managed-image-receipt.test.ts", + "test/e2e/support/openclaw-inference-switch-baseline.test.ts", "test/e2e/support/openclaw-inference-switch-helpers.test.ts", "test/e2e/support/public-nvidia-switch-provider.test.ts", "test/security/admin-approval-helper.test.ts", diff --git a/test/e2e/support/openclaw-inference-switch-baseline.test.ts b/test/e2e/support/openclaw-inference-switch-baseline.test.ts new file mode 100644 index 00000000000..6f68c12102e --- /dev/null +++ b/test/e2e/support/openclaw-inference-switch-baseline.test.ts @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; + +import { afterEach, expect, it, vi } from "vitest"; + +const captured = vi.hoisted(() => ({ test: vi.fn() })); +vi.mock("../fixtures/e2e-test.ts", async () => ({ + expect: (await import("vitest")).expect, + test: captured.test, +})); +vi.mock("../fixtures/managed-image-receipt.ts", () => ({ + selectedE2eManagedImageReference: () => "example.invalid/openclaw@sha256:" + "a".repeat(64), +})); + +const disposables: Array<() => unknown> = []; +afterEach(async () => { + for (const dispose of disposables.splice(0).reverse()) await dispose(); + vi.doUnmock("../live/openclaw-inference-switch-helpers.ts"); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +async function loadNativeSwitchRun() { + vi.resetModules(); + captured.test.mockClear(); + vi.stubEnv("NEMOCLAW_SWITCH_PROVIDER", "nvidia-prod"); + vi.stubEnv("NEMOCLAW_SWITCH_MOCK_ANTHROPIC", "0"); + const exists = fs.existsSync; + vi.spyOn(fs, "existsSync").mockImplementation((file) => + String(file).endsWith("bin/nemoclaw.js") ? true : exists(file), + ); + await import("../live/openclaw-inference-switch.test.ts"); + const { startTestProgress } = await import("../fixtures/progress.ts"); + const progress = startTestProgress( + "native switch baseline", + captured.test.mock.calls[0]![1].meta.e2ePhases, + { logLine: () => undefined }, + ); + disposables.push(() => progress.stop()); + const run = captured.test.mock.calls[0]![2] as (input: object) => Promise; + 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(), + }, + 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 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"); +}); + +it("closes the mock baseline when public key retrieval fails", async () => { + const close = vi.fn(async () => undefined); + vi.doMock("../live/openclaw-inference-switch-helpers.ts", async (importOriginal) => ({ + ...(await importOriginal()), + startMockOpenClawBaselineProvider: async () => ({ close }), + })); + const { progress, run } = await loadNativeSwitchRun(); + const missingKey = new Error("NVIDIA_API_KEY unavailable"); + const registered = new Map unknown>(); + await expect( + run({ + artifacts: { target: { declare: vi.fn() } }, + cleanup: { + trackDisposable: (name: string, dispose: () => unknown) => registered.set(name, dispose), + trackGateway: vi.fn(), + trackSandbox: vi.fn(), + }, + host: { command: vi.fn() }, + progress, + runtimeProvider: { requireAvailable: vi.fn() }, + sandbox: { openshell: vi.fn() }, + secrets: { + required: vi.fn(() => { + throw missingKey; + }), + }, + }), + ).rejects.toBe(missingKey); + const dispose = registered.get("close baseline inference provider"); + expect(dispose).toBeDefined(); + expect(close).not.toHaveBeenCalled(); + await dispose?.(); + expect(close).toHaveBeenCalledOnce(); +});