@molecule/api-ai-zhipu 1.2.4 → 1.3.1

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:48.730Z
6
+ Generated: 2026-11-13T19:22:15.430Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-ai-zhipu
@@ -158,7 +158,7 @@ export function setupAiZhipu(): void {
158
158
 
159
159
  Peer dependencies:
160
160
 
161
- - `@molecule/api-ai` ^1.0.1
161
+ - `@molecule/api-ai` ^1.6.0
162
162
  - `@molecule/api-bond` ^1.0.1
163
163
  - `@molecule/api-i18n` ^1.0.1
164
164
  - `@molecule/api-secrets` ^1.0.1
@@ -1 +1 @@
1
- {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAIH,OAAO,KAAK,EACV,UAAU,EASX,MAAM,kBAAkB,CAAA;AASzB,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAgtB7C;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,UAAU,CAE/D"}
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAIH,OAAO,KAAK,EACV,UAAU,EASX,MAAM,kBAAkB,CAAA;AASzB,OAAO,cAAc,CAAA;AAErB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AA4xB7C;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,UAAU,CAE/D"}
package/dist/provider.js CHANGED
@@ -52,6 +52,53 @@ function carriesSearchResults(payload) {
52
52
  function budgetToEffort(budgetTokens) {
53
53
  return budgetTokens >= 8_000 ? 'high' : 'low';
54
54
  }
55
+ /**
56
+ * Read the upstream's explanation from a rejected response body: its error
57
+ * `type` (or `code`) and `message`, the message bounded to 500 characters.
58
+ *
59
+ * @param text - The rejected response's body text.
60
+ * @returns The upstream error, or `undefined` when the body carried neither field.
61
+ */
62
+ function parseUpstreamError(text) {
63
+ let error;
64
+ try {
65
+ error = JSON.parse(text)?.error;
66
+ }
67
+ catch (_error) {
68
+ // Not JSON (a proxy's error page, plain text): a short body is the message itself.
69
+ const trimmed = text.trim();
70
+ return trimmed && trimmed.length <= 500 ? { message: trimmed } : undefined;
71
+ }
72
+ const type = typeof error?.type === 'string'
73
+ ? error.type
74
+ : typeof error?.code === 'string'
75
+ ? error.code
76
+ : undefined;
77
+ const message = typeof error?.message === 'string' ? error.message.slice(0, 500) : undefined;
78
+ if (!type && !message)
79
+ return undefined;
80
+ return { ...(type ? { type } : {}), ...(message ? { message } : {}) };
81
+ }
82
+ /**
83
+ * Zhipu's documented balance, usage, and spend quota errors on HTTP 429
84
+ * (https://docs.z.ai/api-reference/api-code), distinct from ordinary 1302/1305
85
+ * rate/overload responses. Time-bounded retries cannot restore the quota.
86
+ */
87
+ const QUOTA_EXHAUSTED_CODES = new Set([
88
+ '1113',
89
+ '1308',
90
+ '1310',
91
+ '1316',
92
+ '1317',
93
+ '1318',
94
+ '1319',
95
+ '1320',
96
+ '1321',
97
+ ]);
98
+ /** Whether this is a documented account quota failure on its documented status. */
99
+ function isQuotaExhausted(status, error) {
100
+ return status === 429 && error?.type !== undefined && QUOTA_EXHAUSTED_CODES.has(error.type);
101
+ }
55
102
  /**
56
103
  * Zhipu GLM AI provider that implements the `AIProvider` interface
57
104
  * using Zhipu's OpenAI-compatible Chat Completions API with support
@@ -159,7 +206,9 @@ class ZhipuAIProvider {
159
206
  // Retry with exponential backoff for rate limits (429) and overloaded (503)
160
207
  const MAX_RETRIES = 3;
161
208
  let response = null;
209
+ let rejectedBody;
162
210
  for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
211
+ rejectedBody = undefined;
163
212
  response = await fetch(`${this.baseUrl}${this.completionsPath}`, {
164
213
  method: 'POST',
165
214
  headers,
@@ -167,7 +216,24 @@ class ZhipuAIProvider {
167
216
  signal,
168
217
  });
169
218
  if (response.status === 429 || response.status === 503) {
170
- const willRetry = attempt < MAX_RETRIES;
219
+ // Read the body once: an unread body pins its connection, and only the
220
+ // body says what the upstream actually refused the request for.
221
+ try {
222
+ rejectedBody = await response.text();
223
+ }
224
+ catch (error) {
225
+ // Caller cancellation still ends the request; any other read failure
226
+ // only loses the reason, so the body counts as read and the retry
227
+ // policy goes on (the same guard the moonshot bond applies).
228
+ signal.throwIfAborted();
229
+ logger.debug('Zhipu rejected response body could not be read', { error });
230
+ rejectedBody = '';
231
+ }
232
+ const upstreamError = parseUpstreamError(rejectedBody);
233
+ // An exhausted balance or usage quota does not recover during this
234
+ // bounded budget, so fail at once instead of burning the retries.
235
+ const quotaExhausted = isQuotaExhausted(response.status, upstreamError);
236
+ const willRetry = !quotaExhausted && attempt < MAX_RETRIES;
171
237
  // Retry-After is equally-valid as delta-seconds or an HTTP-date;
172
238
  // parseInt on the date form yields NaN, degrading the backoff to a
173
239
  // ~0ms retry against an already rate-limiting API. Guard it.
@@ -190,6 +256,7 @@ class ZhipuAIProvider {
190
256
  willRetry,
191
257
  retryInMs: delayMs,
192
258
  ...(hasRetryAfter ? { retryAfterSeconds: parsedRetryAfterSeconds } : {}),
259
+ ...(upstreamError ? { upstreamError } : {}),
193
260
  });
194
261
  }
195
262
  catch (error) {
@@ -197,10 +264,13 @@ class ZhipuAIProvider {
197
264
  logger.warn('onRateLimit callback threw', { error });
198
265
  }
199
266
  if (willRetry) {
200
- logger.warn('Zhipu API rate limited, retrying', {
267
+ logger.warn(quotaExhausted
268
+ ? 'Zhipu account balance exhausted, retrying until recharged'
269
+ : 'Zhipu API rate limited, retrying', {
201
270
  status: response.status,
202
271
  attempt: attempt + 1,
203
272
  delayMs,
273
+ ...(upstreamError ? { upstreamError } : {}),
204
274
  });
205
275
  await new Promise((resolve) => {
206
276
  const timer = setTimeout(resolve, delayMs);
@@ -217,7 +287,8 @@ class ZhipuAIProvider {
217
287
  break;
218
288
  }
219
289
  if (!response.ok) {
220
- const errorBody = await response.text();
290
+ // A 429/503 body was already read by the retry loop; a body reads only once.
291
+ const errorBody = rejectedBody ?? (await response.text());
221
292
  let detail = `HTTP ${response.status}`;
222
293
  try {
223
294
  const parsed = JSON.parse(errorBody);
@@ -230,18 +301,20 @@ class ZhipuAIProvider {
230
301
  detail = errorBody;
231
302
  }
232
303
  logger.error('Zhipu API error', { status: response.status, detail, errorBody });
233
- const clientMessage = response.status === 429
234
- ? 'AI rate limit exceeded. Please try again shortly.'
235
- : response.status === 401
236
- ? 'AI service configuration error.'
237
- : response.status === 400 &&
238
- /prompt is too long|too many tokens|token.*limit|context.*length/i.test(detail)
239
- ? "Conversation too long for the model's context window. Use /compact to free space, or start a new conversation."
240
- : response.status === 400
241
- ? 'AI request was invalid — check the model and request parameters.'
242
- : response.status === 503
243
- ? 'AI service is temporarily overloaded. Please try again in a moment.'
244
- : 'AI service error. Please try again.';
304
+ const clientMessage = isQuotaExhausted(response.status, parseUpstreamError(errorBody))
305
+ ? 'AI service is unavailable right now. Please try again later.'
306
+ : response.status === 429
307
+ ? 'AI rate limit exceeded. Please try again shortly.'
308
+ : response.status === 401
309
+ ? 'AI service configuration error.'
310
+ : response.status === 400 &&
311
+ /prompt is too long|too many tokens|token.*limit|context.*length/i.test(detail)
312
+ ? "Conversation too long for the model's context window. Use /compact to free space, or start a new conversation."
313
+ : response.status === 400
314
+ ? 'AI request was invalid — check the model and request parameters.'
315
+ : response.status === 503
316
+ ? 'AI service is temporarily overloaded. Please try again in a moment.'
317
+ : 'AI service error. Please try again.';
245
318
  yield { type: 'error', message: clientMessage, errorKey: 'ai.error.apiError' };
246
319
  return;
247
320
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-ai-zhipu",
3
- "version": "1.2.4",
3
+ "version": "1.3.1",
4
4
  "description": "Zhipu GLM AI provider for molecule.dev",
5
5
  "homepage": "https://www.molecule.dev/packages/api-ai-zhipu",
6
6
  "type": "module",
@@ -34,14 +34,14 @@
34
34
  "directory": "packages/api/bonds/ai/zhipu"
35
35
  },
36
36
  "devDependencies": {
37
- "@molecule/api-ai": "1.3.5",
38
- "@molecule/api-bond": "1.0.3",
37
+ "@molecule/api-ai": "1.6.0",
38
+ "@molecule/api-bond": "1.0.4",
39
39
  "@types/node": "26.6.5",
40
40
  "typescript": "6.0.3",
41
41
  "vitest": "4.1.12"
42
42
  },
43
43
  "peerDependencies": {
44
- "@molecule/api-ai": "^1.0.1",
44
+ "@molecule/api-ai": "^1.6.0",
45
45
  "@molecule/api-bond": "^1.0.1",
46
46
  "@molecule/api-i18n": "^1.0.1",
47
47
  "@molecule/api-secrets": "^1.0.1"