Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(models): replace the /v1 doctor hint with a /models-probe base-URL classifier (#3787)
Garry Tanb0b9af042f41
diff --git a/src/commands/models.ts b/src/commands/models.tsindex 03a4b5634d..513bce0558 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -34,7 +34,8 @@ import {resolveModel,type ModelTier,} from '../core/model-config.ts';-import { resolveRecipe } from '../core/ai/model-resolver.ts';+import { maybeAttachVersionSuffixHint } from '../core/ai/base-url-probe.ts';+import type { AIGatewayConfig } from '../core/ai/types.ts';const TIERS: ModelTier[] = ['utility', 'reasoning', 'deep', 'subagent'];@@ -223,42 +224,33 @@ function classifyError(err: unknown): { status: ProbeStatus; message: string } {return { status: 'unknown', message: msg };}-const OPENAI_COMPAT_V1_HINT =- 'If the API key is correct, the base URL may be missing the /v1 suffix. ' +- 'OpenAI-shaped proxies (codex-proxy, Azure-OpenAI mirrors, LiteLLM fronting an OpenAI route) ' +- 'serve /v1/chat/completions and 401 on the bare path. ' +- 'Confirm with: `curl <base>/models` returns 200 with the same bearer, then append /v1 to the base URL.';+/** Injectable transport + per-run hint cache for the doctor probes. */+interface ProbeDeps {+ chat?: typeof import('../core/ai/gateway.ts').chat;+ embed?: typeof import('../core/ai/gateway.ts').embed;+ rerank?: typeof import('../core/ai/gateway.ts').rerank;+ cfg?: AIGatewayConfig;+ fetchImpl?: typeof fetch;+ cache?: Map<string, string | undefined>;+}/**- * Fix-hint for the openai-compatible-proxy `/v1`-suffix trap.- *- * An OpenAI-shaped proxy whose base URL omits `/v1` (codex-proxy, some- * Azure-OpenAI mirrors, a LiteLLM proxy fronting an OpenAI-route backend)- * serves `/v1/chat/completions` and returns 401 on the bare `/chat/completions`- * the AI SDK appends to the base. `classifyError` reads that 401 as `auth` and- * points the operator at the bearer token, when the real fix is the URL shape.- *- * Returns the corrective hint only when the model routes through an- * openai-compatible recipe (proxy tier, not native anthropic/openai/google),- * `baseURL` is set, and `baseURL` does not already end in `/v1` (optionally with- * a trailing slash). Pure: recipe resolution is synchronous and does no- * network/engine work; any resolution failure returns undefined.- *- * @internal exported for tests.+ * Build a failed-probe ProbeResult and attach the base-URL version hint. Shared+ * by the three reachability-probe catch blocks. `resultTouchpoint` names the+ * result row; `hintTouchpoint` is the auth-resolution touchpoint the hint uses.*/-export function openAiCompatV1Hint(+async function failedProbe(+ err: unknown,modelStr: string,- baseURL: string | undefined | null,-): string | undefined {- if (!baseURL || !baseURL.trim()) return undefined;- if (/\/v1\/?$/.test(baseURL.trim())) return undefined;- try {- const { recipe } = resolveRecipe(modelStr);- if (recipe.tier !== 'openai-compat') return undefined;- return OPENAI_COMPAT_V1_HINT;- } catch {- return undefined;- }+ resultTouchpoint: ProbeResult['touchpoint'],+ hintTouchpoint: 'embedding' | 'expansion' | 'chat' | 'reranker',+ start: number,+ deps: ProbeDeps,+): Promise<ProbeResult> {+ const { status, message } = classifyError(err);+ const result: ProbeResult = { model: modelStr, touchpoint: resultTouchpoint, status, message, elapsed_ms: Date.now() - start };+ await maybeAttachVersionSuffixHint(result, modelStr, hintTouchpoint, deps);+ return result;}/**@@ -487,7 +479,7 @@ async function probeRerankerConfig(engine: BrainEngine): Promise<ProbeResult> {* when set — so a CPU-only local reranker's cold-start warmup doesn't* cause the probe to false-fail with `network`/timeout.*/-async function probeRerankerReachability(engine: BrainEngine): Promise<ProbeResult | null> {+export async function probeRerankerReachability(engine: BrainEngine, deps: ProbeDeps = {}): Promise<ProbeResult | null> {const modelStr = await resolveLiveRerankerModel(engine);if (!modelStr) return null;@@ -501,7 +493,7 @@ async function probeRerankerReachability(engine: BrainEngine): Promise<ProbeResuconst start = Date.now();try {- const { rerank } = await import('../core/ai/gateway.ts');+ const rerank = deps.rerank ?? (await import('../core/ai/gateway.ts')).rerank;const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(new Error(`probe timed out after ${probeTimeoutMs}ms`)), probeTimeoutMs);try {@@ -523,14 +515,7 @@ async function probeRerankerReachability(engine: BrainEngine): Promise<ProbeResuclearTimeout(timeoutId);}} catch (err) {- const { status, message } = classifyError(err);- return {- model: modelStr,- touchpoint: 'reranker_config',- status,- message,- elapsed_ms: Date.now() - start,- };+ return failedProbe(err, modelStr, 'reranker_config', 'reranker', start, deps);}}@@ -547,10 +532,11 @@ async function probeRerankerReachability(engine: BrainEngine): Promise<ProbeResu* Cold-start note: a local CPU embedder loading a model on first call can take* several seconds; the 5s timeout may trip on the very first probe. Re-run if so.*/-async function probeEmbeddingReachability(): Promise<ProbeResult | null> {- const { getEmbeddingModel, embed } = await import('../core/ai/gateway.ts');- const modelStr = getEmbeddingModel();+export async function probeEmbeddingReachability(deps: ProbeDeps = {}): Promise<ProbeResult | null> {+ const gw = await import('../core/ai/gateway.ts');+ const modelStr = gw.getEmbeddingModel();if (!modelStr) return null;+ const embed = deps.embed ?? gw.embed;const start = Date.now();const controller = new AbortController();@@ -565,23 +551,16 @@ async function probeEmbeddingReachability(): Promise<ProbeResult | null> {elapsed_ms: Date.now() - start,};} catch (err) {- const { status, message } = classifyError(err);- return {- model: modelStr,- touchpoint: 'embedding_reachability',- status,- message,- elapsed_ms: Date.now() - start,- };+ return failedProbe(err, modelStr, 'embedding_reachability', 'embedding', start, deps);} finally {clearTimeout(timeoutId);}}-async function probeModel(modelStr: string, touchpoint: 'chat' | 'expansion'): Promise<ProbeResult> {+export async function probeModel(modelStr: string, touchpoint: 'chat' | 'expansion', deps: ProbeDeps = {}): Promise<ProbeResult> {const start = Date.now();try {- const { chat } = await import('../core/ai/gateway.ts');+ const chat = deps.chat ?? (await import('../core/ai/gateway.ts')).chat;// Use AbortController so the 5s timeout doesn't hang on a stuck network.const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(new Error('probe timed out after 5s')), 5000);@@ -597,30 +576,7 @@ async function probeModel(modelStr: string, touchpoint: 'chat' | 'expansion'): PclearTimeout(timeoutId);}} catch (err) {- const { status, message } = classifyError(err);- const result: ProbeResult = { model: modelStr, touchpoint, status, message, elapsed_ms: Date.now() - start };- // An openai-compatible proxy whose base URL omits `/v1` returns 401 (not- // 404) on the bare `/chat/completions` path, which classifyError reads as- // `auth`. Attach the URL-shape hint so the operator doesn't chase the- // bearer token. Fail open: any error resolving the base URL yields no hint- // and never breaks the probe.- if (status === 'auth') {- try {- const { loadConfig } = await import('../core/config.ts');- const { buildGatewayConfig } = await import('../core/ai/build-gateway-config.ts');- const fileCfg = loadConfig();- if (fileCfg) {- const cfg = buildGatewayConfig(fileCfg);- const { recipe } = resolveRecipe(modelStr);- const baseURL = cfg.base_urls?.[recipe.id] ?? recipe.base_url_default;- const hint = openAiCompatV1Hint(modelStr, baseURL);- if (hint) result.fix = hint;- }- } catch {- // fail open — no hint- }- }- return result;+ return failedProbe(err, modelStr, touchpoint, touchpoint, start, deps);}}@@ -700,19 +656,23 @@ Tiers: utility (haiku-class) | reasoning (sonnet) | deep (opus) | subagent (Anth// config keys live search reads (closes file-plane / DB-plane divergence).results.push(await probeRerankerConfig(engine));+ // Per-run cache so several probe sites sharing a base URL run the base-URL+ // /models sweep once, not once per site.+ const hintCache = new Map<string, string | undefined>();+for (const [modelStr, touchpoint] of [[chatModel, 'chat'], [expansionModel, 'expansion']] as const) {if (shouldSkipProvider(modelStr, skip)) {if (!json) process.stderr.write(`[skip] ${touchpoint}: ${modelStr} (provider in --skip)\n`);continue;}- results.push(await probeModel(modelStr, touchpoint));+ results.push(await probeModel(modelStr, touchpoint, { cache: hintCache }));}// v0.40.x: embedding reachability — only when the config probe passed// (codex #8: a config failure shouldn't be reported twice) AND the provider// isn't in --skip. Catches a dead/misconfigured LOCAL embed server early.if (embeddingConfig.status === 'ok' && !shouldSkipProvider(embeddingConfig.model, skip)) {- const er = await probeEmbeddingReachability();+ const er = await probeEmbeddingReachability({ cache: hintCache });if (er) results.push(er);}@@ -721,7 +681,7 @@ Tiers: utility (haiku-class) | reasoning (sonnet) | deep (opus) | subagent (Anth// actually enabled per the resolved mode bundle.const liveRerankerModel = await resolveLiveRerankerModel(engine);if (liveRerankerModel && !shouldSkipProvider(liveRerankerModel, skip)) {- const r = await probeRerankerReachability(engine);+ const r = await probeRerankerReachability(engine, { cache: hintCache });if (r) results.push(r);}diff --git a/src/core/ai/base-url-probe.ts b/src/core/ai/base-url-probe.tsnew file mode 100644index 0000000000..9c9b88fa38--- /dev/null+++ b/src/core/ai/base-url-probe.ts@@ -0,0 +1,323 @@+/**+ * Base-URL fault classifier for openai-compatible proxies, used by+ * `gbrain models doctor` when a chat/embed/rerank probe fails with an `auth`+ * (401/403) or `model_not_found` (404) error. It probes the shared `/models`+ * endpoint at the configured base URL and each canonical version off its root,+ * then classifies the status codes into one targeted verdict, so the doctor+ * points at the real fault (missing or wrong version prefix, wrong endpoint, or+ * a plain credential / model-name problem) instead of a bare error.+ *+ * PROVIDER-AGNOSTIC BY DESIGN. The classifier never hardcodes which providers+ * serve a `/models` list; it reads the actual status and reasons from that.+ * This is deliberate, because openai-compatible endpoints fall into classes that+ * behave differently and the set churns:+ *+ * - AUTHENTICATED `/models` (litellm, ollama, llama-server, most hosted+ * OpenAI-shaped APIs). The canonical missing-`/v1` case lives here: bare+ * `/models` 404s or 401s while `/v1/models` 200s, so append/switch. On an+ * auth failure the control-probe (an unauthenticated GET on the winning+ * path) confirms the key when `/models` requires auth, upgrading the hint to+ * a definite "the key authenticates at /v1".+ * - PUBLIC `/models` (OpenRouter serves `https://openrouter.ai/api/v1/models`+ * with no key). A bad key still 200s the configured `/models`, yielding+ * `key-or-model` ("URL works, check the key"); and the control-probe returns+ * 200 unauthenticated, so we fall to the honest `switch-or-key` rather than+ * a false "the key authenticates". Correct with no special-casing, because+ * we read the observed statuses.+ * - NO `/models` LIST (Voyage serves only `/v1/embeddings`; zeroentropyai, the+ * default reranker, only `/v1/models/rerank`). Every probed `/models` 404s.+ * On an auth failure that is `wrong-endpoint`, whose wording leads with the+ * key (the base URL is demonstrably reachable, since the real call already+ * 401'd); on a `model_not_found` failure the classifier stays SILENT, so a+ * Voyage model-name typo never gets a misleading "fix your base URL".+ *+ * Because every verdict comes from observed `/models` status, adding or changing+ * a provider needs no change here. `probeOpenAICompat` in `./probes.ts` is a+ * separate concern (the providers wizard's unauthenticated, JSON-shape-+ * validating, fixed `/v1/models`, boolean-verdict local detector).+ */++import { resolveRecipe } from './model-resolver.ts';+import type { AIGatewayConfig } from './types.ts';++/** Which doctor failure triggered the sweep. Shapes wording and control-probe use. */+type Trigger = 'auth' | 'model_not_found';++/**+ * Canonical version prefixes probed against an openai-compatible proxy's+ * `/models` endpoint. `/v1` is the OpenAI default; `/v1beta` covers Gemini-shaped+ * routes. Each is tried off the base URL's version-root, so they serve both the+ * "append to a bare base" and "switch a wrong version" cases. Extend here, not at+ * a call site.+ */+const V1_SUFFIX_CANDIDATES = ['/v1', '/v1beta'] as const;++/**+ * The base URL with a trailing `/vN` version segment (optional channel suffix+ * like `/v1beta`, optional trailing slash) removed: `http://h/v4` -> `http://h`;+ * a bare `http://h` is returned unchanged. Canonical candidates are probed off+ * this root so a wrong configured version becomes a swap, not an append.+ */+export function versionRoot(baseURL: string): string {+ return baseURL.replace(/\/+$/, '').replace(/\/v\d+[a-z]*$/i, '');+}++/**+ * GET `url` with the given headers; return the HTTP status, or `null` on any+ * transport error (DNS, connection refused, timeout). Never throws. Uses+ * `AbortSignal.timeout` to match the gateway's fetch-timeout idiom, and+ * `redirect: 'manual'` so a 3xx is never followed: the classifier only reads+ * {200,401,403,404}, so following a redirect buys nothing and could forward the+ * bearer to another origin.+ */+async function fetchProbeStatus(+ url: string,+ headers: Record<string, string>,+ fetchImpl: typeof fetch,+ timeoutMs: number,+): Promise<number | null> {+ try {+ const res = await fetchImpl(url, {+ method: 'GET',+ headers,+ redirect: 'manual',+ signal: AbortSignal.timeout(timeoutMs),+ });+ return res.status;+ } catch {+ return null;+ }+}++/**+ * The diagnosis a `/models` probe sweep supports. Most kinds are auth-only;+ * `model-name` is model_not_found-only; `use-verified` carries its trigger+ * because its wording differs. `undefined` (returned separately) means the+ * statuses were inconclusive.+ */+type BaseUrlVerdict =+ | { kind: 'use-verified'; recommend: string; trigger: Trigger } // an alternate's /models 200s: the route is there+ | { kind: 'switch-or-key'; recommend: string } // auth: configured unauthorized + alt 200 that is public/unconfirmed+ | { kind: 'use-and-key'; recommend: string; status: number } // auth: configured 404, alt 401/403: wrong version AND creds rejected+ | { kind: 'key-or-model' } // auth: configured 200: URL reaches a working endpoint+ | { kind: 'key-only'; status: number } // auth: configured 401/403, no other version serves /models+ | { kind: 'wrong-endpoint' } // auth: no /models at the configured path or any probed version+ | { kind: 'model-name' }; // model_not_found: configured 200: URL correct, the model id is wrong++/**+ * Probe `/models` at the configured base URL AND each canonical version off its+ * root, with the SAME bearer, in parallel, and classify what the status codes+ * prove. A `200` means that path serves a models list for the request we sent;+ * a `404` means the path is absent; a `401`/`403` means the path exists but+ * rejected the credentials. Other statuses (5xx, 429) and transport errors+ * prove nothing.+ *+ * The `trigger` splits behavior: on `auth` the full verdict set runs (including+ * a control-probe that confirms the key when an alternate authenticates); on+ * `model_not_found` only a real 200 speaks (append/switch, or "URL correct,+ * check the model name"), because the key is not in question and a redirect to+ * a check-the-key message would misdirect.+ */+async function classifyBaseUrlProbe(+ baseURL: string,+ headers: Record<string, string>,+ candidates: readonly string[],+ fetchImpl: typeof fetch,+ timeoutMs: number,+ trigger: Trigger,+): Promise<BaseUrlVerdict | undefined> {+ const base = baseURL.replace(/\/+$/, '');+ const root = versionRoot(base);++ // Probe set: the configured URL as-is, plus each canonical version off the+ // root. Dedup so an already-`/v1` base does not probe `/v1` twice.+ const targets: Array<{ suffix: string; configured: boolean }> = [];+ const seen = new Set<string>();+ const add = (suffix: string, configured: boolean) => {+ const url = `${root}${suffix}/models`;+ if (!seen.has(url)) {+ seen.add(url);+ targets.push({ suffix, configured });+ }+ };+ add(base.slice(root.length), true); // configured: '' when bare, else '/vX'+ for (const cand of candidates) add(cand, false);++ const statuses = await Promise.all(+ targets.map(t => fetchProbeStatus(`${root}${t.suffix}/models`, headers, fetchImpl, timeoutMs)),+ );+ const items = targets.map((t, i) => ({ ...t, status: statuses[i] }));+ const authReject = (s: number | null) => s === 401 || s === 403;+ const configured = items.find(t => t.configured)!;+ const alternates = items.filter(t => !t.configured);+ const working = alternates.find(t => t.status === 200);++ // model_not_found: the key is not in question, so speak only on positive URL+ // evidence (a real 200) and stay silent on everything else.+ if (trigger === 'model_not_found') {+ if (configured.status === 200) return { kind: 'model-name' };+ if (working) return { kind: 'use-verified', recommend: working.suffix, trigger };+ return undefined;+ }++ // auth trigger.+ // Configured /models serves a list: the base URL reaches a working route, so+ // the failure is credentials or model access, not the URL shape.+ if (configured.status === 200) return { kind: 'key-or-model' };++ if (working) {+ // A version answers 200 with the key. Disambiguate "the key is valid there"+ // (confident switch) from "that /models is public, key unproven" (both+ // signals) with one unauthenticated control-probe.+ const { Authorization: _drop, ...noAuthHeaders } = headers;+ const noAuth = await fetchProbeStatus(`${root}${working.suffix}/models`, noAuthHeaders, fetchImpl, timeoutMs);+ if (authReject(noAuth)) {+ // /models requires auth AND accepted the key -> the key is valid there.+ return { kind: 'use-verified', recommend: working.suffix, trigger };+ }+ // public or unconfirmed -> name both signals.+ return { kind: 'switch-or-key', recommend: working.suffix };+ }++ // Configured path is absent (404).+ if (configured.status === 404) {+ const rejected = alternates.find(t => authReject(t.status));+ if (rejected) return { kind: 'use-and-key', recommend: rejected.suffix, status: rejected.status! };+ if (alternates.every(t => t.status === 404)) return { kind: 'wrong-endpoint' };+ }++ // Configured path exists and rejects the credentials, and no other version+ // serves /models: the URL shape is fine, the problem is the key/permissions.+ if (authReject(configured.status) && alternates.every(t => t.status === 404 || t.status === null)) {+ return { kind: 'key-only', status: configured.status! };+ }++ return undefined; // inconclusive: 401-everywhere, 5xx/429, or transport errors+}++/** Render a verdict into the operator-facing `fix:` line. */+function verdictHint(verdict: BaseUrlVerdict, baseURL: string): string {+ const base = baseURL.replace(/\/+$/, '');+ const root = versionRoot(base);+ const from = base.slice(root.length); // '' when the base is bare, else '/vX'+ const move = (recommend: string) =>+ from ? `switch ${from} to ${recommend} (base URL ${root}${recommend})` : `append ${recommend} (base URL ${root}${recommend})`;+ switch (verdict.kind) {+ case 'use-verified': {+ const target = `${root}${verdict.recommend}`;+ if (verdict.trigger === 'model_not_found') {+ return `${target}/models responds 200 while ${base}/models does not, so the openai-compatible route is at ` ++ `${verdict.recommend} — ${move(verdict.recommend)}. That explains the model-not-found (the request reached the wrong path).`;+ }+ return `The API key authenticates at ${target} (its /models requires auth and accepted the key), but the ` ++ `configured ${base} does not serve that route, so the base URL ${from ? 'has the wrong' : 'is missing its'} ` ++ `version prefix — ${move(verdict.recommend)}.`;+ }+ case 'switch-or-key':+ return `The request was unauthorized, so check the API key first. Separately, ${root}${verdict.recommend}/models ` ++ `responds 200 (possibly an unauthenticated route), so if the key is correct the base URL should carry ` ++ `${verdict.recommend} — ${move(verdict.recommend)}.`;+ case 'use-and-key':+ return `The openai-compatible route appears to be at ${root}${verdict.recommend} (its /models responds ` ++ `${verdict.status} while the configured ${base}/models returns 404), so ${move(verdict.recommend)}. That route ` ++ `also rejects the current credentials (${verdict.status}), so verify the API key or permissions too.`;+ case 'key-or-model':+ return `${base}/models responds 200 with the configured credentials, so the base URL reaches a working ` ++ `openai-compatible endpoint. The failure is the API key or the model's access, not the URL shape.`;+ case 'key-only':+ return `${base}/models responds ${verdict.status} (the endpoint exists and rejected the credentials) and no ` ++ `other common version prefix serves /models, so the base URL shape is not the problem. Check the API key or permissions.`;+ case 'wrong-endpoint':+ return `The request was unauthorized and no /models list answered at ${base} or the common version prefixes ` ++ `(all 404), so this is most likely a key or permissions problem — check the API key. Some providers do not serve ` ++ `a /models list; if you expected one, verify the base URL host and path.`;+ case 'model-name':+ return `${base}/models responds 200, so the base URL is correct. The model-not-found is most likely a wrong or ` ++ `unavailable model name — check the model id (and that your key or plan can access it).`;+ }+}++/**+ * The mutable probe result `maybeAttachVersionSuffixHint` reads and annotates.+ * The doctor's `ProbeResult` is structurally compatible; kept minimal here so+ * this module does not depend on the command layer.+ */+export interface HintTarget {+ status: string;+ fix?: string;+}++/**+ * Injected config/transport for tests + a per-run memo cache. Real callers pass+ * the cache (created once per doctor run) so several probe sites sharing a base+ * URL do not each re-run the sweep.+ */+export interface HintDeps {+ cfg?: AIGatewayConfig;+ fetchImpl?: typeof fetch;+ cache?: Map<string, string | undefined>;+}++/**+ * On an `auth` (401/403) or `model_not_found` (404) probe failure against an+ * openai-compatible proxy, probe `/models` at the configured base URL and each+ * canonical version and attach a targeted `fix:` line.+ *+ * The base URL and bearer resolve through the same `applyOpenAICompatConfig` /+ * `applyResolveAuth` / `authToHeaders` seams the live gateway uses (read from+ * the live merged config via the gateway's own `requireConfig`, not a config-file+ * re-read, which would miss the DB-plane `base_urls` merge), so the probe hits+ * the exact path production does, on the same host the operator already trusts+ * with the key. Native providers and Azure-templated recipes (bespoke+ * `resolveOpenAICompatConfig`) are skipped. Fail-open: any resolution or+ * transport error yields no hint and never breaks the probe.+ *+ * @internal exported for tests.+ */+export async function maybeAttachVersionSuffixHint(+ target: HintTarget,+ modelStr: string,+ touchpoint: 'embedding' | 'expansion' | 'chat' | 'reranker',+ deps: HintDeps = {},+): Promise<void> {+ const trigger: Trigger | undefined =+ target.status === 'auth' ? 'auth' : target.status === 'model_not_found' ? 'model_not_found' : undefined;+ if (!trigger) return;+ try {+ const { requireConfig, applyOpenAICompatConfig, applyResolveAuth, authToHeaders } = await import('./gateway.ts');+ // Reuse the gateway's own live-config accessor (the DB + file + env merge),+ // not a file re-read. requireConfig throws if the gateway is unconfigured;+ // that path can't happen once doctor is probing models, and the fail-open+ // catch below absorbs it either way.+ const cfg = deps.cfg ?? requireConfig();+ const { recipe } = resolveRecipe(modelStr);+ if (recipe.tier !== 'openai-compat') return; // native provider — no base-URL trap+ if (recipe.resolveOpenAICompatConfig) return; // Azure-templated, non-/vN shape+ const { baseURL } = applyOpenAICompatConfig(recipe, cfg);+ if (!baseURL || !baseURL.trim()) return;++ // Per-run memo: verdicts depend only on (trigger, base URL, recipe), so+ // several probe sites sharing a proxy reuse one sweep. Key is non-secret.+ const cacheKey = `${trigger}\n${baseURL}\n${recipe.id}`;+ if (deps.cache?.has(cacheKey)) {+ const cached = deps.cache.get(cacheKey);+ if (cached) target.fix = cached;+ return;+ }++ const headers = authToHeaders(applyResolveAuth(recipe, cfg, touchpoint));+ const verdict = await classifyBaseUrlProbe(+ baseURL,+ headers,+ V1_SUFFIX_CANDIDATES,+ deps.fetchImpl ?? globalThis.fetch,+ 2000,+ trigger,+ );+ const fix = verdict ? verdictHint(verdict, baseURL) : undefined;+ deps.cache?.set(cacheKey, fix);+ if (fix) target.fix = fix;+ } catch {+ // fail open — no hint+ }+}diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 043ea21f3d..bd77f8642d 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -124,6 +124,20 @@ const DEFAULT_RERANKER_MODEL = 'zeroentropyai:zerank-2';let _config: AIGatewayConfig | null = null;const _modelCache = new Map<string, any>();+/**+ * Materialize `applyResolveAuth`'s SDK-shaped result ({apiKey}|{headers}) into+ * raw HTTP headers: a Bearer-style apiKey becomes an Authorization header;+ * custom/default headers ride alongside (they win on conflict, matching the+ * SDK's header-after-apiKey ordering). Single source for the reranker wire path+ * and the doctor's base-URL probe.+ */+export function authToHeaders(auth: { apiKey?: string; headers?: Record<string, string> }): Record<string, string> {+ return {+ ...(auth.apiKey ? { Authorization: `Bearer ${auth.apiKey}` } : {}),+ ...(auth.headers ?? {}),+ };+}+/*** Recover the process-global gateway for foreground command entrypoints that* were reached without cli.ts's normal engine-connect initialization (#2590).@@ -675,7 +689,10 @@ export function __setChatTransportForTests(_chatTransport = fn;}-function requireConfig(): AIGatewayConfig {+/** The live gateway config, or throw if unconfigured. Exported for the+ * `models doctor` base-URL probe (which reads the same merged config the+ * gateway calls with, inside its own fail-open guard). */+export function requireConfig(): AIGatewayConfig {if (!_config) {throw new AIConfigError('AI gateway is not configured. Call configureGateway() during engine connect.',@@ -3915,10 +3932,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {// through `auth.headers` alongside Bearer-style apiKey. The merge below// materializes both shapes so static-default-headers ride on the reranker// wire path the same way they ride the SDK paths.- const authHeaders: Record<string, string> = {- ...(auth.apiKey ? { Authorization: `Bearer ${auth.apiKey}` } : {}),- ...(auth.headers ?? {}),- };+ const authHeaders = authToHeaders(auth);const body = JSON.stringify({model: parsed.modelId,query: input.query,diff --git a/test/models-doctor-embed.test.ts b/test/models-doctor-embed.test.tsindex b7594ba7b1..bf718a9a90 100644--- a/test/models-doctor-embed.test.ts+++ b/test/models-doctor-embed.test.ts@@ -45,6 +45,6 @@ describe('models doctor — embedding reachability probe (v0.40.x)', () => {// The config probe result is captured and the reachability call is gated// on its status === 'ok' before firing.expect(slice).toContain('const embeddingConfig = await probeEmbeddingConfig()');- expect(slice).toMatch(/embeddingConfig\.status === 'ok'[\s\S]*probeEmbeddingReachability\(\)/);+ expect(slice).toMatch(/embeddingConfig\.status === 'ok'[\s\S]*probeEmbeddingReachability\(/);});});diff --git a/test/models-doctor-v1-hint.test.ts b/test/models-doctor-v1-hint.test.tsindex 1d31be99ce..466efe6144 100644--- a/test/models-doctor-v1-hint.test.ts+++ b/test/models-doctor-v1-hint.test.ts@@ -1,40 +1,346 @@import { describe, test, expect } from 'bun:test';-import { openAiCompatV1Hint } from '../src/commands/models.ts';+import { versionRoot, maybeAttachVersionSuffixHint } from '../src/core/ai/base-url-probe.ts';+import {+ probeModel,+ probeEmbeddingReachability,+ probeRerankerReachability,+} from '../src/commands/models.ts';+import { configureGateway } from '../src/core/ai/gateway.ts';+import type { AIGatewayConfig } from '../src/core/ai/types.ts';/**- * `gbrain models doctor` — the openai-compatible-proxy `/v1`-suffix hint.+ * `gbrain models doctor` — the openai-compatible-proxy base-URL classifier.*- * `openAiCompatV1Hint` is pure: it resolves the model's recipe synchronously- * (no network, no engine) to decide whether the provider is an openai-compatible- * proxy, then inspects the passed base URL. These cases pin the four branches- * without any transport stub.+ * On an auth (401/403) or model_not_found (404) probe failure, the doctor GETs+ * `/models` at the configured base URL and each canonical version off its root,+ * classifies the status codes, and (in the auth `use-verified` case) runs one+ * unauthenticated control-probe to confirm the key. Tests inject the transport+ * (`chat`/`embed`/`rerank`) and a header-aware stub `fetch` (so a route can+ * answer differently with and without the bearer, exercising the control-probe),+ * with zero network. Reverting any probe-site hint call fails a wiring test.*/-describe('openAiCompatV1Hint', () => {- test('openai-compat proxy without /v1 suffix returns a /v1 hint', () => {- const hint = openAiCompatV1Hint('litellm:gpt-4o', 'http://localhost:4000');- expect(hint).toBeDefined();- expect(hint).toContain('/v1');++/**+ * Coverage of the #3553 review (v0.42.69.0 shipped the static hint unchanged, so+ * all four blockers are live on master; this replacement closes them):+ * - Blocker 1 (the gate fired on a recipe's own versioned default, e.g. zhipu+ * `.../paas/v4`, so a bad key was told to append `/v1` onto a `/v4` route):+ * the "#3553 blocker 1" test below. A version is recommended only when its+ * `/models` answers 200, so a bad key never produces a bogus append.+ * - Blocker 2 (the shipped tests exercised only the pure helper; the wiring+ * had no coverage): the "probe-site wiring (discrimination)" block drives the+ * full path and fails if any hint call is reverted.+ * - Blocker 3 (only `probeModel` was patched; the embedding and reranker probes+ * hit the same trap): the wiring block covers all three sites.+ * - Blocker 4 (a hand-rolled `base_urls` lookup that duplicated half of+ * `applyOpenAICompatConfig`): structural — resolution now goes through+ * `applyOpenAICompatConfig` / `applyResolveAuth` / `authToHeaders` /+ * `requireConfig`, which every `classify` case drives via `deps.cfg`.+ *+ * Providers that serve NO `/models` list (Voyage = embeddings only; ZeroEntropy,+ * the default reranker = `/v1/models/rerank` only) are the all-404 cases: the+ * "wrong-endpoint" test (auth -> leads with the key, since the host is reachable)+ * and the model_not_found "silent: all 404" test (a model-name typo -> no+ * misleading "fix your URL").+ */++type ProbeResult = Awaited<ReturnType<typeof probeModel>>;+type ChatFn = typeof import('../src/core/ai/gateway.ts').chat;+type EmbedFn = typeof import('../src/core/ai/gateway.ts').embed;+type RerankFn = typeof import('../src/core/ai/gateway.ts').rerank;+type RouteSpec = number | 'error' | { auth: number; noauth: number };++const LITELLM_CHAT = 'litellm:gpt-4o';+const LITELLM_EMBED = 'litellm:text-embedding-3-large';+const LITELLM_RERANK = 'litellm:rerank-x';++function cfg(base: string): AIGatewayConfig {+ return { env: { LITELLM_API_KEY: 'test-key' }, base_urls: { litellm: base } };+}++/** Stub `fetch` routed by URL suffix. A route may answer differently based on+ * whether the Authorization header is present ({auth,noauth}); `'error'` throws. */+function stubFetch(routes: Record<string, RouteSpec>): typeof fetch {+ return (async (input: string | URL | Request, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString();+ const hasAuth = !!(init?.headers && (init.headers as Record<string, string>).Authorization);+ for (const [suffix, spec] of Object.entries(routes)) {+ if (url.endsWith(suffix)) {+ const status = typeof spec === 'object' ? (hasAuth ? spec.auth : spec.noauth) : spec;+ if (status === 'error') throw new Error('ECONNREFUSED');+ return { status } as Response;+ }+ }+ throw new Error(`unrouted probe url: ${url}`);+ }) as unknown as typeof fetch;+}++const throwAuth: ChatFn = (async () => {+ throw new Error('401 Unauthorized');+}) as unknown as ChatFn;+const throwAuthEmbed: EmbedFn = (async () => {+ throw new Error('401 Unauthorized');+}) as unknown as EmbedFn;+const throwAuthRerank: RerankFn = (async () => {+ throw new Error('401 Unauthorized');+}) as unknown as RerankFn;++function result(status = 'auth', model = LITELLM_CHAT): ProbeResult {+ return { model, touchpoint: 'chat', status: status as ProbeResult['status'], message: 'x', elapsed_ms: 0 };+}++/** (configured `/models`, `/v1/models`, `/v1beta/models`) off a bare `localhost:4000`. */+function routes(models: RouteSpec, v1: RouteSpec, v1beta: RouteSpec): Record<string, RouteSpec> {+ return {+ 'localhost:4000/models': models,+ 'localhost:4000/v1/models': v1,+ 'localhost:4000/v1beta/models': v1beta,+ };+}+/** (configured `/v4/models`, `/v1/models`, `/v1beta/models`) for a versioned base. */+function v4Routes(v4: RouteSpec, v1: RouteSpec, v1beta: RouteSpec): Record<string, RouteSpec> {+ return {+ 'localhost:4000/v4/models': v4,+ 'localhost:4000/v1/models': v1,+ 'localhost:4000/v1beta/models': v1beta,+ };+}++// A bare proxy where /v1 is the real route, /v1/models requires auth and the key is valid.+const V1_CONFIRMED = routes(404, { auth: 200, noauth: 401 }, 404);++async function classify(base: string, fetchRoutes: Record<string, RouteSpec>, status = 'auth'): Promise<string | undefined> {+ const r = result(status);+ await maybeAttachVersionSuffixHint(r, LITELLM_CHAT, 'chat', { cfg: cfg(base), fetchImpl: stubFetch(fetchRoutes) });+ return r.fix;+}++describe('versionRoot (append vs switch)', () => {+ test('a bare base URL is its own root', () => {+ expect(versionRoot('http://localhost:4000')).toBe('http://localhost:4000');+ expect(versionRoot('https://proxy.internal/api')).toBe('https://proxy.internal/api');+ });+ test('a trailing /vN (with optional channel + slash) is stripped', () => {+ expect(versionRoot('http://localhost:4000/v1')).toBe('http://localhost:4000');+ expect(versionRoot('http://localhost:4000/v1/')).toBe('http://localhost:4000');+ expect(versionRoot('https://open.bigmodel.cn/api/paas/v4')).toBe('https://open.bigmodel.cn/api/paas');+ expect(versionRoot('https://x.example/v1beta')).toBe('https://x.example');+ });+});++describe('auth-trigger verdicts', () => {+ test('use-verified (confident): control-probe proves the key -> "authenticates", append', async () => {+ const fix = await classify('http://localhost:4000', V1_CONFIRMED);+ expect(fix).toContain('authenticates');+ expect(fix).toContain('append /v1');+ });++ test('use-verified (confident, versioned): wrong version + key valid -> switch, "authenticates"', async () => {+ const fix = await classify('http://localhost:4000/v4', v4Routes(404, { auth: 200, noauth: 403 }, 404));+ expect(fix).toContain('authenticates');+ expect(fix).toContain('switch /v4 to /v1');+ });++ test('switch-or-key (public /models): both signals, no "authenticates"', async () => {+ // configured 401 (exists, rejected), /v1 200 but PUBLIC (200 without the key too).+ const fix = await classify('http://localhost:4000', routes(401, { auth: 200, noauth: 200 }, 404));+ expect(fix?.toLowerCase()).toContain('check the api key');+ expect(fix).toContain('append /v1');+ expect(fix).not.toContain('authenticates');+ });++ test('use-and-key: configured 404, versioned path 401 -> fix URL AND flag credentials', async () => {+ const fix = await classify('http://localhost:4000', routes(404, 401, 404));+ expect(fix).toContain('/v1');+ expect(fix).toContain('404');+ expect(fix?.toLowerCase()).toContain('key');+ });+ test('use-and-key (403 variant)', async () => {+ const fix = await classify('http://localhost:4000', routes(404, 403, 404));+ expect(fix).toContain('403');+ expect(fix?.toLowerCase()).toContain('permissions');+ });++ test('key-or-model: configured 200 -> URL works, check key or model access (touchpoint-agnostic)', async () => {+ const fix = await classify('http://localhost:4000', routes(200, 404, 404));+ expect(fix).toContain('working');+ expect(fix).toContain("model's access");+ expect(fix).not.toContain('chat model');+ expect(fix).not.toContain('append');+ expect(fix).not.toContain('switch');+ });++ test('key-only (401): configured exists, no other version -> URL fine, check the key', async () => {+ const fix = await classify('http://localhost:4000', routes(401, 404, 404));+ expect(fix).toContain('401');+ expect(fix?.toLowerCase()).toContain('key');+ expect(fix).not.toContain('append');+ });+ test('key-only (403)', async () => {+ const fix = await classify('http://localhost:4000', routes(403, 404, 404));+ expect(fix).toContain('403');+ expect(fix?.toLowerCase()).toContain('permissions');+ });+ test('key-only (null alternate): a transport-error alternate still yields key-only', async () => {+ const fix = await classify('http://localhost:4000', routes(401, 404, 'error'));+ expect(fix?.toLowerCase()).toContain('key');+ expect(fix).not.toContain('append');+ });++ test('#3553 blocker 1: a bad key on a versioned base (zhipu .../paas/v4 shape) -> key-only, never a bogus append /v1', async () => {+ // The shipped static hint gated on "openai-compat AND base does not end in+ // /v1", which fired on zhipu's own /paas/v4 default and told a bad ZHIPUAI+ // key to append /v1 onto a /v4 route. The probe never false-fires: /v4/models+ // 401 (real route, bad key), /v1 + /v1beta 404 (zhipu serves no /v1) ->+ // key-only ("check the key"), not append.+ const fix = await classify('https://open.bigmodel.cn/api/paas/v4', {+ 'paas/v4/models': 401,+ 'paas/v1/models': 404,+ 'paas/v1beta/models': 404,+ });+ expect(fix?.toLowerCase()).toContain('key');+ expect(fix).not.toContain('append');+ expect(fix).not.toContain('switch');});- test('base URL already ending in /v1 returns undefined', () => {- expect(openAiCompatV1Hint('litellm:gpt-4o', 'http://localhost:4000/v1')).toBeUndefined();+ test('wrong-endpoint: all 404 -> leads with the key, host/path secondary (no overclaim)', async () => {+ // No-/models-list providers (Voyage embeddings, the default ZeroEntropy+ // reranker) 404 every /models. Reached via a 401, the host is proven+ // reachable and the real endpoint auth-gated, so lead with the key; never+ // a false "the base URL is wrong".+ const fix = await classify('http://localhost:4000', routes(404, 404, 404));+ expect(fix?.toLowerCase()).toContain('key');+ expect(fix).toContain('host and path');+ expect(fix).not.toContain('does not point at an openai-compatible API');+ });++ test('precedence: configured 200 wins over an alternate 200 -> key-or-model', async () => {+ const fix = await classify('http://localhost:4000', routes(200, 200, 200));+ expect(fix).toContain('working');+ expect(fix).not.toContain('append');+ });++ test('inconclusive: 401 everywhere -> no hint', async () => {+ expect(await classify('http://localhost:4000', routes(401, 401, 401))).toBeUndefined();+ });+ test('inconclusive: 5xx at a versioned path is not "unauthorized" -> no hint', async () => {+ expect(await classify('http://localhost:4000', routes(404, 500, 404))).toBeUndefined();+ });+ test('inconclusive: 5xx at the configured path -> no hint', async () => {+ expect(await classify('http://localhost:4000', routes(500, 404, 404))).toBeUndefined();});+ test('inconclusive: all transport errors -> no hint', async () => {+ expect(await classify('http://localhost:4000', routes('error', 'error', 'error'))).toBeUndefined();+ });+});- test('base URL ending in /v1/ (trailing slash) returns undefined', () => {- expect(openAiCompatV1Hint('litellm:gpt-4o', 'http://localhost:4000/v1/')).toBeUndefined();+describe('model_not_found-trigger verdicts (only a 200 speaks)', () => {+ test('configured 200 -> model-name: URL correct, check the model name', async () => {+ const fix = await classify('http://localhost:4000', routes(200, 404, 404), 'model_not_found');+ expect(fix).toContain('correct');+ expect(fix).toContain('model');+ expect(fix).not.toContain('append');+ expect(fix).not.toContain('switch');+ });+ test('alternate 200 -> use-verified (append), explains the model-not-found, no key claim', async () => {+ const fix = await classify('http://localhost:4000', routes(404, 200, 404), 'model_not_found');+ expect(fix).toContain('append /v1');+ expect(fix).toContain('model-not-found');+ expect(fix).not.toContain('authenticates');+ });+ test('versioned alternate 200 -> switch', async () => {+ const fix = await classify('http://localhost:4000/v4', v4Routes(404, 200, 404), 'model_not_found');+ expect(fix).toContain('switch /v4 to /v1');});+ test('silent: all 404 -> no hint (no wrong-endpoint, no key wording)', async () => {+ // A no-/models provider (Voyage / ZeroEntropy) + a model-name typo: all+ // /models 404 -> stay silent so the raw model-not-found stands, never a+ // misleading "fix your URL".+ expect(await classify('http://localhost:4000', routes(404, 404, 404), 'model_not_found')).toBeUndefined();+ });+ test('silent: configured 401 with no alternate 200 -> no hint', async () => {+ expect(await classify('http://localhost:4000', routes(401, 404, 404), 'model_not_found')).toBeUndefined();+ expect(await classify('http://localhost:4000', routes(401, 401, 401), 'model_not_found')).toBeUndefined();+ });+});- test('native anthropic provider returns undefined', () => {- expect(openAiCompatV1Hint('anthropic:claude-sonnet-4-6', 'https://api.anthropic.com')).toBeUndefined();+describe('per-run memo cache', () => {+ test('a second site with the same base reuses the verdict without re-fetching', async () => {+ const cache = new Map<string, string | undefined>();+ const r1 = result();+ await maybeAttachVersionSuffixHint(r1, LITELLM_CHAT, 'chat', {+ cfg: cfg('http://localhost:4000'), fetchImpl: stubFetch(V1_CONFIRMED), cache,+ });+ expect(r1.fix).toContain('/v1');+ // Second call: a fetch that would throw if invoked; a cache hit avoids it.+ const throwFetch = (async () => { throw new Error('must not fetch on a cache hit'); }) as unknown as typeof fetch;+ const r2 = result();+ await maybeAttachVersionSuffixHint(r2, LITELLM_CHAT, 'chat', {+ cfg: cfg('http://localhost:4000'), fetchImpl: throwFetch, cache,+ });+ expect(r2.fix).toBe(r1.fix);});+});- test('native openai provider returns undefined', () => {- expect(openAiCompatV1Hint('openai:gpt-4o', 'https://api.openai.com')).toBeUndefined();+describe('gate exclusions (no probe at all)', () => {+ test('a native provider is never probed', async () => {+ const r = result('auth', 'anthropic:claude-sonnet-4-6');+ let fetched = false;+ await maybeAttachVersionSuffixHint(r, 'anthropic:claude-sonnet-4-6', 'chat', {+ cfg: { env: {}, base_urls: {} },+ fetchImpl: (async () => { fetched = true; return { status: 200 } as Response; }) as unknown as typeof fetch,+ });+ expect(r.fix).toBeUndefined();+ expect(fetched).toBe(false);+ });+ test('a non-auth, non-model_not_found failure is never probed', async () => {+ const r = result('network');+ let fetched = false;+ await maybeAttachVersionSuffixHint(r, LITELLM_CHAT, 'chat', {+ cfg: cfg('http://localhost:4000'),+ fetchImpl: (async () => { fetched = true; return { status: 200 } as Response; }) as unknown as typeof fetch,+ });+ expect(r.fix).toBeUndefined();+ expect(fetched).toBe(false);});+});- test('missing base URL returns undefined', () => {- expect(openAiCompatV1Hint('litellm:gpt-4o', undefined)).toBeUndefined();- expect(openAiCompatV1Hint('litellm:gpt-4o', null)).toBeUndefined();- expect(openAiCompatV1Hint('litellm:gpt-4o', '')).toBeUndefined();+// #3553 blockers 2 (the shipped tests covered only the pure helper) + 3 (only+// probeModel was patched; the embedding and reranker probes hit the same trap):+// these drive the wiring end-to-end at ALL THREE probe sites; reverting any+// site's hint call drops exactly one test.+describe('probe-site wiring (discrimination — fails if a hint call is reverted)', () => {+ test('probeModel: a chat 401 attaches the /v1 hint', async () => {+ const r = await probeModel(LITELLM_CHAT, 'chat', {+ chat: throwAuth, cfg: cfg('http://localhost:4000'), fetchImpl: stubFetch(V1_CONFIRMED),+ });+ expect(r.status).toBe('auth');+ expect(r.fix).toContain('/v1');+ });+ test('probeModel: a reachable chat probe attaches no hint', async () => {+ const r = await probeModel(LITELLM_CHAT, 'chat', {+ chat: (async () => ({})) as unknown as ChatFn, cfg: cfg('http://localhost:4000'), fetchImpl: stubFetch({}),+ });+ expect(r.status).toBe('ok');+ expect(r.fix).toBeUndefined();+ });+ test('probeEmbeddingReachability: an embedding 401 attaches the /v1 hint', async () => {+ configureGateway({ env: { LITELLM_API_KEY: 'test-key' }, base_urls: { litellm: 'http://localhost:4000' }, embedding_model: LITELLM_EMBED });+ const r = await probeEmbeddingReachability({+ embed: throwAuthEmbed, cfg: cfg('http://localhost:4000'), fetchImpl: stubFetch(V1_CONFIRMED),+ });+ expect(r?.status).toBe('auth');+ expect(r?.fix).toContain('/v1');+ });+ test('probeRerankerReachability: a reranker 401 attaches the /v1 hint', async () => {+ const rerankerConfig: Record<string, string> = { 'search.reranker.model': LITELLM_RERANK, 'search.reranker.enabled': 'true' };+ const engine = {+ async getConfig(key: string): Promise<string | null> { return rerankerConfig[key] ?? null; },+ } as unknown as Parameters<typeof probeRerankerReachability>[0];+ const r = await probeRerankerReachability(engine, {+ rerank: throwAuthRerank, cfg: cfg('http://localhost:4000'), fetchImpl: stubFetch(V1_CONFIRMED),+ });+ expect(r?.status).toBe('auth');+ expect(r?.fix).toContain('/v1');});});