diff --git a/docs/inference/verify-inference-route.mdx b/docs/inference/verify-inference-route.mdx index 2f9d8c1d8ce..5203ac9d792 100644 --- a/docs/inference/verify-inference-route.mdx +++ b/docs/inference/verify-inference-route.mdx @@ -32,7 +32,10 @@ Run the named sandbox status command. $$nemoclaw status ``` -The `Inference` row checks the sandbox's `inference.local` path and reports the provider, model, and endpoint with the rest of the sandbox state. +The `Inference` row checks the sandbox's `inference.local` path and reports it as `reachable` when the route returns HTTP `200` through `499`. +This includes authentication responses such as HTTP `401` and `403`: they confirm route access, not valid provider credentials or a successful model invocation. +Use the status command's upstream provider diagnostic or send a short agent request to verify the configured model. +The provider, model, and endpoint appear with the rest of the sandbox state. This path includes the OpenShell proxy and its authentication rewrite. When onboarding prints a dashboard summary, use it to verify that NemoClaw ran the same route-reachability probe from inside the sandbox. Treat an unreachable route or HTTP 5xx response as a failed readiness check: onboarding marks the sandbox not ready and exits non-zero. @@ -61,7 +64,7 @@ Use the status command and a short agent request after onboarding to verify ongo Connect to the sandbox and send a short request before starting long-running work. A successful response proves that the configured model can serve an agent request through the OpenShell route. -If status is healthy but a tool action returns JSON as normal assistant text, troubleshoot structured tool calling instead of the network route. +If the status route is reachable but a tool action returns JSON as normal assistant text, troubleshoot structured tool calling instead of the network route. ## Related Topics diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 8cb43dbdbf7..f17602b2680 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1218,7 +1218,7 @@ The main `Inference` line reports one of these states: | State | Meaning | |-------|---------| -| `healthy` | The route returned an HTTP status from `200` through `499`. Authentication responses such as `401` and `403` confirm route reachability. | +| `reachable` | The route returned an HTTP status from `200` through `499`. Authentication responses such as `401` and `403` confirm route reachability. | | `unhealthy` | The route returned an HTTP status from `500` through `599`. | | `unreachable` | The route had a transport failure, returned no final HTTP status (`000` or an interim `100` through `199`), or returned an invalid status outside `100` through `599`. | | `not probed` | NemoClaw could not run the authoritative route probe from a reachable sandbox. | @@ -1226,6 +1226,9 @@ The main `Inference` line reports one of these states: An authentication response confirms that the route is reachable, not that provider credentials are valid. The command can also print direct host-side provider checks such as `Inference (upstream)` and provider-specific subprobes. +For supported remote providers, this diagnostic sends an authenticated request to the configured model and accepts only a recognized Chat Completions, streaming Chat Completions, or Anthropic Messages response. +It uses a 3-second connection timeout, a 5-second total timeout, and an 8-token output limit. +If the request reaches the time limit, NemoClaw reports the provider as `not probed` and leaves model health unverified instead of reporting it as unhealthy. These checks are diagnostic only and do not override the authoritative `inference.local` result or determine the command exit status. Local providers add host-side backend diagnostics. @@ -1345,7 +1348,7 @@ The rebuild reuses the existing sandbox name and preserved manifest-defined stat ### `$$nemoclaw doctor` Run a focused health check for one sandbox and the host services it depends on. -The command checks the local CLI build, Docker daemon, OpenShell CLI, NemoClaw gateway container, gateway port mapping, live sandbox state, inference route, provider reachability, Ollama reachability, and the cloudflared tunnel state. +The command checks the local CLI build, Docker daemon, OpenShell CLI, NemoClaw gateway container, gateway port mapping, live sandbox state, inference route, configured-provider model invocation, Ollama reachability, and the cloudflared tunnel state. For gateway-based agents, it also reports messaging channel conflicts. @@ -1353,7 +1356,7 @@ For gateway-based agents, it also reports messaging channel conflicts. For inference health, `doctor` treats the probe to `https://inference.local/v1/models` from inside the sandbox as authoritative. HTTP responses from `200` through `499`, including `401` and `403`, pass this check. HTTP `500` through `599`, interim `100` through `199`, transport failures with status `000`, invalid status values, and an unavailable authoritative probe fail the check. -Direct provider and upstream probes are diagnostics only, so their failure does not fail `doctor` when the authoritative in-sandbox route is healthy. +Direct provider and upstream probes use the same authenticated model-invocation checks as status and remain diagnostic only, so their failure does not fail `doctor` when the authoritative in-sandbox route is reachable. Warnings do not make the command fail. Failed checks, including a failed or unavailable authoritative inference route, exit non-zero so scripts can use `doctor` as a readiness gate. diff --git a/src/lib/actions/sandbox/status-flow.test.ts b/src/lib/actions/sandbox/status-flow.test.ts index 25c1b11321b..474bcaff85a 100644 --- a/src/lib/actions/sandbox/status-flow.test.ts +++ b/src/lib/actions/sandbox/status-flow.test.ts @@ -107,7 +107,7 @@ describe("showSandboxStatus flow", () => { expect(output).toContain("Sandbox-scoped status for 'alpha'"); expect(output).toContain("Sandbox: alpha"); expect(output).toContain("Model: nvidia/nemotron"); - expect(output).toContain("Inference: healthy"); + expect(output).toContain("Inference: reachable"); expect(output).toContain("Inference (ollama backend):"); expect(output).toContain("Host GPU: yes"); expect(output).toContain("last CUDA proof failed: cuInit"); @@ -213,6 +213,41 @@ describe("showSandboxStatus flow", () => { expect(process.exitCode).toBeUndefined(); }); + it("distinguishes route reachability from model-invocation health in the rendered labels (#6846)", async () => { + const harness = createStatusFlowHarness({ + inferenceHealth: { + ok: true, + probed: true, + providerLabel: "Inference route", + endpoint: "https://inference.local/v1/models", + detail: "route reachable", + okLabel: "reachable", + subprobes: [ + { + ok: true, + probed: true, + providerLabel: "NVIDIA Endpoints", + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + detail: "model invocation probe succeeded", + probeLabel: "upstream", + }, + ], + }, + }); + + await expect(harness.showSandboxStatus("alpha")).resolves.toBeUndefined(); + + const output = harness.logSpy.mock.calls.flat().join("\n"); + // The route probe only proves network-path reachability (#6192); the + // upstream subprobe is what proves the configured model is invocable + // (#6846). Rendering the same word for both would re-introduce the + // false-positive this PR fixes. + expect(output).toContain("Inference: reachable"); + expect(output).not.toContain("Inference: healthy"); + expect(output).toContain("Inference (upstream): healthy"); + expect(process.exitCode).toBeUndefined(); + }); + it("probes terminal runtime agent version when cached metadata is missing", async () => { const harness = createStatusFlowHarness({ sandboxEntry: { diff --git a/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts new file mode 100644 index 00000000000..87088dfb1fe --- /dev/null +++ b/src/lib/actions/sandbox/status-snapshot-inference-health.test.ts @@ -0,0 +1,142 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; + +import type { ProviderHealthStatus } from "../../inference/health"; +import type { SandboxEntry } from "../../state/registry"; +import type { SandboxInferenceRouteHealth } from "./inference-route-health"; +import { collectSandboxStatusSnapshot } from "./status-snapshot"; + +// Direct, unmocked coverage of `buildSandboxInferenceRouteHealth` through the +// exported `collectSandboxStatusSnapshot` entry point (it is not itself +// exported). status-flow.test.ts mocks collectSandboxStatusSnapshot wholesale +// and never exercises this code, so it never proves okLabel is actually set +// in production wiring rather than merely respected if present (#6846). +function snapshotDeps( + gateway: SandboxInferenceRouteHealth | null, + providerHealth: ProviderHealthStatus | null = null, +) { + const sandbox: SandboxEntry = { + name: "alpha", + agent: "openclaw", + policies: [], + provider: "nvidia", + model: "nvidia/nemotron", + }; + return { + suppressInferenceProbe: false, + deps: { + getSandbox: () => sandbox, + listSandboxes: () => ({ sandboxes: [sandbox], defaultSandbox: sandbox.name }), + reconcile: async () => ({ state: "present" as const, output: "Phase: Ready" }), + // The live-route RPC lookup is independent of the authoritative + // inference.local gateway probe under test; throwing here just leaves + // liveRoute/routeDrift null without needing a fabricated exec transcript. + captureOpenshellForStatusImpl: async () => { + throw new Error("live route lookup not needed for this test"); + }, + probeProviderHealthImpl: () => providerHealth, + probeSandboxInferenceGatewayHealthImpl: async () => gateway, + }, + }; +} + +describe("collectSandboxStatusSnapshot inference route health", () => { + it("labels a reachable route okLabel: reachable, not a bare healthy claim (#6846)", async () => { + const gateway: SandboxInferenceRouteHealth = { + ok: true, + endpoint: "https://inference.local/v1/models", + httpStatus: 200, + detail: + "Inference gateway responded HTTP 200 on https://inference.local/v1/models (full chain reachable).", + }; + + const snapshot = await collectSandboxStatusSnapshot("alpha", snapshotDeps(gateway)); + + expect(snapshot.inferenceHealth).toMatchObject({ + ok: true, + probed: true, + providerLabel: "Inference route", + endpoint: "https://inference.local/v1/models", + okLabel: "reachable", + }); + expect(snapshot.inferenceHealth?.failureLabel).toBeUndefined(); + }); + + it("does not set okLabel for a 5xx route failure, and classifies it unhealthy (#6846)", async () => { + const gateway: SandboxInferenceRouteHealth = { + ok: false, + endpoint: "https://inference.local/v1/models", + httpStatus: 502, + detail: + "Inference gateway returned HTTP 502 on https://inference.local/v1/models; the route is reachable but unhealthy.", + }; + + const snapshot = await collectSandboxStatusSnapshot("alpha", snapshotDeps(gateway)); + + expect(snapshot.inferenceHealth).toMatchObject({ + ok: false, + failureLabel: "unhealthy", + }); + expect(snapshot.inferenceHealth?.okLabel).toBeUndefined(); + }); + + it("does not set okLabel when the route is unreachable (#6846)", async () => { + const gateway: SandboxInferenceRouteHealth = { + ok: false, + endpoint: "https://inference.local/v1/models", + httpStatus: 0, + detail: + "Inference gateway unreachable on https://inference.local/v1/models from inside the sandbox.", + }; + + const snapshot = await collectSandboxStatusSnapshot("alpha", snapshotDeps(gateway)); + + expect(snapshot.inferenceHealth).toMatchObject({ + ok: false, + failureLabel: "unreachable", + }); + expect(snapshot.inferenceHealth?.okLabel).toBeUndefined(); + }); + + it("stays unprobed with no okLabel when the gateway probe is unavailable (#6846)", async () => { + const snapshot = await collectSandboxStatusSnapshot("alpha", snapshotDeps(null)); + + expect(snapshot.inferenceHealth).toMatchObject({ + ok: false, + probed: false, + providerLabel: "Inference route", + }); + expect(snapshot.inferenceHealth?.okLabel).toBeUndefined(); + expect(snapshot.inferenceHealth?.failureLabel).toBeUndefined(); + }); + + it("keeps a failed model-invocation subprobe distinct from the reachable route label (#6846)", async () => { + const gateway: SandboxInferenceRouteHealth = { + ok: true, + endpoint: "https://inference.local/v1/models", + httpStatus: 200, + detail: + "Inference gateway responded HTTP 200 on https://inference.local/v1/models (full chain reachable).", + }; + const providerHealth: ProviderHealthStatus = { + ok: false, + probed: true, + providerLabel: "NVIDIA Endpoints", + endpoint: "https://integrate.api.nvidia.com/v1/chat/completions", + detail: "model invocation probe failed", + failureLabel: "unauthorized", + }; + + const snapshot = await collectSandboxStatusSnapshot( + "alpha", + snapshotDeps(gateway, providerHealth), + ); + + expect(snapshot.inferenceHealth).toMatchObject({ ok: true, okLabel: "reachable" }); + expect(snapshot.inferenceHealth?.subprobes).toEqual([ + { ...providerHealth, probeLabel: "upstream" }, + ]); + }); +}); diff --git a/src/lib/actions/sandbox/status-snapshot.ts b/src/lib/actions/sandbox/status-snapshot.ts index 62c9c5a830b..bba746acff0 100644 --- a/src/lib/actions/sandbox/status-snapshot.ts +++ b/src/lib/actions/sandbox/status-snapshot.ts @@ -115,7 +115,7 @@ function buildSandboxInferenceRouteHealth( endpoint, detail: gateway.detail, ...(gateway.ok - ? {} + ? { okLabel: "reachable" } : { failureLabel: classifyInferenceRouteFailureLabel(gateway.httpStatus), }), diff --git a/src/lib/actions/sandbox/status-text.ts b/src/lib/actions/sandbox/status-text.ts index a9be7b461a9..7c7038bef31 100644 --- a/src/lib/actions/sandbox/status-text.ts +++ b/src/lib/actions/sandbox/status-text.ts @@ -88,7 +88,7 @@ function printInferenceProbeLine(probe: ProviderHealthStatus): void { return; } if (probe.ok) { - console.log(` ${label}: ${G}healthy${R} (${probe.endpoint})`); + console.log(` ${label}: ${G}${probe.okLabel ?? "healthy"}${R} (${probe.endpoint})`); return; } console.log(` ${label}: ${RD}${probe.failureLabel || "unreachable"}${R} (${probe.endpoint})`); diff --git a/src/lib/inference/health.test.ts b/src/lib/inference/health.test.ts index 91265f8c04c..24c37b7bc81 100644 --- a/src/lib/inference/health.test.ts +++ b/src/lib/inference/health.test.ts @@ -3,305 +3,550 @@ import fs from "node:fs"; -import { describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; // Import source directly so tests cannot pass against a stale build. -import { - getRemoteProviderHealthEndpoint, - probeProviderHealth, - probeRemoteProviderHealth, -} from "./health"; +import { probeProviderHealth, probeRemoteProviderHealth } from "./health"; import { BUILD_ENDPOINT_URL } from "./provider-models"; +afterEach(() => { + vi.unstubAllEnvs(); +}); + +function httpOk(body = '{"choices":[{"message":{"content":"OK"}}]}'): { + ok: true; + httpStatus: 200; + curlStatus: 0; + body: string; + stderr: string; + message: string; +} { + return { ok: true, httpStatus: 200, curlStatus: 0, body, stderr: "", message: "HTTP 200" }; +} + +function curlArgValue(argv: string[], name: string): string | undefined { + const index = argv.indexOf(name); + return index >= 0 ? argv[index + 1] : undefined; +} + +function httpTimeout() { + return { + ok: false as const, + httpStatus: 0, + curlStatus: 28, + body: "", + stderr: "Operation timed out", + message: "curl failed (exit 28): Operation timed out", + }; +} + +function httpUnauthorized() { + return { + ok: false, + httpStatus: 401, + curlStatus: 0, + body: '{"error":"unauthorized"}', + stderr: "", + message: "HTTP 401: unauthorized", + }; +} + +function httpServerError() { + return { + ok: false, + httpStatus: 500, + curlStatus: 0, + body: "", + stderr: "", + message: "HTTP 500", + }; +} + +function connectionRefused() { + return { + ok: false, + httpStatus: 0, + curlStatus: 7, + body: "", + stderr: "Failed to connect", + message: "curl failed (exit 7): Failed to connect", + }; +} + describe("inference health", () => { - describe("getRemoteProviderHealthEndpoint", () => { - it("returns NVIDIA endpoint for nvidia-prod", () => { - expect(getRemoteProviderHealthEndpoint("nvidia-prod")).toBe(`${BUILD_ENDPOINT_URL}/models`); - }); + describe("probeRemoteProviderHealth — Bearer-auth chat-completions family", () => { + it("invokes chat-completions for openai-api and never leaks the key into argv", () => { + vi.stubEnv("NEMOCLAW_ONBOARD_VALIDATION_TIMEOUT_SECONDS", "90"); + let capturedArgv: string[] = []; + let authConfigPath = ""; + let authConfigContent = ""; + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: (envName) => (envName === "OPENAI_API_KEY" ? "sk-test-secret" : null), + runCurlProbeImpl: (argv) => { + capturedArgv = argv; + const configIndex = argv.indexOf("--config"); + authConfigPath = configIndex >= 0 ? argv[configIndex + 1] : ""; + authConfigContent = authConfigPath ? fs.readFileSync(authConfigPath, "utf8") : ""; + return httpOk('{"choices":[{"message":{"content":"OK"}}]}'); + }, + }); - it("returns NVIDIA endpoint for nvidia-nim", () => { - expect(getRemoteProviderHealthEndpoint("nvidia-nim")).toBe(`${BUILD_ENDPOINT_URL}/models`); - }); + expect(result?.ok).toBe(true); + expect(result?.probed).toBe(true); + expect(result?.providerLabel).toBe("OpenAI"); + expect(result?.endpoint).toBe("https://api.openai.com/v1/chat/completions"); + expect(capturedArgv.at(-1)).toBe("https://api.openai.com/v1/chat/completions"); + expect(curlArgValue(capturedArgv, "--connect-timeout")).toBe("3"); + expect(curlArgValue(capturedArgv, "--max-time")).toBe("5"); + + const joined = capturedArgv.join(" "); + expect(joined).not.toContain("sk-test-secret"); + expect(joined).not.toContain("Authorization: Bearer"); + expect(capturedArgv).toContain("--config"); + expect(authConfigContent).toContain("Authorization: Bearer sk-test-secret"); + expect(fs.existsSync(authConfigPath)).toBe(false); - it("returns OpenAI endpoint for openai-api", () => { - expect(getRemoteProviderHealthEndpoint("openai-api")).toBe( - "https://api.openai.com/v1/models", - ); + const payload = JSON.parse(capturedArgv[capturedArgv.indexOf("-d") + 1]); + expect(payload).toEqual({ + model: "gpt-4o-mini", + messages: [{ role: "user", content: "Reply with exactly: OK" }], + max_tokens: 8, + }); }); - it("returns Anthropic endpoint for anthropic-prod", () => { - expect(getRemoteProviderHealthEndpoint("anthropic-prod")).toBe( - "https://api.anthropic.com/v1/models", - ); + it("skips the invocation probe for openai-api without a credential (never authoritative)", () => { + let called = false; + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: () => null, + runCurlProbeImpl: () => { + called = true; + return httpOk(); + }, + }); + + expect(called).toBe(false); + expect(result?.ok).toBe(true); + expect(result?.probed).toBe(false); + expect(result?.detail).toContain("OPENAI_API_KEY"); }); - it("returns Gemini endpoint for gemini-api", () => { - expect(getRemoteProviderHealthEndpoint("gemini-api")).toBe( - "https://generativelanguage.googleapis.com/v1/models", + it("invokes the Gemini OpenAI-compatible chat-completions shim, not the native v1/models surface", () => { + let capturedArgv: string[] = []; + const result = probeRemoteProviderHealth("gemini-api", { + model: "gemini-2.5-flash", + getCredentialImpl: (envName) => (envName === "GEMINI_API_KEY" ? "gm-test-secret" : null), + runCurlProbeImpl: (argv) => { + capturedArgv = argv; + return httpOk(); + }, + }); + + expect(result?.ok).toBe(true); + expect(result?.endpoint).toBe( + "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", ); + expect(capturedArgv.at(-1)).toBe( + "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions", + ); + expect(capturedArgv.join(" ")).not.toContain("gm-test-secret"); }); - it("returns null for compatible-endpoint", () => { - expect(getRemoteProviderHealthEndpoint("compatible-endpoint")).toBeNull(); - }); + it("skips the invocation probe for gemini-api without a credential", () => { + const result = probeRemoteProviderHealth("gemini-api", { + model: "gemini-2.5-flash", + getCredentialImpl: () => null, + runCurlProbeImpl: () => httpOk(), + }); - it("returns null for compatible-anthropic-endpoint", () => { - expect(getRemoteProviderHealthEndpoint("compatible-anthropic-endpoint")).toBeNull(); + expect(result?.ok).toBe(true); + expect(result?.probed).toBe(false); + expect(result?.detail).toContain("GEMINI_API_KEY"); }); - it("returns null for local providers", () => { - expect(getRemoteProviderHealthEndpoint("ollama-local")).toBeNull(); - expect(getRemoteProviderHealthEndpoint("vllm-local")).toBeNull(); + it("probes non-Kimi NVIDIA models with a real chat-completions invocation (Stage A generalization)", () => { + let capturedArgv: string[] = []; + const result = probeRemoteProviderHealth("nvidia-prod", { + model: "meta/llama-3.3-70b-instruct", + getCredentialImpl: (envName) => + envName === "NVIDIA_INFERENCE_API_KEY" ? "nvapi-test" : null, + runCurlProbeImpl: (argv) => { + capturedArgv = argv; + return httpOk(); + }, + }); + + expect(result?.ok).toBe(true); + expect(result?.probed).toBe(true); + expect(result?.endpoint).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); + expect(capturedArgv.at(-1)).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); + const payload = JSON.parse(capturedArgv[capturedArgv.indexOf("-d") + 1]); + expect(payload.model).toBe("meta/llama-3.3-70b-instruct"); }); - it("returns null for unknown providers", () => { - expect(getRemoteProviderHealthEndpoint("unknown-provider")).toBeNull(); + it("always resolves NVIDIA credentials from NVIDIA_INFERENCE_API_KEY, not the route's default credential env", () => { + let resolvedEnvNames: string[] = []; + const result = probeRemoteProviderHealth("nvidia-nim", { + model: "meta/llama-3.3-70b-instruct", + getCredentialImpl: (envName) => { + resolvedEnvNames.push(envName); + return null; + }, + runCurlProbeImpl: () => httpOk(), + }); + + expect(resolvedEnvNames).toEqual(["NVIDIA_INFERENCE_API_KEY"]); + expect(resolvedEnvNames).not.toContain("OPENAI_API_KEY"); + expect(result?.probed).toBe(false); }); - }); - describe("probeRemoteProviderHealth", () => { - it("reports reachable when endpoint returns HTTP 200", () => { - const result = probeRemoteProviderHealth("openai-api", { - runCurlProbeImpl: () => ({ - ok: true, - httpStatus: 200, - curlStatus: 0, - body: "{}", - stderr: "", - message: "HTTP 200", - }), + it("still applies Kimi K2.6's model-specific payload treatment through the generalized helper", () => { + let capturedArgv: string[] = []; + let authConfigPath = ""; + const result = probeRemoteProviderHealth("nvidia-nim", { + model: "moonshotai/kimi-k2.6", + getCredentialImpl: (envName) => + envName === "NVIDIA_INFERENCE_API_KEY" ? "nvapi-test" : null, + runCurlProbeImpl: (argv) => { + capturedArgv = argv; + const configIndex = argv.indexOf("--config"); + authConfigPath = configIndex >= 0 ? argv[configIndex + 1] : ""; + return httpOk('{"choices":[{"message":{"content":"OK"}}]}'); + }, }); - expect(result).toEqual({ - ok: true, - probed: true, - providerLabel: "OpenAI", - endpoint: "https://api.openai.com/v1/models", - detail: "OpenAI endpoint is reachable at https://api.openai.com/v1/models.", + expect(result?.ok).toBe(true); + expect(result?.endpoint).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); + // PR #5975: the bearer credential must route through the central + // auth-config helper, never inline in argv. + expect(capturedArgv.join(" ")).not.toContain("nvapi-test"); + expect(fs.existsSync(authConfigPath)).toBe(false); + + const payload = JSON.parse(capturedArgv[capturedArgv.indexOf("-d") + 1]); + expect(payload).toEqual({ + model: "moonshotai/kimi-k2.6", + messages: [{ role: "user", content: "Reply with exactly: OK" }], + max_tokens: 8, + chat_template_kwargs: { thinking: false }, }); + expect(curlArgValue(capturedArgv, "--connect-timeout")).toBe("3"); + expect(curlArgValue(capturedArgv, "--max-time")).toBe("5"); }); - it("reports reachable when endpoint returns HTTP 401 (auth required)", () => { + it("uses a lightweight DeepSeek V4 Pro status payload and validates its SSE shape", () => { + let capturedArgv: string[] = []; const result = probeRemoteProviderHealth("nvidia-prod", { - runCurlProbeImpl: () => ({ - ok: false, - httpStatus: 401, - curlStatus: 0, - body: '{"error":"unauthorized"}', - stderr: "", - message: "HTTP 401: unauthorized", - }), + model: "deepseek-ai/deepseek-v4-pro", + getCredentialImpl: () => "nvapi-test", + runCurlProbeImpl: (argv) => { + capturedArgv = argv; + return httpOk('data: {"choices":[{"delta":{"content":"OK"}}]}\n\ndata: [DONE]\n'); + }, }); expect(result?.ok).toBe(true); - expect(result?.probed).toBe(true); - expect(result?.detail).toContain("reachable"); + expect(curlArgValue(capturedArgv, "--connect-timeout")).toBe("3"); + expect(curlArgValue(capturedArgv, "--max-time")).toBe("5"); + const payload = JSON.parse(capturedArgv[capturedArgv.indexOf("-d") + 1]); + expect(payload).toMatchObject({ max_tokens: 8, stream: true }); }); - it("reports reachable when endpoint returns HTTP 403 (forbidden)", () => { - const result = probeRemoteProviderHealth("anthropic-prod", { - runCurlProbeImpl: () => ({ - ok: false, - httpStatus: 403, - curlStatus: 0, - body: "", - stderr: "", - message: "HTTP 403", - }), + it.each([ + "deepseek-ai/deepseek-v4-pro", + "qwen/qwen3.5-397b-a17b", + "deepseek-ai/deepseek-v4-flash", + ])("reports the short status timeout as unverified for slow model %s", (model) => { + const result = probeRemoteProviderHealth("nvidia-prod", { + model, + getCredentialImpl: () => "nvapi-test", + runCurlProbeImpl: () => httpTimeout(), }); expect(result?.ok).toBe(true); + expect(result?.probed).toBe(false); + expect(result?.failureLabel).toBeUndefined(); + expect(result?.detail).toContain("model health was not verified"); + }); + + it("reports a malformed HTTP 200 body as unhealthy", () => { + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: () => "sk-test-secret", + runCurlProbeImpl: () => httpOk("upstream proxy"), + }); + + expect(result?.ok).toBe(false); expect(result?.probed).toBe(true); + expect(result?.failureLabel).toBe("unhealthy"); + expect(result?.detail).toContain("not a Chat Completions result"); }); - it("reports unreachable when connection is refused", () => { + it.each([ + ["numeric content", '{"choices":[{"message":{"content":123}}]}'], + ["numeric refusal", '{"choices":[{"message":{"refusal":123}}]}'], + [ + "malformed tool call", + '{"choices":[{"message":{"tool_calls":[{"type":"function","function":{"name":"probe","arguments":7}}]}}]}', + ], + ["numeric streaming delta", 'data: {"choices":[{"delta":{"content":123}}]}\n'], + ])("rejects a Chat Completions response with %s", (_description, body) => { const result = probeRemoteProviderHealth("openai-api", { - runCurlProbeImpl: () => ({ - ok: false, - httpStatus: 0, - curlStatus: 7, - body: "", - stderr: "Failed to connect", - message: "curl failed (exit 7): Failed to connect", - }), + model: "gpt-4o-mini", + getCredentialImpl: () => "sk-test-secret", + runCurlProbeImpl: () => httpOk(body), }); expect(result?.ok).toBe(false); expect(result?.probed).toBe(true); - expect(result?.detail).toContain("unreachable"); - expect(result?.detail).toContain("Check your network connection"); + expect(result?.failureLabel).toBe("unhealthy"); + expect(result?.detail).toContain("not a Chat Completions result"); }); - it("reports unreachable on timeout", () => { - const result = probeRemoteProviderHealth("gemini-api", { - runCurlProbeImpl: () => ({ - ok: false, - httpStatus: 0, - curlStatus: 28, - body: "", - stderr: "Operation timed out", - message: "curl failed (exit 28): Operation timed out", - }), + it("reports a provider error envelope returned with HTTP 200 as unhealthy", () => { + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: () => "sk-test-secret", + runCurlProbeImpl: () => httpOk('{"error":{"message":"model unavailable"}}'), }); expect(result?.ok).toBe(false); expect(result?.probed).toBe(true); - expect(result?.endpoint).toBe("https://generativelanguage.googleapis.com/v1/models"); + expect(result?.failureLabel).toBe("unhealthy"); + expect(result?.detail).toContain("error envelope"); }); - it("returns not-probed status for compatible-endpoint", () => { - const result = probeRemoteProviderHealth("compatible-endpoint"); + it.each([ + ["gemini-api", "gemini-2.5-flash", "{}"], + ["nvidia-prod", "meta/llama-3.3-70b-instruct", '{"error":{"message":"model unavailable"}}'], + ])("rejects malformed HTTP 200 responses from %s", (provider, model, body) => { + const result = probeRemoteProviderHealth(provider, { + model, + getCredentialImpl: () => "test-secret", + runCurlProbeImpl: () => httpOk(body), + }); - expect(result?.ok).toBe(true); - expect(result?.probed).toBe(false); - expect(result?.detail).toContain("not known"); + expect(result?.ok).toBe(false); + expect(result?.probed).toBe(true); + expect(result?.failureLabel).toBe("unhealthy"); }); - it("returns not-probed status for compatible-anthropic-endpoint", () => { - const result = probeRemoteProviderHealth("compatible-anthropic-endpoint"); + it("reports unauthorized (not healthy) on HTTP 401", () => { + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: () => "sk-test-secret", + runCurlProbeImpl: () => httpUnauthorized(), + }); - expect(result?.ok).toBe(true); - expect(result?.probed).toBe(false); + expect(result?.ok).toBe(false); + expect(result?.probed).toBe(true); + expect(result?.failureLabel).toBe("unauthorized"); }); - it("returns null for local providers", () => { - expect(probeRemoteProviderHealth("ollama-local")).toBeNull(); - expect(probeRemoteProviderHealth("vllm-local")).toBeNull(); + it("reports unhealthy on a non-auth HTTP failure", () => { + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: () => "sk-test-secret", + runCurlProbeImpl: () => httpServerError(), + }); + + expect(result?.ok).toBe(false); + expect(result?.probed).toBe(true); + expect(result?.failureLabel).toBe("unhealthy"); }); - it("returns null for unknown providers", () => { - expect(probeRemoteProviderHealth("unknown-provider")).toBeNull(); + it("reports unreachable when the connection is refused", () => { + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: () => "sk-test-secret", + runCurlProbeImpl: () => connectionRefused(), + }); + + expect(result?.ok).toBe(false); + expect(result?.probed).toBe(true); + expect(result?.failureLabel).toBe("unreachable"); }); - it("passes correct curl arguments to the probe", () => { - let capturedArgv: string[] = []; - probeRemoteProviderHealth("openai-api", { - runCurlProbeImpl: (argv) => { - capturedArgv = argv; - return { - ok: true, - httpStatus: 200, - curlStatus: 0, - body: "", - stderr: "", - message: "", - }; + it("reports unhealthy (not probed) when credential lookup throws", () => { + let called = false; + const result = probeRemoteProviderHealth("openai-api", { + model: "gpt-4o-mini", + getCredentialImpl: () => { + throw new Error("credential store unavailable"); + }, + runCurlProbeImpl: () => { + called = true; + return httpOk(); }, }); - expect(capturedArgv).toEqual([ - "-sS", - "--connect-timeout", - "3", - "--max-time", - "5", - "https://api.openai.com/v1/models", - ]); + expect(called).toBe(false); + expect(result?.ok).toBe(false); + expect(result?.probed).toBe(false); + expect(result?.failureLabel).toBe("unhealthy"); + expect(result?.detail).toContain("credential store unavailable"); }); + }); - it("uses Kimi chat completions for NVIDIA managed inference when a credential is available", () => { + describe("probeRemoteProviderHealth — Anthropic Messages", () => { + it("invokes /v1/messages with x-api-key routed only through the config tmpfile", () => { let capturedArgv: string[] = []; let authConfigPath = ""; let authConfigContent = ""; - const result = probeRemoteProviderHealth("nvidia-prod", { - model: "moonshotai/kimi-k2.6", + const result = probeRemoteProviderHealth("anthropic-prod", { + model: "claude-sonnet-4-6", getCredentialImpl: (envName) => - envName === "NVIDIA_INFERENCE_API_KEY" ? "nvapi-test" : null, + envName === "ANTHROPIC_API_KEY" ? "sk-ant-test-secret" : null, runCurlProbeImpl: (argv) => { capturedArgv = argv; const configIndex = argv.indexOf("--config"); authConfigPath = configIndex >= 0 ? argv[configIndex + 1] : ""; authConfigContent = authConfigPath ? fs.readFileSync(authConfigPath, "utf8") : ""; - return { - ok: true, - httpStatus: 200, - curlStatus: 0, - body: '{"choices":[{"message":{"content":"OK"}}]}', - stderr: "", - message: "HTTP 200", - }; + return httpOk('{"content":[{"type":"text","text":"OK"}]}'); }, }); expect(result?.ok).toBe(true); expect(result?.probed).toBe(true); - expect(result?.endpoint).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); - expect(capturedArgv.join(" ")).not.toContain("nvapi-test"); - expect(capturedArgv.join(" ")).not.toContain("Authorization: Bearer"); - expect(capturedArgv).toContain("--config"); - // PR #5975: Kimi health probe must route the bearer through the central - // auth-config helper, identifiable by its `nemoclaw-kimi-health-curl-` - // tmpfile prefix. - expect(authConfigPath).toContain("nemoclaw-kimi-health-curl-"); - expect(authConfigContent).toContain("Authorization: Bearer nvapi-test"); + expect(result?.providerLabel).toBe("Anthropic"); + expect(result?.endpoint).toBe("https://api.anthropic.com/v1/messages"); + expect(capturedArgv.at(-1)).toBe("https://api.anthropic.com/v1/messages"); + + const joined = capturedArgv.join(" "); + expect(joined).not.toContain("sk-ant-test-secret"); + expect(authConfigContent).toContain("x-api-key: sk-ant-test-secret"); expect(fs.existsSync(authConfigPath)).toBe(false); - expect(capturedArgv).toContain("--connect-timeout"); - expect(capturedArgv[capturedArgv.indexOf("--connect-timeout") + 1]).toBe("3"); - expect(capturedArgv).toContain("--max-time"); - expect(capturedArgv[capturedArgv.indexOf("--max-time") + 1]).toBe("5"); - expect(capturedArgv.at(-1)).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); + + // anthropic-version is not a secret and stays a plain inline header arg. + expect(capturedArgv).toContain("anthropic-version: 2023-06-01"); const payload = JSON.parse(capturedArgv[capturedArgv.indexOf("-d") + 1]); expect(payload).toEqual({ - model: "moonshotai/kimi-k2.6", - messages: [{ role: "user", content: "Reply with exactly: OK" }], + model: "claude-sonnet-4-6", max_tokens: 8, - chat_template_kwargs: { thinking: false }, + messages: [{ role: "user", content: "Reply with exactly: OK" }], }); }); - it("does not fall back to provider-level NVIDIA /models for Kimi without a credential", () => { + it("skips the invocation probe for anthropic-prod without a credential", () => { let called = false; - const result = probeRemoteProviderHealth("nvidia-prod", { - model: "moonshotai/kimi-k2.6", + const result = probeRemoteProviderHealth("anthropic-prod", { + model: "claude-sonnet-4-6", getCredentialImpl: () => null, runCurlProbeImpl: () => { called = true; - return { - ok: false, - httpStatus: 0, - curlStatus: 28, - body: "", - stderr: "Operation timed out", - message: "curl failed (exit 28): Operation timed out", - }; + return httpOk(); }, }); expect(called).toBe(false); expect(result?.ok).toBe(true); expect(result?.probed).toBe(false); - expect(result?.endpoint).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); - expect(result?.detail).toContain("NVIDIA_INFERENCE_API_KEY"); - expect(result?.detail).toContain("provider-level /models"); + expect(result?.detail).toContain("ANTHROPIC_API_KEY"); }); - it("reports Kimi health as unhealthy when credential lookup fails", () => { - let called = false; - const result = probeRemoteProviderHealth("nvidia-prod", { - model: "moonshotai/kimi-k2.6", - getCredentialImpl: () => { - throw new Error("credential store unavailable"); - }, - runCurlProbeImpl: () => { - called = true; - return { - ok: false, - httpStatus: 0, - curlStatus: 28, - body: "", - stderr: "Operation timed out", - message: "curl failed (exit 28): Operation timed out", - }; - }, + it("reports unauthorized on HTTP 403", () => { + const result = probeRemoteProviderHealth("anthropic-prod", { + model: "claude-sonnet-4-6", + getCredentialImpl: () => "sk-ant-test-secret", + runCurlProbeImpl: () => ({ + ok: false, + httpStatus: 403, + curlStatus: 0, + body: "", + stderr: "", + message: "HTTP 403", + }), + }); + + expect(result?.ok).toBe(false); + expect(result?.failureLabel).toBe("unauthorized"); + }); + + it("reports a non-Messages HTTP 200 response as unhealthy", () => { + const result = probeRemoteProviderHealth("anthropic-prod", { + model: "claude-sonnet-4-6", + getCredentialImpl: () => "sk-ant-test-secret", + runCurlProbeImpl: () => httpOk('{"message":"OK"}'), }); - expect(called).toBe(false); expect(result?.ok).toBe(false); - expect(result?.probed).toBe(false); expect(result?.failureLabel).toBe("unhealthy"); - expect(result?.detail).toContain("credential store unavailable"); + expect(result?.detail).toContain("not an Anthropic Messages result"); + }); + + it("reports an Anthropic error envelope returned with HTTP 200 as unhealthy", () => { + const result = probeRemoteProviderHealth("anthropic-prod", { + model: "claude-sonnet-4-6", + getCredentialImpl: () => "sk-ant-test-secret", + runCurlProbeImpl: () => httpOk('{"type":"error","error":{"type":"overloaded_error"}}'), + }); + + expect(result?.ok).toBe(false); + expect(result?.failureLabel).toBe("unhealthy"); + expect(result?.detail).toContain("error envelope"); + }); + + it.each([ + ["an unknown block type", '{"content":[{"type":"bogus","text":"OK"}]}'], + ["numeric text", '{"content":[{"type":"text","text":123}]}'], + ["incomplete thinking", '{"content":[{"type":"thinking","thinking":"OK"}]}'], + ])("rejects an Anthropic response with %s", (_description, body) => { + const result = probeRemoteProviderHealth("anthropic-prod", { + model: "claude-sonnet-4-6", + getCredentialImpl: () => "sk-ant-test-secret", + runCurlProbeImpl: () => httpOk(body), + }); + + expect(result?.ok).toBe(false); + expect(result?.probed).toBe(true); + expect(result?.failureLabel).toBe("unhealthy"); + expect(result?.detail).toContain("not an Anthropic Messages result"); + }); + + it("reports the short status timeout as unverified", () => { + const result = probeRemoteProviderHealth("anthropic-prod", { + model: "claude-sonnet-4-6", + getCredentialImpl: () => "sk-ant-test-secret", + runCurlProbeImpl: () => httpTimeout(), + }); + + expect(result?.ok).toBe(true); + expect(result?.probed).toBe(false); + expect(result?.failureLabel).toBeUndefined(); + expect(result?.detail).toContain("model health was not verified"); + }); + }); + + describe("probeRemoteProviderHealth — unrecognized and pass-through providers", () => { + it("returns not-probed status for compatible-endpoint", () => { + const result = probeRemoteProviderHealth("compatible-endpoint"); + + expect(result?.ok).toBe(true); + expect(result?.probed).toBe(false); + expect(result?.detail).toContain("not known"); + }); + + it("returns not-probed status for compatible-anthropic-endpoint", () => { + const result = probeRemoteProviderHealth("compatible-anthropic-endpoint"); + + expect(result?.ok).toBe(true); + expect(result?.probed).toBe(false); + }); + + it("returns null for local providers", () => { + expect(probeRemoteProviderHealth("ollama-local")).toBeNull(); + expect(probeRemoteProviderHealth("vllm-local")).toBeNull(); + }); + + it("returns null for unknown providers", () => { + expect(probeRemoteProviderHealth("unknown-provider")).toBeNull(); + }); + + it("returns null for hermes-provider and openrouter, explicitly out of scope (#6846)", () => { + expect(probeRemoteProviderHealth("hermes-provider")).toBeNull(); + expect(probeRemoteProviderHealth("openrouter")).toBeNull(); }); }); @@ -344,65 +589,31 @@ describe("inference health", () => { it("delegates to remote probe for openai-api", () => { const result = probeProviderHealth("openai-api", { - runCurlProbeImpl: () => ({ - ok: false, - httpStatus: 401, - curlStatus: 0, - body: "", - stderr: "", - message: "HTTP 401", - }), + model: "gpt-4o-mini", + getCredentialImpl: () => "sk-test-secret", + runCurlProbeImpl: () => httpUnauthorized(), }); - expect(result?.ok).toBe(true); + expect(result?.ok).toBe(false); expect(result?.probed).toBe(true); expect(result?.providerLabel).toBe("OpenAI"); + expect(result?.failureLabel).toBe("unauthorized"); }); - it("keeps non-Kimi NVIDIA models on the provider reachability probe", () => { - let capturedArgv: string[] = []; - const result = probeProviderHealth("nvidia-prod", { - model: "minimaxai/minimax-m2.7", - runCurlProbeImpl: (argv) => { - capturedArgv = argv; - return { - ok: false, - httpStatus: 401, - curlStatus: 0, - body: "", - stderr: "", - message: "HTTP 401", - }; - }, - }); - - expect(result?.ok).toBe(true); - expect(result?.endpoint).toBe(`${BUILD_ENDPOINT_URL}/models`); - expect(capturedArgv.at(-1)).toBe(`${BUILD_ENDPOINT_URL}/models`); - expect(capturedArgv).not.toContain(`${BUILD_ENDPOINT_URL}/chat/completions`); - }); - - it("uses model-aware Kimi probing through the unified health entry point", () => { + it("uses model-aware chat-completions probing through the unified health entry point", () => { let capturedArgv: string[] = []; const result = probeProviderHealth("nvidia-nim", { model: "moonshotai/kimi-k2.6", getCredentialImpl: () => "nvapi-test", runCurlProbeImpl: (argv) => { capturedArgv = argv; - return { - ok: false, - httpStatus: 401, - curlStatus: 0, - body: '{"error":"unauthorized"}', - stderr: "", - message: "HTTP 401: unauthorized", - }; + return httpUnauthorized(); }, }); expect(result?.ok).toBe(false); expect(result?.probed).toBe(true); - expect(result?.failureLabel).toBe("unhealthy"); + expect(result?.failureLabel).toBe("unauthorized"); expect(result?.endpoint).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); expect(capturedArgv.at(-1)).toBe(`${BUILD_ENDPOINT_URL}/chat/completions`); }); diff --git a/src/lib/inference/health.ts b/src/lib/inference/health.ts index e18076fcf32..493450dd93a 100644 --- a/src/lib/inference/health.ts +++ b/src/lib/inference/health.ts @@ -3,11 +3,13 @@ /** * Unified inference health probing for both local and remote providers. - * Delegates to probeLocalProviderHealth for vllm-local/ollama-local, - * and performs lightweight reachability checks for remote cloud providers. + * Delegates to probeLocalProviderHealth for vllm-local/ollama-local, and + * performs authenticated model-invocation checks for remote cloud providers + * so a probe result actually proves the configured model is invocable + * rather than just that the provider's endpoint is network-reachable. */ -import { createBearerAuthConfig } from "../adapters/http/auth-config"; +import { createBearerAuthConfig, createXApiKeyAuthConfig } from "../adapters/http/auth-config"; import type { CurlProbeOptions, CurlProbeResult } from "../adapters/http/probe"; import { runCurlProbe } from "../adapters/http/probe"; import { normalizeCredentialValue, resolveProviderCredential } from "../credentials/store"; @@ -30,6 +32,12 @@ export interface ProviderHealthStatus { * line. Absent for providers with a single hop. (#3265) */ probeLabel?: string; + /** + * Overrides the rendered word for a healthy/ok result (e.g. "reachable" + * for a network-only probe that does not prove model invocability). + * Absent producers keep the default "healthy" rendering. (#6846) + */ + okLabel?: string; /** * Additional probes that share the same Inference rendering. Used to * surface the Ollama auth-proxy hop alongside the backend probe so a @@ -48,10 +56,23 @@ export interface ProviderHealthProbeOptions { const COMPATIBLE_PROVIDERS = new Set(["compatible-endpoint", "compatible-anthropic-endpoint"]); const NVIDIA_MANAGED_PROVIDERS = new Set(["nvidia-prod", "nvidia-nim"]); const NVIDIA_HEALTH_CREDENTIAL_ENV = "NVIDIA_INFERENCE_API_KEY"; -const KIMI_K26_MODEL = "moonshotai/kimi-k2.6"; -const KIMI_STATUS_CONNECT_TIMEOUT_SECONDS = "3"; -const KIMI_STATUS_MAX_TIME_SECONDS = "5"; -const KIMI_HEALTH_CURL_CONFIG_PREFIX = "nemoclaw-kimi-health-curl"; +const HEALTH_PROBE_CONNECT_TIMEOUT_SECONDS = "3"; +const HEALTH_PROBE_MAX_TIME_SECONDS = "5"; +const HEALTH_CURL_CONFIG_PREFIX = "nemoclaw-health-curl"; +const OPENAI_CHAT_COMPLETIONS_ENDPOINT = "https://api.openai.com/v1/chat/completions"; +// The native Gemini REST surface (v1/models, v1beta/models) requires +// ?key=/x-goog-api-key auth and rejects a plain Bearer token. Its +// OpenAI-compatible shim at /v1beta/openai/ accepts Bearer auth and is what +// the rest of NemoClaw's onboarding probes already target (see +// onboard-probes.ts getProbeAuthMode), so the health probe uses it too +// instead of a native-REST URL that would falsely read as unauthorized. +const GEMINI_CHAT_COMPLETIONS_ENDPOINT = + "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"; +const ANTHROPIC_MESSAGES_ENDPOINT = "https://api.anthropic.com/v1/messages"; +const ANTHROPIC_VERSION_HEADER = "anthropic-version: 2023-06-01"; +const HEALTH_PROBE_MAX_TOKENS = 8; +const CURL_TIMEOUT_STATUS = 28; +const NODE_SPAWN_TIMEOUT_STATUS = -110; function normalizeModel(model: string | null | undefined): string | null { if (typeof model !== "string") return null; @@ -59,10 +80,6 @@ function normalizeModel(model: string | null | undefined): string | null { return trimmed || null; } -function isKimiK26Model(model: string | null | undefined): model is string { - return normalizeModel(model)?.toLowerCase() === KIMI_K26_MODEL; -} - function resolveProbeCredential(envName: string, options: ProviderHealthProbeOptions): string { const raw = options.getCredentialImpl ? options.getCredentialImpl(envName) @@ -82,143 +99,374 @@ function replaceCurlArgValue(argv: string[], name: string, value: string): strin function useStatusProbeTiming(argv: string[]): string[] { return replaceCurlArgValue( - replaceCurlArgValue(argv, "--connect-timeout", KIMI_STATUS_CONNECT_TIMEOUT_SECONDS), + replaceCurlArgValue(argv, "--connect-timeout", HEALTH_PROBE_CONNECT_TIMEOUT_SECONDS), "--max-time", - KIMI_STATUS_MAX_TIME_SECONDS, + HEALTH_PROBE_MAX_TIME_SECONDS, ); } -function buildKimiStatusProbeCurlArgs( +function capStatusProbeOutput(argv: string[]): string[] { + const next = [...argv]; + const dataIndex = next.indexOf("-d"); + if (dataIndex < 0 || dataIndex + 1 >= next.length) return next; + const payload = parseJsonRecord(next[dataIndex + 1]); + if (!payload) return next; + if ("max_tokens" in payload) payload.max_tokens = HEALTH_PROBE_MAX_TOKENS; + if ("max_completion_tokens" in payload) { + payload.max_completion_tokens = HEALTH_PROBE_MAX_TOKENS; + } + next[dataIndex + 1] = JSON.stringify(payload); + return next; +} + +function buildChatCompletionsStatusProbeCurlArgs( model: string, endpoint: string, authArgs: readonly string[], isWsl?: boolean, ): string[] { - const args = useStatusProbeTiming( - getChatCompletionsProbeCurlArgs({ - credentialArgs: [], - model, - url: endpoint, - isWsl, - }), + const args = capStatusProbeOutput( + useStatusProbeTiming( + getChatCompletionsProbeCurlArgs({ + credentialArgs: [], + model, + url: endpoint, + isWsl, + }), + ), ); const url = args.pop() || endpoint; return [...args, ...authArgs, url]; } -/** - * Maps remote provider names to their health-check endpoints. - * Returns null for local providers, compatible-* providers (unknown URL), - * and unrecognized provider names. - */ -export function getRemoteProviderHealthEndpoint(provider: string): string | null { - switch (provider) { - case "nvidia-prod": - case "nvidia-nim": - return `${BUILD_ENDPOINT_URL}/models`; - case "openai-api": - return "https://api.openai.com/v1/models"; - case "anthropic-prod": - return "https://api.anthropic.com/v1/models"; - case "gemini-api": - return "https://generativelanguage.googleapis.com/v1/models"; - default: - return null; +function buildAnthropicMessagesProbeCurlArgs( + model: string, + endpoint: string, + authArgs: readonly string[], +): string[] { + return [ + "-sS", + "--connect-timeout", + HEALTH_PROBE_CONNECT_TIMEOUT_SECONDS, + "--max-time", + HEALTH_PROBE_MAX_TIME_SECONDS, + "-H", + "Content-Type: application/json", + "-H", + ANTHROPIC_VERSION_HEADER, + ...authArgs, + "-d", + JSON.stringify({ + model, + max_tokens: HEALTH_PROBE_MAX_TOKENS, + messages: [{ role: "user", content: "Reply with exactly: OK" }], + }), + endpoint, + ]; +} + +type ResponseValidation = { ok: true } | { ok: false; reason: string }; + +function isJsonRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function parseJsonRecord(body: string): Record | null { + try { + const parsed: unknown = JSON.parse(body); + return isJsonRecord(parsed) ? parsed : null; + } catch { + return null; } } -function buildRemoteProbeDetail( - providerLabel: string, - endpoint: string, - reachable: boolean, - result: CurlProbeResult, -): string { - if (reachable) { - return `${providerLabel} endpoint is reachable at ${endpoint}.`; +function hasProviderErrorEnvelope(payload: Record): boolean { + return ( + ("error" in payload && payload.error !== null && payload.error !== undefined) || + payload.type === "error" + ); +} + +function isValidChatContentPart(value: unknown): boolean { + if (!isJsonRecord(value) || typeof value.type !== "string") return false; + if (value.type === "text") return typeof value.text === "string"; + if (value.type === "refusal") return typeof value.refusal === "string"; + return false; +} + +function isValidChatContent(value: unknown): boolean { + return ( + value === null || + typeof value === "string" || + (Array.isArray(value) && value.length > 0 && value.every(isValidChatContentPart)) + ); +} + +function isValidChatToolCall(value: unknown): boolean { + if (!isJsonRecord(value) || value.type !== "function" || typeof value.id !== "string") { + return false; + } + const fn = value.function; + return isJsonRecord(fn) && typeof fn.name === "string" && typeof fn.arguments === "string"; +} + +function hasValidChatMessageFields( + message: Record, + allowStreamingDelta: boolean, +): boolean { + let recognizedField = false; + for (const field of ["content", "reasoning_content", "refusal"] as const) { + if (!(field in message)) continue; + recognizedField = true; + const value = message[field]; + const valid = + field === "content" ? isValidChatContent(value) : value === null || typeof value === "string"; + if (!valid) return false; } + if ("tool_calls" in message) { + recognizedField = true; + if ( + !Array.isArray(message.tool_calls) || + message.tool_calls.length === 0 || + !message.tool_calls.every(isValidChatToolCall) + ) { + return false; + } + } + if (allowStreamingDelta && "role" in message) { + recognizedField = true; + if (message.role !== "assistant") return false; + } + return recognizedField; +} + +function hasChatCompletionsChoice( + payload: Record, + allowStreamingDelta: boolean, +): boolean { + if (!Array.isArray(payload.choices) || payload.choices.length === 0) return false; + return payload.choices.some((choice) => { + if (!isJsonRecord(choice)) return false; + const message = choice.message; + if (isJsonRecord(message)) { + return hasValidChatMessageFields(message, false); + } + const delta = choice.delta; + return allowStreamingDelta && isJsonRecord(delta) && hasValidChatMessageFields(delta, true); + }); +} + +function isValidAnthropicContentBlock(value: unknown): boolean { + if (!isJsonRecord(value) || typeof value.type !== "string") return false; + if (value.type === "text") return typeof value.text === "string"; + if (value.type === "thinking") { + return typeof value.thinking === "string" && typeof value.signature === "string"; + } + if (value.type === "redacted_thinking") return typeof value.data === "string"; + if (value.type === "tool_use") { + return ( + typeof value.id === "string" && typeof value.name === "string" && isJsonRecord(value.input) + ); + } + return false; +} + +function validateChatCompletionsResponse(body: string): ResponseValidation { + const parsed = parseJsonRecord(body); + if (parsed) { + if (hasProviderErrorEnvelope(parsed)) { + return { ok: false, reason: "provider returned an error envelope" }; + } + return hasChatCompletionsChoice(parsed, false) + ? { ok: true } + : { ok: false, reason: "response was not a Chat Completions result" }; + } + + // DeepSeek V4 Pro's model-specific probe requests streaming output. Accept + // only a stream containing at least one structured Chat Completions chunk; + // a bare 2xx, malformed SSE, or an SSE error envelope is not health proof. + let hasValidChunk = false; + for (const line of body.split("\n")) { + const match = /^data:\s*(.+)$/i.exec(line.trim()); + if (!match) continue; + const data = match[1].trim(); + if (data === "[DONE]") continue; + const event = parseJsonRecord(data); + if (!event) continue; + if (hasProviderErrorEnvelope(event)) { + return { ok: false, reason: "provider returned an error envelope" }; + } + if (hasChatCompletionsChoice(event, true)) hasValidChunk = true; + } + return hasValidChunk + ? { ok: true } + : { ok: false, reason: "response was not a Chat Completions result" }; +} + +function validateAnthropicMessagesResponse(body: string): ResponseValidation { + const parsed = parseJsonRecord(body); + if (!parsed) return { ok: false, reason: "response was not an Anthropic Messages result" }; + if (hasProviderErrorEnvelope(parsed)) { + return { ok: false, reason: "provider returned an error envelope" }; + } + if (!Array.isArray(parsed.content) || parsed.content.length === 0) { + return { ok: false, reason: "response was not an Anthropic Messages result" }; + } + const hasContentBlock = parsed.content.some(isValidAnthropicContentBlock); + return hasContentBlock + ? { ok: true } + : { ok: false, reason: "response was not an Anthropic Messages result" }; +} + +function validateInvocationProbeResult( + result: CurlProbeResult, + validateResponse: (body: string) => ResponseValidation, +): CurlProbeResult { + if (!result.ok) return result; + const validation = validateResponse(result.body); + if (validation.ok) return result; + return { + ok: false, + httpStatus: result.httpStatus, + curlStatus: result.curlStatus, + body: result.body, + stderr: result.stderr, + message: `HTTP ${result.httpStatus}: ${validation.reason}`, + }; +} + +function isHealthProbeTimeout(result: CurlProbeResult): boolean { return ( - `${providerLabel} endpoint at ${endpoint} is unreachable. ` + - `Check your network connection. (${result.message})` + !result.ok && + (result.curlStatus === CURL_TIMEOUT_STATUS || result.curlStatus === NODE_SPAWN_TIMEOUT_STATUS) ); } -function buildKimiChatCompletionsDetail( +function classifyHealthProbeFailureLabel( + result: CurlProbeResult, +): "unreachable" | "unauthorized" | "unhealthy" { + if (result.curlStatus !== 0) return "unreachable"; + if (result.httpStatus === 401 || result.httpStatus === 403) return "unauthorized"; + return "unhealthy"; +} + +function buildInvocationProbeDetail( providerLabel: string, endpoint: string, + credentialEnv: string, healthy: boolean, result: CurlProbeResult, ): string { - const route = `${providerLabel} Kimi K2.6 chat-completions route`; + const route = `${providerLabel} model-invocation probe`; if (healthy) { - return `${route} is healthy at ${endpoint}.`; + return `${route} succeeded at ${endpoint}.`; } return ( - `${route} at ${endpoint} is not healthy. ` + - `Check your network connection or ${NVIDIA_HEALTH_CREDENTIAL_ENV}. (${result.message})` + `${route} at ${endpoint} did not succeed. ` + + `Check your network connection or ${credentialEnv}. (${result.message})` ); } -function probeNvidiaKimiK26Health( - provider: string, +function missingCredentialHealthStatus( + providerLabel: string, + endpoint: string, + credentialEnv: string, +): ProviderHealthStatus { + return { + ok: true, + probed: false, + providerLabel, + endpoint, + detail: + `${providerLabel} health requires ${credentialEnv}; ` + + "skipping model-invocation probe instead of reporting endpoint reachability as healthy.", + }; +} + +function timedOutHealthStatus( + providerLabel: string, + endpoint: string, + credentialEnv: string, + result: CurlProbeResult, +): ProviderHealthStatus { + return { + ok: true, + probed: false, + providerLabel, + endpoint, + detail: + `${providerLabel} model-invocation probe did not finish within the ` + + `${HEALTH_PROBE_MAX_TIME_SECONDS}s status budget; model health was not verified. ` + + `Check your network connection or ${credentialEnv}. (${result.message})`, + }; +} + +function credentialErrorHealthStatus( + providerLabel: string, + endpoint: string, + credentialEnv: string, + stage: "resolve" | "prepare", + error: unknown, +): ProviderHealthStatus { + const reason = error instanceof Error ? error.message : String(error); + const action = stage === "resolve" ? "resolve" : "prepare"; + return { + ok: false, + probed: false, + providerLabel, + endpoint, + failureLabel: "unhealthy", + detail: `Could not ${action} ${credentialEnv} for ${providerLabel} health. (${reason})`, + }; +} + +/** + * Probes a Bearer-auth, OpenAI-compatible chat-completions endpoint by + * sending a real invocation with the configured model. Covers NVIDIA-managed + * providers (all models, not just Kimi K2.6), OpenAI, and Gemini's + * OpenAI-compatible surface — mechanistically identical aside from + * credential env, endpoint, and label. + */ +function probeChatCompletionsProviderHealth( + providerLabel: string, model: string, + credentialEnv: string, + endpoint: string, options: ProviderHealthProbeOptions, ): ProviderHealthStatus { - const config = getProviderSelectionConfig(provider, model); - const providerLabel = config?.providerLabel ?? provider; - const endpoint = `${BUILD_ENDPOINT_URL}/chat/completions`; let apiKey = ""; try { - apiKey = resolveProbeCredential(NVIDIA_HEALTH_CREDENTIAL_ENV, options); + apiKey = resolveProbeCredential(credentialEnv, options); } catch (error) { - const reason = error instanceof Error ? error.message : String(error); - return { - ok: false, - probed: false, - providerLabel, - endpoint, - failureLabel: "unhealthy", - detail: `Could not resolve ${NVIDIA_HEALTH_CREDENTIAL_ENV} for Kimi K2.6 health. (${reason})`, - }; + return credentialErrorHealthStatus(providerLabel, endpoint, credentialEnv, "resolve", error); } if (!apiKey) { - return { - ok: true, - probed: false, - providerLabel, - endpoint, - detail: - `Kimi K2.6 health requires ${NVIDIA_HEALTH_CREDENTIAL_ENV}; ` + - "skipping model-specific chat-completions probe instead of using provider-level /models reachability.", - }; + return missingCredentialHealthStatus(providerLabel, endpoint, credentialEnv); } const runCurlProbeImpl = options.runCurlProbeImpl ?? runCurlProbe; let authConfig: ReturnType; try { - authConfig = createBearerAuthConfig(apiKey, { prefix: KIMI_HEALTH_CURL_CONFIG_PREFIX }); + authConfig = createBearerAuthConfig(apiKey, { prefix: HEALTH_CURL_CONFIG_PREFIX }); } catch (error) { - const reason = error instanceof Error ? error.message : String(error); - return { - ok: false, - probed: false, - providerLabel, - endpoint, - failureLabel: "unhealthy", - detail: `Could not prepare ${NVIDIA_HEALTH_CREDENTIAL_ENV} for Kimi K2.6 health. (${reason})`, - }; + return credentialErrorHealthStatus(providerLabel, endpoint, credentialEnv, "prepare", error); } - const result = (() => { + const rawResult = (() => { try { return runCurlProbeImpl( - buildKimiStatusProbeCurlArgs(model, endpoint, authConfig.args, options.isWsl), + buildChatCompletionsStatusProbeCurlArgs(model, endpoint, authConfig.args, options.isWsl), { trustedConfigFiles: authConfig.trustedConfigFiles }, ); } finally { authConfig.cleanup(); } })(); + if (isHealthProbeTimeout(rawResult)) { + return timedOutHealthStatus(providerLabel, endpoint, credentialEnv, rawResult); + } + const result = validateInvocationProbeResult(rawResult, validateChatCompletionsResponse); const healthy = result.ok; return { @@ -226,18 +474,82 @@ function probeNvidiaKimiK26Health( probed: true, providerLabel, endpoint, - detail: buildKimiChatCompletionsDetail(providerLabel, endpoint, healthy, result), - ...(healthy ? {} : { failureLabel: result.curlStatus === 0 ? "unhealthy" : "unreachable" }), + detail: buildInvocationProbeDetail(providerLabel, endpoint, credentialEnv, healthy, result), + ...(healthy ? {} : { failureLabel: classifyHealthProbeFailureLabel(result) }), }; } /** - * Probes a remote provider endpoint for reachability. - * Any HTTP response (including 401/403) counts as reachable — we are - * not authenticating, just checking that the endpoint is up. + * Probes Anthropic's Messages API by sending a real invocation with the + * configured model. Separate from the Bearer-auth helper above because + * Anthropic's auth shape differs (`x-api-key` + `anthropic-version` header, + * `/v1/messages` endpoint and payload shape). + */ +function probeAnthropicMessagesProviderHealth( + providerLabel: string, + model: string, + credentialEnv: string, + endpoint: string, + options: ProviderHealthProbeOptions, +): ProviderHealthStatus { + let apiKey = ""; + try { + apiKey = resolveProbeCredential(credentialEnv, options); + } catch (error) { + return credentialErrorHealthStatus(providerLabel, endpoint, credentialEnv, "resolve", error); + } + + if (!apiKey) { + return missingCredentialHealthStatus(providerLabel, endpoint, credentialEnv); + } + + const runCurlProbeImpl = options.runCurlProbeImpl ?? runCurlProbe; + let authConfig: ReturnType; + try { + authConfig = createXApiKeyAuthConfig(apiKey, { prefix: HEALTH_CURL_CONFIG_PREFIX }); + } catch (error) { + return credentialErrorHealthStatus(providerLabel, endpoint, credentialEnv, "prepare", error); + } + + const rawResult = (() => { + try { + return runCurlProbeImpl( + buildAnthropicMessagesProbeCurlArgs(model, endpoint, authConfig.args), + { + trustedConfigFiles: authConfig.trustedConfigFiles, + }, + ); + } finally { + authConfig.cleanup(); + } + })(); + if (isHealthProbeTimeout(rawResult)) { + return timedOutHealthStatus(providerLabel, endpoint, credentialEnv, rawResult); + } + const result = validateInvocationProbeResult(rawResult, validateAnthropicMessagesResponse); + const healthy = result.ok; + + return { + ok: healthy, + probed: true, + providerLabel, + endpoint, + detail: buildInvocationProbeDetail(providerLabel, endpoint, credentialEnv, healthy, result), + ...(healthy ? {} : { failureLabel: classifyHealthProbeFailureLabel(result) }), + }; +} + +/** + * Probes a remote provider by invoking its configured model through a real + * chat-completions (or Messages, for Anthropic) request, proving the model + * is actually invocable rather than just that the endpoint is reachable. * - * Returns null for local providers and unrecognized providers. - * Returns a "not probed" status for compatible-* providers (unknown URL). + * Returns null for local providers and unrecognized providers. Returns a + * "not probed" status for compatible-* providers (unknown URL). `hermes- + * provider` and `openrouter` are intentionally not covered here: both are + * net-new integration surface (zero health signal today, not a regression), + * and hermes-provider's OAuth flow mints a short-lived key that a host-side + * probe reading the ambient credential env would not observe. */ export function probeRemoteProviderHealth( provider: string, @@ -257,29 +569,49 @@ export function probeRemoteProviderHealth( }; } - if (NVIDIA_MANAGED_PROVIDERS.has(provider) && isKimiK26Model(model)) { - return probeNvidiaKimiK26Health(provider, model, options); + if (!config?.model) return null; + + if (NVIDIA_MANAGED_PROVIDERS.has(provider)) { + return probeChatCompletionsProviderHealth( + providerLabel, + config.model, + NVIDIA_HEALTH_CREDENTIAL_ENV, + `${BUILD_ENDPOINT_URL}/chat/completions`, + options, + ); } - const endpoint = getRemoteProviderHealthEndpoint(provider); - if (!endpoint) { - return null; + if (provider === "openai-api") { + return probeChatCompletionsProviderHealth( + providerLabel, + config.model, + config.credentialEnv, + OPENAI_CHAT_COMPLETIONS_ENDPOINT, + options, + ); } - const runCurlProbeImpl = options.runCurlProbeImpl ?? runCurlProbe; - const result = runCurlProbeImpl(["-sS", "--connect-timeout", "3", "--max-time", "5", endpoint]); + if (provider === "gemini-api") { + return probeChatCompletionsProviderHealth( + providerLabel, + config.model, + config.credentialEnv, + GEMINI_CHAT_COMPLETIONS_ENDPOINT, + options, + ); + } - // For remote providers, curlStatus === 0 means curl connected and got an - // HTTP response. Even a 401/403 means the endpoint is reachable. - const reachable = result.curlStatus === 0; + if (provider === "anthropic-prod") { + return probeAnthropicMessagesProviderHealth( + providerLabel, + config.model, + config.credentialEnv, + ANTHROPIC_MESSAGES_ENDPOINT, + options, + ); + } - return { - ok: reachable, - probed: true, - providerLabel, - endpoint, - detail: buildRemoteProbeDetail(providerLabel, endpoint, reachable, result), - }; + return null; } /** diff --git a/test/cli/sandbox-status-json.test.ts b/test/cli/sandbox-status-json.test.ts index e50500203c5..0ed3c76f415 100644 --- a/test/cli/sandbox-status-json.test.ts +++ b/test/cli/sandbox-status-json.test.ts @@ -246,7 +246,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { ]); }); - it("sandbox status --json ignores failed upstream diagnostics when inference.local is healthy (#6192)", () => { + it("sandbox status --json reports a missing upstream credential as not probed when inference.local is reachable (#6192)", () => { const { home, localBin, sandboxName } = createInferenceRouteStatusSetup({ routeOutput: "OK 200", upstreamHttpStatus: "000", @@ -266,7 +266,7 @@ describe("CLI sandbox status JSON output", testTimeoutOptions(20_000), () => { endpoint: "https://inference.local/v1/models", }); expect(parsed.inferenceHealth.subprobes).toEqual([ - expect.objectContaining({ ok: false, probeLabel: "upstream" }), + expect.objectContaining({ ok: true, probed: false, probeLabel: "upstream" }), ]); }); diff --git a/test/cli/sandbox-status-text.test.ts b/test/cli/sandbox-status-text.test.ts index ad536a761e9..c5d738a5adb 100644 --- a/test/cli/sandbox-status-text.test.ts +++ b/test/cli/sandbox-status-text.test.ts @@ -249,7 +249,7 @@ describe("CLI sandbox status text output", () => { expect(r.out).toContain("Run `nemoclaw alpha rebuild` to restore."); }); - it("sandbox status preserves Inference probe and exits 0 when openshellDriver is not docker", () => { + it("sandbox status reports reachable inference and an unprobed upstream when openshellDriver is not docker", () => { const home = fs.mkdtempSync( path.join(os.tmpdir(), "nemoclaw-cli-sandbox-status-non-docker-driver-"), ); @@ -299,7 +299,8 @@ describe("CLI sandbox status text output", () => { expect(r.out).toContain("Sandbox: alpha"); expect(r.out).toContain("Provider: openai-api"); expect(r.out).toContain("Model: gpt-4o-mini"); - expect(r.out).toContain("Inference: healthy"); + expect(r.out).toContain("Inference: reachable (https://inference.local/v1/models)"); + expect(r.out).toContain("Inference (upstream): not probed"); }); it("sandbox status surfaces sandbox_container_stopped when the per-sandbox container exists but is not running", () => { diff --git a/test/support/status-flow-test-harness.ts b/test/support/status-flow-test-harness.ts index 180bdc3acef..c2f0fda4b02 100644 --- a/test/support/status-flow-test-harness.ts +++ b/test/support/status-flow-test-harness.ts @@ -155,6 +155,7 @@ export function createStatusFlowHarness(options: StatusFlowHarnessOptions = {}): providerLabel: "Inference route", endpoint: "https://inference.local/v1/models", detail: "inference route reachable", + okLabel: "reachable", subprobes: [ { ok: true,