diff --git a/docs/inference/use-shared-gateway-routes.mdx b/docs/inference/use-shared-gateway-routes.mdx
index 421c5c27378..6cab8d8691d 100644
--- a/docs/inference/use-shared-gateway-routes.mdx
+++ b/docs/inference/use-shared-gateway-routes.mdx
@@ -26,6 +26,25 @@ Onboarding exits before provider or route mutation when those fields differ.
Do not run `openshell inference set` directly on a shared NemoClaw gateway because that bypasses the registry compatibility checks.
+
+
+## Change the Live Route With Inference Set
+
+Use `$$nemoclaw inference set` to change a registered sandbox's provider or model outside onboarding and `connect`.
+
+```bash
+$$nemoclaw inference set --provider --model
+```
+
+When only the provider or model differs, the command warns immediately before it re-points the shared route.
+The warning names every affected registered sandbox and its recorded provider and model.
+Those sandboxes use the new live route until `connect`, onboarding, or another `inference set` command re-points it.
+
+For the same provider name, custom endpoint, API-family, and credential environment-variable values must remain compatible.
+Incomplete routes and invalid gateway bindings also stop the command before route, agent config, or registry mutation.
+
+
+
## Restore a Sandbox Route When You Connect
Connect to a sandbox when you want its recorded provider and model to become live again.
@@ -70,7 +89,6 @@ NemoClaw fails closed when it cannot prove that a route change preserves the pro
- For a provider-global identity conflict, align the endpoint, API family, and credential environment-variable name, or remove a sandbox you no longer need.
- For incomplete legacy custom-route metadata, back up and remove the affected sandbox, then re-onboard it with an explicit endpoint and API family.
- For an invalid gateway binding, restore known-good `gatewayName` and `gatewayPort` metadata from a trusted backup, or back up and remove the sandbox before re-onboarding it.
-- For a runtime `inference set` conflict, align the registered sandbox routes or remove the conflicting sandbox before retrying.
Refer to [Troubleshooting a Shared Inference Route Conflict](../../reference/troubleshooting#a-shared-inference-route-conflicts-with-another-sandbox) for the recovery commands.
diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx
index ddb3ec8a7c3..9b5ec989b6d 100644
--- a/docs/reference/commands.mdx
+++ b/docs/reference/commands.mdx
@@ -3372,9 +3372,18 @@ Switch the active inference provider or model for a NemoClaw-managed Hermes sand
By default, the command syncs the default registered sandbox.
-Each OpenShell gateway exposes one inference route to every sandbox registered on that gateway. Before changing the route, NemoClaw compares the requested provider and model with every same-gateway registry entry, including stopped sandboxes. Custom compatible routes must also have matching normalized endpoint URLs and API families. Provider-global credential environment-variable names must also match for the same provider name. If a route conflicts or a legacy custom route lacks enough endpoint or API-family metadata to prove compatibility, the command exits non-zero before changing the OpenShell route, agent config, or host registry and names the conflicting sandboxes. Align those sandboxes to the same route or remove a conflicting sandbox that you no longer need.
-
-Onboarding and `connect` can time-share compatible provider and model routes without replacing provider-global configuration. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for the onboarding warnings, compatibility fields, and status drift report.
+Each OpenShell gateway exposes one inference route to every sandbox registered on that gateway.
+Before changing the route, NemoClaw compares it with every same-gateway registry entry, including stopped sandboxes.
+When only the provider or model differs, the command names the affected sandboxes and warns immediately before it re-points the shared route.
+Those sandboxes use the new live route until `connect`, onboarding, or another `inference set` command re-points it.
+
+For the same provider name, custom compatible routes must have matching normalized endpoint URLs and API families.
+Provider-global credential environment-variable names must also match.
+Endpoint, API-family, credential, incomplete-route, and invalid-gateway-binding conflicts remain fail-closed.
+The command exits nonzero before changing the OpenShell route, agent config, or host registry and names the conflicting sandboxes.
+Align the provider-global configuration, repair incomplete metadata, or remove a conflicting sandbox that you no longer need.
+
+Onboarding, `connect`, and `inference set` can time-share compatible provider and model routes without replacing provider-global configuration. Refer to [Use Shared Gateway Routes](../inference/manage-inference/use-shared-gateway-routes) for route-change warnings, compatibility fields, and the status drift report.
```bash
$$nemoclaw inference set --provider --model [--sandbox ] [--no-verify] [--endpoint-url ] [--credential-env ] [--inference-api ]
diff --git a/src/lib/actions/inference-set-gateway-route-containment.test.ts b/src/lib/actions/inference-set-gateway-route-containment.test.ts
index 5da0d4e2661..418fc6f3888 100644
--- a/src/lib/actions/inference-set-gateway-route-containment.test.ts
+++ b/src/lib/actions/inference-set-gateway-route-containment.test.ts
@@ -80,7 +80,7 @@ describe("runtime shared gateway route containment", () => {
expect(deps.calls.updateSandbox).not.toHaveBeenCalled();
});
- it("rejects a same-gateway conflict before OpenShell, config, or registry mutation (#6315)", async () => {
+ it("warns and re-points a same-gateway provider/model-only route (#11890)", async () => {
const deps = createDeps({
config: {},
entries: [entry("alpha"), entry("stopped-peer")],
@@ -92,13 +92,31 @@ describe("runtime shared gateway route containment", () => {
{ provider: "nvidia-prod", model: "nvidia/model-b", sandboxName: "alpha" },
deps,
),
- ).rejects.toThrow("stopped-peer");
+ ).resolves.toMatchObject({ sandboxName: "alpha", model: "nvidia/model-b" });
- expect(deps.calls.captureOpenshell).not.toHaveBeenCalled();
- expect(deps.calls.readSandboxConfig).not.toHaveBeenCalled();
- expect(deps.calls.writeSandboxConfig).not.toHaveBeenCalled();
- expect(deps.calls.updateSandbox).not.toHaveBeenCalled();
- expect(deps.calls.updateSession).not.toHaveBeenCalled();
+ expect(deps.calls.captureOpenshell).toHaveBeenCalledWith(
+ [
+ "inference",
+ "set",
+ "-g",
+ "nemoclaw",
+ "--provider",
+ "nvidia-prod",
+ "--model",
+ "nvidia/model-b",
+ ],
+ expect.objectContaining({ ignoreError: true }),
+ );
+ const messages = deps.calls.log.mock.calls.map(([message]) => message);
+ const warningIndex = messages.findIndex((message) =>
+ message.includes("Changing inference for 'alpha' will re-point"),
+ );
+ const mutationIndex = messages.findIndex((message) =>
+ message.includes("Setting OpenShell inference route"),
+ );
+ expect(warningIndex).toBeGreaterThanOrEqual(0);
+ expect(messages[warningIndex]).toContain("'stopped-peer' (nvidia-prod / nvidia/model-a)");
+ expect(warningIndex).toBeLessThan(mutationIndex);
});
it("targets the selected sandbox gateway and allows a conflicting route elsewhere (#6315)", async () => {
@@ -614,7 +632,7 @@ describe("runtime shared gateway route containment", () => {
expect(deps.calls.updateSandbox).not.toHaveBeenCalled();
});
- it("serializes same-gateway mutations and rejects a conflicting write", async () => {
+ it("serializes same-gateway provider/model mutations and warns about route impact (#11890)", async () => {
const stateDir = await fs.mkdtemp(path.join(os.tmpdir(), "nemoclaw-route-lock-"));
try {
const entries = [entry("route-lock-alpha"), entry("route-lock-beta")];
@@ -648,16 +666,21 @@ describe("runtime shared gateway route containment", () => {
),
]);
- expect(results.map((result) => result.status).sort()).toEqual(["fulfilled", "rejected"]);
+ expect(results.map((result) => result.status)).toEqual(["fulfilled", "fulfilled"]);
expect(
deps.calls.captureOpenshell.mock.calls.filter(
([args]) => args[0] === "inference" && args[1] === "set",
),
- ).toHaveLength(1);
+ ).toHaveLength(2);
expect(entries).toEqual([
expect.objectContaining({ provider: "nvidia-prod", model: "nvidia/model-a" }),
- expect.objectContaining({ provider: "nvidia-prod", model: "nvidia/model-a" }),
+ expect.objectContaining({ provider: "anthropic-prod", model: "claude-new" }),
]);
+ expect(
+ deps.calls.log.mock.calls.some(([message]) =>
+ message.includes("will re-point the one shared inference route"),
+ ),
+ ).toBe(true);
expect(deps.calls.withGatewayRouteMutationLock).toHaveBeenCalledTimes(2);
} finally {
await fs.rm(stateDir, { recursive: true, force: true });
diff --git a/src/lib/actions/inference-set-route-containment.ts b/src/lib/actions/inference-set-route-containment.ts
index 2748570cf24..f6a2022ef21 100644
--- a/src/lib/actions/inference-set-route-containment.ts
+++ b/src/lib/actions/inference-set-route-containment.ts
@@ -4,6 +4,8 @@
import {
checkGatewayRouteCompatibility,
formatGatewayRouteConflict,
+ formatGatewayRouteImpactWarning,
+ isAdvisoryGatewayRouteConflict,
} from "../inference/gateway-route-compatibility";
import {
buildHttpsPinRouteBaseUrl,
@@ -92,6 +94,7 @@ export interface PreparedInferenceSetRoute {
/** Invocation-only source URL; never persisted for HTTPS-pin routes. */
preliminaryExplicitSourceEndpointUrl: string | null;
preliminaryRegistryMetadata: RegistryInferenceMetadata;
+ preliminaryRouteImpactWarning: string | null;
}
const CUSTOM_COMPATIBLE_CREDENTIAL_ENV: Record = {
@@ -402,23 +405,25 @@ function registryMetadataForProviderSwitch(options: {
};
}
-function assertGatewayRouteCompatibility(options: {
+function routeImpactWarningOrThrow(options: {
gatewayName: string;
sandboxName: string;
provider: string;
model: string;
metadata: RegistryInferenceMetadata;
sandboxes: SandboxEntry[];
-}): void {
+}): string | null {
const compatibility = checkGatewayRouteCompatibility({
gatewayName: options.gatewayName,
sandboxName: options.sandboxName,
route: { provider: options.provider, model: options.model, ...options.metadata },
sandboxes: options.sandboxes,
});
- if (!compatibility.ok) {
- throw new InferenceSetError(formatGatewayRouteConflict(compatibility), 2);
+ if (compatibility.ok) return null;
+ if (isAdvisoryGatewayRouteConflict(compatibility)) {
+ return formatGatewayRouteImpactWarning(compatibility, "inference-set");
}
+ throw new InferenceSetError(formatGatewayRouteConflict(compatibility), 2);
}
export function prepareInferenceSetRoute(options: {
@@ -459,7 +464,7 @@ export function prepareInferenceSetRoute(options: {
session: options.session,
explicitMetadata: preliminaryExplicitMetadata,
});
- assertGatewayRouteCompatibility({
+ const preliminaryRouteImpactWarning = routeImpactWarningOrThrow({
gatewayName,
sandboxName: options.sandboxName,
provider: options.provider,
@@ -472,6 +477,7 @@ export function prepareInferenceSetRoute(options: {
preliminaryExplicitMetadata,
preliminaryExplicitSourceEndpointUrl: explicit.sourceEndpointUrl,
preliminaryRegistryMetadata,
+ preliminaryRouteImpactWarning,
};
}
@@ -492,6 +498,7 @@ export async function finalizeInferenceSetRoute(options: {
explicitPreferredInferenceApi: string | null;
directProviderBinding: InferenceSetProviderBinding | null;
httpsPinProviderBinding: HttpsPinProviderBinding | null;
+ routeImpactWarning: string | null;
}> {
const { prepared } = options;
if (!prepared.preliminaryExplicitMetadata) {
@@ -500,6 +507,7 @@ export async function finalizeInferenceSetRoute(options: {
explicitPreferredInferenceApi: null,
directProviderBinding: null,
httpsPinProviderBinding: null,
+ routeImpactWarning: prepared.preliminaryRouteImpactWarning,
};
}
// Bound once per finalize call: preparation already pinned the credential env
@@ -602,7 +610,7 @@ export async function finalizeInferenceSetRoute(options: {
token: credentialValue,
providerType,
};
- assertGatewayRouteCompatibility({
+ const routeImpactWarning = routeImpactWarningOrThrow({
gatewayName: prepared.gatewayName,
sandboxName: options.sandboxName,
provider: options.provider,
@@ -615,5 +623,6 @@ export async function finalizeInferenceSetRoute(options: {
explicitPreferredInferenceApi: registryMetadata.preferredInferenceApi ?? null,
directProviderBinding,
httpsPinProviderBinding,
+ routeImpactWarning,
};
}
diff --git a/src/lib/actions/inference-set.ts b/src/lib/actions/inference-set.ts
index 6f3bc598faf..a9dd238e68f 100644
--- a/src/lib/actions/inference-set.ts
+++ b/src/lib/actions/inference-set.ts
@@ -981,6 +981,7 @@ async function runInferenceSetWithoutHostLock(
explicitPreferredInferenceApi,
directProviderBinding,
httpsPinProviderBinding,
+ routeImpactWarning,
} = await finalizeInferenceSetRoute({
prepared: preparedRoute,
sandboxName,
@@ -1194,6 +1195,7 @@ async function runInferenceSetWithoutHostLock(
}
await assertProviderCurrentBeforeSelection?.();
+ if (routeImpactWarning) deps.log(` ${routeImpactWarning}`);
deps.log(` Setting OpenShell inference route: ${provider} / ${model}`);
const setInferenceRoute = () =>
deps.captureOpenshell(
diff --git a/src/lib/actions/sandbox/connect-inference-gateway.ts b/src/lib/actions/sandbox/connect-inference-gateway.ts
index 0834b10ea7a..112459439ac 100644
--- a/src/lib/actions/sandbox/connect-inference-gateway.ts
+++ b/src/lib/actions/sandbox/connect-inference-gateway.ts
@@ -4,7 +4,7 @@
import {
checkGatewayRouteCompatibility,
GatewayRouteConflictError,
- isAdvisoryProviderModelRouteConflict,
+ isAdvisoryGatewayRouteConflict,
} from "../../inference/gateway-route-compatibility";
import { LOCAL_INFERENCE_TIMEOUT_SECS } from "../../onboard/env";
import { resolveRegisteredRuntimeProvider } from "../../onboard/runtime-provider/selection";
@@ -41,7 +41,7 @@ export function canSandboxGatewayRouteRealign(
sandboxes: readonly SandboxEntry[] = registry.listSandboxes().sandboxes,
): boolean {
const result = sandboxGatewayRouteCompatibility(sandboxName, sb, gatewayName, sandboxes);
- return result.ok || isAdvisoryProviderModelRouteConflict(result);
+ return result.ok || isAdvisoryGatewayRouteConflict(result);
}
export function buildGatewayInferenceSetArgs(
@@ -77,7 +77,7 @@ export function assertSandboxGatewayRouteCompatible(
gatewayName,
registry.listSandboxes().sandboxes,
);
- if (!result.ok && !isAdvisoryProviderModelRouteConflict(result)) {
+ if (!result.ok && !isAdvisoryGatewayRouteConflict(result)) {
throw new GatewayRouteConflictError(result);
}
}
diff --git a/src/lib/inference/gateway-route-compatibility.test.ts b/src/lib/inference/gateway-route-compatibility.test.ts
index 590f96b1bea..2939cc2a9f3 100644
--- a/src/lib/inference/gateway-route-compatibility.test.ts
+++ b/src/lib/inference/gateway-route-compatibility.test.ts
@@ -9,7 +9,6 @@ import {
formatGatewayRouteImpactWarning,
type GatewayInferenceRoute,
isAdvisoryGatewayRouteConflict,
- isAdvisoryProviderModelRouteConflict,
preflightGatewayRouteDiscovery,
} from "./gateway-route-compatibility";
@@ -274,13 +273,16 @@ describe("shared gateway inference route compatibility", () => {
expect(isAdvisoryGatewayRouteConflict(result as Exclude)).toBe(
true,
);
- expect(
- isAdvisoryProviderModelRouteConflict(result as Exclude),
- ).toBe(true);
const warning = formatGatewayRouteImpactWarning(result as Exclude);
expect(warning).toContain("will re-point the one shared inference route");
expect(warning).toContain("'stopped-peer' (nvidia-prod / nvidia/model-a)");
expect(warning).toContain("not per sandbox");
+ expect(
+ formatGatewayRouteImpactWarning(
+ result as Exclude,
+ "inference-set",
+ ),
+ ).toContain("Changing inference for 'target'");
});
it("allows different routes on different gateways (#6315)", () => {
@@ -416,9 +418,6 @@ describe("shared gateway inference route compatibility", () => {
expect(isAdvisoryGatewayRouteConflict(result as Exclude)).toBe(
false,
);
- expect(
- isAdvisoryProviderModelRouteConflict(result as Exclude),
- ).toBe(false);
});
it("does not let a model difference hide a custom endpoint conflict (#6315)", () => {
@@ -441,9 +440,6 @@ describe("shared gateway inference route compatibility", () => {
ok: false,
conflicts: [{ sandboxName: "custom-peer", reason: "custom-endpoint" }],
});
- expect(
- isAdvisoryProviderModelRouteConflict(result as Exclude),
- ).toBe(false);
});
it.each([
diff --git a/src/lib/inference/gateway-route-compatibility.ts b/src/lib/inference/gateway-route-compatibility.ts
index 65c4ec3ab1a..32848cf989d 100644
--- a/src/lib/inference/gateway-route-compatibility.ts
+++ b/src/lib/inference/gateway-route-compatibility.ts
@@ -379,25 +379,10 @@ export function isAdvisoryGatewayRouteConflict(
);
}
-/**
- * True only when a provider/model-only route mutation can safely reconcile the
- * conflict. Provider-global endpoint, API-family, and credential changes stay
- * fail-closed while another registered sandbox depends on the current identity.
- */
-export function isAdvisoryProviderModelRouteConflict(
- result: Exclude,
-): boolean {
- return (
- result.conflicts.length > 0 &&
- result.conflicts.every(
- (conflict) => conflict.scope !== "requested" && conflict.reason === "provider-model",
- )
- );
-}
-
/** Explain the single-gateway side effect immediately before route mutation. */
export function formatGatewayRouteImpactWarning(
result: Exclude,
+ operation: "onboard" | "inference-set" = "onboard",
): string {
const affected = [...result.conflicts]
.sort((left, right) => left.sandboxName.localeCompare(right.sandboxName))
@@ -408,9 +393,14 @@ export function formatGatewayRouteImpactWarning(
: name;
})
.join(", ");
- const target = result.sandboxName
- ? `Onboarding '${safeDisplay(result.sandboxName)}'`
- : "This onboarding run";
+ const target =
+ operation === "inference-set"
+ ? result.sandboxName
+ ? `Changing inference for '${safeDisplay(result.sandboxName)}'`
+ : "This inference change"
+ : result.sandboxName
+ ? `Onboarding '${safeDisplay(result.sandboxName)}'`
+ : "This onboarding run";
const nextRoute = `${safeDisplay(result.route.provider)} / ${safeDisplay(result.route.model)}`;
return (
`Warning: ${target} will re-point the one shared inference route on OpenShell gateway ` +
diff --git a/test/e2e/live/openclaw-inference-switch-helpers.ts b/test/e2e/live/openclaw-inference-switch-helpers.ts
index ae82b51e83e..6c336a5f6ea 100644
--- a/test/e2e/live/openclaw-inference-switch-helpers.ts
+++ b/test/e2e/live/openclaw-inference-switch-helpers.ts
@@ -61,6 +61,58 @@ export function agentReplyContainsToken(reply: string, expected: string): boolea
return normalizedExpected.length > 0 && normalizedReply === normalizedExpected;
}
+/** Record zero only when Anthropic tools are absent or an empty array. */
+export function anthropicToolCount(tools: unknown): number | null {
+ if (tools === undefined) return 0;
+ return Array.isArray(tools) ? tools.length : null;
+}
+
+export interface OpenClawGatewayModelRunResult {
+ model: string;
+ provider: string;
+ text: string;
+ transport: "gateway";
+}
+
+/** Parse the stable JSON envelope emitted by `openclaw infer model run --gateway`. */
+export function parseOpenClawGatewayModelRun(raw: string): OpenClawGatewayModelRunResult | null {
+ let document: unknown;
+ try {
+ document = JSON.parse(raw.trim());
+ } catch {
+ return null;
+ }
+ if (!document || typeof document !== "object" || Array.isArray(document)) return null;
+ const record = document as Record;
+ if (
+ record.ok !== true ||
+ record.capability !== "model.run" ||
+ record.transport !== "gateway" ||
+ typeof record.provider !== "string" ||
+ typeof record.model !== "string" ||
+ !Array.isArray(record.outputs)
+ ) {
+ return null;
+ }
+ const text = record.outputs
+ .map((output) =>
+ output &&
+ typeof output === "object" &&
+ typeof (output as { text?: unknown }).text === "string"
+ ? (output as { text: string }).text
+ : "",
+ )
+ .join("")
+ .trim();
+ if (!text) return null;
+ return {
+ model: record.model,
+ provider: record.provider,
+ text,
+ transport: "gateway",
+ };
+}
+
// Baseline (mock-Anthropic) inference config the live target builds when
// NEMOCLAW_SWITCH_MOCK_ANTHROPIC=1 points OpenClaw at a local fake OpenAI-
// compatible server. Extracted so the fast e2e-support project can assert the
diff --git a/test/e2e/live/openclaw-inference-switch.test.ts b/test/e2e/live/openclaw-inference-switch.test.ts
index 0a8ec03a680..60b930c62f9 100644
--- a/test/e2e/live/openclaw-inference-switch.test.ts
+++ b/test/e2e/live/openclaw-inference-switch.test.ts
@@ -5,7 +5,7 @@
* Preserve the script's real user-visible boundary: install.sh onboards an
* OpenClaw sandbox, `nemoclaw inference set` switches the running route, then
* OpenShell route state, OpenClaw config/hash state, registry/session state,
- * inference.local, and a real OpenClaw agent turn are checked from the live
+ * inference.local, and a real OpenClaw gateway model run are checked from the live
* host/sandbox boundary. Target-specific helpers stay local; shared shell
* primitives come from the fixture layer's production-backed helper.
*/
@@ -46,15 +46,16 @@ import {
writeInferenceSwitchRetryEvidence,
} from "../fixtures/inference-switch-retry.ts";
import { CLI_ENTRYPOINT, REPO_ROOT } from "../fixtures/paths.ts";
-import { parseOpenClawAgentText } from "../fixtures/openclaw-agent-output.ts";
import { runBoundedRetry } from "../../../tools/e2e/retry-evidence.mts";
import type { ShellProbeResult } from "../fixtures/shell-probe.ts";
import {
agentReplyContainsToken,
+ anthropicToolCount,
classifyOpenClawPostSwitchInferenceAttempt,
MOCK_BASELINE_API_KEY,
MOCK_BASELINE_MODEL,
mockBaselineInference,
+ parseOpenClawGatewayModelRun,
} from "./openclaw-inference-switch-helpers.ts";
import {
PUBLIC_NVIDIA_SWITCH_MODEL,
@@ -139,9 +140,18 @@ interface OnboardSession {
interface MockAnthropicProvider {
endpointUrl: string;
+ requests(): readonly MockAnthropicRequest[];
close(): Promise;
}
+interface MockAnthropicRequest {
+ method: string;
+ model: string | null;
+ path: string;
+ stream: boolean;
+ toolCount: number | null;
+}
+
function proveMockBaselineAuthentication(
baseline: Pick | undefined,
sandbox: SandboxClient,
@@ -334,6 +344,7 @@ function closeServer(server: Server): Promise {
}
async function startMockAnthropicProvider(): Promise {
+ const requests: MockAnthropicRequest[] = [];
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://mock.local");
if (req.method === "GET" && url.pathname === "/health") {
@@ -358,13 +369,24 @@ async function startMockAnthropicProvider(): Promise {
raw += chunk;
});
req.on("end", () => {
- let payload: { model?: unknown; stream?: unknown } = {};
+ let payload: { model?: unknown; stream?: unknown; tools?: unknown } = {};
try {
- payload = JSON.parse(raw || "{}") as { model?: unknown; stream?: unknown };
+ payload = JSON.parse(raw || "{}") as {
+ model?: unknown;
+ stream?: unknown;
+ tools?: unknown;
+ };
} catch {
payload = {};
}
const model = typeof payload.model === "string" ? payload.model : "mock-anthropic-model";
+ requests.push({
+ method: req.method ?? "",
+ model: typeof payload.model === "string" ? payload.model : null,
+ path: url.pathname,
+ stream: payload.stream === true,
+ toolCount: anthropicToolCount(payload.tools),
+ });
if (payload.stream === true) {
const message = {
id: "msg_mock",
@@ -430,6 +452,7 @@ async function startMockAnthropicProvider(): Promise {
const port = (address as AddressInfo).port;
return {
endpointUrl: compatibleAnthropicMockEndpointUrl(port),
+ requests: () => requests,
close: () => closeServer(server),
};
}
@@ -731,11 +754,13 @@ async function checkSandboxInference(
throw new Error(`Sandbox inference.local did not work after switch: ${lastFailure}`);
}
-async function checkOpenClawAgentTurn(
+async function checkOpenClawGatewayInference(
host: HostCliClient,
home: string,
+ artifacts: ArtifactSink,
+ mockProvider: MockAnthropicProvider | undefined,
): Promise<"ok" | { skipped: string }> {
- const sessionId = `e2e-inference-switch-openclaw-${Date.now()}-${process.pid}`;
+ const requestOffset = mockProvider?.requests().length ?? 0;
const script = String.raw`
set -u
ssh_config="$(mktemp)"
@@ -760,7 +785,7 @@ run_with_timeout 120s ssh -F "$ssh_config" \
-o ConnectTimeout=10 \
-o LogLevel=ERROR \
"openshell-${SANDBOX_NAME}.default" \
- "openclaw agent --agent main --json --session-id '$SESSION_ID' -m 'Reply with exactly one word: PONG'" \
+ "openclaw infer model run --gateway --json --prompt 'Reply with exactly one word: PONG'" \
2>"$stderr_file"
rc=$?
set -e
@@ -769,33 +794,59 @@ cat "$stderr_file" 2>/dev/null || true
exit "$rc"
`;
const result = await host.command("bash", ["-lc", script], {
- artifactName: "openclaw-agent-turn-after-inference-switch",
- env: commandEnv(home, {
- SANDBOX_NAME,
- SESSION_ID: sessionId,
- }),
+ artifactName: "openclaw-gateway-inference-after-switch",
+ env: commandEnv(home, { SANDBOX_NAME }),
timeoutMs: AGENT_TIMEOUT_MS,
});
+ const mockRequests = mockProvider?.requests().slice(requestOffset) ?? [];
+ const requestArtifact = "mock-anthropic-openclaw-gateway-requests.json";
+ await (mockProvider
+ ? artifacts.writeJson(requestArtifact, {
+ phase: "prove inference.local and OpenClaw gateway inference",
+ requestCount: mockRequests.length,
+ requests: mockRequests.slice(0, 20),
+ truncated: mockRequests.length > 20,
+ })
+ : Promise.resolve());
const [raw = "", warnings = ""] = result.stdout.split("\n__NEMOCLAW_AGENT_STDERR__\n", 2);
- const reply = parseOpenClawAgentText(raw);
+ const modelRun = parseOpenClawGatewayModelRun(raw);
+ const reply = modelRun?.text ?? "";
const fallbackOrPairing =
/EMBEDDED FALLBACK|gateway connect failed|scope upgrade pending approval|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded/i.test(
[raw, warnings, result.stderr].filter(Boolean).join("\n"),
);
- if (result.exitCode === 0 && agentReplyContainsToken(reply, "PONG") && !fallbackOrPairing) {
+ const mockRequestMatched =
+ !mockProvider ||
+ (mockRequests.length > 0 &&
+ mockRequests.every(
+ (request) =>
+ request.method === "POST" &&
+ request.path === "/v1/messages" &&
+ request.model === SWITCH_MODEL &&
+ request.stream &&
+ request.toolCount === 0,
+ ));
+ const expectedOpenClawProvider =
+ SWITCH_INFERENCE_API === "anthropic-messages" ? "anthropic" : "inference";
+ if (
+ result.exitCode === 0 &&
+ modelRun?.provider === expectedOpenClawProvider &&
+ modelRun.model === SWITCH_MODEL &&
+ agentReplyContainsToken(reply, "PONG") &&
+ !fallbackOrPairing &&
+ mockRequestMatched
+ ) {
return "ok";
}
- if (result.exitCode === 124) {
- return {
- skipped: "OpenClaw agent turn timed out after switch; route/config checks already passed",
- };
- }
throw new Error(
[
- `OpenClaw agent turn failed after switch (exit ${result.exitCode})`,
+ `OpenClaw gateway inference failed after switch (exit ${result.exitCode})`,
`reply=${reply.slice(0, 200)}`,
`raw=${raw.slice(0, 200)}`,
`stderr=${[warnings, result.stderr].filter(Boolean).join("\n").slice(0, 200)}`,
+ mockProvider && !mockRequestMatched
+ ? `request evidence mismatch; see ${requestArtifact}`
+ : "",
].join("; "),
);
}
@@ -877,7 +928,7 @@ test(
"prepare the switched provider and endpoint",
"switch the route and verify restart semantics",
"inspect route configuration and recorded state",
- "prove inference.local and OpenClaw agent turns",
+ "prove inference.local and OpenClaw gateway inference",
"apply sandbox retention and record the result",
],
},
@@ -885,7 +936,7 @@ test(
async ({ artifacts, cleanup, host, progress, runtimeProvider, sandbox, secrets, skip }) => {
await artifacts.target.declare({
id: "openclaw-inference-switch",
- boundary: "install-sh-openclaw-inference-set-and-live-agent-turn",
+ boundary: "install-sh-openclaw-inference-set-and-live-gateway-model-run",
sandboxName: SANDBOX_NAME,
switchProvider: SWITCH_PROVIDER,
switchModel: SWITCH_MODEL,
@@ -900,7 +951,7 @@ test(
"OpenClaw config and .config-hash reflect the switched inference API/model",
"registry and onboard session record the switched provider/model",
"sandbox inference.local returns PONG from the switched model",
- "openclaw agent answers through the switched inference route",
+ "OpenClaw gateway model inference answers through the switched route without agent tools",
],
});
@@ -1062,7 +1113,7 @@ test(
await assertOpenClawConfig(sandbox, home);
await assertRegistryAndSession(home, { mockProvider });
- progress.phase("prove inference.local and OpenClaw agent turns");
+ progress.phase("prove inference.local and OpenClaw gateway inference");
const inference = await checkSandboxInference(sandbox, artifacts, home);
if (inference !== "ok") {
await artifacts.target.complete({
@@ -1074,15 +1125,20 @@ test(
skip(inference.skipped);
}
- const agentTurn = await checkOpenClawAgentTurn(host, home);
- if (agentTurn !== "ok") {
+ const gatewayInference = await checkOpenClawGatewayInference(
+ host,
+ home,
+ artifacts,
+ mockProvider,
+ );
+ if (gatewayInference !== "ok") {
await artifacts.target.complete({
id: "openclaw-inference-switch",
status: "skipped",
- reason: agentTurn.skipped,
+ reason: gatewayInference.skipped,
routeConfigAndInferenceChecksPassed: true,
});
- skip(agentTurn.skipped);
+ skip(gatewayInference.skipped);
}
progress.phase("apply sandbox retention and record the result");
@@ -1107,7 +1163,7 @@ test(
registryAndSessionChecked: true,
inferenceLocalPong: true,
inferenceLocalModelMatched: true,
- openClawAgentPong: true,
+ openClawGatewayInferencePong: true,
},
});
},
diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json
index 2785d8731a4..2b7a8f9ccdb 100644
--- a/test/e2e/mock-parity.json
+++ b/test/e2e/mock-parity.json
@@ -723,7 +723,7 @@
"test/e2e/support/compatible-anthropic-switch.test.ts",
"test/e2e/support/e2e-cleanup-resources.test.ts",
"test/e2e/support/e2e-clients.test.ts",
- "test/e2e/support/openclaw-agent-output.test.ts"
+ "test/e2e/support/openclaw-inference-switch-helpers.test.ts"
]
},
{
diff --git a/test/e2e/support/openclaw-inference-switch-helpers.test.ts b/test/e2e/support/openclaw-inference-switch-helpers.test.ts
index 26a86923916..a78ef1d5f47 100644
--- a/test/e2e/support/openclaw-inference-switch-helpers.test.ts
+++ b/test/e2e/support/openclaw-inference-switch-helpers.test.ts
@@ -5,10 +5,12 @@ import { describe, expect, it } from "vitest";
import {
agentReplyContainsToken,
+ anthropicToolCount,
classifyOpenClawPostSwitchInferenceAttempt,
MOCK_BASELINE_API_KEY,
MOCK_BASELINE_MODEL,
mockBaselineInference,
+ parseOpenClawGatewayModelRun,
} from "../live/openclaw-inference-switch-helpers.ts";
describe("openclaw-inference-switch post-switch retry classification", () => {
@@ -108,6 +110,62 @@ describe("openclaw-inference-switch agent reply matching", () => {
});
});
+describe("openclaw-inference-switch Anthropic tool evidence", () => {
+ it("distinguishes tool-free requests from malformed tool metadata", () => {
+ expect(anthropicToolCount(undefined)).toBe(0);
+ expect(anthropicToolCount([])).toBe(0);
+ expect(anthropicToolCount([{ name: "shell" }])).toBe(1);
+ expect(anthropicToolCount({ name: "shell" })).toBeNull();
+ expect(anthropicToolCount("invalid")).toBeNull();
+ });
+});
+
+describe("openclaw-inference-switch gateway model-run output", () => {
+ it("accepts the stable gateway inference envelope", () => {
+ expect(
+ parseOpenClawGatewayModelRun(
+ JSON.stringify({
+ ok: true,
+ capability: "model.run",
+ transport: "gateway",
+ provider: "anthropic",
+ model: "mock-anthropic-model",
+ attempts: [],
+ outputs: [{ text: "PONG", mediaUrl: null }],
+ }),
+ ),
+ ).toEqual({
+ model: "mock-anthropic-model",
+ provider: "anthropic",
+ text: "PONG",
+ transport: "gateway",
+ });
+ });
+
+ it.each([
+ "not json",
+ JSON.stringify({ ok: false, capability: "model.run", transport: "gateway", outputs: [] }),
+ JSON.stringify({
+ ok: true,
+ capability: "model.run",
+ transport: "local",
+ provider: "anthropic",
+ model: "mock-anthropic-model",
+ outputs: [{ text: "PONG" }],
+ }),
+ JSON.stringify({
+ ok: true,
+ capability: "model.run",
+ transport: "gateway",
+ provider: "anthropic",
+ model: "mock-anthropic-model",
+ outputs: [{ mediaUrl: null }],
+ }),
+ ])("rejects malformed or non-gateway output", (raw) => {
+ expect(parseOpenClawGatewayModelRun(raw)).toBeNull();
+ });
+});
+
describe("openclaw-inference-switch mock-Anthropic baseline", () => {
it("uses an authenticated local baseline with the compatible env wiring", () => {
expect(mockBaselineInference("http://127.0.0.1:34567/v1")).toEqual({