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
package/dist/plugin.js CHANGED
@@ -5,17 +5,27 @@
5
5
  * surfaces (commands, tool, the TUI quota RPC and report hooks) are retained in
6
6
  * their source modules but are not registered by this product.
7
7
  */
8
+ import { randomUUID } from "node:crypto";
8
9
  import { Plugin } from "@opencode/plugin";
9
10
  import { startDashboard } from "./gui/lifecycle.js";
10
11
  import { scrubLogReason } from "./gui/log.js";
11
12
  import { registerDashboardRpc } from "./gui/rpc.js";
13
+ import { observeAnthropicApiResponse } from "./lib/anthropic-api-rate-limits.js";
14
+ import { projectOpenCodeCacheObserverEvent } from "./lib/cache-observer-ingestion.js";
15
+ import { readClaudeObservedTtl } from "./lib/claude-agent-transcript-ttl.js";
16
+ import { createClaudeAgentTtlTracker } from "./lib/claude-agent-ttl-tracker.js";
12
17
  import { resolveOpenCodeLocationRoots } from "./lib/config-file-utils.js";
13
18
  import { bindCredentialSource, createIntegrationCredentialSource, notifyCredentialsChanged, scrubCredentialErrorText, } from "./lib/opencode-auth.js";
14
- 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";
15
22
  /** An error as one line that is safe to log: tokens redacted, at most 120 characters. */
16
23
  function logReason(error) {
17
24
  return scrubCredentialErrorText(error instanceof Error ? error.message : String(error));
18
25
  }
