opencode-quota-gui 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/README.md +16 -12
  2. package/dist/contracts/build-identity.js +1 -1
  3. package/dist/contracts/card-order.d.ts +2 -0
  4. package/dist/contracts/card-order.js +2 -2
  5. package/dist/contracts/card-visibility.d.ts +2 -1
  6. package/dist/contracts/card-visibility.js +2 -1
  7. package/dist/contracts/dashboard.d.ts +87 -5
  8. package/dist/contracts/dashboard.js +10 -0
  9. package/dist/contracts/dto-guards.d.ts +4 -0
  10. package/dist/contracts/dto-guards.js +29 -7
  11. package/dist/contracts/guards.js +3 -1
  12. package/dist/contracts/identity.d.ts +37 -5
  13. package/dist/contracts/identity.js +43 -0
  14. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  15. package/dist/contracts/provider-auto-resume.js +24 -0
  16. package/dist/contracts/provider-failure.d.ts +22 -0
  17. package/dist/contracts/provider-failure.js +25 -1
  18. package/dist/contracts/row-order.d.ts +13 -0
  19. package/dist/contracts/row-order.js +34 -0
  20. package/dist/contracts/row-visibility.d.ts +53 -0
  21. package/dist/contracts/row-visibility.js +130 -0
  22. package/dist/data/modelsdev-pricing.min.json +1 -1
  23. package/dist/data/modelsdev-temporal.min.json +3 -634
  24. package/dist/gui/aggregation.d.ts +29 -1
  25. package/dist/gui/aggregation.js +157 -4
  26. package/dist/gui/analytics-bridge.d.ts +8 -9
  27. package/dist/gui/analytics-bridge.js +197 -54
  28. package/dist/gui/analytics-engine.d.ts +7 -15
  29. package/dist/gui/analytics-engine.js +246 -106
  30. package/dist/gui/analytics-model.d.ts +7 -0
  31. package/dist/gui/analytics-model.js +75 -9
  32. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  33. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  34. package/dist/gui/analytics-protocol.d.ts +17 -7
  35. package/dist/gui/analytics-protocol.js +1 -0
  36. package/dist/gui/analytics-service.d.ts +10 -0
  37. package/dist/gui/analytics-service.js +30 -9
  38. package/dist/gui/analytics-state.d.ts +30 -5
  39. package/dist/gui/analytics-state.js +46 -7
  40. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  41. package/dist/gui/analytics-worker-runtime.js +9 -1
  42. package/dist/gui/analytics-worker.js +11 -0
  43. package/dist/gui/config.d.ts +2 -2
  44. package/dist/gui/config.js +46 -5
  45. package/dist/gui/identity.d.ts +6 -20
  46. package/dist/gui/identity.js +6 -54
  47. package/dist/gui/primary-quota-windows.js +55 -34
  48. package/dist/gui/provider-cards.d.ts +12 -8
  49. package/dist/gui/provider-cards.js +12 -53
  50. package/dist/gui/quota-notification-detector.d.ts +25 -2
  51. package/dist/gui/quota-notification-detector.js +60 -5
  52. package/dist/gui/quota-notification-observer.d.ts +1 -1
  53. package/dist/gui/quota-notification-observer.js +5 -1
  54. package/dist/gui/quota-observation.d.ts +4 -0
  55. package/dist/gui/quota-observation.js +18 -0
  56. package/dist/gui/rpc.js +3 -0
  57. package/dist/gui/server.js +6 -1
  58. package/dist/gui/snapshot-service.d.ts +3 -17
  59. package/dist/gui/snapshot-service.js +159 -9
  60. package/dist/gui/sources.js +84 -11
  61. package/dist/gui/temporal-status.d.ts +3 -2
  62. package/dist/gui/temporal-status.js +10 -6
  63. package/dist/gui-experimental.cjs +228 -228
  64. package/dist/lib/accounting-format.d.ts +8 -0
  65. package/dist/lib/accounting-format.js +12 -2
  66. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  67. package/dist/lib/anthropic-api-auth.js +27 -0
  68. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  69. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  70. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  71. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  72. package/dist/lib/anthropic.d.ts +22 -4
  73. package/dist/lib/anthropic.js +498 -180
  74. package/dist/lib/cache-observer-ingestion.js +27 -0
  75. package/dist/lib/cache-observer.d.ts +3 -0
  76. package/dist/lib/cache-observer.js +9 -3
  77. package/dist/lib/cli-show.d.ts +5 -0
  78. package/dist/lib/cli-show.js +16 -5
  79. package/dist/lib/cli-status.js +3 -6
  80. package/dist/lib/config.d.ts +1 -1
  81. package/dist/lib/config.js +64 -2
  82. package/dist/lib/dashboard-visibility.d.ts +5 -0
  83. package/dist/lib/dashboard-visibility.js +11 -10
  84. package/dist/lib/display-sanitize.js +1 -0
  85. package/dist/lib/entries.d.ts +10 -1
  86. package/dist/lib/entries.js +4 -0
  87. package/dist/lib/grouped-entry-normalization.js +1 -1
  88. package/dist/lib/maintainer-announcements.js +2 -2
  89. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  90. package/dist/lib/modelsdev-pricing.js +457 -63
  91. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  92. package/dist/lib/modelsdev-temporal.js +16 -2
  93. package/dist/lib/opencode-config-providers.js +2 -2
  94. package/dist/lib/opencode-storage.d.ts +20 -0
  95. package/dist/lib/opencode-storage.js +89 -2
  96. package/dist/lib/opencode-version-core.d.ts +7 -0
  97. package/dist/lib/opencode-version-core.js +10 -0
  98. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  99. package/dist/lib/opencode-warming-refresh.js +95 -0
  100. package/dist/lib/provider-metadata.d.ts +11 -3
  101. package/dist/lib/provider-metadata.js +20 -2
  102. package/dist/lib/provider-registration.d.ts +342 -3
  103. package/dist/lib/provider-registration.js +409 -27
  104. package/dist/lib/quota-auto-resume.d.ts +74 -0
  105. package/dist/lib/quota-auto-resume.js +539 -0
  106. package/dist/lib/quota-command-format.js +22 -9
  107. package/dist/lib/quota-identity.d.ts +64 -0
  108. package/dist/lib/quota-identity.js +111 -0
  109. package/dist/lib/quota-providers.js +2 -2
  110. package/dist/lib/quota-render-data.js +2 -2
  111. package/dist/lib/quota-reset-notifications.js +11 -155
  112. package/dist/lib/quota-retry-wait.d.ts +106 -5
  113. package/dist/lib/quota-retry-wait.js +301 -34
  114. package/dist/lib/quota-runtime-context.js +1 -0
  115. package/dist/lib/quota-state-codec.d.ts +2 -0
  116. package/dist/lib/quota-state-codec.js +14 -1
  117. package/dist/lib/quota-state.d.ts +1 -1
  118. package/dist/lib/quota-state.js +60 -28
  119. package/dist/lib/quota-stats.d.ts +26 -0
  120. package/dist/lib/quota-stats.js +19 -1
  121. package/dist/lib/quota-surface-data.js +18 -3
  122. package/dist/lib/quota-telemetry.js +2 -2
  123. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  124. package/dist/lib/resolved-auth-identity.js +44 -0
  125. package/dist/lib/state-file-lock.d.ts +26 -0
  126. package/dist/lib/state-file-lock.js +205 -0
  127. package/dist/lib/toast-format-grouped.js +7 -4
  128. package/dist/lib/tui-compact-format.js +29 -16
  129. package/dist/lib/types.d.ts +20 -0
  130. package/dist/lib/types.js +4 -1
  131. package/dist/plugin.js +67 -1
  132. package/dist/providers/alibaba-coding-plan.js +21 -3
  133. package/dist/providers/alibaba-token-plan.js +9 -5
  134. package/dist/providers/anthropic.d.ts +6 -2
  135. package/dist/providers/anthropic.js +123 -14
  136. package/dist/providers/chutes.js +2 -0
  137. package/dist/providers/claude-agent.js +24 -5
  138. package/dist/providers/copilot.js +5 -4
  139. package/dist/providers/glm-coding-plan-provider.js +30 -23
  140. package/dist/providers/ollama-cloud.js +10 -0
  141. package/dist/providers/openai.js +24 -23
  142. package/dist/providers/opencode-go.js +7 -6
  143. package/dist/providers/opencode-zen.js +1 -1
  144. package/dist/providers/result-helpers.d.ts +4 -2
  145. package/dist/providers/result-helpers.js +5 -1
  146. package/dist/providers/synthetic.js +4 -0
  147. package/dist/providers/xai.js +9 -8
  148. package/dist/rpc.d.ts +8 -0
  149. package/dist/rpc.js +15 -2
  150. package/dist/ui/assets/{index-BcueIm3Z.css → index-6_g1FHs-.css} +1 -1
  151. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  152. package/dist/ui/assets/{popover-4bFSvRZ7.js → popover-C4ZLYe9E.js} +1 -1
  153. package/dist/ui/index.html +2 -2
  154. package/package.json +3 -3
  155. package/dist/ui/assets/index-C6qRSoh8.js +0 -10
