@molecule/api-ai-anthropic 1.3.6 → 1.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-10-16T23:28:07.527Z
6
+ Generated: 2026-11-13T19:22:11.520Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-ai-anthropic
@@ -134,7 +134,7 @@ export function setupAiAnthropic(): void {
134
134
 
135
135
  Peer dependencies:
136
136
 
137
- - `@molecule/api-ai` ^1.0.1
137
+ - `@molecule/api-ai` ^1.6.0
138
138
  - `@molecule/api-bond` ^1.0.1
139
139
  - `@molecule/api-i18n` ^1.0.1
140
140
  - `@molecule/api-secrets` ^1.0.1
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,KAAK,EACV,UAAU,EASX,MAAM,kBAAkB,CAAA;AASzB,OAAO,cAAc,CAAA;AAGrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AA25BjD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,eAAe,GAAG,UAAU,CAEnE"}
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,KAAK,EACV,UAAU,EASX,MAAM,kBAAkB,CAAA;AASzB,OAAO,cAAc,CAAA;AAGrB,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AA09BjD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,eAAe,GAAG,UAAU,CAEnE"}
package/dist/provider.js CHANGED
@@ -60,6 +60,39 @@ function parseSpeed(usage) {
60
60
  const raw = usage?.speed ?? usage?.service_tier;
61
61
  return raw === 'fast' || raw === 'standard' ? raw : null;
62
62
  }
63
+ /**
64
+ * Read the upstream's explanation from a rejected response body: its error
65
+ * `type` (or `code`) and `message`, the message bounded to 500 characters.
66
+ *
67
+ * @param text - The rejected response's body text.
68
+ * @returns The upstream error, or `undefined` when the body carried neither field.
69
+ */
70
+ function parseUpstreamError(text) {
71
+ let error;
72
+ try {
73
+ error = JSON.parse(text)?.error;
74
+ }
75
+ catch (_error) {
76
+ // Not JSON (a proxy's error page, plain text): a short body is the message itself.
77
+ const trimmed = text.trim();
78
+ return trimmed && trimmed.length <= 500 ? { message: trimmed } : undefined;
79
+ }
80
+ const type = typeof error?.type === 'string'
81
+ ? error.type
82
+ : typeof error?.code === 'string'
83
+ ? error.code
84
+ : undefined;
85
+ const message = typeof error?.message === 'string' ? error.message.slice(0, 500) : undefined;
86
+ if (!type && !message)
87
+ return undefined;
88
+ return { ...(type ? { type } : {}), ...(message ? { message } : {}) };
89
+ }
90
+ /** Format a rejected-body read failure for bounded server-side diagnostics. */
91
+ function formatBodyReadError(error) {
92
+ const name = error instanceof Error ? error.name : 'Error';
93
+ const message = error instanceof Error ? error.message : String(error);
94
+ return `${name}: ${message}`.slice(0, 500);
95
+ }
63
96
  /**
64
97
  * Anthropic Claude AI provider that implements the `AIProvider` interface
65
98
  * using Anthropic's Messages API with support for streaming, tool use,
@@ -215,6 +248,12 @@ class AnthropicAIProvider {
215
248
  // Retry with exponential backoff for rate limits (429) and overloaded (529/503)
216
249
  const MAX_RETRIES = 3;
217
250
  let response = null;
251
+ // The rejected body already read by the retry loop, when this attempt ended
252
+ // on a 429/529/503: a body reads only once, so the error path below must
253
+ // reuse it instead of calling `text()` a second time (which throws).
254
+ let rejectedBody;
255
+ // The bounded name/message when that single body read was interrupted.
256
+ let rejectedBodyReadError;
218
257
  // Set when THIS attempt's response body was cancelled as retry bookkeeping:
219
258
  // the body is then disturbed, so reading it (`text()`) throws "Body is
220
259
  // unusable" — the error path below must not try. Reached when the caller's
@@ -252,7 +291,32 @@ class AnthropicAIProvider {
252
291
  return;
253
292
  }
254
293
  releasedBody = false;
294
+ rejectedBody = undefined;
295
+ rejectedBodyReadError = undefined;
255
296
  if (response.status === 429 || response.status === 529 || response.status === 503) {
297
+ // Read the body ONCE instead of cancelling it: consuming it also
298
+ // releases the connection (the pool takes a socket back only when the
299
+ // body is consumed or cancelled), and only the body says what the
300
+ // upstream refused the request for.
301
+ try {
302
+ rejectedBody = await response.text();
303
+ }
304
+ catch (error) {
305
+ // Caller cancellation still ends the request; any other read failure
306
+ // only loses the reason, so the body counts as released and the
307
+ // retry policy goes on (the same guard the moonshot bond applies).
308
+ if (params.signal?.aborted)
309
+ throw params.signal.reason;
310
+ // A native body is disturbed even when its pending read rejects.
311
+ // Cache an empty detail before the deadline exit so the terminal
312
+ // error path cannot call text() a second time.
313
+ rejectedBody = '';
314
+ rejectedBodyReadError = formatBodyReadError(error);
315
+ if (signal.aborted)
316
+ break;
317
+ logger.warn('Anthropic rejected response body could not be read', { error });
318
+ }
319
+ const upstreamError = parseUpstreamError(rejectedBody);
256
320
  const willRetry = attempt < MAX_RETRIES;
257
321
  // Use Retry-After header if provided, otherwise exponential backoff.
258
322
  // Retry-After is equally-valid as delta-seconds ('30') or an
@@ -280,6 +344,7 @@ class AnthropicAIProvider {
280
344
  willRetry,
281
345
  retryInMs: delayMs,
282
346
  ...(hasRetryAfter ? { retryAfterSeconds: parsedRetryAfterSeconds } : {}),
347
+ ...(upstreamError ? { upstreamError } : {}),
283
348
  });
284
349
  }
285
350
  catch (error) {
@@ -287,22 +352,15 @@ class AnthropicAIProvider {
287
352
  logger.warn('onRateLimit callback threw', { error });
288
353
  }
289
354
  if (willRetry) {
290
- // Release the rejected response's body (and with it its socket)
291
- // before retrying: the connection pool does not take a connection
292
- // back until the body is consumed or cancelled, so every discarded
293
- // rate-limited response would otherwise strand one socket for its
294
- // GC lifetime — under a sustained 429 storm the retries themselves
295
- // hold connections the pool needs for the next attempt (the same
296
- // fix the liquid-d1 bond's retry applies).
355
+ // The rejected response's body was already read above, releasing its
356
+ // connection; this flag only keeps the error path from trying to
357
+ // read it a second time (a body reads only once).
297
358
  releasedBody = true;
298
- await response.body?.cancel().catch((_error) => {
299
- // Best-effort release only — the retry proceeds on the already-
300
- // known status, and a failed cancel merely delays connection reuse.
301
- });
302
359
  logger.warn('Anthropic API rate limited, retrying', {
303
360
  status: response.status,
304
361
  attempt: attempt + 1,
305
362
  delayMs,
363
+ ...(upstreamError ? { upstreamError } : {}),
306
364
  });
307
365
  await new Promise((resolve) => {
308
366
  // A signal that aborted BEFORE this wait began never fires another
@@ -366,7 +424,12 @@ class AnthropicAIProvider {
366
424
  // escape this generator as a raw `TypeError: terminated`, which carries
367
425
  // no `errorKey` and so defeats the caller's error classification.
368
426
  let errorBody = '';
369
- if (!releasedBody) {
427
+ if (rejectedBody !== undefined) {
428
+ // A 429/529/503 body was already read by the retry loop; a body reads
429
+ // only once, so reuse the text instead of asking the response again.
430
+ errorBody = rejectedBody;
431
+ }
432
+ else if (!releasedBody) {
370
433
  try {
371
434
  errorBody = await response.text();
372
435
  }
@@ -388,6 +451,9 @@ class AnthropicAIProvider {
388
451
  if (errorBody.length > 0 && errorBody.length < 200)
389
452
  detail = errorBody;
390
453
  }
454
+ if (rejectedBodyReadError) {
455
+ detail = `${detail}; response body read failed: ${rejectedBodyReadError}`;
456
+ }
391
457
  // Log full detail server-side for debugging
392
458
  logger.error('Anthropic API error', { status: response.status, detail });
393
459
  // Return sanitized but actionable error to client
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-ai-anthropic",
3
- "version": "1.3.6",
3
+ "version": "1.3.8",
4
4
  "description": "Anthropic Claude AI provider for molecule.dev",
5
5
  "homepage": "https://www.molecule.dev/packages/api-ai-anthropic",
6
6
  "type": "module",
@@ -33,14 +33,14 @@
33
33
  "directory": "packages/api/bonds/ai/anthropic"
34
34
  },
35
35
  "devDependencies": {
36
- "@molecule/api-ai": "1.3.5",
37
- "@molecule/api-bond": "1.0.3",
36
+ "@molecule/api-ai": "1.6.0",
37
+ "@molecule/api-bond": "1.0.4",
38
38
  "@types/node": "26.6.5",
39
39
  "typescript": "6.0.3",
40
40
  "vitest": "4.1.12"
41
41
  },
42
42
  "peerDependencies": {
43
- "@molecule/api-ai": "^1.0.1",
43
+ "@molecule/api-ai": "^1.6.0",
44
44
  "@molecule/api-bond": "^1.0.1",
45
45
  "@molecule/api-i18n": "^1.0.1",
46
46
  "@molecule/api-secrets": "^1.0.1"