Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions ci/source-architecture-budget.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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
}
},
Expand Down
28 changes: 27 additions & 1 deletion scripts/nemoclaw-start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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_]*",
Expand Down Expand Up @@ -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")
Expand Down
8 changes: 5 additions & 3 deletions src/lib/inference-credential.ts
Original file line number Diff line number Diff line change
@@ -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<T extends string>(
Expand Down
168 changes: 168 additions & 0 deletions src/lib/sandbox/compose-sandbox-config-body.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,21 @@
// 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 {
buildOpenClawNativeConfigBatchInvocation,
buildOpenClawNativeConfigSetInvocation,
composeSandboxConfigBody,
hermesConfigAllowsPrivateUrls,
runOpenClawNativeConfigBatchUntilHandleReady,
writeSandboxConfig,
} = require("./config") as {
buildOpenClawNativeConfigBatchInvocation: (
Expand All @@ -34,6 +41,12 @@ const {
},
) => string;
hermesConfigAllowsPrivateUrls: (config: Record<string, unknown>) => 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,
Expand Down Expand Up @@ -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(
Expand Down
Loading