@@ -9,22 +9,21 @@
9
9
  import { execFile } from "child_process";
10
10
  import { createHash } from "crypto";
11
11
  import { existsSync } from "fs";
12
- import { readFile } from "fs/promises";
12
+ import { readFile, stat } from "fs/promises";
13
13
  import { homedir } from "os";
14
14
  import { isAbsolute, join, resolve } from "path";
15
+ import { isTransientProviderFailureCategory, } from "../contracts/provider-failure.js";
16
+ import { ANTHROPIC_OAUTH_RETRY_AFTER_MAX_MS, claimAnthropicOAuthUsageRequest, clearAnthropicOAuthThrottleStateForTests, normalizeAnthropicOAuthPollIntervalMs, } from "./anthropic-oauth-throttle.js";
15
17
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
16
18
  import { fetchWithTimeout } from "./http.js";
17
19
  import { buildFixedWindowEvidence } from "./quota-exhaustion-projection.js";
18
- import { composeResolvedAuthIdentities, deriveResolvedAuthIdentity, } from "./resolved-auth-identity.js";
19
- import { REQUEST_TIMEOUT_MS } from "./types.js";
20
+ import { composeProcessLocalAuthIdentities, composeResolvedAuthIdentities, deriveProcessLocalAuthIdentity, deriveResolvedAuthIdentity, } from "./resolved-auth-identity.js";
20
21
  const DEFAULT_CLAUDE_BINARY = "claude";
21
22
  /** How `binaryPath` reads when the default `claude` ran from PATH. */
22
23
  const CLAUDE_ON_PATH_DISPLAY = "claude (PATH)";
23
24
  const CLAUDE_COMMAND_TIMEOUT_MS = 3_000;
24
- const ANTHROPIC_OAUTH_BACKOFF_BASE_MS = 30_000;
25
- const ANTHROPIC_OAUTH_COOLDOWN_MAX_MS = 15 * 60_000;
26
- const ANTHROPIC_OAUTH_COOLDOWN_MAX_ENTRIES = 16;
27
- const ANTHROPIC_OAUTH_REUSE_MS = 60_000;
25
+ /** Window for treating a failed credential-file read as a transient write race. */
26
+ const CLAUDE_CREDENTIALS_READ_RETRY_MS = 60_000;
28
27
  const ANTHROPIC_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
29
28
  const ANTHROPIC_USAGE_ENHANCED_URL = `${ANTHROPIC_USAGE_URL}?cedar_ember=1`;
30
29
  const ANTHROPIC_BETA_HEADER = "oauth-2025-04-20";
@@ -44,7 +43,6 @@ const anthropicOAuthGlobal = globalThis;
44
43
  let anthropicOAuthSharedState = anthropicOAuthGlobal[ANTHROPIC_OAUTH_SHARED_STATE_KEY];
45
44
  if (anthropicOAuthSharedState === undefined) {
46
45
  anthropicOAuthSharedState = {
47
- cooldowns: new Map(),
48
46
  inFlight: new Map(),
49
47
  recent: new Map(),
50
48
  };
@@ -54,12 +52,25 @@ if (anthropicOAuthSharedState === undefined) {
54
52
  writable: true,
55
53
  });
56
54
  }
57
- const anthropicOAuthCooldowns = anthropicOAuthSharedState.cooldowns;
58
55
  const anthropicOAuthInFlight = anthropicOAuthSharedState.inFlight;
59
56
  anthropicOAuthSharedState.forcedInFlight ??= new Map();
57
+ anthropicOAuthSharedState.plainForm ??= new Set();
60
58
  const anthropicOAuthForcedInFlight = anthropicOAuthSharedState.forcedInFlight;
61
59
  const anthropicOAuthRecent = anthropicOAuthSharedState.recent;
60
+ const anthropicOAuthPlainForm = anthropicOAuthSharedState.plainForm;
62
61
  const anthropicForcedResultsKey = Symbol("anthropic forced results");
