opencode-quota-gui 1.3.0 → 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.
Files changed (146) hide show
  1. package/README.md +27 -17
  2. package/dist/bin/opencode-quota-gui.js +0 -0
  3. package/dist/contracts/build-identity.js +1 -1
  4. package/dist/contracts/dashboard.d.ts +8 -1
  5. package/dist/contracts/dto-guards.js +2 -0
  6. package/dist/contracts/openai-quota.d.ts +3 -0
  7. package/dist/contracts/openai-quota.js +3 -0
  8. package/dist/data/modelsdev-temporal.min.json +57 -0
  9. package/dist/gui/config.d.ts +3 -3
  10. package/dist/gui/config.js +31 -2
  11. package/dist/gui/lifecycle.d.ts +5 -3
  12. package/dist/gui/lifecycle.js +3 -3
  13. package/dist/gui/primary-quota-windows.js +16 -14
  14. package/dist/gui/provider-cards.d.ts +10 -2
  15. package/dist/gui/provider-cards.js +51 -23
  16. package/dist/gui/quota-notification-detector.d.ts +4 -4
  17. package/dist/gui/quota-notification-detector.js +76 -42
  18. package/dist/gui/quota-notification-observer.d.ts +2 -3
  19. package/dist/gui/quota-notification-observer.js +68 -19
  20. package/dist/gui/rpc.d.ts +2 -0
  21. package/dist/gui/rpc.js +11 -3
  22. package/dist/gui/server.js +11 -2
  23. package/dist/gui/snapshot-service.d.ts +3 -1
  24. package/dist/gui/snapshot-service.js +126 -18
  25. package/dist/gui/sources.js +98 -56
  26. package/dist/gui-experimental.cjs +230 -225
  27. package/dist/lib/accounting-format.js +8 -0
  28. package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
  29. package/dist/lib/alibaba-coding-plan-cli.js +539 -0
  30. package/dist/lib/anthropic-auth.d.ts +2 -3
  31. package/dist/lib/anthropic-auth.js +2 -3
  32. package/dist/lib/anthropic.d.ts +48 -12
  33. package/dist/lib/anthropic.js +610 -275
  34. package/dist/lib/api-key-retry-after.d.ts +7 -0
  35. package/dist/lib/api-key-retry-after.js +62 -0
  36. package/dist/lib/atomic-json.d.ts +2 -0
  37. package/dist/lib/atomic-json.js +1 -0
  38. package/dist/lib/cache-observer-ingestion.d.ts +90 -0
  39. package/dist/lib/cache-observer-ingestion.js +981 -0
  40. package/dist/lib/cache-observer.d.ts +138 -0
  41. package/dist/lib/cache-observer.js +317 -0
  42. package/dist/lib/canonical-config-lock.d.ts +9 -0
  43. package/dist/lib/canonical-config-lock.js +36 -0
  44. package/dist/lib/chutes.js +62 -51
  45. package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
  46. package/dist/lib/claude-agent-transcript-ttl.js +154 -0
  47. package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
  48. package/dist/lib/claude-agent-ttl-tracker.js +152 -0
  49. package/dist/lib/cli-show.js +5 -3
  50. package/dist/lib/config-write-target.d.ts +1 -1
  51. package/dist/lib/config-write-target.js +5 -2
  52. package/dist/lib/config.d.ts +2 -1
  53. package/dist/lib/config.js +193 -2
  54. package/dist/lib/copilot.js +171 -86
  55. package/dist/lib/dashboard-web-policy.d.ts +4 -4
  56. package/dist/lib/dashboard-web-policy.js +2 -2
  57. package/dist/lib/deepseek.js +25 -13
  58. package/dist/lib/display-sanitize.js +1 -0
  59. package/dist/lib/entries.d.ts +23 -0
  60. package/dist/lib/entries.js +2 -0
  61. package/dist/lib/glm-coding-plan.js +98 -74
  62. package/dist/lib/google-agy.js +90 -12
  63. package/dist/lib/google-gemini-cli.js +84 -11
  64. package/dist/lib/http.d.ts +4 -0
  65. package/dist/lib/http.js +16 -2
  66. package/dist/lib/init-installer.js +5 -3
  67. package/dist/lib/kilo.js +37 -18
  68. package/dist/lib/kimi.js +35 -18
  69. package/dist/lib/mimo.d.ts +2 -0
  70. package/dist/lib/mimo.js +36 -0
  71. package/dist/lib/nanogpt.d.ts +1 -0
  72. package/dist/lib/nanogpt.js +26 -3
  73. package/dist/lib/ollama-cloud.d.ts +1 -1
  74. package/dist/lib/ollama-cloud.js +48 -35
  75. package/dist/lib/openai.js +84 -38
  76. package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
  77. package/dist/lib/opencode-auth-sqlite.js +2 -2
  78. package/dist/lib/opencode-config-editor.d.ts +1 -0
  79. package/dist/lib/opencode-config-editor.js +6 -1
  80. package/dist/lib/opencode-go.js +29 -2
  81. package/dist/lib/opencode-version-core.d.ts +23 -0
  82. package/dist/lib/opencode-version-core.js +49 -0
  83. package/dist/lib/opencode-version.d.ts +2 -22
  84. package/dist/lib/opencode-version.js +4 -48
  85. package/dist/lib/opencode-zen.d.ts +3 -0
  86. package/dist/lib/opencode-zen.js +71 -5
  87. package/dist/lib/provider-add.js +5 -2
  88. package/dist/lib/provider-registration.d.ts +19 -9
  89. package/dist/lib/provider-registration.js +17 -6
  90. package/dist/lib/quota-command-format.js +1 -1
  91. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  92. package/dist/lib/quota-exhaustion-projection.js +25 -0
  93. package/dist/lib/quota-providers-remote.d.ts +2 -1
  94. package/dist/lib/quota-providers-remote.js +59 -3
  95. package/dist/lib/quota-providers.d.ts +1 -1
  96. package/dist/lib/quota-providers.js +12 -35
  97. package/dist/lib/quota-render-data.d.ts +6 -0
  98. package/dist/lib/quota-render-data.js +43 -17
  99. package/dist/lib/quota-state-codec.js +17 -1
  100. package/dist/lib/quota-state.d.ts +7 -1
  101. package/dist/lib/quota-state.js +208 -34
  102. package/dist/lib/quota-stats.js +21 -0
  103. package/dist/lib/quota-status.js +3 -51
  104. package/dist/lib/scoped-update.d.ts +1 -1
  105. package/dist/lib/synthetic.js +65 -54
  106. package/dist/lib/types.d.ts +31 -1
  107. package/dist/lib/types.js +13 -0
  108. package/dist/lib/xai.js +48 -22
  109. package/dist/plugin.js +261 -13
  110. package/dist/provider-logos/NOTICE.md +1 -1
  111. package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
  112. package/dist/providers/alibaba-coding-plan.js +107 -104
  113. package/dist/providers/anthropic.d.ts +12 -3
  114. package/dist/providers/anthropic.js +71 -228
  115. package/dist/providers/cache-policies.d.ts +11 -4
  116. package/dist/providers/cache-policies.js +19 -13
  117. package/dist/providers/claude-agent.d.ts +19 -0
  118. package/dist/providers/claude-agent.js +196 -0
  119. package/dist/providers/copilot.js +2 -0
  120. package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
  121. package/dist/providers/google-account-format.js +1 -0
  122. package/dist/providers/google-agy.d.ts +6 -5
  123. package/dist/providers/google-agy.js +43 -15
  124. package/dist/providers/google-gemini-cli.js +1 -0
  125. package/dist/providers/kilo.js +1 -0
  126. package/dist/providers/kimi-code.js +2 -0
  127. package/dist/providers/mimo.js +1 -0
  128. package/dist/providers/nanogpt.js +1 -0
  129. package/dist/providers/opencode-go.js +3 -0
  130. package/dist/providers/opencode-zen.js +2 -0
  131. package/dist/providers/openrouter.js +1 -0
  132. package/dist/providers/quota-providers.js +16 -5
  133. package/dist/providers/registry.js +2 -0
  134. package/dist/providers/result-helpers.d.ts +2 -0
  135. package/dist/providers/result-helpers.js +2 -0
  136. package/dist/rpc.d.ts +121 -8
  137. package/dist/rpc.js +204 -12
  138. package/dist/ui/assets/{index-cDd9jUVY.css → index-BcueIm3Z.css} +1 -1
  139. package/dist/ui/assets/index-C6qRSoh8.js +10 -0
  140. package/dist/ui/assets/{popover-BGkgv9s0.js → popover-4bFSvRZ7.js} +1 -1
  141. package/dist/ui/assets/providers/claude-agent.svg +3 -0
  142. package/dist/ui/index.html +2 -2
  143. package/package.json +44 -45
  144. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
  145. package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
  146. package/dist/ui/assets/index-DLHeXYff.js +0 -9
