opencode-quota-gui 1.3.0 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/README.md +34 -20
  2. package/dist/bin/opencode-quota-gui.js +0 -0
  3. package/dist/contracts/build-identity.js +1 -1
  4. package/dist/contracts/card-order.d.ts +2 -0
  5. package/dist/contracts/card-order.js +2 -2
  6. package/dist/contracts/card-visibility.d.ts +2 -1
  7. package/dist/contracts/card-visibility.js +2 -1
  8. package/dist/contracts/dashboard.d.ts +95 -6
  9. package/dist/contracts/dashboard.js +10 -0
  10. package/dist/contracts/dto-guards.d.ts +4 -0
  11. package/dist/contracts/dto-guards.js +31 -7
  12. package/dist/contracts/guards.js +3 -1
  13. package/dist/contracts/identity.d.ts +37 -5
  14. package/dist/contracts/identity.js +43 -0
  15. package/dist/contracts/openai-quota.d.ts +3 -0
  16. package/dist/contracts/openai-quota.js +3 -0
  17. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  18. package/dist/contracts/provider-auto-resume.js +24 -0
  19. package/dist/contracts/provider-failure.d.ts +22 -0
  20. package/dist/contracts/provider-failure.js +25 -1
  21. package/dist/contracts/row-order.d.ts +13 -0
  22. package/dist/contracts/row-order.js +34 -0
  23. package/dist/contracts/row-visibility.d.ts +53 -0
  24. package/dist/contracts/row-visibility.js +130 -0
  25. package/dist/data/modelsdev-pricing.min.json +1 -1
  26. package/dist/data/modelsdev-temporal.min.json +60 -634
  27. package/dist/gui/aggregation.d.ts +29 -1
  28. package/dist/gui/aggregation.js +157 -4
  29. package/dist/gui/analytics-bridge.d.ts +8 -9
  30. package/dist/gui/analytics-bridge.js +197 -54
  31. package/dist/gui/analytics-engine.d.ts +7 -15
  32. package/dist/gui/analytics-engine.js +246 -106
  33. package/dist/gui/analytics-model.d.ts +7 -0
  34. package/dist/gui/analytics-model.js +75 -9
  35. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  36. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  37. package/dist/gui/analytics-protocol.d.ts +17 -7
  38. package/dist/gui/analytics-protocol.js +1 -0
  39. package/dist/gui/analytics-service.d.ts +10 -0
  40. package/dist/gui/analytics-service.js +30 -9
  41. package/dist/gui/analytics-state.d.ts +30 -5
  42. package/dist/gui/analytics-state.js +46 -7
  43. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  44. package/dist/gui/analytics-worker-runtime.js +9 -1
  45. package/dist/gui/analytics-worker.js +11 -0
  46. package/dist/gui/config.d.ts +3 -3
  47. package/dist/gui/config.js +77 -7
  48. package/dist/gui/identity.d.ts +6 -20
  49. package/dist/gui/identity.js +6 -54
  50. package/dist/gui/lifecycle.d.ts +5 -3
  51. package/dist/gui/lifecycle.js +3 -3
  52. package/dist/gui/primary-quota-windows.js +67 -44
  53. package/dist/gui/provider-cards.d.ts +20 -8
  54. package/dist/gui/provider-cards.js +42 -55
  55. package/dist/gui/quota-notification-detector.d.ts +29 -6
  56. package/dist/gui/quota-notification-detector.js +136 -47
  57. package/dist/gui/quota-notification-observer.d.ts +3 -4
  58. package/dist/gui/quota-notification-observer.js +73 -20
  59. package/dist/gui/quota-observation.d.ts +4 -0
  60. package/dist/gui/quota-observation.js +18 -0
  61. package/dist/gui/rpc.d.ts +2 -0
  62. package/dist/gui/rpc.js +14 -3
  63. package/dist/gui/server.js +17 -3
  64. package/dist/gui/snapshot-service.d.ts +3 -15
  65. package/dist/gui/snapshot-service.js +281 -23
  66. package/dist/gui/sources.js +179 -64
  67. package/dist/gui/temporal-status.d.ts +3 -2
  68. package/dist/gui/temporal-status.js +10 -6
  69. package/dist/gui-experimental.cjs +230 -225
  70. package/dist/lib/accounting-format.d.ts +8 -0
  71. package/dist/lib/accounting-format.js +20 -2
  72. package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
  73. package/dist/lib/alibaba-coding-plan-cli.js +539 -0
  74. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  75. package/dist/lib/anthropic-api-auth.js +27 -0
  76. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  77. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  78. package/dist/lib/anthropic-auth.d.ts +2 -3
  79. package/dist/lib/anthropic-auth.js +2 -3
  80. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  81. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  82. package/dist/lib/anthropic.d.ts +68 -14
  83. package/dist/lib/anthropic.js +1016 -363
  84. package/dist/lib/api-key-retry-after.d.ts +7 -0
  85. package/dist/lib/api-key-retry-after.js +62 -0
  86. package/dist/lib/atomic-json.d.ts +2 -0
  87. package/dist/lib/atomic-json.js +1 -0
  88. package/dist/lib/cache-observer-ingestion.d.ts +90 -0
  89. package/dist/lib/cache-observer-ingestion.js +1008 -0
  90. package/dist/lib/cache-observer.d.ts +141 -0
  91. package/dist/lib/cache-observer.js +323 -0
  92. package/dist/lib/canonical-config-lock.d.ts +9 -0
  93. package/dist/lib/canonical-config-lock.js +36 -0
  94. package/dist/lib/chutes.js +62 -51
  95. package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
  96. package/dist/lib/claude-agent-transcript-ttl.js +154 -0
  97. package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
  98. package/dist/lib/claude-agent-ttl-tracker.js +152 -0
  99. package/dist/lib/cli-show.d.ts +5 -0
  100. package/dist/lib/cli-show.js +21 -8
  101. package/dist/lib/cli-status.js +3 -6
  102. package/dist/lib/config-write-target.d.ts +1 -1
  103. package/dist/lib/config-write-target.js +5 -2
  104. package/dist/lib/config.d.ts +2 -1
  105. package/dist/lib/config.js +257 -4
  106. package/dist/lib/copilot.js +171 -86
  107. package/dist/lib/dashboard-visibility.d.ts +5 -0
  108. package/dist/lib/dashboard-visibility.js +11 -10
  109. package/dist/lib/dashboard-web-policy.d.ts +4 -4
  110. package/dist/lib/dashboard-web-policy.js +2 -2
  111. package/dist/lib/deepseek.js +25 -13
  112. package/dist/lib/display-sanitize.js +2 -0
  113. package/dist/lib/entries.d.ts +33 -1
  114. package/dist/lib/entries.js +6 -0
  115. package/dist/lib/glm-coding-plan.js +98 -74
  116. package/dist/lib/google-agy.js +90 -12
  117. package/dist/lib/google-gemini-cli.js +84 -11
  118. package/dist/lib/grouped-entry-normalization.js +1 -1
  119. package/dist/lib/http.d.ts +4 -0
  120. package/dist/lib/http.js +16 -2
  121. package/dist/lib/init-installer.js +5 -3
  122. package/dist/lib/kilo.js +37 -18
  123. package/dist/lib/kimi.js +35 -18
  124. package/dist/lib/maintainer-announcements.js +2 -2
  125. package/dist/lib/mimo.d.ts +2 -0
  126. package/dist/lib/mimo.js +36 -0
  127. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  128. package/dist/lib/modelsdev-pricing.js +457 -63
  129. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  130. package/dist/lib/modelsdev-temporal.js +16 -2
  131. package/dist/lib/nanogpt.d.ts +1 -0
  132. package/dist/lib/nanogpt.js +26 -3
  133. package/dist/lib/ollama-cloud.d.ts +1 -1
  134. package/dist/lib/ollama-cloud.js +48 -35
  135. package/dist/lib/openai.js +84 -38
  136. package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
  137. package/dist/lib/opencode-auth-sqlite.js +2 -2
  138. package/dist/lib/opencode-config-editor.d.ts +1 -0
  139. package/dist/lib/opencode-config-editor.js +6 -1
  140. package/dist/lib/opencode-config-providers.js +2 -2
  141. package/dist/lib/opencode-go.js +29 -2
  142. package/dist/lib/opencode-storage.d.ts +20 -0
  143. package/dist/lib/opencode-storage.js +89 -2
  144. package/dist/lib/opencode-version-core.d.ts +30 -0
  145. package/dist/lib/opencode-version-core.js +59 -0
  146. package/dist/lib/opencode-version.d.ts +2 -22
  147. package/dist/lib/opencode-version.js +4 -48
  148. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  149. package/dist/lib/opencode-warming-refresh.js +95 -0
  150. package/dist/lib/opencode-zen.d.ts +3 -0
  151. package/dist/lib/opencode-zen.js +71 -5
  152. package/dist/lib/provider-add.js +5 -2
  153. package/dist/lib/provider-metadata.d.ts +11 -3
  154. package/dist/lib/provider-metadata.js +20 -2
  155. package/dist/lib/provider-registration.d.ts +358 -9
  156. package/dist/lib/provider-registration.js +423 -30
  157. package/dist/lib/quota-auto-resume.d.ts +74 -0
  158. package/dist/lib/quota-auto-resume.js +539 -0
  159. package/dist/lib/quota-command-format.js +23 -10
  160. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  161. package/dist/lib/quota-exhaustion-projection.js +25 -0
  162. package/dist/lib/quota-identity.d.ts +64 -0
  163. package/dist/lib/quota-identity.js +111 -0
  164. package/dist/lib/quota-providers-remote.d.ts +2 -1
  165. package/dist/lib/quota-providers-remote.js +59 -3
  166. package/dist/lib/quota-providers.d.ts +1 -1
  167. package/dist/lib/quota-providers.js +14 -37
  168. package/dist/lib/quota-render-data.d.ts +6 -0
  169. package/dist/lib/quota-render-data.js +45 -19
  170. package/dist/lib/quota-reset-notifications.js +11 -155
  171. package/dist/lib/quota-retry-wait.d.ts +106 -5
  172. package/dist/lib/quota-retry-wait.js +301 -34
  173. package/dist/lib/quota-runtime-context.js +1 -0
  174. package/dist/lib/quota-state-codec.d.ts +2 -0
  175. package/dist/lib/quota-state-codec.js +31 -2
  176. package/dist/lib/quota-state.d.ts +8 -2
  177. package/dist/lib/quota-state.js +253 -47
  178. package/dist/lib/quota-stats.d.ts +26 -0
  179. package/dist/lib/quota-stats.js +40 -1
  180. package/dist/lib/quota-status.js +3 -51
  181. package/dist/lib/quota-surface-data.js +18 -3
  182. package/dist/lib/quota-telemetry.js +2 -2
  183. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  184. package/dist/lib/resolved-auth-identity.js +44 -0
  185. package/dist/lib/scoped-update.d.ts +1 -1
  186. package/dist/lib/state-file-lock.d.ts +26 -0
  187. package/dist/lib/state-file-lock.js +205 -0
  188. package/dist/lib/synthetic.js +65 -54
  189. package/dist/lib/toast-format-grouped.js +7 -4
  190. package/dist/lib/tui-compact-format.js +29 -16
  191. package/dist/lib/types.d.ts +51 -1
  192. package/dist/lib/types.js +17 -1
  193. package/dist/lib/xai.js +48 -22
  194. package/dist/plugin.js +328 -14
  195. package/dist/provider-logos/NOTICE.md +1 -1
  196. package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
  197. package/dist/providers/alibaba-coding-plan.js +125 -104
  198. package/dist/providers/alibaba-token-plan.js +9 -5
  199. package/dist/providers/anthropic.d.ts +16 -3
  200. package/dist/providers/anthropic.js +172 -220
  201. package/dist/providers/cache-policies.d.ts +11 -4
  202. package/dist/providers/cache-policies.js +19 -13
  203. package/dist/providers/chutes.js +2 -0
  204. package/dist/providers/claude-agent.d.ts +19 -0
  205. package/dist/providers/claude-agent.js +215 -0
  206. package/dist/providers/copilot.js +7 -4
  207. package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
  208. package/dist/providers/glm-coding-plan-provider.js +30 -23
  209. package/dist/providers/google-account-format.js +1 -0
  210. package/dist/providers/google-agy.d.ts +6 -5
  211. package/dist/providers/google-agy.js +43 -15
  212. package/dist/providers/google-gemini-cli.js +1 -0
  213. package/dist/providers/kilo.js +1 -0
  214. package/dist/providers/kimi-code.js +2 -0
  215. package/dist/providers/mimo.js +1 -0
  216. package/dist/providers/nanogpt.js +1 -0
  217. package/dist/providers/ollama-cloud.js +10 -0
  218. package/dist/providers/openai.js +24 -23
  219. package/dist/providers/opencode-go.js +10 -6
  220. package/dist/providers/opencode-zen.js +3 -1
  221. package/dist/providers/openrouter.js +1 -0
  222. package/dist/providers/quota-providers.js +16 -5
  223. package/dist/providers/registry.js +2 -0
  224. package/dist/providers/result-helpers.d.ts +6 -2
  225. package/dist/providers/result-helpers.js +7 -1
  226. package/dist/providers/synthetic.js +4 -0
  227. package/dist/providers/xai.js +9 -8
  228. package/dist/rpc.d.ts +129 -8
  229. package/dist/rpc.js +219 -14
  230. package/dist/ui/assets/{index-cDd9jUVY.css → index-6_g1FHs-.css} +1 -1
  231. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  232. package/dist/ui/assets/{popover-BGkgv9s0.js → popover-C4ZLYe9E.js} +1 -1
  233. package/dist/ui/assets/providers/claude-agent.svg +3 -0
  234. package/dist/ui/index.html +2 -2
  235. package/package.json +45 -46
  236. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
  237. package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
  238. package/dist/ui/assets/index-DLHeXYff.js +0 -9
