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
@@ -2,38 +2,314 @@
2
2
  * `waitForQuotaReset` (on by default): when a model request hits a provider limit and the quota data
3
3
  * shows a used-up window for that model's provider, OpenCode retries once that window resets
4
4
  * instead of following its normal retry timing.
5
+ *
6
+ * `autoResumeOnQuotaRecovery` reuses the same window walk and probe: after a terminal quota failure
7
+ * it waits for the failed route's verified identity to recover, then sends one continuation prompt.
5
8
  */
6
9
  import { isPercentEntry } from "./entries.js";
10
+ import { readCredentialRows } from "./opencode-auth.js";
11
+ import { getQuotaProviderIdsForRuntimeId, getQuotaProviderRegistration, } from "./provider-metadata.js";
7
12
  import { collectQuotaRenderData } from "./quota-render-data.js";
8
13
  import { createQuotaRuntimeRequestContext, resolveQuotaRuntimeContext, } from "./quota-runtime-context.js";
9
14
  /** Extra wait after the reset time, so the provider has reset the window when the retry runs. */
10
15
  export const QUOTA_RESET_RETRY_BUFFER_MS = 60_000;
11
- /** Longest single wait. If the window is still used up, the next retry waits again. */
16
+ /** Longest wait for a reset; the buffer is added after this cap so a retry never lands just before it. */
12
17
  export const QUOTA_RESET_RETRY_MAX_DELAY_MS = 5 * 60 * 60 * 1000;
13
- /** OpenCode's error types for a provider rate limit or used-up quota, or any HTTP 429. */
18
+ /**
19
+ * OpenCode's error types for a provider limit, a used-up quota or a spent budget, or any HTTP 429.
20
+ * A match only forces an early retry when a used-up window with a known reset is observed below.
21
+ */
22
+ const QUOTA_LIMIT_ERROR_TYPES = new Set([
23
+ "provider.rate-limit",
24
+ "provider.quota",
25
+ "provider.free-limit",
26
+ "provider.budget-limit",
27
+ "provider.model-budget-limit",
28
+ "provider.go-limit",
29
+ "provider.chatgpt-limit",
30
+ "provider.chatgpt-workspace-limit",
31
+ ]);
14
32
  export function isQuotaLimitError(error) {
15
- return (error.type === "provider.rate-limit" || error.type === "provider.quota" || error.status === 429);
33
+ return QUOTA_LIMIT_ERROR_TYPES.has(error.type) || error.status === 429;
34
+ }
35
+ const NON_ROUTE_WINDOW_KINDS = new Set(["code_review", "mcp"]);
36
+ /** A primary quota/rate-limit window that can govern the model route that failed. */
37
+ function isPrimaryRouteWindow(entry, includeNamed) {
38
+ const semantic = entry.semantic;
39
+ if (!semantic || semantic.prominence !== "primary")
40
+ return false;
41
+ const routeResultType = entry.accounting.resultType === "quota" || entry.accounting.resultType === "rate_limit";
42
+ if (!routeResultType)
43
+ return false;
44
+ if (semantic.metric.kind === "named") {
45
+ return includeNamed.has(`named:${semantic.metric.name}`);
46
+ }
47
+ if (semantic.metric.kind !== "window")
48
+ return false;
49
+ return !NON_ROUTE_WINDOW_KINDS.has(semantic.metric.window);
50
+ }
51
+ /** A provider result with no account identity of its own: exactly one source by construction. */
52
+ function hasNoAccountIdentity(result) {
53
+ return ((result.accounts === undefined || result.accounts.length === 0) &&
54
+ result.entries.every((entry) => entry.accounting.sourceId === undefined));
55
+ }
56
+ /** The row belongs to the known active account, directly or through a single result account. */
57
+ function isBoundToActiveAccount(result, entry, activeSourceId) {
58
+ if (entry.accounting.sourceId !== undefined) {
59
+ return entry.accounting.sourceId === activeSourceId;
60
+ }
61
+ const accounts = result.accounts;
62
+ return accounts?.length === 1 && accounts[0]?.sourceId === activeSourceId;
63
+ }
64
+ export function sameQuotaWindowBinding(left, right) {
65
+ if (left === undefined || right === undefined || left.kind !== right.kind)
66
+ return false;
67
+ if (left.kind === "account") {
68
+ return right.kind === "account" && left.sourceId === right.sourceId;
69
+ }
70
+ return (right.kind === "provider-scope" &&
71
+ left.providerId === right.providerId &&
72
+ left.scope === right.scope);
73
+ }
74
+ /** The row identity the Provider field contract allows: typed semantics or an explicit rowKey. */
75
+ function quotaWindowKey(entry) {
76
+ if (entry.rowKey)
77
+ return entry.rowKey;
78
+ const metric = entry.semantic?.metric;
79
+ if (!metric)
80
+ return undefined;
81
+ switch (metric.kind) {
82
+ case "window":
83
+ return `window:${metric.window}`;
84
+ case "named":
85
+ return `named:${metric.name}`;
86
+ case "component":
87
+ return `component:${metric.component}`;
88
+ case "aggregate":
89
+ return "aggregate";
90
+ }
16
91
  }
