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
19 changes: 19 additions & 0 deletions src/lib/actions/inference-set-gateway-route-containment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,25 @@ describe("runtime shared gateway route containment", () => {
delete process.env[HTTPS_PIN_RUNTIME_ADAPTER_PROVIDER_CREDENTIAL_ENV];
});

it("retains native Hermes metadata when switching models on the same provider", () => {
const metadata = {
endpointUrl: "https://integrate.api.nvidia.com/v1",
credentialEnv: "NVIDIA_INFERENCE_API_KEY",
preferredInferenceApi: "openai-completions",
};
const baseline = entry("hermes-switch", { agent: "hermes", ...metadata });
const prepared = prepareInferenceSetRoute({
entry: baseline,
sandboxName: baseline.name,
provider: "nvidia-prod",
model: "nvidia/nemotron-3-super-120b-a12b",
customRoute: {},
session: null,
sandboxes: [baseline],
});
expect(prepared.preliminaryRegistryMetadata).toMatchObject(metadata);
});

it("rejects an ambient gateway endpoint before OpenShell prep or state mutation", async () => {
vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://other.example.test");
const deps = createDeps({
Expand Down
6 changes: 6 additions & 0 deletions test/e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,12 @@ Changes to shared catalogue execution paths select every catalogue target.
The `openclaw-inference-switch` target owns fresh custom-image route initialization.
Its fixture contains only a different baked model and stale limits.
The target requires onboarding to create the selected model without those limits, then preserves that native configuration through restart and rebuild.
The OpenClaw native NVIDIA and mock Anthropic switch variants start with an authenticated local OpenAI-compatible fixture.
The native NVIDIA destination uses the public endpoint and its public credential only after switching.
Route assertions use JSON fields so terminal column alignment does not affect the result.
Hermes native installation uses the public NVIDIA provider before its same-provider model switch.
The Hermes native switch derives its baseline model expectation from the environment passed to installation.
Its later proxy-resolution probe pairs the public NVIDIA credential with the public endpoint.

Most entries use one ID for catalogue selection, evidence, and artifacts.
Matrix-style targets use one target ID for evidence and artifacts, with separate catalogue IDs and shards for each concrete execution.
Expand Down
26 changes: 21 additions & 5 deletions test/e2e/live/hermes-inference-switch-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import type { AddressInfo } from "node:net";
import os from "node:os";
import path from "node:path";

import { resolveAgentInferenceApi } from "../../../src/lib/inference/config.ts";
import {
DEFAULT_CLOUD_MODEL,
resolveAgentInferenceApi,
} from "../../../src/lib/inference/config.ts";
import { NVIDIA_HOSTED_NATIVE_ENDPOINT } from "../../../src/lib/inference/native-nvidia/index.ts";
import { NATIVE_NVIDIA_AUTH_HEADER_SCRIPT } from "../../../src/lib/inference/native-nvidia/contract.ts";
import { execTimeout } from "../../helpers/timeouts.ts";
Expand Down Expand Up @@ -182,7 +185,12 @@ export function env(apiKey?: string, extra: NodeJS.ProcessEnv = {}): NodeJS.Proc
NEMOCLAW_SANDBOX_NAME: SANDBOX_NAME,
OPENSHELL_GATEWAY: openshellGatewayName(),
};
apiKey && Object.assign(out, { NVIDIA_INFERENCE_API_KEY: apiKey });
apiKey &&
Object.assign(out, {
NVIDIA_INFERENCE_API_KEY: apiKey,
NEMOCLAW_PROVIDER: "build",
NEMOCLAW_MODEL: process.env.NEMOCLAW_MODEL ?? DEFAULT_CLOUD_MODEL,
});
USE_COMPATIBLE_HOSTED &&
apiKey &&
Object.assign(out, {
Expand Down Expand Up @@ -231,7 +239,10 @@ export async function prepareProxyResolutionRoute({
redactionValues: string[];
}): Promise<{ model: string; requestOffset: number }> {
const endpoint =
mockBaseline?.baseUrl ?? process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL;
mockBaseline?.baseUrl ??
(USE_COMPATIBLE_HOSTED
? (process.env.NEMOCLAW_ENDPOINT_URL ?? DEFAULT_HOSTED_INFERENCE_BASE_URL)
: NVIDIA_HOSTED_NATIVE_ENDPOINT);
const model = mockBaseline ? PROXY_RESOLUTION_MODEL : SWITCH_MODEL;
const requestOffset = mockBaseline?.requests().length ?? 0;

Expand Down Expand Up @@ -755,8 +766,13 @@ export function expectedApiMode(): string | undefined {
// POSIX ERE character classes; support tests pin the accepted scalar shapes.
export const API_KEY_SHAPE_PATTERN = `^[[:space:]]*api_key:[[:space:]]*("sk-[^"[:space:]]+"|'sk-[^'[:space:]]+'|sk-[^"'[:space:]]+)[[:space:]]*$`;

export function apiKeyShapeCommand(): string[] {
return ["grep", "-Eq", API_KEY_SHAPE_PATTERN, "/sandbox/.hermes/config.yaml"];
export function apiKeyShapeCommand(provider: 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:]]*$`
: API_KEY_SHAPE_PATTERN;
return ["grep", "-Eq", pattern, "/sandbox/.hermes/config.yaml"];
}

export async function apiKeyShape(sandbox: SandboxClient): Promise<ShellProbeResult> {
Expand Down
12 changes: 7 additions & 5 deletions test/e2e/live/hermes-inference-switch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,11 @@ test(
expect(baselineRoute.exitCode, resultText(baselineRoute)).toBe(0);
expect(parseInferenceRoute(resultText(baselineRoute))).toEqual({
provider: mockBaseline ? "compatible-endpoint" : PUBLIC_NVIDIA_SWITCH_PROVIDER,
model: hostedInstallModel(installEnv),
model: hostedInstallModel(env(apiKey, installEnv)),
});
const baselineSession = structuredClone(registryState().session);
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);
Expand Down Expand Up @@ -338,12 +340,12 @@ test(
expect(state.session).toEqual(baselineSession);
const publicSwitch = SWITCH_PROVIDER === PUBLIC_NVIDIA_SWITCH_PROVIDER;
const durableEndpointUrl = publicSwitch
? null
? baselineRegistry?.endpointUrl
: (switchEndpointUrl ??
process.env.NEMOCLAW_ENDPOINT_URL ??
DEFAULT_HOSTED_INFERENCE_BASE_URL);
const durableCredentialEnv = publicSwitch
? null
? baselineRegistry?.credentialEnv
: switchEndpointUrl
? "COMPATIBLE_ANTHROPIC_API_KEY"
: "COMPATIBLE_API_KEY";
Expand All @@ -352,7 +354,7 @@ test(
);
expect(state.registry.sandboxes?.[SANDBOX_NAME]?.credentialEnv).toBe(durableCredentialEnv);
expect(state.registry.sandboxes?.[SANDBOX_NAME]?.preferredInferenceApi).toBe(
publicSwitch ? null : RUNTIME_SWITCH_API,
publicSwitch ? baselineRegistry?.preferredInferenceApi : RUNTIME_SWITCH_API,
);
expect(state.registry.sandboxes?.[SANDBOX_NAME]?.nimContainer).toBeNull();
progress.phase("exercise sandbox inference and Hermes API");
Expand Down
50 changes: 50 additions & 0 deletions test/e2e/live/openclaw-inference-switch-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@
// Fixture and response helpers shared by the openclaw-inference-switch live
// target and fast e2e-support tests without gating on NEMOCLAW_RUN_LIVE_E2E=1.

import type { HostCliClient } from "../fixtures/clients/host.ts";
import type { SandboxClient } from "../fixtures/clients/sandbox.ts";
import type { ShellProbeResult } from "../fixtures/shell-probe.ts";
import { CLI_ENTRYPOINT } from "../fixtures/paths.ts";
import type { RetryFailureClass } from "../../../tools/e2e/retry-evidence.mts";
import {
startFakeOpenAiCompatibleServer,
Expand Down Expand Up @@ -188,3 +192,49 @@ export function mockBaselineInference(endpointUrl: string): BaselineInferenceCon
},
};
}

/** Read the structured route through the same host CLI used by the live scenario. */
export async function getRouteOutput(
host: HostCliClient,
options: { env: NodeJS.ProcessEnv; timeoutMs: number },
): Promise<ShellProbeResult> {
return host.command("node", [CLI_ENTRYPOINT, "inference", "get", "--json"], {
...options,
artifactName: "nemoclaw-inference-get-after-switch",
});
}

/** Validate the native handle inside the sandbox before artifact redaction. */
export async function readOpenClawConfig(
sandbox: SandboxClient,
sandboxName: string,
options: {
env: NodeJS.ProcessEnv;
timeoutMs: number;
artifactName: string;
nativeNvidia?: boolean;
},
): Promise<ShellProbeResult> {
return sandbox.exec(
sandboxName,
options.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: options.artifactName, env: options.env, timeoutMs: options.timeoutMs },
);
}
46 changes: 12 additions & 34 deletions test/e2e/live/openclaw-inference-switch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts";
import { runBoundedRetry } from "../../../tools/e2e/retry-evidence.mts";
import type { ShellProbeResult } from "../fixtures/shell-probe.ts";
import {
getRouteOutput,
readOpenClawConfig,
agentReplyContainsToken,
anthropicToolCount,
classifyExhaustedPostSwitchEvidence,
Expand Down Expand Up @@ -530,13 +532,6 @@ async function openclawGatewayPid(sandbox: SandboxClient, home: string): Promise
return result.stdout.trim();
}

async function getRouteOutput(host: HostCliClient, home: string): Promise<ShellProbeResult> {
return runNemoclaw(host, home, ["inference", "get", "--json"], {
artifactName: "nemoclaw-inference-get-after-switch",
timeoutMs: COMMAND_TIMEOUT_MS,
});
}

async function assertRegistryAndSession(
home: string,
options: { mockProvider?: MockAnthropicProvider; sandbox: SandboxClient },
Expand Down Expand Up @@ -617,32 +612,12 @@ async function readAndAssertOpenClawConfig(
nativeNvidia?: boolean;
},
): Promise<OpenClawModelConfig | undefined> {
const configResult = await sandbox.exec(
SANDBOX_NAME,
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),
timeoutMs: COMMAND_TIMEOUT_MS,
},
);
const configResult = await readOpenClawConfig(sandbox, SANDBOX_NAME, {
nativeNvidia: expected.nativeNvidia,
artifactName: expected.artifactName,
env: commandEnv(home),
timeoutMs: COMMAND_TIMEOUT_MS,
});
expect(configResult.exitCode, resultText(configResult)).toBe(0);
const config = JSON.parse(configResult.stdout) as OpenClawConfig;
const expectedProviderKey =
Expand Down Expand Up @@ -1334,7 +1309,10 @@ test(
}

progress.phase("inspect route configuration and recorded state");
const route = await getRouteOutput(host, home);
const route = await getRouteOutput(host, {
env: commandEnv(home),
timeoutMs: COMMAND_TIMEOUT_MS,
});
expect(route.exitCode, resultText(route)).toBe(0);
const routeState = JSON.parse(route.stdout) as { provider?: unknown; model?: unknown };
expect(routeState.provider).toBe(SWITCH_PROVIDER);
Expand Down
56 changes: 55 additions & 1 deletion test/e2e/support/hermes-inference-switch-command-shape.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,13 @@ import {
describe("Hermes inference switch command shape", () => {
afterEach(() => vi.unstubAllEnvs());

async function nativeSwitchHelpers() {
vi.stubEnv("NEMOCLAW_E2E_USE_HOSTED_INFERENCE", "0");
vi.stubEnv("NEMOCLAW_MODEL", undefined);
vi.resetModules();
return import("../live/hermes-inference-switch-helpers.ts");
}

function matchesApiKeyShape(line: string): boolean {
return (
spawnSync("grep", ["-Eq", API_KEY_SHAPE_PATTERN], {
Expand Down Expand Up @@ -156,12 +163,24 @@ describe("Hermes inference switch command shape", () => {
});

it("uses direct single-line argv for the in-sandbox API-key probe", () => {
const command = apiKeyShapeCommand();
const command = apiKeyShapeCommand("compatible-anthropic-endpoint");

expect(command).toEqual(["grep", "-Eq", API_KEY_SHAPE_PATTERN, "/sandbox/.hermes/config.yaml"]);
expect(command.every((argument) => !/[\r\n]/u.test(argument))).toBe(true);
});

it("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);
});

it("accepts only complete sk-prefixed YAML scalars", () => {
expect(
[" api_key: sk-value", ' api_key: "sk-value"', " api_key: 'sk-value'"].every(
Expand Down Expand Up @@ -190,6 +209,41 @@ describe("Hermes inference switch command shape", () => {
).toBe("initial-hosted-model");
});

it("derives the native baseline model from the install environment", async () => {
const { env } = await nativeSwitchHelpers();
const installEnv = env("nvapi-public-fixture-key");
expect(hostedInstallModel(installEnv)).toBe("nvidia/nemotron-3-super-120b-a12b");
});

it("keeps the public proxy-resolution credential on the public NVIDIA endpoint", async () => {
const { prepareProxyResolutionRoute } = await nativeSwitchHelpers();
const command = vi.fn().mockResolvedValue({
exitCode: 0,
stderr: "",
stdout: "Type: openai\nCredentials: NVIDIA_INFERENCE_API_KEY\nConfig: OPENAI_BASE_URL\n",
});
await prepareProxyResolutionRoute({
apiKey: "nvapi-public-fixture-key",
host: { command } as unknown as HostCliClient,
mockBaseline: undefined,
redactionValues: ["nvapi-public-fixture-key"],
});
expect(command.mock.calls[0]).toEqual([
"openshell",
expect.arrayContaining([
"provider",
"create",
"--credential",
"NVIDIA_INFERENCE_API_KEY",
"OPENAI_BASE_URL=https://integrate.api.nvidia.com/v1",
]),
expect.objectContaining({
env: expect.objectContaining({ NVIDIA_INFERENCE_API_KEY: "nvapi-public-fixture-key" }),
redactionValues: ["nvapi-public-fixture-key"],
}),
]);
});

it("keeps proxy-resolution evidence on a dedicated OpenAI provider", async () => {
const command = vi
.fn()
Expand Down
Loading