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
@@ -42,6 +42,7 @@ export const QUOTA_TOAST_SETTING_SOURCE_KEYS = [
42
42
  "enableToast",
43
43
  "resetNotifications.enabled",
44
44
  "resetNotifications.windows",
45
+ "nativeQuotaNotifications",
45
46
  "lowQuotaThresholdRemainingPercent",
46
47
  "duplicateCooldownMinutes",
47
48
  "tuiCommandDisplay",
@@ -231,6 +232,16 @@ function cloneConfig(config) {
231
232
  ...config.resetNotifications,
232
233
  windows: [...config.resetNotifications.windows],
233
234
  },
235
+ nativeQuotaNotifications: {
236
+ ...config.nativeQuotaNotifications,
237
+ low: { ...config.nativeQuotaNotifications.low },
238
+ exhausted: { ...config.nativeQuotaNotifications.exhausted },
239
+ reset: {
240
+ ...config.nativeQuotaNotifications.reset,
241
+ windows: [...config.nativeQuotaNotifications.reset.windows],
242
+ },
243
+ providerError: { ...config.nativeQuotaNotifications.providerError },
244
+ },
234
245
  opencodeGoWindows: [...config.opencodeGoWindows],
235
246
  opencodeMonthlyLimit: config.opencodeMonthlyLimit,
236
247
  pricingSnapshot: { ...config.pricingSnapshot },
@@ -291,6 +302,133 @@ function extractQuotaResetNotificationsPatch(value, reportIssue) {
291
302
  }
292
303
  return Object.keys(patch).length > 0 ? patch : undefined;
293
304
  }