26
+ const MAX_PENDING_CACHE_OBSERVER_EVENTS = 512;
27
+ const MAX_SAMPLED_SESSIONS = 1_024;
28
+ const HOST_EVENT_RECONNECT_DELAY_MS = 1_000;
19
29
  export const QuotaToastPlugin = Plugin.define({
20
30
  id: "opencode-quota-gui",
21
31
  async setup(ctx) {
@@ -24,6 +34,7 @@ export const QuotaToastPlugin = Plugin.define({
24
34
  // does not expose a mutable global config to plugins; runtime settings are
25
35
  // read from the canonical GUI config file by the collector.
26
36
  const client = {
37
+ integration: { list: () => ctx.integration.list() },
27
38
  config: {
28
39
  get: async () => ({ data: {} }),
29
40
  providers: async () => ({
@@ -46,25 +57,307 @@ export const QuotaToastPlugin = Plugin.define({
46
57
  console.warn(`[opencode-quota-gui] retry hook failed: ${logReason(error)}`);
47
58
  }
48
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
+ });
106
+ // Owner-approved per-session approximation (not per-request proof): the host shares no
107
+ // per-invocation id between `model.request` and `session.step.started`, and connections
108
+ // rarely change, so the active OpenAI connection METHOD is sampled once per session — on
109
+ // its `session.created` event, or on its first step for a session that predates this
110
+ // plugin — and reused for that session's OpenAI steps. A lookup still pending (or failed)
111
+ // leaves the step without a method, i.e. the conservative 5-minute TTL fallback; relayed
112
+ // steps are never rewritten and a mid-session credential change is not reflected.
113
+ // Only the allowlisted method is kept; credential values, ids and labels are never read.
114
+ const openaiMethodBySession = new Map();
115
+ const sampleOpenAiMethod = (sessionID) => {
116
+ if (typeof sessionID !== "string" || sessionID === "")
117
+ return;
118
+ if (openaiMethodBySession.has(sessionID))
119
+ return;
120
+ if (openaiMethodBySession.size >= MAX_SAMPLED_SESSIONS) {
121
+ const oldest = openaiMethodBySession.keys().next().value;
122
+ if (oldest !== undefined)
123
+ openaiMethodBySession.delete(oldest);
124
+ }
125
+ const entry = {};
126
+ openaiMethodBySession.set(sessionID, entry);
127
+ void (async () => {
128
+ try {
129
+ const connection = await ctx.integration.connection.active("openai");
130
+ const method = connection?.type === "credential" ? connection.method : undefined;
131
+ if (method === "oauth" || method === "key" || method === "external") {
132
+ entry.method = method;
133
+ }
134
+ }
135
+ catch {
136
+ // Unavailable metadata keeps the 5-minute fallback.
137
+ }
138
+ })();
139
+ };
49
140
  // Every login read in this process goes through this location's `ctx.integration`. Bound
50
141
  // last, so a setup that fails part way leaves no binding behind. OpenCode routes the
51
142
  // retained hooks only after setup, so no read comes earlier.
52
143
  const unbindCredentialSource = bindCredentialSource(createIntegrationCredentialSource(ctx.integration));
53
- // A login added, changed or switched in OpenCode drops cached logins and failed-login
54
- // entries, so the next read asks OpenCode again. If the subscription fails, cached logins
55
- // stay until they expire; the log says why. The cleanup's abort ends it silently.
56
- const credentialEvents = new AbortController();
57
- void (async () => {
58
- for await (const event of ctx.event.subscribe({ signal: credentialEvents.signal })) {
59
- if (event.type === "credential.updated" || event.type === "credential.switched") {
60
- notifyCredentialsChanged();
144
+ let dashboardRpc;
145
+ let cacheObserverEmitChain = Promise.resolve();
146
+ const pendingCacheObserverEvents = [];
147
+ let pendingCacheObserverEventsDropped = false;
148
+ let pendingHostEventObservedAtMs;
149
+ const cacheObserverRelayAbort = new AbortController();
150
+ let cacheObserverEmitWorkerRunning = false;
151
+ const hostEventSourceBinding = randomUUID();
152
+ let hostEventSourceState = "unverified";
153
+ const readHostEventSourceState = () => hostEventSourceState;
154
+ async function waitForHostEventReconnect(signal) {
155
+ if (signal.aborted)
156
+ return;
157
+ await new Promise((resolve) => {
158
+ let timer;
159
+ const finish = () => {
160
+ if (timer !== undefined)
161
+ clearTimeout(timer);
162
+ signal.removeEventListener("abort", finish);
163
+ resolve();
164
+ };
165
+ timer = setTimeout(finish, HOST_EVENT_RECONNECT_DELAY_MS);
166
+ signal.addEventListener("abort", finish, { once: true });
167
+ if (signal.aborted)
168
+ finish();
169
+ });
170
+ }
171
+ async function emitCacheObserverEventNow(registration, pending) {
172
+ const { signal } = cacheObserverRelayAbort;
173
+ if (signal.aborted)
174
+ return;
175
+ const emission = Promise.resolve()
176
+ .then(() => {
177
+ if (signal.aborted)
178
+ return;
179
+ return registration.events.emit("invalidated", {
180
+ topic: "cache.observer",
181
+ at: pending.at,
182
+ cacheObserverEvent: pending.event,
183
+ });
184
+ })
185
+ .then(() => undefined, () => undefined);
186
+ if (signal.aborted)
187
+ return;
188
+ await new Promise((resolve) => {
189
+ const finish = () => {
190
+ signal.removeEventListener("abort", finish);
191
+ resolve();
192
+ };
193
+ signal.addEventListener("abort", finish, { once: true });
194
+ void emission.then(finish);
195
+ });
196
+ }
197
+ async function drainCacheObserverEvents() {
198
+ try {
199
+ while (!cacheObserverRelayAbort.signal.aborted) {
200
+ if (pendingCacheObserverEventsDropped) {
201
+ pendingCacheObserverEventsDropped = false;
202
+ const registration = dashboardRpc;
203
+ if (!registration)
204
+ continue;
205
+ const gapAt = Date.now();
206
+ await emitCacheObserverEventNow(registration, {
207
+ at: gapAt,
208
+ event: {
209
+ type: "source.status",
210
+ created: gapAt,
211
+ data: { state: "unavailable", sourceBinding: hostEventSourceBinding },
212
+ },
213
+ });
214
+ if (hostEventSourceState === "observed")
215
+ pendingHostEventObservedAtMs = gapAt;
216
+ continue;
217
+ }
218
+ const pending = pendingCacheObserverEvents.shift();
219
+ if (!pending) {
220
+ const observedAt = pendingHostEventObservedAtMs;
221
+ if (observedAt === undefined)
222
+ break;
223
+ pendingHostEventObservedAtMs = undefined;
224
+ if (hostEventSourceState !== "observed")
225
+ continue;
226
+ const registration = dashboardRpc;
227
+ if (registration) {
228
+ await emitCacheObserverEventNow(registration, {
229
+ at: observedAt,
230
+ event: {
231
+ type: "source.status",
232
+ created: observedAt,
233
+ data: { state: "observed", sourceBinding: hostEventSourceBinding },
234
+ },
235
+ });
236
+ }
237
+ continue;
238
+ }
239
+ const registration = dashboardRpc;
240
+ if (registration)
241
+ await emitCacheObserverEventNow(registration, pending);
61
242
  }
62
243
  }
63
- })().catch((error) => {
64
- if (credentialEvents.signal.aborted)
244
+ finally {
245
+ cacheObserverEmitWorkerRunning = false;
246
+ }
247
+ }
248
+ const startCacheObserverEmitWorker = () => {
249
+ if (!dashboardRpc ||
250
+ cacheObserverRelayAbort.signal.aborted ||
251
+ cacheObserverEmitWorkerRunning) {
252
+ return;
253
+ }
254
+ cacheObserverEmitWorkerRunning = true;
255
+ cacheObserverEmitChain = drainCacheObserverEvents().catch(() => undefined);
256
+ };
257
+ const emitCacheObserverEvent = (event, at) => {
258
+ if (cacheObserverRelayAbort.signal.aborted)
259
+ return;
260
+ if (pendingCacheObserverEvents.length >= MAX_PENDING_CACHE_OBSERVER_EVENTS) {
261
+ pendingCacheObserverEvents.shift();
262
+ pendingCacheObserverEventsDropped = true;
263
+ }
264
+ pendingCacheObserverEvents.push({ at, event });
265
+ startCacheObserverEmitWorker();
266
+ };
267
+ const publishHostEventSourceState = (state, at) => {
268
+ if (hostEventSourceState === state)
65
269
  return;
66
- console.warn(`[opencode-quota-gui] credential event subscription stopped: ${logReason(error)}`);
270
+ hostEventSourceState = state;
271
+ if (state !== "observed")
272
+ pendingHostEventObservedAtMs = undefined;
273
+ emitCacheObserverEvent({
274
+ type: "source.status",
275
+ created: at,
276
+ data: { state, sourceBinding: hostEventSourceBinding },
277
+ }, at);
278
+ };
279
+ const claudeTtl = createClaudeAgentTtlTracker({
280
+ directory: ctx.location.directory,
281
+ read: readClaudeObservedTtl,
282
+ emit: emitCacheObserverEvent,
67
283
  });
284
+ // Reuse the existing host stream for credential invalidation and narrowly projected cache
285
+ // evidence. No Native-side OpenCode event subscription is opened.
286
+ const hostEvents = new AbortController();
287
+ void (async () => {
288
+ const { signal } = hostEvents;
289
+ while (!signal.aborted) {
290
+ try {
291
+ for await (const event of ctx.event.subscribe({ signal })) {
292
+ if (signal.aborted)
293
+ return;
294
+ if (readHostEventSourceState() !== "observed") {
295
+ publishHostEventSourceState("observed", typeof event.created === "number" && Number.isFinite(event.created)
296
+ ? event.created
297
+ : Date.now());
298
+ }
299
+ if (event.type === "credential.updated" || event.type === "credential.switched") {
300
+ notifyCredentialsChanged();
301
+ }
302
+ try {
303
+ autoResume.handleEvent(event);
304
+ }
305
+ catch {
306
+ // Resume tracking is observation only; never break the host event stream.
307
+ }
308
+ // The Started event's model identity is available before invocation completion. Do not
309
+ // enrich it from model.list here: that mutable catalog may no longer match dispatch.
310
+ const sessionID = event.data?.sessionID;
311
+ if (event.type === "session.created")
312
+ sampleOpenAiMethod(sessionID);
313
+ else if (event.type === "session.deleted" && typeof sessionID === "string") {
314
+ openaiMethodBySession.delete(sessionID);
315
+ }
316
+ let cacheObserverEvent = projectOpenCodeCacheObserverEvent(event);
317
+ if (cacheObserverEvent?.type === "session.step.started" &&
318
+ cacheObserverEvent.data.model.providerID === "openai") {
319
+ sampleOpenAiMethod(cacheObserverEvent.data.sessionID);
320
+ const method = openaiMethodBySession.get(cacheObserverEvent.data.sessionID)?.method;
321
+ if (method !== undefined) {
322
+ cacheObserverEvent = {
323
+ ...cacheObserverEvent,
324
+ data: { ...cacheObserverEvent.data, connectionMethod: method },
325
+ };
326
+ }
327
+ }
328
+ if (cacheObserverEvent !== undefined &&
329
+ typeof event.created === "number" &&
330
+ Number.isFinite(event.created) &&
331
+ event.created >= 0) {
332
+ emitCacheObserverEvent(cacheObserverEvent, event.created);
333
+ }
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
+ }
345
+ }
346
+ if (signal.aborted)
347
+ return;
348
+ throw new Error("host event stream ended");
349
+ }
350
+ catch (error) {
351
+ if (signal.aborted)
352
+ return;
353
+ if (readHostEventSourceState() !== "unavailable") {
354
+ publishHostEventSourceState("unavailable", Date.now());
355
+ }
356
+ console.warn(`[opencode-quota-gui] host event subscription failed; retrying: ${logReason(error)}`);
357
+ await waitForHostEventReconnect(signal);
358
+ }
359
+ }
360
+ })();
68
361
  // The dashboard host binds last — after the retry hook and the credential binding — and it
69
362
  // never fails setup: every dashboard error stays a controlled log line and an `unavailable`
70
363
  // lease (spec §4.3). The first owner workspace supplies the config import root, and the
@@ -87,20 +380,41 @@ export const QuotaToastPlugin = Plugin.define({
87
380
  // Attach the native RPC transport to the same host runtime the web
88
381
  // transport receives. It is available when web is disabled or its bind
89
382
  // failed, and it never constructs another source/snapshot/service.
90
- let dashboardRpc;
91
383
  if (dashboardLease?.runtime && ctx.rpc) {
92
384
  try {
93
385
  dashboardRpc = await registerDashboardRpc(ctx.rpc, dashboardLease.runtime, {
94
386
  location: ctx.location,
387
+ onWatchSnapshot: (attemptNonce) => {
388
+ const at = Date.now();
389
+ emitCacheObserverEvent({
390
+ type: "source.status",
391
+ created: at,
392
+ data: {
393
+ state: readHostEventSourceState(),
394
+ attemptNonce,
395
+ sourceBinding: hostEventSourceBinding,
396
+ },
397
+ }, at);
398
+ },
95
399
  });
400
+ startCacheObserverEmitWorker();
96
401
  }
97
402
  catch {
98
403
  console.warn(`[opencode-quota-gui] dashboard RPC unavailable: registration-failed`);
99
404
  }
100
405
  }
101
406
  return async () => {
102
- credentialEvents.abort();
407
+ hostEvents.abort();
408
+ autoResume.dispose();
409
+ claudeTtl.dispose();
410
+ openaiMethodBySession.clear();
411
+ pendingCacheObserverEvents.length = 0;
412
+ publishHostEventSourceState("stopped", Date.now());
103
413
  unbindCredentialSource();
414
+ pendingCacheObserverEvents.length = 0;
415
+ pendingCacheObserverEventsDropped = false;
416
+ cacheObserverRelayAbort.abort();
417
+ await cacheObserverEmitChain;
104
418
  if (dashboardRpc) {
105
419
  try {
106
420
  await dashboardRpc.dispose();
@@ -5,7 +5,7 @@ Provider logo assets in this directory are vendored from [models.dev](https://gi
5
5
  - **Upstream license:** MIT. The copyright and permission notice is preserved verbatim in `UPSTREAM-MIT.txt`.
6
6
  - **Source path:** `providers/<provider-id>/logo.svg` in the pinned models.dev archive.
7
7
  - **Normalization:** each SVG is stored as UTF-8 with XML/DTD declarations removed, trailing horizontal whitespace outside whitespace-sensitive text content stripped, and a final newline added; the artwork itself is unchanged.
8
- - **Local use:** 222 upstream provider logos, the local neutral `generic.svg` fallback and the local OpenCode Go G mark are copied into the package at build time and served from same-origin `/assets/providers/`. The dashboard never hotlinks a remote logo.
8
+ - **Local use:** 222 upstream provider logos, the local neutral `generic.svg` fallback and the local OpenCode Go G and Claude Agent marks are copied into the package at build time and served from same-origin `/assets/providers/`. The dashboard never hotlinks a remote logo.
9
9
  - **OpenCode identities:** the upstream `opencode` and `opencode-go` entries in models.dev both contain the O artwork and remain vendored unchanged. Presentation overrides only `opencode-go` with a dedicated G mark extracted from [OpenCode](https://github.com/anomalyco/opencode) at `86976449c40d48f2731553a024f74552593d1764`; see `OPENCODE-NOTICE.md` and `OPENCODE-MIT.txt`. `opencode` and OpenCode Zen keep the O mark. Raw analytics identities are never rewritten.
10
10
  - **Brand rights:** the MIT license covers the models.dev repository and the assets as distributed there. It does not establish or grant rights in any provider's name, logo, or other trademark, and individual brand-use terms may still apply. The logos identify the corresponding providers in a local dashboard; no affiliation or endorsement is implied.
11
11
  - **Mask-incompatible marks:** a small number of upstream marks use an opaque raster or full-bleed background and would collapse to a solid block under a one-colour mask. The catalog shows the local neutral fallback for those while keeping the vendored file and attribution.
@@ -1,4 +1,4 @@
1
- # OpenCode Go artwork attribution
1
+ # OpenCode provider artwork attribution
2
2
 
3
3
  The local OpenCode Go mark in `opencode-go-g.svg` is extracted from the public OpenCode provider icon sprite.
4
4
 
@@ -7,6 +7,7 @@ The local OpenCode Go mark in `opencode-go-g.svg` is extracted from the public O
7
7
  - **Source file:** `packages/ui/src/components/provider-icons/sprite.svg`
8
8
  - **Source symbol:** `<symbol id="opencode-go">`
9
9
  - **License:** MIT; copyright `Copyright (c) 2025 opencode`. The full upstream text is preserved verbatim in `OPENCODE-MIT.txt`.
10
- - **Extraction:** only the single `<path>` inside the `opencode-go` symbol is included, wrapped in a standalone SVG with `viewBox="0 0 24 24"` and `fill="currentColor"`. No other artwork from the sprite is included.
10
+ - **Extraction:** only the single `<path>` inside the `opencode-go` symbol is included in that asset, wrapped in a standalone SVG with `viewBox="0 0 24 24"` and `fill="currentColor"`.
11
11
  - **Upstream separation:** models.dev's upstream `opencode-go` O mark remains vendored unchanged in `opencode-go.svg`; the local G mark is a presentation override for OpenCode Go only. `opencode` and OpenCode Zen continue to use the models.dev O mark.
12
- - **Use:** the mark identifies OpenCode Go in this local dashboard. No affiliation or endorsement is implied, and brand rights remain with their owners.
12
+ - **Claude Agent:** `claude-agent.svg` extracts only the `<symbol id="claude-agent">` path from the same sprite at commit `850504188198976c668bd3b514c3e8de21b9e0e2` (sprite SHA-256 `9f17db4e21f4450b000c2e105ad137c775172135eb31d8441940a45e567d0792`), wrapped as a standalone monochrome SVG retaining its viewBox.
13
+ - **Use:** the marks identify OpenCode Go and Claude Agent in this local dashboard. No affiliation or endorsement is implied, and brand rights remain with their owners.