@@ -1,8 +1,9 @@
1
1
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
2
2
  import { readGlobalProviderConfigString } from "./api-key-resolver.js";
3
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
3
4
  import { clearGeminiCliCompanionCacheForTests as clearGeminiCliCompanionResolutionCacheForTests, inspectGeminiCliCompanionPresence, resolveGeminiCliClientCredentials, } from "./google-gemini-cli-companion.js";
4
5
  import { getCachedAccessToken, makeAccountCacheKey, setCachedAccessToken, } from "./google-token-cache.js";
5
- import { fetchWithTimeout } from "./http.js";
6
+ import { fetchWithTimeout, RequestTimeoutError } from "./http.js";
6
7
  import { mapWithConcurrency } from "./map-with-concurrency.js";
7
8
  import { readAuthFileCached } from "./opencode-auth.js";
8
9
  import { composeResolvedAuthIdentities, deriveResolvedAuthIdentity, } from "./resolved-auth-identity.js";
@@ -215,6 +216,8 @@ async function refreshAccessToken(params) {
215
216
  timeoutMs: params.timeoutMs ?? GEMINI_TOKEN_TIMEOUT_MS,
216
217
  consume: async (response, timeoutSignal) => {
217
218
  if (!response.ok) {
219
+ const retryAtMs = retryAfterDeadline(response);
220
+ const retry = retryAtMs !== undefined ? { retryAtMs } : {};
218
221
  try {
219
222
  const errorData = (await response.json());
220
223
  if (errorData.error === "invalid_grant") {
@@ -223,6 +226,7 @@ async function refreshAccessToken(params) {
223
226
  return {
224
227
  error: errorData.error_description || `HTTP ${response.status}`,
225
228
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
229
+ ...retry,
226
230
  };
227
231
  }
228
232
  catch (error) {
@@ -231,6 +235,7 @@ async function refreshAccessToken(params) {
231
235
  return {
232
236
  error: `HTTP ${response.status}`,
233
237
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
238
+ ...retry,
234
239
  };
235
240
  }
236
241
  }
@@ -249,6 +254,13 @@ async function refreshAccessToken(params) {
249
254
  });
250
255
  }
251
256
  catch (err) {
257
+ if (err instanceof RequestTimeoutError) {
258
+ return {
259
+ error: "Token refresh timeout",
260
+ failureCategory: "provider_api",
261
+ ...(err.retryAtMs !== undefined ? { retryAtMs: err.retryAtMs } : {}),
262
+ };
263
+ }
252
264
  if (err instanceof Error && err.message.includes("timeout")) {
253
265
  return { error: "Token refresh timeout", failureCategory: "provider_api" };
254
266
  }
@@ -271,14 +283,26 @@ async function refreshGeminiCliAccessTokenWithCache(params) {
271
283
  return { accessToken: params.account.accessToken };
272
284
  }
273
285
  }
274
- const refreshed = await refreshAccessToken({
275
- refreshToken: params.account.refreshToken,
276
- clientId: params.credentials.clientId,
277
- clientSecret: params.credentials.clientSecret,
278
- timeoutMs: params.timeoutMs,
279
- });
280
- if ("error" in refreshed)
281
- return refreshed;
286
+ // Guarded per refresh token: the token endpoint's limit is independent of quota reads.
287
+ const guarded = await tokenGuard(params.account.refreshToken, async () => {
288
+ const result = await refreshAccessToken({
289
+ refreshToken: params.account.refreshToken,
290
+ clientId: params.credentials.clientId,
291
+ clientSecret: params.credentials.clientSecret,
292
+ timeoutMs: params.timeoutMs,
293
+ });
294
+ return "error" in result
295
+ ? { success: false, ...result }
296
+ : { success: true, ...result };
297
+ }, params.timeoutMs);
298
+ if (!guarded.success) {
299
+ return {
300
+ error: guarded.error,
301
+ failureCategory: guarded.failureCategory,
302
+ ...(guarded.retryAtMs !== undefined ? { retryAtMs: guarded.retryAtMs } : {}),
303
+ };
304
+ }
305
+ const refreshed = { accessToken: guarded.accessToken, expiresIn: guarded.expiresIn };
282
306
  await setCachedAccessToken({
283
307
  key,
284
308
  entry: {
@@ -290,12 +314,27 @@ async function refreshGeminiCliAccessTokenWithCache(params) {
290
314
  }
291
315
  class GeminiCliQuotaRequestError extends Error {
292
316
  failureCategory;
293
- constructor(message, failureCategory) {
317
+ retryAtMs;
318
+ constructor(message, failureCategory, retryAtMs) {
294
319
  super(message);
295
320
  this.name = "GeminiCliQuotaRequestError";
296
321
  this.failureCategory = failureCategory;
322
+ if (retryAtMs !== undefined)
323
+ this.retryAtMs = retryAtMs;
297
324
  }
298
325
  }
326
+ const tokenGuard = createApiKeyRetryGuard((retryAtMs) => ({
327
+ success: false,
328
+ error: "Token refresh failed: HTTP 429",
329
+ failureCategory: "provider_api",
330
+ retryAtMs,
331
+ }));
332
+ const accountGuard = createApiKeyRetryGuard((retryAtMs) => ({
333
+ success: false,
334
+ error: "Gemini CLI quota API error: 429",
335
+ failureCategory: "provider_api",
336
+ retryAtMs,
337
+ }));
299
338
  async function retrieveGeminiCliQuota(accessToken, projectId, timeoutMs = GEMINI_QUOTA_TIMEOUT_MS) {
300
339
  return await fetchWithTimeout(GEMINI_QUOTA_API_URL, {
301
340
  request: {
@@ -313,7 +352,7 @@ async function retrieveGeminiCliQuota(accessToken, projectId, timeoutMs = GEMINI
313
352
  const failureCategory = providerFailureCategoryForHttpStatus(response.status);
314
353
  throw new GeminiCliQuotaRequestError(response.status === 401 || response.status === 403
315
354
  ? `Gemini CLI quota auth error: ${response.status}`
316
- : `Gemini CLI quota API error: ${response.status}`, failureCategory);
355
+ : `Gemini CLI quota API error: ${response.status}`, failureCategory, retryAfterDeadline(response));
317
356
  }
318
357
  return (await response.json());
319
358
  },
@@ -404,7 +443,32 @@ function mapQuotaBuckets(buckets, account) {
404
443
  });
405
444
  return aggregateGeminiCliQualityTiers(normalizedBuckets);
406
445
  }
446
+ /** Cooldowns are per refresh token + project; a concurrent identical call shares one request. */
407
447
  async function fetchAccountQuota(params) {
448
+ const accountEmail = params.account.email || params.account.sourceKey;
449
+ const { tokenRetryAtMs, ...result } = await accountGuard(`${params.account.refreshToken}\n${params.account.projectId}`, () => fetchAccountQuotaUncached(params), params.timeoutMs, (retryAtMs) => ({
450
+ success: false,
451
+ error: "Gemini CLI quota API error: 429",
452
+ failureCategory: "provider_api",
453
+ accountEmail,
454
+ retryAtMs,
455
+ }));
456
+ const buckets = result.buckets?.map((bucket) => {
457
+ const projected = { ...bucket, sourceKey: params.account.sourceKey };
458
+ if (params.account.email)
459
+ projected.accountEmail = params.account.email;
460
+ else
461
+ delete projected.accountEmail;
462
+ return projected;
463
+ });
464
+ return {
465
+ ...result,
466
+ accountEmail,
467
+ ...(buckets ? { buckets } : {}),
468
+ ...(tokenRetryAtMs !== undefined ? { retryAtMs: tokenRetryAtMs } : {}),
469
+ };
470
+ }
471
+ async function fetchAccountQuotaUncached(params) {
408
472
  const accountEmail = params.account.email || params.account.sourceKey;
409
473
  try {
410
474
  const tokenResult = await refreshGeminiCliAccessTokenWithCache({
@@ -418,6 +482,7 @@ async function fetchAccountQuota(params) {
418
482
  error: tokenResult.error,
419
483
  failureCategory: tokenResult.failureCategory,
420
484
  accountEmail,
485
+ ...(tokenResult.retryAtMs !== undefined ? { tokenRetryAtMs: tokenResult.retryAtMs } : {}),
421
486
  };
422
487
  }
423
488
  let quota;
@@ -438,6 +503,7 @@ async function fetchAccountQuota(params) {
438
503
  error: retryToken.error,
439
504
  failureCategory: retryToken.failureCategory,
440
505
  accountEmail,
506
+ ...(retryToken.retryAtMs !== undefined ? { tokenRetryAtMs: retryToken.retryAtMs } : {}),
441
507
  };
442
508
  }
443
509
  quota = await retrieveGeminiCliQuota(retryToken.accessToken, params.account.projectId, params.timeoutMs);
@@ -459,6 +525,9 @@ async function fetchAccountQuota(params) {
459
525
  error: "API timeout",
460
526
  failureCategory: "provider_api",
461
527
  accountEmail,
528
+ ...(err instanceof RequestTimeoutError && err.retryAtMs !== undefined
529
+ ? { retryAtMs: err.retryAtMs }
530
+ : {}),
462
531
  };
463
532
  }
464
533
  return {
@@ -466,6 +535,9 @@ async function fetchAccountQuota(params) {
466
535
  error: err instanceof Error ? err.message : String(err),
467
536
  failureCategory: err instanceof GeminiCliQuotaRequestError ? err.failureCategory : "provider_api",
468
537
  accountEmail,
538
+ ...(err instanceof GeminiCliQuotaRequestError && err.retryAtMs !== undefined
539
+ ? { retryAtMs: err.retryAtMs }
540
+ : {}),
469
541
  };
470
542
  }
471
543
  }
@@ -504,6 +576,7 @@ export async function queryGeminiCliQuota(options = {}) {
504
576
  ...(result.failureCategory !== undefined
505
577
  ? { failureCategory: result.failureCategory }
506
578
  : {}),
579
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
507
580
  });
508
581
  }
509
582
  }
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * HTTP utilities for provider API calls.
3
3
  */
4
+ export declare class RequestTimeoutError extends Error {
5
+ readonly retryAtMs?: number;
6
+ constructor(message: string, retryAtMs?: number);
7
+ }
4
8
  export type FetchWithTimeoutOptions<T> = {
5
9
  request: Omit<RequestInit, "signal">;
6
10
  timeoutMs?: number;
package/dist/lib/http.js CHANGED
@@ -1,7 +1,17 @@
1
1
  /**
2
2
  * HTTP utilities for provider API calls.
3
3
  */
4
+ import { retryAfterDeadline } from "./api-key-retry-after.js";
4
5
  import { REQUEST_TIMEOUT_MS } from "./types.js";
6
+ export class RequestTimeoutError extends Error {
7
+ retryAtMs;
8
+ constructor(message, retryAtMs) {
9
+ super(message);
10
+ this.name = "RequestTimeoutError";
11
+ if (retryAtMs !== undefined)
12
+ this.retryAtMs = retryAtMs;
13
+ }
14
+ }
5
15
  /**
6
16
  * Fetch and consume a response within one timeout.
7
17
  *
@@ -14,13 +24,16 @@ export async function fetchWithTimeout(url, options) {
14
24
  const timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
15
25
  const controller = new AbortController();
16
26
  let timedOut = false;
27
+ let observedRetryAtMs;
28
+ let timeoutError;
17
29
  const timeoutErrorMessage = `Request timeout after ${Math.round(timeoutMs / 1000)}s`;
18
30
  let timeoutId;
19
31
  const timeout = new Promise((_resolve, reject) => {
20
32
  timeoutId = setTimeout(() => {
21
33
  timedOut = true;
22
34
  controller.abort();
23
- reject(new Error(timeoutErrorMessage));
35
+ timeoutError = new RequestTimeoutError(timeoutErrorMessage, observedRetryAtMs);
36
+ reject(timeoutError);
24
37
  }, timeoutMs);
25
38
  });
26
39
  try {
@@ -30,13 +43,14 @@ export async function fetchWithTimeout(url, options) {
30
43
  ...options.request,
31
44
  signal: controller.signal,
32
45
  });
46
+ observedRetryAtMs = retryAfterDeadline(response);
33
47
  return await options.consume(response, controller.signal);
34
48
  })();
35
49
  return await Promise.race([transaction, timeout]);
36
50
  }
37
51
  catch (err) {
38
52
  if (timedOut) {
39
- throw new Error(timeoutErrorMessage);
53
+ throw timeoutError ?? new RequestTimeoutError(timeoutErrorMessage, observedRetryAtMs);
40
54
  }
41
55
  throw err;
42
56
  }
@@ -653,9 +653,11 @@ function buildPlanSummary(plan) {
653
653
  }
654
654
  export function getInstallerProviderPromptOptions() {
655
655
  return QUOTA_PROVIDER_SHAPES.map((shape) => ({
656
- label: shape.autoSetup === "needs_quick_setup"
657
- ? `${getQuotaProviderDisplayLabel(shape.id)} (quick setup)`
658
- : getQuotaProviderDisplayLabel(shape.id),
656
+ label: shape.autoSetup === "unavailable"
657
+ ? `${getQuotaProviderDisplayLabel(shape.id)} (quota unavailable)`
658
+ : shape.autoSetup === "needs_quick_setup"
659
+ ? `${getQuotaProviderDisplayLabel(shape.id)} (quick setup)`
660
+ : getQuotaProviderDisplayLabel(shape.id),
659
661
  value: shape.id,
660
662
  }));
661
663
  }
package/dist/lib/kilo.js CHANGED
@@ -6,12 +6,20 @@
6
6
  * without an active Kilo Pass.
7
7
  */
8
8
  import { providerFailureCategoryForHttpStatus } from "../contracts/provider-failure.js";
9
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
9
10
  import { sanitizeSingleLineDisplayText } from "./display-sanitize.js";
10
11
  import { fetchWithTimeout } from "./http.js";
11
12
  import { resolveKiloApiKey } from "./kilo-config.js";
12
13
  const KILO_PASS_STATE_ENDPOINT = "https://app.kilo.ai/api/trpc/kiloPass.getState";
13
14
  const KILO_BALANCE_ENDPOINT = "https://api.kilo.ai/api/profile/balance";
14
15
  const MAX_RESPONSE_BYTES = 64 * 1024;
16
+ const kiloBlocked = (retryAtMs) => ({
17
+ success: false,
18
+ error: "Kilo Gateway API error 429",
19
+ failureCategory: "provider_api",
20
+ retryAtMs,
21
+ });
22
+ const quotaGuard = createApiKeyRetryGuard(kiloBlocked);
15
23
  function invalidKiloResponse(error) {
16
24
  return { success: false, error, failureCategory: "provider_api" };
17
25
  }
@@ -144,6 +152,7 @@ async function requestKiloPassState(key, options) {
144
152
  input: JSON.stringify({ "0": null }),
145
153
  });
146
154
  let responseStatus;
155
+ let retryAtMs;
147
156
  try {
148
157
  return await fetchWithTimeout(`${KILO_PASS_STATE_ENDPOINT}?${query.toString()}`, {
149
158
  request: {
@@ -158,12 +167,14 @@ async function requestKiloPassState(key, options) {
158
167
  timeoutMs: options.requestTimeoutMs,
159
168
  consume: async (response) => {
160
169
  responseStatus = response.status;
170
+ retryAtMs = retryAfterDeadline(response);
161
171
  const text = await readResponseText(response, "state");
162
172
  if (!response.ok) {
163
173
  return {
164
174
  success: false,
165
175
  error: `Kilo Gateway state API error ${response.status}: ${sanitizeMessage(text, key)}`,
166
176
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
177
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
167
178
  };
168
179
  }
169
180
  return parseKiloPassState(JSON.parse(text));
@@ -177,11 +188,13 @@ async function requestKiloPassState(key, options) {
177
188
  failureCategory: responseStatus === undefined
178
189
  ? "provider_api"
179
190
  : providerFailureCategoryForHttpStatus(responseStatus),
191
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
180
192
  };
181
193
  }
182
194
  }
183
195
  async function requestKiloBalance(key, options) {
184
196
  let responseStatus;
197
+ let retryAtMs;
185
198
  try {
186
199
  return await fetchWithTimeout(KILO_BALANCE_ENDPOINT, {
187
200
  request: {
@@ -196,12 +209,14 @@ async function requestKiloBalance(key, options) {
196
209
  timeoutMs: options.requestTimeoutMs,
197
210
  consume: async (response) => {
198
211
  responseStatus = response.status;
212
+ retryAtMs = retryAfterDeadline(response);
199
213
  const text = await readResponseText(response, "balance");
200
214
  if (!response.ok) {
201
215
  return {
202
216
  success: false,
203
217
  error: `Kilo Gateway balance API error ${response.status}: ${sanitizeMessage(text, key)}`,
204
218
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
219
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
205
220
  };
206
221
  }
207
222
  return parseKiloBalance(JSON.parse(text));
@@ -215,6 +230,7 @@ async function requestKiloBalance(key, options) {
215
230
  failureCategory: responseStatus === undefined
216
231
  ? "provider_api"
217
232
  : providerFailureCategoryForHttpStatus(responseStatus),
233
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
218
234
  };
219
235
  }
220
236
  }
@@ -232,23 +248,26 @@ export async function queryKiloQuota(options = {}) {
232
248
  const resolved = await resolveKiloApiKey();
233
249
  if (!resolved)
234
250
  return null;
235
- const passResult = await requestKiloPassState(resolved.key, options);
236
- if (passResult.success) {
237
- return { ...passResult, mode: "kilo_pass" };
238
- }
239
- if (!isNoActiveKiloPassResult(passResult)) {
240
- return passResult;
241
- }
242
- const balanceResult = await requestKiloBalance(resolved.key, options);
243
- if (balanceResult.success) {
244
- return { ...balanceResult, mode: "gateway_balance" };
245
- }
246
- return {
247
- success: false,
248
- error: `Kilo Gateway has no active Kilo Pass subscription; balance fallback failed: ${balanceResult.error}`,
249
- ...(balanceResult.failureCategory !== undefined
250
- ? { failureCategory: balanceResult.failureCategory }
251
- : {}),
252
- };
251
+ return quotaGuard(resolved.key, async () => {
252
+ const passResult = await requestKiloPassState(resolved.key, options);
253
+ if (passResult.success) {
254
+ return { ...passResult, mode: "kilo_pass" };
255
+ }
256
+ if (!isNoActiveKiloPassResult(passResult)) {
257
+ return passResult;
258
+ }
259
+ const balanceResult = await requestKiloBalance(resolved.key, options);
260
+ if (balanceResult.success) {
261
+ return { ...balanceResult, mode: "gateway_balance" };
262
+ }
263
+ return {
264
+ success: false,
265
+ error: `Kilo Gateway has no active Kilo Pass subscription; balance fallback failed: ${balanceResult.error}`,
266
+ ...(balanceResult.failureCategory !== undefined
267
+ ? { failureCategory: balanceResult.failureCategory }
268
+ : {}),
269
+ ...(balanceResult.retryAtMs !== undefined ? { retryAtMs: balanceResult.retryAtMs } : {}),
270
+ };
271
+ }, options.requestTimeoutMs);
253
272
  }
254
273
  //# sourceMappingURL=kilo.js.map
package/dist/lib/kimi.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
2
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
2
3
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
3
4
  import { clampPercent } from "./format-utils.js";
4
5
  import { fetchWithTimeout } from "./http.js";
@@ -178,8 +179,15 @@ function parseKimiUsagePayload(payload) {
178
179
  }
179
180
  return { windows, topLevelKeys };
180
181
  }
182
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
183
+ success: false,
184
+ error: "Kimi API error 429",
185
+ failureCategory: "provider_api",
186
+ retryAtMs,
187
+ }));
181
188
  async function fetchKimiQuotaFromUrl(url, apiKey, requestTimeoutMs) {
182
189
  let responseStatus;
190
+ let retryAtMs;
183
191
  try {
184
192
  return await fetchWithTimeout(url, {
185
193
  request: {
@@ -192,11 +200,13 @@ async function fetchKimiQuotaFromUrl(url, apiKey, requestTimeoutMs) {
192
200
  consume: async (resp) => {
193
201
  responseStatus = resp.status;
194
202
  if (!resp.ok) {
203
+ retryAtMs = retryAfterDeadline(resp);
195
204
  const text = await resp.text();
196
205
  return {
197
206
  ok: false,
198
207
  error: `Kimi API error ${resp.status}: ${sanitizeDisplaySnippet(text, 120)}`,
199
208
  failureCategory: providerFailureCategoryForHttpStatus(resp.status),
209
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
200
210
  };
201
211
  }
202
212
  const payload = (await resp.json());
@@ -212,31 +222,38 @@ async function fetchKimiQuotaFromUrl(url, apiKey, requestTimeoutMs) {
212
222
  failureCategory: responseStatus === undefined
213
223
  ? "provider_api"
214
224
  : providerFailureCategoryForHttpStatus(responseStatus),
225
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
215
226
  };
216
227
  }
217
228
  }
218
229
  export async function queryKimiQuota(options) {
219
230
  const endpoint = getKimiQuotaEndpoint(options.endpoint);
220
- const result = await fetchKimiQuotaFromUrl(endpoint.quotaUrl, options.apiKey, options.requestTimeoutMs);
221
- if (result.ok && result.windows.length > 0) {
222
- return {
223
- success: true,
224
- label: options.label ?? endpoint.label,
225
- windows: result.windows,
226
- };
227
- }
228
- if (!result.ok) {
231
+ // Endpoint is part of the guarded identity so one key on global/cn stays isolated.
232
+ return guard(`${options.endpoint}\0${options.apiKey}`, async () => {
233
+ const result = await fetchKimiQuotaFromUrl(endpoint.quotaUrl, options.apiKey, options.requestTimeoutMs);
234
+ if (result.ok && result.windows.length > 0) {
235
+ return {
236
+ success: true,
237
+ label: options.label ?? endpoint.label,
238
+ windows: result.windows,
239
+ };
240
+ }
241
+ if (!result.ok) {
242
+ return {
243
+ success: false,
244
+ error: result.error,
245
+ ...(result.failureCategory !== undefined
246
+ ? { failureCategory: result.failureCategory }
247
+ : {}),
248
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
249
+ };
250
+ }
251
+ // Succeeded structurally but had no usable windows.
229
252
  return {
230
253
  success: false,
231
- error: result.error,
232
- ...(result.failureCategory !== undefined ? { failureCategory: result.failureCategory } : {}),
254
+ error: describeUnexpectedPayload(result.topLevelKeys),
255
+ failureCategory: "provider_api",
233
256
  };
234
- }
235
- // Succeeded structurally but had no usable windows.
236
- return {
237
- success: false,
238
- error: describeUnexpectedPayload(result.topLevelKeys),
239
- failureCategory: "provider_api",
240
- };
257
+ }, options.requestTimeoutMs);
241
258
  }
242
259
  //# sourceMappingURL=kimi.js.map
@@ -21,6 +21,8 @@ export type MimoEndpointResult<T> = {
21
21
  state: "error";
22
22
  error: string;
23
23
  failureCategory: ProviderFailureCategory;
24
+ /** Deadline observed in an upstream Retry-After response. */
25
+ retryAtMs?: number;
24
26
  };
25
27
  export interface MimoDashboardResult {
26
28
  usage: MimoEndpointResult<MimoMonthlyQuota>;
package/dist/lib/mimo.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
1
2
  import { sanitizeSingleLineDisplaySnippet } from "./display-sanitize.js";
2
3
  import { fetchWithTimeout } from "./http.js";
3
4
  const MIMO_USAGE_URL = "https://platform.xiaomimimo.com/api/v1/tokenPlan/usage";
@@ -6,6 +7,16 @@ const MIMO_BALANCE_URL = "https://platform.xiaomimimo.com/api/v1/balance";
6
7
  const MIMO_REQUEST_TIMEOUT_MS = 10_000;
7
8
  const MIMO_RESPONSE_MAX_BYTES = 256 * 1024;
8
9
  const MIMO_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36";
10
+ const endpointGuard = createApiKeyRetryGuard((retryAtMs) => ({
11
+ success: false,
12
+ retryAtMs,
13
+ endpoint: {
14
+ state: "error",
15
+ error: "Xiaomi MiMo request failed (HTTP 429)",
16
+ failureCategory: "provider_api",
17
+ retryAtMs,
18
+ },
19
+ }));
9
20
  function isRecord(value) {
10
21
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11
22
  }
@@ -144,7 +155,30 @@ function sanitizeRequestError(error, cookie) {
144
155
  }
145
156
  return sanitizeSingleLineDisplaySnippet(message, 120) || "request failed";
146
157
  }
158
+ /** One cooldown per session cookie and endpoint; other cookies are unaffected. */
147
159
  async function fetchMimoEndpoint(params) {
160
+ const guarded = await endpointGuard(JSON.stringify([params.cookie, params.name]), async () => {
161
+ const endpoint = await requestMimoEndpoint(params);
162
+ return {
163
+ success: endpoint.state === "success",
164
+ ...(endpoint.state === "error" && endpoint.retryAtMs !== undefined
165
+ ? { retryAtMs: endpoint.retryAtMs }
166
+ : {}),
167
+ endpoint,
168
+ };
169
+ }, params.requestTimeoutMs, (retryAtMs) => ({
170
+ success: false,
171
+ retryAtMs,
172
+ endpoint: {
173
+ state: "error",
174
+ error: `Xiaomi MiMo ${params.name} request failed (HTTP 429)`,
175
+ failureCategory: "provider_api",
176
+ retryAtMs,
177
+ },
178
+ }));
179
+ return guarded.endpoint;
180
+ }
181
+ async function requestMimoEndpoint(params) {
148
182
  try {
149
183
  return await fetchWithTimeout(params.url, {
150
184
  request: {
@@ -170,10 +204,12 @@ async function fetchMimoEndpoint(params) {
170
204
  };
171
205
  }
172
206
  if (!response.ok) {
207
+ const retryAtMs = retryAfterDeadline(response);
173
208
  return {
174
209
  state: "error",
175
210
  error: `Xiaomi MiMo ${params.name} request failed (HTTP ${response.status})`,
176
211
  failureCategory: response.status === 401 || response.status === 403 ? "credentials" : "provider_api",
212
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
177
213
  };
178
214
  }
179
215
  let json;
@@ -41,6 +41,7 @@ export type NanoGptResult = {
41
41
  endpoint: NanoGptEndpoint;
42
42
  message: string;
43
43
  failureCategory?: ProviderFailureCategory;
44
+ retryAtMs?: number;
44
45
  }>;
45
46
  } | QuotaError | null;
46
47
  export { getNanoGptKeyDiagnostics, hasNanoGptApiKey as hasNanoGptApiKeyConfigured, type NanoGptKeySource, } from "./nanogpt-config.js";