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
@@ -7,8 +7,9 @@
7
7
  */
8
8
  import { existsSync, readFileSync } from "fs";
9
9
  import { join } from "path";
10
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
10
11
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
11
- import { fetchWithTimeout } from "./http.js";
12
+ import { fetchWithTimeout, RequestTimeoutError } from "./http.js";
12
13
  import { readAuthFile } from "./opencode-auth.js";
13
14
  import { getOpencodeRuntimeDirs } from "./opencode-runtime-paths.js";
14
15
  import { deriveResolvedAuthIdentity } from "./resolved-auth-identity.js";
@@ -465,15 +466,30 @@ function redactGitHubErrorText(text, secrets) {
465
466
  }
466
467
  class CopilotRequestError extends Error {
467
468
  failureCategory;
468
- constructor(message, failureCategory) {
469
+ retryAtMs;
470
+ constructor(message, failureCategory, retryAtMs) {
469
471
  super(message);
470
472
  this.failureCategory = failureCategory;
473
+ this.retryAtMs = retryAtMs;
471
474
  this.name = "CopilotRequestError";
472
475
  }
473
476
  }
474
477
  function requestFailureCategory(error) {
475
478
  return error instanceof CopilotRequestError ? error.failureCategory : "provider_api";
476
479
  }
480
+ function requestRetryAtMs(error) {
481
+ if (error instanceof CopilotRequestError)
482
+ return error.retryAtMs;
483
+ return error instanceof RequestTimeoutError ? error.retryAtMs : undefined;
484
+ }
485
+ function preserveRetryAtOnTimeout(error, retryAtMs) {
486
+ return error instanceof RequestTimeoutError &&
487
+ error.retryAtMs === undefined &&
488
+ retryAtMs !== undefined
489
+ ? new RequestTimeoutError(error.message, retryAtMs)
490
+ : error;
491
+ }
492
+ const guard = createApiKeyRetryGuard((retryAtMs) => toQuotaError("GitHub API error 429", "provider_api", retryAtMs));
477
493
  async function readGitHubRestErrorMessage(response, secrets) {
478
494
  const text = await response.text();
479
495
  try {
@@ -503,27 +519,53 @@ async function readGitHubRestErrorMessageForClassification(response, secrets) {
503
519
  return "response body could not be read";
504
520
  }
505
521
  }
522
+ /**
523
+ * A 429, or a 403 GitHub itself marks as a rate limit (exhausted primary limit
524
+ * or the documented secondary-limit message). Only then is Retry-After read,
525
+ * so a permission 403 never gets a cooldown.
526
+ */
527
+ function classifyGitHubRateLimit(response, message) {
528
+ const limited = response.status === 429 ||
529
+ (response.status === 403 &&
530
+ (response.headers.get("x-ratelimit-remaining") === "0" ||
531
+ /secondary rate limit/iu.test(message)));
532
+ if (!limited)
533
+ return { limited };
534
+ // retryAfterDeadline only accepts 429; re-present the same headers as one.
535
+ const retryAtMs = retryAfterDeadline(new Response(null, { status: 429, headers: response.headers }));
536
+ return { limited, ...(retryAtMs !== undefined ? { retryAtMs } : {}) };
537
+ }
506
538
  async function fetchGitHubRestJson(url, token, requestTimeoutMs) {
507
- return await fetchWithTimeout(url, {
508
- request: { headers: buildGitHubRestHeaders(token) },
509
- timeoutMs: requestTimeoutMs,
510
- consume: async (response) => {
511
- if (!response.ok) {
512
- const message = await readGitHubRestErrorMessageForClassification(response, [token]);
513
- const rateLimited = response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0";
514
- const rateLimit = rateLimited ? " (GitHub API rate limit exhausted)" : "";
515
- throw new CopilotRequestError(`GitHub API error ${response.status}: ${message}${rateLimit}`, response.status === 401 || (response.status === 403 && !rateLimited)
516
- ? "credentials"
517
- : "provider_api");
518
- }
519
- try {
520
- return (await response.json());
521
- }
522
- catch {
523
- throw new CopilotRequestError("GitHub API returned malformed JSON", "provider_api");
524
- }
525
- },
526
- });
539
+ let observedRetryAtMs;
540
+ try {
541
+ return await fetchWithTimeout(url, {
542
+ request: { headers: buildGitHubRestHeaders(token) },
543
+ timeoutMs: requestTimeoutMs,
544
+ consume: async (response) => {
545
+ if (!response.ok) {
546
+ if (response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
547
+ // Snapshot a confirmed primary limit before its body can stall.
548
+ observedRetryAtMs = classifyGitHubRateLimit(response, "").retryAtMs;
549
+ }
550
+ const message = await readGitHubRestErrorMessageForClassification(response, [token]);
551
+ const limit = classifyGitHubRateLimit(response, message);
552
+ const rateLimit = response.status === 403 && limit.limited ? " (GitHub API rate limit exhausted)" : "";
553
+ throw new CopilotRequestError(`GitHub API error ${response.status}: ${message}${rateLimit}`, response.status === 401 || (response.status === 403 && !limit.limited)
554
+ ? "credentials"
555
+ : "provider_api", limit.retryAtMs);
556
+ }
557
+ try {
558
+ return (await response.json());
559
+ }
560
+ catch {
561
+ throw new CopilotRequestError("GitHub API returned malformed JSON", "provider_api");
562
+ }
563
+ },
564
+ });
565
+ }
566
+ catch (error) {
567
+ throw preserveRetryAtOnTimeout(error, observedRetryAtMs);
568
+ }
527
569
  }
528
570
  async function resolveGitHubUsername(apiBaseUrl, token, requestTimeoutMs) {
529
571
  const response = await fetchGitHubRestJson(`${apiBaseUrl}/user`, token, requestTimeoutMs);
@@ -788,6 +830,12 @@ async function fetchApplicableBudget(params) {
788
830
  authority: percentRemaining === undefined ? "provider_reported" : "locally_derived",
789
831
  };
790
832
  }
833
+ // Separate from the usage guard: a limited budget report must not block usage.
834
+ const budgetGuard = createApiKeyRetryGuard((retryAtMs) => ({
835
+ success: false,
836
+ error: `GitHub API error 429: budget report rate limited until ${new Date(retryAtMs).toISOString()}`,
837
+ retryAtMs,
838
+ }));
791
839
  function makeBudgetWarning(error) {
792
840
  const message = error instanceof Error ? error.message : String(error);
793
841
  return `AI Credit usage loaded, but the budget report failed: ${message}`;
@@ -798,18 +846,33 @@ async function toAiCreditResult(params) {
798
846
  let budget;
799
847
  const warnings = [];
800
848
  if (params.target.scope !== "user") {
801
- try {
802
- budget = await fetchApplicableBudget({
803
- apiBaseUrl: params.apiBaseUrl,
804
- token: params.token,
805
- target: params.target,
806
- spentUsd: totals.billedAmountUsd,
807
- requestTimeoutMs: params.requestTimeoutMs,
808
- });
809
- }
810
- catch (error) {
811
- warnings.push(makeBudgetWarning(error));
812
- }
849
+ const target = params.target;
850
+ const fetched = await budgetGuard(`budget\0${params.apiBaseUrl}\0${params.token}`, async () => {
851
+ try {
852
+ return {
853
+ success: true,
854
+ budget: await fetchApplicableBudget({
855
+ apiBaseUrl: params.apiBaseUrl,
856
+ token: params.token,
857
+ target,
858
+ spentUsd: totals.billedAmountUsd,
859
+ requestTimeoutMs: params.requestTimeoutMs,
860
+ }),
861
+ };
862
+ }
863
+ catch (error) {
864
+ const retryAtMs = requestRetryAtMs(error);
865
+ return {
866
+ success: false,
867
+ error: error instanceof Error ? error.message : String(error),
868
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
869
+ };
870
+ }
871
+ }, params.requestTimeoutMs, undefined, JSON.stringify({ target, spentUsd: totals.billedAmountUsd }));
872
+ if (fetched.success)
873
+ budget = fetched.budget;
874
+ else
875
+ warnings.push(makeBudgetWarning(new Error(fetched.error)));
813
876
  }
814
877
  if (params.target.scope === "organization") {
815
878
  return {
@@ -861,11 +924,12 @@ function toLegacyResult(response, config) {
861
924
  resetTimeIso: getApproxNextResetIso(),
862
925
  };
863
926
  }
864
- function toQuotaError(message, failureCategory) {
927
+ function toQuotaError(message, failureCategory, retryAtMs) {
865
928
  return {
866
929
  success: false,
867
930
  error: message,
868
931
  ...(failureCategory !== undefined ? { failureCategory } : {}),
932
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
869
933
  };
870
934
  }
871
935
  function buildCopilotInternalHeaders(token) {
@@ -984,27 +1048,42 @@ function parseCopilotInternalUser(response) {
984
1048
  throw new Error("GitHub Copilot user response did not include a usable quota snapshot");
985
1049
  }
986
1050
  async function fetchCopilotInternalUser(params) {
987
- return await fetchWithTimeout(`${params.apiBaseUrl}${COPILOT_INTERNAL_USER_PATH}`, {
988
- request: { headers: buildCopilotInternalHeaders(params.token) },
989
- timeoutMs: params.requestTimeoutMs,
990
- consume: async (response) => {
991
- if (!response.ok) {
992
- const message = await readGitHubRestErrorMessageForClassification(response, [params.token]);
993
- throw new CopilotRequestError(`GitHub Copilot API error ${response.status}: ${message}`, response.status === 401 || response.status === 403 ? "credentials" : "provider_api");
994
- }
995
- let parsed;
996
- try {
997
- parsed = (await response.json());
998
- }
999
- catch {
1000
- throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1001
- }
1002
- if (!parsed || typeof parsed !== "object") {
1003
- throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1004
- }
1005
- return parseCopilotInternalUser(parsed);
1006
- },
1007
- });
1051
+ let observedRetryAtMs;
1052
+ try {
1053
+ return await fetchWithTimeout(`${params.apiBaseUrl}${COPILOT_INTERNAL_USER_PATH}`, {
1054
+ request: { headers: buildCopilotInternalHeaders(params.token) },
1055
+ timeoutMs: params.requestTimeoutMs,
1056
+ consume: async (response) => {
1057
+ if (!response.ok) {
1058
+ if (response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
1059
+ // Snapshot a confirmed primary limit before its body can stall.
1060
+ observedRetryAtMs = classifyGitHubRateLimit(response, "").retryAtMs;
1061
+ }
1062
+ const message = await readGitHubRestErrorMessageForClassification(response, [
1063
+ params.token,
1064
+ ]);
1065
+ const limit = classifyGitHubRateLimit(response, message);
1066
+ throw new CopilotRequestError(`GitHub Copilot API error ${response.status}: ${message}`, response.status === 401 || (response.status === 403 && !limit.limited)
1067
+ ? "credentials"
1068
+ : "provider_api", limit.retryAtMs);
1069
+ }
1070
+ let parsed;
1071
+ try {
1072
+ parsed = (await response.json());
1073
+ }
1074
+ catch {
1075
+ throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1076
+ }
1077
+ if (!parsed || typeof parsed !== "object") {
1078
+ throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1079
+ }
1080
+ return parseCopilotInternalUser(parsed);
1081
+ },
1082
+ });
1083
+ }
1084
+ catch (error) {
1085
+ throw preserveRetryAtOnTimeout(error, observedRetryAtMs);
1086
+ }
1008
1087
  }
1009
1088
  /**
1010
1089
  * Query GitHub Copilot accounting.
@@ -1029,16 +1108,19 @@ export async function queryCopilotQuota(options = {}) {
1029
1108
  if (enterpriseHost.error) {
1030
1109
  return toQuotaError(`Invalid OpenCode Copilot enterpriseUrl: ${enterpriseHost.error}`);
1031
1110
  }
1032
- try {
1033
- return await fetchCopilotInternalUser({
1034
- apiBaseUrl: getApiBaseUrl(enterpriseHost.host),
1035
- token,
1036
- requestTimeoutMs: options.requestTimeoutMs,
1037
- });
1038
- }
1039
- catch (error) {
1040
- return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error));
1041
- }
1111
+ const apiBaseUrl = getApiBaseUrl(enterpriseHost.host);
1112
+ return await guard(`oauth\0${apiBaseUrl}\0${token}`, async () => {
1113
+ try {
1114
+ return await fetchCopilotInternalUser({
1115
+ apiBaseUrl,
1116
+ token,
1117
+ requestTimeoutMs: options.requestTimeoutMs,
1118
+ });
1119
+ }
1120
+ catch (error) {
1121
+ return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error), requestRetryAtMs(error));
1122
+ }
1123
+ }, options.requestTimeoutMs);
1042
1124
  }
1043
1125
  const resolved = resolvePatBillingTarget(pat.config);
1044
1126
  if (!resolved.target) {
@@ -1047,29 +1129,32 @@ export async function queryCopilotQuota(options = {}) {
1047
1129
  const compatibilityError = validatePatTargetCompatibility(resolved.target, pat.tokenKind);
1048
1130
  if (compatibilityError)
1049
1131
  return toQuotaError(compatibilityError);
1050
- try {
1051
- const billingModel = pat.config.billingModel ?? "ai_credits";
1052
- const apiBaseUrl = getApiBaseUrl(pat.config.enterpriseUrl);
1053
- const { response, target } = await fetchBillingUsage({
1054
- apiBaseUrl,
1055
- token: pat.config.token,
1056
- target: resolved.target,
1057
- billingModel,
1058
- requestTimeoutMs: options.requestTimeoutMs,
1059
- });
1060
- return billingModel === "legacy_premium_requests"
1061
- ? toLegacyResult(response, pat.config)
1062
- : await toAiCreditResult({
1132
+ const config = pat.config;
1133
+ const apiBaseUrl = getApiBaseUrl(config.enterpriseUrl);
1134
+ const billingModel = config.billingModel ?? "ai_credits";
1135
+ return await guard(`pat\0${apiBaseUrl}\0${config.token}`, async () => {
1136
+ try {
1137
+ const { response, target } = await fetchBillingUsage({
1063
1138
  apiBaseUrl,
1064
- response,
1065
- target,
1066
- token: pat.config.token,
1139
+ token: config.token,
1140
+ target: resolved.target,
1141
+ billingModel,
1067
1142
  requestTimeoutMs: options.requestTimeoutMs,
1068
1143
  });
1069
- }
1070
- catch (error) {
1071
- return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error));
1072
- }
1144
+ return billingModel === "legacy_premium_requests"
1145
+ ? toLegacyResult(response, config)
1146
+ : await toAiCreditResult({
1147
+ apiBaseUrl,
1148
+ response,
1149
+ target,
1150
+ token: config.token,
1151
+ requestTimeoutMs: options.requestTimeoutMs,
1152
+ });
1153
+ }
1154
+ catch (error) {
1155
+ return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error), requestRetryAtMs(error));
1156
+ }
1157
+ }, options.requestTimeoutMs, undefined, JSON.stringify({ billingModel, tier: config.tier, target: resolved.target }));
1073
1158
  }
1074
1159
  export async function resolveCopilotAuthIdentity() {
1075
1160
  const pat = readQuotaConfigWithMeta();
@@ -10,4 +10,9 @@ export declare function dashboardProviderScopeHash(providerId: string): string;
10
10
  export declare function legacyProviderIdForScopeCardId(id: string): string | undefined;
11
11
  /** Deterministic legacy (v1) hiddenCards normalization, preserving first-seen order. */
12
12
  export declare function normalizeLegacyDashboardHiddenCards(ids: readonly string[]): string[];
13
+ /**
14
+ * Row ids saved before per-window semantics are resolved against the live card
15
+ * at render/notification time in `src/contracts/row-visibility.ts`. They are
16
+ * intentionally preserved verbatim here until an explicit Settings toggle.
17
+ */
13
18
  //# sourceMappingURL=dashboard-visibility.d.ts.map
@@ -1,23 +1,19 @@
1
1
  /**
2
- * Persisted semantics for `dashboard.hiddenCards` (backend-only helpers).
2
+ * Persisted semantics for `dashboard.hiddenCards` and `dashboard.hiddenRows`
3
+ * (backend-only helpers).
3
4
  *
4
5
  * Version 1 (implicit, no marker) treated a provider-scope card id as a
5
6
  * provider-wide hide. Version 2 treats every hiddenCards entry as an exact card
6
7
  * id, while a plain provider id and the legacy bare provider-scope hash remain
7
- * provider-wide forms. The domain and identity-key literals below are pinned to
8
- * `src/gui/identity.ts` by the backend tests; importing GUI identity (and its
9
- * node:crypto hash) from this layer would couple config loading to the GUI.
8
+ * provider-wide forms. The card/row identity helpers live in
9
+ * `src/contracts/identity.ts` so this layer and the GUI share one hash.
10
10
  */
11
- import { createHash } from "node:crypto";
11
+ import { hashQuotaCardIdentity, PROVIDER_SCOPE_IDENTITY_KEY } from "./quota-identity.js";
12
12
  export const DASHBOARD_HIDDEN_CARDS_VERSION = 2;
13
- const CARD_HASH_DOMAIN = "ocq-card-v1";
14
- const PROVIDER_SCOPE_IDENTITY_KEY = "provider";
15
13
  const CARD_HASH_RE = /^[0-9a-f]{64}$/u;
16
14
  /** The provider-scope hash exactly as `buildProviderScopeCardId` derives it. */
17
15
  export function dashboardProviderScopeHash(providerId) {
18
- return createHash("sha256")
19
- .update(`${CARD_HASH_DOMAIN}\0${providerId}\0${PROVIDER_SCOPE_IDENTITY_KEY}`, "utf8")
20
- .digest("hex");
16
+ return hashQuotaCardIdentity(providerId, PROVIDER_SCOPE_IDENTITY_KEY);
21
17
  }
22
18
  /**
23
19
  * Converts one legacy provider-scope card id to its provider id. Only a full
@@ -48,4 +44,9 @@ export function normalizeLegacyDashboardHiddenCards(ids) {
48
44
  }
49
45
  return normalized;
50
46
  }
47
+ /**
48
+ * Row ids saved before per-window semantics are resolved against the live card
49
+ * at render/notification time in `src/contracts/row-visibility.ts`. They are
50
+ * intentionally preserved verbatim here until an explicit Settings toggle.
51
+ */
51
52
  //# sourceMappingURL=dashboard-visibility.js.map
@@ -1,15 +1,15 @@
1
1
  /**
2
2
  * Effective localhost web dashboard switch.
3
3
  *
4
- * The Native GUI is the primary surface from OpenCode 2.2.0, so the compatibility
4
+ * The full Native GUI is the primary surface from OpenCode 2.2.1, so the compatibility
5
5
  * web transport follows the host version when the canonical key is absent:
6
- * hosts below 2.2.0 keep it on (the only GUI they have), and 2.2.0+ keeps it off.
6
+ * supported hosts below 2.2.1 keep it on (including 2.2.0), and 2.2.1+ keeps it off.
7
7
  * An explicit `dashboard.enabled` value always wins. Missing or unparseable host
8
8
  * versions, a malformed canonical file, and an invalid `dashboard.enabled` value
9
9
  * all fail closed. The listener itself stays loopback-only at `dashboard.port`.
10
10
  */
11
11
  import type { LoadConfigMeta } from "./config.js";
12
- import { type OpenCodeVersion } from "./opencode-version.js";
12
+ import { type OpenCodeVersion } from "./opencode-version-core.js";
13
13
  export interface DashboardWebPolicyInput {
14
14
  /** Canonical `dashboard.enabled` when the key is present and valid. */
15
15
  explicitEnabled?: boolean;
@@ -18,7 +18,7 @@ export interface DashboardWebPolicyInput {
18
18
  /** A malformed canonical file or an invalid `dashboard.enabled` fails closed. */
19
19
  invalidConfig?: boolean;
20
20
  }
21
- /** Explicit config wins; otherwise only a parseable pre-2.2.0 host defaults on. */
21
+ /** Explicit config wins; otherwise only a parseable pre-2.2.1 host defaults on. */
22
22
  export declare function resolveDashboardWebEnabled(input: DashboardWebPolicyInput): boolean;
23
23
  /**
24
24
  * The canonical value when the loader actually applied it. The setting-source
@@ -1,5 +1,5 @@
1
- import { isPreNativeGuiVersion } from "./opencode-version.js";
2
- /** Explicit config wins; otherwise only a parseable pre-2.2.0 host defaults on. */
1
+ import { isPreNativeGuiVersion } from "./opencode-version-core.js";
2
+ /** Explicit config wins; otherwise only a parseable pre-2.2.1 host defaults on. */
3
3
  export function resolveDashboardWebEnabled(input) {
4
4
  if (input.invalidConfig)
5
5
  return false;
@@ -6,12 +6,19 @@
6
6
  */
7
7
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
8
8
  import { isCanonicalAccountingDecimal } from "./accounting-format.js";
9
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
9
10
  import { resolveDeepSeekApiKey } from "./deepseek-auth.js";
10
11
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
11
12
  import { fetchWithTimeout } from "./http.js";
12
13
  const DEEPSEEK_BALANCE_URL = "https://api.deepseek.com/user/balance";
13
14
  const USER_AGENT = "opencode-quota-gui/1.0";
14
15
  const MAX_PARSE_ISSUES = 6;
16
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
17
+ success: false,
18
+ error: "DeepSeek API error 429",
19
+ failureCategory: "provider_api",
20
+ retryAtMs,
21
+ }));
15
22
  function isRecord(value) {
16
23
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
17
24
  }
@@ -77,11 +84,13 @@ async function fetchDeepSeekBalance(apiKey, requestTimeoutMs) {
77
84
  consume: async (response) => {
78
85
  responseStatus = response.status;
79
86
  if (!response.ok) {
80
- const text = await response.text();
87
+ const deadline = retryAfterDeadline(response);
88
+ const text = await response.text().catch(() => "");
81
89
  return {
82
90
  success: false,
83
91
  message: `DeepSeek API error ${response.status}: ${sanitizeDisplaySnippet(text, 120)}`,
84
92
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
93
+ ...(deadline !== undefined ? { retryAtMs: deadline } : {}),
85
94
  };
86
95
  }
87
96
  return {
@@ -110,20 +119,23 @@ export async function queryDeepSeekBalance(options = {}) {
110
119
  const resolved = await resolveDeepSeekApiKey();
111
120
  if (!resolved)
112
121
  return null;
113
- const result = await fetchDeepSeekBalance(resolved.key, options.requestTimeoutMs);
114
- if (!result.success) {
122
+ return guard(resolved.key, async () => {
123
+ const result = await fetchDeepSeekBalance(resolved.key, options.requestTimeoutMs);
124
+ if (!result.success) {
125
+ return {
126
+ success: false,
127
+ error: result.message,
128
+ failureCategory: result.failureCategory,
129
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
130
+ };
131
+ }
115
132
  return {
116
- success: false,
117
- error: result.message,
118
- failureCategory: result.failureCategory,
133
+ success: true,
134
+ isAvailable: result.data.isAvailable,
135
+ balanceInfos: result.data.balanceInfos,
136
+ parseIssues: result.data.parseIssues,
119
137
  };
120
- }
121
- return {
122
- success: true,
123
- isAvailable: result.data.isAvailable,
124
- balanceInfos: result.data.balanceInfos,
125
- parseIssues: result.data.parseIssues,
126
- };
138
+ }, options.requestTimeoutMs);
127
139
  }
128
140
  export { getDeepSeekKeyDiagnostics, hasDeepSeekApiKey as hasDeepSeekApiKeyConfigured, } from "./deepseek-auth.js";
129
141
  //# sourceMappingURL=deepseek.js.map
@@ -103,6 +103,8 @@ export function sanitizeQuotaToastError(error) {
103
103
  return {
104
104
  label: sanitizeDisplayText(error.label),
105
105
  message: sanitizeDisplayText(error.message),
106
+ ...(error.retryAtMs !== undefined ? { retryAtMs: error.retryAtMs } : {}),
107
+ ...(error.attemptOutcome !== undefined ? { attemptOutcome: error.attemptOutcome } : {}),
106
108
  ...(error.retryable === true ? { retryable: true } : {}),
107
109
  ...(error.failureCategory !== undefined ? { failureCategory: error.failureCategory } : {}),
108
110
  ...(error.kind ? { kind: error.kind } : {}),
@@ -1,5 +1,5 @@
1
1
  import type { BankedResetAvailability } from "../contracts/openai-quota.js";
2
- import type { ProviderFailureCategory } from "../contracts/provider-failure.js";
2
+ import type { ProviderFailureCategory, QuotaAttemptOutcome } from "../contracts/provider-failure.js";
3
3
  import type { QuotaProviderDefinition } from "./quota-providers.js";
4
4
  import type { QuotaTelemetryToken } from "./quota-telemetry.js";
5
5
  import type { ResolvedAuthIdentity } from "./resolved-auth-identity.js";
@@ -162,11 +162,20 @@ export declare function isPercentEntry(e: QuotaToastEntry): e is QuotaPercentEnt
162
162
  export declare function cloneAccountingUnit(unit: AccountingUnit): AccountingUnit;
163
163
  export declare function cloneAccountingQuantity(quantity: AccountingQuantity): AccountingQuantity;
164
164
  export declare function cloneAccountingSemantic(semantic: AccountingSemantic): AccountingSemantic;
165
+ /** The one typed-window semantic builder every provider window mapping must use. */
166
+ export declare function windowSemantic(window: AccountingWindow, prominence?: AccountingProminence): AccountingSemantic;
165
167
  export declare function cloneAccountingBasisFact(fact: AccountingBasisFact): AccountingBasisFact;
166
168
  export declare function cloneAccountingPercentageBasis(basis: AccountingPercentageBasis): AccountingPercentageBasis;
167
169
  export declare function cloneBankedResetAvailability(bankedResets: BankedResetAvailability): BankedResetAvailability;
168
170
  export declare function cloneQuotaToastEntry(entry: QuotaToastEntry): QuotaToastEntry;
169
171
  export interface QuotaToastError {
172
+ /** Deadline observed in an upstream Retry-After response. */
173
+ retryAtMs?: number;
174
+ /**
175
+ * Outcome of the attempt that produced this error. A `cooldown` skip made no
176
+ * request, so it is not a failure observation. Absence means unknown.
177
+ */
178
+ attemptOutcome?: QuotaAttemptOutcome;
170
179
  /** Short label that will be rendered as "label: message". */
171
180
  label: string;
172
181
  message: string;
@@ -266,6 +275,11 @@ export interface QuotaProviderResult {
266
275
  errors: QuotaToastError[];
267
276
  /** Additive discovered-account descriptors; absent when no account identity exists. */
268
277
  accounts?: readonly QuotaProviderAccount[];
278
+ /**
279
+ * Optional display-only plan for a provider-scope result with no discovered accounts (the Claude CLI
280
+ * login shown alone). Never an identity input and never set beside OpenCode account descriptors.
281
+ */
282
+ planLabel?: string;
269
283
  /** Internal provider diagnostics; not projected into normal presentation/export surfaces. */
270
284
  diagnostics?: QuotaProviderDiagnostic[];
271
285
  /**
@@ -282,8 +296,23 @@ export interface QuotaProviderMatchContext {
282
296
  quotaProviders?: QuotaProviderDefinition[];
283
297
  currentProviderID?: string;
284
298
  }
299
+ /** Marks a single provider operation as an explicit freshness request. */
300
+ export declare const QUOTA_FORCE_REFRESH: unique symbol;
285
301
  export interface QuotaProviderContext {
302
+ /** Ephemeral memoization shared only within one quota refresh operation. */
303
+ operationCache?: Map<symbol, unknown>;
286
304
  client: {
305
+ integration?: {
306
+ list: () => Promise<{
307
+ data: Array<{
308
+ id: string;
309
+ connections: Array<{
310
+ type: string;
311
+ method?: string;
312
+ }>;
313
+ }>;
314
+ }>;
315
+ };
287
316
  config: {
288
317
  providers: () => Promise<{
289
318
  data?: {
@@ -313,6 +342,8 @@ export interface QuotaProviderContext {
313
342
  workspaceRoot: string;
314
343
  config: {
315
344
  anthropicBinaryPath?: string;
345
+ /** Minimum spacing between Claude Agent usage requests, shared by processes. */
346
+ claudeAgentPollIntervalMs?: number;
316
347
  cursorPlan: CursorQuotaPlan;
317
348
  cursorIncludedApiUsd?: number;
318
349
  cursorBillingCycleStartDay?: number;
@@ -340,6 +371,7 @@ export type QuotaProviderCachePolicy = {
340
371
  kind: "uncached";
341
372
  } | {
342
373
  kind: "resolved-auth";
374
+ revalidateWithCycleCache?: true;
343
375
  resolveIdentity: (ctx: QuotaProviderContext, cacheContext: QuotaProviderCacheContext) => Promise<ResolvedAuthIdentity | null>;
344
376
  };
345
377
  export interface QuotaProvider {
@@ -29,6 +29,10 @@ export function cloneAccountingQuantity(quantity) {
29
29
  export function cloneAccountingSemantic(semantic) {
30
30
  return { metric: { ...semantic.metric }, prominence: semantic.prominence };
31
31
  }
32
+ /** The one typed-window semantic builder every provider window mapping must use. */
33
+ export function windowSemantic(window, prominence = "primary") {
34
+ return { metric: { kind: "window", window }, prominence };
35
+ }
32
36
  export function cloneAccountingBasisFact(fact) {
33
37
  return { quantity: cloneAccountingQuantity(fact.quantity), authority: fact.authority };
34
38
  }
@@ -66,4 +70,6 @@ export function cloneQuotaToastEntry(entry) {
66
70
  : {}),
67
71
  };
68
72
  }
73
+ /** Marks a single provider operation as an explicit freshness request. */
74
+ export const QUOTA_FORCE_REFRESH = Symbol("quota-force-refresh");
69
75
  //# sourceMappingURL=entries.js.map