opencode-quota-gui 1.3.0 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -20
- package/dist/bin/opencode-quota-gui.js +0 -0
- package/dist/contracts/build-identity.js +1 -1
- package/dist/contracts/card-order.d.ts +2 -0
- package/dist/contracts/card-order.js +2 -2
- package/dist/contracts/card-visibility.d.ts +2 -1
- package/dist/contracts/card-visibility.js +2 -1
- package/dist/contracts/dashboard.d.ts +95 -6
- package/dist/contracts/dashboard.js +10 -0
- package/dist/contracts/dto-guards.d.ts +4 -0
- package/dist/contracts/dto-guards.js +31 -7
- package/dist/contracts/guards.js +3 -1
- package/dist/contracts/identity.d.ts +37 -5
- package/dist/contracts/identity.js +43 -0
- package/dist/contracts/openai-quota.d.ts +3 -0
- package/dist/contracts/openai-quota.js +3 -0
- package/dist/contracts/provider-auto-resume.d.ts +9 -0
- package/dist/contracts/provider-auto-resume.js +24 -0
- package/dist/contracts/provider-failure.d.ts +22 -0
- package/dist/contracts/provider-failure.js +25 -1
- package/dist/contracts/row-order.d.ts +13 -0
- package/dist/contracts/row-order.js +34 -0
- package/dist/contracts/row-visibility.d.ts +53 -0
- package/dist/contracts/row-visibility.js +130 -0
- package/dist/data/modelsdev-pricing.min.json +1 -1
- package/dist/data/modelsdev-temporal.min.json +60 -634
- package/dist/gui/aggregation.d.ts +29 -1
- package/dist/gui/aggregation.js +157 -4
- package/dist/gui/analytics-bridge.d.ts +8 -9
- package/dist/gui/analytics-bridge.js +197 -54
- package/dist/gui/analytics-engine.d.ts +7 -15
- package/dist/gui/analytics-engine.js +246 -106
- package/dist/gui/analytics-model.d.ts +7 -0
- package/dist/gui/analytics-model.js +75 -9
- package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
- package/dist/gui/analytics-pricing-upkeep.js +23 -0
- package/dist/gui/analytics-protocol.d.ts +17 -7
- package/dist/gui/analytics-protocol.js +1 -0
- package/dist/gui/analytics-service.d.ts +10 -0
- package/dist/gui/analytics-service.js +30 -9
- package/dist/gui/analytics-state.d.ts +30 -5
- package/dist/gui/analytics-state.js +46 -7
- package/dist/gui/analytics-worker-runtime.d.ts +5 -0
- package/dist/gui/analytics-worker-runtime.js +9 -1
- package/dist/gui/analytics-worker.js +11 -0
- package/dist/gui/config.d.ts +3 -3
- package/dist/gui/config.js +77 -7
- package/dist/gui/identity.d.ts +6 -20
- package/dist/gui/identity.js +6 -54
- package/dist/gui/lifecycle.d.ts +5 -3
- package/dist/gui/lifecycle.js +3 -3
- package/dist/gui/primary-quota-windows.js +67 -44
- package/dist/gui/provider-cards.d.ts +20 -8
- package/dist/gui/provider-cards.js +42 -55
- package/dist/gui/quota-notification-detector.d.ts +29 -6
- package/dist/gui/quota-notification-detector.js +136 -47
- package/dist/gui/quota-notification-observer.d.ts +3 -4
- package/dist/gui/quota-notification-observer.js +73 -20
- package/dist/gui/quota-observation.d.ts +4 -0
- package/dist/gui/quota-observation.js +18 -0
- package/dist/gui/rpc.d.ts +2 -0
- package/dist/gui/rpc.js +14 -3
- package/dist/gui/server.js +17 -3
- package/dist/gui/snapshot-service.d.ts +3 -15
- package/dist/gui/snapshot-service.js +281 -23
- package/dist/gui/sources.js +179 -64
- package/dist/gui/temporal-status.d.ts +3 -2
- package/dist/gui/temporal-status.js +10 -6
- package/dist/gui-experimental.cjs +230 -225
- package/dist/lib/accounting-format.d.ts +8 -0
- package/dist/lib/accounting-format.js +20 -2
- package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
- package/dist/lib/alibaba-coding-plan-cli.js +539 -0
- package/dist/lib/anthropic-api-auth.d.ts +7 -0
- package/dist/lib/anthropic-api-auth.js +27 -0
- package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
- package/dist/lib/anthropic-api-rate-limits.js +92 -0
- package/dist/lib/anthropic-auth.d.ts +2 -3
- package/dist/lib/anthropic-auth.js +2 -3
- package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
- package/dist/lib/anthropic-oauth-throttle.js +379 -0
- package/dist/lib/anthropic.d.ts +68 -14
- package/dist/lib/anthropic.js +1016 -363
- package/dist/lib/api-key-retry-after.d.ts +7 -0
- package/dist/lib/api-key-retry-after.js +62 -0
- package/dist/lib/atomic-json.d.ts +2 -0
- package/dist/lib/atomic-json.js +1 -0
- package/dist/lib/cache-observer-ingestion.d.ts +90 -0
- package/dist/lib/cache-observer-ingestion.js +1008 -0
- package/dist/lib/cache-observer.d.ts +141 -0
- package/dist/lib/cache-observer.js +323 -0
- package/dist/lib/canonical-config-lock.d.ts +9 -0
- package/dist/lib/canonical-config-lock.js +36 -0
- package/dist/lib/chutes.js +62 -51
- package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
- package/dist/lib/claude-agent-transcript-ttl.js +154 -0
- package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
- package/dist/lib/claude-agent-ttl-tracker.js +152 -0
- package/dist/lib/cli-show.d.ts +5 -0
- package/dist/lib/cli-show.js +21 -8
- package/dist/lib/cli-status.js +3 -6
- package/dist/lib/config-write-target.d.ts +1 -1
- package/dist/lib/config-write-target.js +5 -2
- package/dist/lib/config.d.ts +2 -1
- package/dist/lib/config.js +257 -4
- package/dist/lib/copilot.js +171 -86
- package/dist/lib/dashboard-visibility.d.ts +5 -0
- package/dist/lib/dashboard-visibility.js +11 -10
- package/dist/lib/dashboard-web-policy.d.ts +4 -4
- package/dist/lib/dashboard-web-policy.js +2 -2
- package/dist/lib/deepseek.js +25 -13
- package/dist/lib/display-sanitize.js +2 -0
- package/dist/lib/entries.d.ts +33 -1
- package/dist/lib/entries.js +6 -0
- package/dist/lib/glm-coding-plan.js +98 -74
- package/dist/lib/google-agy.js +90 -12
- package/dist/lib/google-gemini-cli.js +84 -11
- package/dist/lib/grouped-entry-normalization.js +1 -1
- package/dist/lib/http.d.ts +4 -0
- package/dist/lib/http.js +16 -2
- package/dist/lib/init-installer.js +5 -3
- package/dist/lib/kilo.js +37 -18
- package/dist/lib/kimi.js +35 -18
- package/dist/lib/maintainer-announcements.js +2 -2
- package/dist/lib/mimo.d.ts +2 -0
- package/dist/lib/mimo.js +36 -0
- package/dist/lib/modelsdev-pricing.d.ts +74 -2
- package/dist/lib/modelsdev-pricing.js +457 -63
- package/dist/lib/modelsdev-temporal.d.ts +6 -0
- package/dist/lib/modelsdev-temporal.js +16 -2
- package/dist/lib/nanogpt.d.ts +1 -0
- package/dist/lib/nanogpt.js +26 -3
- package/dist/lib/ollama-cloud.d.ts +1 -1
- package/dist/lib/ollama-cloud.js +48 -35
- package/dist/lib/openai.js +84 -38
- package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
- package/dist/lib/opencode-auth-sqlite.js +2 -2
- package/dist/lib/opencode-config-editor.d.ts +1 -0
- package/dist/lib/opencode-config-editor.js +6 -1
- package/dist/lib/opencode-config-providers.js +2 -2
- package/dist/lib/opencode-go.js +29 -2
- package/dist/lib/opencode-storage.d.ts +20 -0
- package/dist/lib/opencode-storage.js +89 -2
- package/dist/lib/opencode-version-core.d.ts +30 -0
- package/dist/lib/opencode-version-core.js +59 -0
- package/dist/lib/opencode-version.d.ts +2 -22
- package/dist/lib/opencode-version.js +4 -48
- package/dist/lib/opencode-warming-refresh.d.ts +19 -0
- package/dist/lib/opencode-warming-refresh.js +95 -0
- package/dist/lib/opencode-zen.d.ts +3 -0
- package/dist/lib/opencode-zen.js +71 -5
- package/dist/lib/provider-add.js +5 -2
- package/dist/lib/provider-metadata.d.ts +11 -3
- package/dist/lib/provider-metadata.js +20 -2
- package/dist/lib/provider-registration.d.ts +358 -9
- package/dist/lib/provider-registration.js +423 -30
- package/dist/lib/quota-auto-resume.d.ts +74 -0
- package/dist/lib/quota-auto-resume.js +539 -0
- package/dist/lib/quota-command-format.js +23 -10
- package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
- package/dist/lib/quota-exhaustion-projection.js +25 -0
- package/dist/lib/quota-identity.d.ts +64 -0
- package/dist/lib/quota-identity.js +111 -0
- package/dist/lib/quota-providers-remote.d.ts +2 -1
- package/dist/lib/quota-providers-remote.js +59 -3
- package/dist/lib/quota-providers.d.ts +1 -1
- package/dist/lib/quota-providers.js +14 -37
- package/dist/lib/quota-render-data.d.ts +6 -0
- package/dist/lib/quota-render-data.js +45 -19
- package/dist/lib/quota-reset-notifications.js +11 -155
- package/dist/lib/quota-retry-wait.d.ts +106 -5
- package/dist/lib/quota-retry-wait.js +301 -34
- package/dist/lib/quota-runtime-context.js +1 -0
- package/dist/lib/quota-state-codec.d.ts +2 -0
- package/dist/lib/quota-state-codec.js +31 -2
- package/dist/lib/quota-state.d.ts +8 -2
- package/dist/lib/quota-state.js +253 -47
- package/dist/lib/quota-stats.d.ts +26 -0
- package/dist/lib/quota-stats.js +40 -1
- package/dist/lib/quota-status.js +3 -51
- package/dist/lib/quota-surface-data.js +18 -3
- package/dist/lib/quota-telemetry.js +2 -2
- package/dist/lib/resolved-auth-identity.d.ts +19 -0
- package/dist/lib/resolved-auth-identity.js +44 -0
- package/dist/lib/scoped-update.d.ts +1 -1
- package/dist/lib/state-file-lock.d.ts +26 -0
- package/dist/lib/state-file-lock.js +205 -0
- package/dist/lib/synthetic.js +65 -54
- package/dist/lib/toast-format-grouped.js +7 -4
- package/dist/lib/tui-compact-format.js +29 -16
- package/dist/lib/types.d.ts +51 -1
- package/dist/lib/types.js +17 -1
- package/dist/lib/xai.js +48 -22
- package/dist/plugin.js +328 -14
- package/dist/provider-logos/NOTICE.md +1 -1
- package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
- package/dist/providers/alibaba-coding-plan.js +125 -104
- package/dist/providers/alibaba-token-plan.js +9 -5
- package/dist/providers/anthropic.d.ts +16 -3
- package/dist/providers/anthropic.js +172 -220
- package/dist/providers/cache-policies.d.ts +11 -4
- package/dist/providers/cache-policies.js +19 -13
- package/dist/providers/chutes.js +2 -0
- package/dist/providers/claude-agent.d.ts +19 -0
- package/dist/providers/claude-agent.js +215 -0
- package/dist/providers/copilot.js +7 -4
- package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
- package/dist/providers/glm-coding-plan-provider.js +30 -23
- package/dist/providers/google-account-format.js +1 -0
- package/dist/providers/google-agy.d.ts +6 -5
- package/dist/providers/google-agy.js +43 -15
- package/dist/providers/google-gemini-cli.js +1 -0
- package/dist/providers/kilo.js +1 -0
- package/dist/providers/kimi-code.js +2 -0
- package/dist/providers/mimo.js +1 -0
- package/dist/providers/nanogpt.js +1 -0
- package/dist/providers/ollama-cloud.js +10 -0
- package/dist/providers/openai.js +24 -23
- package/dist/providers/opencode-go.js +10 -6
- package/dist/providers/opencode-zen.js +3 -1
- package/dist/providers/openrouter.js +1 -0
- package/dist/providers/quota-providers.js +16 -5
- package/dist/providers/registry.js +2 -0
- package/dist/providers/result-helpers.d.ts +6 -2
- package/dist/providers/result-helpers.js +7 -1
- package/dist/providers/synthetic.js +4 -0
- package/dist/providers/xai.js +9 -8
- package/dist/rpc.d.ts +129 -8
- package/dist/rpc.js +219 -14
- package/dist/ui/assets/{index-cDd9jUVY.css → index-6_g1FHs-.css} +1 -1
- package/dist/ui/assets/index-sZnGUuML.js +10 -0
- package/dist/ui/assets/{popover-BGkgv9s0.js → popover-C4ZLYe9E.js} +1 -1
- package/dist/ui/assets/providers/claude-agent.svg +3 -0
- package/dist/ui/index.html +2 -2
- package/package.json +45 -46
- package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
- package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
- package/dist/ui/assets/index-DLHeXYff.js +0 -9
package/dist/lib/anthropic.js
CHANGED
|
@@ -4,36 +4,73 @@
|
|
|
4
4
|
* Uses the local Claude CLI/runtime to detect install/auth state first. When
|
|
5
5
|
* Claude auth is confirmed but local quota windows are missing, it falls back
|
|
6
6
|
* to Anthropic's OAuth usage endpoint using the first usable OAuth access
|
|
7
|
-
* token
|
|
8
|
-
* Keychain first, then the local credentials file).
|
|
7
|
+
* token from Claude OAuth credentials (macOS Keychain first, then the local credentials file).
|
|
9
8
|
*/
|
|
10
9
|
import { execFile } from "child_process";
|
|
11
10
|
import { createHash } from "crypto";
|
|
12
11
|
import { existsSync } from "fs";
|
|
13
|
-
import { readFile } from "fs/promises";
|
|
12
|
+
import { readFile, stat } from "fs/promises";
|
|
14
13
|
import { homedir } from "os";
|
|
15
|
-
import { join } from "path";
|
|
16
|
-
import {
|
|
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";
|
|
17
17
|
import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
|
|
18
18
|
import { fetchWithTimeout } from "./http.js";
|
|
19
|
-
import {
|
|
19
|
+
import { buildFixedWindowEvidence } from "./quota-exhaustion-projection.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
|
-
|
|
25
|
-
const
|
|
26
|
-
const ANTHROPIC_OAUTH_COOLDOWN_MAX_MS = 15 * 60_000;
|
|
27
|
-
const ANTHROPIC_OAUTH_COOLDOWN_MAX_ENTRIES = 16;
|
|
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";
|
|
28
|
+
const ANTHROPIC_USAGE_ENHANCED_URL = `${ANTHROPIC_USAGE_URL}?cedar_ember=1`;
|
|
29
29
|
const ANTHROPIC_BETA_HEADER = "oauth-2025-04-20";
|
|
30
30
|
const CLAUDE_CODE_CREDENTIALS_SERVICE = "Claude Code-credentials";
|
|
31
31
|
const CLAUDE_NO_LOCAL_QUOTA_MESSAGE = "Claude CLI auth detected, but local quota windows were not exposed.";
|
|
32
32
|
const ANTHROPIC_NO_QUOTA_MESSAGE = "Claude CLI auth detected, but quota was unavailable from the local CLI and OAuth credential sources.";
|
|
33
|
-
const
|
|
34
|
-
const
|
|
35
|
-
|
|
36
|
-
const
|
|
33
|
+
const CLAUDE_NON_SUBSCRIPTION_LOGIN_MESSAGE = "Claude CLI is not signed in with a claude.ai subscription. Run `claude auth login` and try again.";
|
|
34
|
+
const CLAUDE_CLI_TOKEN_UNVERIFIED_DETAIL = "Claude CLI did not confirm a first-party claude.ai login, so its stored token is not used.";
|
|
35
|
+
/** Environment variable the Claude CLI reads for its config directory. */
|
|
36
|
+
const CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR";
|
|
37
|
+
const CLAUDE_CONFIG_DIRECTORY_UNRESOLVED_DETAIL = "The Claude CLI config directory could not be determined, so its login is not used.";
|
|
38
|
+
/** Fixed labels for where a Claude login is kept. They name neither the home folder nor a custom path. */
|
|
39
|
+
const CLAUDE_DEFAULT_CREDENTIALS_LOCATION = "~/.claude/.credentials.json";
|
|
40
|
+
const CLAUDE_CUSTOM_CONFIG_DIRECTORY_LOCATION = "the Claude CLI config directory";
|
|
41
|
+
const ANTHROPIC_OAUTH_SHARED_STATE_KEY = Symbol.for("opencode-quota-gui.anthropic-oauth-shared-state.v1");
|
|
42
|
+
const anthropicOAuthGlobal = globalThis;
|
|
43
|
+
let anthropicOAuthSharedState = anthropicOAuthGlobal[ANTHROPIC_OAUTH_SHARED_STATE_KEY];
|
|
44
|
+
if (anthropicOAuthSharedState === undefined) {
|
|
45
|
+
anthropicOAuthSharedState = {
|
|
46
|
+
inFlight: new Map(),
|
|
47
|
+
recent: new Map(),
|
|
48
|
+
};
|
|
49
|
+
Object.defineProperty(anthropicOAuthGlobal, ANTHROPIC_OAUTH_SHARED_STATE_KEY, {
|
|
50
|
+
value: anthropicOAuthSharedState,
|
|
51
|
+
configurable: true,
|
|
52
|
+
writable: true,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
const anthropicOAuthInFlight = anthropicOAuthSharedState.inFlight;
|
|
56
|
+
anthropicOAuthSharedState.forcedInFlight ??= new Map();
|
|
57
|
+
anthropicOAuthSharedState.plainForm ??= new Set();
|
|
58
|
+
const anthropicOAuthForcedInFlight = anthropicOAuthSharedState.forcedInFlight;
|
|
59
|
+
const anthropicOAuthRecent = anthropicOAuthSharedState.recent;
|
|
60
|
+
const anthropicOAuthPlainForm = anthropicOAuthSharedState.plainForm;
|
|
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();
|
|
37
74
|
export function resolveAnthropicBinaryPath(binaryPath) {
|
|
38
75
|
const trimmed = binaryPath?.trim();
|
|
39
76
|
return trimmed ? trimmed : DEFAULT_CLAUDE_BINARY;
|
|
@@ -60,9 +97,16 @@ function formatCommandDisplayArg(value) {
|
|
|
60
97
|
function formatCommandDisplay(parts) {
|
|
61
98
|
return parts.map(formatCommandDisplayArg).join(" ");
|
|
62
99
|
}
|
|
100
|
+
/**
|
|
101
|
+
* cmd.exe cannot escape `"` inside a quoted argument, and `%` and `!` expand even inside
|
|
102
|
+
* quotes, so a path containing any of these is refused rather than handed to the shell.
|
|
103
|
+
*/
|
|
104
|
+
const WINDOWS_CMD_UNSAFE_ARG = /[%!^&|<>"\r\n]/u;
|
|
63
105
|
function quoteWindowsCmdArg(value) {
|
|
64
|
-
|
|
65
|
-
|
|
106
|
+
if (WINDOWS_CMD_UNSAFE_ARG.test(value)) {
|
|
107
|
+
throw new Error("Claude CLI path contains characters that cannot be passed safely through cmd.exe.");
|
|
108
|
+
}
|
|
109
|
+
return `"${value}"`;
|
|
66
110
|
}
|
|
67
111
|
function shouldBridgeClaudeCommandThroughWindowsShell(binaryPath) {
|
|
68
112
|
const normalized = binaryPath.trim().toLowerCase();
|
|
@@ -76,10 +120,13 @@ export function buildClaudeCommandInvocation(binaryPath, args, runtime = {}) {
|
|
|
76
120
|
const display = formatCommandDisplay([resolvedBinaryPath, ...args]);
|
|
77
121
|
if ((runtime.platform ?? process.platform) === "win32" &&
|
|
78
122
|
shouldBridgeClaudeCommandThroughWindowsShell(resolvedBinaryPath)) {
|
|
123
|
+
// `/s` strips only the outermost quote pair, so the quoted command line is wrapped once more.
|
|
124
|
+
const commandLine = [resolvedBinaryPath, ...args].map(quoteWindowsCmdArg).join(" ");
|
|
79
125
|
return {
|
|
80
126
|
file: runtime.comspec?.trim() || process.env["ComSpec"]?.trim() || "cmd.exe",
|
|
81
|
-
args: ["/d", "/s", "/c",
|
|
127
|
+
args: ["/d", "/s", "/c", `"${commandLine}"`],
|
|
82
128
|
display,
|
|
129
|
+
windowsVerbatimArguments: true,
|
|
83
130
|
};
|
|
84
131
|
}
|
|
85
132
|
return {
|
|
@@ -161,8 +208,19 @@ function parseExtraUsageQuota(extraUsage) {
|
|
|
161
208
|
if (!record || record["is_enabled"] !== true) {
|
|
162
209
|
return undefined;
|
|
163
210
|
}
|
|
164
|
-
const
|
|
165
|
-
|
|
211
|
+
const utilization = record["utilization"];
|
|
212
|
+
const usedCredits = record["used_credits"];
|
|
213
|
+
const monthlyLimit = record["monthly_limit"];
|
|
214
|
+
const used = typeof utilization === "number" && Number.isFinite(utilization)
|
|
215
|
+
? utilization
|
|
216
|
+
: typeof usedCredits === "number" &&
|
|
217
|
+
Number.isFinite(usedCredits) &&
|
|
218
|
+
typeof monthlyLimit === "number" &&
|
|
219
|
+
Number.isFinite(monthlyLimit) &&
|
|
220
|
+
monthlyLimit > 0
|
|
221
|
+
? (usedCredits / monthlyLimit) * 100
|
|
222
|
+
: undefined;
|
|
223
|
+
if (used === undefined || used < 0 || used > 100) {
|
|
166
224
|
return undefined;
|
|
167
225
|
}
|
|
168
226
|
return { percentRemaining: Math.round(100 - used) };
|
|
@@ -217,46 +275,202 @@ function parseFableWeeklyWindow(limits) {
|
|
|
217
275
|
}
|
|
218
276
|
return undefined;
|
|
219
277
|
}
|
|
220
|
-
function
|
|
278
|
+
function readUsageWindow(root, snakeKey, camelKey) {
|
|
279
|
+
const hasSnakeKey = Object.hasOwn(root, snakeKey);
|
|
280
|
+
const hasCamelKey = Object.hasOwn(root, camelKey);
|
|
281
|
+
if (!hasSnakeKey && !hasCamelKey) {
|
|
282
|
+
return { state: "absent" };
|
|
283
|
+
}
|
|
284
|
+
if (hasSnakeKey && hasCamelKey && root[snakeKey] !== root[camelKey]) {
|
|
285
|
+
return { state: "malformed" };
|
|
286
|
+
}
|
|
287
|
+
const value = hasSnakeKey ? root[snakeKey] : root[camelKey];
|
|
288
|
+
if (value === null) {
|
|
289
|
+
return { state: "absent" };
|
|
290
|
+
}
|
|
291
|
+
const window = parseQuotaWindow(value);
|
|
292
|
+
return window ? { state: "present", window } : { state: "malformed" };
|
|
293
|
+
}
|
|
294
|
+
function findUsageWindows(data, options = {}) {
|
|
221
295
|
for (const root of getUsageRoots(data)) {
|
|
222
|
-
const fiveHour =
|
|
223
|
-
const sevenDay =
|
|
224
|
-
if (
|
|
296
|
+
const fiveHour = readUsageWindow(root, "five_hour", "fiveHour");
|
|
297
|
+
const sevenDay = readUsageWindow(root, "seven_day", "sevenDay");
|
|
298
|
+
if (fiveHour.state === "malformed" || sevenDay.state === "malformed") {
|
|
225
299
|
continue;
|
|
226
300
|
}
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
301
|
+
const fiveHourWindow = fiveHour.state === "present" ? fiveHour.window : undefined;
|
|
302
|
+
const sevenDayWindow = sevenDay.state === "present" ? sevenDay.window : undefined;
|
|
303
|
+
if (!fiveHourWindow && !sevenDayWindow) {
|
|
304
|
+
if (!options.allowSupplementalOnly) {
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
if (!parseExtraUsageQuota(root["extra_usage"]) && !parseFableWeeklyWindow(root["limits"])) {
|
|
308
|
+
continue;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
230
311
|
return {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
...(extraUsage ? { extra_usage: extraUsage } : {}),
|
|
312
|
+
root,
|
|
313
|
+
...(fiveHourWindow ? { fiveHour: fiveHourWindow } : {}),
|
|
314
|
+
...(sevenDayWindow ? { sevenDay: sevenDayWindow } : {}),
|
|
235
315
|
};
|
|
236
316
|
}
|
|
237
317
|
return null;
|
|
238
318
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
319
|
+
/** Anthropic's 5-hour session window and its weekly windows (including the Fable weekly scope). */
|
|
320
|
+
const FIVE_HOUR_WINDOW_MS = 5 * 60 * 60_000;
|
|
321
|
+
const SEVEN_DAY_WINDOW_MS = 7 * 24 * 60 * 60_000;
|
|
322
|
+
/**
|
|
323
|
+
* Attaches fixed-window evidence derived from the window length and its reset. The 5h and weekly
|
|
324
|
+
* windows are assumed to reset on a fixed cycle; that is not verified against the provider. A
|
|
325
|
+
* window without a valid reset, or observed outside its inferred span, gets no evidence.
|
|
326
|
+
*/
|
|
327
|
+
function windowWithFixedEvidence(window, durationMs, observedAtMs) {
|
|
328
|
+
const fixedWindow = buildFixedWindowEvidence({
|
|
329
|
+
durationMs,
|
|
330
|
+
resetTimeIso: window.resetTimeIso,
|
|
331
|
+
observedAtMs,
|
|
332
|
+
});
|
|
333
|
+
return fixedWindow ? { ...window, fixedWindow } : window;
|
|
334
|
+
}
|
|
335
|
+
function parseUsageResponse(data, options = {}) {
|
|
336
|
+
const windows = findUsageWindows(data);
|
|
337
|
+
if (!windows?.fiveHour || !windows.sevenDay)
|
|
338
|
+
return null;
|
|
339
|
+
const extraUsage = options.includeExtraUsage
|
|
340
|
+
? parseExtraUsageQuota(windows.root["extra_usage"])
|
|
341
|
+
: undefined;
|
|
342
|
+
const observedAtMs = options.observedAtMs ?? Date.now();
|
|
343
|
+
return {
|
|
344
|
+
success: true,
|
|
345
|
+
five_hour: windowWithFixedEvidence(windows.fiveHour, FIVE_HOUR_WINDOW_MS, observedAtMs),
|
|
346
|
+
seven_day: windowWithFixedEvidence(windows.sevenDay, SEVEN_DAY_WINDOW_MS, observedAtMs),
|
|
347
|
+
...(extraUsage ? { extra_usage: extraUsage } : {}),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/** Display cap for saved reset segments and the displayed count; larger valid inventories are truncated, not hidden. */
|
|
351
|
+
const MAX_SAVED_RESET_SEGMENTS = 100;
|
|
352
|
+
/** An optional ISO date: absent/null is open (`undefined`), a bad string is invalid (`NaN`). */
|
|
353
|
+
function savedResetDateMs(value) {
|
|
354
|
+
if (value === undefined || value === null)
|
|
355
|
+
return undefined;
|
|
356
|
+
return typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Independent of the quota windows: any malformed part only drops that grant (or the inventory).
|
|
360
|
+
* Identifiers, labels and every other field are discarded; unknown expiry stays absent.
|
|
361
|
+
*/
|
|
362
|
+
function parseSavedResets(raw, nowMs) {
|
|
363
|
+
const root = asRecord(raw);
|
|
364
|
+
if (root?.["eligible"] !== true || !Array.isArray(root["grants"]))
|
|
365
|
+
return undefined;
|
|
366
|
+
const grants = [];
|
|
367
|
+
for (const entry of root["grants"]) {
|
|
368
|
+
const grant = asRecord(entry);
|
|
369
|
+
if (!grant || grant["paused"] !== false)
|
|
370
|
+
continue;
|
|
371
|
+
const left = grant["resets_left"];
|
|
372
|
+
if (typeof left !== "number" || !Number.isSafeInteger(left) || left <= 0)
|
|
373
|
+
continue;
|
|
374
|
+
const startMs = savedResetDateMs(grant["starts_at"]);
|
|
375
|
+
const endMs = savedResetDateMs(grant["ends_at"]);
|
|
376
|
+
if (Number.isNaN(startMs) || Number.isNaN(endMs))
|
|
377
|
+
continue;
|
|
378
|
+
if (startMs !== undefined && startMs > nowMs)
|
|
379
|
+
continue;
|
|
380
|
+
if (endMs !== undefined && endMs <= nowMs)
|
|
381
|
+
continue;
|
|
382
|
+
const total = grant["resets_total"];
|
|
383
|
+
if (total !== undefined &&
|
|
384
|
+
(typeof total !== "number" || !Number.isSafeInteger(total) || total < left)) {
|
|
244
385
|
continue;
|
|
245
386
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
387
|
+
// Counts are clamped per grant so huge safe integers never grow the sum or the allocation.
|
|
388
|
+
grants.push({ count: Math.min(left, MAX_SAVED_RESET_SEGMENTS), endMs });
|
|
389
|
+
}
|
|
390
|
+
// Earliest known expiry first, unknown last; stable for equal expiries.
|
|
391
|
+
grants.sort((a, b) => (a.endMs ?? Infinity) - (b.endMs ?? Infinity) || 0);
|
|
392
|
+
const credits = [];
|
|
393
|
+
for (const grant of grants) {
|
|
394
|
+
const expiry = grant.endMs === undefined ? {} : { expiresAtIso: new Date(grant.endMs).toISOString() };
|
|
395
|
+
for (let n = grant.count; n > 0 && credits.length < MAX_SAVED_RESET_SEGMENTS; n -= 1) {
|
|
396
|
+
credits.push({ ...expiry });
|
|
397
|
+
}
|
|
255
398
|
}
|
|
256
|
-
return
|
|
399
|
+
return credits.length > 0 ? { availableCount: credits.length, credits } : undefined;
|
|
257
400
|
}
|
|
258
|
-
function
|
|
259
|
-
|
|
401
|
+
function parseOAuthUsageResponse(data, observedAtMs = Date.now()) {
|
|
402
|
+
const windows = findUsageWindows(data, { allowSupplementalOnly: true });
|
|
403
|
+
if (!windows)
|
|
404
|
+
return null;
|
|
405
|
+
const extraUsage = parseExtraUsageQuota(windows.root["extra_usage"]);
|
|
406
|
+
const fableWeekly = parseFableWeeklyWindow(windows.root["limits"]);
|
|
407
|
+
const savedResets = parseSavedResets(windows.root["cedar_ember"], observedAtMs);
|
|
408
|
+
return {
|
|
409
|
+
...(savedResets ? { saved_resets: savedResets } : {}),
|
|
410
|
+
success: true,
|
|
411
|
+
...(windows.fiveHour
|
|
412
|
+
? {
|
|
413
|
+
five_hour: windowWithFixedEvidence(windows.fiveHour, FIVE_HOUR_WINDOW_MS, observedAtMs),
|
|
414
|
+
}
|
|
415
|
+
: {}),
|
|
416
|
+
...(windows.sevenDay
|
|
417
|
+
? {
|
|
418
|
+
seven_day: windowWithFixedEvidence(windows.sevenDay, SEVEN_DAY_WINDOW_MS, observedAtMs),
|
|
419
|
+
}
|
|
420
|
+
: {}),
|
|
421
|
+
...(extraUsage ? { extra_usage: extraUsage } : {}),
|
|
422
|
+
...(fableWeekly ? { fable_weekly: fableWeekly } : {}),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Parses one candidate config directory. `undefined` means the value is absent, which is not an
|
|
427
|
+
* error. `null` means it is present but cannot name a directory (not a string, empty, padded with
|
|
428
|
+
* whitespace, or relative), so the caller must fail closed rather than read another login.
|
|
429
|
+
*/
|
|
430
|
+
export function parseClaudeConfigDirectoryCandidate(value) {
|
|
431
|
+
if (value === undefined)
|
|
432
|
+
return undefined;
|
|
433
|
+
if (typeof value !== "string")
|
|
434
|
+
return null;
|
|
435
|
+
if (!value || value.trim() !== value || !isAbsolute(value))
|
|
436
|
+
return null;
|
|
437
|
+
return resolve(value);
|
|
438
|
+
}
|
|
439
|
+
function isSameConfigDirectory(left, right) {
|
|
440
|
+
return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* The directory the Claude CLI reads its login from. A directory the CLI reports is authoritative;
|
|
444
|
+
* otherwise CLAUDE_CONFIG_DIR names it, and with neither set it is the default `~/.claude`. An
|
|
445
|
+
* invalid value, or a reported directory that disagrees with CLAUDE_CONFIG_DIR, is unresolved, so
|
|
446
|
+
* no login is read in its place.
|
|
447
|
+
*/
|
|
448
|
+
function resolveClaudeConfigDirectory(reported, environment) {
|
|
449
|
+
const fromReport = parseClaudeConfigDirectoryCandidate(reported);
|
|
450
|
+
const fromEnvironment = parseClaudeConfigDirectoryCandidate(environment);
|
|
451
|
+
if (fromReport === null || fromEnvironment === null)
|
|
452
|
+
return { state: "unresolved" };
|
|
453
|
+
if (fromReport && fromEnvironment && !isSameConfigDirectory(fromReport, fromEnvironment)) {
|
|
454
|
+
return { state: "unresolved" };
|
|
455
|
+
}
|
|
456
|
+
const defaultDirectory = resolve(join(homedir(), ".claude"));
|
|
457
|
+
const path = fromReport ?? fromEnvironment ?? defaultDirectory;
|
|
458
|
+
return {
|
|
459
|
+
state: "resolved",
|
|
460
|
+
path,
|
|
461
|
+
// An explicit config directory may use a different macOS Keychain service,
|
|
462
|
+
// even when it names the default path; never guess that service's identity.
|
|
463
|
+
isDefault: fromEnvironment === undefined && isSameConfigDirectory(path, defaultDirectory),
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
/** The identity qualifier for a config directory: its resolved path, or a fixed word when none is bound. */
|
|
467
|
+
function claudeConfigDirectoryQualifier(configDirectory) {
|
|
468
|
+
return configDirectory?.state === "resolved" ? configDirectory.path : "unresolved";
|
|
469
|
+
}
|
|
470
|
+
function claudeCredentialsLocation(directory) {
|
|
471
|
+
return directory.isDefault
|
|
472
|
+
? CLAUDE_DEFAULT_CREDENTIALS_LOCATION
|
|
473
|
+
: CLAUDE_CUSTOM_CONFIG_DIRECTORY_LOCATION;
|
|
260
474
|
}
|
|
261
475
|
function getClaudeKeychainLocation() {
|
|
262
476
|
return `macOS Keychain service ${sanitizeDisplayText(CLAUDE_CODE_CREDENTIALS_SERVICE)}`;
|
|
@@ -280,7 +494,7 @@ function buildAnthropicNoQuotaDiagnosticsMessage(detail) {
|
|
|
280
494
|
function extractClaudeCredentialsAccessToken(data) {
|
|
281
495
|
const root = asRecord(data);
|
|
282
496
|
if (!root) {
|
|
283
|
-
return "";
|
|
497
|
+
return { accessToken: "" };
|
|
284
498
|
}
|
|
285
499
|
for (const candidate of [asRecord(root["claudeAiOauth"]), asRecord(root["oauth"]), root]) {
|
|
286
500
|
if (!candidate) {
|
|
@@ -289,11 +503,17 @@ function extractClaudeCredentialsAccessToken(data) {
|
|
|
289
503
|
for (const key of ["accessToken", "access_token", "token"]) {
|
|
290
504
|
const token = candidate[key];
|
|
291
505
|
if (typeof token === "string" && token.trim()) {
|
|
292
|
-
|
|
506
|
+
const expiresAt = candidate["expiresAt"];
|
|
507
|
+
return {
|
|
508
|
+
accessToken: token.trim(),
|
|
509
|
+
...(typeof expiresAt === "number" && Number.isFinite(expiresAt)
|
|
510
|
+
? { expiresAtMs: expiresAt }
|
|
511
|
+
: {}),
|
|
512
|
+
};
|
|
293
513
|
}
|
|
294
514
|
}
|
|
295
515
|
}
|
|
296
|
-
return "";
|
|
516
|
+
return { accessToken: "" };
|
|
297
517
|
}
|
|
298
518
|
function parseClaudeCredentialsAccessToken(content, options) {
|
|
299
519
|
const trimmed = content.trim();
|
|
@@ -305,13 +525,14 @@ function parseClaudeCredentialsAccessToken(content, options) {
|
|
|
305
525
|
}
|
|
306
526
|
try {
|
|
307
527
|
const parsed = JSON.parse(trimmed);
|
|
308
|
-
const accessToken = extractClaudeCredentialsAccessToken(parsed);
|
|
309
|
-
return accessToken
|
|
528
|
+
const { accessToken, expiresAtMs } = extractClaudeCredentialsAccessToken(parsed);
|
|
529
|
+
return accessToken
|
|
530
|
+
? { accessToken, ...(expiresAtMs === undefined ? {} : { expiresAtMs }) }
|
|
531
|
+
: { error: "missing" };
|
|
310
532
|
}
|
|
311
|
-
catch
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
};
|
|
533
|
+
catch {
|
|
534
|
+
// The parser's own message can quote a fragment of the token, so only a fixed reason is kept.
|
|
535
|
+
return { error: "invalid JSON" };
|
|
315
536
|
}
|
|
316
537
|
}
|
|
317
538
|
async function runCredentialCommand(file, args) {
|
|
@@ -321,6 +542,7 @@ async function runCredentialCommand(file, args) {
|
|
|
321
542
|
encoding: "utf8",
|
|
322
543
|
timeout: CLAUDE_COMMAND_TIMEOUT_MS,
|
|
323
544
|
maxBuffer: 1024 * 1024,
|
|
545
|
+
windowsHide: true,
|
|
324
546
|
}, (error, stdout, stderr) => {
|
|
325
547
|
const stdoutText = typeof stdout === "string" ? stdout : stdout.toString("utf8");
|
|
326
548
|
const stderrText = typeof stderr === "string" ? stderr : stderr.toString("utf8");
|
|
@@ -371,6 +593,8 @@ async function readClaudeCredentialsAccessTokenFromMacOSKeychain() {
|
|
|
371
593
|
return {
|
|
372
594
|
state: "configured",
|
|
373
595
|
accessToken: parsed.accessToken,
|
|
596
|
+
storage: "keychain",
|
|
597
|
+
...(parsed.expiresAtMs === undefined ? {} : { expiresAtMs: parsed.expiresAtMs }),
|
|
374
598
|
};
|
|
375
599
|
}
|
|
376
600
|
return {
|
|
@@ -380,23 +604,25 @@ async function readClaudeCredentialsAccessTokenFromMacOSKeychain() {
|
|
|
380
604
|
: `Claude OAuth access token missing in ${location}.`,
|
|
381
605
|
};
|
|
382
606
|
}
|
|
383
|
-
async function readClaudeCredentialsAccessTokenFromFile() {
|
|
384
|
-
const
|
|
607
|
+
async function readClaudeCredentialsAccessTokenFromFile(directory) {
|
|
608
|
+
const location = claudeCredentialsLocation(directory);
|
|
385
609
|
try {
|
|
386
|
-
const content = await readFile(
|
|
610
|
+
const content = await readFile(join(directory.path, ".credentials.json"), "utf8");
|
|
387
611
|
const parsed = parseClaudeCredentialsAccessToken(content, { allowPlainText: false });
|
|
388
612
|
const accessToken = parsed.accessToken?.trim() ?? "";
|
|
389
613
|
if (!accessToken) {
|
|
390
614
|
return {
|
|
391
615
|
state: "unavailable",
|
|
392
616
|
detail: parsed.error && parsed.error !== "missing"
|
|
393
|
-
? `Could not parse Claude credentials
|
|
394
|
-
: `Claude OAuth access token missing in ${
|
|
617
|
+
? `Could not parse Claude credentials in ${location}: ${parsed.error}.`
|
|
618
|
+
: `Claude OAuth access token missing in ${location}.`,
|
|
395
619
|
};
|
|
396
620
|
}
|
|
397
621
|
return {
|
|
398
622
|
state: "configured",
|
|
399
623
|
accessToken,
|
|
624
|
+
storage: "file",
|
|
625
|
+
...(parsed.expiresAtMs === undefined ? {} : { expiresAtMs: parsed.expiresAtMs }),
|
|
400
626
|
};
|
|
401
627
|
}
|
|
402
628
|
catch (error) {
|
|
@@ -406,19 +632,102 @@ async function readClaudeCredentialsAccessTokenFromFile() {
|
|
|
406
632
|
if (code === "ENOENT") {
|
|
407
633
|
return {
|
|
408
634
|
state: "not-found",
|
|
409
|
-
location
|
|
635
|
+
location,
|
|
410
636
|
};
|
|
411
637
|
}
|
|
638
|
+
// Only a system error code is shown: a file system message can name the path it failed on.
|
|
639
|
+
const shownCode = typeof code === "string" && /^E[A-Z0-9]+$/u.test(code) ? code : "unknown";
|
|
412
640
|
return {
|
|
413
641
|
state: "unavailable",
|
|
414
|
-
detail: `Could not read Claude credentials
|
|
642
|
+
detail: `Could not read Claude credentials in ${location}: ${shownCode} error.`,
|
|
415
643
|
};
|
|
416
644
|
}
|
|
417
645
|
}
|
|
418
|
-
|
|
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
|
+
}
|
|
721
|
+
async function readClaudeOAuthAccessToken(configDirectory) {
|
|
722
|
+
if (configDirectory.state !== "resolved") {
|
|
723
|
+
return { state: "unavailable", detail: CLAUDE_CONFIG_DIRECTORY_UNRESOLVED_DETAIL };
|
|
724
|
+
}
|
|
419
725
|
const locationsChecked = [];
|
|
420
726
|
const unavailableDetails = [];
|
|
421
|
-
|
|
727
|
+
// Only the default directory has a macOS Keychain entry, so a custom directory never reads it.
|
|
728
|
+
const keychainCredentials = configDirectory.isDefault
|
|
729
|
+
? await readClaudeCredentialsAccessTokenFromMacOSKeychain()
|
|
730
|
+
: null;
|
|
422
731
|
if (keychainCredentials?.state === "configured") {
|
|
423
732
|
return { ...keychainCredentials, source: "claude-credentials" };
|
|
424
733
|
}
|
|
@@ -428,8 +737,14 @@ async function readClaudeOAuthAccessToken() {
|
|
|
428
737
|
if (keychainCredentials?.state === "not-found") {
|
|
429
738
|
locationsChecked.push(keychainCredentials.location);
|
|
430
739
|
}
|
|
431
|
-
|
|
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
|
+
}
|
|
432
746
|
if (fileCredentials.state === "configured") {
|
|
747
|
+
rememberClaudeCredentialsRead(configDirectory);
|
|
433
748
|
return { ...fileCredentials, source: "claude-credentials" };
|
|
434
749
|
}
|
|
435
750
|
if (fileCredentials.state === "unavailable") {
|
|
@@ -443,20 +758,17 @@ async function readClaudeOAuthAccessToken() {
|
|
|
443
758
|
detail: unavailableDetails[0] ?? getClaudeCredentialsNotFoundDetail(locationsChecked),
|
|
444
759
|
};
|
|
445
760
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
};
|
|
761
|
+
/**
|
|
762
|
+
* The Claude CLI's stored subscription token. It is read only when the CLI positively reports a
|
|
763
|
+
* first-party claude.ai login, because an absent or non-JSON status cannot prove whose token it is.
|
|
764
|
+
*/
|
|
765
|
+
async function readClaudeCliSubscriptionToken(localDiagnostics) {
|
|
766
|
+
if (localDiagnostics.claudeAiLoginVerified !== true) {
|
|
767
|
+
return { state: "unavailable", detail: CLAUDE_CLI_TOKEN_UNVERIFIED_DETAIL };
|
|
454
768
|
}
|
|
455
|
-
return
|
|
456
|
-
? await readClaudeOAuthAccessToken()
|
|
457
|
-
: { state: "unavailable" };
|
|
769
|
+
return await readClaudeOAuthAccessToken(localDiagnostics.configDirectory ?? { state: "unresolved" });
|
|
458
770
|
}
|
|
459
|
-
function fingerprintAccessToken(accessToken) {
|
|
771
|
+
export function fingerprintAccessToken(accessToken) {
|
|
460
772
|
return createHash("sha256").update(accessToken).digest("hex");
|
|
461
773
|
}
|
|
462
774
|
function parseRetryAfterMs(value, nowMs) {
|
|
@@ -466,32 +778,33 @@ function parseRetryAfterMs(value, nowMs) {
|
|
|
466
778
|
}
|
|
467
779
|
if (/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(trimmed)) {
|
|
468
780
|
const seconds = Number(trimmed);
|
|
469
|
-
|
|
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;
|
|
470
787
|
}
|
|
471
788
|
const retryAtMs = Date.parse(trimmed);
|
|
472
789
|
const durationMs = retryAtMs - nowMs;
|
|
473
|
-
return Number.isFinite(durationMs) &&
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
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;
|
|
479
795
|
}
|
|
480
796
|
function getAnthropicOAuthCooldownMessage(remainingMs) {
|
|
481
|
-
|
|
482
|
-
return `Anthropic OAuth usage probe paused after HTTP 429; retry in ${Math.ceil(boundedRemainingMs / 1_000)}s.`;
|
|
797
|
+
return `Anthropic OAuth usage probe paused after HTTP 429; retry in ${Math.ceil(Math.max(0, remainingMs) / 1_000)}s.`;
|
|
483
798
|
}
|
|
484
|
-
function
|
|
485
|
-
const
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
break;
|
|
492
|
-
if (fingerprint !== tokenFingerprint)
|
|
493
|
-
anthropicOAuthCooldowns.delete(fingerprint);
|
|
799
|
+
function rememberAnthropicOAuthQuota(tokenFingerprint, quota, measuredAtMs, pollIntervalMs) {
|
|
800
|
+
const nowMs = Date.now();
|
|
801
|
+
const reuseWindowMs = normalizeAnthropicOAuthPollIntervalMs(pollIntervalMs);
|
|
802
|
+
for (const [fingerprint, entry] of anthropicOAuthRecent) {
|
|
803
|
+
if (nowMs - entry.measuredAtMs >= reuseWindowMs) {
|
|
804
|
+
anthropicOAuthRecent.delete(fingerprint);
|
|
805
|
+
}
|
|
494
806
|
}
|
|
807
|
+
anthropicOAuthRecent.set(tokenFingerprint, { quota, measuredAtMs });
|
|
495
808
|
}
|
|
496
809
|
function redactAccessTokenFromSanitizedDetail(detail, accessToken) {
|
|
497
810
|
const sanitizedDetail = sanitizeDisplayText(detail);
|
|
@@ -507,32 +820,56 @@ function sanitizeAnthropicApiDetail(detail, accessToken) {
|
|
|
507
820
|
function sanitizeAnthropicRequestError(detail, accessToken) {
|
|
508
821
|
return redactAccessTokenFromSanitizedDetail(detail, accessToken);
|
|
509
822
|
}
|
|
510
|
-
|
|
823
|
+
/** The usage endpoint rejects unrecognized clients, so identify as the Claude CLI that owns the login. */
|
|
824
|
+
function claudeCodeUserAgent(cliVersion, enhanced) {
|
|
825
|
+
const version = (cliVersion ?? "").replace(/[^0-9A-Za-z.+-]/gu, "").slice(0, 48);
|
|
826
|
+
if (enhanced)
|
|
827
|
+
return version ? `claude-cli/${version} (external, cli)` : "claude-cli (external, cli)";
|
|
828
|
+
// The plain fallback keeps the identity the usage probe has always sent.
|
|
829
|
+
return version ? `claude-code/${version}` : "claude-code";
|
|
830
|
+
}
|
|
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);
|
|
839
|
+
}
|
|
840
|
+
async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, enhanced, publishRateLimit) {
|
|
511
841
|
try {
|
|
512
|
-
return await fetchWithTimeout(ANTHROPIC_USAGE_URL, {
|
|
842
|
+
return await fetchWithTimeout(enhanced ? ANTHROPIC_USAGE_ENHANCED_URL : ANTHROPIC_USAGE_URL, {
|
|
513
843
|
request: {
|
|
514
844
|
headers: {
|
|
515
845
|
Authorization: `Bearer ${accessToken}`,
|
|
516
846
|
"anthropic-beta": ANTHROPIC_BETA_HEADER,
|
|
847
|
+
"User-Agent": claudeCodeUserAgent(cliVersion, enhanced),
|
|
517
848
|
},
|
|
518
849
|
},
|
|
519
850
|
timeoutMs: requestTimeoutMs,
|
|
520
851
|
consume: async (response, timeoutSignal) => {
|
|
521
852
|
if (response.status === 429) {
|
|
853
|
+
anthropicOAuthRecent.delete(tokenFingerprint);
|
|
522
854
|
const nowMs = Date.now();
|
|
523
|
-
const
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
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.
|
|
529
868
|
let detail = "";
|
|
530
869
|
try {
|
|
531
870
|
detail = sanitizeAnthropicApiDetail(await response.text(), accessToken);
|
|
532
871
|
}
|
|
533
|
-
catch
|
|
534
|
-
if (timeoutSignal.aborted)
|
|
535
|
-
throw error;
|
|
872
|
+
catch {
|
|
536
873
|
detail = "";
|
|
537
874
|
}
|
|
538
875
|
const errorDetail = detail
|
|
@@ -540,29 +877,41 @@ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint,
|
|
|
540
877
|
: `Anthropic API returned ${response.status}`;
|
|
541
878
|
return {
|
|
542
879
|
state: "unavailable",
|
|
543
|
-
detail:
|
|
880
|
+
detail: errorDetail,
|
|
544
881
|
failureCategory: "provider_api",
|
|
882
|
+
rateLimited: true,
|
|
883
|
+
...(retryAfterMs !== undefined ? { retryAfterMs } : {}),
|
|
884
|
+
attempt: "transient",
|
|
545
885
|
};
|
|
546
886
|
}
|
|
547
|
-
anthropicOAuthCooldowns.delete(tokenFingerprint);
|
|
548
887
|
if (!response.ok) {
|
|
549
888
|
const authenticationFailure = response.status === 401 || response.status === 403;
|
|
550
889
|
let detail = "";
|
|
890
|
+
let enhancedRejected = enhanced && response.status === 400;
|
|
551
891
|
try {
|
|
552
|
-
|
|
892
|
+
const body = await response.text();
|
|
893
|
+
// A 403 naming a missing scope or user:profile is a real credential problem, never an enhanced-form rejection.
|
|
894
|
+
if (enhanced && response.status === 403 && !/scope|user:profile/iu.test(body)) {
|
|
895
|
+
enhancedRejected = true;
|
|
896
|
+
}
|
|
897
|
+
detail = sanitizeAnthropicApiDetail(body, accessToken);
|
|
553
898
|
}
|
|
554
899
|
catch (error) {
|
|
555
900
|
if (timeoutSignal.aborted && !authenticationFailure)
|
|
556
901
|
throw error;
|
|
557
902
|
detail = "";
|
|
558
903
|
}
|
|
904
|
+
if (enhancedRejected)
|
|
905
|
+
anthropicOAuthPlainForm.add(tokenFingerprint);
|
|
559
906
|
return {
|
|
560
907
|
state: "unavailable",
|
|
561
908
|
detail: detail
|
|
562
909
|
? `Anthropic API error ${response.status}: ${detail}`
|
|
563
910
|
: `Anthropic API returned ${response.status}`,
|
|
564
911
|
...(authenticationFailure ? { failureKind: "authentication" } : {}),
|
|
912
|
+
httpStatus: response.status,
|
|
565
913
|
failureCategory: authenticationFailure ? "credentials" : "provider_api",
|
|
914
|
+
attempt: authenticationFailure ? "credentials" : "transient",
|
|
566
915
|
};
|
|
567
916
|
}
|
|
568
917
|
let data;
|
|
@@ -576,6 +925,7 @@ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint,
|
|
|
576
925
|
state: "unavailable",
|
|
577
926
|
detail: "Failed to parse Anthropic quota response",
|
|
578
927
|
failureCategory: "provider_api",
|
|
928
|
+
attempt: "transient",
|
|
579
929
|
};
|
|
580
930
|
}
|
|
581
931
|
const quota = parseOAuthUsageResponse(data);
|
|
@@ -584,11 +934,14 @@ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint,
|
|
|
584
934
|
state: "unavailable",
|
|
585
935
|
detail: "Unexpected Anthropic quota response shape",
|
|
586
936
|
failureCategory: "provider_api",
|
|
937
|
+
attempt: "transient",
|
|
587
938
|
};
|
|
588
939
|
}
|
|
589
940
|
return {
|
|
590
941
|
state: "success",
|
|
591
942
|
quota,
|
|
943
|
+
attempt: "fresh",
|
|
944
|
+
measuredAtMs: Date.now(),
|
|
592
945
|
};
|
|
593
946
|
},
|
|
594
947
|
});
|
|
@@ -598,37 +951,179 @@ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint,
|
|
|
598
951
|
state: "unavailable",
|
|
599
952
|
detail: sanitizeAnthropicRequestError(error instanceof Error ? error.message : String(error), accessToken),
|
|
600
953
|
failureCategory: "provider_api",
|
|
954
|
+
attempt: "transient",
|
|
601
955
|
};
|
|
602
956
|
}
|
|
603
957
|
}
|
|
604
|
-
async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs) {
|
|
958
|
+
async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs, forcedOperationCache, cliVersion, pollIntervalMs) {
|
|
605
959
|
const tokenFingerprint = fingerprintAccessToken(accessToken);
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
}
|
|
960
|
+
const intervalMs = normalizeAnthropicOAuthPollIntervalMs(pollIntervalMs);
|
|
961
|
+
let forcedResults;
|
|
962
|
+
if (forcedOperationCache) {
|
|
963
|
+
forcedResults = forcedOperationCache.get(anthropicForcedResultsKey);
|
|
964
|
+
if (!forcedResults) {
|
|
965
|
+
forcedResults = new Map();
|
|
966
|
+
forcedOperationCache.set(anthropicForcedResultsKey, forcedResults);
|
|
967
|
+
}
|
|
968
|
+
const existing = forcedResults.get(tokenFingerprint);
|
|
969
|
+
if (existing)
|
|
970
|
+
return await existing;
|
|
971
|
+
}
|
|
972
|
+
if (forcedResults) {
|
|
973
|
+
const existingForced = anthropicOAuthForcedInFlight.get(tokenFingerprint);
|
|
974
|
+
if (existingForced) {
|
|
975
|
+
forcedResults.set(tokenFingerprint, existingForced);
|
|
976
|
+
return await existingForced;
|
|
977
|
+
}
|
|
614
978
|
}
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
979
|
+
else {
|
|
980
|
+
const existing = anthropicOAuthInFlight.get(tokenFingerprint);
|
|
981
|
+
if (existing)
|
|
982
|
+
return await existing;
|
|
618
983
|
}
|
|
619
|
-
const
|
|
984
|
+
const prior = forcedResults ? anthropicOAuthInFlight.get(tokenFingerprint) : undefined;
|
|
985
|
+
const inFlight = (async () => {
|
|
986
|
+
if (prior)
|
|
987
|
+
await prior;
|
|
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);
|
|
1017
|
+
return {
|
|
1018
|
+
state: "unavailable",
|
|
1019
|
+
detail: claim.reason === "cooldown" && retryAtMs !== undefined
|
|
1020
|
+
? getAnthropicOAuthCooldownMessage(retryAtMs - nowMs)
|
|
1021
|
+
: "Claude Agent usage request is already being coordinated.",
|
|
1022
|
+
failureCategory: "provider_api",
|
|
1023
|
+
...(retryAtMs !== undefined ? { retryAtMs } : {}),
|
|
1024
|
+
attempt: "cooldown",
|
|
1025
|
+
};
|
|
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;
|
|
1071
|
+
if (result.state === "success") {
|
|
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" });
|
|
1097
|
+
}
|
|
1098
|
+
else {
|
|
1099
|
+
await claim.complete({ kind: "network-error" });
|
|
1100
|
+
}
|
|
1101
|
+
if (result.state !== "success") {
|
|
1102
|
+
const cached = anthropicOAuthRecent.get(tokenFingerprint);
|
|
1103
|
+
if (cached?.quota.saved_resets) {
|
|
1104
|
+
const { saved_resets: _savedResets, ...quota } = cached.quota;
|
|
1105
|
+
anthropicOAuthRecent.set(tokenFingerprint, { ...cached, quota });
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
return result;
|
|
1109
|
+
})();
|
|
620
1110
|
anthropicOAuthInFlight.set(tokenFingerprint, inFlight);
|
|
1111
|
+
if (forcedResults) {
|
|
1112
|
+
forcedResults.set(tokenFingerprint, inFlight);
|
|
1113
|
+
anthropicOAuthForcedInFlight.set(tokenFingerprint, inFlight);
|
|
1114
|
+
}
|
|
621
1115
|
try {
|
|
622
1116
|
return await inFlight;
|
|
623
1117
|
}
|
|
624
1118
|
finally {
|
|
625
|
-
if (anthropicOAuthInFlight.get(tokenFingerprint) === inFlight)
|
|
1119
|
+
if (anthropicOAuthInFlight.get(tokenFingerprint) === inFlight)
|
|
626
1120
|
anthropicOAuthInFlight.delete(tokenFingerprint);
|
|
627
|
-
|
|
1121
|
+
if (anthropicOAuthForcedInFlight.get(tokenFingerprint) === inFlight)
|
|
1122
|
+
anthropicOAuthForcedInFlight.delete(tokenFingerprint);
|
|
628
1123
|
}
|
|
629
1124
|
}
|
|
630
|
-
export async function queryAnthropicQuotaWithOAuth(accessToken, requestTimeoutMs) {
|
|
631
|
-
const result = await queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs);
|
|
1125
|
+
export async function queryAnthropicQuotaWithOAuth(accessToken, requestTimeoutMs, forcedOperationCache) {
|
|
1126
|
+
const result = await queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs, forcedOperationCache);
|
|
632
1127
|
return result.state === "success"
|
|
633
1128
|
? result.quota
|
|
634
1129
|
: {
|
|
@@ -673,6 +1168,98 @@ function extractAuthBoolean(data) {
|
|
|
673
1168
|
}
|
|
674
1169
|
return undefined;
|
|
675
1170
|
}
|
|
1171
|
+
/**
|
|
1172
|
+
* `auth status --json` reports how the login was made. Only a claude.ai subscription login on
|
|
1173
|
+
* Anthropic's first-party API is the Claude Code account; any other reported method or provider is
|
|
1174
|
+
* stale or unrelated. A field that is absent is not evidence either way.
|
|
1175
|
+
*/
|
|
1176
|
+
/**
|
|
1177
|
+
* Positive evidence that the Claude CLI login is a first-party claude.ai subscription. Both fields
|
|
1178
|
+
* must be reported; an absent field proves nothing, so a login without them cannot prove its identity.
|
|
1179
|
+
*/
|
|
1180
|
+
function hasFirstPartyClaudeAiLogin(payload) {
|
|
1181
|
+
const record = asRecord(payload);
|
|
1182
|
+
if (!record)
|
|
1183
|
+
return false;
|
|
1184
|
+
const method = record["authMethod"];
|
|
1185
|
+
const provider = record["apiProvider"];
|
|
1186
|
+
return (typeof method === "string" &&
|
|
1187
|
+
method.trim().toLowerCase() === "claude.ai" &&
|
|
1188
|
+
typeof provider === "string" &&
|
|
1189
|
+
provider.trim().toLowerCase() === "firstparty");
|
|
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
|
+
}
|
|
1227
|
+
/** The only plan names shown. The CLI's `subscriptionType` is undocumented, so anything else is omitted. */
|
|
1228
|
+
const CLAUDE_PLAN_LABELS = new Map([
|
|
1229
|
+
["free", "Free"],
|
|
1230
|
+
["pro", "Pro"],
|
|
1231
|
+
["max", "Max"],
|
|
1232
|
+
["team", "Team"],
|
|
1233
|
+
["enterprise", "Enterprise"],
|
|
1234
|
+
["ultra", "Ultra"],
|
|
1235
|
+
]);
|
|
1236
|
+
/**
|
|
1237
|
+
* Display-only plan name from a verified login's `subscriptionType`; absent, null, or unknown gives none.
|
|
1238
|
+
* Bare name (e.g. "Max"): the card already names the provider, so the header reads `Anthropic · Max`,
|
|
1239
|
+
* the same shape as OpenAI's account header (`OpenAI · Pro`).
|
|
1240
|
+
*/
|
|
1241
|
+
function deriveClaudePlanLabel(payload) {
|
|
1242
|
+
const subscriptionType = asRecord(payload)?.["subscriptionType"];
|
|
1243
|
+
if (typeof subscriptionType !== "string")
|
|
1244
|
+
return undefined;
|
|
1245
|
+
return CLAUDE_PLAN_LABELS.get(subscriptionType.trim().toLowerCase());
|
|
1246
|
+
}
|
|
1247
|
+
function hasNonSubscriptionLogin(payload) {
|
|
1248
|
+
const record = asRecord(payload);
|
|
1249
|
+
if (!record)
|
|
1250
|
+
return false;
|
|
1251
|
+
const method = record["authMethod"];
|
|
1252
|
+
if (method !== undefined && method !== null) {
|
|
1253
|
+
if (typeof method !== "string" || method.trim().toLowerCase() !== "claude.ai")
|
|
1254
|
+
return true;
|
|
1255
|
+
}
|
|
1256
|
+
const provider = record["apiProvider"];
|
|
1257
|
+
if (provider !== undefined && provider !== null) {
|
|
1258
|
+
if (typeof provider !== "string" || provider.trim().toLowerCase() !== "firstparty")
|
|
1259
|
+
return true;
|
|
1260
|
+
}
|
|
1261
|
+
return false;
|
|
1262
|
+
}
|
|
676
1263
|
function hasUnsupportedCommandText(output) {
|
|
677
1264
|
const normalized = output.toLowerCase();
|
|
678
1265
|
return (normalized.includes("unknown command") ||
|
|
@@ -718,6 +1305,8 @@ async function runClaudeCommand(invocation) {
|
|
|
718
1305
|
encoding: "utf8",
|
|
719
1306
|
timeout: CLAUDE_COMMAND_TIMEOUT_MS,
|
|
720
1307
|
maxBuffer: 1024 * 1024,
|
|
1308
|
+
windowsHide: true,
|
|
1309
|
+
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
|
721
1310
|
}, (error, stdout, stderr) => {
|
|
722
1311
|
const stdoutText = typeof stdout === "string" ? stdout : stdout.toString("utf8");
|
|
723
1312
|
const stderrText = typeof stderr === "string" ? stderr : stderr.toString("utf8");
|
|
@@ -748,6 +1337,43 @@ async function runClaudeCommand(invocation) {
|
|
|
748
1337
|
}
|
|
749
1338
|
function parseClaudeAuthStatusResult(result) {
|
|
750
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
|
+
}
|
|
751
1377
|
if (hasUnsupportedCommandText(combinedOutput)) {
|
|
752
1378
|
return {
|
|
753
1379
|
authStatus: "unknown",
|
|
@@ -761,33 +1387,13 @@ function parseClaudeAuthStatusResult(result) {
|
|
|
761
1387
|
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
|
762
1388
|
};
|
|
763
1389
|
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
authStatus: "authenticated",
|
|
772
|
-
jsonPayload: payload,
|
|
773
|
-
};
|
|
774
|
-
}
|
|
775
|
-
if (auth === false) {
|
|
776
|
-
return {
|
|
777
|
-
authStatus: "unauthenticated",
|
|
778
|
-
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
|
779
|
-
jsonPayload: payload,
|
|
780
|
-
};
|
|
781
|
-
}
|
|
782
|
-
return {
|
|
783
|
-
authStatus: "unknown",
|
|
784
|
-
message: "Could not verify Claude authentication status from JSON output.",
|
|
785
|
-
jsonPayload: payload,
|
|
786
|
-
};
|
|
787
|
-
}
|
|
788
|
-
catch {
|
|
789
|
-
// Fall through to exit-code-based handling.
|
|
790
|
-
}
|
|
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
|
+
};
|
|
791
1397
|
}
|
|
792
1398
|
if (result.code === 0) {
|
|
793
1399
|
return { authStatus: "authenticated" };
|
|
@@ -796,6 +1402,8 @@ function parseClaudeAuthStatusResult(result) {
|
|
|
796
1402
|
return {
|
|
797
1403
|
authStatus: "unknown",
|
|
798
1404
|
message: "Timed out while running Claude CLI auth status.",
|
|
1405
|
+
failureCategory: "provider_api",
|
|
1406
|
+
probeFailure: true,
|
|
799
1407
|
};
|
|
800
1408
|
}
|
|
801
1409
|
const detail = detailFromCommandResult(result);
|
|
@@ -804,6 +1412,8 @@ function parseClaudeAuthStatusResult(result) {
|
|
|
804
1412
|
message: detail
|
|
805
1413
|
? `Could not verify Claude authentication status. ${detail}`
|
|
806
1414
|
: "Could not verify Claude authentication status.",
|
|
1415
|
+
failureCategory: "provider_api",
|
|
1416
|
+
probeFailure: true,
|
|
807
1417
|
};
|
|
808
1418
|
}
|
|
809
1419
|
function mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics) {
|
|
@@ -817,6 +1427,9 @@ function mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics) {
|
|
|
817
1427
|
binaryPath: localDiagnostics.binaryPath,
|
|
818
1428
|
checkedCommands: localDiagnostics.checkedCommands,
|
|
819
1429
|
quota: localDiagnostics.localQuota,
|
|
1430
|
+
...(localDiagnostics.planLabel === undefined
|
|
1431
|
+
? {}
|
|
1432
|
+
: { planLabel: localDiagnostics.planLabel }),
|
|
820
1433
|
};
|
|
821
1434
|
}
|
|
822
1435
|
const diagnostics = {
|
|
@@ -831,6 +1444,12 @@ function mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics) {
|
|
|
831
1444
|
if (localDiagnostics.message) {
|
|
832
1445
|
diagnostics.message = localDiagnostics.message;
|
|
833
1446
|
}
|
|
1447
|
+
if (localDiagnostics.failureCategory !== undefined) {
|
|
1448
|
+
diagnostics.failureCategory = localDiagnostics.failureCategory;
|
|
1449
|
+
}
|
|
1450
|
+
if (localDiagnostics.probeFailure === true) {
|
|
1451
|
+
diagnostics.probeFailure = true;
|
|
1452
|
+
}
|
|
834
1453
|
return diagnostics;
|
|
835
1454
|
}
|
|
836
1455
|
async function runClaudeVersionCommand(binaryPath, checkedCommands) {
|
|
@@ -891,261 +1510,295 @@ async function probeAnthropicLocalDiagnostics(options = {}) {
|
|
|
891
1510
|
binaryPath: binaryPathDisplay,
|
|
892
1511
|
checkedCommands,
|
|
893
1512
|
message: parsedAuth.message,
|
|
1513
|
+
...(parsedAuth.failureCategory !== undefined
|
|
1514
|
+
? { failureCategory: parsedAuth.failureCategory }
|
|
1515
|
+
: {}),
|
|
1516
|
+
...(parsedAuth.probeFailure === true ? { probeFailure: true } : {}),
|
|
894
1517
|
};
|
|
895
1518
|
}
|
|
1519
|
+
// The CLI's report wins; otherwise CLAUDE_CONFIG_DIR, then the default. The CLI inherits this
|
|
1520
|
+
// environment, so this is the directory it reads its login from.
|
|
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);
|
|
896
1524
|
const quota = parsedAuth.jsonPayload ? parseUsageResponse(parsedAuth.jsonPayload) : null;
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
localQuota: quota,
|
|
905
|
-
};
|
|
906
|
-
}
|
|
907
|
-
return {
|
|
1525
|
+
// Only a verified first-party login may name its plan; the same login answers the quota above.
|
|
1526
|
+
const planLabel = parsedAuth.claudeAiLoginVerified === true
|
|
1527
|
+
? deriveClaudePlanLabel(parsedAuth.jsonPayload)
|
|
1528
|
+
: undefined;
|
|
1529
|
+
// Both successful returns are the same authenticated CLI diagnostics; only the quota evidence
|
|
1530
|
+
// or the no-quota message differs.
|
|
1531
|
+
const diagnostics = {
|
|
908
1532
|
installed: true,
|
|
909
1533
|
version,
|
|
910
1534
|
authStatus: "authenticated",
|
|
911
1535
|
binaryPath: binaryPathDisplay,
|
|
912
1536
|
checkedCommands,
|
|
913
|
-
|
|
1537
|
+
effectiveBinary: binaryPath,
|
|
1538
|
+
configDirectory,
|
|
1539
|
+
claudeAiLoginVerified: parsedAuth.claudeAiLoginVerified === true,
|
|
1540
|
+
...(planLabel === undefined ? {} : { planLabel }),
|
|
1541
|
+
...(accountHint === undefined ? {} : { accountHint }),
|
|
1542
|
+
...(orgOnlyAccountEvidence ? { orgOnlyAccountEvidence: true } : {}),
|
|
914
1543
|
};
|
|
1544
|
+
if (quota) {
|
|
1545
|
+
return { ...diagnostics, localQuota: quota };
|
|
1546
|
+
}
|
|
1547
|
+
return { ...diagnostics, message: CLAUDE_NO_LOCAL_QUOTA_MESSAGE };
|
|
915
1548
|
}
|
|
916
1549
|
export function clearAnthropicDiagnosticsCacheForTests() {
|
|
917
|
-
diagnosticsCache.clear();
|
|
918
|
-
localDiagnosticsCache.clear();
|
|
919
|
-
anthropicOAuthCooldowns.clear();
|
|
920
1550
|
anthropicOAuthInFlight.clear();
|
|
1551
|
+
anthropicOAuthForcedInFlight.clear();
|
|
1552
|
+
anthropicOAuthRecent.clear();
|
|
1553
|
+
anthropicOAuthPlainForm.clear();
|
|
1554
|
+
clearAnthropicOAuthThrottleStateForTests();
|
|
1555
|
+
claudeCredentialsLastGoodReads.clear();
|
|
1556
|
+
claudeIdentitySuccesses.clear();
|
|
921
1557
|
}
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
});
|
|
944
|
-
localDiagnosticsCache.set(binaryPath, {
|
|
945
|
-
timestamp: cached.timestamp,
|
|
946
|
-
value: cached.value,
|
|
947
|
-
inFlight,
|
|
948
|
-
});
|
|
1558
|
+
const localDiagnosticsCacheKey = Symbol("anthropic local diagnostics");
|
|
1559
|
+
async function getAnthropicLocalDiagnostics(options = {}) {
|
|
1560
|
+
if (!options.operationCache)
|
|
1561
|
+
return await probeAnthropicLocalDiagnostics(options);
|
|
1562
|
+
let probes = options.operationCache.get(localDiagnosticsCacheKey);
|
|
1563
|
+
if (!probes) {
|
|
1564
|
+
probes = new Map();
|
|
1565
|
+
options.operationCache.set(localDiagnosticsCacheKey, probes);
|
|
1566
|
+
}
|
|
1567
|
+
const key = JSON.stringify([
|
|
1568
|
+
resolveAnthropicBinaryPath(options.binaryPath),
|
|
1569
|
+
process.env[CLAUDE_CONFIG_DIR_ENV],
|
|
1570
|
+
]);
|
|
1571
|
+
let probe = probes.get(key);
|
|
1572
|
+
if (!probe) {
|
|
1573
|
+
probe = probeAnthropicLocalDiagnostics(options);
|
|
1574
|
+
probes.set(key, probe);
|
|
1575
|
+
}
|
|
1576
|
+
return await probe;
|
|
1577
|
+
}
|
|
1578
|
+
async function readSavedResetsForLocalQuota(localDiagnostics, options) {
|
|
949
1579
|
try {
|
|
950
|
-
|
|
1580
|
+
const credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
|
|
1581
|
+
if (credentials.state !== "configured")
|
|
1582
|
+
return undefined;
|
|
1583
|
+
const result = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version, options.pollIntervalMs);
|
|
1584
|
+
return result.state === "success" ? result.quota.saved_resets : undefined;
|
|
951
1585
|
}
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
if (latest?.inFlight === inFlight) {
|
|
955
|
-
localDiagnosticsCache.set(binaryPath, {
|
|
956
|
-
timestamp: latest.timestamp,
|
|
957
|
-
value: latest.value,
|
|
958
|
-
});
|
|
959
|
-
}
|
|
1586
|
+
catch {
|
|
1587
|
+
return undefined;
|
|
960
1588
|
}
|
|
961
1589
|
}
|
|
962
1590
|
export async function getAnthropicDiagnostics(options = {}) {
|
|
963
|
-
const
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
1591
|
+
const localDiagnostics = await getAnthropicLocalDiagnostics(options);
|
|
1592
|
+
if (localDiagnostics.localQuota) {
|
|
1593
|
+
// Local quota stays authoritative and needs no token. Saved resets are an optional extra read
|
|
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.
|
|
1596
|
+
const mapped = mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
|
|
1597
|
+
const savedResets = await readSavedResetsForLocalQuota(localDiagnostics, options);
|
|
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;
|
|
973
1606
|
}
|
|
974
|
-
if (
|
|
975
|
-
return
|
|
1607
|
+
if (localDiagnostics.authStatus !== "authenticated") {
|
|
1608
|
+
return mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
|
|
976
1609
|
}
|
|
977
|
-
const
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
return mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
|
|
981
|
-
}
|
|
982
|
-
let credentials = await readAnthropicOAuthAccessToken({
|
|
983
|
-
includeClaudeCredentials: localDiagnostics.authStatus === "authenticated",
|
|
984
|
-
});
|
|
985
|
-
if (credentials.state !== "configured") {
|
|
986
|
-
if (localDiagnostics.authStatus !== "authenticated") {
|
|
987
|
-
return mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
|
|
988
|
-
}
|
|
989
|
-
const diagnostics = {
|
|
990
|
-
installed: localDiagnostics.installed,
|
|
991
|
-
version: localDiagnostics.version,
|
|
992
|
-
authStatus: localDiagnostics.authStatus,
|
|
993
|
-
quotaSupported: false,
|
|
994
|
-
quotaSource: "none",
|
|
995
|
-
binaryPath: localDiagnostics.binaryPath,
|
|
996
|
-
checkedCommands: localDiagnostics.checkedCommands,
|
|
997
|
-
message: buildAnthropicNoQuotaDiagnosticsMessage(credentials.detail),
|
|
998
|
-
};
|
|
999
|
-
return diagnostics;
|
|
1000
|
-
}
|
|
1001
|
-
let fallbackQuota = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs);
|
|
1002
|
-
if (fallbackQuota.state === "unavailable" &&
|
|
1003
|
-
fallbackQuota.failureKind === "authentication" &&
|
|
1004
|
-
credentials.source === "opencode-auth" &&
|
|
1005
|
-
localDiagnostics.authStatus === "authenticated") {
|
|
1006
|
-
const claudeCredentials = await readClaudeOAuthAccessToken();
|
|
1007
|
-
if (claudeCredentials.state === "configured") {
|
|
1008
|
-
credentials = claudeCredentials;
|
|
1009
|
-
fallbackQuota = await queryAnthropicQuotaFromOAuthAccessToken(claudeCredentials.accessToken, options.requestTimeoutMs);
|
|
1010
|
-
}
|
|
1011
|
-
}
|
|
1012
|
-
if (fallbackQuota.state !== "success") {
|
|
1013
|
-
const diagnostics = {
|
|
1014
|
-
installed: localDiagnostics.installed,
|
|
1015
|
-
version: localDiagnostics.version,
|
|
1016
|
-
authStatus: localDiagnostics.authStatus,
|
|
1017
|
-
quotaSupported: false,
|
|
1018
|
-
quotaSource: "none",
|
|
1019
|
-
oauthCredentialSource: credentials.source,
|
|
1020
|
-
binaryPath: localDiagnostics.binaryPath,
|
|
1021
|
-
checkedCommands: localDiagnostics.checkedCommands,
|
|
1022
|
-
message: buildAnthropicNoQuotaDiagnosticsMessage(fallbackQuota.detail),
|
|
1023
|
-
...(fallbackQuota.failureCategory !== undefined
|
|
1024
|
-
? { failureCategory: fallbackQuota.failureCategory }
|
|
1025
|
-
: {}),
|
|
1026
|
-
};
|
|
1027
|
-
return diagnostics;
|
|
1028
|
-
}
|
|
1029
|
-
const diagnostics = {
|
|
1610
|
+
const credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
|
|
1611
|
+
if (credentials.state !== "configured") {
|
|
1612
|
+
return {
|
|
1030
1613
|
installed: localDiagnostics.installed,
|
|
1031
1614
|
version: localDiagnostics.version,
|
|
1032
1615
|
authStatus: localDiagnostics.authStatus,
|
|
1033
|
-
quotaSupported:
|
|
1034
|
-
quotaSource:
|
|
1035
|
-
? "opencode-auth-oauth-api"
|
|
1036
|
-
: "claude-credentials-oauth-api",
|
|
1037
|
-
oauthCredentialSource: credentials.source,
|
|
1616
|
+
quotaSupported: false,
|
|
1617
|
+
quotaSource: "none",
|
|
1038
1618
|
binaryPath: localDiagnostics.binaryPath,
|
|
1039
1619
|
checkedCommands: localDiagnostics.checkedCommands,
|
|
1040
|
-
|
|
1620
|
+
message: buildAnthropicNoQuotaDiagnosticsMessage(credentials.detail),
|
|
1041
1621
|
};
|
|
1042
|
-
return diagnostics;
|
|
1043
|
-
})().then((value) => {
|
|
1044
|
-
diagnosticsCache.set(binaryPath, {
|
|
1045
|
-
timestamp: Date.now(),
|
|
1046
|
-
value,
|
|
1047
|
-
});
|
|
1048
|
-
return value;
|
|
1049
|
-
});
|
|
1050
|
-
diagnosticsCache.set(binaryPath, {
|
|
1051
|
-
timestamp: cached.timestamp,
|
|
1052
|
-
value: cached.value,
|
|
1053
|
-
inFlight,
|
|
1054
|
-
});
|
|
1055
|
-
try {
|
|
1056
|
-
return await inFlight;
|
|
1057
1622
|
}
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1623
|
+
const credentialFingerprint = fingerprintAccessToken(credentials.accessToken);
|
|
1624
|
+
const fallbackQuota = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version, options.pollIntervalMs);
|
|
1625
|
+
if (fallbackQuota.state !== "success") {
|
|
1626
|
+
return {
|
|
1627
|
+
installed: localDiagnostics.installed,
|
|
1628
|
+
version: localDiagnostics.version,
|
|
1629
|
+
authStatus: localDiagnostics.authStatus,
|
|
1630
|
+
quotaSupported: false,
|
|
1631
|
+
quotaSource: "none",
|
|
1632
|
+
oauthCredentialSource: credentials.source,
|
|
1633
|
+
binaryPath: localDiagnostics.binaryPath,
|
|
1634
|
+
checkedCommands: localDiagnostics.checkedCommands,
|
|
1635
|
+
message: buildAnthropicNoQuotaDiagnosticsMessage(fallbackQuota.detail),
|
|
1636
|
+
credentialFingerprint,
|
|
1637
|
+
attemptOutcome: fallbackQuota.attempt,
|
|
1638
|
+
...(fallbackQuota.failureCategory !== undefined
|
|
1639
|
+
? { failureCategory: fallbackQuota.failureCategory }
|
|
1640
|
+
: {}),
|
|
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
|
+
: {}),
|
|
1648
|
+
};
|
|
1066
1649
|
}
|
|
1650
|
+
return {
|
|
1651
|
+
installed: localDiagnostics.installed,
|
|
1652
|
+
version: localDiagnostics.version,
|
|
1653
|
+
authStatus: localDiagnostics.authStatus,
|
|
1654
|
+
quotaSupported: true,
|
|
1655
|
+
quotaSource: "claude-credentials-oauth-api",
|
|
1656
|
+
oauthCredentialSource: credentials.source,
|
|
1657
|
+
binaryPath: localDiagnostics.binaryPath,
|
|
1658
|
+
checkedCommands: localDiagnostics.checkedCommands,
|
|
1659
|
+
quota: fallbackQuota.quota,
|
|
1660
|
+
credentialFingerprint,
|
|
1661
|
+
attemptOutcome: fallbackQuota.attempt,
|
|
1662
|
+
quotaMeasuredAtMs: fallbackQuota.measuredAtMs,
|
|
1663
|
+
// The plan belongs to the CLI login only when this quota came from that login's own token.
|
|
1664
|
+
...(credentials.source === "claude-credentials" && localDiagnostics.planLabel !== undefined
|
|
1665
|
+
? { planLabel: localDiagnostics.planLabel }
|
|
1666
|
+
: {}),
|
|
1667
|
+
};
|
|
1067
1668
|
}
|
|
1068
|
-
export async function hasAnthropicCredentialsConfigured(options = {}) {
|
|
1669
|
+
export async function hasAnthropicCredentialsConfigured(options = {}, availability = {}) {
|
|
1069
1670
|
try {
|
|
1070
|
-
const
|
|
1071
|
-
|
|
1072
|
-
if (opencodeCredentials.state === "configured" || opencodeCredentials.state === "failed") {
|
|
1671
|
+
const diagnostics = await getAnthropicLocalDiagnostics(options);
|
|
1672
|
+
if (diagnostics.installed && diagnostics.authStatus === "authenticated")
|
|
1073
1673
|
return true;
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
try {
|
|
1080
|
-
const diagnostics = await getCachedAnthropicLocalDiagnostics(options);
|
|
1081
|
-
return diagnostics.installed && diagnostics.authStatus === "authenticated";
|
|
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");
|
|
1082
1679
|
}
|
|
1083
1680
|
catch {
|
|
1084
|
-
return
|
|
1681
|
+
return availability.treatUnverifiedAsConfigured === true;
|
|
1085
1682
|
}
|
|
1086
1683
|
}
|
|
1087
|
-
|
|
1684
|
+
/**
|
|
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.
|
|
1690
|
+
*/
|
|
1691
|
+
export async function resolveClaudeAgentAccountIdentity(params) {
|
|
1088
1692
|
let localDiagnostics;
|
|
1089
1693
|
try {
|
|
1090
|
-
localDiagnostics = await
|
|
1694
|
+
localDiagnostics = await getAnthropicLocalDiagnostics({
|
|
1695
|
+
binaryPath: params.binaryPath,
|
|
1696
|
+
operationCache: params.operationCache,
|
|
1697
|
+
});
|
|
1091
1698
|
}
|
|
1092
1699
|
catch {
|
|
1093
1700
|
return null;
|
|
1094
1701
|
}
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
if (localDiagnostics.localQuota)
|
|
1702
|
+
const identity = await claudeCliAccountIdentity(localDiagnostics, params.runtimeDetected);
|
|
1703
|
+
if (!identity)
|
|
1098
1704
|
return null;
|
|
1099
|
-
const
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
if (localDiagnostics.authStatus !== "authenticated") {
|
|
1107
|
-
return opencodeIdentity;
|
|
1108
|
-
}
|
|
1109
|
-
const claudeCredentials = await readClaudeOAuthAccessToken();
|
|
1110
|
-
const claudeIdentity = claudeCredentials.state === "configured"
|
|
1111
|
-
? await deriveResolvedAuthIdentity({
|
|
1112
|
-
providerId: "anthropic:claude-credentials",
|
|
1113
|
-
principal: { kind: "credential", value: claudeCredentials.accessToken },
|
|
1114
|
-
})
|
|
1115
|
-
: null;
|
|
1116
|
-
if (opencodeIdentity && claudeIdentity) {
|
|
1117
|
-
return composeResolvedAuthIdentities({
|
|
1118
|
-
providerId: "anthropic",
|
|
1119
|
-
identities: [opencodeIdentity, claudeIdentity],
|
|
1120
|
-
});
|
|
1121
|
-
}
|
|
1122
|
-
return opencodeIdentity ?? claudeIdentity;
|
|
1705
|
+
const composition = {
|
|
1706
|
+
providerId: "claude-agent",
|
|
1707
|
+
identities: [identity],
|
|
1708
|
+
qualifiers: [params.onlyCurrentModel ? "only-current-model" : "all-models"],
|
|
1709
|
+
};
|
|
1710
|
+
return ((await composeResolvedAuthIdentities(composition)) ??
|
|
1711
|
+
composeProcessLocalAuthIdentities(composition));
|
|
1123
1712
|
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1713
|
+
/**
|
|
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.
|
|
1719
|
+
*/
|
|
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;
|
|
1736
|
+
if (localDiagnostics.authStatus === "authenticated") {
|
|
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);
|
|
1741
|
+
if (credentials.state === "configured") {
|
|
1742
|
+
const protectedIdentity = await deriveResolvedAuthIdentity({
|
|
1743
|
+
providerId: "anthropic:claude-cli-account",
|
|
1744
|
+
principal: { kind: "credential", value: credentials.accessToken },
|
|
1745
|
+
qualifiers: accountQualifiers,
|
|
1746
|
+
});
|
|
1747
|
+
if (protectedIdentity) {
|
|
1748
|
+
if (credentials.storage === "file") {
|
|
1749
|
+
rememberClaudeIdentitySuccess(localDiagnostics.configDirectory, protectedIdentity, credentialSignature);
|
|
1750
|
+
}
|
|
1751
|
+
return protectedIdentity;
|
|
1752
|
+
}
|
|
1140
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);
|
|
1141
1759
|
return null;
|
|
1142
1760
|
}
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
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;
|
|
1774
|
+
}
|
|
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;
|
|
1148
1783
|
}
|
|
1784
|
+
if (localDiagnostics.localQuota && localDiagnostics.accountHint === undefined)
|
|
1785
|
+
return null;
|
|
1786
|
+
return await deriveResolvedAuthIdentity({
|
|
1787
|
+
providerId: "anthropic:claude-cli-state",
|
|
1788
|
+
principal: { kind: "stable-id", value: "claude-cli-state" },
|
|
1789
|
+
qualifiers: [
|
|
1790
|
+
localDiagnostics.installed ? "installed" : "missing",
|
|
1791
|
+
localDiagnostics.version ?? "",
|
|
1792
|
+
localDiagnostics.authStatus,
|
|
1793
|
+
localDiagnostics.effectiveBinary ?? "",
|
|
1794
|
+
claudeConfigDirectoryQualifier(localDiagnostics.configDirectory),
|
|
1795
|
+
localDiagnostics.claudeAiLoginVerified === true ? "verified" : "unverified",
|
|
1796
|
+
claudeCodeRuntimeDetected ? "detected" : "undetected",
|
|
1797
|
+
...(localDiagnostics.accountHint === undefined
|
|
1798
|
+
? []
|
|
1799
|
+
: [`account:${localDiagnostics.accountHint}`]),
|
|
1800
|
+
],
|
|
1801
|
+
});
|
|
1149
1802
|
}
|
|
1150
1803
|
export { parseOAuthUsageResponse, parseUsageResponse };
|
|
1151
1804
|
//# sourceMappingURL=anthropic.js.map
|