opencode-quota-gui 1.3.0 → 1.3.1

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 (146) hide show
  1. package/README.md +27 -17
  2. package/dist/bin/opencode-quota-gui.js +0 -0
  3. package/dist/contracts/build-identity.js +1 -1
  4. package/dist/contracts/dashboard.d.ts +8 -1
  5. package/dist/contracts/dto-guards.js +2 -0
  6. package/dist/contracts/openai-quota.d.ts +3 -0
  7. package/dist/contracts/openai-quota.js +3 -0
  8. package/dist/data/modelsdev-temporal.min.json +57 -0
  9. package/dist/gui/config.d.ts +3 -3
  10. package/dist/gui/config.js +31 -2
  11. package/dist/gui/lifecycle.d.ts +5 -3
  12. package/dist/gui/lifecycle.js +3 -3
  13. package/dist/gui/primary-quota-windows.js +16 -14
  14. package/dist/gui/provider-cards.d.ts +10 -2
  15. package/dist/gui/provider-cards.js +51 -23
  16. package/dist/gui/quota-notification-detector.d.ts +4 -4
  17. package/dist/gui/quota-notification-detector.js +76 -42
  18. package/dist/gui/quota-notification-observer.d.ts +2 -3
  19. package/dist/gui/quota-notification-observer.js +68 -19
  20. package/dist/gui/rpc.d.ts +2 -0
  21. package/dist/gui/rpc.js +11 -3
  22. package/dist/gui/server.js +11 -2
  23. package/dist/gui/snapshot-service.d.ts +3 -1
  24. package/dist/gui/snapshot-service.js +126 -18
  25. package/dist/gui/sources.js +98 -56
  26. package/dist/gui-experimental.cjs +230 -225
  27. package/dist/lib/accounting-format.js +8 -0
  28. package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
  29. package/dist/lib/alibaba-coding-plan-cli.js +539 -0
  30. package/dist/lib/anthropic-auth.d.ts +2 -3
  31. package/dist/lib/anthropic-auth.js +2 -3
  32. package/dist/lib/anthropic.d.ts +48 -12
  33. package/dist/lib/anthropic.js +610 -275
  34. package/dist/lib/api-key-retry-after.d.ts +7 -0
  35. package/dist/lib/api-key-retry-after.js +62 -0
  36. package/dist/lib/atomic-json.d.ts +2 -0
  37. package/dist/lib/atomic-json.js +1 -0
  38. package/dist/lib/cache-observer-ingestion.d.ts +90 -0
  39. package/dist/lib/cache-observer-ingestion.js +981 -0
  40. package/dist/lib/cache-observer.d.ts +138 -0
  41. package/dist/lib/cache-observer.js +317 -0
  42. package/dist/lib/canonical-config-lock.d.ts +9 -0
  43. package/dist/lib/canonical-config-lock.js +36 -0
  44. package/dist/lib/chutes.js +62 -51
  45. package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
  46. package/dist/lib/claude-agent-transcript-ttl.js +154 -0
  47. package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
  48. package/dist/lib/claude-agent-ttl-tracker.js +152 -0
  49. package/dist/lib/cli-show.js +5 -3
  50. package/dist/lib/config-write-target.d.ts +1 -1
  51. package/dist/lib/config-write-target.js +5 -2
  52. package/dist/lib/config.d.ts +2 -1
  53. package/dist/lib/config.js +193 -2
  54. package/dist/lib/copilot.js +171 -86
  55. package/dist/lib/dashboard-web-policy.d.ts +4 -4
  56. package/dist/lib/dashboard-web-policy.js +2 -2
  57. package/dist/lib/deepseek.js +25 -13
  58. package/dist/lib/display-sanitize.js +1 -0
  59. package/dist/lib/entries.d.ts +23 -0
  60. package/dist/lib/entries.js +2 -0
  61. package/dist/lib/glm-coding-plan.js +98 -74
  62. package/dist/lib/google-agy.js +90 -12
  63. package/dist/lib/google-gemini-cli.js +84 -11
  64. package/dist/lib/http.d.ts +4 -0
  65. package/dist/lib/http.js +16 -2
  66. package/dist/lib/init-installer.js +5 -3
  67. package/dist/lib/kilo.js +37 -18
  68. package/dist/lib/kimi.js +35 -18
  69. package/dist/lib/mimo.d.ts +2 -0
  70. package/dist/lib/mimo.js +36 -0
  71. package/dist/lib/nanogpt.d.ts +1 -0
  72. package/dist/lib/nanogpt.js +26 -3
  73. package/dist/lib/ollama-cloud.d.ts +1 -1
  74. package/dist/lib/ollama-cloud.js +48 -35
  75. package/dist/lib/openai.js +84 -38
  76. package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
  77. package/dist/lib/opencode-auth-sqlite.js +2 -2
  78. package/dist/lib/opencode-config-editor.d.ts +1 -0
  79. package/dist/lib/opencode-config-editor.js +6 -1
  80. package/dist/lib/opencode-go.js +29 -2
  81. package/dist/lib/opencode-version-core.d.ts +23 -0
  82. package/dist/lib/opencode-version-core.js +49 -0
  83. package/dist/lib/opencode-version.d.ts +2 -22
  84. package/dist/lib/opencode-version.js +4 -48
  85. package/dist/lib/opencode-zen.d.ts +3 -0
  86. package/dist/lib/opencode-zen.js +71 -5
  87. package/dist/lib/provider-add.js +5 -2
  88. package/dist/lib/provider-registration.d.ts +19 -9
  89. package/dist/lib/provider-registration.js +17 -6
  90. package/dist/lib/quota-command-format.js +1 -1
  91. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  92. package/dist/lib/quota-exhaustion-projection.js +25 -0
  93. package/dist/lib/quota-providers-remote.d.ts +2 -1
  94. package/dist/lib/quota-providers-remote.js +59 -3
  95. package/dist/lib/quota-providers.d.ts +1 -1
  96. package/dist/lib/quota-providers.js +12 -35
  97. package/dist/lib/quota-render-data.d.ts +6 -0
  98. package/dist/lib/quota-render-data.js +43 -17
  99. package/dist/lib/quota-state-codec.js +17 -1
  100. package/dist/lib/quota-state.d.ts +7 -1
  101. package/dist/lib/quota-state.js +208 -34
  102. package/dist/lib/quota-stats.js +21 -0
  103. package/dist/lib/quota-status.js +3 -51
  104. package/dist/lib/scoped-update.d.ts +1 -1
  105. package/dist/lib/synthetic.js +65 -54
  106. package/dist/lib/types.d.ts +31 -1
  107. package/dist/lib/types.js +13 -0
  108. package/dist/lib/xai.js +48 -22
  109. package/dist/plugin.js +261 -13
  110. package/dist/provider-logos/NOTICE.md +1 -1
  111. package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
  112. package/dist/providers/alibaba-coding-plan.js +107 -104
  113. package/dist/providers/anthropic.d.ts +12 -3
  114. package/dist/providers/anthropic.js +71 -228
  115. package/dist/providers/cache-policies.d.ts +11 -4
  116. package/dist/providers/cache-policies.js +19 -13
  117. package/dist/providers/claude-agent.d.ts +19 -0
  118. package/dist/providers/claude-agent.js +196 -0
  119. package/dist/providers/copilot.js +2 -0
  120. package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
  121. package/dist/providers/google-account-format.js +1 -0
  122. package/dist/providers/google-agy.d.ts +6 -5
  123. package/dist/providers/google-agy.js +43 -15
  124. package/dist/providers/google-gemini-cli.js +1 -0
  125. package/dist/providers/kilo.js +1 -0
  126. package/dist/providers/kimi-code.js +2 -0
  127. package/dist/providers/mimo.js +1 -0
  128. package/dist/providers/nanogpt.js +1 -0
  129. package/dist/providers/opencode-go.js +3 -0
  130. package/dist/providers/opencode-zen.js +2 -0
  131. package/dist/providers/openrouter.js +1 -0
  132. package/dist/providers/quota-providers.js +16 -5
  133. package/dist/providers/registry.js +2 -0
  134. package/dist/providers/result-helpers.d.ts +2 -0
  135. package/dist/providers/result-helpers.js +2 -0
  136. package/dist/rpc.d.ts +121 -8
  137. package/dist/rpc.js +204 -12
  138. package/dist/ui/assets/{index-cDd9jUVY.css → index-BcueIm3Z.css} +1 -1
  139. package/dist/ui/assets/index-C6qRSoh8.js +10 -0
  140. package/dist/ui/assets/{popover-BGkgv9s0.js → popover-4bFSvRZ7.js} +1 -1
  141. package/dist/ui/assets/providers/claude-agent.svg +3 -0
  142. package/dist/ui/index.html +2 -2
  143. package/package.json +44 -45
  144. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
  145. package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
  146. package/dist/ui/assets/index-DLHeXYff.js +0 -9