305
+ export function isValidNativeQuotaNotificationPolicy(value) {
306
+ if (!isPlainObject(value))
307
+ return false;
308
+ if (typeof value.enabled !== "boolean")
309
+ return false;
310
+ if (typeof value.modelChangeToastEnabled !== "boolean")
311
+ return false;
312
+ if (!isPlainObject(value.low) || typeof value.low.enabled !== "boolean")
313
+ return false;
314
+ if (!isValidLowQuotaThresholdRemainingPercent(value.low.thresholdRemainingPercent))
315
+ return false;
316
+ if (!isPlainObject(value.exhausted) || typeof value.exhausted.enabled !== "boolean")
317
+ return false;
318
+ if (!isPlainObject(value.reset) || typeof value.reset.enabled !== "boolean")
319
+ return false;
320
+ if (!Array.isArray(value.reset.windows) ||
321
+ !value.reset.windows.every((window) => QUOTA_RESET_WINDOWS.includes(window))) {
322
+ return false;
323
+ }
324
+ if (!isPlainObject(value.providerError) || typeof value.providerError.enabled !== "boolean") {
325
+ return false;
326
+ }
327
+ return isValidDuplicateCooldownMinutes(value.duplicateCooldownMinutes);
328
+ }
329
+ function extractNativeQuotaNotificationPolicyPatch(value, reportIssue) {
330
+ if (!isPlainObject(value))
331
+ return undefined;
332
+ const patch = {};
333
+ if (hasOwnKey(value, "enabled")) {
334
+ if (typeof value.enabled === "boolean")
335
+ patch.enabled = value.enabled;
336
+ else
337
+ reportIssue?.("nativeQuotaNotifications.enabled", "expected boolean");
338
+ }
339
+ if (hasOwnKey(value, "modelChangeToastEnabled")) {
340
+ if (typeof value.modelChangeToastEnabled === "boolean") {
341
+ patch.modelChangeToastEnabled = value.modelChangeToastEnabled;
342
+ }
343
+ else {
344
+ reportIssue?.("nativeQuotaNotifications.modelChangeToastEnabled", "expected boolean");
345
+ }
346
+ }
347
+ if (hasOwnKey(value, "low")) {
348
+ if (!isPlainObject(value.low)) {
349
+ reportIssue?.("nativeQuotaNotifications.low", "expected object");
350
+ }
351
+ else {
352
+ const low = {};
353
+ if (hasOwnKey(value.low, "enabled")) {
354
+ if (typeof value.low.enabled === "boolean")
355
+ low.enabled = value.low.enabled;
356
+ else
357
+ reportIssue?.("nativeQuotaNotifications.low.enabled", "expected boolean");
358
+ }
359
+ if (hasOwnKey(value.low, "thresholdRemainingPercent")) {
360
+ if (isValidLowQuotaThresholdRemainingPercent(value.low.thresholdRemainingPercent)) {
361
+ low.thresholdRemainingPercent = value.low.thresholdRemainingPercent;
362
+ }
363
+ else {
364
+ reportIssue?.("nativeQuotaNotifications.low.thresholdRemainingPercent", "expected an integer between 1 and 100");
365
+ }
366
+ }
367
+ if (Object.keys(low).length > 0)
368
+ patch.low = low;
369
+ }
370
+ }
371
+ if (hasOwnKey(value, "exhausted")) {
372
+ if (!isPlainObject(value.exhausted)) {
373
+ reportIssue?.("nativeQuotaNotifications.exhausted", "expected object");
374
+ }
375
+ else if (hasOwnKey(value.exhausted, "enabled")) {
376
+ if (typeof value.exhausted.enabled === "boolean") {
377
+ patch.exhausted = { enabled: value.exhausted.enabled };
378
+ }
379
+ else {
380
+ reportIssue?.("nativeQuotaNotifications.exhausted.enabled", "expected boolean");
381
+ }
382
+ }
383
+ }
384
+ if (hasOwnKey(value, "reset")) {
385
+ if (!isPlainObject(value.reset)) {
386
+ reportIssue?.("nativeQuotaNotifications.reset", "expected object");
387
+ }
388
+ else {
389
+ const reset = {};
390
+ if (hasOwnKey(value.reset, "enabled")) {
391
+ if (typeof value.reset.enabled === "boolean")
392
+ reset.enabled = value.reset.enabled;
393
+ else
394
+ reportIssue?.("nativeQuotaNotifications.reset.enabled", "expected boolean");
395
+ }
396
+ if (hasOwnKey(value.reset, "windows")) {
397
+ if (Array.isArray(value.reset.windows) &&
398
+ value.reset.windows.every((window) => QUOTA_RESET_WINDOWS.includes(window))) {
399
+ reset.windows = dedupe(value.reset.windows);
400
+ }
401
+ else {
402
+ reportIssue?.("nativeQuotaNotifications.reset.windows", `expected an array of: ${QUOTA_RESET_WINDOWS.join(", ")}`);
403
+ }
404
+ }
405
+ if (Object.keys(reset).length > 0)
406
+ patch.reset = reset;
407
+ }
408
+ }
409
+ if (hasOwnKey(value, "providerError")) {
410
+ if (!isPlainObject(value.providerError)) {
411
+ reportIssue?.("nativeQuotaNotifications.providerError", "expected object");
412
+ }
413
+ else if (hasOwnKey(value.providerError, "enabled")) {
414
+ if (typeof value.providerError.enabled === "boolean") {
415
+ patch.providerError = { enabled: value.providerError.enabled };
416
+ }
417
+ else {
418
+ reportIssue?.("nativeQuotaNotifications.providerError.enabled", "expected boolean");
419
+ }
420
+ }
421
+ }
422
+ if (hasOwnKey(value, "duplicateCooldownMinutes")) {
423
+ if (isValidDuplicateCooldownMinutes(value.duplicateCooldownMinutes)) {
424
+ patch.duplicateCooldownMinutes = value.duplicateCooldownMinutes;
425
+ }
426
+ else {
427
+ reportIssue?.("nativeQuotaNotifications.duplicateCooldownMinutes", "expected an integer of 0 or more");
428
+ }
429
+ }
430
+ return Object.keys(patch).length > 0 ? patch : undefined;
431
+ }
294
432
  function describeInvalidProviderValue(value) {
295
433
  return typeof value === "string" ? value : typeof value;
296
434
  }
@@ -553,6 +691,11 @@ function extractValidatedQuotaToastPatch(quotaToastConfig, reportIssue, options
553
691
  if (resetNotifications)
554
692
  patch.resetNotifications = resetNotifications;
555
693
  }
