opencode-quota-gui 1.3.1 → 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 (155) hide show
  1. package/README.md +16 -12
  2. package/dist/contracts/build-identity.js +1 -1
  3. package/dist/contracts/card-order.d.ts +2 -0
  4. package/dist/contracts/card-order.js +2 -2
  5. package/dist/contracts/card-visibility.d.ts +2 -1
  6. package/dist/contracts/card-visibility.js +2 -1
  7. package/dist/contracts/dashboard.d.ts +87 -5
  8. package/dist/contracts/dashboard.js +10 -0
  9. package/dist/contracts/dto-guards.d.ts +4 -0
  10. package/dist/contracts/dto-guards.js +29 -7
  11. package/dist/contracts/guards.js +3 -1
  12. package/dist/contracts/identity.d.ts +37 -5
  13. package/dist/contracts/identity.js +43 -0
  14. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  15. package/dist/contracts/provider-auto-resume.js +24 -0
  16. package/dist/contracts/provider-failure.d.ts +22 -0
  17. package/dist/contracts/provider-failure.js +25 -1
  18. package/dist/contracts/row-order.d.ts +13 -0
  19. package/dist/contracts/row-order.js +34 -0
  20. package/dist/contracts/row-visibility.d.ts +53 -0
  21. package/dist/contracts/row-visibility.js +130 -0
  22. package/dist/data/modelsdev-pricing.min.json +1 -1
  23. package/dist/data/modelsdev-temporal.min.json +3 -634
  24. package/dist/gui/aggregation.d.ts +29 -1
  25. package/dist/gui/aggregation.js +157 -4
  26. package/dist/gui/analytics-bridge.d.ts +8 -9
  27. package/dist/gui/analytics-bridge.js +197 -54
  28. package/dist/gui/analytics-engine.d.ts +7 -15
  29. package/dist/gui/analytics-engine.js +246 -106
  30. package/dist/gui/analytics-model.d.ts +7 -0
  31. package/dist/gui/analytics-model.js +75 -9
  32. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  33. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  34. package/dist/gui/analytics-protocol.d.ts +17 -7
  35. package/dist/gui/analytics-protocol.js +1 -0
  36. package/dist/gui/analytics-service.d.ts +10 -0
  37. package/dist/gui/analytics-service.js +30 -9
  38. package/dist/gui/analytics-state.d.ts +30 -5
  39. package/dist/gui/analytics-state.js +46 -7
  40. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  41. package/dist/gui/analytics-worker-runtime.js +9 -1
  42. package/dist/gui/analytics-worker.js +11 -0
  43. package/dist/gui/config.d.ts +2 -2
  44. package/dist/gui/config.js +46 -5
  45. package/dist/gui/identity.d.ts +6 -20
  46. package/dist/gui/identity.js +6 -54
  47. package/dist/gui/primary-quota-windows.js +55 -34
  48. package/dist/gui/provider-cards.d.ts +12 -8
  49. package/dist/gui/provider-cards.js +12 -53
  50. package/dist/gui/quota-notification-detector.d.ts +25 -2
  51. package/dist/gui/quota-notification-detector.js +60 -5
  52. package/dist/gui/quota-notification-observer.d.ts +1 -1
  53. package/dist/gui/quota-notification-observer.js +5 -1
  54. package/dist/gui/quota-observation.d.ts +4 -0
  55. package/dist/gui/quota-observation.js +18 -0
  56. package/dist/gui/rpc.js +3 -0
  57. package/dist/gui/server.js +6 -1
  58. package/dist/gui/snapshot-service.d.ts +3 -17
  59. package/dist/gui/snapshot-service.js +159 -9
  60. package/dist/gui/sources.js +84 -11
  61. package/dist/gui/temporal-status.d.ts +3 -2
  62. package/dist/gui/temporal-status.js +10 -6
  63. package/dist/gui-experimental.cjs +228 -228
  64. package/dist/lib/accounting-format.d.ts +8 -0
  65. package/dist/lib/accounting-format.js +12 -2
  66. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  67. package/dist/lib/anthropic-api-auth.js +27 -0
  68. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  69. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  70. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  71. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  72. package/dist/lib/anthropic.d.ts +22 -4
  73. package/dist/lib/anthropic.js +498 -180
  74. package/dist/lib/cache-observer-ingestion.js +27 -0
  75. package/dist/lib/cache-observer.d.ts +3 -0
  76. package/dist/lib/cache-observer.js +9 -3
  77. package/dist/lib/cli-show.d.ts +5 -0
  78. package/dist/lib/cli-show.js +16 -5
  79. package/dist/lib/cli-status.js +3 -6
  80. package/dist/lib/config.d.ts +1 -1
  81. package/dist/lib/config.js +64 -2
  82. package/dist/lib/dashboard-visibility.d.ts +5 -0
  83. package/dist/lib/dashboard-visibility.js +11 -10
  84. package/dist/lib/display-sanitize.js +1 -0
  85. package/dist/lib/entries.d.ts +10 -1
  86. package/dist/lib/entries.js +4 -0
  87. package/dist/lib/grouped-entry-normalization.js +1 -1
  88. package/dist/lib/maintainer-announcements.js +2 -2
  89. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  90. package/dist/lib/modelsdev-pricing.js +457 -63
  91. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  92. package/dist/lib/modelsdev-temporal.js +16 -2
  93. package/dist/lib/opencode-config-providers.js +2 -2
  94. package/dist/lib/opencode-storage.d.ts +20 -0
  95. package/dist/lib/opencode-storage.js +89 -2
  96. package/dist/lib/opencode-version-core.d.ts +7 -0
  97. package/dist/lib/opencode-version-core.js +10 -0
  98. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  99. package/dist/lib/opencode-warming-refresh.js +95 -0
  100. package/dist/lib/provider-metadata.d.ts +11 -3
  101. package/dist/lib/provider-metadata.js +20 -2
  102. package/dist/lib/provider-registration.d.ts +342 -3
  103. package/dist/lib/provider-registration.js +409 -27
  104. package/dist/lib/quota-auto-resume.d.ts +74 -0
  105. package/dist/lib/quota-auto-resume.js +539 -0
  106. package/dist/lib/quota-command-format.js +22 -9
  107. package/dist/lib/quota-identity.d.ts +64 -0
  108. package/dist/lib/quota-identity.js +111 -0
  109. package/dist/lib/quota-providers.js +2 -2
  110. package/dist/lib/quota-render-data.js +2 -2
  111. package/dist/lib/quota-reset-notifications.js +11 -155
  112. package/dist/lib/quota-retry-wait.d.ts +106 -5
  113. package/dist/lib/quota-retry-wait.js +301 -34
  114. package/dist/lib/quota-runtime-context.js +1 -0
  115. package/dist/lib/quota-state-codec.d.ts +2 -0
  116. package/dist/lib/quota-state-codec.js +14 -1
  117. package/dist/lib/quota-state.d.ts +1 -1
  118. package/dist/lib/quota-state.js +60 -28
  119. package/dist/lib/quota-stats.d.ts +26 -0
  120. package/dist/lib/quota-stats.js +19 -1
  121. package/dist/lib/quota-surface-data.js +18 -3
  122. package/dist/lib/quota-telemetry.js +2 -2
  123. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  124. package/dist/lib/resolved-auth-identity.js +44 -0
  125. package/dist/lib/state-file-lock.d.ts +26 -0
  126. package/dist/lib/state-file-lock.js +205 -0
  127. package/dist/lib/toast-format-grouped.js +7 -4
  128. package/dist/lib/tui-compact-format.js +29 -16
  129. package/dist/lib/types.d.ts +20 -0
  130. package/dist/lib/types.js +4 -1
  131. package/dist/plugin.js +67 -1
  132. package/dist/providers/alibaba-coding-plan.js +21 -3
  133. package/dist/providers/alibaba-token-plan.js +9 -5
  134. package/dist/providers/anthropic.d.ts +6 -2
  135. package/dist/providers/anthropic.js +123 -14
  136. package/dist/providers/chutes.js +2 -0
  137. package/dist/providers/claude-agent.js +24 -5
  138. package/dist/providers/copilot.js +5 -4
  139. package/dist/providers/glm-coding-plan-provider.js +30 -23
  140. package/dist/providers/ollama-cloud.js +10 -0
  141. package/dist/providers/openai.js +24 -23
  142. package/dist/providers/opencode-go.js +7 -6
  143. package/dist/providers/opencode-zen.js +1 -1
  144. package/dist/providers/result-helpers.d.ts +4 -2
  145. package/dist/providers/result-helpers.js +5 -1
  146. package/dist/providers/synthetic.js +4 -0
  147. package/dist/providers/xai.js +9 -8
  148. package/dist/rpc.d.ts +8 -0
  149. package/dist/rpc.js +15 -2
  150. package/dist/ui/assets/{index-BcueIm3Z.css → index-6_g1FHs-.css} +1 -1
  151. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  152. package/dist/ui/assets/{popover-4bFSvRZ7.js → popover-C4ZLYe9E.js} +1 -1
  153. package/dist/ui/index.html +2 -2
  154. package/package.json +3 -3
  155. package/dist/ui/assets/index-C6qRSoh8.js +0 -10