@@ -1,19 +1,57 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readdir, readFile, rm, stat } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
+ import { CLAUDE_AGENT_RESETS_ROW_KEY } from "../contracts/openai-quota.js";
5
+ import { isTransientProviderFailureCategory } from "../contracts/provider-failure.js";
4
6
  import { writeJsonAtomic } from "./atomic-json.js";
7
+ import { QUOTA_FORCE_REFRESH } from "./entries.js";
8
+ export { QUOTA_FORCE_REFRESH } from "./entries.js";
5
9
  import { getGuiPrivateCacheDir } from "./private-state-paths.js";
6
10
  import { getQuotaProviderDisplayLabel, isLiveLocalUsageProviderId } from "./provider-metadata.js";
7
11
  import { QUOTA_PROVIDERS_AGGREGATE_ID, selectEligibleQuotaProviderDefinitions, } from "./quota-providers.js";
8
- import { cloneQuotaProviderResult, decodePersistedQuotaProviderCacheEntry, encodePersistedQuotaProviderCacheEntry, normalizeQuotaProviderResult, } from "./quota-state-codec.js";
12
+ import { cloneQuotaProviderResult, decodePersistedQuotaProviderCacheEntry, describeQuotaProviderResultViolation, encodePersistedQuotaProviderCacheEntry, normalizeQuotaProviderResult, } from "./quota-state-codec.js";
9
13
  import { updateQuotaTelemetrySnapshot } from "./quota-telemetry.js";
