Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(contextual): classify wrapped synopsis rate limits and timeouts as transient (#6047)
time-attack8279e2619ca1
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.tsindex b34eca58cf..2a227d7fd7 100644--- a/src/core/ai/errors.ts+++ b/src/core/ai/errors.ts@@ -254,6 +254,37 @@ function numericStatusOf(e: unknown): number | undefined {return undefined;}+/**+ * A thrown provider error and the errors it wraps, outermost first: the+ * `cause` chain, including the AI SDK's RetryError (`lastError`) once its+ * retries are spent. normalizeAIError keeps the provider's own error on+ * `cause`, so its status, name and code are only reachable this way.+ * Objects only, at most five layers.+ */+export function providerErrorChain(err: unknown): object[] {+ const chain: object[] = [];+ let cur: unknown = err;+ for (let depth = 0; cur && typeof cur === 'object' && depth < 5; depth++) {+ chain.push(cur);+ const e = cur as { cause?: unknown; lastError?: unknown };+ cur = e.cause ?? e.lastError;+ }+ return chain;+}++/**+ * The HTTP status a thrown provider error carries, outermost first along its+ * providerErrorChain: `status`, `statusCode`, or the claude-cli provider's+ * `apiErrorStatus`, which normalizeAIError carries to the top level.+ */+export function providerErrorStatus(err: unknown): number | undefined {+ for (const e of providerErrorChain(err)) {+ const status = numericStatusOf(e);+ if (status !== undefined) return status;+ }+ return undefined;+}+/*** Did the provider refuse the request BECAUSE of its `response_format:* json_schema` (an Ollama build predating structured outputs, a strict proxy@@ -268,15 +299,11 @@ function numericStatusOf(e: unknown): number | undefined {const STRUCTURED_OUTPUT_REJECTION_RE = /response_format|json_schema|structured[ _-]?outputs?/i;export function isStructuredOutputRejection(err: unknown): boolean {- let status: number | undefined;- let named = false;- let cur: unknown = err;- for (let depth = 0; cur && typeof cur === 'object' && depth < 5; depth++) {- const e = cur as { message?: unknown; responseBody?: unknown; cause?: unknown; lastError?: unknown };- status ??= numericStatusOf(e);- named ||= [e.message, e.responseBody].some(t => typeof t === 'string' && STRUCTURED_OUTPUT_REJECTION_RE.test(t));- cur = e.cause ?? e.lastError;- }+ const status = providerErrorStatus(err);+ const named = providerErrorChain(err).some((e) => {+ const { message, responseBody } = e as { message?: unknown; responseBody?: unknown };+ return [message, responseBody].some(t => typeof t === 'string' && STRUCTURED_OUTPUT_REJECTION_RE.test(t));+ });if (status !== undefined && (status < 400 || status >= 500 || status === 429)) return false;return named;}diff --git a/src/core/page-summary.ts b/src/core/page-summary.tsindex e50e052eec..4d4d2bd847 100644--- a/src/core/page-summary.ts+++ b/src/core/page-summary.ts@@ -30,6 +30,7 @@* loop and handles page-level fall-back.*/+import { providerErrorChain, providerErrorStatus } from './ai/errors.ts';import { chat, type ChatOpts, type ChatResult } from './ai/gateway.ts';import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.ts';import { sanitizeSynopsis } from './embedding-context.ts';@@ -281,8 +282,13 @@ function buildUserPrompt(/*** Map a thrown error from `gateway.chat()` into the D27 P1-2 failure envelope.*- * Gateway throws Anthropic-flavored errors with HTTP status info; we- * pattern-match on those for the classification.+ * chat() throws the gateway's normalized error, which keeps the provider's+ * own error on `cause` (#5964): the claude-cli provider's status rides as+ * `apiErrorStatus`, an AI SDK provider's as `statusCode` on the wrapped+ * cause (RetryError's `lastError` once retries are spent), and an AI SDK+ * timeout keeps its `TimeoutError` name there. Missing them turns a rate+ * limit or a timeout into `malformed`, which downgrades the whole page to+ * the title tier.*/function classifyChatError(err: unknown): {kind: SynopsisFailureKind;@@ -291,32 +297,33 @@ function classifyChatError(err: unknown): {if (err == null) {return { kind: 'malformed', detail: 'null error' };}- const e = err as { status?: number; message?: string; code?: string; name?: string };+ const e = err as { message?: string; code?: string };const msg = (e.message ?? String(err)).slice(0, 200);+ const status = providerErrorStatus(err);+ const chain = providerErrorChain(err) as Array<{ name?: unknown; code?: unknown }>;+ const networkCode = chain.map((c) => c.code).find(+ (code) => code === 'ENOTFOUND' || code === 'ECONNREFUSED' || code === 'ECONNRESET',+ );- if (e.status === 401 || e.status === 403) {- return { kind: 'auth_failure', detail: `status=${e.status} msg=${msg}` };+ if (status === 401 || status === 403) {+ return { kind: 'auth_failure', detail: `status=${status} msg=${msg}` };}- if (e.status === 429) {+ if (status === 429) {return { kind: 'rate_limit', detail: `status=429 msg=${msg}` };}- if (e.status != null && e.status >= 500 && e.status < 600) {- return { kind: 'provider_5xx', detail: `status=${e.status} msg=${msg}` };+ if (status != null && status >= 500 && status < 600) {+ return { kind: 'provider_5xx', detail: `status=${status} msg=${msg}` };}+ // The message test covers wrappers that drop the name: the claude-cli+ // adapter rejects a timed-out or aborted call as "claude-cli adapter aborted".if (- e.name === 'AbortError' ||- e.code === 'ETIMEDOUT' ||- /timeout/i.test(msg)+ chain.some((c) => c.name === 'AbortError' || c.name === 'TimeoutError' || c.code === 'ETIMEDOUT') ||+ /timeout|timed out|\baborted\b/i.test(msg)) {return { kind: 'timeout', detail: msg };}- if (- e.code === 'ENOTFOUND' ||- e.code === 'ECONNREFUSED' ||- e.code === 'ECONNRESET' ||- /network|fetch/i.test(msg)- ) {- return { kind: 'network', detail: `code=${e.code ?? '?'} msg=${msg}` };+ if (networkCode !== undefined || /network|fetch/i.test(msg)) {+ return { kind: 'network', detail: `code=${networkCode ?? e.code ?? '?'} msg=${msg}` };}// Unknown error shape — treat as malformed so the service routes itdiff --git a/test/contextual-retrieval-service-pure.test.ts b/test/contextual-retrieval-service-pure.test.tsindex 812959668a..06f5085089 100644--- a/test/contextual-retrieval-service-pure.test.ts+++ b/test/contextual-retrieval-service-pure.test.ts@@ -24,6 +24,8 @@ import {type ChatOpts,type ChatResult,} from '../src/core/ai/gateway.ts';+import { normalizeAIError } from '../src/core/ai/errors.ts';+import { ClaudeCliProcessError } from '../src/core/ai/providers/claude-cli-language-model.ts';import type { ChunkInput } from '../src/core/types.ts';import { MARKDOWN_CHUNKER_VERSION } from '../src/core/chunkers/recursive.ts';import { mockEmbedProjectionEngine } from './helpers/embed-projection-mock.ts';@@ -347,6 +349,27 @@ describe('per-chunk synopsis concurrency', () => {expect(started).toBeLessThanOrEqual(3);});+ test('a claude-cli subscription limit is transient, not a title-tier downgrade (#5964)', async () => {+ const out = await runWithChatStub({+ chunks: makeChunks(['chunk-0', 'chunk-1']),+ concurrency: 2,+ chat: async () => {+ // The error chat() throws for this failure: normalizeAIError keeps the+ // claude-cli status as apiErrorStatus and leaves `status` unset.+ throw normalizeAIError(+ new ClaudeCliProcessError("claude-cli API error 429: You've hit your session limit", { apiErrorStatus: 429, exitCode: 1 }),+ 'chat(claude-cli:claude-haiku-4-5)',+ );+ },+ });++ expect(out.result.kind).toBe('transient_error');+ if (out.result.kind === 'transient_error') {+ expect(out.result.cause).toBe('rate_limit');+ }+ expect(out.embeddedChunks).toHaveLength(0);+ });+test('fenced code chunks bypass synopsis calls and leases', async () => {let chatCalls = 0;let leaseCalls = 0;diff --git a/test/page-summary-chat-errors.test.ts b/test/page-summary-chat-errors.test.tsnew file mode 100644index 0000000000..e8f602d353--- /dev/null+++ b/test/page-summary-chat-errors.test.ts@@ -0,0 +1,107 @@+/**+ * #5964: generatePerChunkSynopsis classifies a thrown chat() error by its HTTP+ * status and its timeout or abort signal, wherever the gateway's normalized+ * error carries them.+ *+ * 1. Protects the D27 P1-2 dispatch: a rate limit, an auth failure, a+ * provider outage or a timed-out call must not classify as `malformed`,+ * because `malformed` makes the service re-embed the whole page at the+ * `title` tier and the job report success.+ * 2. Fails when the classifier reads only the top-level error: the claude-cli+ * provider carries its status as `apiErrorStatus`, AI SDK providers carry+ * `statusCode` on the wrapped error (`cause`, then RetryError's `lastError`+ * once the SDK's retries are spent), an AI SDK timeout keeps its+ * `TimeoutError` name on `cause`, and the claude-cli adapter rejects an+ * aborted call with a plain "claude-cli adapter aborted" error.+ * 3. The existing synopsis tests stub chat() whole, so no thrown error ever+ * passed through normalizeAIError on its way to the classifier.+ * 4. No new seam: it drives the real chat() through the existing+ * generateText transport seam.+ */+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';+import { APICallError, RetryError } from 'ai';+import { generatePerChunkSynopsis } from '../src/core/page-summary.ts';+import type { SynopsisFailureKind } from '../src/core/audit-synopsis.ts';+import {+ __setGenerateTextTransportForTests,+ configureGateway,+ resetGateway,+} from '../src/core/ai/gateway.ts';+import { ClaudeCliProcessError } from '../src/core/ai/providers/claude-cli-language-model.ts';++const CLAUDE_CLI = 'claude-cli:claude-haiku-4-5';+const ANTHROPIC_API = 'anthropic:claude-haiku-4-5';++function claudeCliError(status: number | undefined, text: string): ClaudeCliProcessError {+ const message = status === undefined ? text : `claude-cli API error ${status}: ${text}`;+ return new ClaudeCliProcessError(message, { apiErrorStatus: status, exitCode: 1 });+}++function sdkError(statusCode: number): APICallError {+ return new APICallError({+ message: `synthetic provider error ${statusCode}`,+ url: 'https://provider.example.invalid/v1/messages',+ requestBodyValues: {},+ statusCode,+ isRetryable: statusCode === 429 || statusCode >= 500,+ });+}++/** The AI SDK's shape once its retries on a retryable status are spent. */+function sdkRetriesExhausted(statusCode: number): RetryError {+ const errors = [sdkError(statusCode), sdkError(statusCode), sdkError(statusCode)];+ return new RetryError({+ message: `Failed after 3 attempts. Last error: synthetic provider error ${statusCode}`,+ reason: 'maxRetriesExceeded',+ errors,+ });+}++beforeEach(() => {+ configureGateway({ env: { ANTHROPIC_API_KEY: 'fake-anthropic' } });+});++afterEach(() => {+ __setGenerateTextTransportForTests(null);+ resetGateway();+});++describe('generatePerChunkSynopsis classifies thrown chat errors by status and timeout (#5964)', () => {+ const cases: Array<{ name: string; model: string; error: () => unknown; kind: SynopsisFailureKind }> = [+ { name: 'claude-cli subscription limit (429)', model: CLAUDE_CLI, error: () => claudeCliError(429, "You've hit your session limit · resets 3:00am (UTC)"), kind: 'rate_limit' },+ { name: 'claude-cli rejected credentials (401)', model: CLAUDE_CLI, error: () => claudeCliError(401, 'Invalid authentication credentials'), kind: 'auth_failure' },+ { name: 'claude-cli forbidden (403)', model: CLAUDE_CLI, error: () => claudeCliError(403, 'Request not allowed'), kind: 'auth_failure' },+ { name: 'claude-cli overloaded (529)', model: CLAUDE_CLI, error: () => claudeCliError(529, 'Overloaded'), kind: 'provider_5xx' },+ { name: 'claude-cli failure with no status', model: CLAUDE_CLI, error: () => claudeCliError(undefined, 'claude-cli returned an unexpected result'), kind: 'malformed' },+ { name: 'API provider rejected key (401, not retried)', model: ANTHROPIC_API, error: () => sdkError(401), kind: 'auth_failure' },+ { name: 'API provider rate limit after retries (429)', model: ANTHROPIC_API, error: () => sdkRetriesExhausted(429), kind: 'rate_limit' },+ { name: 'API provider outage after retries (529)', model: ANTHROPIC_API, error: () => sdkRetriesExhausted(529), kind: 'provider_5xx' },+ { name: 'API provider request-shaped 400', model: ANTHROPIC_API, error: () => sdkError(400), kind: 'malformed' },+ // The reason AbortSignal.timeout() rejects with when the gateway's default chat timeout fires.+ { name: 'API provider call timed out', model: ANTHROPIC_API, error: () => new DOMException('The operation timed out.', 'TimeoutError'), kind: 'timeout' },+ { name: 'API provider call aborted', model: ANTHROPIC_API, error: () => new DOMException('The operation was aborted.', 'AbortError'), kind: 'timeout' },+ { name: 'claude-cli call timed out or aborted', model: CLAUDE_CLI, error: () => new Error('claude-cli adapter aborted'), kind: 'timeout' },+ { name: 'API provider connection reset on the wrapped cause', model: ANTHROPIC_API, error: () => new Error('socket closed by peer', { cause: Object.assign(new Error('read failed'), { code: 'ECONNRESET' }) }), kind: 'network' },+ { name: 'thrown primitive string with no status', model: ANTHROPIC_API, error: () => 'unexpected provider reply', kind: 'malformed' },+ ];++ for (const c of cases) {+ test(`${c.name} -> ${c.kind}`, async () => {+ __setGenerateTextTransportForTests((async () => {+ throw c.error();+ }) as never);++ const result = await generatePerChunkSynopsis({+ documentText: 'Full document text about widget-co.',+ chunkText: 'The chunk about the widget-co launch.',+ pageTitle: 'Widget Co',+ pageSlug: 'companies/widget-co',+ sourceId: 'default',+ chunkIndex: 0,+ model: c.model,+ });++ expect(result.kind).toBe(c.kind);+ });+ }+});