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
@@ -67,7 +67,8 @@ const SNAPSHOT_KEYS = new Set([
67
67
  "jurisdictions",
68
68
  "providers",
69
69
  ]);
70
- const POLICY_KEYS = new Set(["status", "source", "overrides", "multipliers", "reason"]);
70
+ const POLICY_KEYS = new Set(["status", "source", "base", "overrides", "multipliers", "reason"]);
71
+ const BASE_RATE_KEYS = new Set(TEMPORAL_RATE_KEYS);
71
72
  const CALENDAR_KEYS = new Set(["timeZone", "source", "published", "intervals", "makeupWorkdays"]);
72
73
  const INTERVAL_KEYS = new Set(["id", "localStart", "localEnd", "startMs", "endMs"]);
73
74
  const OVERRIDE_KEYS = new Set(["id", "field", "when", "rates"]);
@@ -282,6 +283,18 @@ function parseRates(raw, field, path) {
282
283
  fail(`${path} must set at least one rate`);
283
284
  return rates;
284
285
  }
286
+ function parseBaseRates(raw, path) {
287
+ const object = asObject(raw, path);
288
+ assertKeys(object, BASE_RATE_KEYS, path);
289
+ const rates = {};
290
+ for (const key of TEMPORAL_RATE_KEYS) {
291
+ if (hasOwn(object, key))
292
+ rates[key] = asRate(object[key], `${path}.${key}`);
293
+ }
294
+ if (Object.keys(rates).length === 0)
295
+ fail(`${path} must set at least one rate`);
296
+ return rates;
297
+ }
285
298
  function parseMultiplierFactor(raw, path) {
286
299
  if (typeof raw === "number") {
287
300
  return asRate(raw, path);
@@ -310,6 +323,7 @@ function parsePolicyEntry(raw, providerId, modelId, path) {
310
323
  }
311
324
  if (status !== "supported")
312
325
  fail(`${path}.status is not supported`);
326
+ const base = hasOwn(object, "base") ? parseBaseRates(object.base, `${path}.base`) : undefined;
313
327
  const rawOverrides = asArray(object.overrides, `${path}.overrides`);
314
328
  const rawMultipliers = asArray(object.multipliers, `${path}.multipliers`);
315
329
  if (rawOverrides.length === 0 && rawMultipliers.length === 0) {
@@ -348,7 +362,7 @@ function parsePolicyEntry(raw, providerId, modelId, path) {
348
362
  factor: parseMultiplierFactor(multiplier.factor, `${multiplierPath}.factor`),
349
363
  };
350
364
  });
351
- return { status: "supported", source, overrides, multipliers };
365
+ return { status: "supported", source, ...(base ? { base } : {}), overrides, multipliers };
352
366
  }
