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
@@ -11,7 +11,7 @@
11
11
  */
12
12
  import { orderCardsByPreference } from "../contracts/card-order.js";
13
13
  import { PRIMARY_QUOTA_WINDOW_LIMIT, } from "../contracts/dashboard.js";
14
- import { OPENAI_CREDITS_INFO, OPENAI_CREDITS_ROW_KEY, OPENAI_CREDITS_ROW_LABEL, OPENAI_CREDITS_ROW_RESULT_TYPE, OPENAI_RESETS_INFO, OPENAI_RESETS_ROW_KEY, OPENAI_RESETS_ROW_LABEL, OPENAI_RESETS_ROW_RESULT_TYPE, } from "../contracts/openai-quota.js";
14
+ import { CLAUDE_AGENT_RESETS_INFO, CLAUDE_AGENT_RESETS_ROW_KEY, OPENAI_CREDITS_INFO, OPENAI_CREDITS_ROW_KEY, OPENAI_CREDITS_ROW_LABEL, OPENAI_CREDITS_ROW_RESULT_TYPE, OPENAI_RESETS_INFO, OPENAI_RESETS_ROW_KEY, OPENAI_RESETS_ROW_LABEL, OPENAI_RESETS_ROW_RESULT_TYPE, } from "../contracts/openai-quota.js";
15
15
  import { formatAccountingQuantity, interpretAccountingRow, isCanonicalAccountingDecimal, } from "../lib/accounting-format.js";
16
16
  import { sanitizeDisplayText, sanitizeQuotaToastEntry, sanitizeSingleLineDisplayText, } from "../lib/display-sanitize.js";
17
17
  import { cloneBankedResetAvailability, isBooleanEntry, isPercentEntry, isQuantityEntry, isValueEntry, } from "../lib/entries.js";
@@ -25,6 +25,10 @@ import { primaryQuotaWindowSlot } from "./primary-quota-windows.js";
25
25
  export const PROVIDER_ERROR_GENERIC_MESSAGE = "Provider request failed; check upstream quota diagnostics.";
26
26
  /** Controlled fallback label when an error label itself is unredactable. */
27
27
  export const PROVIDER_ERROR_GENERIC_LABEL = "Provider error";
28
+ export const UNSCOPED = Symbol("unscoped");
29
+ export function cardSourceKey(sourceId, accountSourceIds) {
30
+ return sourceId !== undefined && accountSourceIds.has(sourceId) ? sourceId : UNSCOPED;
31
+ }
28
32
  // Raw identities shorter than this are not string-replaced (avoids gutting
29
33
  // ordinary words); real OpenCode connection ids are longer.
30
34
  const MIN_SECRET_LENGTH = 4;
@@ -77,6 +81,10 @@ function mapProviderError(error, secrets) {
77
81
  };
78
82
  if (error.retryable === true)
79
83
  mapped.retryable = true;
84
+ if (error.retryAtMs !== undefined)
85
+ mapped.retryAtMs = error.retryAtMs;
86
+ if (error.kind !== undefined)
87
+ mapped.kind = error.kind;
80
88
  if (error.failureCategory !== undefined)
81
89
  mapped.failureCategory = error.failureCategory;
82
90
  return mapped;
@@ -161,8 +169,7 @@ function mapEntryRow(params) {
161
169
  row.percentUsed = 100 - entry.percentRemaining;
162
170
  }
163
171
  applyResetFields(row, entry, preferences);
164
- if (preferences.quotaProjection === "runway")
165
- applyRunway(row, entry, nowMs);
172
+ applyRunway(row, entry, nowMs);
166
173
  if (preferences.accountingDetail === "detailed" && entry.basis) {
167
174
  const detailRows = detailRowsFor(entry.basis);
168
175
  if (detailRows.length > 0)
@@ -249,6 +256,23 @@ export function openAiOptionalVisibilityRows(cardId) {
249
256
  },
250
257
  ];
251
258
  }