62
+ /**
63
+ * Config directories whose credentials file was read successfully in this process. The CLI
64
+ * rewrites that file while refreshing its token, so a read that fails during that window is
65
+ * retried once instead of being reported as a missing login.
66
+ */
67
+ const claudeCredentialsLastGoodReads = new Map();
68
+ /**
69
+ * The last successful Claude CLI identity for each config directory. It lives only in this
70
+ * process: a transient probe failure may reuse it only while the credentials file is provably
71
+ * unchanged, so a switch or a rotated login can never borrow another account's last-good.
72
+ */
73
+ const claudeIdentitySuccesses = new Map();
63
74
  export function resolveAnthropicBinaryPath(binaryPath) {
64
75
  const trimmed = binaryPath?.trim();
65
76
  return trimmed ? trimmed : DEFAULT_CLAUDE_BINARY;
@@ -483,7 +494,7 @@ function buildAnthropicNoQuotaDiagnosticsMessage(detail) {
483
494
  function extractClaudeCredentialsAccessToken(data) {
484
495
  const root = asRecord(data);
485
496
  if (!root) {
486
- return "";
497
+ return { accessToken: "" };
487
498
  }
488
499
  for (const candidate of [asRecord(root["claudeAiOauth"]), asRecord(root["oauth"]), root]) {
489
500
  if (!candidate) {
@@ -492,11 +503,17 @@ function extractClaudeCredentialsAccessToken(data) {
492
503
  for (const key of ["accessToken", "access_token", "token"]) {
493
504
  const token = candidate[key];
494
505
  if (typeof token === "string" && token.trim()) {
495
- return token.trim();
506
+ const expiresAt = candidate["expiresAt"];
507
+ return {
508
+ accessToken: token.trim(),
509
+ ...(typeof expiresAt === "number" && Number.isFinite(expiresAt)
510
+ ? { expiresAtMs: expiresAt }
511
+ : {}),
512
+ };
496
513
  }
497
514
  }
498
515
  }
499
- return "";
516
+ return { accessToken: "" };
500
517
  }
501
518
  function parseClaudeCredentialsAccessToken(content, options) {
502
519
  const trimmed = content.trim();
@@ -508,8 +525,10 @@ function parseClaudeCredentialsAccessToken(content, options) {
508
525
  }
509
526
  try {
510
527
  const parsed = JSON.parse(trimmed);
511
- const accessToken = extractClaudeCredentialsAccessToken(parsed);
512
- return accessToken ? { accessToken } : { error: "missing" };
528
+ const { accessToken, expiresAtMs } = extractClaudeCredentialsAccessToken(parsed);
529
+ return accessToken
530
+ ? { accessToken, ...(expiresAtMs === undefined ? {} : { expiresAtMs }) }
531
+ : { error: "missing" };
513
532
  }
514
533
  catch {
515
534
  // The parser's own message can quote a fragment of the token, so only a fixed reason is kept.
@@ -574,6 +593,8 @@ async function readClaudeCredentialsAccessTokenFromMacOSKeychain() {
574
593
  return {
575
594
  state: "configured",
576
595
  accessToken: parsed.accessToken,
596
+ storage: "keychain",
597
+ ...(parsed.expiresAtMs === undefined ? {} : { expiresAtMs: parsed.expiresAtMs }),
577
598
  };
578
599
  }
579
600
  return {
@@ -600,6 +621,8 @@ async function readClaudeCredentialsAccessTokenFromFile(directory) {
600
621
  return {
601
622
  state: "configured",
602
623
  accessToken,
624
+ storage: "file",
625
+ ...(parsed.expiresAtMs === undefined ? {} : { expiresAtMs: parsed.expiresAtMs }),
603
626
  };
604
627
  }
605
628
  catch (error) {
@@ -620,6 +643,81 @@ async function readClaudeCredentialsAccessTokenFromFile(directory) {
620
643
  };
621
644
  }
622
645
  }
646
+ function rememberClaudeCredentialsRead(directory) {
647
+ const nowMs = Date.now();
648
+ for (const [path, readAtMs] of claudeCredentialsLastGoodReads) {
649
+ if (nowMs - readAtMs >= CLAUDE_CREDENTIALS_READ_RETRY_MS) {
650
+ claudeCredentialsLastGoodReads.delete(path);
651
+ }
652
+ }
653
+ claudeCredentialsLastGoodReads.set(directory.path, nowMs);
654
+ }
655
+ function hadRecentClaudeCredentialsRead(directory) {
656
+ const readAtMs = claudeCredentialsLastGoodReads.get(directory.path);
657
+ return readAtMs !== undefined && Date.now() - readAtMs < CLAUDE_CREDENTIALS_READ_RETRY_MS;
658
+ }
659
+ /**
660
+ * The credential file's identity signature, captured before its token is read. `stat` is the only
661
+ * read here: a changed, missing, or unreadable file yields null, which disables reuse.
662
+ */
663
+ async function readClaudeCredentialFileSignature(configDirectory) {
664
+ if (configDirectory?.state !== "resolved")
665
+ return null;
666
+ const path = join(configDirectory.path, ".credentials.json");
667
+ try {
668
+ const stats = await stat(path);
669
+ if (!stats.isFile())
670
+ return null;
671
+ return {
672
+ path,
673
+ configDirEnv: process.env[CLAUDE_CONFIG_DIR_ENV],
674
+ mtimeMs: stats.mtimeMs,
675
+ size: stats.size,
676
+ };
677
+ }
678
+ catch {
679
+ return null;
680
+ }
681
+ }
682
+ /**
683
+ * Remember a successful, file-backed, user-specific Claude identity. Organization-only evidence
684
+ * never reaches this helper: it cannot distinguish two members of one organization. A keychain
685
+ * token has no stat-able source, so it is never remembered and can never be reused from memory.
686
+ */
687
+ function rememberClaudeIdentitySuccess(configDirectory, identity, signature) {
688
+ if (configDirectory?.state !== "resolved" || signature === null)
689
+ return;
690
+ claudeIdentitySuccesses.set(configDirectory.path, { identity, signature });
691
+ }
692
+ /** Drop a remembered identity once the current probe can no longer attribute the same user. */
693
+ function forgetClaudeIdentitySuccess(configDirectory) {
694
+ if (configDirectory?.state !== "resolved")
695
+ return;
696
+ claudeIdentitySuccesses.delete(configDirectory.path);
697
+ }
698
+ /**
699
+ * Reuse the last successful identity only while the credential source is provably unchanged:
700
+ * the same directory, the same CLAUDE_CONFIG_DIR value, and an identical credentials-file stat.
701
+ * Any change, an unreadable file, or no record yields null, leaving this cycle without a scope.
702
+ */
703
+ async function recallClaudeIdentitySuccess() {
704
+ const configDirectory = resolveClaudeConfigDirectory(undefined, process.env[CLAUDE_CONFIG_DIR_ENV]);
705
+ if (configDirectory.state !== "resolved")
706
+ return null;
707
+ const remembered = claudeIdentitySuccesses.get(configDirectory.path);
708
+ if (!remembered)
709
+ return null;
710
+ if (remembered.signature.configDirEnv !== process.env[CLAUDE_CONFIG_DIR_ENV])
711
+ return null;
712
+ const current = await readClaudeCredentialFileSignature(configDirectory);
713
+ if (current === null ||
714
+ current.path !== remembered.signature.path ||
715
+ current.mtimeMs !== remembered.signature.mtimeMs ||
716
+ current.size !== remembered.signature.size) {
717
+ return null;
718
+ }
719
+ return remembered.identity;
720
+ }
623
721
  async function readClaudeOAuthAccessToken(configDirectory) {
624
722
  if (configDirectory.state !== "resolved") {
625
723
  return { state: "unavailable", detail: CLAUDE_CONFIG_DIRECTORY_UNRESOLVED_DETAIL };
@@ -639,8 +737,14 @@ async function readClaudeOAuthAccessToken(configDirectory) {
639
737
  if (keychainCredentials?.state === "not-found") {
640
738
  locationsChecked.push(keychainCredentials.location);
641
739
  }
642
- const fileCredentials = await readClaudeCredentialsAccessTokenFromFile(configDirectory);
740
+ let fileCredentials = await readClaudeCredentialsAccessTokenFromFile(configDirectory);
741
+ // The CLI rewrites this file while refreshing its token. If it was readable moments ago, one
742
+ // more read can land after the write instead of reporting a missing login for a poll.
743
+ if (fileCredentials.state !== "configured" && hadRecentClaudeCredentialsRead(configDirectory)) {
744
+ fileCredentials = await readClaudeCredentialsAccessTokenFromFile(configDirectory);
745
+ }
643
746
  if (fileCredentials.state === "configured") {
747
+ rememberClaudeCredentialsRead(configDirectory);
644
748
  return { ...fileCredentials, source: "claude-credentials" };
645
749
  }
646
750
  if (fileCredentials.state === "unavailable") {
@@ -674,41 +778,33 @@ function parseRetryAfterMs(value, nowMs) {
674
778
  }
675
779
  if (/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(trimmed)) {
676
780
  const seconds = Number(trimmed);
677
- return Number.isFinite(seconds) && seconds > 0 ? seconds * 1_000 : undefined;
781
+ const durationMs = seconds * 1_000;
782
+ return Number.isFinite(durationMs) &&
783
+ durationMs > 0 &&
784
+ durationMs <= ANTHROPIC_OAUTH_RETRY_AFTER_MAX_MS
785
+ ? durationMs
786
+ : undefined;
678
787
  }
679
788
  const retryAtMs = Date.parse(trimmed);
680
789
  const durationMs = retryAtMs - nowMs;
681
- return Number.isFinite(durationMs) && durationMs > 0 ? durationMs : undefined;
682
- }
683
- function getAnthropicOAuthCooldownDurationMs(failureCount, retryAfter, nowMs) {
684
- const exponentialMs = Math.min(ANTHROPIC_OAUTH_COOLDOWN_MAX_MS, ANTHROPIC_OAUTH_BACKOFF_BASE_MS * 2 ** Math.min(failureCount, 30));
685
- const retryAfterMs = Math.min(ANTHROPIC_OAUTH_COOLDOWN_MAX_MS, parseRetryAfterMs(retryAfter, nowMs) ?? 0);
686
- return Math.max(exponentialMs, retryAfterMs);
790
+ return Number.isFinite(durationMs) &&
791
+ durationMs > 0 &&
792
+ durationMs <= ANTHROPIC_OAUTH_RETRY_AFTER_MAX_MS
793
+ ? durationMs
794
+ : undefined;
687
795
  }
688
796
  function getAnthropicOAuthCooldownMessage(remainingMs) {
689
- const boundedRemainingMs = Math.min(ANTHROPIC_OAUTH_COOLDOWN_MAX_MS, Math.max(0, remainingMs));
690
- return `Anthropic OAuth usage probe paused after HTTP 429; retry in ${Math.ceil(boundedRemainingMs / 1_000)}s.`;
691
- }
692
- function retainAnthropicOAuthCooldownForToken(tokenFingerprint) {
693
- const targetSize = anthropicOAuthCooldowns.has(tokenFingerprint)
694
- ? ANTHROPIC_OAUTH_COOLDOWN_MAX_ENTRIES
695
- : ANTHROPIC_OAUTH_COOLDOWN_MAX_ENTRIES - 1;
696
- const oldestFirst = [...anthropicOAuthCooldowns.entries()].sort(([, left], [, right]) => left.blockedUntilMs - right.blockedUntilMs);
697
- for (const [fingerprint] of oldestFirst) {
698
- if (anthropicOAuthCooldowns.size <= targetSize)
699
- break;
700
- if (fingerprint !== tokenFingerprint)
701
- anthropicOAuthCooldowns.delete(fingerprint);
702
- }
703
- }
704
- function rememberAnthropicOAuthQuota(tokenFingerprint, quota) {
797
+ return `Anthropic OAuth usage probe paused after HTTP 429; retry in ${Math.ceil(Math.max(0, remainingMs) / 1_000)}s.`;
798
+ }
799
+ function rememberAnthropicOAuthQuota(tokenFingerprint, quota, measuredAtMs, pollIntervalMs) {
705
800
  const nowMs = Date.now();
801
+ const reuseWindowMs = normalizeAnthropicOAuthPollIntervalMs(pollIntervalMs);
706
802
  for (const [fingerprint, entry] of anthropicOAuthRecent) {
707
- if (nowMs - entry.checkedAtMs >= ANTHROPIC_OAUTH_REUSE_MS) {
803
+ if (nowMs - entry.measuredAtMs >= reuseWindowMs) {
708
804
  anthropicOAuthRecent.delete(fingerprint);
709
805
  }
710
806
  }
711
- anthropicOAuthRecent.set(tokenFingerprint, { quota, checkedAtMs: nowMs });
807
+ anthropicOAuthRecent.set(tokenFingerprint, { quota, measuredAtMs });
712
808
  }
713
809
  function redactAccessTokenFromSanitizedDetail(detail, accessToken) {
714
810
  const sanitizedDetail = sanitizeDisplayText(detail);
@@ -732,27 +828,16 @@ function claudeCodeUserAgent(cliVersion, enhanced) {
732
828
  // The plain fallback keeps the identity the usage probe has always sent.
733
829
  return version ? `claude-code/${version}` : "claude-code";
734
830
  }
735
- const RETRY_WITHOUT_ENHANCED = Symbol("retry usage request without cedar_ember");
736
- /** Enhanced request, then one plain retry only when the enhanced form itself was rejected. */
737
- async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion) {
738
- const startedAtMs = Date.now();
739
- const timeoutMs = requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
740
- const enhanced = await requestAnthropicOAuthUsage(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, true);
741
- if (enhanced !== RETRY_WITHOUT_ENHANCED)
742
- return enhanced;
743
- // The fallback shares the caller's one timeout budget rather than doubling it.
744
- const remainingMs = timeoutMs - (Date.now() - startedAtMs);
745
- if (remainingMs <= 0) {
746
- return {
747
- state: "unavailable",
748
- detail: "Anthropic OAuth usage request timed out",
749
- failureCategory: "provider_api",
750
- };
751
- }
752
- // The plain request never yields the retry sentinel.
753
- return (await requestAnthropicOAuthUsage(accessToken, tokenFingerprint, remainingMs, cliVersion, false));
831
+ /**
832
+ * One HTTP request per claim. The enhanced form is remembered per credential; a
833
+ * rejection switches later, separately-spaced claims to the plain form instead
834
+ * of firing a second request inside this claim's spacing window.
835
+ */
836
+ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, publishRateLimit) {
837
+ const enhanced = !anthropicOAuthPlainForm.has(tokenFingerprint);
838
+ return await requestAnthropicOAuthUsage(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, enhanced, publishRateLimit);
754
839
  }
755
- async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, enhanced) {
840
+ async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, enhanced, publishRateLimit) {
756
841
  try {
757
842
  return await fetchWithTimeout(enhanced ? ANTHROPIC_USAGE_ENHANCED_URL : ANTHROPIC_USAGE_URL, {
758
843
  request: {
@@ -767,19 +852,24 @@ async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, request
767
852
  if (response.status === 429) {
768
853
  anthropicOAuthRecent.delete(tokenFingerprint);
769
854
  const nowMs = Date.now();
770
- const previousFailureCount = anthropicOAuthCooldowns.get(tokenFingerprint)?.failureCount ?? 0;
771
- const durationMs = getAnthropicOAuthCooldownDurationMs(previousFailureCount, response.headers?.get?.("Retry-After") ?? null, nowMs);
772
- anthropicOAuthCooldowns.set(tokenFingerprint, {
773
- failureCount: previousFailureCount + 1,
774
- blockedUntilMs: Math.ceil(nowMs + durationMs),
775
- });
855
+ const retryAfterMs = parseRetryAfterMs(response.headers?.get?.("Retry-After") ?? null, nowMs);
856
+ // The headers already prove the deadline; publish it before the body
857
+ // read, which may time out and would otherwise lose the cooldown.
858
+ if (publishRateLimit) {
859
+ try {
860
+ await publishRateLimit({ retryAfterMs, nowMs });
861
+ }
862
+ catch {
863
+ // The throttle keeps the deadline in-process and retries the write.
864
+ }
865
+ }
866
+ // The 429 is already proven; a body read failure must not discard the
867
+ // known deadline or turn this attempt into an unclassified error.
776
868
  let detail = "";
777
869
  try {
778
870
  detail = sanitizeAnthropicApiDetail(await response.text(), accessToken);
779
871
  }
780
- catch (error) {
781
- if (timeoutSignal.aborted)
782
- throw error;
872
+ catch {
783
873
  detail = "";
784
874
  }
785
875
  const errorDetail = detail
@@ -787,22 +877,22 @@ async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, request
787
877
  : `Anthropic API returned ${response.status}`;
788
878
  return {
789
879
  state: "unavailable",
790
- detail: `${errorDetail} ${getAnthropicOAuthCooldownMessage(durationMs)}`,
880
+ detail: errorDetail,
791
881
  failureCategory: "provider_api",
792
- retryAtMs: Math.ceil(nowMs + durationMs),
882
+ rateLimited: true,
883
+ ...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
884
+ attempt: "transient",
793
885
  };
794
886
  }
795
- anthropicOAuthCooldowns.delete(tokenFingerprint);
796
887
  if (!response.ok) {
797
888
  const authenticationFailure = response.status === 401 || response.status === 403;
798
889
  let detail = "";
890
+ let enhancedRejected = enhanced && response.status === 400;
799
891
  try {
800
892
  const body = await response.text();
801
893
  // A 403 naming a missing scope or user:profile is a real credential problem, never an enhanced-form rejection.
802
- if (enhanced &&
803
- (response.status === 400 ||
804
- (response.status === 403 && !/scope|user:profile/iu.test(body)))) {
805
- return RETRY_WITHOUT_ENHANCED;
894
+ if (enhanced && response.status === 403 && !/scope|user:profile/iu.test(body)) {
895
+ enhancedRejected = true;
806
896
  }
807
897
  detail = sanitizeAnthropicApiDetail(body, accessToken);
808
898
  }
@@ -811,13 +901,17 @@ async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, request
811
901
  throw error;
812
902
  detail = "";
813
903
  }
904
+ if (enhancedRejected)
905
+ anthropicOAuthPlainForm.add(tokenFingerprint);
814
906
  return {
815
907
  state: "unavailable",
816
908
  detail: detail
817
909
  ? `Anthropic API error ${response.status}: ${detail}`
818
910
  : `Anthropic API returned ${response.status}`,
819
911
  ...(authenticationFailure ? { failureKind: "authentication" } : {}),
912
+ httpStatus: response.status,
820
913
  failureCategory: authenticationFailure ? "credentials" : "provider_api",
914
+ attempt: authenticationFailure ? "credentials" : "transient",
821
915
  };
822
916
  }
823
917
  let data;
@@ -831,6 +925,7 @@ async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, request
831
925
  state: "unavailable",
832
926
  detail: "Failed to parse Anthropic quota response",
833
927
  failureCategory: "provider_api",
928
+ attempt: "transient",
834
929
  };
835
930
  }
836
931
  const quota = parseOAuthUsageResponse(data);
@@ -839,11 +934,14 @@ async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, request
839
934
  state: "unavailable",
840
935
  detail: "Unexpected Anthropic quota response shape",
841
936
  failureCategory: "provider_api",
937
+ attempt: "transient",
842
938
  };
843
939
  }
844
940
  return {
845
941
  state: "success",
846
942
  quota,
943
+ attempt: "fresh",
944
+ measuredAtMs: Date.now(),
847
945
  };
848
946
  },
849
947
  });
@@ -853,28 +951,13 @@ async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, request
853
951
  state: "unavailable",
854
952
  detail: sanitizeAnthropicRequestError(error instanceof Error ? error.message : String(error), accessToken),
855
953
  failureCategory: "provider_api",
954
+ attempt: "transient",
856
955
  };
857
956
  }
858
957
  }
859
- async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs, forcedOperationCache, cliVersion) {
958
+ async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs, forcedOperationCache, cliVersion, pollIntervalMs) {
860
959
  const tokenFingerprint = fingerprintAccessToken(accessToken);
861
- retainAnthropicOAuthCooldownForToken(tokenFingerprint);
862
- const nowMs = Date.now();
863
- const cooldown = anthropicOAuthCooldowns.get(tokenFingerprint);
864
- if (cooldown && cooldown.blockedUntilMs > nowMs) {
865
- return {
866
- state: "unavailable",
867
- detail: getAnthropicOAuthCooldownMessage(cooldown.blockedUntilMs - nowMs),
868
- failureCategory: "provider_api",
869
- retryAtMs: cooldown.blockedUntilMs,
870
- };
871
- }
872
- const recent = forcedOperationCache ? undefined : anthropicOAuthRecent.get(tokenFingerprint);
873
- if (recent &&
874
- nowMs >= recent.checkedAtMs &&
875
- nowMs - recent.checkedAtMs < ANTHROPIC_OAUTH_REUSE_MS) {
876
- return { state: "success", quota: recent.quota };
877
- }
960
+ const intervalMs = normalizeAnthropicOAuthPollIntervalMs(pollIntervalMs);
878
961
  let forcedResults;
879
962
  if (forcedOperationCache) {
880
963
  forcedResults = forcedOperationCache.get(anthropicForcedResultsKey);
@@ -902,20 +985,120 @@ async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeo
902
985
  const inFlight = (async () => {
903
986
  if (prior)
904
987
  await prior;
905
- const activeCooldown = anthropicOAuthCooldowns.get(tokenFingerprint);
906
- const remaining = (activeCooldown?.blockedUntilMs ?? 0) - Date.now();
907
- if (remaining > 0)
988
+ // The claim is cross-process: a busy lock, an active cooldown or a request
989
+ // still inside the configured spacing window all skip without fetching.
990
+ const claim = await claimAnthropicOAuthUsageRequest({
991
+ nowMs: Date.now(),
992
+ pollIntervalMs: intervalMs,
993
+ requestTimeoutMs,
994
+ });
995
+ if (claim.state === "skip") {
996
+ if (claim.reason === "spacing") {
997
+ const recent = anthropicOAuthRecent.get(tokenFingerprint);
998
+ const nowMs = Date.now();
999
+ if (recent && nowMs >= recent.measuredAtMs && nowMs - recent.measuredAtMs < intervalMs) {
1000
+ return {
1001
+ state: "success",
1002
+ quota: recent.quota,
1003
+ attempt: "reuse",
1004
+ measuredAtMs: recent.measuredAtMs,
1005
+ };
1006
+ }
1007
+ return {
1008
+ state: "unavailable",
1009
+ detail: "Claude Agent waiting for its next configured usage request.",
1010
+ failureCategory: "provider_api",
1011
+ ...(claim.retryAtMs !== undefined ? { retryAtMs: claim.retryAtMs } : {}),
1012
+ attempt: "cooldown",
1013
+ };
1014
+ }
1015
+ const nowMs = Date.now();
1016
+ const retryAtMs = claim.retryAtMs ?? (claim.reason === "cooldown" ? nowMs : undefined);
908
1017
  return {
909
1018
  state: "unavailable",
910
- detail: getAnthropicOAuthCooldownMessage(remaining),
1019
+ detail: claim.reason === "cooldown" && retryAtMs !== undefined
1020
+ ? getAnthropicOAuthCooldownMessage(retryAtMs - nowMs)
1021
+ : "Claude Agent usage request is already being coordinated.",
911
1022
  failureCategory: "provider_api",
912
- retryAtMs: activeCooldown?.blockedUntilMs,
1023
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
1024
+ attempt: "cooldown",
913
1025
  };
914
- const result = await performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion);
1026
+ }
1027
+ let publishedCompletion;
1028
+ let publishedRetryAfterMs;
1029
+ const publishRateLimit = async (info) => {
1030
+ publishedRetryAfterMs = info.retryAfterMs;
1031
+ publishedCompletion = await claim.complete({
1032
+ kind: "rate-limited",
1033
+ ...(info.retryAfterMs !== undefined ? { retryAfterMs: info.retryAfterMs } : {}),
1034
+ nowMs: info.nowMs,
1035
+ });
1036
+ };
1037
+ let result;
1038
+ try {
1039
+ result = await performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, publishRateLimit);
1040
+ }
1041
+ catch (error) {
1042
+ if (publishedCompletion === undefined) {
1043
+ await claim.complete({ kind: "network-error" });
1044
+ throw error;
1045
+ }
1046
+ // The 429 was proven from headers before this failure; report the cooldown.
1047
+ result = {
1048
+ state: "unavailable",
1049
+ detail: "Anthropic API returned 429",
1050
+ failureCategory: "provider_api",
1051
+ rateLimited: true,
1052
+ ...(publishedRetryAfterMs !== undefined ? { retryAfterMs: publishedRetryAfterMs } : {}),
1053
+ attempt: "transient",
1054
+ };
1055
+ }
1056
+ // A body-read timeout is classified as a plain transient failure, but the
1057
+ // headers already proved the 429. Keep that deadline and do not downgrade it.
1058
+ if (publishedCompletion !== undefined &&
1059
+ result.state !== "success" &&
1060
+ result.rateLimited !== true) {
1061
+ result = {
1062
+ state: "unavailable",
1063
+ detail: "Anthropic API returned 429",
1064
+ failureCategory: "provider_api",
1065
+ rateLimited: true,
1066
+ ...(publishedRetryAfterMs !== undefined ? { retryAfterMs: publishedRetryAfterMs } : {}),
1067
+ attempt: "transient",
1068
+ };
1069
+ }
1070
+ let completion;
915
1071
  if (result.state === "success") {
916
- rememberAnthropicOAuthQuota(tokenFingerprint, result.quota);
1072
+ await claim.complete({ kind: "success" });
1073
+ rememberAnthropicOAuthQuota(tokenFingerprint, result.quota, result.measuredAtMs, intervalMs);
1074
+ }
1075
+ else if (result.rateLimited === true) {
1076
+ completion =
1077
+ publishedCompletion ??
1078
+ (await claim.complete({
1079
+ kind: "rate-limited",
1080
+ ...(result.retryAfterMs !== undefined ? { retryAfterMs: result.retryAfterMs } : {}),
1081
+ nowMs: Date.now(),
1082
+ }));
1083
+ const nowMs = Date.now();
1084
+ const blockedUntilMs = completion.blockedUntilMs ?? nowMs;
1085
+ // The shared request spacing still applies: the card and diagnostics must
1086
+ // name the next real attempt, not an earlier server deadline.
1087
+ const nextAttemptAtMs = Math.max(blockedUntilMs, claim.claimedAtMs + intervalMs);
1088
+ result = {
1089
+ ...result,
1090
+ detail: `${result.detail ?? ""} ${getAnthropicOAuthCooldownMessage(nextAttemptAtMs - nowMs)}`.trim(),
1091
+ retryAtMs: nextAttemptAtMs,
1092
+ };
1093
+ }
1094
+ else if (result.httpStatus !== undefined) {
1095
+ // Any response other than 429 ends the previous 429 streak.
1096
+ await claim.complete({ kind: "response" });
917
1097
  }
918
1098
  else {
1099
+ await claim.complete({ kind: "network-error" });
1100
+ }
1101
+ if (result.state !== "success") {
919
1102
  const cached = anthropicOAuthRecent.get(tokenFingerprint);
920
1103
  if (cached?.quota.saved_resets) {
921
1104
  const { saved_resets: _savedResets, ...quota } = cached.quota;
@@ -1005,6 +1188,42 @@ function hasFirstPartyClaudeAiLogin(payload) {
1005
1188
  typeof provider === "string" &&
1006
1189
  provider.trim().toLowerCase() === "firstparty");
1007
1190
  }
1191
+ /** Field names that carry a user-specific account id in the CLI's own status. */
1192
+ const CLAUDE_USER_ACCOUNT_ID_FIELDS = [
1193
+ "accountUuid",
1194
+ "account_uuid",
1195
+ "userUuid",
1196
+ "user_uuid",
1197
+ "userId",
1198
+ "user_id",
1199
+ ];
1200
+ /**
1201
+ * User-specific evidence in the CLI's own status, used only to key the cache identity when the
1202
+ * stored token cannot be read. An organization id alone is not evidence because every member
1203
+ * shares it; when user evidence exists, the organization is only a qualifier. It is never
1204
+ * displayed, persisted, or sent anywhere.
1205
+ */
1206
+ function claudeLoginAccountHint(payload) {
1207
+ const record = asRecord(payload);
1208
+ if (!record)
1209
+ return undefined;
1210
+ const orgId = typeof record["orgId"] === "string" ? record["orgId"].trim() : "";
1211
+ const email = typeof record["email"] === "string" ? record["email"].trim().toLowerCase() : "";
1212
+ const userId = CLAUDE_USER_ACCOUNT_ID_FIELDS.map((key) => typeof record[key] === "string" ? record[key].trim() : "").find((value) => value !== "") ?? "";
1213
+ if (!email && !userId)
1214
+ return undefined;
1215
+ // The organization id is only a qualifier here; the email/user id keeps it user-specific.
1216
+ // Omitting the extra element when no user id exists preserves the existing email-only scope.
1217
+ return userId ? JSON.stringify([orgId, email, userId]) : JSON.stringify([orgId, email]);
1218
+ }
1219
+ /** True when the CLI named an organization but no user-specific account evidence. */
1220
+ function hasClaudeOrgOnlyAccountEvidence(payload) {
1221
+ const record = asRecord(payload);
1222
+ if (!record)
1223
+ return false;
1224
+ const orgId = typeof record["orgId"] === "string" ? record["orgId"].trim() : "";
1225
+ return orgId !== "" && claudeLoginAccountHint(payload) === undefined;
1226
+ }
1008
1227
  /** The only plan names shown. The CLI's `subscriptionType` is undocumented, so anything else is omitted. */
1009
1228
  const CLAUDE_PLAN_LABELS = new Map([
1010
1229
  ["free", "Free"],
@@ -1118,6 +1337,43 @@ async function runClaudeCommand(invocation) {
1118
1337
  }
1119
1338
  function parseClaudeAuthStatusResult(result) {
1120
1339
  const combinedOutput = `${result.stdout}\n${result.stderr}`;
1340
+ const trimmed = result.stdout.trim();
1341
+ let jsonPayload;
1342
+ let hasJsonBody = false;
1343
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1344
+ try {
1345
+ jsonPayload = JSON.parse(trimmed);
1346
+ hasJsonBody = true;
1347
+ }
1348
+ catch {
1349
+ // Not a JSON body; the text/exit-code fallbacks below decide.
1350
+ }
1351
+ }
1352
+ // A JSON status body is authoritative. stderr noise (banners, update notices) must not turn a
1353
+ // positively reported login into a sign-out.
1354
+ if (hasJsonBody) {
1355
+ const auth = extractAuthBoolean(jsonPayload);
1356
+ if (auth === true) {
1357
+ if (hasNonSubscriptionLogin(jsonPayload)) {
1358
+ return {
1359
+ authStatus: "unknown",
1360
+ message: CLAUDE_NON_SUBSCRIPTION_LOGIN_MESSAGE,
1361
+ };
1362
+ }
1363
+ return {
1364
+ authStatus: "authenticated",
1365
+ jsonPayload,
1366
+ claudeAiLoginVerified: hasFirstPartyClaudeAiLogin(jsonPayload),
1367
+ };
1368
+ }
1369
+ if (auth === false) {
1370
+ return {
1371
+ authStatus: "unauthenticated",
1372
+ message: "Claude is not authenticated. Run `claude auth login` and try again.",
1373
+ jsonPayload,
1374
+ };
1375
+ }
1376
+ }
1121
1377
  if (hasUnsupportedCommandText(combinedOutput)) {
1122
1378
  return {
1123
1379
  authStatus: "unknown",
@@ -1131,40 +1387,13 @@ function parseClaudeAuthStatusResult(result) {
1131
1387
  message: "Claude is not authenticated. Run `claude auth login` and try again.",
1132
1388
  };
1133
1389
  }
1134
- const trimmed = result.stdout.trim();
1135
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1136
- try {
1137
- const payload = JSON.parse(trimmed);
1138
- const auth = extractAuthBoolean(payload);
1139
- if (auth === true) {
1140
- if (hasNonSubscriptionLogin(payload)) {
1141
- return {
1142
- authStatus: "unknown",
1143
- message: CLAUDE_NON_SUBSCRIPTION_LOGIN_MESSAGE,
1144
- };
1145
- }
1146
- return {
1147
- authStatus: "authenticated",
1148
- jsonPayload: payload,
1149
- claudeAiLoginVerified: hasFirstPartyClaudeAiLogin(payload),
1150
- };
1151
- }
1152
- if (auth === false) {
1153
- return {
1154
- authStatus: "unauthenticated",
1155
- message: "Claude is not authenticated. Run `claude auth login` and try again.",
1156
- jsonPayload: payload,
1157
- };
1158
- }
1159
- return {
1160
- authStatus: "unknown",
1161
- message: "Could not verify Claude authentication status from JSON output.",
1162
- jsonPayload: payload,
1163
- };
1164
- }
1165
- catch {
1166
- // Fall through to exit-code-based handling.
1167
- }
1390
+ if (hasJsonBody) {
1391
+ return {
1392
+ authStatus: "unknown",
1393
+ message: "Could not verify Claude authentication status from JSON output.",
1394
+ jsonPayload,
1395
+ failureCategory: "provider_api",
1396
+ };
1168
1397
  }
1169
1398
  if (result.code === 0) {
1170
1399
  return { authStatus: "authenticated" };
@@ -1173,6 +1402,8 @@ function parseClaudeAuthStatusResult(result) {
1173
1402
  return {
1174
1403
  authStatus: "unknown",
1175
1404
  message: "Timed out while running Claude CLI auth status.",
1405
+ failureCategory: "provider_api",
1406
+ probeFailure: true,
1176
1407
  };
1177
1408
  }
1178
1409
  const detail = detailFromCommandResult(result);
@@ -1181,6 +1412,8 @@ function parseClaudeAuthStatusResult(result) {
1181
1412
  message: detail
1182
1413
  ? `Could not verify Claude authentication status. ${detail}`
1183
1414
  : "Could not verify Claude authentication status.",
1415
+ failureCategory: "provider_api",
1416
+ probeFailure: true,
1184
1417
  };
1185
1418
  }
1186
1419
  function mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics) {
@@ -1211,6 +1444,12 @@ function mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics) {
1211
1444
  if (localDiagnostics.message) {
1212
1445
  diagnostics.message = localDiagnostics.message;
1213
1446
  }
1447
+ if (localDiagnostics.failureCategory !== undefined) {
1448
+ diagnostics.failureCategory = localDiagnostics.failureCategory;
1449
+ }
1450
+ if (localDiagnostics.probeFailure === true) {
1451
+ diagnostics.probeFailure = true;
1452
+ }
1214
1453
  return diagnostics;
1215
1454
  }
1216
1455
  async function runClaudeVersionCommand(binaryPath, checkedCommands) {
@@ -1271,48 +1510,50 @@ async function probeAnthropicLocalDiagnostics(options = {}) {
1271
1510
  binaryPath: binaryPathDisplay,
1272
1511
  checkedCommands,
1273
1512
  message: parsedAuth.message,
1513
+ ...(parsedAuth.failureCategory !== undefined
1514
+ ? { failureCategory: parsedAuth.failureCategory }
1515
+ : {}),
1516
+ ...(parsedAuth.probeFailure === true ? { probeFailure: true } : {}),
1274
1517
  };
1275
1518
  }
1276
1519
  // The CLI's report wins; otherwise CLAUDE_CONFIG_DIR, then the default. The CLI inherits this
1277
1520
  // environment, so this is the directory it reads its login from.
1278
1521
  const configDirectory = resolveClaudeConfigDirectory(asRecord(parsedAuth.jsonPayload)?.["configDirectory"], process.env[CLAUDE_CONFIG_DIR_ENV]);
1522
+ const accountHint = claudeLoginAccountHint(parsedAuth.jsonPayload);
1523
+ const orgOnlyAccountEvidence = hasClaudeOrgOnlyAccountEvidence(parsedAuth.jsonPayload);
1279
1524
  const quota = parsedAuth.jsonPayload ? parseUsageResponse(parsedAuth.jsonPayload) : null;
1280
1525
  // Only a verified first-party login may name its plan; the same login answers the quota above.
1281
1526
  const planLabel = parsedAuth.claudeAiLoginVerified === true
1282
1527
  ? deriveClaudePlanLabel(parsedAuth.jsonPayload)
1283
1528
  : undefined;
1284
- if (quota) {
1285
- return {
1286
- installed: true,
1287
- version,
1288
- authStatus: "authenticated",
1289
- binaryPath: binaryPathDisplay,
1290
- checkedCommands,
1291
- localQuota: quota,
1292
- effectiveBinary: binaryPath,
1293
- configDirectory,
1294
- claudeAiLoginVerified: parsedAuth.claudeAiLoginVerified === true,
1295
- ...(planLabel === undefined ? {} : { planLabel }),
1296
- };
1297
- }
1298
- return {
1529
+ // Both successful returns are the same authenticated CLI diagnostics; only the quota evidence
1530
+ // or the no-quota message differs.
1531
+ const diagnostics = {
1299
1532
  installed: true,
1300
1533
  version,
1301
1534
  authStatus: "authenticated",
1302
1535
  binaryPath: binaryPathDisplay,
1303
1536
  checkedCommands,
1304
- message: CLAUDE_NO_LOCAL_QUOTA_MESSAGE,
1305
1537
  effectiveBinary: binaryPath,
1306
1538
  configDirectory,
1307
1539
  claudeAiLoginVerified: parsedAuth.claudeAiLoginVerified === true,
1308
1540
  ...(planLabel === undefined ? {} : { planLabel }),
1541
+ ...(accountHint === undefined ? {} : { accountHint }),
1542
+ ...(orgOnlyAccountEvidence ? { orgOnlyAccountEvidence: true } : {}),
1309
1543
  };
1544
+ if (quota) {
1545
+ return { ...diagnostics, localQuota: quota };
1546
+ }
1547
+ return { ...diagnostics, message: CLAUDE_NO_LOCAL_QUOTA_MESSAGE };
1310
1548
  }
1311
1549
  export function clearAnthropicDiagnosticsCacheForTests() {
1312
- anthropicOAuthCooldowns.clear();
1313
1550
  anthropicOAuthInFlight.clear();
1314
1551
  anthropicOAuthForcedInFlight.clear();
1315
1552
  anthropicOAuthRecent.clear();
1553
+ anthropicOAuthPlainForm.clear();
1554
+ clearAnthropicOAuthThrottleStateForTests();
1555
+ claudeCredentialsLastGoodReads.clear();
1556
+ claudeIdentitySuccesses.clear();
1316
1557
  }
1317
1558
  const localDiagnosticsCacheKey = Symbol("anthropic local diagnostics");
1318
1559
  async function getAnthropicLocalDiagnostics(options = {}) {
@@ -1339,7 +1580,7 @@ async function readSavedResetsForLocalQuota(localDiagnostics, options) {
1339
1580
  const credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
1340
1581
  if (credentials.state !== "configured")
1341
1582
  return undefined;
1342
- const result = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version);
1583
+ const result = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version, options.pollIntervalMs);
1343
1584
  return result.state === "success" ? result.quota.saved_resets : undefined;
1344
1585
  }
1345
1586
  catch {
@@ -1350,13 +1591,18 @@ export async function getAnthropicDiagnostics(options = {}) {
1350
1591
  const localDiagnostics = await getAnthropicLocalDiagnostics(options);
1351
1592
  if (localDiagnostics.localQuota) {
1352
1593
  // Local quota stays authoritative and needs no token. Saved resets are an optional extra read
1353
- // with the same verified-login token gate; the result still has no account identity, so it is
1354
- // never cached across accounts.
1594
+ // with the same verified-login token gate; the cache identity is derived separately from the
1595
+ // CLI login's own token or account evidence.
1355
1596
  const mapped = mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
1356
1597
  const savedResets = await readSavedResetsForLocalQuota(localDiagnostics, options);
1357
- return savedResets && mapped.quota
1358
- ? { ...mapped, quota: { ...mapped.quota, saved_resets: savedResets } }
1359
- : mapped;
1598
+ const measured = {
1599
+ ...mapped,
1600
+ attemptOutcome: "fresh",
1601
+ quotaMeasuredAtMs: Date.now(),
1602
+ };
1603
+ return savedResets && measured.quota
1604
+ ? { ...measured, quota: { ...measured.quota, saved_resets: savedResets } }
1605
+ : measured;
1360
1606
  }
1361
1607
  if (localDiagnostics.authStatus !== "authenticated") {
1362
1608
  return mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
@@ -1375,7 +1621,7 @@ export async function getAnthropicDiagnostics(options = {}) {
1375
1621
  };
1376
1622
  }
1377
1623
  const credentialFingerprint = fingerprintAccessToken(credentials.accessToken);
1378
- const fallbackQuota = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version);
1624
+ const fallbackQuota = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version, options.pollIntervalMs);
1379
1625
  if (fallbackQuota.state !== "success") {
1380
1626
  return {
1381
1627
  installed: localDiagnostics.installed,
@@ -1388,10 +1634,17 @@ export async function getAnthropicDiagnostics(options = {}) {
1388
1634
  checkedCommands: localDiagnostics.checkedCommands,
1389
1635
  message: buildAnthropicNoQuotaDiagnosticsMessage(fallbackQuota.detail),
1390
1636
  credentialFingerprint,
1637
+ attemptOutcome: fallbackQuota.attempt,
1391
1638
  ...(fallbackQuota.failureCategory !== undefined
1392
1639
  ? { failureCategory: fallbackQuota.failureCategory }
1393
1640
  : {}),
1394
1641
  ...(fallbackQuota.retryAtMs !== undefined ? { retryAtMs: fallbackQuota.retryAtMs } : {}),
1642
+ // Evidence only: the CLI's own expiry says the token is stale; the request is still made.
1643
+ ...(fallbackQuota.httpStatus === 401 &&
1644
+ credentials.expiresAtMs !== undefined &&
1645
+ credentials.expiresAtMs <= Date.now()
1646
+ ? { storedAccessTokenExpired: true }
1647
+ : {}),
1395
1648
  };
1396
1649
  }
1397
1650
  return {
@@ -1405,24 +1658,35 @@ export async function getAnthropicDiagnostics(options = {}) {
1405
1658
  checkedCommands: localDiagnostics.checkedCommands,
1406
1659
  quota: fallbackQuota.quota,
1407
1660
  credentialFingerprint,
1661
+ attemptOutcome: fallbackQuota.attempt,
1662
+ quotaMeasuredAtMs: fallbackQuota.measuredAtMs,
1408
1663
  // The plan belongs to the CLI login only when this quota came from that login's own token.
1409
1664
  ...(credentials.source === "claude-credentials" && localDiagnostics.planLabel !== undefined
1410
1665
  ? { planLabel: localDiagnostics.planLabel }
1411
1666
  : {}),
1412
1667
  };
1413
1668
  }
1414
- export async function hasAnthropicCredentialsConfigured(options = {}) {
1669
+ export async function hasAnthropicCredentialsConfigured(options = {}, availability = {}) {
1415
1670
  try {
1416
1671
  const diagnostics = await getAnthropicLocalDiagnostics(options);
1417
- return diagnostics.installed && diagnostics.authStatus === "authenticated";
1672
+ if (diagnostics.installed && diagnostics.authStatus === "authenticated")
1673
+ return true;
1674
+ // A probe that could not report a status (timeout, unreadable output) is not a sign-out; a
1675
+ // caller that shows the error row instead of hiding the provider treats it as still configured.
1676
+ return (availability.treatUnverifiedAsConfigured === true &&
1677
+ diagnostics.installed &&
1678
+ diagnostics.authStatus === "unknown");
1418
1679
  }
1419
1680
  catch {
1420
- return false;
1681
+ return availability.treatUnverifiedAsConfigured === true;
1421
1682
  }
1422
1683
  }
1423
1684
  /**
1424
- * Identity of the Claude Agent provider's single Claude CLI login. Null when the CLI reports quota
1425
- * itself (no account binding) or cannot be probed, so the caller must not cache it.
1685
+ * Identity of the Claude Agent provider's single Claude CLI login. It is account-specific:
1686
+ * the readable first-party token keys it, otherwise the CLI's own user-specific account evidence
1687
+ * (email or account/user id) does. An organization id alone is shared by its members, so it never
1688
+ * keys a scope. Without user-specific evidence, null keeps another account's last-good from being
1689
+ * reused.
1426
1690
  */
1427
1691
  export async function resolveClaudeAgentAccountIdentity(params) {
1428
1692
  let localDiagnostics;
@@ -1435,39 +1699,90 @@ export async function resolveClaudeAgentAccountIdentity(params) {
1435
1699
  catch {
1436
1700
  return null;
1437
1701
  }
1438
- // Claude CLI quota does not expose an account identity.
1439
- if (localDiagnostics.localQuota)
1440
- return null;
1441
1702
  const identity = await claudeCliAccountIdentity(localDiagnostics, params.runtimeDetected);
1442
1703
  if (!identity)
1443
1704
  return null;
1444
- return await composeResolvedAuthIdentities({
1705
+ const composition = {
1445
1706
  providerId: "claude-agent",
1446
1707
  identities: [identity],
1447
1708
  qualifiers: [params.onlyCurrentModel ? "only-current-model" : "all-models"],
1448
- });
1709
+ };
1710
+ return ((await composeResolvedAuthIdentities(composition)) ??
1711
+ composeProcessLocalAuthIdentities(composition));
1449
1712
  }
1450
1713
  /**
1451
- * The Claude CLI row's identity. A readable first-party CLI token keys it, because its quota and its
1452
- * quota depends on that token. Otherwise the row shows only the CLI's install and sign-in
1453
- * state, so that state keys it.
1714
+ * The Claude CLI row's identity. A readable first-party CLI token keys it, because its quota
1715
+ * depends on that token. Otherwise the CLI's own non-secret, user-specific account evidence keys
1716
+ * it; an organization id alone is shared by every member and is never used. Without user
1717
+ * evidence, a machine-only state would outlive an account switch. On platforms without protected
1718
+ * identity storage the token is never used and only the in-memory process-local identity applies.
1454
1719
  */
1455
1720
  async function claudeCliAccountIdentity(localDiagnostics, claudeCodeRuntimeDetected) {
1721
+ // A transient probe failure carries no account evidence for this cycle. Reuse the last
1722
+ // successful identity only while its credentials source is provably unchanged; otherwise this
1723
+ // cycle deliberately has no scope, so another account's last-good can never be shown.
1724
+ if (localDiagnostics.authStatus === "unknown" &&
1725
+ isTransientProviderFailureCategory(localDiagnostics.failureCategory)) {
1726
+ return await recallClaudeIdentitySuccess();
1727
+ }
1728
+ const accountQualifiers = [
1729
+ localDiagnostics.effectiveBinary ?? "",
1730
+ claudeConfigDirectoryQualifier(localDiagnostics.configDirectory),
1731
+ // Preserve the existing cache identity for the previously non-excluded CLI login.
1732
+ "distinct",
1733
+ ];
1734
+ let credentials;
1735
+ let credentialSignature = null;
1456
1736
  if (localDiagnostics.authStatus === "authenticated") {
1457
- const credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
1737
+ // Capture the source signature before the token is read: a file rewritten during the read
1738
+ // leaves a mismatch here, so a later recall cannot attribute a new login to the old identity.
1739
+ credentialSignature = await readClaudeCredentialFileSignature(localDiagnostics.configDirectory);
1740
+ credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
1458
1741
  if (credentials.state === "configured") {
1459
- return await deriveResolvedAuthIdentity({
1742
+ const protectedIdentity = await deriveResolvedAuthIdentity({
1460
1743
  providerId: "anthropic:claude-cli-account",
1461
1744
  principal: { kind: "credential", value: credentials.accessToken },
1462
- qualifiers: [
1463
- localDiagnostics.effectiveBinary ?? "",
1464
- claudeConfigDirectoryQualifier(localDiagnostics.configDirectory),
1465
- // Preserve the existing cache identity for the previously non-excluded CLI login.
1466
- "distinct",
1467
- ],
1745
+ qualifiers: accountQualifiers,
1468
1746
  });
1747
+ if (protectedIdentity) {
1748
+ if (credentials.storage === "file") {
1749
+ rememberClaudeIdentitySuccess(localDiagnostics.configDirectory, protectedIdentity, credentialSignature);
1750
+ }
1751
+ return protectedIdentity;
1752
+ }
1753
+ }
1754
+ }
1755
+ // An organization id alone is shared by every member, so it can neither key a scope nor
1756
+ // authorize reusing a previous member's last-good. A readable user token above still wins.
1757
+ if (localDiagnostics.orgOnlyAccountEvidence === true) {
1758
+ forgetClaudeIdentitySuccess(localDiagnostics.configDirectory);
1759
+ return null;
1760
+ }
1761
+ // Without protected identity storage (Windows) the non-secret CLI account evidence still gives
1762
+ // an account-specific, in-memory-only scope. The token is never used for it.
1763
+ if (localDiagnostics.accountHint !== undefined) {
1764
+ const processLocalIdentity = deriveProcessLocalAuthIdentity({
1765
+ providerId: "anthropic:claude-cli-account",
1766
+ principal: { kind: "stable-id", value: localDiagnostics.accountHint },
1767
+ qualifiers: accountQualifiers,
1768
+ });
1769
+ if (processLocalIdentity) {
1770
+ if (credentials?.state === "configured" && credentials.storage === "file") {
1771
+ rememberClaudeIdentitySuccess(localDiagnostics.configDirectory, processLocalIdentity, credentialSignature);
1772
+ }
1773
+ return processLocalIdentity;
1469
1774
  }
1470
1775
  }
1776
+ // A signed-in CLI with no account evidence this cycle cannot be attributed. Reuse the last
1777
+ // success's scope only while its credentials source is provably unchanged.
1778
+ if (localDiagnostics.authStatus === "authenticated" &&
1779
+ localDiagnostics.accountHint === undefined) {
1780
+ const recalled = await recallClaudeIdentitySuccess();
1781
+ if (recalled)
1782
+ return recalled;
1783
+ }
1784
+ if (localDiagnostics.localQuota && localDiagnostics.accountHint === undefined)
1785
+ return null;
1471
1786
  return await deriveResolvedAuthIdentity({
1472
1787
  providerId: "anthropic:claude-cli-state",
1473
1788
  principal: { kind: "stable-id", value: "claude-cli-state" },
@@ -1479,6 +1794,9 @@ async function claudeCliAccountIdentity(localDiagnostics, claudeCodeRuntimeDetec
1479
1794
  claudeConfigDirectoryQualifier(localDiagnostics.configDirectory),
1480
1795
  localDiagnostics.claudeAiLoginVerified === true ? "verified" : "unverified",
1481
1796
  claudeCodeRuntimeDetected ? "detected" : "undetected",
1797
+ ...(localDiagnostics.accountHint === undefined
1798
+ ? []
1799
+ : [`account:${localDiagnostics.accountHint}`]),
1482
1800
  ],
1483
1801
  });
1484
1802
  }