package/dist/plugin.js CHANGED
@@ -5,10 +5,14 @@
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 { projectOpenCodeCacheObserverEvent } from "./lib/cache-observer-ingestion.js";
14
+ import { readClaudeObservedTtl } from "./lib/claude-agent-transcript-ttl.js";
15
+ import { createClaudeAgentTtlTracker } from "./lib/claude-agent-ttl-tracker.js";
12
16
  import { resolveOpenCodeLocationRoots } from "./lib/config-file-utils.js";
13
17
  import { bindCredentialSource, createIntegrationCredentialSource, notifyCredentialsChanged, scrubCredentialErrorText, } from "./lib/opencode-auth.js";
14
18
  import { resolveQuotaResetRetryDelayMs } from "./lib/quota-retry-wait.js";
@@ -16,6 +20,9 @@ import { resolveQuotaResetRetryDelayMs } from "./lib/quota-retry-wait.js";
16
20
  function logReason(error) {
17
21
  return scrubCredentialErrorText(error instanceof Error ? error.message : String(error));
18
22
  }
23
+ const MAX_PENDING_CACHE_OBSERVER_EVENTS = 512;
24
+ const MAX_SAMPLED_SESSIONS = 1_024;
25
+ const HOST_EVENT_RECONNECT_DELAY_MS = 1_000;
19
26
  export const QuotaToastPlugin = Plugin.define({
20
27
  id: "opencode-quota-gui",
21
28
  async setup(ctx) {
@@ -24,6 +31,7 @@ export const QuotaToastPlugin = Plugin.define({
24
31
  // does not expose a mutable global config to plugins; runtime settings are
25
32
  // read from the canonical GUI config file by the collector.
26
33
  const client = {
34
+ integration: { list: () => ctx.integration.list() },
27
35
  config: {
28
36
  get: async () => ({ data: {} }),
29
37
  providers: async () => ({
@@ -46,25 +54,245 @@ export const QuotaToastPlugin = Plugin.define({
46
54
  console.warn(`[opencode-quota-gui] retry hook failed: ${logReason(error)}`);
47
55
  }
48
56
  });
57
+ // Owner-approved per-session approximation (not per-request proof): the host shares no
58
+ // per-invocation id between `model.request` and `session.step.started`, and connections
59
+ // rarely change, so the active OpenAI connection METHOD is sampled once per session — on
60
+ // its `session.created` event, or on its first step for a session that predates this
61
+ // plugin — and reused for that session's OpenAI steps. A lookup still pending (or failed)
62
+ // leaves the step without a method, i.e. the conservative 5-minute TTL fallback; relayed
63
+ // steps are never rewritten and a mid-session credential change is not reflected.
64
+ // Only the allowlisted method is kept; credential values, ids and labels are never read.
65
+ const openaiMethodBySession = new Map();
66
+ const sampleOpenAiMethod = (sessionID) => {
67
+ if (typeof sessionID !== "string" || sessionID === "")
68
+ return;
69
+ if (openaiMethodBySession.has(sessionID))
70
+ return;
71
+ if (openaiMethodBySession.size >= MAX_SAMPLED_SESSIONS) {
72
+ const oldest = openaiMethodBySession.keys().next().value;
73
+ if (oldest !== undefined)
74
+ openaiMethodBySession.delete(oldest);
75
+ }
76
+ const entry = {};
77
+ openaiMethodBySession.set(sessionID, entry);
78
+ void (async () => {
79
+ try {
80
+ const connection = await ctx.integration.connection.active("openai");
81
+ const method = connection?.type === "credential" ? connection.method : undefined;
82
+ if (method === "oauth" || method === "key" || method === "external") {
83
+ entry.method = method;
84
+ }
85
+ }
86
+ catch {
87
+ // Unavailable metadata keeps the 5-minute fallback.
88
+ }
89
+ })();
90
+ };
49
91
  // Every login read in this process goes through this location's `ctx.integration`. Bound
50
92
  // last, so a setup that fails part way leaves no binding behind. OpenCode routes the
51
93
  // retained hooks only after setup, so no read comes earlier.
52
94
  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();
95
+ let dashboardRpc;
96
+ let cacheObserverEmitChain = Promise.resolve();
97
+ const pendingCacheObserverEvents = [];
98
+ let pendingCacheObserverEventsDropped = false;
99
+ let pendingHostEventObservedAtMs;
100
+ const cacheObserverRelayAbort = new AbortController();
101
+ let cacheObserverEmitWorkerRunning = false;
102
+ const hostEventSourceBinding = randomUUID();
103
+ let hostEventSourceState = "unverified";
104
+ const readHostEventSourceState = () => hostEventSourceState;
105
+ async function waitForHostEventReconnect(signal) {
106
+ if (signal.aborted)
107
+ return;
108
+ await new Promise((resolve) => {
109
+ let timer;
110
+ const finish = () => {
111
+ if (timer !== undefined)
112
+ clearTimeout(timer);
113
+ signal.removeEventListener("abort", finish);
114
+ resolve();
115
+ };
116
+ timer = setTimeout(finish, HOST_EVENT_RECONNECT_DELAY_MS);
117
+ signal.addEventListener("abort", finish, { once: true });
118
+ if (signal.aborted)
119
+ finish();
120
+ });
121
+ }
122
+ async function emitCacheObserverEventNow(registration, pending) {
123
+ const { signal } = cacheObserverRelayAbort;
124
+ if (signal.aborted)
125
+ return;
126
+ const emission = Promise.resolve()
127
+ .then(() => {
128
+ if (signal.aborted)
129
+ return;
130
+ return registration.events.emit("invalidated", {
131
+ topic: "cache.observer",
132
+ at: pending.at,
133
+ cacheObserverEvent: pending.event,
134
+ });
135
+ })
136
+ .then(() => undefined, () => undefined);
137
+ if (signal.aborted)
138
+ return;
139
+ await new Promise((resolve) => {
140
+ const finish = () => {
141
+ signal.removeEventListener("abort", finish);
142
+ resolve();
143
+ };
144
+ signal.addEventListener("abort", finish, { once: true });
145
+ void emission.then(finish);
146
+ });
147
+ }
148
+ async function drainCacheObserverEvents() {
149
+ try {
150
+ while (!cacheObserverRelayAbort.signal.aborted) {
151
+ if (pendingCacheObserverEventsDropped) {
152
+ pendingCacheObserverEventsDropped = false;
153
+ const registration = dashboardRpc;
154
+ if (!registration)
155
+ continue;
156
+ const gapAt = Date.now();
157
+ await emitCacheObserverEventNow(registration, {
158
+ at: gapAt,
159
+ event: {
160
+ type: "source.status",
161
+ created: gapAt,
162
+ data: { state: "unavailable", sourceBinding: hostEventSourceBinding },
163
+ },
164
+ });
165
+ if (hostEventSourceState === "observed")
166
+ pendingHostEventObservedAtMs = gapAt;
167
+ continue;
168
+ }
169
+ const pending = pendingCacheObserverEvents.shift();
170
+ if (!pending) {
171
+ const observedAt = pendingHostEventObservedAtMs;
172
+ if (observedAt === undefined)
173
+ break;
174
+ pendingHostEventObservedAtMs = undefined;
175
+ if (hostEventSourceState !== "observed")
176
+ continue;
177
+ const registration = dashboardRpc;
178
+ if (registration) {
179
+ await emitCacheObserverEventNow(registration, {
180
+ at: observedAt,
181
+ event: {
182
+ type: "source.status",
183
+ created: observedAt,
184
+ data: { state: "observed", sourceBinding: hostEventSourceBinding },
185
+ },
186
+ });
187
+ }
188
+ continue;
189
+ }
190
+ const registration = dashboardRpc;
191
+ if (registration)
192
+ await emitCacheObserverEventNow(registration, pending);
61
193
  }
62
194
  }
63
- })().catch((error) => {
64
- if (credentialEvents.signal.aborted)
195
+ finally {
196
+ cacheObserverEmitWorkerRunning = false;
197
+ }
198
+ }
199
+ const startCacheObserverEmitWorker = () => {
200
+ if (!dashboardRpc ||
201
+ cacheObserverRelayAbort.signal.aborted ||
202
+ cacheObserverEmitWorkerRunning) {
203
+ return;
204
+ }
205
+ cacheObserverEmitWorkerRunning = true;
206
+ cacheObserverEmitChain = drainCacheObserverEvents().catch(() => undefined);
207
+ };
208
+ const emitCacheObserverEvent = (event, at) => {
209
+ if (cacheObserverRelayAbort.signal.aborted)
65
210
  return;
66
- console.warn(`[opencode-quota-gui] credential event subscription stopped: ${logReason(error)}`);
211
+ if (pendingCacheObserverEvents.length >= MAX_PENDING_CACHE_OBSERVER_EVENTS) {
212
+ pendingCacheObserverEvents.shift();
213
+ pendingCacheObserverEventsDropped = true;
214
+ }
215
+ pendingCacheObserverEvents.push({ at, event });
216
+ startCacheObserverEmitWorker();
217
+ };
218
+ const publishHostEventSourceState = (state, at) => {
219
+ if (hostEventSourceState === state)
220
+ return;
221
+ hostEventSourceState = state;
222
+ if (state !== "observed")
223
+ pendingHostEventObservedAtMs = undefined;
224
+ emitCacheObserverEvent({
225
+ type: "source.status",
226
+ created: at,
227
+ data: { state, sourceBinding: hostEventSourceBinding },
228
+ }, at);
229
+ };
230
+ const claudeTtl = createClaudeAgentTtlTracker({
231
+ directory: ctx.location.directory,
232
+ read: readClaudeObservedTtl,
233
+ emit: emitCacheObserverEvent,
67
234
  });
235
+ // Reuse the existing host stream for credential invalidation and narrowly projected cache
236
+ // evidence. No Native-side OpenCode event subscription is opened.
237
+ const hostEvents = new AbortController();
238
+ void (async () => {
239
+ const { signal } = hostEvents;
240
+ while (!signal.aborted) {
241
+ try {
242
+ for await (const event of ctx.event.subscribe({ signal })) {
243
+ if (signal.aborted)
244
+ return;
245
+ if (readHostEventSourceState() !== "observed") {
246
+ publishHostEventSourceState("observed", typeof event.created === "number" && Number.isFinite(event.created)
247
+ ? event.created
248
+ : Date.now());
249
+ }
250
+ if (event.type === "credential.updated" || event.type === "credential.switched") {
251
+ notifyCredentialsChanged();
252
+ }
253
+ // The Started event's model identity is available before invocation completion. Do not
254
+ // enrich it from model.list here: that mutable catalog may no longer match dispatch.
255
+ const sessionID = event.data?.sessionID;
256
+ if (event.type === "session.created")
257
+ sampleOpenAiMethod(sessionID);
258
+ else if (event.type === "session.deleted" && typeof sessionID === "string") {
259
+ openaiMethodBySession.delete(sessionID);
260
+ }
261
+ let cacheObserverEvent = projectOpenCodeCacheObserverEvent(event);
262
+ if (cacheObserverEvent?.type === "session.step.started" &&
263
+ cacheObserverEvent.data.model.providerID === "openai") {
264
+ sampleOpenAiMethod(cacheObserverEvent.data.sessionID);
265
+ const method = openaiMethodBySession.get(cacheObserverEvent.data.sessionID)?.method;
266
+ if (method !== undefined) {
267
+ cacheObserverEvent = {
268
+ ...cacheObserverEvent,
269
+ data: { ...cacheObserverEvent.data, connectionMethod: method },
270
+ };
271
+ }
272
+ }
273
+ if (cacheObserverEvent !== undefined &&
274
+ typeof event.created === "number" &&
275
+ Number.isFinite(event.created) &&
276
+ event.created >= 0) {
277
+ emitCacheObserverEvent(cacheObserverEvent, event.created);
278
+ }
279
+ claudeTtl.observe(event, cacheObserverEvent);
280
+ }
281
+ if (signal.aborted)
282
+ return;
283
+ throw new Error("host event stream ended");
284
+ }
285
+ catch (error) {
286
+ if (signal.aborted)
287
+ return;
288
+ if (readHostEventSourceState() !== "unavailable") {
289
+ publishHostEventSourceState("unavailable", Date.now());
290
+ }
291
+ console.warn(`[opencode-quota-gui] host event subscription failed; retrying: ${logReason(error)}`);
292
+ await waitForHostEventReconnect(signal);
293
+ }
294
+ }
295
+ })();
68
296
  // The dashboard host binds last — after the retry hook and the credential binding — and it
69
297
  // never fails setup: every dashboard error stays a controlled log line and an `unavailable`
70
298
  // lease (spec §4.3). The first owner workspace supplies the config import root, and the
@@ -87,20 +315,40 @@ export const QuotaToastPlugin = Plugin.define({
87
315
  // Attach the native RPC transport to the same host runtime the web
88
316
  // transport receives. It is available when web is disabled or its bind
89
317
  // failed, and it never constructs another source/snapshot/service.
90
- let dashboardRpc;
91
318
  if (dashboardLease?.runtime && ctx.rpc) {
92
319
  try {
93
320
  dashboardRpc = await registerDashboardRpc(ctx.rpc, dashboardLease.runtime, {
94
321
  location: ctx.location,
322
+ onWatchSnapshot: (attemptNonce) => {
323
+ const at = Date.now();
324
+ emitCacheObserverEvent({
325
+ type: "source.status",
326
+ created: at,
327
+ data: {
328
+ state: readHostEventSourceState(),
329
+ attemptNonce,
330
+ sourceBinding: hostEventSourceBinding,
331
+ },
332
+ }, at);
333
+ },
95
334
  });
335
+ startCacheObserverEmitWorker();
96
336
  }
97
337
  catch {
98
338
  console.warn(`[opencode-quota-gui] dashboard RPC unavailable: registration-failed`);
99
339
  }
100
340
  }
101
341
  return async () => {
102
- credentialEvents.abort();
342
+ hostEvents.abort();
343
+ claudeTtl.dispose();
344
+ openaiMethodBySession.clear();
345
+ pendingCacheObserverEvents.length = 0;
346
+ publishHostEventSourceState("stopped", Date.now());
103
347
  unbindCredentialSource();
348
+ pendingCacheObserverEvents.length = 0;
349
+ pendingCacheObserverEventsDropped = false;
350
+ cacheObserverRelayAbort.abort();
351
+ await cacheObserverEmitChain;
104
352
  if (dashboardRpc) {
105
353
  try {
106
354
  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.
@@ -1,18 +1,96 @@
1
- import { DEFAULT_ALIBABA_AUTH_CACHE_MAX_AGE_MS, getAlibabaCodingPlanAuthDiagnostics, isAlibabaModelId, resolveAlibabaCodingPlanAuthCached, } from "../lib/alibaba-auth.js";
2
- import { ALIBABA_CODING_PLAN_STATE_VERSION, computeAlibabaCodingPlanQuota, getAlibabaCodingPlanQuotaPath, readAlibabaCodingPlanQuotaState, } from "../lib/alibaba-coding-plan-local-quota.js";
3
- import { findQuotaProviderDefinition } from "../lib/quota-providers.js";
4
- import { attemptedErrorResult, attemptedResult, inspectGeneratedCounterFile, notAttemptedResult, statusDetailsFromRecord, withStatusDetails, } from "./result-helpers.js";
5
- function tierLabel(tier) {
6
- return tier === "pro" ? "Pro" : "Lite";
1
+ import { isAlibabaModelId } from "../lib/alibaba-auth.js";
2
+ import { queryAlibabaCodingPlanQuota, } from "../lib/alibaba-coding-plan-cli.js";
3
+ import { sanitizeSingleLineDisplayText } from "../lib/display-sanitize.js";
4
+ import { isCanonicalProviderAvailable } from "../lib/provider-availability.js";
5
+ import { attemptedErrorResult, attemptedResult, statusDetailsFromRecord, withStatusDetails, } from "./result-helpers.js";
6
+ const CLI_LABEL = "Bailian CLI";
7
+ const QUOTA_ACCOUNTING = {
8
+ resultType: "quota",
9
+ acquisitionMethod: "local_cli",
10
+ ownership: "maintained",
11
+ authority: "provider_reported",
12
+ };
13
+ const STATUS_ACCOUNTING = {
14
+ ...QUOTA_ACCOUNTING,
15
+ resultType: "status",
16
+ };
17
+ function windowEntry(window, params) {
18
+ if (!window)
19
+ return undefined;
20
+ const name = `${params.group} ${params.suffix}`;
21
+ const resetTime = window.resetTimeIso ? { resetTimeIso: window.resetTimeIso } : {};
22
+ if (window.percentage !== undefined) {
23
+ const hasCounts = window.used !== undefined && window.total !== undefined && window.total > 0;
24
+ return {
25
+ accounting: { ...QUOTA_ACCOUNTING },
26
+ name,
27
+ group: params.group,
28
+ label: params.label,
29
+ ...(hasCounts ? { right: `${window.used}/${window.total}` } : {}),
30
+ percentRemaining: Math.max(0, Math.min(100, (1 - window.percentage) * 100)),
31
+ ...resetTime,
32
+ };
33
+ }
34
+ if (window.resetTimeIso) {
35
+ return {
36
+ kind: "value",
37
+ accounting: { ...STATUS_ACCOUNTING },
38
+ name,
39
+ group: params.group,
40
+ label: params.label,
41
+ value: "Quota details unavailable",
42
+ ...resetTime,
43
+ };
44
+ }
45
+ return undefined;
46
+ }
47
+ function entriesFromUsage(result) {
48
+ const instanceType = result.usage.instanceType
49
+ ? sanitizeSingleLineDisplayText(result.usage.instanceType).trim().slice(0, 40)
50
+ : "";
51
+ const group = `Alibaba Coding Plan${instanceType ? ` (${instanceType})` : ""} (CLI)`;
52
+ 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
+ ].filter((entry) => entry !== undefined);
57
+ }
58
+ function failureCategoryFor(kind) {
59
+ if (kind === "not_authenticated")
60
+ return "credentials";
61
+ if (kind === "invalid_json" ||
62
+ kind === "invalid_schema" ||
63
+ kind === "nonzero_exit" ||
64
+ kind === "output_truncated" ||
65
+ kind === "no_quota_data") {
66
+ return "provider_api";
67
+ }
68
+ return "local";
69
+ }
70
+ function resultWithCliStatus(result, statusDetails, status) {
71
+ return withStatusDetails(result, [
72
+ ...statusDetails,
73
+ ...statusDetailsFromRecord({ alibaba_coding_plan_cli_status: status }),
74
+ ]);
7
75
  }
8
76
  export const alibabaCodingPlanProvider = {
9
77
  id: "alibaba-coding-plan",
10
- async isAvailable(_ctx) {
11
- const plan = await resolveAlibabaCodingPlanAuthCached({
12
- maxAgeMs: DEFAULT_ALIBABA_AUTH_CACHE_MAX_AGE_MS,
13
- fallbackTier: "lite",
78
+ async isAvailable(ctx) {
79
+ const selected = await isCanonicalProviderAvailable({
80
+ ctx,
81
+ providerId: "alibaba-coding-plan",
82
+ fallbackOnError: false,
14
83
  });
15
- return plan.state === "configured" || plan.state === "invalid";
84
+ if (selected)
85
+ return true;
86
+ if (ctx.config.currentProviderID === "alibaba-coding-plan" ||
87
+ ctx.config.currentProviderID === "alibaba") {
88
+ return true;
89
+ }
90
+ const currentModel = ctx.config.currentModel;
91
+ return typeof currentModel === "string" && currentModel.length > 0
92
+ ? isAlibabaModelId(currentModel)
93
+ : false;
16
94
  },
17
95
  matchesCurrentModel(model, context) {
18
96
  return context?.currentProviderID
@@ -21,104 +99,29 @@ export const alibabaCodingPlanProvider = {
21
99
  : isAlibabaModelId(model);
22
100
  },
23
101
  async fetch(ctx) {
24
- const diagnostics = await getAlibabaCodingPlanAuthDiagnostics({
25
- maxAgeMs: DEFAULT_ALIBABA_AUTH_CACHE_MAX_AGE_MS,
26
- fallbackTier: "lite",
27
- });
28
- const plan = await resolveAlibabaCodingPlanAuthCached({
29
- maxAgeMs: DEFAULT_ALIBABA_AUTH_CACHE_MAX_AGE_MS,
30
- fallbackTier: "lite",
102
+ const result = await queryAlibabaCodingPlanQuota({
103
+ requestTimeoutMs: ctx.config?.requestTimeoutMs,
104
+ runtime: { cwd: ctx.workspaceRoot },
31
105
  });
32
- const statePath = getAlibabaCodingPlanQuotaPath();
33
- const state = await inspectGeneratedCounterFile(statePath, ALIBABA_CODING_PLAN_STATE_VERSION);
34
- const lastUpdate = state.lastUpdatedAt === null ? "(none)" : new Date(state.lastUpdatedAt).toISOString();
35
- const authError = diagnostics.state === "invalid" ? diagnostics.error : undefined;
36
106
  const statusDetails = statusDetailsFromRecord({
37
- "alibaba auth configured": diagnostics.state === "none" ? "false" : "true",
38
- alibaba_api_key_source: diagnostics.source ?? "(none)",
39
- alibaba_api_key_checked_paths: diagnostics.checkedPaths.join(" | ") || "(none)",
40
- alibaba_api_key_credential_database_paths: diagnostics.credentialDatabasePaths.join(" | ") || "(none)",
41
- alibaba_coding_plan: diagnostics.state === "configured"
42
- ? diagnostics.tier
43
- : diagnostics.state === "invalid"
44
- ? "invalid"
45
- : "(none)",
46
- alibaba_auth_error: authError,
47
- "alibaba coding plan error": authError,
48
- "alibaba coding plan local quota": `path=${statePath} exists=${state.exists ? "true" : "false"} health=${state.health} version=${state.version ?? "(none)"} last_update=${lastUpdate}`,
49
- local_state_path: statePath,
50
- local_state_exists: state.exists ? "true" : "false",
51
- local_state_health: state.health,
52
- local_state_version: String(state.version ?? "(none)"),
53
- local_state_last_update: lastUpdate,
107
+ alibaba_coding_plan_source: "bl usage coding-plan --output json",
54
108
  });
55
- if (plan.state === "none") {
56
- return withStatusDetails(notAttemptedResult(), statusDetails);
109
+ if (result.state === "error") {
110
+ return resultWithCliStatus(attemptedErrorResult(`${CLI_LABEL} Coding Plan usage`, result.error.message, {
111
+ retryable: result.error.retryable,
112
+ failureCategory: failureCategoryFor(result.error.kind),
113
+ }), statusDetails, result.error.kind);
57
114
  }
58
- if (plan.state === "invalid") {
59
- return withStatusDetails(attemptedErrorResult("Alibaba Coding Plan", plan.error, {
60
- failureCategory: "credentials",
61
- }), statusDetails);
115
+ if (result.state === "no-subscription") {
116
+ return resultWithCliStatus(attemptedResult([]), statusDetails, "no-subscription");
62
117
  }
63
- const tuning = findQuotaProviderDefinition(ctx.config.quotaProviders ?? [], "alibaba-coding-plan");
64
- const limits = tuning?.mode === "local-estimate"
65
- ? {
66
- fiveHour: tuning.windows.find((window) => window.id === "five-hour").requestLimit,
67
- weekly: tuning.windows.find((window) => window.id === "weekly").requestLimit,
68
- monthly: tuning.windows.find((window) => window.id === "monthly").requestLimit,
69
- }
70
- : undefined;
71
- const quota = computeAlibabaCodingPlanQuota({
72
- state: await readAlibabaCodingPlanQuotaState(),
73
- tier: plan.tier,
74
- ...(limits ? { limits } : {}),
75
- });
76
- const label = `Alibaba Coding Plan (${tierLabel(plan.tier)})`;
77
- const entries = [
78
- {
79
- accounting: {
80
- resultType: "quota",
81
- acquisitionMethod: "local_estimation",
82
- ownership: "maintained",
83
- authority: "locally_derived",
84
- },
85
- name: `${label} 5h`,
86
- group: label,
87
- label: "5h:",
88
- right: `${quota.fiveHour.used}/${quota.fiveHour.limit}`,
89
- percentRemaining: quota.fiveHour.percentRemaining,
90
- resetTimeIso: quota.fiveHour.resetTimeIso,
91
- },
92
- {
93
- accounting: {
94
- resultType: "quota",
95
- acquisitionMethod: "local_estimation",
96
- ownership: "maintained",
97
- authority: "locally_derived",
98
- },
99
- name: `${label} Weekly`,
100
- group: label,
101
- label: "Weekly:",
102
- right: `${quota.weekly.used}/${quota.weekly.limit}`,
103
- percentRemaining: quota.weekly.percentRemaining,
104
- resetTimeIso: quota.weekly.resetTimeIso,
105
- },
106
- {
107
- accounting: {
108
- resultType: "quota",
109
- acquisitionMethod: "local_estimation",
110
- ownership: "maintained",
111
- authority: "locally_derived",
112
- },
113
- name: `${label} Monthly`,
114
- group: label,
115
- label: "Monthly:",
116
- right: `${quota.monthly.used}/${quota.monthly.limit}`,
117
- percentRemaining: quota.monthly.percentRemaining,
118
- resetTimeIso: quota.monthly.resetTimeIso,
119
- },
120
- ];
121
- return withStatusDetails(attemptedResult(entries), statusDetails);
118
+ const entries = entriesFromUsage(result);
119
+ if (entries.length === 0) {
120
+ return resultWithCliStatus(attemptedErrorResult(`${CLI_LABEL} Coding Plan usage`, "Bailian CLI returned no usable Coding Plan quota data.", {
121
+ failureCategory: "provider_api",
122
+ }), statusDetails, "no-quota-data");
123
+ }
124
+ return resultWithCliStatus(attemptedResult(entries), statusDetails, "success");
122
125
  },
123
126
  };
124
127
  //# sourceMappingURL=alibaba-coding-plan.js.map
@@ -1,9 +1,18 @@
1
1
  /**
2
- * Anthropic Claude provider wrapper.
2
+ * Anthropic provider: OpenCode's own Anthropic logins only.
3
3
  *
4
- * Normalizes Claude CLI-exposed quota windows into generic toast entries.
4
+ * Subscription quota belongs to Claude Agent. API credentials expose no comparable quota here.
5
5
  */
6
- import type { QuotaProvider } from "../lib/entries.js";
6
+ import type { AnthropicQuotaResult } from "../lib/anthropic.js";
7
+ import type { QuotaProvider, QuotaToastEntry } from "../lib/entries.js";
7
8
  export declare function getAnthropicNoDataMessage(): string;
9
+ /**
10
+ * Map subscription quota returned for the Claude Agent CLI login.
11
+ */
12
+ export declare function anthropicQuotaEntries(quota: AnthropicQuotaResult, params: {
13
+ group: string;
14
+ acquisitionMethod: QuotaToastEntry["accounting"]["acquisitionMethod"];
15
+ sourceId?: string;
16
+ }): QuotaToastEntry[];
8
17
  export declare const anthropicProvider: QuotaProvider;
9
18
  //# sourceMappingURL=anthropic.d.ts.map