14
+ import { isProcessLocalResolvedAuthIdentity, } from "./resolved-auth-identity.js";
10
15
  import { getPackageVersion } from "./version.js";
11
16
  const QUOTA_PROVIDER_CACHE_PACKAGE_VERSION_FALLBACK = "unknown";
12
17
  const QUOTA_PROVIDER_CACHE_DIRNAME = "quota-provider-state";
13
18
  const QUOTA_PROVIDER_CACHE_RETENTION_MS = 24 * 60 * 60 * 1000;
14
19
  const QUOTA_PROVIDER_CACHE_PRUNE_INTERVAL_MS = 60 * 60 * 1000;
20
+ function isClaudeResetsEntry(entry) {
21
+ return "rowKey" in entry && entry.rowKey === CLAUDE_AGENT_RESETS_ROW_KEY;
22
+ }
23
+ /** Retained (not freshly measured) entries must never carry Claude Agent saved resets. */
24
+ export function withoutClaudeAgentSavedResets(entries) {
25
+ return entries.filter((entry) => !isClaudeResetsEntry(entry));
26
+ }
27
+ /**
28
+ * Cached reads must not show a saved reset past its expiry. Unknown (absent) and explicit-null
29
+ * expiries are kept; once no reset remains the row is dropped.
30
+ */
31
+ function withoutExpiredClaudeResets(result) {
32
+ if (!result.entries.some(isClaudeResetsEntry))
33
+ return result;
34
+ const nowMs = Date.now();
35
+ const entries = result.entries.flatMap((entry) => {
36
+ if (!isClaudeResetsEntry(entry) || entry.kind !== "value" || !entry.bankedResets)
37
+ return [entry];
38
+ const credits = entry.bankedResets.credits.filter((credit) => typeof credit.expiresAtIso !== "string" || Date.parse(credit.expiresAtIso) > nowMs);
39
+ const availableCount = entry.bankedResets.availableCount - (entry.bankedResets.credits.length - credits.length);
40
+ return availableCount > 0
41
+ ? [
42
+ {
43
+ ...entry,
44
+ value: `${availableCount} available`,
45
+ bankedResets: { availableCount, credits },
46
+ },
47
+ ]
48
+ : [];
49
+ });
50
+ return { ...result, entries };
51
+ }
15
52
  const inMemoryCache = new Map();