353
367
  function parseHolidayCalendar(raw, path) {
354
368
  const object = asObject(raw, path);
@@ -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";
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
9
9
  import { isCanonicalAccountingDecimal } from "./accounting-format.js";
10
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
10
11
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
11
12
  import { clampPercent } from "./format-utils.js";
12
13
  import { fetchWithTimeout } from "./http.js";
@@ -14,6 +15,16 @@ import { resolveNanoGptApiKey } from "./nanogpt-config.js";
14
15
  const USER_AGENT = "opencode-quota-gui/1.0";
15
16
  const NANOGPT_USAGE_URL = "https://nano-gpt.com/api/subscription/v1/usage";
16
17
  const NANOGPT_BALANCE_URL = "https://nano-gpt.com/api/check-balance";
18
+ // Per-endpoint cooldown: a limited endpoint must not block the healthy one.
19
+ const blockedEndpoint = (retryAtMs) => ({
20
+ success: false,
21
+ message: "NanoGPT API error 429",
22
+ retryable: true,
23
+ failureCategory: "provider_api",
24
+ retryAtMs,
25
+ });
26
+ const usageGuard = createApiKeyRetryGuard(blockedEndpoint);
27
+ const balanceGuard = createApiKeyRetryGuard(blockedEndpoint);
17
28
  function isRetryableHttpStatus(status) {
18
29
  return status === 408 || status === 425 || status === 429 || status >= 500;
19
30
  }
@@ -144,6 +155,7 @@ async function fetchNanoGptUsage(headers, requestTimeoutMs) {
144
155
  timeoutMs: requestTimeoutMs,
145
156
  consume: async (response) => {
146
157
  if (!response.ok) {
158
+ const retryAtMs = retryAfterDeadline(response);
147
159
  let text;
148
160
  try {
149
161
  text = await response.text();
@@ -156,6 +168,7 @@ async function fetchNanoGptUsage(headers, requestTimeoutMs) {
156
168
  message: `NanoGPT API error ${response.status}: ${sanitizeDisplaySnippet(text, 120)}`,
157
169
  retryable: isRetryableHttpStatus(response.status),
158
170
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
171
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
159
172
  };
160
173
  }
161
174
  return {
@@ -184,6 +197,7 @@ async function fetchNanoGptBalance(headers, requestTimeoutMs) {
184
197
  timeoutMs: requestTimeoutMs,
185
198
  consume: async (response) => {
186
199
  if (!response.ok) {
200
+ const retryAtMs = retryAfterDeadline(response);
187
201
  let text;
188
202
  try {
189
203
  text = await response.text();
@@ -196,6 +210,7 @@ async function fetchNanoGptBalance(headers, requestTimeoutMs) {
196
210
  message: `NanoGPT API error ${response.status}: ${sanitizeDisplaySnippet(text, 120)}`,
197
211
  retryable: isRetryableHttpStatus(response.status),
198
212
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
213
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
199
214
  };
200
215
  }
201
216
  return {
@@ -219,13 +234,14 @@ export async function queryNanoGptQuota(options = {}) {
219
234
  const resolved = await resolveNanoGptApiKey();
220
235
  if (!resolved)
221
236
  return null;
237
+ const key = resolved.key;
222
238
  const headers = {
223
- "x-api-key": resolved.key,
239
+ "x-api-key": key,
224
240
  "User-Agent": USER_AGENT,
225
241
  };
226
242
  const [usageResult, balanceResult] = await Promise.all([
227
- fetchNanoGptUsage(headers, options.requestTimeoutMs),
228
- fetchNanoGptBalance(headers, options.requestTimeoutMs),
243
+ usageGuard(key, () => fetchNanoGptUsage(headers, options.requestTimeoutMs), options.requestTimeoutMs),
244
+ balanceGuard(key, () => fetchNanoGptBalance(headers, options.requestTimeoutMs), options.requestTimeoutMs),
229
245
  ]);
230
246
  const endpointErrors = [];
231
247
  if (!usageResult.success) {
@@ -233,6 +249,7 @@ export async function queryNanoGptQuota(options = {}) {
233
249
  endpoint: "usage",
234
250
  message: usageResult.message,
235
251
  failureCategory: usageResult.failureCategory,
252
+ ...(usageResult.retryAtMs !== undefined ? { retryAtMs: usageResult.retryAtMs } : {}),
236
253
  });
237
254
  }
238
255
  if (!balanceResult.success) {
@@ -240,6 +257,7 @@ export async function queryNanoGptQuota(options = {}) {
240
257
  endpoint: "balance",
241
258
  message: balanceResult.message,
242
259
  failureCategory: balanceResult.failureCategory,
260
+ ...(balanceResult.retryAtMs !== undefined ? { retryAtMs: balanceResult.retryAtMs } : {}),
243
261
  });
244
262
  }
245
263
  else if (balanceResult.fieldErrors.length > 0) {
@@ -250,7 +268,12 @@ export async function queryNanoGptQuota(options = {}) {
250
268
  });
251
269
  }
252
270
  if (!usageResult.success && !balanceResult.success) {
271
+ // A whole-query deadline exists only when both endpoints reported one.
272
+ const retryAtMs = usageResult.retryAtMs !== undefined && balanceResult.retryAtMs !== undefined
273
+ ? Math.max(usageResult.retryAtMs, balanceResult.retryAtMs)
274
+ : undefined;
253
275
  return {
276
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
254
277
  success: false,
255
278
  error: endpointErrors
256
279
  .map((entry) => `${entry.endpoint === "usage" ? "Usage" : "Balance"}: ${entry.message}`)
@@ -6,7 +6,7 @@
6
6
  * endpoint.
7
7
  */
8
8
  import type { OllamaCloudResult } from "./types.js";
9
- declare function parseOllamaCloudBalance(payload: unknown): OllamaCloudResult;
9
+ declare function parseOllamaCloudBalance(payload: unknown): Exclude<OllamaCloudResult, null>;
10
10
  export declare function queryOllamaCloudQuota(options?: {
11
11
  requestTimeoutMs?: number;
12
12
  }): Promise<OllamaCloudResult>;
@@ -6,11 +6,18 @@
6
6
  * endpoint.
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 { resolveOllamaCloudApiKey } from "./ollama-cloud-config.js";
12
13
  const OLLAMA_CLOUD_BALANCE_URL = "https://ollama.com/api/balance";
13
14
  const MAX_RESPONSE_BYTES = 256 * 1024;
15
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
16
+ success: false,
17
+ error: "Ollama Cloud balance API error 429",
18
+ failureCategory: "provider_api",
19
+ retryAtMs,
20
+ }));
14
21
  function isRecord(value) {
15
22
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
16
23
  }
@@ -154,42 +161,48 @@ export async function queryOllamaCloudQuota(options = {}) {
154
161
  const resolved = await resolveOllamaCloudApiKey();
155
162
  if (!resolved)
156
163
  return null;
157
- let responseStatus;
158
- try {
159
- return await fetchWithTimeout(OLLAMA_CLOUD_BALANCE_URL, {
160
- request: {
161
- method: "GET",
162
- headers: {
163
- Accept: "application/json",
164
- Authorization: `Bearer ${resolved.key}`,
164
+ return guard(resolved.key, async () => {
165
+ let responseStatus;
166
+ let retryAtMs;
167
+ try {
168
+ return await fetchWithTimeout(OLLAMA_CLOUD_BALANCE_URL, {
169
+ request: {
170
+ method: "GET",
171
+ headers: {
172
+ Accept: "application/json",
173
+ Authorization: `Bearer ${resolved.key}`,
174
+ },
175
+ redirect: "manual",
165
176
  },
166
- redirect: "manual",
167
- },
168
- timeoutMs: options.requestTimeoutMs,
169
- consume: async (response) => {
170
- responseStatus = response.status;
171
- const text = await readBoundedText(response, MAX_RESPONSE_BYTES);
172
- if (!response.ok) {
173
- const snippet = sanitizeMessage(text, resolved.key);
174
- return {
175
- success: false,
176
- error: `Ollama Cloud balance API error ${response.status}: ${snippet}`,
177
- failureCategory: providerFailureCategoryForHttpStatus(response.status),
178
- };
179
- }
180
- return parseOllamaCloudBalance(JSON.parse(text));
181
- },
182
- });
183
- }
184
- catch (error) {
185
- return {
186
- success: false,
187
- error: sanitizeMessage(error instanceof Error ? error.message : String(error), resolved.key),
188
- failureCategory: responseStatus === undefined
189
- ? "provider_api"
190
- : providerFailureCategoryForHttpStatus(responseStatus),
191
- };
192
- }
177
+ timeoutMs: options.requestTimeoutMs,
178
+ consume: async (response) => {
179
+ responseStatus = response.status;
180
+ retryAtMs = retryAfterDeadline(response);
181
+ const text = await readBoundedText(response, MAX_RESPONSE_BYTES);
182
+ if (!response.ok) {
183
+ const snippet = sanitizeMessage(text, resolved.key);
184
+ return {
185
+ success: false,
186
+ error: `Ollama Cloud balance API error ${response.status}: ${snippet}`,
187
+ failureCategory: providerFailureCategoryForHttpStatus(response.status),
188
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
189
+ };
190
+ }
191
+ return parseOllamaCloudBalance(JSON.parse(text));
192
+ },
193
+ });
194
+ }
195
+ catch (error) {
196
+ return {
197
+ success: false,
198
+ error: sanitizeMessage(error instanceof Error ? error.message : String(error), resolved.key),
199
+ failureCategory: responseStatus === undefined
200
+ ? "provider_api"
201
+ : providerFailureCategoryForHttpStatus(responseStatus),
202
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
203
+ };
204
+ }
205
+ }, options.requestTimeoutMs);
193
206
  }
194
207
  export { parseOllamaCloudBalance as _parseOllamaCloudBalance };
195
208
  //# sourceMappingURL=ollama-cloud.js.map
@@ -5,10 +5,12 @@
5
5
  * https://chatgpt.com/backend-api/wham/usage
6
6
  */
7
7
  import { providerFailureCategoryForHttpStatus } from "../contracts/provider-failure.js";
8
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
8
9
  import { sanitizeDisplayText, sanitizeSingleLineDisplayText } from "./display-sanitize.js";
9
10
  import { clampPercent } from "./format-utils.js";
10
- import { fetchWithTimeout } from "./http.js";
11
+ import { fetchWithTimeout, RequestTimeoutError } from "./http.js";
11
12
  import { readAuthFileCached } from "./opencode-auth.js";
13
+ import { buildFixedWindowEvidence } from "./quota-exhaustion-projection.js";
12
14
  import { deriveResolvedAuthIdentity } from "./resolved-auth-identity.js";
13
15
  function base64UrlDecode(input) {
14
16
  const base64 = input.replace(/-/g, "+").replace(/_/g, "/");
@@ -95,17 +97,13 @@ function parseRateLimitWindow(window, observedAtMs) {
95
97
  const value = parseWindowValue(window, observedAtMs);
96
98
  if (!value)
97
99
  return null;
98
- const endsAtMs = value.resetTimeIso ? Date.parse(value.resetTimeIso) : Number.NaN;
99
- const startedAtMs = endsAtMs - raw.limit_window_seconds * 1000;
100
- if (Number.isFinite(startedAtMs) && startedAtMs < observedAtMs && observedAtMs < endsAtMs) {
101
- value.fixedWindow = {
102
- kind: "fixed_window",
103
- startedAtIso: new Date(startedAtMs).toISOString(),
104
- observedAtIso: new Date(observedAtMs).toISOString(),
105
- endsAtIso: new Date(endsAtMs).toISOString(),
106
- fullReset: true,
107
- };
108
- }
100
+ const fixedWindow = buildFixedWindowEvidence({
101
+ durationMs: raw.limit_window_seconds * 1000,
102
+ resetTimeIso: value.resetTimeIso,
103
+ observedAtMs,
104
+ });
105
+ if (fixedWindow)
106
+ value.fixedWindow = fixedWindow;
109
107
  return { kind, value };
110
108
  }
111
109
  function derivePlanLabel(planType) {
@@ -121,6 +119,12 @@ function derivePlanLabel(planType) {
121
119
  return "OpenAI";
122
120
  }
123
121
  const OPENAI_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
122
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
123
+ success: false,
124
+ error: "OpenAI API error 429",
125
+ failureCategory: "provider_api",
126
+ retryAtMs,
127
+ }));
124
128
  const OPENAI_RESET_CREDITS_URL = "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
125
129
  export const DEFAULT_OPENAI_AUTH_CACHE_MAX_AGE_MS = 5_000;
126
130
  // Not `opencode`: in OpenCode 2 its OAuth entry is the Console login, which
@@ -257,27 +261,47 @@ function parseAvailableResetCredits(payload) {
257
261
  : Date.parse(credit.expiresAtIso);
258
262
  return credits.sort((left, right) => rank(left) - rank(right));
259
263
  }
260
- /** Detail failures degrade to no known expiry metadata; ordinary data stays. */
261
- async function fetchOpenAIResetCredits(headers, timeoutMs) {
262
- try {
263
- return await fetchWithTimeout(OPENAI_RESET_CREDITS_URL, {
264
- request: { headers },
265
- timeoutMs,
266
- consume: async (resp) => {
267
- if (!resp.ok)
268
- return [];
269
- try {
270
- return parseAvailableResetCredits(await resp.json());
271
- }
272
- catch {
273
- return [];
274
- }
275
- },
276
- });
277
- }
278
- catch {
279
- return [];
280
- }
264
+ // Separate from the usage guard: a limited detail endpoint must not block usage.
265
+ const resetCreditsGuard = createApiKeyRetryGuard((retryAtMs) => ({
266
+ success: false,
267
+ credits: [],
268
+ retryAtMs,
269
+ }));
270
+ async function fetchOpenAIResetCredits(headers, timeoutMs, cooldownKey) {
271
+ const result = await resetCreditsGuard(cooldownKey, async () => {
272
+ try {
273
+ return await fetchWithTimeout(OPENAI_RESET_CREDITS_URL, {
274
+ request: { headers },
275
+ timeoutMs,
276
+ consume: async (resp) => {
277
+ if (!resp.ok) {
278
+ const retryAtMs = retryAfterDeadline(resp);
279
+ return {
280
+ success: false,
281
+ credits: [],
282
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
283
+ };
284
+ }
285
+ try {
286
+ return { success: true, credits: parseAvailableResetCredits(await resp.json()) };
287
+ }
288
+ catch {
289
+ return { success: false, credits: [] };
290
+ }
291
+ },
292
+ });
293
+ }
294
+ catch (error) {
295
+ return {
296
+ success: false,
297
+ credits: [],
298
+ ...(error instanceof RequestTimeoutError && error.retryAtMs !== undefined
299
+ ? { retryAtMs: error.retryAtMs }
300
+ : {}),
301
+ };
302
+ }
303
+ }, timeoutMs);
304
+ return result.credits;
281
305
  }
282
306
  export async function queryOpenAIQuota(options = {}) {
283
307
  const resolvedAuth = options.auth ??
@@ -313,16 +337,24 @@ export async function queryOpenAIQuota(options = {}) {
313
337
  if (accountId) {
314
338
  headers["ChatGPT-Account-Id"] = accountId;
315
339
  }
316
- const result = await fetchWithTimeout(OPENAI_USAGE_URL, {
340
+ // The ChatGPT account id names a workspace shared by its members, so it
341
+ // cannot identify a credential (and an email claim does not prove identity
342
+ // either). Key on the credential itself: the refresh token survives access
343
+ // token rotation, the access token is the fallback when there is none. The
344
+ // guard hashes the key and never retains it.
345
+ const cooldownKey = `${accountId ?? ""}\0${resolvedAuth.refreshToken ?? resolvedAuth.accessToken}`;
346
+ const result = await guard(cooldownKey, () => fetchWithTimeout(OPENAI_USAGE_URL, {
317
347
  request: { headers },
318
348
  timeoutMs: options.requestTimeoutMs,
319
349
  consume: async (resp) => {
320
350
  if (!resp.ok) {
351
+ const retryAtMs = retryAfterDeadline(resp);
321
352
  const code = await readOpenAIErrorCode(resp);
322
353
  return {
323
354
  success: false,
324
355
  error: `OpenAI API error ${resp.status}${code ? ` (${code})` : ""}`,
325
356
  failureCategory: providerFailureCategoryForHttpStatus(resp.status),
357
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
326
358
  };
327
359
  }
328
360
  const data = (await resp.json());
@@ -366,7 +398,9 @@ export async function queryOpenAIQuota(options = {}) {
366
398
  Number(mappedCredits.balance) > 0));
367
399
  // Empty bodies stay invalid; a useful Credits-only/reset-count-only
368
400
  // payload is a real measurement even without a percent window.
369
- if (Object.keys(windows).length === 0 && !positiveCredits && availableResetCount === null) {
401
+ if (Object.keys(windows).length === 0 &&
402
+ !positiveCredits &&
403
+ availableResetCount === null) {
370
404
  return { success: false, error: "No quota data", failureCategory: "provider_api" };
371
405
  }
372
406
  return {
@@ -380,11 +414,20 @@ export async function queryOpenAIQuota(options = {}) {
380
414
  : {}),
381
415
  };
382
416
  },
383
- });
384
- if (!result || !result.success || !result.bankedResets || !options.includeResetDetails) {
417
+ }).catch((err) => {
418
+ if (!(err instanceof RequestTimeoutError) || err.retryAtMs === undefined)
419
+ throw err;
420
+ return {
421
+ success: false,
422
+ error: sanitizeDisplayText(err.message),
423
+ failureCategory: "provider_api",
424
+ retryAtMs: err.retryAtMs,
425
+ };
426
+ }), options.requestTimeoutMs);
427
+ if (!result.success || !result.bankedResets || !options.includeResetDetails) {
385
428
  return result;
386
429
  }
387
- result.bankedResets.credits = await fetchOpenAIResetCredits(headers, options.requestTimeoutMs);
430
+ result.bankedResets.credits = await fetchOpenAIResetCredits(headers, options.requestTimeoutMs, `reset-credits:${cooldownKey}`);
388
431
  return result;
389
432
  }
390
433
  catch (err) {
@@ -392,6 +435,9 @@ export async function queryOpenAIQuota(options = {}) {
392
435
  success: false,
393
436
  error: sanitizeDisplayText(err instanceof Error ? err.message : String(err)),
394
437
  failureCategory: "provider_api",
438
+ ...(err instanceof RequestTimeoutError && err.retryAtMs !== undefined
439
+ ? { retryAtMs: err.retryAtMs }
440
+ : {}),
395
441
  };
396
442
  }
397
443
  }
@@ -4,8 +4,8 @@
4
4
  * `opencode-quota-gui show` and `status` bind this source while one report runs, so they work
5
5
  * with OpenCode closed. It is the only code that queries OpenCode's `credential` table. It
6
6
  * never refreshes or writes a login: a sign-in whose token expired stays expired here until
7
- * OpenCode refreshes it. The server plugin and the TUI must never import this file
8
- * (`tests/tui-dist-import-graph.test.ts`).
7
+ * OpenCode refreshes it. The server plugin must never import this file
8
+ * (`tests/plugin-dist-import-graph.test.ts`).
9
9
  */
10
10
  import { type CredentialSource } from "./opencode-auth.js";
11
11
  /**
@@ -4,8 +4,8 @@
4
4
  * `opencode-quota-gui show` and `status` bind this source while one report runs, so they work
5
5
  * with OpenCode closed. It is the only code that queries OpenCode's `credential` table. It
6
6
  * never refreshes or writes a login: a sign-in whose token expired stays expired here until
7
- * OpenCode refreshes it. The server plugin and the TUI must never import this file
8
- * (`tests/tui-dist-import-graph.test.ts`).
7
+ * OpenCode refreshes it. The server plugin must never import this file
8
+ * (`tests/plugin-dist-import-graph.test.ts`).
9
9
  */
10
10
  import { existsSync } from "fs";
11
11
  import { getCredentialDatabasePaths, } from "./opencode-auth.js";
@@ -58,5 +58,6 @@ export declare function applyConfigDocumentEdit(edit: ConfigDocumentEdit, option
58
58
  pathExists?: (path: string) => boolean;
59
59
  writeText?: (path: string, content: string) => Promise<void>;
60
60
  removePath?: (path: string) => Promise<void>;
61
+ beforeRename?: () => Promise<void>;
61
62
  }): Promise<void>;
62
63
  //# sourceMappingURL=opencode-config-editor.d.ts.map
@@ -352,15 +352,20 @@ export async function applyConfigDocumentEdit(edit, options = {}) {
352
352
  return;
353
353
  }
354
354
  await validateConfigDocumentEdit(edit, options);
355
+ const validateBeforeRename = async () => {
356
+ await options.beforeRename?.();
357
+ await validateConfigDocumentEdit(edit, options);
358
+ };
355
359
  const removePath = options.removePath ?? ((path) => rm(path));
356
360
  try {
357
361
  const currentTarget = await resolveConfigWriteTarget(edit.path);
358
362
  assertSameConfigWriteTarget(edit.writeTarget, currentTarget);
359
363
  if (options.writeText) {
364
+ await validateBeforeRename();
360
365
  await options.writeText(currentTarget.writePath, edit.updated);
361
366
  }
362
367
  else {
363
- await writeResolvedConfigText(currentTarget, edit.updated);
368
+ await writeResolvedConfigText(currentTarget, edit.updated, validateBeforeRename);
364
369
  }
365
370
  }
366
371
  catch (error) {
@@ -3,7 +3,7 @@ import { dedupeNonEmptyStrings, extractPluginSpecsFromParsedConfig, extractProvi
3
3
  import { applyConfigDocumentEdit, ConfigDocumentError, parseConfigDocument, planConfigDocumentEdit, } from "./opencode-config-editor.js";
4
4
  import { buildOpenCodeConfigCandidates, readOpenCodeConfigCandidate, selectFirstExistingOpenCodeConfigCandidate, } from "./opencode-config-read.js";
5
5
  import { getOpencodeRuntimeDirs } from "./opencode-runtime-paths.js";
6
- import { getQuotaProviderRuntimeIds, getQuotaProviderShape, normalizeQuotaProviderId, } from "./provider-metadata.js";
6
+ import { getQuotaProviderRegistration, getQuotaProviderRuntimeIds, normalizeQuotaProviderId, } from "./provider-metadata.js";
7
7
  function isRecord(value) {
8
8
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
9
9
  }
@@ -88,7 +88,7 @@ export async function reconcileDetectedProvidersInGlobalConfig(options) {
88
88
  const detectedProviderIds = dedupeNonEmptyStrings(options.detectedProviderIds
89
89
  .map((providerId) => normalizeQuotaProviderId(providerId))
90
90
  .filter((providerId) => {
91
- const shape = getQuotaProviderShape(providerId);
91
+ const shape = getQuotaProviderRegistration(providerId);
92
92
  return Boolean(shape && shape.id !== "quota-providers");
93
93
  }));
94
94
  const globalConfigDir = getOpencodeRuntimeDirs().configDir;
@@ -1,3 +1,4 @@
1
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
1
2
  import { sanitizeDisplayText } from "./display-sanitize.js";
2
3
  import { fetchWithTimeout } from "./http.js";
3
4
  import { consoleBaseUrl, consoleHeaders, } from "./opencode-console-auth.js";
@@ -118,7 +119,19 @@ function isNotSubscribedResponse(status, text) {
118
119
  return false;
119
120
  }
120
121
  }
121
- export async function queryOpenCodeGoQuota(accessToken, options = {}) {
122
+ const rateLimited = (retryAtMs) => ({
123
+ success: false,
124
+ error: "OpenCode Go API error 429",
125
+ retryable: true,
126
+ failureCategory: "provider_api",
127
+ retryAtMs,
128
+ });
129
+ const apiKeyGuard = createApiKeyRetryGuard(rateLimited);
130
+ const consoleGuard = createApiKeyRetryGuard(rateLimited);
131
+ export function queryOpenCodeGoQuota(accessToken, options = {}) {
132
+ return apiKeyGuard(accessToken, () => fetchOpenCodeGoQuota(accessToken, options), options.requestTimeoutMs);
133
+ }
134
+ async function fetchOpenCodeGoQuota(accessToken, options) {
122
135
  try {
123
136
  return await fetchWithTimeout(OPENCODE_GO_USAGE_URL, {
124
137
  request: {
@@ -131,6 +144,7 @@ export async function queryOpenCodeGoQuota(accessToken, options = {}) {
131
144
  timeoutMs: options.requestTimeoutMs,
132
145
  consume: async (response) => {
133
146
  if (!response.ok) {
147
+ const retryAtMs = retryAfterDeadline(response);
134
148
  let text;
135
149
  try {
136
150
  text = await response.text();
@@ -141,6 +155,7 @@ export async function queryOpenCodeGoQuota(accessToken, options = {}) {
141
155
  error: `OpenCode Go API error ${response.status}: ${errorMessage(error, accessToken)}`,
142
156
  retryable: isRetryableHttpStatus(response.status),
143
157
  failureCategory: httpFailureCategory(response.status),
158
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
144
159
  };
145
160
  }
146
161
  if (isNotSubscribedResponse(response.status, text)) {
@@ -156,6 +171,7 @@ export async function queryOpenCodeGoQuota(accessToken, options = {}) {
156
171
  error: `OpenCode Go API error ${response.status}: ${sanitizeMessage(text, accessToken)}`,
157
172
  retryable: isRetryableHttpStatus(response.status),
158
173
  failureCategory: httpFailureCategory(response.status),
174
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
159
175
  };
160
176
  }
161
177
  let payload;
@@ -219,7 +235,16 @@ function normalizeConsoleMeter(windowKey, meter) {
219
235
  * accounts without any pre-2.0 workspace API key. The request goes to the
220
236
  * login's Console server, scoped to the login's org when it has one.
221
237
  */
222
- export async function queryOpenCodeGoConsoleStatus(credential, options = {}) {
238
+ export function queryOpenCodeGoConsoleStatus(credential, options = {}) {
239
+ // Same token under another org or server is a different account.
240
+ const identity = JSON.stringify([
241
+ credential.accessToken,
242
+ credential.orgId ?? null,
243
+ consoleBaseUrl(credential),
244
+ ]);
245
+ return consoleGuard(identity, () => fetchOpenCodeGoConsoleStatus(credential, options), options.requestTimeoutMs);
246
+ }
247
+ async function fetchOpenCodeGoConsoleStatus(credential, options) {
223
248
  try {
224
249
  return await fetchWithTimeout(`${consoleBaseUrl(credential)}/api/go/status`, {
225
250
  request: {
@@ -240,11 +265,13 @@ export async function queryOpenCodeGoConsoleStatus(credential, options = {}) {
240
265
  notSubscribed: true,
241
266
  };
242
267
  }
268
+ const retryAtMs = retryAfterDeadline(response);
243
269
  return {
244
270
  success: false,
245
271
  error: `OpenCode Console API error ${response.status} (/api/go/status)`,
246
272
  retryable: isRetryableHttpStatus(response.status),
247
273
  failureCategory: httpFailureCategory(response.status),
274
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
248
275
  };
249
276
  }
250
277
  let payload;