@@ -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";
@@ -274,8 +274,10 @@ function isQuotaToastError(value) {
274
274
  "kind",
275
275
  "sourceId",
276
276
  "retryAtMs",
277
+ "attemptOutcome",
277
278
  ]) &&
278
279
  typeof value.label === "string" &&
280
+ (value.attemptOutcome === undefined || isQuotaAttemptOutcome(value.attemptOutcome)) &&
279
281
  typeof value.message === "string" &&
280
282
  (value.retryAtMs === undefined ||
281
283
  (Number.isSafeInteger(value.retryAtMs) && value.retryAtMs >= 0)) &&
@@ -426,6 +428,17 @@ function isQuotaProviderResult(value, safeText) {
426
428
  (isDenseArray(value.rawDetails) && value.rawDetails.every(isQuotaProviderStatusDetail))) &&
427
429
  (value.presentation === undefined || isQuotaProviderPresentation(value.presentation)));
428
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
+ }
429
442
  export function normalizeQuotaProviderResult(value) {
430
443
  if (!isQuotaProviderResult(value, false))
431
444
  return null;
@@ -1,7 +1,7 @@
1
1
  import type { QuotaProvider, QuotaProviderContext, QuotaProviderResult, QuotaToastEntry } from "./entries.js";
2
2
  export { QUOTA_FORCE_REFRESH } from "./entries.js";
3
3
  import type { QuotaProviderDefinition } from "./quota-providers.js";
4
- import type { ResolvedAuthIdentity } from "./resolved-auth-identity.js";
4
+ import { type ResolvedAuthIdentity } from "./resolved-auth-identity.js";
5
5
  /** Retained (not freshly measured) entries must never carry Claude Agent saved resets. */
6
6
  export declare function withoutClaudeAgentSavedResets(entries: readonly QuotaToastEntry[]): QuotaToastEntry[];
7
7
  export declare function buildQuotaProviderStateCacheKey(providerId: string, ctx: QuotaProviderContext, options?: {
@@ -2,14 +2,16 @@ import { createHash } from "node:crypto";
2
2
  import { readdir, readFile, rm, stat } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { CLAUDE_AGENT_RESETS_ROW_KEY } from "../contracts/openai-quota.js";
5
+ import { isTransientProviderFailureCategory } from "../contracts/provider-failure.js";
5
6
  import { writeJsonAtomic } from "./atomic-json.js";
6
7
  import { QUOTA_FORCE_REFRESH } from "./entries.js";
7
8
  export { QUOTA_FORCE_REFRESH } from "./entries.js";
8
9
  import { getGuiPrivateCacheDir } from "./private-state-paths.js";
9
10
  import { getQuotaProviderDisplayLabel, isLiveLocalUsageProviderId } from "./provider-metadata.js";
10
11
  import { QUOTA_PROVIDERS_AGGREGATE_ID, selectEligibleQuotaProviderDefinitions, } from "./quota-providers.js";
11
- import { cloneQuotaProviderResult, decodePersistedQuotaProviderCacheEntry, encodePersistedQuotaProviderCacheEntry, normalizeQuotaProviderResult, } from "./quota-state-codec.js";
12
+ import { cloneQuotaProviderResult, decodePersistedQuotaProviderCacheEntry, describeQuotaProviderResultViolation, encodePersistedQuotaProviderCacheEntry, normalizeQuotaProviderResult, } from "./quota-state-codec.js";
12
13
  import { updateQuotaTelemetrySnapshot } from "./quota-telemetry.js";
14
+ import { isProcessLocalResolvedAuthIdentity, } from "./resolved-auth-identity.js";
13
15
  import { getPackageVersion } from "./version.js";
14
16
  const QUOTA_PROVIDER_CACHE_PACKAGE_VERSION_FALLBACK = "unknown";
15
17
  const QUOTA_PROVIDER_CACHE_DIRNAME = "quota-provider-state";
@@ -189,6 +191,9 @@ async function fetchValidatedProviderResult(provider, ctx, cacheContext) {
189
191
  message: "Invalid normalized provider result",
190
192
  },
191
193
  ],
194
+ statusDetails: [
195
+ { key: "normalization_violation", value: describeQuotaProviderResultViolation(fetched) },
196
+ ],
192
197
  };
193
198
  }
