Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Revert "feat(models): name the setting that selected the model in model_not_found errors (#5437)"

time-attack01ae6a1b65bf
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
index 2be08e8661..8ef35c49ce 100644
--- a/src/core/agent-output.ts
+++ b/src/core/agent-output.ts
@@ -666,10 +666,10 @@ const ROWS: Row[] = [
// ── generic rows: the DB classifier runs before these ──
{
match: e => named('AIConfigError')(e) || named('AITransientError')(e),
- map: (e: Error & { fix?: string; why?: string }) => ({
+ map: (e: Error & { fix?: string }) => ({
error: 'unavailable', code: 'unavailable', message: e.message,
reason: e.name === 'AIConfigError' ? 'ai_config' : 'ai_transient',
- suggestion: e.fix, why: e.why, retryable: e.name === 'AITransientError',
+ suggestion: e.fix, retryable: e.name === 'AITransientError',
}),
},
{
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index 85f9ced240..93dd607dff 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -29,9 +29,6 @@ export class AIServiceError extends Error {
}
export class AIConfigError extends AIServiceError {
- /** Why the failure happened, beyond the message (a provider 404 names the setting that selected the model). */
- why?: string;
-
constructor(
message: string,
public readonly fix?: string,
diff --git a/src/core/ai/gateway-model-sources.ts b/src/core/ai/gateway-model-sources.ts
index 2fd3201900..0c2631e138 100644
--- a/src/core/ai/gateway-model-sources.ts
+++ b/src/core/ai/gateway-model-sources.ts
@@ -10,7 +10,6 @@
*/
import { describeResolveOrigin, type EffectiveModelSource, type ResolvedModel, type ResolveSource } from '../model-config.ts';
-import { AIConfigError } from './errors.ts';
export type GatewayModelSourceKind = ResolveSource | 'file_config';
@@ -63,45 +62,6 @@ export function getGatewayModelSource(touchpoint: GatewayTouchpoint, model: stri
return r && r.model === model ? { source: r.source, origin: r.origin } : undefined;
}
-/**
- * `why` for a provider 404 (`model_not_found`) on `model`: the setting that
- * selected it, computed from this record at the throw site. Names keys and
- * env-variable names only, never their values (the model id is already in the
- * error message). A model the record does not describe came from
- * chat_fallback_chain or was named by the call itself.
- */
-export function modelNotFoundWhy(touchpoint: GatewayTouchpoint, model: string, fallbackChain: readonly string[] = []): string {
- const r = RESOLUTION[touchpoint];
- const override = `gbrain config set ${r.configKey} <provider>:<model> overrides every other setting`;
- const src = getGatewayModelSource(touchpoint, model);
- if (!src) {
- return fallbackChain.includes(model)
- ? 'The model came from chat_fallback_chain; replace that entry with a model the provider serves.'
- : `The call named this model itself; it was not selected by configuration, so no config key changes it (\`gbrain models\` shows the configured ${touchpoint} model).`;
- }
- switch (src.source) {
- case 'config_key':
- case 'deprecated_key':
- case 'tier_config':
- case 'models_default':
- return `The model was selected by the DB-plane key ${src.origin}; gbrain config set ${src.origin} <provider>:<model> replaces it.`;
- case 'file_config':
- return `The model was selected by the ${r.pinKey} pin in ~/.gbrain/config.json; edit or remove that pin, or ${override} (gbrain config set ${r.pinKey} writes the DB plane, which does not replace the pin).`;
- case 'env':
- return `The model was selected by the ${src.origin} environment variable; change or unset it, or ${override}.`;
- case 'cli_flag':
- return `The model was selected by the ${src.origin} flag on this command.`;
- default:
- return `The model is the built-in ${r.tier}-tier default; ${override}.`;
- }
-}
-
-/** Sets `why` on a provider 404 (an AIConfigError with status 404); any other error passes through unchanged. */
-export function withModelNotFoundWhy<E>(err: E, touchpoint: GatewayTouchpoint, model: string, fallbackChain?: readonly string[]): E {
- if (err instanceof AIConfigError && (err.apiErrorStatus ?? err.status) === 404) err.why = modelNotFoundWhy(touchpoint, model, fallbackChain);
- return err;
-}
-
export function clearGatewayModelSources(): void {
records.clear();
}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 1fc884c540..90a43c8067 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -55,7 +55,7 @@ import {
} from './recipes/openrouter.ts';
import { resolveModelDetailed, resolveEffectiveChatModel, resolveEffectiveExpansionModel } from '../model-config.ts';
import { snapshotConfigReader } from '../config-snapshot.ts';
-import { clearGatewayModelSources, gatewayModelSource, setGatewayModelSource, withModelNotFoundWhy } from './gateway-model-sources.ts';
+import { clearGatewayModelSources, gatewayModelSource, setGatewayModelSource } from './gateway-model-sources.ts';
import { parseLlmJson } from '../llm-json.ts';
import type { BrainEngine } from '../engine.ts';
import { dimsProviderOptions } from './dims.ts';
@@ -2563,9 +2563,9 @@ export async function expand(query: string): Promise<string[]> {
} catch (err) {
if (isAIInvocationPolicyError(err)) throw err;
// Expansion is best-effort: on failure, fall back to the original query alone.
- const normalized = withModelNotFoundWhy(normalizeAIError(err, 'expand', redactKeys), 'expansion', _config?.expansion_model ?? DEFAULT_EXPANSION_MODEL);
+ const normalized = normalizeAIError(err, 'expand', redactKeys);
if (normalized instanceof AIConfigError) {
- console.warn(`[ai.gateway] expansion disabled: ${normalized.message}${normalized.why ? ` ${normalized.why}` : ''}`);
+ console.warn(`[ai.gateway] expansion disabled: ${normalized.message}`);
}
return [query];
}
@@ -3754,7 +3754,7 @@ async function chatAdmitted(opts: ChatOpts, admitted: {
// Pessimistic fallback (A3 amended): when err.usage isn't there, charge
// the worst-case ceiling — better to overcount on failure than under.
_recordBudget(failedCallUsage(err, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }));
- throw withModelNotFoundWhy(normalizeAIError(err, `chat(${recipe.id}:${modelId})`, redactKeys), 'chat', modelStr, cfg.chat_fallback_chain);
+ throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`, redactKeys);
}
}
diff --git a/test/gateway-reconfigure-clobber.serial.test.ts b/test/gateway-reconfigure-clobber.serial.test.ts
index d2d67f8136..8f6ea3821e 100644
--- a/test/gateway-reconfigure-clobber.serial.test.ts
+++ b/test/gateway-reconfigure-clobber.serial.test.ts
@@ -23,11 +23,7 @@ import {
reconfigureGatewayWithEngine,
getChatModel,
resetGateway,
- chat,
- __setGenerateTextTransportForTests,
} from '../src/core/ai/gateway.ts';
-import { AIConfigError } from '../src/core/ai/errors.ts';
-import { renderCliError } from '../src/core/agent-output.ts';
import { TIER_DEFAULTS, _resetDeprecationWarningsForTest, openaiStaticTierFallback } from '../src/core/model-config.ts';
class StubEngine {
@@ -144,86 +140,3 @@ describe('expansion-side effective resolution (review-army addition)', () => {
expect(stderrCapture).toContain('expansion_model');
});
});
-
-describe('model_not_found names the setting that selected the model (#5304)', () => {
- const raw404 = (model: string) => Object.assign(new Error(`The model \`${model}\` does not exist or you do not have access to it`), { status: 404 });
-
- /** Runs the real chat() throw site with a provider that answers 404 (401 when `status` says so). */
- async function chatFailure(model?: string, status = 404): Promise<AIConfigError> {
- __setGenerateTextTransportForTests((async (args: { model: { modelId: string } }) => {
- throw status === 404 ? raw404(args.model.modelId) : Object.assign(new Error('invalid x-api-key'), { status });
- }) as never);
- try {
- await chat({ messages: [{ role: 'user', content: 'hello' }], ...(model ? { model } : {}), allowFallback: false });
- } catch (err) {
- expect(err).toBeInstanceOf(AIConfigError);
- return err as AIConfigError;
- } finally {
- __setGenerateTextTransportForTests(null);
- }
- throw new Error('chat() resolved; expected a provider failure');
- }
-
- test('DB tier key: why names models.tier.reasoning, fix points at gbrain models, rendered through the contract', async () => {
- writeFileConfig({});
- configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
- stub.set('models.tier.reasoning', 'anthropic:claude-gone-1');
- await reconfigureGatewayWithEngine(stub as never);
- const err = await chatFailure();
- expect(err.why).toBe('The model was selected by the DB-plane key models.tier.reasoning; gbrain config set models.tier.reasoning <provider>:<model> replaces it.');
- expect(err.fix).toContain('gbrain models');
- const rendered = renderCliError(err, { json: false, command: 'think', tty: false }).stderr ?? '';
- expect(rendered).toContain('Why: The model was selected by the DB-plane key models.tier.reasoning');
- const envelope = JSON.parse(renderCliError(err, { json: true, command: 'think', tty: false }).stdout!);
- expect(envelope.why).toBe(err.why);
- });
-
- test('a second configure does not rewrite an earlier call\'s explanation', async () => {
- writeFileConfig({});
- configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
- stub.set('models.tier.reasoning', 'anthropic:claude-gone-1');
- await reconfigureGatewayWithEngine(stub as never);
- const before = await chatFailure();
- stub.set('models.chat', 'anthropic:claude-other-2');
- await reconfigureGatewayWithEngine(stub as never);
- // The first call's error keeps its own why; configuration B describes only B's model.
- expect(before.why).toContain('models.tier.reasoning');
- expect((await chatFailure()).why).toContain('DB-plane key models.chat');
- expect((await chatFailure('anthropic:claude-gone-1')).why).toContain('The call named this model itself');
- });
-
- test('file pin: names the chat_model pin in config.json and the models.chat override, not config set chat_model', async () => {
- writeFileConfig({ chat_model: 'openai:gpt-5.2' });
- configureGateway({ chat_model: 'openai:gpt-5.2', env: { OPENAI_API_KEY: 'sk-test' } });
- await reconfigureGatewayWithEngine(stub as never);
- const why = (await chatFailure()).why ?? '';
- expect(why).toContain('the chat_model pin in ~/.gbrain/config.json');
- expect(why).toContain('gbrain config set models.chat <provider>:<model>');
- expect(why).toContain('gbrain config set chat_model writes the DB plane, which does not replace the pin');
- });
-
- test('env: names the variable, never its value', async () => {
- process.env.GBRAIN_CHAT_MODEL = 'openai:gpt-secret-canary';
- writeFileConfig({});
- configureGateway({ chat_model: 'openai:gpt-secret-canary', env: { OPENAI_API_KEY: 'sk-test' } });
- await reconfigureGatewayWithEngine(stub as never);
- const why = (await chatFailure()).why ?? '';
- expect(why).toContain('the GBRAIN_CHAT_MODEL environment variable');
- expect(why).not.toContain('gpt-secret-canary');
- });
-
- test('tier default: names the built-in default and the models.chat override', async () => {
- writeFileConfig({});
- configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
- await reconfigureGatewayWithEngine(stub as never);
- expect((await chatFailure()).why).toBe('The model is the built-in reasoning-tier default; gbrain config set models.chat <provider>:<model> overrides every other setting.');
- });
-
- test('a non-404 provider error carries no provenance', async () => {
- writeFileConfig({});
- configureGateway({ env: { ANTHROPIC_API_KEY: 'sk-ant-test' } });
- stub.set('models.tier.reasoning', 'anthropic:claude-gone-1');
- await reconfigureGatewayWithEngine(stub as never);
- expect((await chatFailure(undefined, 401)).why).toBeUndefined();
- });
-});