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
package/dist/plugin.js CHANGED
@@ -10,12 +10,15 @@ import { Plugin } from "@opencode/plugin";
10
10
  import { startDashboard } from "./gui/lifecycle.js";
11
11
  import { scrubLogReason } from "./gui/log.js";
12
12
  import { registerDashboardRpc } from "./gui/rpc.js";
13
+ import { observeAnthropicApiResponse } from "./lib/anthropic-api-rate-limits.js";
13
14
  import { projectOpenCodeCacheObserverEvent } from "./lib/cache-observer-ingestion.js";
14
15
  import { readClaudeObservedTtl } from "./lib/claude-agent-transcript-ttl.js";
15
16
  import { createClaudeAgentTtlTracker } from "./lib/claude-agent-ttl-tracker.js";
16
17
  import { resolveOpenCodeLocationRoots } from "./lib/config-file-utils.js";
17
18
  import { bindCredentialSource, createIntegrationCredentialSource, notifyCredentialsChanged, scrubCredentialErrorText, } from "./lib/opencode-auth.js";
18
- import { resolveQuotaResetRetryDelayMs } from "./lib/quota-retry-wait.js";
19
+ import { OpencodeWarmingRefreshTracker } from "./lib/opencode-warming-refresh.js";
20
+ import { createQuotaAutoResumption } from "./lib/quota-auto-resume.js";
21
+ import { collectQuotaWindows, probeQuotaForModelState, resolveQuotaResetRetryDelayMs, } from "./lib/quota-retry-wait.js";
19
22
  /** An error as one line that is safe to log: tokens redacted, at most 120 characters. */
20
23
  function logReason(error) {
21
24
  return scrubCredentialErrorText(error instanceof Error ? error.message : String(error));
@@ -54,6 +57,52 @@ export const QuotaToastPlugin = Plugin.define({
54
57
  console.warn(`[opencode-quota-gui] retry hook failed: ${logReason(error)}`);
55
58
  }
56
59
  });
60
+ // With autoResumeOnQuotaRecovery on (default off), a session that terminally failed on a
61
+ // provider quota limit gets one `continue` prompt after the failed route's exhausted window
62
+ // is observed as reset for the same verified identity. In-process timers only: a plugin
63
+ // restart drops a pending resume.
64
+ const autoResume = createQuotaAutoResumption({
65
+ session: ctx.session,
66
+ probe: async (model) => {
67
+ const result = await probeQuotaForModelState(retryHost, model, (config) => config.autoResumeOnQuotaRecovery, { includeProviderScope: true });
68
+ if (result.state === "disabled")
69
+ return { kind: "disabled" };
70
+ if (result.state === "unsupported")
71
+ return { kind: "unsupported" };
72
+ if (result.state === "unavailable")
73
+ return { kind: "absent" };
74
+ const collection = collectQuotaWindows(result.probe.providerResults.map((entry) => entry.result), result.probe.binding, {
75
+ primaryAccountOnly: true,
76
+ // The controller keeps this model-scoped row only for a Fable failed model.
77
+ includeNamedWindows: ["named:Fable weekly"],
78
+ });
79
+ return collection ? { kind: "collection", collection } : { kind: "absent" };
80
+ },
81
+ log: (message) => console.warn(`[opencode-quota-gui] ${message}`),
82
+ });
83
+ // A user-submitted prompt suppresses a pending auto-resume; our own prompt carries the marker.
84
+ await ctx.session.hook("prompt", (event) => {
85
+ try {
86
+ autoResume.onPrompt(event);
87
+ }
88
+ catch {
89
+ // Pending-resume tracking must never interfere with a prompt.
90
+ }
91
+ });
92
+ const warming = new OpencodeWarmingRefreshTracker();
93
+ await ctx.session.hook("model.request", (event) => {
94
+ try {
95
+ warming.onModelRequest(event, Date.now());
96
+ }
97
+ catch {
98
+ // Observation must never interfere with a request.
99
+ }
100
+ });
101
+ // Read-only and synchronous: records allowlisted rate-limit headers from API-key Messages
102
+ // responses for the Anthropic API card. It never alters, delays or throws into the request.
103
+ await ctx.session.hook("http.response", (event) => {
104
+ observeAnthropicApiResponse({ request: event.request, response: event.response });
105
+ });
57
106
  // Owner-approved per-session approximation (not per-request proof): the host shares no
58
107
  // per-invocation id between `model.request` and `session.step.started`, and connections
59
108
  // rarely change, so the active OpenAI connection METHOD is sampled once per session — on