194
199
  async function resolveRuntimeEligibleQuotaProviders(providerId, ctx) {
@@ -217,7 +222,12 @@ async function resolveProviderCacheScope(provider, ctx, cacheContext) {
217
222
  return {};
218
223
  try {
219
224
  const resolvedAuthIdentity = await policy.resolveIdentity(ctx, cacheContext);
220
- return resolvedAuthIdentity ? { resolvedAuthIdentity } : null;
225
+ if (!resolvedAuthIdentity)
226
+ return null;
227
+ return {
228
+ resolvedAuthIdentity,
229
+ ...(isProcessLocalResolvedAuthIdentity(resolvedAuthIdentity) ? { memoryOnly: true } : {}),
230
+ };
221
231
  }
222
232
  catch {
223
233
  return null;
@@ -342,6 +352,13 @@ export async function fetchQuotaProviderResult(params) {
342
352
  runtimeEligibleQuotaProviders,
343
353
  resolvedAuthIdentity: scope.resolvedAuthIdentity,
344
354
  });
355
+ // A process-local identity (Windows) may key only the in-memory tier: the value is not stable
356
+ // across restarts, so it must never name a persisted file.
357
+ const memoryOnly = scope.memoryOnly === true;
358
+ const removePersistedCacheFile = async () => {
359
+ if (!memoryOnly)
360
+ await safeRm(getQuotaProviderStateCacheFilePath(provider.id, key));
361
+ };
345
362
  if (params.forceRefresh && !isLiveLocalUsageProviderId(provider.id)) {
346
363
  const existing = refreshByKey.get(key);
347
364
  if (existing)
@@ -423,7 +440,7 @@ export async function fetchQuotaProviderResult(params) {
423
440
  });
424
441
  return cloneQuotaProviderResult(snapshot);
425
442
  }
426
- const persisted = forceAggregateRefresh
443
+ const persisted = forceAggregateRefresh || memoryOnly
427
444
  ? null
428
445
  : await readPersistedQuotaProviderCacheEntry({
429
446
  key,
@@ -470,14 +487,16 @@ export async function fetchQuotaProviderResult(params) {
470
487
  catch (error) {
471
488
  if (ctx.operationCache?.get(QUOTA_FORCE_REFRESH) === true) {
472
489
  const previous = inMemoryCache.get(key) ??
473
- (await readPersistedQuotaProviderCacheEntry({
474
- key,
475
- providerId: provider.id,
476
- packageVersion,
477
- ttlMs,
478
- now: Date.now(),
479
- ignoreExpiry: true,
480
- }));
490
+ (memoryOnly
491
+ ? null
492
+ : await readPersistedQuotaProviderCacheEntry({
493
+ key,
494
+ providerId: provider.id,
495
+ packageVersion,
496
+ ttlMs,
497
+ now: Date.now(),
498
+ ignoreExpiry: true,
499
+ }));
481
500
  if (previous && (await isProviderCacheScopeCurrent(provider, ctx, scope))) {
482
501
  inMemoryCache.set(key, {
483
502
  ...previous,
@@ -491,23 +510,32 @@ export async function fetchQuotaProviderResult(params) {
491
510
  else {
492
511
  inMemoryCache.delete(key);
493
512
  }
494
- await safeRm(getQuotaProviderStateCacheFilePath(provider.id, key));
513
+ await removePersistedCacheFile();
495
514
  }
496
515
  throw error;
497
516
  }
498
- const rateLimited = snapshot.errors.filter((error) => error.retryAtMs !== undefined);
517
+ const failures = snapshot.errors.filter((error) => error.kind !== "intentional-filter");
518
+ const allFailuresTransient = failures.length > 0 &&
519
+ failures.every((error) => isTransientProviderFailureCategory(error.failureCategory));
520
+ // A rate-limited account and a transient provider failure both prove nothing about that
521
+ // account's quota, so its last measurement stays. A credentials failure (or a mixed result
522
+ // that includes one) still drops it: the account itself may have changed.
523
+ const retentionFailures = allFailuresTransient
524
+ ? failures
525
+ : snapshot.errors.filter((error) => error.retryAtMs !== undefined);
499
526
  const previous = inMemoryCache.get(key);
500
- if (rateLimited.length > 0 &&
527
+ if (retentionFailures.length > 0 &&
501
528
  previous &&
502
529
  (await isProviderCacheScopeCurrent(provider, ctx, scope))) {
503
- const failedAccounts = new Set(rateLimited.map((error) => error.sourceId).filter((id) => id !== undefined));
530
+ const failedAccounts = new Set(retentionFailures.map((error) => error.sourceId).filter((id) => id !== undefined));
504
531
  const accountsWithFreshEntries = new Set(snapshot.entries
505
532
  .map((entry) => entry.accounting.sourceId)
506
533
  .filter((id) => id !== undefined));
507
534
  // A failed refresh proves neither eligibility nor remaining expiry, so saved resets are
508
535
  // never carried over from an earlier snapshot.
509
536
  const retained = previous.result.entries.filter((entry) => !isClaudeResetsEntry(entry));
510
- const fallback = snapshot.entries.length === 0 && rateLimited.some((error) => error.sourceId === undefined)
537
+ const fallback = snapshot.entries.length === 0 &&
538
+ retentionFailures.some((error) => error.sourceId === undefined)
511
539
  ? provider.id === "openrouter"
512
540
  ? retained.filter((entry) => entry.accounting.sourceId === undefined)
513
541
  : retained
@@ -521,7 +549,7 @@ export async function fetchQuotaProviderResult(params) {
521
549
  stale: true,
522
550
  result: cloneQuotaProviderResult(stale),
523
551
  });
524
- await safeRm(getQuotaProviderStateCacheFilePath(provider.id, key));
552
+ await removePersistedCacheFile();
525
553
  return stale;
526
554
  }
527
555
  }
@@ -529,7 +557,7 @@ export async function fetchQuotaProviderResult(params) {
529
557
  snapshot.entries.length === 0 ||
530
558
  !(await isProviderCacheScopeCurrent(provider, ctx, scope))) {
531
559
  inMemoryCache.delete(key);
532
- await safeRm(getQuotaProviderStateCacheFilePath(provider.id, key));
560
+ await removePersistedCacheFile();
533
561
  return snapshot;
534
562
  }
535
563
  const entry = encodePersistedQuotaProviderCacheEntry({
@@ -541,14 +569,15 @@ export async function fetchQuotaProviderResult(params) {
541
569
  });
542
570
  if (snapshot.errors.some((error) => error.kind !== "intentional-filter")) {
543
571
  inMemoryCache.set(key, { ...entry, stale: true, result: cloneQuotaProviderResult(snapshot) });
544
- await safeRm(getQuotaProviderStateCacheFilePath(provider.id, key));
572
+ await removePersistedCacheFile();
545
573
  return snapshot;
546
574
  }
547
575
  inMemoryCache.set(key, {
548
576
  ...entry,
549
577
  result: cloneQuotaProviderResult(entry.result),
550
578
  });
551
- await writePersistedQuotaProviderCacheEntry(entry, key);
579
+ if (!memoryOnly)
580
+ await writePersistedQuotaProviderCacheEntry(entry, key);
552
581
  return snapshot;
553
582
  })().finally(() => {
554
583
  inFlightByKey.delete(key);
@@ -586,6 +615,7 @@ export async function readCachedProviderResult(params) {
586
615
  resolvedAuthIdentity: scope.resolvedAuthIdentity,
587
616
  });
588
617
  const now = Date.now();
618
+ const memoryOnly = scope.memoryOnly === true;
589
619
  const inMemory = inMemoryCache.get(key);
590
620
  if (inMemory) {
591
621
  publishQuotaTelemetry({
@@ -602,14 +632,16 @@ export async function readCachedProviderResult(params) {
602
632
  };
603
633
  }
604
634
  const packageVersion = await getQuotaProviderCachePackageVersion();
605
- const persisted = await readPersistedQuotaProviderCacheEntry({
606
- key,
607
- providerId: params.provider.id,
608
- packageVersion,
609
- ttlMs: params.ttlMs,
610
- now,
611
- ignoreExpiry: true,
612
- });
635
+ const persisted = memoryOnly
636
+ ? null
637
+ : await readPersistedQuotaProviderCacheEntry({
638
+ key,
639
+ providerId: params.provider.id,
640
+ packageVersion,
641
+ ttlMs: params.ttlMs,
642
+ now,
643
+ ignoreExpiry: true,
644
+ });
613
645
  if (persisted) {
614
646
  if (!(await isProviderCacheScopeCurrent(params.provider, params.ctx, scope))) {
615
647
  return { hit: false };
@@ -207,6 +207,32 @@ export declare function priceTokenBuckets(params: {
207
207
  atMs?: number;
208
208
  cache?: Map<string, PricingResolution>;
209
209
  }): TokenPricingOutcome;
210
+ /**
211
+ * A message priced from OpenCode's recorded cost instead of models.dev. The
212
+ * source stays distinguishable so the estimate can say so and so the unpriced
213
+ * kicker still prefers models.dev once it has a price.
214
+ */
215
+ type RecordedCostPricingOutcome = {
216
+ status: "recorded_cost";
217
+ costUsd: number;
218
+ recordedTokens: number;
219
+ };
220
+ export type TokenPricingWithRecordedCostOutcome = TokenPricingOutcome | RecordedCostPricingOutcome;
221
+ /**
222
+ * models.dev remains primary. Only a row whose resolved route has no usable
223
+ * models.dev rates (unknown or unpriced) may use the host-recorded message cost,
224
+ * and only a finite positive value: zero/missing/negative/NaN stays unpriced
225
+ * and is never Free evidence. Partially priced rows keep their models.dev cost.
226
+ */
227
+ export declare function priceTokenBucketsWithRecordedCost(params: {
228
+ providerID?: string | null;
229
+ modelID?: string | null;
230
+ tokens: TokenBuckets;
231
+ recordedCostUsd?: number;
232
+ contextTokens?: number;
233
+ atMs?: number;
234
+ cache?: Map<string, PricingResolution>;
235
+ }): TokenPricingWithRecordedCostOutcome;
210
236
  export declare function resolveSessionTree(rootSessionID: string): Promise<SessionTreeNode[]>;
211
237
  export declare function aggregateUsage(params: {
212
238
  sinceMs?: number;