opencode-quota-gui 1.3.0 → 1.3.2

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 (238) hide show
  1. package/README.md +34 -20
  2. package/dist/bin/opencode-quota-gui.js +0 -0
  3. package/dist/contracts/build-identity.js +1 -1
  4. package/dist/contracts/card-order.d.ts +2 -0
  5. package/dist/contracts/card-order.js +2 -2
  6. package/dist/contracts/card-visibility.d.ts +2 -1
  7. package/dist/contracts/card-visibility.js +2 -1
  8. package/dist/contracts/dashboard.d.ts +95 -6
  9. package/dist/contracts/dashboard.js +10 -0
  10. package/dist/contracts/dto-guards.d.ts +4 -0
  11. package/dist/contracts/dto-guards.js +31 -7
  12. package/dist/contracts/guards.js +3 -1
  13. package/dist/contracts/identity.d.ts +37 -5
  14. package/dist/contracts/identity.js +43 -0
  15. package/dist/contracts/openai-quota.d.ts +3 -0
  16. package/dist/contracts/openai-quota.js +3 -0
  17. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  18. package/dist/contracts/provider-auto-resume.js +24 -0
  19. package/dist/contracts/provider-failure.d.ts +22 -0
  20. package/dist/contracts/provider-failure.js +25 -1
  21. package/dist/contracts/row-order.d.ts +13 -0
  22. package/dist/contracts/row-order.js +34 -0
  23. package/dist/contracts/row-visibility.d.ts +53 -0
  24. package/dist/contracts/row-visibility.js +130 -0
  25. package/dist/data/modelsdev-pricing.min.json +1 -1
  26. package/dist/data/modelsdev-temporal.min.json +60 -634
  27. package/dist/gui/aggregation.d.ts +29 -1
  28. package/dist/gui/aggregation.js +157 -4
  29. package/dist/gui/analytics-bridge.d.ts +8 -9
  30. package/dist/gui/analytics-bridge.js +197 -54
  31. package/dist/gui/analytics-engine.d.ts +7 -15
  32. package/dist/gui/analytics-engine.js +246 -106
  33. package/dist/gui/analytics-model.d.ts +7 -0
  34. package/dist/gui/analytics-model.js +75 -9
  35. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  36. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  37. package/dist/gui/analytics-protocol.d.ts +17 -7
  38. package/dist/gui/analytics-protocol.js +1 -0
  39. package/dist/gui/analytics-service.d.ts +10 -0
  40. package/dist/gui/analytics-service.js +30 -9
  41. package/dist/gui/analytics-state.d.ts +30 -5
  42. package/dist/gui/analytics-state.js +46 -7
  43. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  44. package/dist/gui/analytics-worker-runtime.js +9 -1
  45. package/dist/gui/analytics-worker.js +11 -0
  46. package/dist/gui/config.d.ts +3 -3
  47. package/dist/gui/config.js +77 -7
  48. package/dist/gui/identity.d.ts +6 -20
  49. package/dist/gui/identity.js +6 -54
  50. package/dist/gui/lifecycle.d.ts +5 -3
  51. package/dist/gui/lifecycle.js +3 -3
  52. package/dist/gui/primary-quota-windows.js +67 -44
  53. package/dist/gui/provider-cards.d.ts +20 -8
  54. package/dist/gui/provider-cards.js +42 -55
  55. package/dist/gui/quota-notification-detector.d.ts +29 -6
  56. package/dist/gui/quota-notification-detector.js +136 -47
  57. package/dist/gui/quota-notification-observer.d.ts +3 -4
  58. package/dist/gui/quota-notification-observer.js +73 -20
  59. package/dist/gui/quota-observation.d.ts +4 -0
  60. package/dist/gui/quota-observation.js +18 -0
  61. package/dist/gui/rpc.d.ts +2 -0
  62. package/dist/gui/rpc.js +14 -3
  63. package/dist/gui/server.js +17 -3
  64. package/dist/gui/snapshot-service.d.ts +3 -15
  65. package/dist/gui/snapshot-service.js +281 -23
  66. package/dist/gui/sources.js +179 -64
  67. package/dist/gui/temporal-status.d.ts +3 -2
  68. package/dist/gui/temporal-status.js +10 -6
  69. package/dist/gui-experimental.cjs +230 -225
  70. package/dist/lib/accounting-format.d.ts +8 -0
  71. package/dist/lib/accounting-format.js +20 -2
  72. package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
  73. package/dist/lib/alibaba-coding-plan-cli.js +539 -0
  74. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  75. package/dist/lib/anthropic-api-auth.js +27 -0
  76. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  77. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  78. package/dist/lib/anthropic-auth.d.ts +2 -3
  79. package/dist/lib/anthropic-auth.js +2 -3
  80. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  81. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  82. package/dist/lib/anthropic.d.ts +68 -14
  83. package/dist/lib/anthropic.js +1016 -363
  84. package/dist/lib/api-key-retry-after.d.ts +7 -0
  85. package/dist/lib/api-key-retry-after.js +62 -0
  86. package/dist/lib/atomic-json.d.ts +2 -0
  87. package/dist/lib/atomic-json.js +1 -0
  88. package/dist/lib/cache-observer-ingestion.d.ts +90 -0
  89. package/dist/lib/cache-observer-ingestion.js +1008 -0
  90. package/dist/lib/cache-observer.d.ts +141 -0
  91. package/dist/lib/cache-observer.js +323 -0
  92. package/dist/lib/canonical-config-lock.d.ts +9 -0
  93. package/dist/lib/canonical-config-lock.js +36 -0
  94. package/dist/lib/chutes.js +62 -51
  95. package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
  96. package/dist/lib/claude-agent-transcript-ttl.js +154 -0
  97. package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
  98. package/dist/lib/claude-agent-ttl-tracker.js +152 -0
  99. package/dist/lib/cli-show.d.ts +5 -0
  100. package/dist/lib/cli-show.js +21 -8
  101. package/dist/lib/cli-status.js +3 -6
  102. package/dist/lib/config-write-target.d.ts +1 -1
  103. package/dist/lib/config-write-target.js +5 -2
  104. package/dist/lib/config.d.ts +2 -1
  105. package/dist/lib/config.js +257 -4
  106. package/dist/lib/copilot.js +171 -86
  107. package/dist/lib/dashboard-visibility.d.ts +5 -0
  108. package/dist/lib/dashboard-visibility.js +11 -10
  109. package/dist/lib/dashboard-web-policy.d.ts +4 -4
  110. package/dist/lib/dashboard-web-policy.js +2 -2
  111. package/dist/lib/deepseek.js +25 -13
  112. package/dist/lib/display-sanitize.js +2 -0
  113. package/dist/lib/entries.d.ts +33 -1
  114. package/dist/lib/entries.js +6 -0
  115. package/dist/lib/glm-coding-plan.js +98 -74
  116. package/dist/lib/google-agy.js +90 -12
  117. package/dist/lib/google-gemini-cli.js +84 -11
  118. package/dist/lib/grouped-entry-normalization.js +1 -1
  119. package/dist/lib/http.d.ts +4 -0
  120. package/dist/lib/http.js +16 -2
  121. package/dist/lib/init-installer.js +5 -3
  122. package/dist/lib/kilo.js +37 -18
  123. package/dist/lib/kimi.js +35 -18
  124. package/dist/lib/maintainer-announcements.js +2 -2
  125. package/dist/lib/mimo.d.ts +2 -0
  126. package/dist/lib/mimo.js +36 -0
  127. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  128. package/dist/lib/modelsdev-pricing.js +457 -63
  129. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  130. package/dist/lib/modelsdev-temporal.js +16 -2
  131. package/dist/lib/nanogpt.d.ts +1 -0
  132. package/dist/lib/nanogpt.js +26 -3
  133. package/dist/lib/ollama-cloud.d.ts +1 -1
  134. package/dist/lib/ollama-cloud.js +48 -35
  135. package/dist/lib/openai.js +84 -38
  136. package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
  137. package/dist/lib/opencode-auth-sqlite.js +2 -2
  138. package/dist/lib/opencode-config-editor.d.ts +1 -0
  139. package/dist/lib/opencode-config-editor.js +6 -1
  140. package/dist/lib/opencode-config-providers.js +2 -2
  141. package/dist/lib/opencode-go.js +29 -2
  142. package/dist/lib/opencode-storage.d.ts +20 -0
  143. package/dist/lib/opencode-storage.js +89 -2
  144. package/dist/lib/opencode-version-core.d.ts +30 -0
  145. package/dist/lib/opencode-version-core.js +59 -0
  146. package/dist/lib/opencode-version.d.ts +2 -22
  147. package/dist/lib/opencode-version.js +4 -48
  148. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  149. package/dist/lib/opencode-warming-refresh.js +95 -0
  150. package/dist/lib/opencode-zen.d.ts +3 -0
  151. package/dist/lib/opencode-zen.js +71 -5
  152. package/dist/lib/provider-add.js +5 -2
  153. package/dist/lib/provider-metadata.d.ts +11 -3
  154. package/dist/lib/provider-metadata.js +20 -2
  155. package/dist/lib/provider-registration.d.ts +358 -9
  156. package/dist/lib/provider-registration.js +423 -30
  157. package/dist/lib/quota-auto-resume.d.ts +74 -0
  158. package/dist/lib/quota-auto-resume.js +539 -0
  159. package/dist/lib/quota-command-format.js +23 -10
  160. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  161. package/dist/lib/quota-exhaustion-projection.js +25 -0
  162. package/dist/lib/quota-identity.d.ts +64 -0
  163. package/dist/lib/quota-identity.js +111 -0
  164. package/dist/lib/quota-providers-remote.d.ts +2 -1
  165. package/dist/lib/quota-providers-remote.js +59 -3
  166. package/dist/lib/quota-providers.d.ts +1 -1
  167. package/dist/lib/quota-providers.js +14 -37
  168. package/dist/lib/quota-render-data.d.ts +6 -0
  169. package/dist/lib/quota-render-data.js +45 -19
  170. package/dist/lib/quota-reset-notifications.js +11 -155
  171. package/dist/lib/quota-retry-wait.d.ts +106 -5
  172. package/dist/lib/quota-retry-wait.js +301 -34
  173. package/dist/lib/quota-runtime-context.js +1 -0
  174. package/dist/lib/quota-state-codec.d.ts +2 -0
  175. package/dist/lib/quota-state-codec.js +31 -2
  176. package/dist/lib/quota-state.d.ts +8 -2
  177. package/dist/lib/quota-state.js +253 -47
  178. package/dist/lib/quota-stats.d.ts +26 -0
  179. package/dist/lib/quota-stats.js +40 -1
  180. package/dist/lib/quota-status.js +3 -51
  181. package/dist/lib/quota-surface-data.js +18 -3
  182. package/dist/lib/quota-telemetry.js +2 -2
  183. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  184. package/dist/lib/resolved-auth-identity.js +44 -0
  185. package/dist/lib/scoped-update.d.ts +1 -1
  186. package/dist/lib/state-file-lock.d.ts +26 -0
  187. package/dist/lib/state-file-lock.js +205 -0
  188. package/dist/lib/synthetic.js +65 -54
  189. package/dist/lib/toast-format-grouped.js +7 -4
  190. package/dist/lib/tui-compact-format.js +29 -16
  191. package/dist/lib/types.d.ts +51 -1
  192. package/dist/lib/types.js +17 -1
  193. package/dist/lib/xai.js +48 -22
  194. package/dist/plugin.js +328 -14
  195. package/dist/provider-logos/NOTICE.md +1 -1
  196. package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
  197. package/dist/providers/alibaba-coding-plan.js +125 -104
  198. package/dist/providers/alibaba-token-plan.js +9 -5
  199. package/dist/providers/anthropic.d.ts +16 -3
  200. package/dist/providers/anthropic.js +172 -220
  201. package/dist/providers/cache-policies.d.ts +11 -4
  202. package/dist/providers/cache-policies.js +19 -13
  203. package/dist/providers/chutes.js +2 -0
  204. package/dist/providers/claude-agent.d.ts +19 -0
  205. package/dist/providers/claude-agent.js +215 -0
  206. package/dist/providers/copilot.js +7 -4
  207. package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
  208. package/dist/providers/glm-coding-plan-provider.js +30 -23
  209. package/dist/providers/google-account-format.js +1 -0
  210. package/dist/providers/google-agy.d.ts +6 -5
  211. package/dist/providers/google-agy.js +43 -15
  212. package/dist/providers/google-gemini-cli.js +1 -0
  213. package/dist/providers/kilo.js +1 -0
  214. package/dist/providers/kimi-code.js +2 -0
  215. package/dist/providers/mimo.js +1 -0
  216. package/dist/providers/nanogpt.js +1 -0
  217. package/dist/providers/ollama-cloud.js +10 -0
  218. package/dist/providers/openai.js +24 -23
  219. package/dist/providers/opencode-go.js +10 -6
  220. package/dist/providers/opencode-zen.js +3 -1
  221. package/dist/providers/openrouter.js +1 -0
  222. package/dist/providers/quota-providers.js +16 -5
  223. package/dist/providers/registry.js +2 -0
  224. package/dist/providers/result-helpers.d.ts +6 -2
  225. package/dist/providers/result-helpers.js +7 -1
  226. package/dist/providers/synthetic.js +4 -0
  227. package/dist/providers/xai.js +9 -8
  228. package/dist/rpc.d.ts +129 -8
  229. package/dist/rpc.js +219 -14
  230. package/dist/ui/assets/{index-cDd9jUVY.css → index-6_g1FHs-.css} +1 -1
  231. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  232. package/dist/ui/assets/{popover-BGkgv9s0.js → popover-C4ZLYe9E.js} +1 -1
  233. package/dist/ui/assets/providers/claude-agent.svg +3 -0
  234. package/dist/ui/index.html +2 -2
  235. package/package.json +45 -46
  236. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
  237. package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
  238. package/dist/ui/assets/index-DLHeXYff.js +0 -9