@@ -250,6 +299,12 @@ export const QuotaToastPlugin = Plugin.define({
250
299
  if (event.type === "credential.updated" || event.type === "credential.switched") {
251
300
  notifyCredentialsChanged();
252
301
  }
302
+ try {
303
+ autoResume.handleEvent(event);
304
+ }
305
+ catch {
306
+ // Resume tracking is observation only; never break the host event stream.
307
+ }
253
308
  // The Started event's model identity is available before invocation completion. Do not
254
309
  // enrich it from model.list here: that mutable catalog may no longer match dispatch.
255
310
  const sessionID = event.data?.sessionID;
@@ -277,6 +332,16 @@ export const QuotaToastPlugin = Plugin.define({
277
332
  emitCacheObserverEvent(cacheObserverEvent, event.created);
278
333
  }
279
334
  claudeTtl.observe(event, cacheObserverEvent);
335
+ if (event.type === "session.step.started")
336
+ warming.onStepStarted(event);
337
+ else if (event.type === "session.step.ended")
338
+ warming.onStepEnded(event);
339
+ else if (event.type === "session.usage.updated") {
340
+ const refresh = warming.onUsageUpdated(event);
341
+ if (refresh !== undefined) {
342
+ emitCacheObserverEvent({ type: "session.cache.warming", data: refresh }, Date.now());
343
+ }
344
+ }
280
345
  }
281
346
  if (signal.aborted)
282
347
  return;
@@ -340,6 +405,7 @@ export const QuotaToastPlugin = Plugin.define({
340
405
  }
341
406
  return async () => {
342
407
  hostEvents.abort();
408
+ autoResume.dispose();
343
409
  claudeTtl.dispose();
344
410
  openaiMethodBySession.clear();
345
411
  pendingCacheObserverEvents.length = 0;
@@ -1,6 +1,7 @@
1
1
  import { isAlibabaModelId } from "../lib/alibaba-auth.js";
2
2
  import { queryAlibabaCodingPlanQuota, } from "../lib/alibaba-coding-plan-cli.js";
3
3
  import { sanitizeSingleLineDisplayText } from "../lib/display-sanitize.js";
4
+ import { windowSemantic } from "../lib/entries.js";
4
5
  import { isCanonicalProviderAvailable } from "../lib/provider-availability.js";
5
6
  import { attemptedErrorResult, attemptedResult, statusDetailsFromRecord, withStatusDetails, } from "./result-helpers.js";
6
7
  const CLI_LABEL = "Bailian CLI";
@@ -26,6 +27,7 @@ function windowEntry(window, params) {
26
27
  name,
27
28
  group: params.group,
28
29
  label: params.label,
30
+ semantic: windowSemantic(params.semanticWindow),
29
31
  ...(hasCounts ? { right: `${window.used}/${window.total}` } : {}),
30
32
  percentRemaining: Math.max(0, Math.min(100, (1 - window.percentage) * 100)),
31
33
  ...resetTime,
@@ -38,6 +40,7 @@ function windowEntry(window, params) {
38
40
  name,
39
41
  group: params.group,
40
42
  label: params.label,
43
+ semantic: windowSemantic(params.semanticWindow),
41
44
  value: "Quota details unavailable",
42
45
  ...resetTime,
43
46
  };
@@ -50,9 +53,24 @@ function entriesFromUsage(result) {
50
53
  : "";
51
54
  const group = `Alibaba Coding Plan${instanceType ? ` (${instanceType})` : ""} (CLI)`;
52
55
  return [
53
- windowEntry(result.usage.fiveHour, { group, suffix: "5h", label: "5h:" }),
54
- windowEntry(result.usage.weekly, { group, suffix: "Weekly", label: "Weekly:" }),
55
- windowEntry(result.usage.monthly, { group, suffix: "Monthly", label: "Monthly:" }),
56
+ windowEntry(result.usage.fiveHour, {
57
+ group,
58
+ suffix: "5h",
59
+ label: "5h:",
60
+ semanticWindow: "five_hour",
61
+ }),
62
+ windowEntry(result.usage.weekly, {
63
+ group,
64
+ suffix: "Weekly",
65
+ label: "Weekly:",
66
+ semanticWindow: "week",
67
+ }),
68
+ windowEntry(result.usage.monthly, {
69
+ group,
70
+ suffix: "Monthly",
71
+ label: "Monthly:",
72
+ semanticWindow: "month",
73
+ }),
56
74
  ].filter((entry) => entry !== undefined);
57
75
  }
58
76
  function failureCategoryFor(kind) {
@@ -1,4 +1,5 @@
1
1
  import { isAlibabaTokenPlanSupportedPlatform, queryAlibabaTokenPlanQuota, } from "../lib/alibaba-token-plan.js";
2
+ import { windowSemantic } from "../lib/entries.js";
2
3
  import { isCanonicalProviderAvailable } from "../lib/provider-availability.js";
3
4
  import { modelProviderMatchesRuntimeId } from "../lib/provider-model-matching.js";
4
5
  import { REQUEST_TIMEOUT_MS } from "../lib/types.js";
@@ -10,12 +11,13 @@ const ACCOUNTING = {
10
11
  ownership: "maintained",
11
12
  authority: "provider_reported",
12
13
  };
13
- function windowEntry(window, suffix, label) {
14
+ function windowEntry(window, suffix, label, semanticWindow) {
14
15
  return {
15
16
  accounting: { ...ACCOUNTING },
16
17
  name: `${GROUP} ${suffix}`,
17
18
  group: GROUP,
18
19
  label,
20
+ semantic: windowSemantic(semanticWindow),
19
21
  percentRemaining: window.percentRemaining,
20
22
  ...(window.resetTimeIso ? { resetTimeIso: window.resetTimeIso } : {}),
21
23
  };
@@ -56,10 +58,12 @@ function alibabaFailureCategory(kind) {
56
58
  function mapClosedResult(result) {
57
59
  if (result.ok) {
58
60
  const entries = [];
59
- if (result.fiveHour)
60
- entries.push(windowEntry(result.fiveHour, "5h", "5h:"));
61
- if (result.weekly)
62
- entries.push(windowEntry(result.weekly, "Weekly", "Weekly:"));
61
+ if (result.fiveHour) {
62
+ entries.push(windowEntry(result.fiveHour, "5h", "5h:", "five_hour"));
63
+ }
64
+ if (result.weekly) {
65
+ entries.push(windowEntry(result.weekly, "Weekly", "Weekly:", "week"));
66
+ }
63
67
  return attemptedResult(entries);
64
68
  }
65
69
  if (result.error.kind === "unsupported_platform") {
@@ -1,7 +1,9 @@
1
1
  /**
2
- * Anthropic provider: OpenCode's own Anthropic logins only.
2
+ * Anthropic provider: the Anthropic API-key connection only.
3
3
  *
4
- * Subscription quota belongs to Claude Agent. API credentials expose no comparable quota here.
4
+ * Subscription quota belongs to Claude Agent. An ordinary API key exposes no spend, balance or
5
+ * quota endpoint, so this card shows only per-minute rate limits passively observed on real
6
+ * OpenCode API-key Messages traffic (see `../lib/anthropic-api-rate-limits.ts`).
5
7
  */
6
8
  import type { AnthropicQuotaResult } from "../lib/anthropic.js";
7
9
  import type { QuotaProvider, QuotaToastEntry } from "../lib/entries.js";
@@ -13,6 +15,8 @@ export declare function anthropicQuotaEntries(quota: AnthropicQuotaResult, param
13
15
  group: string;
14
16
  acquisitionMethod: QuotaToastEntry["accounting"]["acquisitionMethod"];
15
17
  sourceId?: string;
18
+ /** When this quota was measured; omitted for legacy callers that carry no timestamp. */
19
+ observedAtMs?: number;
16
20
  }): QuotaToastEntry[];
17
21
  export declare const anthropicProvider: QuotaProvider;
18
22
  //# sourceMappingURL=anthropic.d.ts.map
@@ -1,14 +1,20 @@
1
1
  /**
2
- * Anthropic provider: OpenCode's own Anthropic logins only.
2
+ * Anthropic provider: the Anthropic API-key connection only.
3
3
  *
4
- * Subscription quota belongs to Claude Agent. API credentials expose no comparable quota here.
4
+ * Subscription quota belongs to Claude Agent. An ordinary API key exposes no spend, balance or
5
+ * quota endpoint, so this card shows only per-minute rate limits passively observed on real
6
+ * OpenCode API-key Messages traffic (see `../lib/anthropic-api-rate-limits.ts`).
5
7
  */
8
+ import { resolveAnthropicApiKey } from "../lib/anthropic-api-auth.js";
9
+ import { ANTHROPIC_RATE_LIMIT_METERS, digestAnthropicApiKey, readAnthropicApiObservation, } from "../lib/anthropic-api-rate-limits.js";
10
+ import { windowSemantic } from "../lib/entries.js";
6
11
  import { resolveQuotaProviderSessionModelIdentity } from "../lib/quota-providers.js";
7
- import { attemptedErrorResult, notAttemptedResult, statusDetailsFromRecord, withStatusDetails, } from "./result-helpers.js";
12
+ import { attemptedErrorResult, attemptedResult, notAttemptedResult, statusDetailsFromRecord, withStatusDetails, } from "./result-helpers.js";
8
13
  export function getAnthropicNoDataMessage() {
9
- return "Anthropic API quota unavailable";
14
+ return "No Anthropic API key configured";
10
15
  }
11
- const ANTHROPIC_API_QUOTA_UNAVAILABLE_MESSAGE = "Anthropic API quota is unavailable.";
16
+ const ANTHROPIC_API_KEY_MISSING_MESSAGE = "No Anthropic API key is configured.";
17
+ const ANTHROPIC_NO_OBSERVATION_TEXT = "No rate-limit headers observed yet";
12
18
  /**
13
19
  * Map subscription quota returned for the Claude Agent CLI login.
14
20
  */
@@ -20,11 +26,14 @@ export function anthropicQuotaEntries(quota, params) {
20
26
  ownership: "maintained",
21
27
  authority: "provider_reported",
22
28
  ...(params.sourceId !== undefined ? { sourceId: params.sourceId } : {}),
29
+ ...(params.observedAtMs !== undefined
30
+ ? { observedAtIso: new Date(params.observedAtMs).toISOString() }
31
+ : {}),
23
32
  };
24
33
  const entries = [];
25
- for (const [label, window, rowKey] of [
26
- ["5h", quota.five_hour, "window:five_hour"],
27
- ["Weekly", quota.seven_day, "window:week"],
34
+ for (const [label, window, semantic] of [
35
+ ["5h", quota.five_hour, windowSemantic("five_hour")],
36
+ ["Weekly", quota.seven_day, windowSemantic("week")],
28
37
  ]) {
29
38
  if (!window)
30
39
  continue;
@@ -33,7 +42,7 @@ export function anthropicQuotaEntries(quota, params) {
33
42
  name: `${group} ${label}`,
34
43
  group,
35
44
  label: `${label}:`,
36
- rowKey,
45
+ semantic,
37
46
  percentRemaining: window.percentRemaining,
38
47
  resetTimeIso: window.resetTimeIso,
39
48
  ...(window.fixedWindow ? { fixedWindow: { ...window.fixedWindow } } : {}),
@@ -45,7 +54,7 @@ export function anthropicQuotaEntries(quota, params) {
45
54
  name: `${group} Usage Credits`,
46
55
  group: `${group} Usage Credits`,
47
56
  label: "Monthly:",
48
- rowKey: "window:month",
57
+ semantic: windowSemantic("month"),
49
58
  percentRemaining: quota.extra_usage.percentRemaining,
50
59
  });
51
60
  }
@@ -65,6 +74,77 @@ export function anthropicQuotaEntries(quota, params) {
65
74
  }
66
75
  return entries;
67
76
  }
77
+ const ANTHROPIC_GROUP = "Anthropic";
78
+ const RATE_LIMIT_INFO = "Anthropic API rate limit (per minute) observed on your API-key requests. Not subscription quota, spend or balance.";
79
+ const METER_LABELS = {
80
+ requests: "Requests",
81
+ tokens: "Tokens",
82
+ inputTokens: "Input tokens",
83
+ outputTokens: "Output tokens",
84
+ };
85
+ function numberText(value) {
86
+ return value.toLocaleString("en-US");
87
+ }
88
+ function meterValueText(meter) {
89
+ if (meter.remaining !== undefined && meter.limit !== undefined) {
90
+ return `${numberText(meter.remaining)} of ${numberText(meter.limit)} remaining`;
91
+ }
92
+ if (meter.remaining !== undefined)
93
+ return `${numberText(meter.remaining)} remaining`;
94
+ if (meter.limit !== undefined)
95
+ return `Limit ${numberText(meter.limit)}`;
96
+ return undefined;
97
+ }
98
+ /**
99
+ * Rows for one passive observation. Plain value rows: a percentage is never computed, so no
100
+ * quota alert, runway or reset-notice logic can treat a per-minute rate limit as quota.
101
+ */
102
+ function anthropicApiRateLimitEntries(observation, nowMs) {
103
+ const accounting = {
104
+ resultType: "rate_limit",
105
+ acquisitionMethod: "remote_api",
106
+ ownership: "maintained",
107
+ authority: "provider_reported",
108
+ observedAtIso: new Date(observation.observedAtMs).toISOString(),
109
+ };
110
+ const entries = [];
111
+ for (const [, name] of ANTHROPIC_RATE_LIMIT_METERS) {
112
+ const observed = observation.meters[name];
113
+ if (!observed)
114
+ continue;
115
+ // A passed reset means the observed remaining count is stale; only the limit still applies.
116
+ const expired = observed.resetAtIso !== undefined && Date.parse(observed.resetAtIso) <= nowMs;
117
+ const meter = expired ? { limit: observed.limit } : observed;
118
+ const value = meterValueText(meter);
119
+ if (value === undefined)
120
+ continue;
121
+ entries.push({
122
+ kind: "value",
123
+ accounting: { ...accounting },
124
+ name: `${ANTHROPIC_GROUP} ${METER_LABELS[name]}`,
125
+ group: ANTHROPIC_GROUP,
126
+ label: `${METER_LABELS[name]}:`,
127
+ info: RATE_LIMIT_INFO,
128
+ rowKey: `rate_limit:${name}`,
129
+ value,
130
+ ...(meter.resetAtIso !== undefined ? { resetTimeIso: meter.resetAtIso } : {}),
131
+ });
132
+ }
133
+ if (observation.retryAfterSeconds !== undefined &&
134
+ observation.observedAtMs + observation.retryAfterSeconds * 1000 > nowMs) {
135
+ entries.push({
136
+ kind: "value",
137
+ accounting: { ...accounting },
138
+ name: `${ANTHROPIC_GROUP} Retry after`,
139
+ group: ANTHROPIC_GROUP,
140
+ label: "Retry after:",
141
+ info: RATE_LIMIT_INFO,
142
+ rowKey: "rate_limit:retry_after",
143
+ value: `${numberText(observation.retryAfterSeconds)} s (last rate-limited response)`,
144
+ });
145
+ }
146
+ return entries;
147
+ }
68
148
  export const anthropicProvider = {
69
149
  id: "anthropic",
70
150
  async isAvailable(ctx) {
@@ -74,15 +154,44 @@ export const anthropicProvider = {
74
154
  ?.providerId;
75
155
  return selected?.trim().toLowerCase() === "anthropic";
76
156
  }
77
- return false;
157
+ return (await resolveAnthropicApiKey()) !== null;
78
158
  },
79
159
  matchesCurrentModel(model) {
80
160
  return model.toLowerCase().startsWith("anthropic/");
81
161
  },
82
162
  async fetch(ctx) {
83
- return withStatusDetails(ctx.config?.onlyCurrentModel
84
- ? attemptedErrorResult("Anthropic", ANTHROPIC_API_QUOTA_UNAVAILABLE_MESSAGE)
85
- : notAttemptedResult(), statusDetailsFromRecord({}));
163
+ const apiKey = await resolveAnthropicApiKey();
164
+ if (apiKey === null) {
165
+ return withStatusDetails(ctx.config?.onlyCurrentModel
166
+ ? attemptedErrorResult(ANTHROPIC_GROUP, ANTHROPIC_API_KEY_MISSING_MESSAGE)
167
+ : notAttemptedResult(), statusDetailsFromRecord({ api_key: "(none)" }));
168
+ }
169
+ const observation = readAnthropicApiObservation(digestAnthropicApiKey(apiKey));
170
+ const entries = observation ? anthropicApiRateLimitEntries(observation, Date.now()) : [];
171
+ // Configured but nothing observed yet is a truthful status, neither an error nor a zero.
172
+ const result = attemptedResult(entries.length > 0
173
+ ? entries
174
+ : [
175
+ {
176
+ kind: "value",
177
+ accounting: {
178
+ resultType: "status",
179
+ acquisitionMethod: "remote_api",
180
+ ownership: "maintained",
181
+ authority: "provider_reported",
182
+ },
183
+ name: `${ANTHROPIC_GROUP} Rate limits`,
184
+ group: ANTHROPIC_GROUP,
185
+ label: "Rate limits:",
186
+ info: RATE_LIMIT_INFO,
187
+ rowKey: "rate_limit:none",
188
+ value: ANTHROPIC_NO_OBSERVATION_TEXT,
189
+ },
190
+ ]);
191
+ return withStatusDetails(result, statusDetailsFromRecord({
192
+ api_key: "(configured)",
193
+ observed: observation ? "true" : "false",
194
+ }));
86
195
  },
87
196
  };
88
197
  //# sourceMappingURL=anthropic.js.map
@@ -2,6 +2,7 @@
2
2
  * Chutes AI provider wrapper.
3
3
  */
4
4
  import { getChutesKeyDiagnostics, hasChutesApiKeyConfigured, queryChutesQuota, } from "../lib/chutes.js";
5
+ import { windowSemantic } from "../lib/entries.js";
5
6
  import { isCanonicalProviderAvailable } from "../lib/provider-availability.js";
6
7
  import { modelProviderIncludesAny } from "../lib/provider-model-matching.js";
7
8
  import { attemptedResult, mapNullableProviderResult, withStatusDetails } from "./result-helpers.js";
@@ -38,6 +39,7 @@ export const chutesProvider = {
38
39
  authority: "provider_reported",
39
40
  },
40
41
  name: "Chutes",
42
+ semantic: windowSemantic("day"),
41
43
  percentRemaining: result.percentRemaining,
42
44
  resetTimeIso: result.resetTimeIso,
43
45
  },
@@ -14,7 +14,7 @@ import { attemptedErrorResult, attemptedResult, statusDetailsFromRecord, withSta
14
14
  export const CLAUDE_AGENT_RUNTIME_IDS = ["claude-agent", "claude-code"];
15
15
  const CLAUDE_AGENT_GROUP = "Claude Agent";
16
16
  /** Always the OAuth-reported value: even beside CLI-local windows, resets come from the usage API. */
17
- function claudeAgentResetsEntry(resets) {
17
+ function claudeAgentResetsEntry(resets, observedAtMs) {
18
18
  return {
19
19
  kind: "value",
20
20
  accounting: {
@@ -22,6 +22,9 @@ function claudeAgentResetsEntry(resets) {
22
22
  acquisitionMethod: "remote_api",
23
23
  ownership: "maintained",
24
24
  authority: "provider_reported",
25
+ ...(observedAtMs !== undefined
26
+ ? { observedAtIso: new Date(observedAtMs).toISOString() }
27
+ : {}),
25
28
  },
26
29
  name: `${CLAUDE_AGENT_GROUP} Resets`,
27
30
  group: CLAUDE_AGENT_GROUP,
@@ -40,16 +43,23 @@ export function getClaudeAgentNoDataMessage() {
40
43
  return "Quota unavailable via local Claude CLI";
41
44
  }
42
45
  function safeDiagnosticMessage(diagnostics) {
46
+ // A probe that timed out says nothing about the login; keep the token and the card, show the error.
47
+ if (diagnostics.probeFailure === true && diagnostics.quotaSource === "none")
48
+ return "Claude CLI did not respond. Retry.";
43
49
  if (diagnostics.failureCategory === "provider_api")
44
50
  return "Claude quota request failed.";
51
+ if (diagnostics.storedAccessTokenExpired)
52
+ return "Claude's stored access token has expired. Run any `claude` command to refresh it, then Retry.";
53
+ // "credentials" is only assigned after the CLI reported a verified login, so this is the usage
54
+ // endpoint rejecting the stored token, not proof that the login is invalid.
45
55
  if (diagnostics.failureCategory === "credentials")
46
- return "Claude sign-in could not be used. Run `claude auth login` and try again.";
56
+ return "Claude CLI reports you are signed in, but the usage request was rejected. Retry; if it persists, run `claude auth login`.";
47
57
  if (!diagnostics.installed)
48
58
  return "Claude CLI is unavailable.";
49
59
  if (diagnostics.authStatus === "unauthenticated")
50
60
  return "Claude is not authenticated. Run `claude auth login` and try again.";
51
61
  if (diagnostics.authStatus === "unknown")
52
- return "Claude authentication could not be verified. Run `claude auth login` and try again.";
62
+ return "Claude authentication could not be verified. Retry; if it persists, run `claude auth login`.";
53
63
  return "Claude Agent usage is unavailable.";
54
64
  }
55
65
  /** The Claude Agent route selected by `onlyCurrentModel`, if any. */
@@ -114,10 +124,12 @@ export const claudeAgentProvider = {
114
124
  });
115
125
  if (!runtimeAvailable)
116
126
  return false;
127
+ // A probe that cannot report a status must not hide a detected runtime: fetch then shows the
128
+ // error row (and a genuine sign-out still hides it). Only a confirmed sign-out is unavailable.
117
129
  return await hasAnthropicCredentialsConfigured({
118
130
  binaryPath: ctx.config?.anthropicBinaryPath,
119
131
  operationCache: ctx.operationCache,
120
- });
132
+ }, { treatUnverifiedAsConfigured: true });
121
133
  },
122
134
  async isDiscovered(ctx) {
123
135
  // Dashboard-only: a detected Claude Agent runtime stays visible while its CLI is not ready, and
@@ -138,6 +150,7 @@ export const claudeAgentProvider = {
138
150
  binaryPath: ctx.config?.anthropicBinaryPath,
139
151
  ...(ctx.operationCache ? { operationCache: ctx.operationCache } : {}),
140
152
  requestTimeoutMs: ctx.config?.requestTimeoutMs,
153
+ pollIntervalMs: ctx.config?.claudeAgentPollIntervalMs,
141
154
  ...(forceRefresh ? { forceRefresh: true } : {}),
142
155
  });
143
156
  }
@@ -174,9 +187,12 @@ export const claudeAgentProvider = {
174
187
  ...anthropicQuotaEntries(diagnostics.quota, {
175
188
  group: CLAUDE_AGENT_GROUP,
176
189
  acquisitionMethod,
190
+ ...(diagnostics.quotaMeasuredAtMs !== undefined
191
+ ? { observedAtMs: diagnostics.quotaMeasuredAtMs }
192
+ : {}),
177
193
  }),
178
194
  ...(savedResets && savedResets.availableCount > 0
179
- ? [claudeAgentResetsEntry(savedResets)]
195
+ ? [claudeAgentResetsEntry(savedResets, diagnostics.quotaMeasuredAtMs)]
180
196
  : []),
181
197
  ]);
182
198
  return withStatusDetails(diagnostics.planLabel === undefined
@@ -187,6 +203,9 @@ export const claudeAgentProvider = {
187
203
  ...(diagnostics.failureCategory !== undefined
188
204
  ? { failureCategory: diagnostics.failureCategory }
189
205
  : {}),
206
+ ...(diagnostics.attemptOutcome !== undefined
207
+ ? { attemptOutcome: diagnostics.attemptOutcome }
208
+ : {}),
190
209
  ...(diagnostics.retryAtMs !== undefined
191
210
  ? { retryable: true, retryAtMs: diagnostics.retryAtMs }
192
211
  : {}),
@@ -5,6 +5,7 @@
5
5
  * into the shared provider/result boundary.
6
6
  */
7
7
  import { COPILOT_AUTH_KEYS, getCopilotQuotaAuthDiagnostics, hasCopilotQuotaRuntimeAvailable, queryCopilotQuota, } from "../lib/copilot.js";
8
+ import { windowSemantic } from "../lib/entries.js";
8
9
  import { credentialRowAuthEntry, formatCredentialDisplayNames, readAuthFileCached, readCredentialRows, } from "../lib/opencode-auth.js";
9
10
  import { isCanonicalProviderAvailable } from "../lib/provider-availability.js";
10
11
  import { modelIncludesAny, modelProviderIncludesAny } from "../lib/provider-model-matching.js";
@@ -118,7 +119,7 @@ function personalEntries(result) {
118
119
  name,
119
120
  group,
120
121
  label: "Quota:",
121
- rowKey: "window:month",
122
+ semantic: windowSemantic("month"),
122
123
  value: "Unlimited",
123
124
  resetTimeIso: result.resetTimeIso,
124
125
  },
@@ -131,7 +132,7 @@ function personalEntries(result) {
131
132
  name,
132
133
  group,
133
134
  label: result.unit === "ai_credits" ? "Credits:" : "Quota:",
134
- rowKey: "window:month",
135
+ semantic: windowSemantic("month"),
135
136
  right: `${formatNumber(result.used)}/${formatNumber(result.total)}`,
136
137
  percentRemaining: result.percentRemaining,
137
138
  resetTimeIso: result.resetTimeIso,
@@ -144,7 +145,7 @@ function personalEntries(result) {
144
145
  name,
145
146
  group,
146
147
  label: result.unit === "ai_credits" ? "Credits:" : "Usage:",
147
- rowKey: "window:month",
148
+ semantic: windowSemantic("month", "supplementary"),
148
149
  value: result.unit === "ai_credits"
149
150
  ? formatAiCreditUsageValue(result)
150
151
  : `Used ${formatNumber(result.used)}`,
@@ -207,7 +208,7 @@ function managedEntries(result) {
207
208
  name: "Copilot AI Credits",
208
209
  group,
209
210
  label: "Credits:",
210
- rowKey: "window:month",
211
+ semantic: windowSemantic("month", "supplementary"),
211
212
  value: formatAiCreditUsageValue(result),
212
213
  resetTimeIso: result.resetTimeIso,
213
214
  },
@@ -1,39 +1,46 @@
1
+ import { windowSemantic } from "../lib/entries.js";
1
2
  import { credentialRowAuthEntry, formatCredentialDisplayNames, readCredentialRows, } from "../lib/opencode-auth.js";
2
3
  import { isCanonicalProviderAvailable } from "../lib/provider-availability.js";
3
4
  import { apiKeyStatusDetails, attemptedResult, groupedPercentWindowEntries, mapNullableProviderResult, statusDetailsFromRecord, withStatusDetails, } from "./result-helpers.js";
4
- const GLM_WINDOW_ROW_KEYS = {
5
- fiveHour: "window:five_hour",
6
- weekly: "window:week",
7
- mcp: "window:mcp",
5
+ const GLM_WINDOW_METRICS = {
6
+ fiveHour: "five_hour",
7
+ weekly: "week",
8
+ mcp: "mcp",
8
9
  };
9
- /**
10
- * Percent-only window rows carry no typed `semantic`, so they get stable
11
- * explicit `rowKey`s (metric + window) instead of label-derived ids.
12
- */
13
- function windowEntriesWithRowKeys(params) {
10
+ /** Percent-only window rows carry typed window semantics instead of label-derived ids. */
11
+ function windowEntriesWithSemantics(params) {
14
12
  const specs = [];
15
- const rowKeys = [];
16
13
  if (params.windows.fiveHour) {
17
- specs.push({ window: params.windows.fiveHour, suffix: "5h", label: "5h:" });
18
- rowKeys.push(GLM_WINDOW_ROW_KEYS.fiveHour);
14
+ specs.push({
15
+ window: params.windows.fiveHour,
16
+ suffix: "5h",
17
+ label: "5h:",
18
+ semantic: windowSemantic(GLM_WINDOW_METRICS.fiveHour),
19
+ });
19
20
  }
20
21
  if (params.windows.weekly) {
21
- specs.push({ window: params.windows.weekly, suffix: "Weekly", label: "Weekly:" });
22
- rowKeys.push(GLM_WINDOW_ROW_KEYS.weekly);
22
+ specs.push({
23
+ window: params.windows.weekly,
24
+ suffix: "Weekly",
25
+ label: "Weekly:",
26
+ semantic: windowSemantic(GLM_WINDOW_METRICS.weekly),
27
+ });
23
28
  }
24
29
  if (params.windows.mcp) {
25
- specs.push({ window: params.windows.mcp, suffix: "MCP", label: "MCP:" });
26
- rowKeys.push(GLM_WINDOW_ROW_KEYS.mcp);
30
+ specs.push({
31
+ window: params.windows.mcp,
32
+ suffix: "MCP",
33
+ label: "MCP:",
34
+ semantic: windowSemantic(GLM_WINDOW_METRICS.mcp),
35
+ });
27
36
  }
28
37
  return groupedPercentWindowEntries({
29
38
  group: params.group,
30
39
  accounting: params.accounting,
31
40
  windows: specs,
32
- }).map((entry, index) => ({
33
- ...entry,
34
- // groupedPercentWindowEntries emits one aggregate fallback row when no window exists.
35
- rowKey: rowKeys[index] ?? "aggregate",
36
- }));
41
+ // No reported window is not a 0% quota.
42
+ fallbackWhenEmpty: false,
43
+ });
37
44
  }
38
45
  export function createGlmCodingPlanProvider(params) {
39
46
  return {
@@ -92,7 +99,7 @@ export function createGlmCodingPlanProvider(params) {
92
99
  const group = names[index] ?? params.errorLabel;
93
100
  const mapped = mapNullableProviderResult(result, {
94
101
  errorLabel: group,
95
- onSuccess: (quota) => attemptedResult(windowEntriesWithRowKeys({
102
+ onSuccess: (quota) => attemptedResult(windowEntriesWithSemantics({
96
103
  group,
97
104
  accounting: {
98
105
  resultType: "quota",
@@ -113,7 +120,7 @@ export function createGlmCodingPlanProvider(params) {
113
120
  const result = await params.queryQuota({ requestTimeoutMs: ctx.config?.requestTimeoutMs });
114
121
  const providerResult = mapNullableProviderResult(result, {
115
122
  errorLabel: params.errorLabel,
116
- onSuccess: (quota) => attemptedResult(windowEntriesWithRowKeys({
123
+ onSuccess: (quota) => attemptedResult(windowEntriesWithSemantics({
117
124
  group: quota.label,
118
125
  accounting: {
119
126
  resultType: "quota",