259
+ /** Persistent Resets choice for a Claude Agent card (no Credits row). */
260
+ export function claudeAgentOptionalVisibilityRows(cardId) {
261
+ return [
262
+ {
263
+ rowId: optionalValueRowId(cardId, CLAUDE_AGENT_RESETS_ROW_KEY, OPENAI_RESETS_ROW_RESULT_TYPE),
264
+ label: OPENAI_RESETS_ROW_LABEL,
265
+ info: CLAUDE_AGENT_RESETS_INFO,
266
+ },
267
+ ];
268
+ }
269
+ function optionalVisibilityRowsFor(providerId, cardId) {
270
+ if (providerId === "openai")
271
+ return openAiOptionalVisibilityRows(cardId);
272
+ if (providerId === "claude-agent")
273
+ return claudeAgentOptionalVisibilityRows(cardId);
274
+ return undefined;
275
+ }
252
276
  function latestObservedAtIso(entries) {
253
277
  let latest;
254
278
  let latestMs = Number.NEGATIVE_INFINITY;
@@ -285,6 +309,18 @@ function pushInto(map, key, value) {
285
309
  else
286
310
  map.set(key, [value]);
287
311
  }
312
+ function finishCard(card, mapped, entries) {
313
+ if (mapped.primaryQuotaWindows.length > 0) {
314
+ card.primaryQuotaWindows = mapped.primaryQuotaWindows;
315
+ }
316
+ const optionalRows = optionalVisibilityRowsFor(card.providerId, card.cardId);
317
+ if (optionalRows)
318
+ card.visibilityRows = optionalRows;
319
+ const observedAtIso = latestObservedAtIso(entries);
320
+ if (observedAtIso)
321
+ card.observedAtIso = observedAtIso;
322
+ return card;
323
+ }
288
324
  function buildProviderCard(params) {
289
325
  const cardId = buildProviderScopeCardId(params.providerId);
290
326
  const mapped = mapEntryRows({
@@ -294,25 +330,19 @@ function buildProviderCard(params) {
294
330
  preferences: params.preferences,
295
331
  nowMs: params.nowMs,
296
332
  });
333
+ const planLabel = params.planLabel ? sanitizeSingleLineDisplayText(params.planLabel).trim() : "";
297
334
  const card = {
298
335
  cardId,
299
336
  providerId: params.providerId,
300
337
  providerLabel: params.providerLabel,
301
338
  providerScopeId: params.providerScopeId,
302
339
  providerScopeHash: params.providerScopeHash,
340
+ ...(planLabel ? { planLabel } : {}),
303
341
  labelSource: "provider",
304
342
  rows: mapped.rows,
305
343
  errors: params.errors.map((error) => mapProviderError(error, params.secrets)),
306
344
  };
307
- if (mapped.primaryQuotaWindows.length > 0) {
308
- card.primaryQuotaWindows = mapped.primaryQuotaWindows;
309
- }
310
- if (params.providerId === "openai")
311
- card.visibilityRows = openAiOptionalVisibilityRows(cardId);
312
- const observedAtIso = latestObservedAtIso(params.entries);
313
- if (observedAtIso)
314
- card.observedAtIso = observedAtIso;
315
- return card;
345
+ return finishCard(card, mapped, params.entries);
316
346
  }
317
347
  function buildAccountCard(params) {
318
348
  const identityKey = params.account.identityKey?.trim()
@@ -344,15 +374,7 @@ function buildAccountCard(params) {
344
374
  rows: mapped.rows,
345
375
  errors: params.errors.map((error) => mapProviderError(error, params.secrets)),
346
376
  };
347
- if (mapped.primaryQuotaWindows.length > 0) {
348
- card.primaryQuotaWindows = mapped.primaryQuotaWindows;
349
- }
350
- if (params.providerId === "openai")
351
- card.visibilityRows = openAiOptionalVisibilityRows(cardId);
352
- const observedAtIso = latestObservedAtIso(params.entries);
353
- if (observedAtIso)
354
- card.observedAtIso = observedAtIso;
355
- return card;
377
+ return finishCard(card, mapped, params.entries);
356
378
  }
357
379
  /**
358
380
  * One card per discovered account (zero-entry and failed ones included) plus a
@@ -382,7 +404,7 @@ export function buildProviderCards(input) {
382
404
  const unscopedErrors = [];
383
405
  for (const entry of probe.result.entries) {
384
406
  const sourceId = entry.accounting.sourceId;
385
- if (sourceId !== undefined && accountSourceIds.has(sourceId)) {
407
+ if (cardSourceKey(sourceId, accountSourceIds) !== UNSCOPED && sourceId !== undefined) {
386
408
  pushInto(entriesBySource, sourceId, entry);
387
409
  }
388
410
  else {
@@ -391,7 +413,7 @@ export function buildProviderCards(input) {
391
413
  }
392
414
  for (const error of probe.result.errors) {
393
415
  const sourceId = error.sourceId;
394
- if (sourceId !== undefined && accountSourceIds.has(sourceId)) {
416
+ if (cardSourceKey(sourceId, accountSourceIds) !== UNSCOPED && sourceId !== undefined) {
395
417
  pushInto(errorsBySource, sourceId, error);
396
418
  }
397
419
  else {
@@ -405,12 +427,16 @@ export function buildProviderCards(input) {
405
427
  providerLabel,
406
428
  providerScopeId,
407
429
  providerScopeHash,
430
+ // A plan belongs to this card only when the provider has no account cards of its own.
431
+ planLabel: accounts.length === 0 ? probe.result.planLabel : undefined,
408
432
  entries: unscopedEntries,
409
433
  errors: unscopedErrors,
410
434
  secrets,
411
435
  preferences,
412
436
  nowMs,
413
437
  });
438
+ if (probe.retainedUnscoped)
439
+ card.stale = true;
414
440
  if (!seenCardIds.has(card.cardId)) {
415
441
  seenCardIds.add(card.cardId);
416
442
  cards.push(card);
@@ -430,6 +456,8 @@ export function buildProviderCards(input) {
430
456
  preferences,
431
457
  nowMs,
432
458
  });
459
+ if (probe.retainedSourceIds?.has(account.sourceId))
460
+ card.stale = true;
433
461
  if (seenCardIds.has(card.cardId))
434
462
  continue;
435
463
  seenCardIds.add(card.cardId);
@@ -1,6 +1,7 @@
1
1
  import type { QuotaCardRow } from "../contracts/dashboard.js";
2
2
  import type { ProviderFailureCategory } from "../contracts/provider-failure.js";
3
3
  import { type ResetObservation } from "../lib/quota-reset-notifications.js";
4
+ import type { NativeQuotaNotificationPolicy } from "../lib/types.js";
4
5
  export declare const QUOTA_NOTIFICATION_DETECTOR_STATE_VERSION: 1;
5
6
  /** Shared proven reset-transition age limit re-exported for detector consumers. */
6
7
  export declare const RESET_TRANSITION_MAX_AGE_MS: number;
@@ -62,6 +63,7 @@ export interface QuotaNotificationRowObservation {
62
63
  label: string;
63
64
  kind: QuotaCardRow["kind"];
64
65
  resultType: QuotaCardRow["resultType"];
66
+ metric?: QuotaCardRow["metric"];
65
67
  percentRemaining?: number;
66
68
  resetAtIso?: string;
67
69
  }
@@ -117,10 +119,8 @@ export interface DetectQuotaNotificationsInput {
117
119
  cooldowns?: Readonly<Record<string, number>>;
118
120
  /** Injectable clock supplied by the caller. */
119
121
  nowMs: number;
120
- /** Caller/settings-supplied low threshold. The detector owns no default. */
121
- lowThresholdPercent: number;
122
- /** Caller/settings-supplied cooldown. The detector owns no default. */
123
- cooldownMs: number;
122
+ /** Canonical Native notification policy. The detector owns no settings defaults. */
123
+ policy: NativeQuotaNotificationPolicy;
124
124
  }
125
125
  export interface DetectQuotaNotificationsResult {
126
126
  notifications: QuotaNotification[];
@@ -127,6 +127,26 @@ function isEligiblePercentRow(row) {
127
127
  typeof row.percentRemaining === "number" &&
128
128
  Number.isFinite(row.percentRemaining));
129
129
  }
130
+ function resetWindowForRow(row) {
131
+ if (row.metric?.kind !== "window")
132
+ return undefined;
133
+ switch (row.metric.window) {
134
+ case "five_hour":
135
+ return "fiveHour";
136
+ case "hour":
137
+ return "hourly";
138
+ case "day":
139
+ return "daily";
140
+ case "week":
141
+ return "weekly";
142
+ case "month":
143
+ return "monthly";
144
+ case "year":
145
+ return "yearly";
146
+ default:
147
+ return undefined;
148
+ }
149
+ }
130
150
  export function detectQuotaNotifications(input) {
131
151
  const nowMs = input.nowMs;
132
152
  const hiddenCards = new Set(input.hiddenCards ?? []);
@@ -134,12 +154,14 @@ export function detectQuotaNotifications(input) {
134
154
  const previousState = input.state?.version === QUOTA_NOTIFICATION_DETECTOR_STATE_VERSION ? input.state : undefined;
135
155
  const cooldowns = { ...(input.cooldowns ?? {}) };
136
156
  const notifications = [];
157
+ const { policy } = input;
158
+ const cooldownMs = policy.duplicateCooldownMinutes * 60_000;
137
159
  const nextRows = new Map();
138
160
  const nextProviders = new Map();
139
161
  const seenCards = new Set();
140
162
  const emit = (fingerprint, notification) => {
141
163
  const lastAtMs = cooldowns[fingerprint];
142
- if (lastAtMs !== undefined && nowMs - lastAtMs < input.cooldownMs)
164
+ if (lastAtMs !== undefined && nowMs - lastAtMs < cooldownMs)
143
165
  return false;
144
166
  notifications.push(notification);
145
167
  cooldowns[fingerprint] = nowMs;
@@ -198,42 +220,52 @@ export function detectQuotaNotifications(input) {
198
220
  nextRows.set(key, makeRowState(currentPercent, nowMs, resetObservation));
199
221
  if (resetEvent) {
200
222
  const resetAtIso = new Date(resetEvent.resetAtMs).toISOString();
201
- const fingerprint = quotaNotificationFingerprint({
202
- kind: "reset",
203
- cardId: card.cardId,
204
- rowId: row.rowId,
205
- resetAtIso,
206
- });
207
- emit(fingerprint, {
208
- ...notificationBase(card, fingerprint, nowMs),
209
- kind: "reset",
210
- rowId: row.rowId,
211
- rowLabel: row.label,
212
- percentRemaining: currentPercent,
213
- resetAtIso,
214
- previousResetAtIso: new Date(resetEvent.previousResetAtMs).toISOString(),
215
- });
223
+ const resetWindow = resetWindowForRow(row);
224
+ if (policy.enabled &&
225
+ policy.reset.enabled &&
226
+ resetWindow !== undefined &&
227
+ policy.reset.windows.includes(resetWindow)) {
228
+ const fingerprint = quotaNotificationFingerprint({
229
+ kind: "reset",
230
+ cardId: card.cardId,
231
+ rowId: row.rowId,
232
+ resetAtIso,
233
+ });
234
+ emit(fingerprint, {
235
+ ...notificationBase(card, fingerprint, nowMs),
236
+ kind: "reset",
237
+ rowId: row.rowId,
238
+ rowLabel: row.label,
239
+ percentRemaining: currentPercent,
240
+ resetAtIso,
241
+ previousResetAtIso: new Date(resetEvent.previousResetAtMs).toISOString(),
242
+ });
243
+ }
216
244
  continue;
217
245
  }
218
246
  const previousPercent = previousRow.percentRemaining;
219
247
  if (previousPercent > 0 && currentPercent <= 0) {
220
- const fingerprint = quotaNotificationFingerprint({
221
- kind: "exhausted",
222
- cardId: card.cardId,
223
- rowId: row.rowId,
224
- });
225
- emit(fingerprint, {
226
- ...notificationBase(card, fingerprint, nowMs),
227
- kind: "exhausted",
228
- rowId: row.rowId,
229
- rowLabel: row.label,
230
- percentRemaining: currentPercent,
231
- ...(normalizedResetAtIso !== undefined ? { resetAtIso: normalizedResetAtIso } : {}),
232
- });
248
+ if (policy.enabled && policy.exhausted.enabled) {
249
+ const fingerprint = quotaNotificationFingerprint({
250
+ kind: "exhausted",
251
+ cardId: card.cardId,
252
+ rowId: row.rowId,
253
+ });
254
+ emit(fingerprint, {
255
+ ...notificationBase(card, fingerprint, nowMs),
256
+ kind: "exhausted",
257
+ rowId: row.rowId,
258
+ rowLabel: row.label,
259
+ percentRemaining: currentPercent,
260
+ ...(normalizedResetAtIso !== undefined ? { resetAtIso: normalizedResetAtIso } : {}),
261
+ });
262
+ }
233
263
  continue;
234
264
  }
235
- if (previousPercent > input.lowThresholdPercent &&
236
- currentPercent <= input.lowThresholdPercent) {
265
+ if (policy.enabled &&
266
+ policy.low.enabled &&
267
+ previousPercent > policy.low.thresholdRemainingPercent &&
268
+ currentPercent <= policy.low.thresholdRemainingPercent) {
237
269
  const fingerprint = quotaNotificationFingerprint({
238
270
  kind: "low",
239
271
  cardId: card.cardId,
@@ -244,7 +276,7 @@ export function detectQuotaNotifications(input) {
244
276
  kind: "low",
245
277
  rowId: row.rowId,
246
278
  rowLabel: row.label,
247
- thresholdPercent: input.lowThresholdPercent,
279
+ thresholdPercent: policy.low.thresholdRemainingPercent,
248
280
  percentRemaining: currentPercent,
249
281
  ...(normalizedResetAtIso !== undefined ? { resetAtIso: normalizedResetAtIso } : {}),
250
282
  });
@@ -260,16 +292,18 @@ export function detectQuotaNotifications(input) {
260
292
  if (!previousProvider || previousProvider.status !== "healthy" || status !== "error") {
261
293
  continue;
262
294
  }
263
- const fingerprint = quotaNotificationFingerprint({
264
- kind: "provider-error",
265
- cardId: card.cardId,
266
- category: QUOTA_NOTIFICATION_PROVIDER_ERROR_CATEGORY,
267
- });
268
- emit(fingerprint, {
269
- ...notificationBase(card, fingerprint, nowMs),
270
- kind: "provider-error",
271
- category: QUOTA_NOTIFICATION_PROVIDER_ERROR_CATEGORY,
272
- });
295
+ if (policy.enabled && policy.providerError.enabled) {
296
+ const fingerprint = quotaNotificationFingerprint({
297
+ kind: "provider-error",
298
+ cardId: card.cardId,
299
+ category: QUOTA_NOTIFICATION_PROVIDER_ERROR_CATEGORY,
300
+ });
301
+ emit(fingerprint, {
302
+ ...notificationBase(card, fingerprint, nowMs),
303
+ kind: "provider-error",
304
+ category: QUOTA_NOTIFICATION_PROVIDER_ERROR_CATEGORY,
305
+ });
306
+ }
273
307
  }
274
308
  return {
275
309
  notifications,
@@ -1,11 +1,10 @@
1
1
  import type { QuotaSnapshot, SettingsSnapshot } from "../contracts/dashboard.js";
2
- import { type PercentDisplayMode } from "../lib/types.js";
2
+ import { type NativeQuotaNotificationPolicy, type PercentDisplayMode } from "../lib/types.js";
3
3
  import type { DashboardRpcQuotaNotificationData } from "../rpc.js";
4
4
  import { type GuiLogger } from "./log.js";
5
5
  /** Effective settings for one observation. */
6
6
  export interface QuotaNotificationSettings {
7
- readonly lowThresholdPercent: number;
8
- readonly cooldownMs: number;
7
+ readonly policy: NativeQuotaNotificationPolicy;
9
8
  readonly hiddenCards: readonly string[];
10
9
  readonly hiddenRows: readonly string[];
11
10
  readonly percentDisplayMode: PercentDisplayMode;
@@ -18,9 +18,10 @@
18
18
  */
19
19
  import { readFile } from "node:fs/promises";
20
20
  import { writeJsonAtomic } from "../lib/atomic-json.js";
21
+ import { isValidDuplicateCooldownMinutes, isValidLowQuotaThresholdRemainingPercent, isValidNativeQuotaNotificationPolicy, } from "../lib/config.js";
21
22
  import { formatResetCountdown } from "../lib/format-utils.js";
22
23
  import { getGuiPrivateStatePath } from "../lib/private-state-paths.js";
23
- import { DEFAULT_CONFIG } from "../lib/types.js";
24
+ import { DEFAULT_CONFIG, } from "../lib/types.js";
24
25
  import { createGuiLogger } from "./log.js";
25
26
  import { detectQuotaNotifications, QUOTA_NOTIFICATION_DETECTOR_STATE_VERSION, } from "./quota-notification-detector.js";
26
27
  const PERSISTED_STATE_VERSION = 1;
@@ -33,15 +34,6 @@ function isRecord(value) {
33
34
  function isFiniteNumber(value) {
34
35
  return typeof value === "number" && Number.isFinite(value);
35
36
  }
36
- function numberSetting(values, key, fallback, min, max) {
37
- const value = values[key];
38
- if (value === undefined || value === null)
39
- return fallback;
40
- if (!isFiniteNumber(value) || value < min || value > max) {
41
- throw new Error(CONFIG_UNAVAILABLE);
42
- }
43
- return value;
44
- }
45
37
  function displayModeSetting(values) {
46
38
  const value = values.percentDisplayMode;
47
39
  if (value === undefined || value === null)
@@ -62,6 +54,64 @@ function hiddenIds(value) {
62
54
  }
63
55
  return result;
64
56
  }
57
+ function nativeQuotaNotificationPolicyFromValues(values) {
58
+ const rawPolicy = values.nativeQuotaNotifications;
59
+ if (rawPolicy !== undefined && !isRecord(rawPolicy))
60
+ throw new Error(CONFIG_UNAVAILABLE);
61
+ const fields = isRecord(rawPolicy) ? rawPolicy : {};
62
+ const defaults = DEFAULT_CONFIG.nativeQuotaNotifications;
63
+ const candidate = {
64
+ ...defaults,
65
+ ...fields,
66
+ low: Object.hasOwn(fields, "low")
67
+ ? isRecord(fields.low)
68
+ ? { ...defaults.low, ...fields.low }
69
+ : fields.low
70
+ : { ...defaults.low },
71
+ exhausted: Object.hasOwn(fields, "exhausted")
72
+ ? isRecord(fields.exhausted)
73
+ ? { ...defaults.exhausted, ...fields.exhausted }
74
+ : fields.exhausted
75
+ : { ...defaults.exhausted },
76
+ reset: Object.hasOwn(fields, "reset")
77
+ ? isRecord(fields.reset)
78
+ ? { ...defaults.reset, ...fields.reset }
79
+ : fields.reset
80
+ : { ...defaults.reset, windows: [...defaults.reset.windows] },
81
+ providerError: Object.hasOwn(fields, "providerError")
82
+ ? isRecord(fields.providerError)
83
+ ? { ...defaults.providerError, ...fields.providerError }
84
+ : fields.providerError
85
+ : { ...defaults.providerError },
86
+ };
87
+ if (!isValidNativeQuotaNotificationPolicy(candidate))
88
+ throw new Error(CONFIG_UNAVAILABLE);
89
+ const policy = {
90
+ ...candidate,
91
+ low: { ...candidate.low },
92
+ exhausted: { ...candidate.exhausted },
93
+ reset: { ...candidate.reset, windows: [...candidate.reset.windows] },
94
+ providerError: { ...candidate.providerError },
95
+ };
96
+ const hasCanonicalLowThreshold = isRecord(fields.low) && Object.hasOwn(fields.low, "thresholdRemainingPercent");
97
+ const legacyLowThreshold = values.lowQuotaThresholdRemainingPercent;
98
+ if (!hasCanonicalLowThreshold &&
99
+ legacyLowThreshold !== undefined &&
100
+ legacyLowThreshold !== null) {
101
+ if (!isValidLowQuotaThresholdRemainingPercent(legacyLowThreshold)) {
102
+ throw new Error(CONFIG_UNAVAILABLE);
103
+ }
104
+ policy.low.thresholdRemainingPercent = legacyLowThreshold;
105
+ }
106
+ const hasCanonicalCooldown = Object.hasOwn(fields, "duplicateCooldownMinutes");
107
+ const legacyCooldown = values.duplicateCooldownMinutes;
108
+ if (!hasCanonicalCooldown && legacyCooldown !== undefined && legacyCooldown !== null) {
109
+ if (!isValidDuplicateCooldownMinutes(legacyCooldown))
110
+ throw new Error(CONFIG_UNAVAILABLE);
111
+ policy.duplicateCooldownMinutes = legacyCooldown;
112
+ }
113
+ return policy;
114
+ }
65
115
  /**
66
116
  * Maps the canonical settings snapshot to the observer's effective values.
67
117
  * Missing keys use the product defaults; malformed values and malformed or
@@ -73,10 +123,9 @@ export function quotaNotificationSettingsFromSnapshot(snapshot) {
73
123
  throw new Error(CONFIG_UNAVAILABLE);
74
124
  if (!isRecord(snapshot.visibility))
75
125
  throw new Error(CONFIG_UNAVAILABLE);
76
- const cooldownMinutes = numberSetting(snapshot.values, "duplicateCooldownMinutes", DEFAULT_CONFIG.duplicateCooldownMinutes, 0, Number.MAX_SAFE_INTEGER);
126
+ const policy = nativeQuotaNotificationPolicyFromValues(snapshot.values);
77
127
  return {
78
- lowThresholdPercent: numberSetting(snapshot.values, "lowQuotaThresholdRemainingPercent", DEFAULT_CONFIG.lowQuotaThresholdRemainingPercent, 0, 100),
79
- cooldownMs: cooldownMinutes * 60_000,
128
+ policy,
80
129
  hiddenCards: hiddenIds(snapshot.visibility.hiddenCards),
81
130
  hiddenRows: hiddenIds(snapshot.visibility.hiddenRows),
82
131
  percentDisplayMode: displayModeSetting(snapshot.values),
@@ -274,17 +323,18 @@ export function createQuotaNotificationObserver(options) {
274
323
  if (closed || epoch !== sourceEpoch)
275
324
  return;
276
325
  const nowMs = now();
326
+ const cooldownMs = settings.policy.duplicateCooldownMinutes * 60_000;
277
327
  if (!cooldownsLoaded) {
278
328
  cooldowns = mergeCooldowns(cooldowns, await readCooldowns(statePath));
279
329
  cooldownsLoaded = true;
280
330
  if (closed || epoch !== sourceEpoch)
281
331
  return;
282
332
  }
283
- const prunedCooldowns = pruneCooldowns(cooldowns, nowMs, settings.cooldownMs);
333
+ const prunedCooldowns = pruneCooldowns(cooldowns, nowMs, cooldownMs);
284
334
  const cooldownsWerePruned = !sameCooldowns(cooldowns, prunedCooldowns);
285
335
  cooldowns = prunedCooldowns;
286
336
  if (cooldownsWerePruned) {
287
- const persisted = await persist(cooldowns, nowMs, settings.cooldownMs);
337
+ const persisted = await persist(cooldowns, nowMs, cooldownMs);
288
338
  cooldowns = persisted ?? cooldowns;
289
339
  if (closed || epoch !== sourceEpoch)
290
340
  return;
@@ -296,8 +346,7 @@ export function createQuotaNotificationObserver(options) {
296
346
  ...(needsBaseline || detectorState === undefined ? {} : { state: detectorState }),
297
347
  cooldowns,
298
348
  nowMs,
299
- lowThresholdPercent: settings.lowThresholdPercent,
300
- cooldownMs: settings.cooldownMs,
349
+ policy: settings.policy,
301
350
  });
302
351
  if (closed || epoch !== sourceEpoch)
303
352
  return;
@@ -307,10 +356,10 @@ export function createQuotaNotificationObserver(options) {
307
356
  providers: result.state.providers,
308
357
  };
309
358
  needsBaseline = false;
310
- cooldowns = pruneCooldowns(result.cooldowns, nowMs, settings.cooldownMs);
359
+ cooldowns = pruneCooldowns(result.cooldowns, nowMs, cooldownMs);
311
360
  if (result.notifications.length === 0)
312
361
  return;
313
- const persisted = await persist(cooldowns, nowMs, settings.cooldownMs);
362
+ const persisted = await persist(cooldowns, nowMs, cooldownMs);
314
363
  cooldowns = persisted ?? cooldowns;
315
364
  // A handoff can land while the cooldown write is in flight. Fence before
316
365
  // publishing so the old source's event never reaches the new generation.
package/dist/gui/rpc.d.ts CHANGED
@@ -38,6 +38,8 @@ export interface DashboardRpcLocation {
38
38
  }
39
39
  export interface RegisterDashboardRpcOptions {
40
40
  logger?: GuiLogger;
41
+ /** Enqueues a source-state snapshot through this registration's owner relay. */
42
+ onWatchSnapshot?: (attemptNonce: string) => void;
41
43
  /**
42
44
  * The complete location this setup serves. OpenCode's event bus filters on
43
45
  * both `directory` and `workspaceID`, so sharing is keyed by both: setups at
package/dist/gui/rpc.js CHANGED
@@ -132,10 +132,18 @@ function waitForAbort(signal, onStop) {
132
132
  signal.addEventListener("abort", finish, { once: true });
133
133
  });
134
134
  }
135
- function createHandlers(runtime, heldWatches) {
135
+ function createHandlers(runtime, heldWatches, onWatchSnapshot) {
136
136
  async function watch(input, context) {
137
137
  return guard(context, async () => {
138
138
  const viewer = runtime.snapshots.addScopedViewer(input.scope);
139
+ if (!context.signal.aborted && input.attemptNonce !== undefined) {
140
+ try {
141
+ onWatchSnapshot?.(input.attemptNonce);
142
+ }
143
+ catch {
144
+ // Snapshot relay failure cannot interrupt this held viewer's lifecycle.
145
+ }
146
+ }
139
147
  let stopped = false;
140
148
  let stop = () => { };
141
149
  await waitForAbort(context.signal, (finish) => {
@@ -159,7 +167,7 @@ function createHandlers(runtime, heldWatches) {
159
167
  version: BUILD_IDENTITY.version,
160
168
  build: BUILD_IDENTITY.build,
161
169
  }),
162
- quota: (_input, context) => guard(context, () => runtime.snapshots.quota()),
170
+ quota: (input, context) => guard(context, () => runtime.snapshots.quota(input)),
163
171
  home: (input, context) => guard(context, () => runtime.snapshots.home(input)),
164
172
  groups: (input, context) => guard(context, () => runtime.snapshots.groups(input)),
165
173
  project: (input, context) => guard(context, () => runtime.snapshots.project(input)),
@@ -278,7 +286,7 @@ export async function registerDashboardRpc(rpc, runtime, options = {}) {
278
286
  const logger = options.logger ?? createGuiLogger();
279
287
  const key = locationKey(options.location);
280
288
  const heldWatches = new Set();
281
- const registration = await rpc.register(DashboardRpc, createHandlers(runtime, heldWatches));
289
+ const registration = await rpc.register(DashboardRpc, createHandlers(runtime, heldWatches, options.onWatchSnapshot));
282
290
  const member = { registration, heldWatches, alive: true };
283
291
  const entry = joinSharedEntry(runtime.snapshots, key, member, runtime.quotaNotifications);
284
292
  let disposed = false;
@@ -426,11 +426,20 @@ export function createDashboardServer(options) {
426
426
  return;
427
427
  }
428
428
  if (rest.length === 1 && rest[0] === "quota") {
429
- if (!requireMethods(req, res, ["GET", "HEAD"]))
429
+ if (!requireMethods(req, res, ["GET", "HEAD", "POST"]))
430
430
  return;
431
+ if (method === "POST") {
432
+ const parsed = await readWriteJson(req, res);
433
+ if (!parsed.ok)
434
+ return;
435
+ if (!isRecord(parsed.value) || !hasExactKeys(parsed.value, [])) {
436
+ sendError(res, "bad-request");
437
+ return;
438
+ }
439
+ }
431
440
  // Inference only; an explicit PUT /api/v1/view signal wins.
432
441
  snapshots.setViewScope("quota", "request");
433
- sendJson(res, 200, await snapshots.quota());
442
+ sendJson(res, 200, await snapshots.quota(req.method === "POST" ? { refresh: true } : undefined));
434
443
  return;
435
444
  }
436
445
  if (rest.length === 1 && rest[0] === "home") {
@@ -106,7 +106,9 @@ export interface SnapshotService {
106
106
  home(input: {
107
107
  range: RangeKey;
108
108
  }): Promise<HomeSnapshot>;
109
- quota(): Promise<QuotaSnapshot>;
109
+ quota(input?: {
110
+ refresh?: boolean;
111
+ }): Promise<QuotaSnapshot>;
110
112
  project(input: {
111
113
  projectId: string;
112
114
  range: RangeKey;