17
92
  /**
18
- * Milliseconds until the earliest reset among used-up (0% left) windows, plus the buffer, at
19
- * most the cap. Undefined when no used-up window has a reset time still ahead.
93
+ * Walks the percent rows for the verified binding. A window is exhausted when its percentage is
94
+ * zero. `resetMs` is the parsed reset instant when the row carries one. A provider-scope binding
95
+ * requires exactly one unaccounted provider result, so two sources can never be mixed.
20
96
  */
21
- export function getQuotaResetRetryDelayMs(results, nowMs) {
22
- let earliestResetMs;
97
+ export function collectQuotaWindows(results, binding, options = {}) {
98
+ const providerScope = binding?.kind === "provider-scope" ? binding : undefined;
99
+ if (providerScope !== undefined && results.length !== 1)
100
+ return undefined;
101
+ const sources = new Set(results.flatMap((result) => [
102
+ ...result.entries.flatMap((entry) => entry.accounting.sourceId ? [entry.accounting.sourceId] : []),
103
+ ...(result.accounts?.map((account) => account.sourceId) ?? []),
104
+ ]));
105
+ const marked = new Set(results.flatMap((result) => result.accounts?.filter((account) => account.active).map((account) => account.sourceId) ??
106
+ []));
107
+ const active = binding?.kind === "account" ? binding.sourceId : marked.size === 1 ? [...marked][0] : undefined;
108
+ // Auto-resume has no safe account to bind a failure or a recovery to.
109
+ if (options.primaryAccountOnly && providerScope === undefined && active === undefined) {
110
+ return undefined;
111
+ }
112
+ if (providerScope === undefined) {
113
+ // Several accounts and no known active one: leave the host decision as is.
114
+ if (sources.size > 1 && !active)
115
+ return undefined;
116
+ if (active && sources.size > 0 && !sources.has(active))
117
+ return undefined;
118
+ }
119
+ const windows = [];
120
+ const includeNamed = new Set(options.includeNamedWindows ?? []);
23
121
  for (const result of results) {
122
+ if (!result.attempted)
123
+ return undefined;
124
+ if (providerScope !== undefined) {
125
+ if (result.errors.length > 0 || !hasNoAccountIdentity(result))
126
+ return undefined;
127
+ }
128
+ else if (result.errors.some((error) => !active || !error.sourceId || error.sourceId === active)) {
129
+ return undefined;
130
+ }
24
131
  for (const entry of result.entries) {
25
- if (!isPercentEntry(entry) || !(entry.percentRemaining <= 0) || !entry.resetTimeIso)
132
+ if (providerScope === undefined) {
133
+ if (sources.size > 1 && !entry.accounting.sourceId)
134
+ return undefined;
135
+ if (active && entry.accounting.sourceId && entry.accounting.sourceId !== active)
136
+ continue;
137
+ }
138
+ if (!isPercentEntry(entry))
26
139
  continue;
27
- const resetMs = Date.parse(entry.resetTimeIso);
28
- if (!(resetMs > nowMs))
29
- continue;
30
- if (earliestResetMs === undefined || resetMs < earliestResetMs)
31
- earliestResetMs = resetMs;
140
+ if (!Number.isFinite(entry.percentRemaining))
141
+ return undefined;
142
+ if (options.primaryAccountOnly) {
143
+ if (!isPrimaryRouteWindow(entry, includeNamed))
144
+ continue;
145
+ if (providerScope === undefined &&
146
+ (!active || !isBoundToActiveAccount(result, entry, active))) {
147
+ continue;
148
+ }
149
+ }
150
+ const key = quotaWindowKey(entry);
151
+ const resetMs = entry.resetTimeIso ? Date.parse(entry.resetTimeIso) : undefined;
152
+ windows.push({
153
+ ...(key !== undefined ? { key } : {}),
154
+ percentRemaining: entry.percentRemaining,
155
+ ...(resetMs !== undefined && Number.isFinite(resetMs) ? { resetMs } : {}),
156
+ });
32
157
  }
33
158
  }
34
- if (earliestResetMs === undefined)
159
+ const resolvedBinding = providerScope ?? (active !== undefined ? { kind: "account", sourceId: active } : undefined);
160
+ return {
161
+ ...(resolvedBinding !== undefined ? { binding: resolvedBinding } : {}),
162
+ windows,
163
+ };
164
+ }
165
+ /**
166
+ * Milliseconds until all used-up windows have reset, plus the buffer, with the reset wait at most
167
+ * the cap. The buffer is added after the cap so the retry never lands just before a reset.
168
+ */
169
+ export function getQuotaResetRetryDelayMs(results, nowMs, activeSourceId) {
170
+ const collected = collectQuotaWindows(results, activeSourceId !== undefined ? { kind: "account", sourceId: activeSourceId } : undefined);
171
+ if (!collected)
172
+ return undefined;
173
+ let latestResetMs;
174
+ for (const entry of collected.windows) {
175
+ if (entry.percentRemaining > 0)
176
+ continue;
177
+ if (entry.resetMs === undefined || !(entry.resetMs > nowMs))
178
+ return undefined;
179
+ if (latestResetMs === undefined || entry.resetMs > latestResetMs)
180
+ latestResetMs = entry.resetMs;
181
+ }
182
+ if (latestResetMs === undefined)
35
183
  return undefined;
36
- return Math.min(earliestResetMs - nowMs + QUOTA_RESET_RETRY_BUFFER_MS, QUOTA_RESET_RETRY_MAX_DELAY_MS);
184
+ return (Math.min(latestResetMs - nowMs, QUOTA_RESET_RETRY_MAX_DELAY_MS) + QUOTA_RESET_RETRY_BUFFER_MS);
185
+ }
186
+ /** Canonical providers for a runtime route that declare auto-resume evidence. */
187
+ export function getQuotaAutoResumeProviderIds(modelProviderID) {
188
+ return new Set(getQuotaProviderIdsForRuntimeId(modelProviderID).filter((providerId) => getQuotaProviderRegistration(providerId)?.autoResume !== undefined));
189
+ }
190
+ /**
191
+ * Picks the verified identity for auto-resume evidence. A single-source route uses the provider
192
+ * cache scope of its unaccounted result (the Claude CLI login, one API key); everything else
193
+ * needs an active OpenCode credential row. Ambiguous or missing evidence yields undefined.
194
+ */
195
+ export function resolveQuotaEvidenceBinding(params) {
196
+ const eligibleProviderIds = getQuotaAutoResumeProviderIds(params.modelProviderID);
197
+ if (eligibleProviderIds.size === 0)
198
+ return undefined;
199
+ const routeResults = params.providerResults.filter((probe) => eligibleProviderIds.has(probe.providerId));
200
+ const [routeResult] = routeResults;
201
+ // A single-source adapter that exposes no account ids can only be bound by its cache scope.
202
+ if (routeResults.length === 1 && routeResult && hasNoAccountIdentity(routeResult.result)) {
203
+ const mode = getQuotaProviderRegistration(routeResult.providerId)?.autoResume;
204
+ const singleSource = mode === "single-source" || mode === "account-or-single-source";
205
+ if (singleSource) {
206
+ return routeResult.cacheScope !== undefined
207
+ ? {
208
+ kind: "provider-scope",
209
+ providerId: routeResult.providerId,
210
+ scope: routeResult.cacheScope,
211
+ }
212
+ : undefined;
213
+ }
214
+ }
215
+ return params.activeSourceId !== undefined
216
+ ? { kind: "account", sourceId: params.activeSourceId }
217
+ : undefined;
218
+ }
219
+ /** Resolves after `promise` or `fallback` when the deadline passes first. */
220
+ function withTimeout(promise, timeoutMs) {
221
+ if (!(Number.isFinite(timeoutMs) && timeoutMs > 0))
222
+ return promise;
223
+ return new Promise((resolve, reject) => {
224
+ const timer = setTimeout(() => resolve(undefined), timeoutMs);
225
+ timer.unref?.();
226
+ promise.then((value) => {
227
+ clearTimeout(timer);
228
+ resolve(value);
229
+ }, (error) => {
230
+ clearTimeout(timer);
231
+ reject(error);
232
+ });
233
+ });
234
+ }
235
+ /**
236
+ * One live quota probe for the model's provider, keeping "the feature is off", "this route can
237
+ * never supply auto-resume evidence", and "the evidence is temporarily unavailable" distinct.
238
+ * Auto-resume stops immediately for the first two and keeps polling the last.
239
+ */
240
+ export async function probeQuotaForModelState(host, model, isEnabled, options = {}) {
241
+ const runtime = await resolveQuotaRuntimeContext({
242
+ client: host.client,
243
+ roots: host.roots,
244
+ sessionMeta: { modelID: model.id, providerID: model.providerID },
245
+ });
246
+ if (!isEnabled(runtime.config))
247
+ return { state: "disabled" };
248
+ // The provider registration is the permanent eligibility contract; never infer it from rows.
249
+ const autoResumeProviderIds = options.includeProviderScope
250
+ ? getQuotaAutoResumeProviderIds(model.providerID)
251
+ : undefined;
252
+ if (autoResumeProviderIds !== undefined && autoResumeProviderIds.size === 0) {
253
+ return { state: "unsupported" };
254
+ }
255
+ const probed = await withTimeout((async () => {
256
+ const collected = await collectQuotaRenderData({
257
+ client: runtime.client,
258
+ resolveRuntimeProviderIds: runtime.resolveRuntimeProviderIds,
259
+ // Only the provider of the model that hit the limit counts, whatever onlyCurrentModel says.
260
+ config: {
261
+ ...runtime.config,
262
+ onlyCurrentModel: true,
263
+ opencodeGoWindows: ["rolling", "weekly", "monthly"],
264
+ },
265
+ configMeta: runtime.configMeta,
266
+ request: createQuotaRuntimeRequestContext(runtime),
267
+ workspaceRoot: runtime.roots.workspaceRoot,
268
+ surfaceExplicitProviderIssues: false,
269
+ bypassProviderCache: true,
270
+ includeProviderScope: options.includeProviderScope === true,
271
+ providers: runtime.providers,
272
+ });
273
+ const rows = await readCredentialRows([model.providerID], { firstOnly: true });
274
+ if (rows.some((row) => row.resolveError !== undefined))
275
+ return undefined;
276
+ return {
277
+ collected,
278
+ activeSourceId: rows.find((row) => row.active)?.id,
279
+ };
280
+ })(), runtime.config.requestTimeoutMs);
281
+ if (!probed)
282
+ return { state: "unavailable" };
283
+ // Eligibility is decided above; only providers that declare autoResume evidence can feed the
284
+ // collection, so an account row cannot smuggle an ineligible provider's windows in.
285
+ const routeResults = autoResumeProviderIds !== undefined
286
+ ? probed.collected.providerResults.filter((entry) => autoResumeProviderIds.has(entry.providerId))
287
+ : probed.collected.providerResults;
288
+ const binding = options.includeProviderScope
289
+ ? resolveQuotaEvidenceBinding({
290
+ modelProviderID: model.providerID,
291
+ providerResults: routeResults,
292
+ ...(probed.activeSourceId !== undefined ? { activeSourceId: probed.activeSourceId } : {}),
293
+ })
294
+ : undefined;
295
+ // A provider-scope binding is only meaningful for its own provider result.
296
+ const providerResults = binding?.kind === "provider-scope"
297
+ ? routeResults.filter((entry) => entry.providerId === binding.providerId)
298
+ : routeResults;
299
+ return {
300
+ state: "probe",
301
+ probe: {
302
+ config: runtime.config,
303
+ providerResults,
304
+ ...(probed.activeSourceId !== undefined ? { activeSourceId: probed.activeSourceId } : {}),
305
+ ...(binding !== undefined ? { binding } : {}),
306
+ },
307
+ };
308
+ }
309
+ /** One live quota probe for the model's provider. `undefined` when disabled or unavailable. */
310
+ export async function probeQuotaForModel(...args) {
311
+ const result = await probeQuotaForModelState(...args);
312
+ return result.state === "probe" ? result.probe : undefined;
37
313
  }
38
314
  /**
39
315
  * The retry delay for a limit error on `event.model`, or undefined to keep OpenCode's decision.
@@ -43,25 +319,16 @@ export function getQuotaResetRetryDelayMs(results, nowMs) {
43
319
  export async function resolveQuotaResetRetryDelayMs(host, event) {
44
320
  if (!isQuotaLimitError(event.error))
45
321
  return undefined;
46
- const runtime = await resolveQuotaRuntimeContext({
47
- client: host.client,
48
- roots: host.roots,
49
- sessionMeta: { modelID: event.model.id, providerID: event.model.providerID },
50
- });
51
- if (!runtime.config.waitForQuotaReset)
322
+ const probe = await probeQuotaForModel(host, event.model, (config) => config.waitForQuotaReset);
323
+ if (!probe)
52
324
  return undefined;
53
- const collected = await collectQuotaRenderData({
54
- client: runtime.client,
55
- resolveRuntimeProviderIds: runtime.resolveRuntimeProviderIds,
56
- // Only the provider of the model that hit the limit counts, whatever onlyCurrentModel says.
57
- config: { ...runtime.config, onlyCurrentModel: true },
58
- configMeta: runtime.configMeta,
59
- request: createQuotaRuntimeRequestContext(runtime),
60
- workspaceRoot: runtime.roots.workspaceRoot,
61
- surfaceExplicitProviderIssues: false,
62
- bypassProviderCache: true,
63
- providers: runtime.providers,
64
- });
65
- return getQuotaResetRetryDelayMs(collected.providerResults.map((probe) => probe.result), Date.now());
325
+ const delay = getQuotaResetRetryDelayMs(probe.providerResults.map((entry) => entry.result), Date.now(), probe.activeSourceId);
326
+ if (delay === undefined)
327
+ return undefined;
328
+ // The provider's requested wait is a floor: never retry earlier than it asked.
329
+ const retryAfterMs = event.error.retryAfterMs;
330
+ return typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && retryAfterMs > delay
331
+ ? retryAfterMs
332
+ : delay;
66
333
  }
67
334
  //# sourceMappingURL=quota-retry-wait.js.map
@@ -65,6 +65,7 @@ export function createQuotaProviderRuntimeContext(runtime) {
65
65
  workspaceRoot: runtime.workspaceRoot,
66
66
  config: {
67
67
  anthropicBinaryPath: runtime.config.anthropicBinaryPath,
68
+ claudeAgentPollIntervalMs: runtime.config.claudeAgentPollIntervalMs,
68
69
  cursorPlan: runtime.config.cursorPlan,
69
70
  cursorIncludedApiUsd: runtime.config.cursorIncludedApiUsd,
70
71
  cursorBillingCycleStartDay: runtime.config.cursorBillingCycleStartDay,
@@ -10,6 +10,8 @@ export type PersistedQuotaProviderCacheEntry = {
10
10
  };
11
11
  export type PersistedQuotaProviderCacheIdentity = Pick<PersistedQuotaProviderCacheEntry, "packageVersion" | "key" | "providerId">;
12
12
  export declare function cloneQuotaProviderResult(result: QuotaProviderResult): QuotaProviderResult;
13
+ /** Privacy-safe location of the first contract violation, e.g. `errors[0]`; never field values. */
14
+ export declare function describeQuotaProviderResultViolation(value: unknown): string;
13
15
  export declare function normalizeQuotaProviderResult(value: unknown): QuotaProviderResult | null;
14
16
  export declare function encodePersistedQuotaProviderCacheEntry(value: Omit<PersistedQuotaProviderCacheEntry, "version">): PersistedQuotaProviderCacheEntry;
15
17
  export declare function decodePersistedQuotaProviderCacheEntry(value: unknown, expected: PersistedQuotaProviderCacheIdentity): PersistedQuotaProviderCacheEntry | null;
@@ -1,4 +1,4 @@
1
- import { isProviderFailureCategory } from "../contracts/provider-failure.js";
1
+ import { isProviderFailureCategory, isQuotaAttemptOutcome } from "../contracts/provider-failure.js";
2
2
  import { accountingUnitsEqual, isCanonicalAccountingDecimal } from "./accounting-format.js";
3
3
  import { sanitizeQuotaProviderResult, sanitizeSingleLineDisplayText } from "./display-sanitize.js";
4
4
  import { cloneQuotaToastEntry } from "./entries.js";
@@ -10,6 +10,7 @@ export function cloneQuotaProviderResult(result) {
10
10
  entries: result.entries.map(cloneQuotaToastEntry),
11
11
  errors: result.errors.map((error) => ({ ...error })),
12
12
  ...(result.accounts ? { accounts: result.accounts.map((account) => ({ ...account })) } : {}),
13
+ ...(result.planLabel === undefined ? {} : { planLabel: result.planLabel }),
13
14
  ...(result.diagnostics
14
15
  ? {
15
16
  diagnostics: result.diagnostics.map((diagnostic) => ({
@@ -265,9 +266,21 @@ function isQuotaToastEntry(value, safeText) {
265
266
  function isQuotaToastError(value) {
266
267
  if (!isRecord(value))
267
268
  return false;
268
- return (hasOnlyKeys(value, ["label", "message", "retryable", "failureCategory", "kind", "sourceId"]) &&
269
+ return (hasOnlyKeys(value, [
270
+ "label",
271
+ "message",
272
+ "retryable",
273
+ "failureCategory",
274
+ "kind",
275
+ "sourceId",
276
+ "retryAtMs",
277
+ "attemptOutcome",
278
+ ]) &&
269
279
  typeof value.label === "string" &&
280
+ (value.attemptOutcome === undefined || isQuotaAttemptOutcome(value.attemptOutcome)) &&
270
281
  typeof value.message === "string" &&
282
+ (value.retryAtMs === undefined ||
283
+ (Number.isSafeInteger(value.retryAtMs) && value.retryAtMs >= 0)) &&
271
284
  (value.retryable === undefined || typeof value.retryable === "boolean") &&
272
285
  (value.failureCategory === undefined || isProviderFailureCategory(value.failureCategory)) &&
273
286
  (value.kind === undefined || value.kind === "intentional-filter") &&
@@ -392,6 +405,7 @@ function isQuotaProviderResult(value, safeText) {
392
405
  "entries",
393
406
  "errors",
394
407
  "accounts",
408
+ "planLabel",
395
409
  "diagnostics",
396
410
  "statusDetails",
397
411
  "rawDetails",
@@ -404,6 +418,7 @@ function isQuotaProviderResult(value, safeText) {
404
418
  value.errors.every(isQuotaToastError) &&
405
419
  (value.accounts === undefined ||
406
420
  (isDenseArray(value.accounts) && value.accounts.every(isQuotaProviderAccount))) &&
421
+ (value.planLabel === undefined || typeof value.planLabel === "string") &&
407
422
  (value.diagnostics === undefined ||
408
423
  (isDenseArray(value.diagnostics) && value.diagnostics.every(isQuotaProviderDiagnostic))) &&
409
424
  (value.statusDetails === undefined ||
@@ -413,6 +428,17 @@ function isQuotaProviderResult(value, safeText) {
413
428
  (isDenseArray(value.rawDetails) && value.rawDetails.every(isQuotaProviderStatusDetail))) &&
414
429
  (value.presentation === undefined || isQuotaProviderPresentation(value.presentation)));
415
430
  }
431
+ /** Privacy-safe location of the first contract violation, e.g. `errors[0]`; never field values. */
432
+ export function describeQuotaProviderResultViolation(value) {
433
+ if (!isRecord(value) || !isDenseArray(value.entries) || !isDenseArray(value.errors)) {
434
+ return "result";
435
+ }
436
+ const entry = value.entries.findIndex((item) => !isQuotaToastEntry(item, false));
437
+ if (entry >= 0)
438
+ return `entries[${entry}]`;
439
+ const error = value.errors.findIndex((item) => !isQuotaToastError(item));
440
+ return error >= 0 ? `errors[${error}]` : "result";
441
+ }
416
442
  export function normalizeQuotaProviderResult(value) {
417
443
  if (!isQuotaProviderResult(value, false))
418
444
  return null;
@@ -440,6 +466,9 @@ export function normalizeQuotaProviderResult(value) {
440
466
  })),
441
467
  }
442
468
  : {}),
469
+ ...(value.planLabel !== undefined
470
+ ? { planLabel: sanitizeSingleLineDisplayText(value.planLabel) }
471
+ : {}),
443
472
  };
444
473
  return isQuotaProviderResult(preserved, true) ? cloneQuotaProviderResult(preserved) : null;
445
474
  }
@@ -1,16 +1,22 @@
1
- import type { QuotaProvider, QuotaProviderContext, QuotaProviderResult } from "./entries.js";
1
+ import type { QuotaProvider, QuotaProviderContext, QuotaProviderResult, QuotaToastEntry } from "./entries.js";
2
+ export { QUOTA_FORCE_REFRESH } from "./entries.js";
2
3
  import type { QuotaProviderDefinition } from "./quota-providers.js";
3
- import type { ResolvedAuthIdentity } from "./resolved-auth-identity.js";
4
+ import { type ResolvedAuthIdentity } from "./resolved-auth-identity.js";
5
+ /** Retained (not freshly measured) entries must never carry Claude Agent saved resets. */
6
+ export declare function withoutClaudeAgentSavedResets(entries: readonly QuotaToastEntry[]): QuotaToastEntry[];
4
7
  export declare function buildQuotaProviderStateCacheKey(providerId: string, ctx: QuotaProviderContext, options?: {
5
8
  runtimeEligibleQuotaProviders?: readonly QuotaProviderDefinition[];
6
9
  resolvedAuthIdentity?: ResolvedAuthIdentity;
7
10
  }): string;
8
11
  export declare function getQuotaProviderStateCacheFilePath(providerId: string, key: string): string;
12
+ /** Private, opaque identity for server-side last-good matching; never a DTO field. */
13
+ export declare function getQuotaProviderResultScope(provider: QuotaProvider, ctx: QuotaProviderContext): Promise<string | undefined>;
9
14
  export declare function fetchQuotaProviderResult(params: {
10
15
  provider: QuotaProvider;
11
16
  ctx: QuotaProviderContext;
12
17
  ttlMs: number;
13
18
  bypassCache?: boolean;
19
+ forceRefresh?: boolean;
14
20
  }): Promise<QuotaProviderResult>;
15
21
  export type CachedProviderRead = {
16
22
  hit: true;