@@ -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";
@@ -11,81 +12,104 @@ export async function queryGlmCodingPlanQuota(descriptor, options = {}) {
11
12
  if (auth.state === "invalid") {
12
13
  return { success: false, error: auth.error, failureCategory: "credentials" };
13
14
  }
14
- let responseStatus;
15
- try {
16
- return await fetchWithTimeout(descriptor.endpoint, {
17
- request: {
18
- headers: {
19
- Authorization: auth.apiKey,
20
- "User-Agent": "opencode-quota-gui/1.0",
21
- "Content-Type": "application/json",
15
+ return guard(JSON.stringify([descriptor.endpoint, auth.apiKey]), async () => {
16
+ let responseStatus;
17
+ try {
18
+ return await fetchWithTimeout(descriptor.endpoint, {
19
+ request: {
20
+ headers: {
21
+ Authorization: auth.apiKey,
22
+ "User-Agent": "opencode-quota-gui/1.0",
23
+ "Content-Type": "application/json",
24
+ },
22
25
  },
23
- },
24
- timeoutMs: options.requestTimeoutMs,
25
- consume: async (response) => {
26
- responseStatus = response.status;
27
- if (!response.ok) {
28
- const body = sanitizeDisplaySnippet(await response.text(), 120);
29
- return {
30
- success: false,
31
- error: `${descriptor.httpErrorPrefix} ${response.status}: ${body}`,
32
- failureCategory: providerFailureCategoryForHttpStatus(response.status),
33
- };
34
- }
35
- const body = (await response.json());
36
- if (descriptor.envelope === "zai" &&
37
- (body.success === false || (typeof body.code === "number" && body.code >= 400))) {
38
- const message = typeof body.msg === "string" ? sanitizeDisplayText(body.msg) : "";
39
- return {
40
- success: false,
41
- error: message ||
42
- (typeof body.code === "number"
43
- ? `${descriptor.apiErrorPrefix} ${body.code}`
44
- : descriptor.apiErrorPrefix),
45
- failureCategory: "provider_api",
46
- };
47
- }
48
- const limits = descriptor.envelope === "zai" ? (body.data?.limits ?? body.limits) : body.data?.limits;
49
- if (!Array.isArray(limits)) {
50
- return { success: false, error: "Invalid quota data", failureCategory: "provider_api" };
51
- }
52
- const windows = {};
53
- for (const limit of limits) {
54
- const resetDate = limit.nextResetTime ? new Date(Math.round(limit.nextResetTime)) : null;
55
- const resetTimeIso = resetDate && Number.isFinite(resetDate.valueOf()) && resetDate.valueOf() > 0
56
- ? resetDate.toISOString()
57
- : undefined;
58
- let percentRemaining = clampPercent(100 - limit.percentage);
59
- if (limit.type === "CREDIT_LIMIT" &&
60
- typeof limit.usage === "number" &&
61
- Number.isFinite(limit.usage) &&
62
- limit.usage > 0 &&
63
- typeof limit.currentValue === "number" &&
64
- Number.isFinite(limit.currentValue) &&
65
- limit.currentValue >= 0) {
66
- percentRemaining = clampPercent(((limit.usage - limit.currentValue) / limit.usage) * 100);
26
+ timeoutMs: options.requestTimeoutMs,
27
+ consume: async (response) => {
28
+ responseStatus = response.status;
29
+ if (!response.ok) {
30
+ const retryAtMs = retryAfterDeadline(response);
31
+ const body = sanitizeDisplaySnippet(await response.text().catch(() => ""), 120);
32
+ return {
33
+ success: false,
34
+ error: `${descriptor.httpErrorPrefix} ${response.status}: ${body}`,
35
+ failureCategory: providerFailureCategoryForHttpStatus(response.status),
36
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
37
+ };
67
38
  }
68
- const window = { percentRemaining, resetTimeIso };
69
- const isQuotaWindow = limit.type === "TOKENS_LIMIT" || limit.type === "CREDIT_LIMIT";
70
- if (isQuotaWindow && limit.unit === 3)
71
- windows.fiveHour = window;
72
- else if (isQuotaWindow && limit.unit === 6)
73
- windows.weekly = window;
74
- else if (limit.type === "TIME_LIMIT")
75
- windows.mcp = window;
76
- }
77
- return { success: true, label: descriptor.label, windows };
78
- },
79
- });
80
- }
81
- catch (error) {
82
- return {
83
- success: false,
84
- error: sanitizeDisplayText(error instanceof Error ? error.message : String(error)),
85
- failureCategory: responseStatus === undefined
86
- ? "provider_api"
87
- : providerFailureCategoryForHttpStatus(responseStatus),
88
- };
89
- }
39
+ const body = (await response.json());
40
+ if (descriptor.envelope === "zai" &&
41
+ (body.success === false || (typeof body.code === "number" && body.code >= 400))) {
42
+ const message = typeof body.msg === "string" ? sanitizeDisplayText(body.msg) : "";
43
+ return {
44
+ success: false,
45
+ error: message ||
46
+ (typeof body.code === "number"
47
+ ? `${descriptor.apiErrorPrefix} ${body.code}`
48
+ : descriptor.apiErrorPrefix),
49
+ failureCategory: "provider_api",
50
+ };
51
+ }
52
+ const limits = descriptor.envelope === "zai"
53
+ ? (body.data?.limits ?? body.limits)
54
+ : body.data?.limits;
55
+ if (!Array.isArray(limits)) {
56
+ return {
57
+ success: false,
58
+ error: "Invalid quota data",
59
+ failureCategory: "provider_api",
60
+ };
61
+ }
62
+ const windows = {};
63
+ for (const limit of limits) {
64
+ const resetDate = limit.nextResetTime
65
+ ? new Date(Math.round(limit.nextResetTime))
66
+ : null;
67
+ const resetTimeIso = resetDate && Number.isFinite(resetDate.valueOf()) && resetDate.valueOf() > 0
68
+ ? resetDate.toISOString()
69
+ : undefined;
70
+ let percentRemaining = clampPercent(100 - limit.percentage);
71
+ if (limit.type === "CREDIT_LIMIT" &&
72
+ typeof limit.usage === "number" &&
73
+ Number.isFinite(limit.usage) &&
74
+ limit.usage > 0 &&
75
+ typeof limit.currentValue === "number" &&
76
+ Number.isFinite(limit.currentValue) &&
77
+ limit.currentValue >= 0) {
78
+ percentRemaining = clampPercent(((limit.usage - limit.currentValue) / limit.usage) * 100);
79
+ }
80
+ const window = { percentRemaining, resetTimeIso };
81
+ const isQuotaWindow = limit.type === "TOKENS_LIMIT" || limit.type === "CREDIT_LIMIT";
82
+ if (isQuotaWindow && limit.unit === 3)
83
+ windows.fiveHour = window;
84
+ else if (isQuotaWindow && limit.unit === 6)
85
+ windows.weekly = window;
86
+ else if (limit.type === "TIME_LIMIT")
87
+ windows.mcp = window;
88
+ }
89
+ return { success: true, label: descriptor.label, windows };
90
+ },
91
+ });
92
+ }
93
+ catch (error) {
94
+ return {
95
+ success: false,
96
+ error: sanitizeDisplayText(error instanceof Error ? error.message : String(error)),
97
+ failureCategory: responseStatus === undefined
98
+ ? "provider_api"
99
+ : providerFailureCategoryForHttpStatus(responseStatus),
100
+ };
101
+ }
102
+ }, options.requestTimeoutMs, (retryAtMs) => ({
103
+ success: false,
104
+ error: `${descriptor.httpErrorPrefix} 429`,
105
+ failureCategory: "provider_api",
106
+ retryAtMs,
107
+ }));
90
108
  }
109
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
110
+ success: false,
111
+ error: "HTTP 429",
112
+ failureCategory: "provider_api",
113
+ retryAtMs,
114
+ }));
91
115
  //# sourceMappingURL=glm-coding-plan.js.map
