Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): a provider 404 is model_not_found, not auth (B-N7)

time-attack47e1034b3663
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index 9858ea3a05..b34eca58cf 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -83,6 +83,25 @@ function scrubErrorChain(err: unknown, redact: (text: string) => string): void {
}
}
+/** Model ids a provider renamed, mapped to the current id (B-N7: suggested on a 404). */
+const KNOWN_MODEL_RENAMES: Readonly<Record<string, string>> = {
+ 'deepseek:deepseek-v4-flash': 'deepseek:deepseek-flash',
+};
+
+/**
+ * Recovery text for a provider 404 (`model_not_found`): the model id and
+ * provider from the call context (`chat(provider:model)`), the command that
+ * lists the configured routes, and a known rename when there is one.
+ */
+export function modelNotFoundFix(context: string | undefined): string {
+ const model = context?.match(/\(([^()\s]+:[^()\s]+)\)\s*$/)?.[1];
+ const provider = model?.slice(0, model.indexOf(':'));
+ const rename = model ? KNOWN_MODEL_RENAMES[model] : undefined;
+ return `Check the model id: ${model ? `the ${provider} provider does not serve ${model}` : 'the provider does not serve this model'}, or this key has no access to it. ` +
+ 'Run `gbrain models` to see the configured model routes, then set a model the provider lists.' +
+ (rename ? ` ${model} was renamed: use ${rename}.` : '');
+}
+
/**
* `redact` scrubs upstream text before it becomes the message, and in the
* wrapped error (#5137: the gateway passes its provider-key redactor, since
@@ -118,6 +137,7 @@ export function normalizeAIError(err: unknown, context?: string, redact?: (text:
`${ctxPrefix}${msg}`,
status === 401 || status === 403
? 'Check your API key is valid and has access to this model.'
+ : status === 404 ? modelNotFoundFix(context)
: 'Check your model id + provider options match the provider API.',
err,
));
@@ -181,7 +201,7 @@ export function providerContentBlockReason(err: unknown): string | undefined {
}
/** Whole-run LLM failure classes — see classifyGlobalLlmError. */
-export type GlobalLlmErrorClass = 'auth' | 'billing' | 'rate_limit';
+export type GlobalLlmErrorClass = 'auth' | 'billing' | 'rate_limit' | 'model_not_found';
/**
* Consecutive rate_limit-classified failures a cycle phase tolerates before
@@ -210,6 +230,10 @@ const BILLING_MESSAGE_RE =
const AUTH_MESSAGE_RE =
/authentication_error|permission_error|invalid (?:x-)?api[-_ ]?key|api key (?:is )?(?:invalid|expired|missing)|unauthorized/i;
const RATE_MESSAGE_RE = /rate[-_ ]?limit(?:ed|_error)?\b|too many requests/i;
+// Provider 404 phrasings for an unknown or inaccessible model (OpenAI
+// `model_not_found` / "does not exist or you do not have access", Anthropic
+// `not_found_error`), for errors that carry no numeric 404.
+const MODEL_NOT_FOUND_MESSAGE_RE = /\bmodel_not_found\b|\bnot_found_error\b|does not exist or you do not have access/i;
// Structured status forms only; a bare number in prose ("processed 429
// pages") never matches either shape. The quoted-JSON form
// (`"api_error_status":429`, the claude-cli result blob) cannot occur as free
@@ -260,15 +284,18 @@ export function isStructuredOutputRejection(err: unknown): boolean {
function statusToClass(status: number): GlobalLlmErrorClass | null {
if (status === 401 || status === 403) return 'auth';
if (status === 402) return 'billing';
+ if (status === 404) return 'model_not_found';
if (status === 429) return 'rate_limit';
return null;
}
/**
- * Detect whole-run LLM failure conditions — auth, billing, rate limit — that
+ * Detect whole-run LLM failure conditions — auth, billing, rate limit, an
+ * unknown or inaccessible model (a 404, `model_not_found`, B-N7: labelled
+ * apart from auth so an operator does not debug a valid key) — that
* make retrying the SAME call on the next item pointless: every remaining
* page/take in a cycle phase would fail identically (#3044). Callers halt
- * their per-item loop on 'auth'/'billing' immediately and on 'rate_limit'
+ * their per-item loop on 'auth'/'billing'/'model_not_found' immediately and on 'rate_limit'
* after RATE_LIMIT_HALT_STREAK consecutive hits, surfacing a phase-level
* halt instead of accumulating one swallowed warning per item.
*
@@ -308,6 +335,7 @@ export function classifyGlobalLlmError(err: unknown): GlobalLlmErrorClass | null
const byStatus = statusToClass(status);
if (byStatus) return byStatus;
}
+ if (MODEL_NOT_FOUND_MESSAGE_RE.test(phraseText)) return 'model_not_found';
// Config-level errors are whole-run by construction — a missing/invalid
// key or an unknown model id fails identically on every call. The gateway
// throws AIConfigError directly for missing keys ("OpenAI chat requires
@@ -334,6 +362,7 @@ export type GlobalLlmHaltDecision =
| 'halt-auth'
| 'halt-billing'
| 'halt-rate_limit'
+ | 'halt-model_not_found'
| 'continue';
/** Map a halt decision back to its GlobalLlmErrorClass ('continue' → null). */
@@ -359,7 +388,7 @@ export interface GlobalLlmHaltTracker {
/**
* The one halt policy every cycle phase's per-item LLM loop applies (#3044):
- * auth/billing halt on the FIRST hit (a revoked key or exhausted spend limit
+ * auth/billing/model_not_found halt on the FIRST hit (a revoked key, a missing model or exhausted spend limit
* is deterministic — every remaining item would fail identically); a bare
* rate_limit halts only after RATE_LIMIT_HALT_STREAK consecutive hits (a
* burst 429 can clear between items); everything else stays per-item.
@@ -373,7 +402,7 @@ export function createGlobalLlmHaltTracker(): GlobalLlmHaltTracker {
observe(err, opts) {
const cls = classifyGlobalLlmError(err);
lastCls = cls;
- if (cls === 'auth' || cls === 'billing') {
+ if (cls === 'auth' || cls === 'billing' || cls === 'model_not_found') {
lastNote = `${cls} error is a whole-run condition`;
return `halt-${cls}`;
}
diff --git a/src/core/facts/absorb-log.ts b/src/core/facts/absorb-log.ts
index b4580b56bd..3d6333ffd9 100644
--- a/src/core/facts/absorb-log.ts
+++ b/src/core/facts/absorb-log.ts
@@ -53,6 +53,7 @@ export const FACTS_ABSORB_REASONS = [
'gateway_auth',
'gateway_billing',
'gateway_rate_limit',
+ 'gateway_model_not_found',
'write_refused',
] as const;
@@ -176,7 +177,9 @@ export async function writeFactsAbsorbFailure(
? 'gateway_billing'
: globalClass === 'rate_limit'
? 'gateway_rate_limit'
- : classifyFactsAbsorbError(err);
+ : globalClass === 'model_not_found'
+ ? 'gateway_model_not_found'
+ : classifyFactsAbsorbError(err);
await writeFactsAbsorbLog(engine, ref, reason, `${reason.startsWith('gateway_') ? 'provider request failed' : 'extraction failed'} (${errorType})`, sourceId);
}
diff --git a/src/core/facts/extract.ts b/src/core/facts/extract.ts
index 2c6d9b42d7..79e59becdc 100644
--- a/src/core/facts/extract.ts
+++ b/src/core/facts/extract.ts
@@ -417,7 +417,7 @@ export type ExtractFactsOutcome =
* Bounded diagnostic breadcrumb for the message: the cause's CONSTRUCTOR name
* (validated as a plain identifier — never `.name`, never `.message`) plus
* the whole-run class `classifyGlobalLlmError` derives from the cause chain
- * (`auth` / `billing` / `rate_limit`, the same vocabulary ingest_log uses).
+ * (`auth` / `billing` / `rate_limit` / `model_not_found`, the same vocabulary ingest_log uses).
* Both are closed vocabularies with no interpolated provider text, so a 4xx
* body echoing a key / org id cannot ride through. Defense-in-depth, not a
* hard boundary: anything unexpected is dropped (never substituted), and a
diff --git a/src/core/minions/llm-halt-cooldown.ts b/src/core/minions/llm-halt-cooldown.ts
index 7ba02cb306..72e162b1bf 100644
--- a/src/core/minions/llm-halt-cooldown.ts
+++ b/src/core/minions/llm-halt-cooldown.ts
@@ -48,6 +48,7 @@ export const HALT_COOLDOWN_BASE_MS: Record<GlobalLlmErrorClass, number> = {
auth: 5 * 60_000, // deterministic until an operator fixes the key
billing: 5 * 60_000, // deterministic until quota/credit is restored
rate_limit: 60_000, // bursts clear on their own — probe sooner
+ model_not_found: 5 * 60_000, // deterministic until an operator changes the model
};
export const HALT_COOLDOWN_MAX_MS = 30 * 60_000;
/** Defer cadence while a probe is in flight (plus jitter). */
diff --git a/test/ai/model-not-found-class.test.ts b/test/ai/model-not-found-class.test.ts
new file mode 100644
index 0000000000..3f136e568a
--- /dev/null
+++ b/test/ai/model-not-found-class.test.ts
@@ -0,0 +1,63 @@
+/**
+ * B-N7 (#5394 triage): a provider 404 ("model does not exist or you do not
+ * have access") was normalized to AIConfigError and classified `auth`, so
+ * `(cause=AIConfigError auth)` sent operators to debug a valid key. It is now
+ * its own whole-run class, `model_not_found`, with a fix naming the model,
+ * the provider, `gbrain models`, and a known rename when there is one.
+ */
+import { describe, test, expect } from 'bun:test';
+import {
+ AIConfigError,
+ classifyGlobalLlmError,
+ createGlobalLlmHaltTracker,
+ normalizeAIError,
+} from '../../src/core/ai/errors.ts';
+import { FactsExtractionError } from '../../src/core/facts/extract.ts';
+
+const openai404 = () => Object.assign(
+ new Error('The model `gpt-5.6-terra` does not exist or you do not have access to it.'),
+ { statusCode: 404 },
+);
+
+describe('model_not_found class (B-N7)', () => {
+ test('401 and 403 stay auth', () => {
+ expect(classifyGlobalLlmError(normalizeAIError(Object.assign(new Error('bad key'), { statusCode: 401 }), 'chat(openai:gpt-5.6-terra)'))).toBe('auth');
+ expect(classifyGlobalLlmError(normalizeAIError(Object.assign(new Error('forbidden'), { statusCode: 403 }), 'chat(openai:gpt-5.6-terra)'))).toBe('auth');
+ });
+
+ test('a 404 is model_not_found, through normalizeAIError and on a claude-cli apiErrorStatus', () => {
+ expect(classifyGlobalLlmError(normalizeAIError(openai404(), 'chat(openai:gpt-5.6-terra)'))).toBe('model_not_found');
+ expect(classifyGlobalLlmError(Object.assign(new Error('claude-cli API error 404'), { apiErrorStatus: 404 }))).toBe('model_not_found');
+ });
+
+ test('a status-less AIConfigError naming a missing model is model_not_found; a missing key stays auth', () => {
+ expect(classifyGlobalLlmError(new AIConfigError('[chat(openai:gpt-x)] model_not_found: The model gpt-x does not exist or you do not have access to it.'))).toBe('model_not_found');
+ expect(classifyGlobalLlmError(new AIConfigError('OpenAI chat requires OPENAI_API_KEY.'))).toBe('auth');
+ });
+
+ test('the 404 fix names the model, the provider and gbrain models', () => {
+ const err = normalizeAIError(openai404(), 'chat(openai:gpt-5.6-terra)');
+ expect(err).toBeInstanceOf(AIConfigError);
+ const fix = (err as AIConfigError).fix!;
+ expect(fix).toContain('openai:gpt-5.6-terra');
+ expect(fix).toContain('the openai provider does not serve openai:gpt-5.6-terra');
+ expect(fix).toContain('`gbrain models`');
+ expect(fix).not.toContain('renamed');
+ });
+
+ test('a known rename is suggested', () => {
+ const err = normalizeAIError(Object.assign(new Error('Model Not Exist'), { status: 404 }), 'chat(deepseek:deepseek-v4-flash)');
+ expect((err as AIConfigError).fix).toContain('deepseek:deepseek-v4-flash was renamed: use deepseek:deepseek-flash.');
+ });
+
+ test('model_not_found halts the phase on the first hit', () => {
+ const tracker = createGlobalLlmHaltTracker();
+ expect(tracker.observe(normalizeAIError(openai404(), 'chat(openai:gpt-5.6-terra)'))).toBe('halt-model_not_found');
+ });
+
+ test('the facts extraction breadcrumb labels the cause model_not_found, not auth', () => {
+ const err = new FactsExtractionError('provider_error', 'openai:gpt-5.6-terra', normalizeAIError(openai404(), 'chat(openai:gpt-5.6-terra)'));
+ expect(err.message).toContain('(cause=AIConfigError model_not_found)');
+ expect(err.message).not.toContain('auth');
+ });
+});
diff --git a/test/facts-absorb-log.test.ts b/test/facts-absorb-log.test.ts
index c3333d7bb2..18d184df0b 100644
--- a/test/facts-absorb-log.test.ts
+++ b/test/facts-absorb-log.test.ts
@@ -129,15 +129,18 @@ describe('writeFactsAbsorbLog — ingest_log row shape', () => {
expect(FACTS_ABSORB_REASONS).toContain('gateway_auth');
expect(FACTS_ABSORB_REASONS).toContain('gateway_billing');
expect(FACTS_ABSORB_REASONS).toContain('gateway_rate_limit');
+ // B-N7: a provider 404 (unknown or inaccessible model) is not an auth failure.
+ expect(FACTS_ABSORB_REASONS).toContain('gateway_model_not_found');
// #5362: write-path refusals record their own code.
expect(FACTS_ABSORB_REASONS).toContain('write_refused');
- expect(FACTS_ABSORB_REASONS.length).toBe(16);
+ expect(FACTS_ABSORB_REASONS.length).toBe(17);
});
test.each([
['typed-auth', Object.assign(new Error('invalid api key sk-sensitive-auth'), { status: 401 }), 'gateway_auth'],
['typed-billing', new Error('credit balance is too low: acct-sensitive'), 'gateway_billing'],
['typed-rate', Object.assign(new Error('rate limit: req-sensitive'), { status: 429 }), 'gateway_rate_limit'],
+ ['typed-model-not-found', Object.assign(new Error('The model gpt-x does not exist or you do not have access to it (org-sensitive)'), { status: 404 }), 'gateway_model_not_found'],
])('%s provider failure records only its typed class', async (ref, err, reason) => {
await writeFactsAbsorbFailure(engine, `meetings/${ref}`, err);
const log = await engine.getIngestLog({ limit: 30 });