16
53
  const inFlightByKey = new Map();
54
+ const refreshByKey = new Map();
17
55
  let processLocalLatestByRuntime = new WeakMap();
18
56
  let lastPruneAtMs = 0;
19
57
  export function buildQuotaProviderStateCacheKey(providerId, ctx, options = {}) {
@@ -153,6 +191,9 @@ async function fetchValidatedProviderResult(provider, ctx, cacheContext) {
153
191
  message: "Invalid normalized provider result",
154
192
  },
155
193
  ],
194
+ statusDetails: [
195
+ { key: "normalization_violation", value: describeQuotaProviderResultViolation(fetched) },
196
+ ],
156
197
  };
157
198
  }
158
199
  async function resolveRuntimeEligibleQuotaProviders(providerId, ctx) {
@@ -181,12 +222,30 @@ async function resolveProviderCacheScope(provider, ctx, cacheContext) {
181
222
  return {};
182
223
  try {
183
224
  const resolvedAuthIdentity = await policy.resolveIdentity(ctx, cacheContext);
184
- return resolvedAuthIdentity ? { resolvedAuthIdentity } : null;
225
+ if (!resolvedAuthIdentity)
226
+ return null;
227
+ return {
228
+ resolvedAuthIdentity,
229
+ ...(isProcessLocalResolvedAuthIdentity(resolvedAuthIdentity) ? { memoryOnly: true } : {}),
230
+ };
185
231
  }
186
232
  catch {
187
233
  return null;
188
234
  }
189
235
  }
236
+ /** Private, opaque identity for server-side last-good matching; never a DTO field. */
237
+ export async function getQuotaProviderResultScope(provider, ctx) {
238
+ const runtimeEligibleQuotaProviders = await resolveRuntimeEligibleQuotaProviders(provider.id, ctx);
239
+ if (runtimeEligibleQuotaProviders === null)
240
+ return undefined;
241
+ const scope = await resolveProviderCacheScope(provider, ctx, { runtimeEligibleQuotaProviders });
242
+ if (!scope)
243
+ return undefined;
244
+ return getQuotaProviderStateCacheLocator(buildQuotaProviderStateCacheKey(provider.id, ctx, {
245
+ runtimeEligibleQuotaProviders,
246
+ resolvedAuthIdentity: scope.resolvedAuthIdentity,
247
+ }));
248
+ }
190
249
  async function isProviderCacheScopeCurrent(provider, ctx, scope) {
191
250
  if (provider.cachePolicy?.kind === "account-neutral")
192
251
  return true;
@@ -196,8 +255,7 @@ async function isProviderCacheScopeCurrent(provider, ctx, scope) {
196
255
  const runtimeEligibleQuotaProviders = await resolveRuntimeEligibleQuotaProviders(provider.id, ctx);
197
256
  if (runtimeEligibleQuotaProviders === null)
198
257
  return false;
199
- return ((await provider.cachePolicy.resolveIdentity(ctx, { runtimeEligibleQuotaProviders })) ===
200
- scope.resolvedAuthIdentity);
258
+ return ((await provider.cachePolicy.resolveIdentity(provider.cachePolicy.revalidateWithCycleCache ? ctx : { ...ctx, operationCache: undefined }, { runtimeEligibleQuotaProviders })) === scope.resolvedAuthIdentity);
201
259
  }
202
260
  catch {
203
261
  return false;
@@ -207,32 +265,41 @@ function getProcessLocalRuntimeOwner(ctx) {
207
265
  const owner = ctx.client;
208
266
  return owner && (typeof owner === "object" || typeof owner === "function") ? owner : null;
209
267
  }
268
+ function buildProcessLocalRouteKey(params) {
269
+ return buildQuotaProviderStateCacheKey(params.provider.id, params.ctx, {
270
+ runtimeEligibleQuotaProviders: params.runtimeEligibleQuotaProviders,
271
+ });
272
+ }
210
273
  function rememberProcessLocalLatest(params) {
211
- const runtimeOwner = getProcessLocalRuntimeOwner(params.ctx);
212
- if (!runtimeOwner)
274
+ const owner = getProcessLocalRuntimeOwner(params.ctx);
275
+ if (!owner)
213
276
  return;
214
- let runtimeSnapshots = processLocalLatestByRuntime.get(runtimeOwner);
215
- if (!runtimeSnapshots) {
216
- runtimeSnapshots = new WeakMap();
217
- processLocalLatestByRuntime.set(runtimeOwner, runtimeSnapshots);
277
+ let runtime = processLocalLatestByRuntime.get(owner);
278
+ if (!runtime) {
279
+ runtime = new WeakMap();
280
+ processLocalLatestByRuntime.set(owner, runtime);
218
281
  }
219
- runtimeSnapshots.set(params.provider, {
282
+ let routes = runtime.get(params.provider);
283
+ if (!routes) {
284
+ routes = new Map();
285
+ runtime.set(params.provider, routes);
286
+ }
287
+ routes.set(buildProcessLocalRouteKey(params), {
220
288
  result: cloneQuotaProviderResult(params.result),
221
289
  timestamp: Date.now(),
222
290
  });
223
291
  }
224
292
  function readProcessLocalLatest(params) {
225
- const runtimeOwner = getProcessLocalRuntimeOwner(params.ctx);
226
- if (!runtimeOwner)
227
- return { hit: false };
228
- const entry = processLocalLatestByRuntime.get(runtimeOwner)?.get(params.provider);
229
- if (!entry)
293
+ const owner = getProcessLocalRuntimeOwner(params.ctx);
294
+ if (!owner)
230
295
  return { hit: false };
231
- return {
232
- hit: true,
233
- result: cloneQuotaProviderResult(entry.result),
234
- timestamp: entry.timestamp,
235
- };
296
+ const entry = processLocalLatestByRuntime
297
+ .get(owner)
298
+ ?.get(params.provider)
299
+ ?.get(buildProcessLocalRouteKey(params));
300
+ return entry
301
+ ? { hit: true, result: cloneQuotaProviderResult(entry.result), timestamp: entry.timestamp }
302
+ : { hit: false };
236
303
  }
237
304
  function publishQuotaTelemetry(params) {
238
305
  if (!params.ctx.config.telemetryToken)
@@ -250,10 +317,20 @@ function publishQuotaTelemetry(params) {
250
317
  });
251
318
  }
252
319
  export async function fetchQuotaProviderResult(params) {
253
- const { provider, ctx, ttlMs, bypassCache = false } = params;
320
+ const { provider, ttlMs, bypassCache = false } = params;
321
+ const ctx = params.forceRefresh
322
+ ? { ...params.ctx, operationCache: new Map(params.ctx.operationCache) }
323
+ : params.ctx;
324
+ if (params.forceRefresh)
325
+ ctx.operationCache.set(QUOTA_FORCE_REFRESH, true);
254
326
  const fetchUncached = async (cacheContext = {}) => {
255
327
  const snapshot = await fetchValidatedProviderResult(provider, ctx, cacheContext);
256
- rememberProcessLocalLatest({ provider, ctx, result: snapshot });
328
+ rememberProcessLocalLatest({
329
+ provider,
330
+ ctx,
331
+ result: snapshot,
332
+ runtimeEligibleQuotaProviders: cacheContext.runtimeEligibleQuotaProviders,
333
+ });
257
334
  publishQuotaTelemetry({
258
335
  ctx,
259
336
  providerId: provider.id,
@@ -275,6 +352,32 @@ export async function fetchQuotaProviderResult(params) {
275
352
  runtimeEligibleQuotaProviders,
276
353
  resolvedAuthIdentity: scope.resolvedAuthIdentity,
277
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
+ };
362
+ if (params.forceRefresh && !isLiveLocalUsageProviderId(provider.id)) {
363
+ const existing = refreshByKey.get(key);
364
+ if (existing)
365
+ return cloneQuotaProviderResult(await existing);
366
+ const refresh = (async () => {
367
+ // An earlier ordinary request is not a refresh; wait for it to settle
368
+ // before retrying so its result cannot overwrite the newer measurement.
369
+ await inFlightByKey.get(key)?.catch(() => undefined);
370
+ return fetchQuotaProviderResult({ provider, ctx, ttlMs: 0 });
371
+ })();
372
+ refreshByKey.set(key, refresh);
373
+ try {
374
+ return cloneQuotaProviderResult(await refresh);
375
+ }
376
+ finally {
377
+ if (refreshByKey.get(key) === refresh)
378
+ refreshByKey.delete(key);
379
+ }
380
+ }
278
381
  if (isLiveLocalUsageProviderId(provider.id)) {
279
382
  const snapshot = await fetchValidatedProviderResult(provider, ctx, cacheContext);
280
383
  if (!(await isProviderCacheScopeCurrent(provider, ctx, scope))) {
@@ -308,6 +411,7 @@ export async function fetchQuotaProviderResult(params) {
308
411
  await maybePrunePersistedQuotaProviderCache(now);
309
412
  const inMemory = forceAggregateRefresh ? undefined : inMemoryCache.get(key);
310
413
  if (inMemory &&
414
+ !inMemory.stale &&
311
415
  inMemory.packageVersion === packageVersion &&
312
416
  ttlMs > 0 &&
313
417
  now - inMemory.timestamp < ttlMs) {
@@ -318,10 +422,14 @@ export async function fetchQuotaProviderResult(params) {
318
422
  result: inMemory.result,
319
423
  cacheTimestamp: inMemory.timestamp,
320
424
  });
321
- return cloneQuotaProviderResult(inMemory.result);
425
+ return withoutExpiredClaudeResets(cloneQuotaProviderResult(inMemory.result));
322
426
  }
323
427
  const inFlight = inFlightByKey.get(key);
324
428
  if (inFlight) {
429
+ if (ctx.operationCache?.get(QUOTA_FORCE_REFRESH) === true) {
430
+ await inFlight.catch(() => undefined);
431
+ return fetchQuotaProviderResult({ provider, ctx, ttlMs: 0 });
432
+ }
325
433
  const snapshot = await inFlight;
326
434
  publishQuotaTelemetry({
327
435
  ctx,
@@ -332,7 +440,7 @@ export async function fetchQuotaProviderResult(params) {
332
440
  });
333
441
  return cloneQuotaProviderResult(snapshot);
334
442
  }
335
- const persisted = forceAggregateRefresh
443
+ const persisted = forceAggregateRefresh || memoryOnly
336
444
  ? null
337
445
  : await readPersistedQuotaProviderCacheEntry({
338
446
  key,
@@ -341,7 +449,7 @@ export async function fetchQuotaProviderResult(params) {
341
449
  ttlMs,
342
450
  now,
343
451
  });
344
- if (persisted) {
452
+ if (persisted && !inMemoryCache.has(key)) {
345
453
  inMemoryCache.set(key, {
346
454
  ...persisted,
347
455
  result: cloneQuotaProviderResult(persisted.result),
@@ -353,10 +461,14 @@ export async function fetchQuotaProviderResult(params) {
353
461
  result: persisted.result,
354
462
  cacheTimestamp: persisted.timestamp,
355
463
  });
356
- return cloneQuotaProviderResult(persisted.result);
464
+ return withoutExpiredClaudeResets(cloneQuotaProviderResult(persisted.result));
357
465
  }
358
466
  const inFlightAfterDiskRead = inFlightByKey.get(key);
359
467
  if (inFlightAfterDiskRead) {
468
+ if (ctx.operationCache?.get(QUOTA_FORCE_REFRESH) === true) {
469
+ await inFlightAfterDiskRead.catch(() => undefined);
470
+ return fetchQuotaProviderResult({ provider, ctx, ttlMs: 0 });
471
+ }
360
472
  const snapshot = await inFlightAfterDiskRead;
361
473
  publishQuotaTelemetry({
362
474
  ctx,
@@ -368,12 +480,84 @@ export async function fetchQuotaProviderResult(params) {
368
480
  return cloneQuotaProviderResult(snapshot);
369
481
  }
370
482
  const fetchPromise = (async () => {
371
- const snapshot = await fetchValidatedProviderResult(provider, ctx, cacheContext);
483
+ let snapshot;
484
+ try {
485
+ snapshot = await fetchValidatedProviderResult(provider, ctx, cacheContext);
486
+ }
487
+ catch (error) {
488
+ if (ctx.operationCache?.get(QUOTA_FORCE_REFRESH) === true) {
489
+ const previous = inMemoryCache.get(key) ??
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
+ }));
500
+ if (previous && (await isProviderCacheScopeCurrent(provider, ctx, scope))) {
501
+ inMemoryCache.set(key, {
502
+ ...previous,
503
+ stale: true,
504
+ result: {
505
+ ...previous.result,
506
+ entries: previous.result.entries.filter((entry) => !isClaudeResetsEntry(entry)),
507
+ },
508
+ });
509
+ }
510
+ else {
511
+ inMemoryCache.delete(key);
512
+ }
513
+ await removePersistedCacheFile();
514
+ }
515
+ throw error;
516
+ }
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);
526
+ const previous = inMemoryCache.get(key);
527
+ if (retentionFailures.length > 0 &&
528
+ previous &&
529
+ (await isProviderCacheScopeCurrent(provider, ctx, scope))) {
530
+ const failedAccounts = new Set(retentionFailures.map((error) => error.sourceId).filter((id) => id !== undefined));
531
+ const accountsWithFreshEntries = new Set(snapshot.entries
532
+ .map((entry) => entry.accounting.sourceId)
533
+ .filter((id) => id !== undefined));
534
+ // A failed refresh proves neither eligibility nor remaining expiry, so saved resets are
535
+ // never carried over from an earlier snapshot.
536
+ const retained = previous.result.entries.filter((entry) => !isClaudeResetsEntry(entry));
537
+ const fallback = snapshot.entries.length === 0 &&
538
+ retentionFailures.some((error) => error.sourceId === undefined)
539
+ ? provider.id === "openrouter"
540
+ ? retained.filter((entry) => entry.accounting.sourceId === undefined)
541
+ : retained
542
+ : retained.filter((entry) => entry.accounting.sourceId !== undefined &&
543
+ failedAccounts.has(entry.accounting.sourceId) &&
544
+ !accountsWithFreshEntries.has(entry.accounting.sourceId));
545
+ if (fallback.length > 0) {
546
+ const stale = { ...snapshot, entries: [...snapshot.entries, ...fallback] };
547
+ inMemoryCache.set(key, {
548
+ ...previous,
549
+ stale: true,
550
+ result: cloneQuotaProviderResult(stale),
551
+ });
552
+ await removePersistedCacheFile();
553
+ return stale;
554
+ }
555
+ }
372
556
  if (!snapshot.attempted ||
373
557
  snapshot.entries.length === 0 ||
374
558
  !(await isProviderCacheScopeCurrent(provider, ctx, scope))) {
375
559
  inMemoryCache.delete(key);
376
- await safeRm(getQuotaProviderStateCacheFilePath(provider.id, key));
560
+ await removePersistedCacheFile();
377
561
  return snapshot;
378
562
  }
379
563
  const entry = encodePersistedQuotaProviderCacheEntry({
@@ -383,11 +567,17 @@ export async function fetchQuotaProviderResult(params) {
383
567
  timestamp: Date.now(),
384
568
  result: snapshot,
385
569
  });
570
+ if (snapshot.errors.some((error) => error.kind !== "intentional-filter")) {
571
+ inMemoryCache.set(key, { ...entry, stale: true, result: cloneQuotaProviderResult(snapshot) });
572
+ await removePersistedCacheFile();
573
+ return snapshot;
574
+ }
386
575
  inMemoryCache.set(key, {
387
576
  ...entry,
388
577
  result: cloneQuotaProviderResult(entry.result),
389
578
  });
390
- await writePersistedQuotaProviderCacheEntry(entry, key);
579
+ if (!memoryOnly)
580
+ await writePersistedQuotaProviderCacheEntry(entry, key);
391
581
  return snapshot;
392
582
  })().finally(() => {
393
583
  inFlightByKey.delete(key);
@@ -407,12 +597,17 @@ export async function readCachedProviderResult(params) {
407
597
  const runtimeEligibleQuotaProviders = await resolveRuntimeEligibleQuotaProviders(params.provider.id, params.ctx);
408
598
  if (runtimeEligibleQuotaProviders === null)
409
599
  return { hit: false };
600
+ if (runtimeEligibleQuotaProviders?.length === 0)
601
+ return { hit: false };
410
602
  const cacheContext = { runtimeEligibleQuotaProviders };
411
603
  const scope = await resolveProviderCacheScope(params.provider, params.ctx, cacheContext);
412
604
  if (!scope) {
605
+ if (params.provider.cachePolicy?.kind === "resolved-auth")
606
+ return { hit: false };
413
607
  return readProcessLocalLatest({
414
608
  provider: params.provider,
415
609
  ctx: params.ctx,
610
+ runtimeEligibleQuotaProviders,
416
611
  });
417
612
  }
418
613
  const key = buildQuotaProviderStateCacheKey(params.provider.id, params.ctx, {
@@ -420,6 +615,7 @@ export async function readCachedProviderResult(params) {
420
615
  resolvedAuthIdentity: scope.resolvedAuthIdentity,
421
616
  });
422
617
  const now = Date.now();
618
+ const memoryOnly = scope.memoryOnly === true;
423
619
  const inMemory = inMemoryCache.get(key);
424
620
  if (inMemory) {
425
621
  publishQuotaTelemetry({
@@ -431,35 +627,44 @@ export async function readCachedProviderResult(params) {
431
627
  });
432
628
  return {
433
629
  hit: true,
434
- result: cloneQuotaProviderResult(inMemory.result),
630
+ result: withoutExpiredClaudeResets(cloneQuotaProviderResult(inMemory.result)),
435
631
  timestamp: inMemory.timestamp,
436
632
  };
437
633
  }
438
634
  const packageVersion = await getQuotaProviderCachePackageVersion();
439
- const persisted = await readPersistedQuotaProviderCacheEntry({
440
- key,
441
- providerId: params.provider.id,
442
- packageVersion,
443
- ttlMs: params.ttlMs,
444
- now,
445
- ignoreExpiry: true,
446
- });
447
- if (persisted) {
448
- inMemoryCache.set(key, {
449
- ...persisted,
450
- result: cloneQuotaProviderResult(persisted.result),
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,
451
644
  });
645
+ if (persisted) {
646
+ if (!(await isProviderCacheScopeCurrent(params.provider, params.ctx, scope))) {
647
+ return { hit: false };
648
+ }
649
+ const current = inMemoryCache.get(key);
650
+ const selected = current ?? persisted;
651
+ if (!current) {
652
+ inMemoryCache.set(key, {
653
+ ...persisted,
654
+ result: cloneQuotaProviderResult(persisted.result),
655
+ });
656
+ }
452
657
  publishQuotaTelemetry({
453
658
  ctx: params.ctx,
454
659
  providerId: params.provider.id,
455
660
  snapshotId: key,
456
- result: persisted.result,
457
- cacheTimestamp: persisted.timestamp,
661
+ result: selected.result,
662
+ cacheTimestamp: selected.timestamp,
458
663
  });
459
664
  return {
460
665
  hit: true,
461
- result: cloneQuotaProviderResult(persisted.result),
462
- timestamp: persisted.timestamp,
666
+ result: withoutExpiredClaudeResets(cloneQuotaProviderResult(selected.result)),
667
+ timestamp: selected.timestamp,
463
668
  };
464
669
  }
465
670
  return { hit: false };
@@ -467,6 +672,7 @@ export async function readCachedProviderResult(params) {
467
672
  export function __resetQuotaStateForTests() {
468
673
  inMemoryCache.clear();
469
674
  inFlightByKey.clear();
675
+ refreshByKey.clear();
470
676
  processLocalLatestByRuntime = new WeakMap();
471
677
  lastPruneAtMs = 0;
472
678
  }
@@ -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;
@@ -4,7 +4,7 @@ import { hasCatalogModel, hasCost, hasModel, hasProvider, isModelsDevProviderId,
4
4
  import { getTemporalPolicy, resolveTemporalRates } from "./modelsdev-temporal.js";
5
5
  import { getOpenCodeDbPath } from "./opencode-db-path.js";
6
6
  import { iterAssistantMessages, iterAssistantMessagesForSession, iterAssistantMessagesForSessions, readAllSessionsIndex, SessionNotFoundError, } from "./opencode-storage.js";
7
- import { addTokenBuckets, emptyTokenBuckets, tokenBucketsFromMessage } from "./token-buckets.js";
7
+ import { addTokenBuckets, emptyTokenBuckets, tokenBucketsFromMessage, totalTokenBuckets, } from "./token-buckets.js";
8
8
  import { calculateUsdFromTokenBuckets, splitTokenBucketsByRate, tokenRateCoverage, } from "./token-cost.js";
9
9
  // Re-export for consumers
10
10
  export { SessionNotFoundError } from "./opencode-storage.js";
@@ -95,6 +95,13 @@ function parseModelIdHint(rawModelId) {
95
95
  * literal instead of deriving nearby versions.
96
96
  */
97
97
  const PROVIDER_MODEL_PRICING_ALIASES = {
98
+ // Claude Code Anthropic API family aliases, current list-price estimates only:
99
+ // https://code.claude.com/docs/en/model-config#model-aliases
100
+ anthropic: {
101
+ haiku: "claude-haiku-5-5",
102
+ sonnet: "claude-sonnet-5-5",
103
+ opus: "claude-opus-5-5",
104
+ },
98
105
  "opencode-go": {
99
106
  "deepseek-v4-flash": "deepseek-v4.1-flash",
100
107
  },
@@ -119,6 +126,7 @@ function resolveExplicitPricingAlias(providerID, ...models) {
119
126
  return null;
120
127
  }
121
128
  const SOURCE_PROVIDER_ALIASES = {
129
+ "claude-agent": "anthropic",
122
130
  cursor: "cursor",
123
131
  "cursor-acp": "cursor",
124
132
  "github-copilot": "openai",
@@ -359,6 +367,19 @@ export function resolvePricingKey(source) {
359
367
  method: "source_provider",
360
368
  };
361
369
  }
370
+ // Family aliases require an Anthropic source and its concrete price; do not
371
+ // infer another route from an alias or from an Anthropic model prefix alone.
372
+ if ((sourceProviderHint === "anthropic" || modelProviderHint === "anthropic") &&
373
+ Object.hasOwn(PROVIDER_MODEL_PRICING_ALIASES.anthropic, normalizedModel)) {
374
+ return {
375
+ ok: false,
376
+ unknown: {
377
+ sourceProviderID: srcProvider,
378
+ sourceModelID: srcModel,
379
+ reason: "missing_provider",
380
+ },
381
+ };
382
+ }
362
383
  // Only now run same-provider heuristics (free-suffix stripping, -thinking,
363
384
  // Gemini preview, Kimi/Anthropic variants).
364
385
  const fromSourceProvider = tryProvider(sourceProviderHint, "source_provider");
@@ -737,6 +758,24 @@ export function priceTokenBuckets(params) {
737
758
  },
738
759
  };
739
760
  }
761
+ /**
762
+ * models.dev remains primary. Only a row whose resolved route has no usable
763
+ * models.dev rates (unknown or unpriced) may use the host-recorded message cost,
764
+ * and only a finite positive value: zero/missing/negative/NaN stays unpriced
765
+ * and is never Free evidence. Partially priced rows keep their models.dev cost.
766
+ */
767
+ export function priceTokenBucketsWithRecordedCost(params) {
768
+ const outcome = priceTokenBuckets(params);
769
+ if (outcome.status === "priced" || outcome.status === "partial")
770
+ return outcome;
771
+ const recorded = params.recordedCostUsd;
772
+ if (typeof recorded !== "number" || !Number.isFinite(recorded) || recorded <= 0)
773
+ return outcome;
774
+ const recordedTokens = totalTokenBuckets(params.tokens);
775
+ if (!(recordedTokens > 0))
776
+ return outcome;
777
+ return { status: "recorded_cost", costUsd: recorded, recordedTokens };
778
+ }
740
779
  function compareSessionCreatedAt(a, b) {
741
780
  const aCreated = typeof a.time?.created === "number" && Number.isFinite(a.time.created)
742
781
  ? a.time.created