Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(ai): classify credit exhaustion as billing, not a rate limit (#8385)

garrytan3c440d90b396
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index 916bd32614..b925202d5a 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -265,7 +265,20 @@ const PER_ITEM_HTTP_STATUSES = new Set([400, 408, 413, 422]);
// halts an entire cycle phase, so a stray word inside a raw-output slice
// must not trip it. Only specific provider phrasings qualify.
export const BILLING_MESSAGE_RE =
- /insufficient_quota|quota exceeded|exceeded your (?:current )?quota|credit balance is too low|spend limit|billing_not_active|billing hard limit|payment required/i;
+ /insufficient_quota|quota exceeded|exceeded your (?:current )?quota|credit balance is too low|no credits remaining|spend limit|billing_not_active|billing hard limit|payment required/i;
+// #8385: the provider's structured error type or code, read from a parsed
+// response body, so a 429 whose message names no billing phrase still halts.
+const BILLING_ERROR_CODES = new Set(['insufficient_quota', 'credit_balance_exhausted', 'billing_not_active']);
+
+function billingErrorBody(responseBody: unknown): boolean {
+ if (typeof responseBody !== 'string') return false;
+ try {
+ const error = JSON.parse(responseBody)?.error;
+ return [error?.type, error?.code].some(v => typeof v === 'string' && BILLING_ERROR_CODES.has(v));
+ } catch {
+ return false;
+ }
+}
const AUTH_MESSAGE_RE =
/authentication_error|permission_error|invalid (?:x-)?api[-_ ]?key|api key (?:is )?(?:invalid|expired|missing)|unauthorized|failed to authenticate|oauth session expired/i;
export const RATE_MESSAGE_RE = /rate[-_ ]?limit(?:ed|_error)?\b|too many requests/i;
@@ -414,7 +427,7 @@ export function classifyGlobalLlmError(err: unknown): GlobalLlmErrorClass | null
const rawIdx = message.indexOf('--- raw ---');
const phraseText = rawIdx === -1 ? message : message.slice(0, rawIdx);
- if (BILLING_MESSAGE_RE.test(phraseText)) return 'billing';
+ if ([...wrappedErrorLayers(err)].some(layer => billingErrorBody(layer.responseBody)) || BILLING_MESSAGE_RE.test(phraseText)) return 'billing';
if (MODEL_NOT_FOUND_MESSAGE_RE.test(phraseText)) return 'model_not_found';
if (status !== undefined) {
const byStatus = statusToClass(status);
diff --git a/test/ai/classify-billing-credits-8400.test.ts b/test/ai/classify-billing-credits-8400.test.ts
new file mode 100644
index 0000000000..5269b6e8c1
--- /dev/null
+++ b/test/ai/classify-billing-credits-8400.test.ts
@@ -0,0 +1,60 @@
+/**
+ * #8385 / #8400 — an OpenAI organisation with no credits answers HTTP 429
+ * ("You have no credits remaining", body error.type insufficient_quota,
+ * error.code credit_balance_exhausted). That is a billing condition: callers
+ * must halt with a billing message instead of retrying it as a rate limit.
+ */
+import { describe, test, expect } from 'bun:test';
+import { APICallError, RetryError } from 'ai';
+import { classifyGlobalLlmError, AITransientError } from '../../src/core/ai/errors.ts';
+
+function apiError(statusCode: number, message: string, responseBody?: string): APICallError {
+ return new APICallError({
+ message,
+ url: 'https://provider.example.invalid/v1/chat/completions',
+ requestBodyValues: {},
+ statusCode,
+ responseBody,
+ isRetryable: statusCode === 429,
+ });
+}
+
+const CREDITS_BODY = JSON.stringify({
+ error: { message: 'synthetic provider message', type: 'insufficient_quota', code: 'credit_balance_exhausted' },
+});
+
+describe('credit exhaustion classifies as billing (#8385)', () => {
+ test('the no-credits message on a 429 is billing', () => {
+ const err = Object.assign(new Error('You have no credits remaining'), { statusCode: 429 });
+ expect(classifyGlobalLlmError(err)).toBe('billing');
+ });
+
+ test('the provider body type/code decides billing whatever the message says', () => {
+ expect(classifyGlobalLlmError(apiError(429, 'Too Many Requests', CREDITS_BODY))).toBe('billing');
+ const codeOnly = JSON.stringify({ error: { code: 'credit_balance_exhausted' } });
+ expect(classifyGlobalLlmError(apiError(429, 'Too Many Requests', codeOnly))).toBe('billing');
+ });
+
+ test('after the SDK spends its retries, the last attempt body still decides', () => {
+ const attempt = () => apiError(429, 'Too Many Requests', CREDITS_BODY);
+ const err = new RetryError({ message: 'Failed after 3 attempts.', reason: 'maxRetriesExceeded', errors: [attempt(), attempt(), attempt()] });
+ expect(classifyGlobalLlmError(err)).toBe('billing');
+ });
+
+ test('the body decides through the facts backstop wrapper chain', () => {
+ const codeOnly = JSON.stringify({ error: { code: 'credit_balance_exhausted' } });
+ const attempt = () => apiError(429, 'Too Many Requests', codeOnly);
+ const retry = new RetryError({ message: 'Failed after 3 attempts.', reason: 'maxRetriesExceeded', errors: [attempt(), attempt(), attempt()] });
+ const err = new Error('facts extraction failed', { cause: new AITransientError('chat failed: Too Many Requests', retry) });
+ expect(classifyGlobalLlmError(err)).toBe('billing');
+ });
+
+ test('a real rate-limit body stays rate_limit', () => {
+ const body = JSON.stringify({ error: { type: 'rate_limit_exceeded', code: 'rate_limit_exceeded' } });
+ expect(classifyGlobalLlmError(apiError(429, 'Too Many Requests', body))).toBe('rate_limit');
+ });
+
+ test('an unparseable body changes nothing', () => {
+ expect(classifyGlobalLlmError(apiError(429, 'Too Many Requests', '<html>insufficient_quota</html>'))).toBe('rate_limit');
+ });
+});