694
+ if (hasOwnKey(quotaToastConfig, "nativeQuotaNotifications")) {
695
+ const nativeQuotaNotifications = extractNativeQuotaNotificationPolicyPatch(quotaToastConfig.nativeQuotaNotifications, reportIssue);
696
+ if (nativeQuotaNotifications)
697
+ patch.nativeQuotaNotifications = nativeQuotaNotifications;
698
+ }
556
699
  if (hasOwnKey(quotaToastConfig, "lowQuotaThresholdRemainingPercent")) {
557
700
  if (isValidLowQuotaThresholdRemainingPercent(quotaToastConfig.lowQuotaThresholdRemainingPercent)) {
558
701
  patch.lowQuotaThresholdRemainingPercent = quotaToastConfig.lowQuotaThresholdRemainingPercent;
@@ -770,7 +913,7 @@ function extractValidatedQuotaToastPatch(quotaToastConfig, reportIssue, options
770
913
  function applySettingSource(settingSources, key, sourcePath) {
771
914
  settingSources[key] = sourcePath;
772
915
  }
773
- function applyValidatedQuotaToastPatch(config, patch, sourcePath, settingSources) {
916
+ function applyValidatedQuotaToastPatch(config, patch, sourcePath, settingSources, nativeQuotaNotificationCanonicalFields = new Set()) {
774
917
  if (hasOwnKey(patch, "enabled")) {
775
918
  config.enabled = patch.enabled;
776
919
  applySettingSource(settingSources, "enabled", sourcePath);
@@ -789,13 +932,60 @@ function applyValidatedQuotaToastPatch(config, patch, sourcePath, settingSources
789
932
  applySettingSource(settingSources, "resetNotifications.windows", sourcePath);
790
933
  }
791
934
  }
935
+ if (patch.nativeQuotaNotifications) {
936
+ const policy = patch.nativeQuotaNotifications;
937
+ if (hasOwnKey(policy, "enabled")) {
938
+ config.nativeQuotaNotifications.enabled = policy.enabled;
939
+ }
940
+ if (hasOwnKey(policy, "modelChangeToastEnabled")) {
941
+ config.nativeQuotaNotifications.modelChangeToastEnabled = policy.modelChangeToastEnabled;
942
+ }
943
+ if (policy.low) {
944
+ if (hasOwnKey(policy.low, "enabled")) {
945
+ config.nativeQuotaNotifications.low.enabled = policy.low.enabled;
946
+ }
947
+ if (hasOwnKey(policy.low, "thresholdRemainingPercent")) {
948
+ config.nativeQuotaNotifications.low.thresholdRemainingPercent =
949
+ policy.low.thresholdRemainingPercent;
950
+ nativeQuotaNotificationCanonicalFields.add("low.thresholdRemainingPercent");
951
+ }
952
+ }
953
+ if (policy.exhausted && hasOwnKey(policy.exhausted, "enabled")) {
954
+ config.nativeQuotaNotifications.exhausted.enabled = policy.exhausted.enabled;
955
+ }
956
+ if (policy.reset) {
957
+ if (hasOwnKey(policy.reset, "enabled")) {
958
+ config.nativeQuotaNotifications.reset.enabled = policy.reset.enabled;
959
+ }
960
+ if (hasOwnKey(policy.reset, "windows")) {
961
+ config.nativeQuotaNotifications.reset.windows = [...policy.reset.windows];
962
+ }
963
+ }
964
+ if (policy.providerError && hasOwnKey(policy.providerError, "enabled")) {
965
+ config.nativeQuotaNotifications.providerError.enabled = policy.providerError.enabled;
966
+ }
967
+ if (hasOwnKey(policy, "duplicateCooldownMinutes")) {
968
+ config.nativeQuotaNotifications.duplicateCooldownMinutes = policy.duplicateCooldownMinutes;
969
+ nativeQuotaNotificationCanonicalFields.add("duplicateCooldownMinutes");
970
+ }
971
+ applySettingSource(settingSources, "nativeQuotaNotifications", sourcePath);
972
+ }
792
973
  if (hasOwnKey(patch, "lowQuotaThresholdRemainingPercent")) {
793
974
  config.lowQuotaThresholdRemainingPercent = patch.lowQuotaThresholdRemainingPercent;
794
975
  applySettingSource(settingSources, "lowQuotaThresholdRemainingPercent", sourcePath);
976
+ if (!nativeQuotaNotificationCanonicalFields.has("low.thresholdRemainingPercent")) {
977
+ config.nativeQuotaNotifications.low.thresholdRemainingPercent =
978
+ patch.lowQuotaThresholdRemainingPercent;
979
+ applySettingSource(settingSources, "nativeQuotaNotifications", sourcePath);
980
+ }
795
981
  }
796
982
  if (hasOwnKey(patch, "duplicateCooldownMinutes")) {
797
983
  config.duplicateCooldownMinutes = patch.duplicateCooldownMinutes;
798
984
  applySettingSource(settingSources, "duplicateCooldownMinutes", sourcePath);
985
+ if (!nativeQuotaNotificationCanonicalFields.has("duplicateCooldownMinutes")) {
986
+ config.nativeQuotaNotifications.duplicateCooldownMinutes = patch.duplicateCooldownMinutes;
987
+ applySettingSource(settingSources, "nativeQuotaNotifications", sourcePath);
988
+ }
799
989
  }
800
990
  if (hasOwnKey(patch, "tuiCommandDisplay")) {
801
991
  config.tuiCommandDisplay = patch.tuiCommandDisplay;
@@ -1148,6 +1338,7 @@ export async function loadConfigLayered(client, meta, options) {
1148
1338
  const globalConfigPaths = [];
1149
1339
  const workspaceConfigPaths = [];
1150
1340
  const settingSources = {};
1341
+ const nativeQuotaNotificationCanonicalFields = new Set();
1151
1342
  const settingSourceLayers = {};
1152
1343
  const configIssues = [];
1153
1344
  const authoritativeSidecarRoots = new Set();
@@ -1212,7 +1403,7 @@ export async function loadConfigLayered(client, meta, options) {
1212
1403
  }
1213
1404
  applyValidatedQuotaToastPatch(config, extractValidatedQuotaToastPatch(extractedQuotaToast, (key, message) => {
1214
1405
  configIssues.push({ path: sourcePath, key, message });
1215
- }, { allowZeroMonthlyLimit: candidate.kind === "canonical" }), sourcePath, settingSources);
1406
+ }, { allowZeroMonthlyLimit: candidate.kind === "canonical" }), sourcePath, settingSources, nativeQuotaNotificationCanonicalFields);
1216
1407
  if (hasOwnKey(extractedQuotaToast, "alibabaCodingPlanTier")) {
1217
1408
  configIssues.push({
1218
1409
  path: sourcePath,
@@ -7,8 +7,9 @@
7
7
  */
8
8
  import { existsSync, readFileSync } from "fs";
9
9
  import { join } from "path";
10
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
10
11
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
11
- import { fetchWithTimeout } from "./http.js";
12
+ import { fetchWithTimeout, RequestTimeoutError } from "./http.js";
12
13
  import { readAuthFile } from "./opencode-auth.js";
13
14
  import { getOpencodeRuntimeDirs } from "./opencode-runtime-paths.js";
14
15
  import { deriveResolvedAuthIdentity } from "./resolved-auth-identity.js";
@@ -465,15 +466,30 @@ function redactGitHubErrorText(text, secrets) {
465
466
  }
466
467
  class CopilotRequestError extends Error {
467
468
  failureCategory;
468
- constructor(message, failureCategory) {
469
+ retryAtMs;
470
+ constructor(message, failureCategory, retryAtMs) {
469
471
  super(message);
470
472
  this.failureCategory = failureCategory;
473
+ this.retryAtMs = retryAtMs;
471
474
  this.name = "CopilotRequestError";
472
475
  }
473
476
  }
474
477
  function requestFailureCategory(error) {
475
478
  return error instanceof CopilotRequestError ? error.failureCategory : "provider_api";
476
479
  }
480
+ function requestRetryAtMs(error) {
481
+ if (error instanceof CopilotRequestError)
482
+ return error.retryAtMs;
483
+ return error instanceof RequestTimeoutError ? error.retryAtMs : undefined;
484
+ }
485
+ function preserveRetryAtOnTimeout(error, retryAtMs) {
486
+ return error instanceof RequestTimeoutError &&
487
+ error.retryAtMs === undefined &&
488
+ retryAtMs !== undefined
489
+ ? new RequestTimeoutError(error.message, retryAtMs)
490
+ : error;
491
+ }
492
+ const guard = createApiKeyRetryGuard((retryAtMs) => toQuotaError("GitHub API error 429", "provider_api", retryAtMs));
477
493
  async function readGitHubRestErrorMessage(response, secrets) {
478
494
  const text = await response.text();
479
495
  try {
@@ -503,27 +519,53 @@ async function readGitHubRestErrorMessageForClassification(response, secrets) {
503
519
  return "response body could not be read";
504
520
  }
505
521
  }
522
+ /**
523
+ * A 429, or a 403 GitHub itself marks as a rate limit (exhausted primary limit
524
+ * or the documented secondary-limit message). Only then is Retry-After read,
525
+ * so a permission 403 never gets a cooldown.
526
+ */
527
+ function classifyGitHubRateLimit(response, message) {
528
+ const limited = response.status === 429 ||
529
+ (response.status === 403 &&
530
+ (response.headers.get("x-ratelimit-remaining") === "0" ||
531
+ /secondary rate limit/iu.test(message)));
532
+ if (!limited)
533
+ return { limited };
534
+ // retryAfterDeadline only accepts 429; re-present the same headers as one.
535
+ const retryAtMs = retryAfterDeadline(new Response(null, { status: 429, headers: response.headers }));
536
+ return { limited, ...(retryAtMs !== undefined ? { retryAtMs } : {}) };
537
+ }
506
538
  async function fetchGitHubRestJson(url, token, requestTimeoutMs) {
507
- return await fetchWithTimeout(url, {
508
- request: { headers: buildGitHubRestHeaders(token) },
509
- timeoutMs: requestTimeoutMs,
510
- consume: async (response) => {
511
- if (!response.ok) {
512
- const message = await readGitHubRestErrorMessageForClassification(response, [token]);
513
- const rateLimited = response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0";
514
- const rateLimit = rateLimited ? " (GitHub API rate limit exhausted)" : "";
515
- throw new CopilotRequestError(`GitHub API error ${response.status}: ${message}${rateLimit}`, response.status === 401 || (response.status === 403 && !rateLimited)
516
- ? "credentials"
517
- : "provider_api");
518
- }
519
- try {
520
- return (await response.json());
521
- }
522
- catch {
523
- throw new CopilotRequestError("GitHub API returned malformed JSON", "provider_api");
524
- }
525
- },
526
- });
539
+ let observedRetryAtMs;
540
+ try {
541
+ return await fetchWithTimeout(url, {
542
+ request: { headers: buildGitHubRestHeaders(token) },
543
+ timeoutMs: requestTimeoutMs,
544
+ consume: async (response) => {
545
+ if (!response.ok) {
546
+ if (response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
547
+ // Snapshot a confirmed primary limit before its body can stall.
548
+ observedRetryAtMs = classifyGitHubRateLimit(response, "").retryAtMs;
549
+ }
550
+ const message = await readGitHubRestErrorMessageForClassification(response, [token]);
551
+ const limit = classifyGitHubRateLimit(response, message);
552
+ const rateLimit = response.status === 403 && limit.limited ? " (GitHub API rate limit exhausted)" : "";
553
+ throw new CopilotRequestError(`GitHub API error ${response.status}: ${message}${rateLimit}`, response.status === 401 || (response.status === 403 && !limit.limited)
554
+ ? "credentials"
555
+ : "provider_api", limit.retryAtMs);
556
+ }
557
+ try {
558
+ return (await response.json());
559
+ }
560
+ catch {
561
+ throw new CopilotRequestError("GitHub API returned malformed JSON", "provider_api");
562
+ }
563
+ },
564
+ });
565
+ }
566
+ catch (error) {
567
+ throw preserveRetryAtOnTimeout(error, observedRetryAtMs);
568
+ }
527
569
  }
528
570
  async function resolveGitHubUsername(apiBaseUrl, token, requestTimeoutMs) {
529
571
  const response = await fetchGitHubRestJson(`${apiBaseUrl}/user`, token, requestTimeoutMs);
@@ -788,6 +830,12 @@ async function fetchApplicableBudget(params) {
788
830
  authority: percentRemaining === undefined ? "provider_reported" : "locally_derived",
789
831
  };
790
832
  }
833
+ // Separate from the usage guard: a limited budget report must not block usage.
834
+ const budgetGuard = createApiKeyRetryGuard((retryAtMs) => ({
835
+ success: false,
836
+ error: `GitHub API error 429: budget report rate limited until ${new Date(retryAtMs).toISOString()}`,
837
+ retryAtMs,
838
+ }));
791
839
  function makeBudgetWarning(error) {
792
840
  const message = error instanceof Error ? error.message : String(error);
793
841
  return `AI Credit usage loaded, but the budget report failed: ${message}`;
@@ -798,18 +846,33 @@ async function toAiCreditResult(params) {
798
846
  let budget;
799
847
  const warnings = [];
800
848
  if (params.target.scope !== "user") {
801
- try {
802
- budget = await fetchApplicableBudget({
803
- apiBaseUrl: params.apiBaseUrl,
804
- token: params.token,
805
- target: params.target,
806
- spentUsd: totals.billedAmountUsd,
807
- requestTimeoutMs: params.requestTimeoutMs,
808
- });
809
- }
810
- catch (error) {
811
- warnings.push(makeBudgetWarning(error));
812
- }
849
+ const target = params.target;
850
+ const fetched = await budgetGuard(`budget\0${params.apiBaseUrl}\0${params.token}`, async () => {
851
+ try {
852
+ return {
853
+ success: true,
854
+ budget: await fetchApplicableBudget({
855
+ apiBaseUrl: params.apiBaseUrl,
856
+ token: params.token,
857
+ target,
858
+ spentUsd: totals.billedAmountUsd,
859
+ requestTimeoutMs: params.requestTimeoutMs,
860
+ }),
861
+ };
862
+ }
863
+ catch (error) {
864
+ const retryAtMs = requestRetryAtMs(error);
865
+ return {
866
+ success: false,
867
+ error: error instanceof Error ? error.message : String(error),
868
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
869
+ };
870
+ }
871
+ }, params.requestTimeoutMs, undefined, JSON.stringify({ target, spentUsd: totals.billedAmountUsd }));
872
+ if (fetched.success)
873
+ budget = fetched.budget;
874
+ else
875
+ warnings.push(makeBudgetWarning(new Error(fetched.error)));
813
876
  }
814
877
  if (params.target.scope === "organization") {
815
878
  return {
@@ -861,11 +924,12 @@ function toLegacyResult(response, config) {
861
924
  resetTimeIso: getApproxNextResetIso(),
862
925
  };
863
926
  }
864
- function toQuotaError(message, failureCategory) {
927
+ function toQuotaError(message, failureCategory, retryAtMs) {
865
928
  return {
866
929
  success: false,
867
930
  error: message,
868
931
  ...(failureCategory !== undefined ? { failureCategory } : {}),
932
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
869
933
  };
870
934
  }
871
935
  function buildCopilotInternalHeaders(token) {
@@ -984,27 +1048,42 @@ function parseCopilotInternalUser(response) {
984
1048
  throw new Error("GitHub Copilot user response did not include a usable quota snapshot");
985
1049
  }
986
1050
  async function fetchCopilotInternalUser(params) {
987
- return await fetchWithTimeout(`${params.apiBaseUrl}${COPILOT_INTERNAL_USER_PATH}`, {
988
- request: { headers: buildCopilotInternalHeaders(params.token) },
989
- timeoutMs: params.requestTimeoutMs,
990
- consume: async (response) => {
991
- if (!response.ok) {
992
- const message = await readGitHubRestErrorMessageForClassification(response, [params.token]);
993
- throw new CopilotRequestError(`GitHub Copilot API error ${response.status}: ${message}`, response.status === 401 || response.status === 403 ? "credentials" : "provider_api");
994
- }
995
- let parsed;
996
- try {
997
- parsed = (await response.json());
998
- }
999
- catch {
1000
- throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1001
- }
1002
- if (!parsed || typeof parsed !== "object") {
1003
- throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1004
- }
1005
- return parseCopilotInternalUser(parsed);
1006
- },
1007
- });
1051
+ let observedRetryAtMs;
1052
+ try {
1053
+ return await fetchWithTimeout(`${params.apiBaseUrl}${COPILOT_INTERNAL_USER_PATH}`, {
1054
+ request: { headers: buildCopilotInternalHeaders(params.token) },
1055
+ timeoutMs: params.requestTimeoutMs,
1056
+ consume: async (response) => {
1057
+ if (!response.ok) {
1058
+ if (response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
1059
+ // Snapshot a confirmed primary limit before its body can stall.
1060
+ observedRetryAtMs = classifyGitHubRateLimit(response, "").retryAtMs;
1061
+ }
1062
+ const message = await readGitHubRestErrorMessageForClassification(response, [
1063
+ params.token,
1064
+ ]);
1065
+ const limit = classifyGitHubRateLimit(response, message);
1066
+ throw new CopilotRequestError(`GitHub Copilot API error ${response.status}: ${message}`, response.status === 401 || (response.status === 403 && !limit.limited)
1067
+ ? "credentials"
1068
+ : "provider_api", limit.retryAtMs);
1069
+ }
1070
+ let parsed;
1071
+ try {
1072
+ parsed = (await response.json());
1073
+ }
1074
+ catch {
1075
+ throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1076
+ }
1077
+ if (!parsed || typeof parsed !== "object") {
1078
+ throw new CopilotRequestError("GitHub Copilot API returned malformed JSON", "provider_api");
1079
+ }
1080
+ return parseCopilotInternalUser(parsed);
1081
+ },
1082
+ });
1083
+ }
1084
+ catch (error) {
1085
+ throw preserveRetryAtOnTimeout(error, observedRetryAtMs);
1086
+ }
1008
1087
  }
1009
1088
  /**
1010
1089
  * Query GitHub Copilot accounting.
@@ -1029,16 +1108,19 @@ export async function queryCopilotQuota(options = {}) {
1029
1108
  if (enterpriseHost.error) {
1030
1109
  return toQuotaError(`Invalid OpenCode Copilot enterpriseUrl: ${enterpriseHost.error}`);
1031
1110
  }
1032
- try {
1033
- return await fetchCopilotInternalUser({
1034
- apiBaseUrl: getApiBaseUrl(enterpriseHost.host),
1035
- token,
1036
- requestTimeoutMs: options.requestTimeoutMs,
1037
- });
1038
- }
1039
- catch (error) {
1040
- return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error));
1041
- }
1111
+ const apiBaseUrl = getApiBaseUrl(enterpriseHost.host);
1112
+ return await guard(`oauth\0${apiBaseUrl}\0${token}`, async () => {
1113
+ try {
1114
+ return await fetchCopilotInternalUser({
1115
+ apiBaseUrl,
1116
+ token,
1117
+ requestTimeoutMs: options.requestTimeoutMs,
1118
+ });
1119
+ }
1120
+ catch (error) {
1121
+ return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error), requestRetryAtMs(error));
1122
+ }
1123
+ }, options.requestTimeoutMs);
1042
1124
  }
1043
1125
  const resolved = resolvePatBillingTarget(pat.config);
1044
1126
  if (!resolved.target) {
@@ -1047,29 +1129,32 @@ export async function queryCopilotQuota(options = {}) {
1047
1129
  const compatibilityError = validatePatTargetCompatibility(resolved.target, pat.tokenKind);
1048
1130
  if (compatibilityError)
1049
1131
  return toQuotaError(compatibilityError);
1050
- try {
1051
- const billingModel = pat.config.billingModel ?? "ai_credits";
1052
- const apiBaseUrl = getApiBaseUrl(pat.config.enterpriseUrl);
1053
- const { response, target } = await fetchBillingUsage({
1054
- apiBaseUrl,
1055
- token: pat.config.token,
1056
- target: resolved.target,
1057
- billingModel,
1058
- requestTimeoutMs: options.requestTimeoutMs,
1059
- });
1060
- return billingModel === "legacy_premium_requests"
1061
- ? toLegacyResult(response, pat.config)
1062
- : await toAiCreditResult({
1132
+ const config = pat.config;
1133
+ const apiBaseUrl = getApiBaseUrl(config.enterpriseUrl);
1134
+ const billingModel = config.billingModel ?? "ai_credits";
1135
+ return await guard(`pat\0${apiBaseUrl}\0${config.token}`, async () => {
1136
+ try {
1137
+ const { response, target } = await fetchBillingUsage({
1063
1138
  apiBaseUrl,
1064
- response,
1065
- target,
1066
- token: pat.config.token,
1139
+ token: config.token,
1140
+ target: resolved.target,
1141
+ billingModel,
1067
1142
  requestTimeoutMs: options.requestTimeoutMs,
1068
1143
  });
1069
- }
1070
- catch (error) {
1071
- return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error));
1072
- }
1144
+ return billingModel === "legacy_premium_requests"
1145
+ ? toLegacyResult(response, config)
1146
+ : await toAiCreditResult({
1147
+ apiBaseUrl,
1148
+ response,
1149
+ target,
1150
+ token: config.token,
1151
+ requestTimeoutMs: options.requestTimeoutMs,
1152
+ });
1153
+ }
1154
+ catch (error) {
1155
+ return toQuotaError(error instanceof Error ? error.message : String(error), requestFailureCategory(error), requestRetryAtMs(error));
1156
+ }
1157
+ }, options.requestTimeoutMs, undefined, JSON.stringify({ billingModel, tier: config.tier, target: resolved.target }));
1073
1158
  }
1074
1159
  export async function resolveCopilotAuthIdentity() {
1075
1160
  const pat = readQuotaConfigWithMeta();
@@ -1,15 +1,15 @@
1
1
  /**
2
2
  * Effective localhost web dashboard switch.
3
3
  *
4
- * The Native GUI is the primary surface from OpenCode 2.2.0, so the compatibility
4
+ * The full Native GUI is the primary surface from OpenCode 2.2.1, so the compatibility
5
5
  * web transport follows the host version when the canonical key is absent:
6
- * hosts below 2.2.0 keep it on (the only GUI they have), and 2.2.0+ keeps it off.
6
+ * supported hosts below 2.2.1 keep it on (including 2.2.0), and 2.2.1+ keeps it off.
7
7
  * An explicit `dashboard.enabled` value always wins. Missing or unparseable host
8
8
  * versions, a malformed canonical file, and an invalid `dashboard.enabled` value
9
9
  * all fail closed. The listener itself stays loopback-only at `dashboard.port`.
10
10
  */
11
11
  import type { LoadConfigMeta } from "./config.js";
12
- import { type OpenCodeVersion } from "./opencode-version.js";
12
+ import { type OpenCodeVersion } from "./opencode-version-core.js";
13
13
  export interface DashboardWebPolicyInput {
14
14
  /** Canonical `dashboard.enabled` when the key is present and valid. */
15
15
  explicitEnabled?: boolean;
@@ -18,7 +18,7 @@ export interface DashboardWebPolicyInput {
18
18
  /** A malformed canonical file or an invalid `dashboard.enabled` fails closed. */
19
19
  invalidConfig?: boolean;
20
20
  }
21
- /** Explicit config wins; otherwise only a parseable pre-2.2.0 host defaults on. */
21
+ /** Explicit config wins; otherwise only a parseable pre-2.2.1 host defaults on. */
22
22
  export declare function resolveDashboardWebEnabled(input: DashboardWebPolicyInput): boolean;
23
23
  /**
24
24
  * The canonical value when the loader actually applied it. The setting-source
@@ -1,5 +1,5 @@
1
- import { isPreNativeGuiVersion } from "./opencode-version.js";
2
- /** Explicit config wins; otherwise only a parseable pre-2.2.0 host defaults on. */
1
+ import { isPreNativeGuiVersion } from "./opencode-version-core.js";
2
+ /** Explicit config wins; otherwise only a parseable pre-2.2.1 host defaults on. */
3
3
  export function resolveDashboardWebEnabled(input) {
4
4
  if (input.invalidConfig)
5
5
  return false;