@@ -1,9 +1,10 @@
1
1
  import crypto from "node:crypto";
2
2
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
3
3
  import { readGlobalProviderConfigString } from "./api-key-resolver.js";
4
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
4
5
  import { clearAgyCompanionCacheForTests, inspectAgyCompanionPresence, resolveAgyClientCredentials, } from "./google-agy-companion.js";
5
6
  import { getCachedAccessToken, makeAccountCacheKey, setCachedAccessToken, } from "./google-token-cache.js";
6
- import { fetchWithTimeout } from "./http.js";
7
+ import { fetchWithTimeout, RequestTimeoutError } from "./http.js";
7
8
  import { mapWithConcurrency } from "./map-with-concurrency.js";
8
9
  import { readAuthFileCached } from "./opencode-auth.js";
9
10
  import { composeResolvedAuthIdentities, deriveResolvedAuthIdentity, } from "./resolved-auth-identity.js";
@@ -188,6 +189,8 @@ async function refreshAccessToken(params) {
188
189
  timeoutMs: params.timeoutMs ?? AGY_TOKEN_TIMEOUT_MS,
189
190
  consume: async (response, timeoutSignal) => {
190
191
  if (!response.ok) {
192
+ const retryAtMs = retryAfterDeadline(response);
193
+ const retry = retryAtMs !== undefined ? { retryAtMs } : {};
191
194
  try {
192
195
  const errorData = (await response.json());
193
196
  if (errorData.error === "invalid_grant") {
@@ -196,6 +199,7 @@ async function refreshAccessToken(params) {
196
199
  return {
197
200
  error: errorData.error_description || `HTTP ${response.status}`,
198
201
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
202
+ ...retry,
199
203
  };
200
204
  }
201
205
  catch (error) {
@@ -204,6 +208,7 @@ async function refreshAccessToken(params) {
204
208
  return {
205
209
  error: `HTTP ${response.status}`,
206
210
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
211
+ ...retry,
207
212
  };
208
213
  }
209
214
  }
@@ -222,6 +227,13 @@ async function refreshAccessToken(params) {
222
227
  });
223
228
  }
224
229
  catch (err) {
230
+ if (err instanceof RequestTimeoutError) {
231
+ return {
232
+ error: "Token refresh timeout",
233
+ failureCategory: "provider_api",
234
+ ...(err.retryAtMs !== undefined ? { retryAtMs: err.retryAtMs } : {}),
235
+ };
236
+ }
225
237
  if (err instanceof Error && err.message.includes("timeout")) {
226
238
  return { error: "Token refresh timeout", failureCategory: "provider_api" };
227
239
  }
@@ -244,14 +256,26 @@ async function refreshAgyAccessTokenWithCache(params) {
244
256
  return { accessToken: params.account.accessToken };
245
257
  }
246
258
  }
247
- const refreshed = await refreshAccessToken({
248
- refreshToken: params.account.refreshToken,
249
- clientId: params.credentials.clientId,
250
- clientSecret: params.credentials.clientSecret,
251
- timeoutMs: params.timeoutMs,
252
- });
253
- if ("error" in refreshed)
254
- return refreshed;
259
+ // Guarded per refresh token: the token endpoint's limit is independent of quota reads.
260
+ const guarded = await tokenGuard(params.account.refreshToken, async () => {
261
+ const result = await refreshAccessToken({
262
+ refreshToken: params.account.refreshToken,
263
+ clientId: params.credentials.clientId,
264
+ clientSecret: params.credentials.clientSecret,
265
+ timeoutMs: params.timeoutMs,
266
+ });
267
+ return "error" in result
268
+ ? { success: false, ...result }
269
+ : { success: true, ...result };
270
+ }, params.timeoutMs);
271
+ if (!guarded.success) {
272
+ return {
273
+ error: guarded.error,
274
+ failureCategory: guarded.failureCategory,
275
+ ...(guarded.retryAtMs !== undefined ? { retryAtMs: guarded.retryAtMs } : {}),
276
+ };
277
+ }
278
+ const refreshed = { accessToken: guarded.accessToken, expiresIn: guarded.expiresIn };
255
279
  await setCachedAccessToken({
256
280
  key,
257
281
  entry: {
@@ -263,12 +287,27 @@ async function refreshAgyAccessTokenWithCache(params) {
263
287
  }
264
288
  class GoogleAgyQuotaRequestError extends Error {
265
289
  failureCategory;
266
- constructor(message, failureCategory) {
290
+ retryAtMs;
291
+ constructor(message, failureCategory, retryAtMs) {
267
292
  super(message);
268
293
  this.name = "GoogleAgyQuotaRequestError";
269
294
  this.failureCategory = failureCategory;
295
+ if (retryAtMs !== undefined)
296
+ this.retryAtMs = retryAtMs;
270
297
  }
271
298
  }
299
+ const tokenGuard = createApiKeyRetryGuard((retryAtMs) => ({
300
+ success: false,
301
+ error: "Token refresh failed: HTTP 429",
302
+ failureCategory: "provider_api",
303
+ retryAtMs,
304
+ }));
305
+ const accountGuard = createApiKeyRetryGuard((retryAtMs) => ({
306
+ success: false,
307
+ error: "Google AGY quota API error: 429",
308
+ failureCategory: "provider_api",
309
+ retryAtMs,
310
+ }));
272
311
  async function retrieveGoogleAgyQuotaSummary(accessToken, projectId, timeoutMs = AGY_QUOTA_TIMEOUT_MS) {
273
312
  return await fetchWithTimeout(AGY_QUOTA_SUMMARY_API_URL, {
274
313
  request: {
@@ -287,7 +326,7 @@ async function retrieveGoogleAgyQuotaSummary(accessToken, projectId, timeoutMs =
287
326
  const failureCategory = providerFailureCategoryForHttpStatus(response.status);
288
327
  throw new GoogleAgyQuotaRequestError(response.status === 401 || response.status === 403
289
328
  ? `Google AGY quota auth error: ${response.status}`
290
- : `Google AGY quota API error: ${response.status}`, failureCategory);
329
+ : `Google AGY quota API error: ${response.status}`, failureCategory, retryAfterDeadline(response));
291
330
  }
292
331
  return (await response.json());
293
332
  },
@@ -486,7 +525,36 @@ function mapSummaryBuckets(response, account, accountIndex) {
486
525
  }
487
526
  return Array.from(deduplicated.values()).sort(compareSummaryBuckets);
488
527
  }
528
+ /** Cooldowns are per refresh token + project; a concurrent identical call shares one request. */
489
529
  async function fetchAccountQuota(params) {
530
+ const accountEmail = params.account.email || params.account.sourceKey;
531
+ const { tokenRetryAtMs, ...result } = await accountGuard(`${params.account.refreshToken}\n${params.account.projectId}`, () => fetchAccountQuotaUncached(params), params.timeoutMs, (retryAtMs) => ({
532
+ success: false,
533
+ error: "Google AGY quota API error: 429",
534
+ failureCategory: "provider_api",
535
+ accountEmail,
536
+ retryAtMs,
537
+ }));
538
+ const buckets = result.buckets?.map((bucket) => {
539
+ const projected = {
540
+ ...bucket,
541
+ accountIndex: params.accountIndex,
542
+ sourceKey: params.account.sourceKey,
543
+ };
544
+ if (params.account.email)
545
+ projected.accountEmail = params.account.email;
546
+ else
547
+ delete projected.accountEmail;
548
+ return projected;
549
+ });
550
+ return {
551
+ ...result,
552
+ accountEmail,
553
+ ...(buckets ? { buckets } : {}),
554
+ ...(tokenRetryAtMs !== undefined ? { retryAtMs: tokenRetryAtMs } : {}),
555
+ };
556
+ }
557
+ async function fetchAccountQuotaUncached(params) {
490
558
  const accountEmail = params.account.email || params.account.sourceKey;
491
559
  try {
492
560
  const tokenResult = await refreshAgyAccessTokenWithCache({
@@ -500,6 +568,7 @@ async function fetchAccountQuota(params) {
500
568
  error: tokenResult.error,
501
569
  failureCategory: tokenResult.failureCategory,
502
570
  accountEmail,
571
+ ...(tokenResult.retryAtMs !== undefined ? { tokenRetryAtMs: tokenResult.retryAtMs } : {}),
503
572
  };
504
573
  }
505
574
  let summary;
@@ -520,6 +589,7 @@ async function fetchAccountQuota(params) {
520
589
  error: retryToken.error,
521
590
  failureCategory: retryToken.failureCategory,
522
591
  accountEmail,
592
+ ...(retryToken.retryAtMs !== undefined ? { tokenRetryAtMs: retryToken.retryAtMs } : {}),
523
593
  };
524
594
  }
525
595
  summary = await retrieveGoogleAgyQuotaSummary(retryToken.accessToken, params.account.projectId, params.timeoutMs);
@@ -546,6 +616,9 @@ async function fetchAccountQuota(params) {
546
616
  error: "API timeout",
547
617
  failureCategory: "provider_api",
548
618
  accountEmail,
619
+ ...(err instanceof RequestTimeoutError && err.retryAtMs !== undefined
620
+ ? { retryAtMs: err.retryAtMs }
621
+ : {}),
549
622
  };
550
623
  }
551
624
  return {
@@ -553,6 +626,9 @@ async function fetchAccountQuota(params) {
553
626
  error: err instanceof Error ? err.message : String(err),
554
627
  failureCategory: err instanceof GoogleAgyQuotaRequestError ? err.failureCategory : "provider_api",
555
628
  accountEmail,
629
+ ...(err instanceof GoogleAgyQuotaRequestError && err.retryAtMs !== undefined
630
+ ? { retryAtMs: err.retryAtMs }
631
+ : {}),
556
632
  };
557
633
  }
558
634
  }
@@ -585,17 +661,19 @@ export async function queryGoogleAgyQuota(options = {}) {
585
661
  }));
586
662
  const allBuckets = [];
587
663
  const errors = [];
588
- for (const result of results) {
664
+ for (const [accountIndex, result] of results.entries()) {
589
665
  if (result.success && result.buckets && result.buckets.length > 0) {
590
666
  allBuckets.push(...result.buckets);
591
667
  }
592
668
  else if (!result.success && result.error && result.accountEmail) {
593
669
  errors.push({
594
670
  email: result.accountEmail,
671
+ accountIndex,
595
672
  error: result.error,
596
673
  ...(result.failureCategory !== undefined
597
674
  ? { failureCategory: result.failureCategory }
598
675
  : {}),
676
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
599
677
  });
600
678
  }
601
679
  }
@@ -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
  }
@@ -58,7 +58,7 @@ function normalizeGroupedQuotaEntry(entry, target) {
58
58
  return {
59
59
  ...normalized,
60
60
  group: owned.name.trim(),
61
- ...(target === "quota" ? { label: label ?? "Status:" } : {}),
61
+ ...(target === "quota" && !owned.semantic ? { label: label ?? "Status:" } : {}),
62
62
  };
63
63
  }
64
64
  function sortLegacyEntries(entries) {
@@ -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
  }