opencode-quota-gui 1.3.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -17
- package/dist/bin/opencode-quota-gui.js +0 -0
- package/dist/contracts/build-identity.js +1 -1
- package/dist/contracts/dashboard.d.ts +8 -1
- package/dist/contracts/dto-guards.js +2 -0
- package/dist/contracts/openai-quota.d.ts +3 -0
- package/dist/contracts/openai-quota.js +3 -0
- package/dist/data/modelsdev-temporal.min.json +57 -0
- package/dist/gui/config.d.ts +3 -3
- package/dist/gui/config.js +31 -2
- package/dist/gui/lifecycle.d.ts +5 -3
- package/dist/gui/lifecycle.js +3 -3
- package/dist/gui/primary-quota-windows.js +16 -14
- package/dist/gui/provider-cards.d.ts +10 -2
- package/dist/gui/provider-cards.js +51 -23
- package/dist/gui/quota-notification-detector.d.ts +4 -4
- package/dist/gui/quota-notification-detector.js +76 -42
- package/dist/gui/quota-notification-observer.d.ts +2 -3
- package/dist/gui/quota-notification-observer.js +68 -19
- package/dist/gui/rpc.d.ts +2 -0
- package/dist/gui/rpc.js +11 -3
- package/dist/gui/server.js +11 -2
- package/dist/gui/snapshot-service.d.ts +3 -1
- package/dist/gui/snapshot-service.js +126 -18
- package/dist/gui/sources.js +98 -56
- package/dist/gui-experimental.cjs +230 -225
- package/dist/lib/accounting-format.js +8 -0
- 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-auth.d.ts +2 -3
- package/dist/lib/anthropic-auth.js +2 -3
- package/dist/lib/anthropic.d.ts +48 -12
- package/dist/lib/anthropic.js +610 -275
- 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 +981 -0
- package/dist/lib/cache-observer.d.ts +138 -0
- package/dist/lib/cache-observer.js +317 -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.js +5 -3
- 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 +193 -2
- package/dist/lib/copilot.js +171 -86
- 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 +1 -0
- package/dist/lib/entries.d.ts +23 -0
- package/dist/lib/entries.js +2 -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/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/mimo.d.ts +2 -0
- package/dist/lib/mimo.js +36 -0
- 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-go.js +29 -2
- package/dist/lib/opencode-version-core.d.ts +23 -0
- package/dist/lib/opencode-version-core.js +49 -0
- package/dist/lib/opencode-version.d.ts +2 -22
- package/dist/lib/opencode-version.js +4 -48
- 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-registration.d.ts +19 -9
- package/dist/lib/provider-registration.js +17 -6
- package/dist/lib/quota-command-format.js +1 -1
- package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
- package/dist/lib/quota-exhaustion-projection.js +25 -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 +12 -35
- package/dist/lib/quota-render-data.d.ts +6 -0
- package/dist/lib/quota-render-data.js +43 -17
- package/dist/lib/quota-state-codec.js +17 -1
- package/dist/lib/quota-state.d.ts +7 -1
- package/dist/lib/quota-state.js +208 -34
- package/dist/lib/quota-stats.js +21 -0
- package/dist/lib/quota-status.js +3 -51
- package/dist/lib/scoped-update.d.ts +1 -1
- package/dist/lib/synthetic.js +65 -54
- package/dist/lib/types.d.ts +31 -1
- package/dist/lib/types.js +13 -0
- package/dist/lib/xai.js +48 -22
- package/dist/plugin.js +261 -13
- package/dist/provider-logos/NOTICE.md +1 -1
- package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
- package/dist/providers/alibaba-coding-plan.js +107 -104
- package/dist/providers/anthropic.d.ts +12 -3
- package/dist/providers/anthropic.js +71 -228
- package/dist/providers/cache-policies.d.ts +11 -4
- package/dist/providers/cache-policies.js +19 -13
- package/dist/providers/claude-agent.d.ts +19 -0
- package/dist/providers/claude-agent.js +196 -0
- package/dist/providers/copilot.js +2 -0
- package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
- 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/opencode-go.js +3 -0
- package/dist/providers/opencode-zen.js +2 -0
- 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 +2 -0
- package/dist/providers/result-helpers.js +2 -0
- package/dist/rpc.d.ts +121 -8
- package/dist/rpc.js +204 -12
- package/dist/ui/assets/{index-cDd9jUVY.css → index-BcueIm3Z.css} +1 -1
- package/dist/ui/assets/index-C6qRSoh8.js +10 -0
- package/dist/ui/assets/{popover-BGkgv9s0.js → popover-4bFSvRZ7.js} +1 -1
- package/dist/ui/assets/providers/claude-agent.svg +3 -0
- package/dist/ui/index.html +2 -2
- package/package.json +44 -45
- 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,62 @@
|
|
|
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
12
|
import { readFile } from "fs/promises";
|
|
14
13
|
import { homedir } from "os";
|
|
15
|
-
import { join } from "path";
|
|
16
|
-
import { resolveAnthropicOAuthCached } from "./anthropic-auth.js";
|
|
14
|
+
import { isAbsolute, join, resolve } from "path";
|
|
17
15
|
import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
|
|
18
16
|
import { fetchWithTimeout } from "./http.js";
|
|
17
|
+
import { buildFixedWindowEvidence } from "./quota-exhaustion-projection.js";
|
|
19
18
|
import { composeResolvedAuthIdentities, deriveResolvedAuthIdentity, } from "./resolved-auth-identity.js";
|
|
19
|
+
import { REQUEST_TIMEOUT_MS } from "./types.js";
|
|
20
20
|
const DEFAULT_CLAUDE_BINARY = "claude";
|
|
21
21
|
/** How `binaryPath` reads when the default `claude` ran from PATH. */
|
|
22
22
|
const CLAUDE_ON_PATH_DISPLAY = "claude (PATH)";
|
|
23
23
|
const CLAUDE_COMMAND_TIMEOUT_MS = 3_000;
|
|
24
|
-
const ANTHROPIC_DIAGNOSTICS_TTL_MS = 5_000;
|
|
25
24
|
const ANTHROPIC_OAUTH_BACKOFF_BASE_MS = 30_000;
|
|
26
25
|
const ANTHROPIC_OAUTH_COOLDOWN_MAX_MS = 15 * 60_000;
|
|
27
26
|
const ANTHROPIC_OAUTH_COOLDOWN_MAX_ENTRIES = 16;
|
|
27
|
+
const ANTHROPIC_OAUTH_REUSE_MS = 60_000;
|
|
28
28
|
const ANTHROPIC_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
29
|
+
const ANTHROPIC_USAGE_ENHANCED_URL = `${ANTHROPIC_USAGE_URL}?cedar_ember=1`;
|
|
29
30
|
const ANTHROPIC_BETA_HEADER = "oauth-2025-04-20";
|
|
30
31
|
const CLAUDE_CODE_CREDENTIALS_SERVICE = "Claude Code-credentials";
|
|
31
32
|
const CLAUDE_NO_LOCAL_QUOTA_MESSAGE = "Claude CLI auth detected, but local quota windows were not exposed.";
|
|
32
33
|
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
|
|
34
|
+
const CLAUDE_NON_SUBSCRIPTION_LOGIN_MESSAGE = "Claude CLI is not signed in with a claude.ai subscription. Run `claude auth login` and try again.";
|
|
35
|
+
const CLAUDE_CLI_TOKEN_UNVERIFIED_DETAIL = "Claude CLI did not confirm a first-party claude.ai login, so its stored token is not used.";
|
|
36
|
+
/** Environment variable the Claude CLI reads for its config directory. */
|
|
37
|
+
const CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR";
|
|
38
|
+
const CLAUDE_CONFIG_DIRECTORY_UNRESOLVED_DETAIL = "The Claude CLI config directory could not be determined, so its login is not used.";
|
|
39
|
+
/** Fixed labels for where a Claude login is kept. They name neither the home folder nor a custom path. */
|
|
40
|
+
const CLAUDE_DEFAULT_CREDENTIALS_LOCATION = "~/.claude/.credentials.json";
|
|
41
|
+
const CLAUDE_CUSTOM_CONFIG_DIRECTORY_LOCATION = "the Claude CLI config directory";
|
|
42
|
+
const ANTHROPIC_OAUTH_SHARED_STATE_KEY = Symbol.for("opencode-quota-gui.anthropic-oauth-shared-state.v1");
|
|
43
|
+
const anthropicOAuthGlobal = globalThis;
|
|
44
|
+
let anthropicOAuthSharedState = anthropicOAuthGlobal[ANTHROPIC_OAUTH_SHARED_STATE_KEY];
|
|
45
|
+
if (anthropicOAuthSharedState === undefined) {
|
|
46
|
+
anthropicOAuthSharedState = {
|
|
47
|
+
cooldowns: new Map(),
|
|
48
|
+
inFlight: new Map(),
|
|
49
|
+
recent: new Map(),
|
|
50
|
+
};
|
|
51
|
+
Object.defineProperty(anthropicOAuthGlobal, ANTHROPIC_OAUTH_SHARED_STATE_KEY, {
|
|
52
|
+
value: anthropicOAuthSharedState,
|
|
53
|
+
configurable: true,
|
|
54
|
+
writable: true,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
const anthropicOAuthCooldowns = anthropicOAuthSharedState.cooldowns;
|
|
58
|
+
const anthropicOAuthInFlight = anthropicOAuthSharedState.inFlight;
|
|
59
|
+
anthropicOAuthSharedState.forcedInFlight ??= new Map();
|
|
60
|
+
const anthropicOAuthForcedInFlight = anthropicOAuthSharedState.forcedInFlight;
|
|
61
|
+
const anthropicOAuthRecent = anthropicOAuthSharedState.recent;
|
|
62
|
+
const anthropicForcedResultsKey = Symbol("anthropic forced results");
|
|
37
63
|
export function resolveAnthropicBinaryPath(binaryPath) {
|
|
38
64
|
const trimmed = binaryPath?.trim();
|
|
39
65
|
return trimmed ? trimmed : DEFAULT_CLAUDE_BINARY;
|
|
@@ -60,9 +86,16 @@ function formatCommandDisplayArg(value) {
|
|
|
60
86
|
function formatCommandDisplay(parts) {
|
|
61
87
|
return parts.map(formatCommandDisplayArg).join(" ");
|
|
62
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* cmd.exe cannot escape `"` inside a quoted argument, and `%` and `!` expand even inside
|
|
91
|
+
* quotes, so a path containing any of these is refused rather than handed to the shell.
|
|
92
|
+
*/
|
|
93
|
+
const WINDOWS_CMD_UNSAFE_ARG = /[%!^&|<>"\r\n]/u;
|
|
63
94
|
function quoteWindowsCmdArg(value) {
|
|
64
|
-
|
|
65
|
-
|
|
95
|
+
if (WINDOWS_CMD_UNSAFE_ARG.test(value)) {
|
|
96
|
+
throw new Error("Claude CLI path contains characters that cannot be passed safely through cmd.exe.");
|
|
97
|
+
}
|
|
98
|
+
return `"${value}"`;
|
|
66
99
|
}
|
|
67
100
|
function shouldBridgeClaudeCommandThroughWindowsShell(binaryPath) {
|
|
68
101
|
const normalized = binaryPath.trim().toLowerCase();
|
|
@@ -76,10 +109,13 @@ export function buildClaudeCommandInvocation(binaryPath, args, runtime = {}) {
|
|
|
76
109
|
const display = formatCommandDisplay([resolvedBinaryPath, ...args]);
|
|
77
110
|
if ((runtime.platform ?? process.platform) === "win32" &&
|
|
78
111
|
shouldBridgeClaudeCommandThroughWindowsShell(resolvedBinaryPath)) {
|
|
112
|
+
// `/s` strips only the outermost quote pair, so the quoted command line is wrapped once more.
|
|
113
|
+
const commandLine = [resolvedBinaryPath, ...args].map(quoteWindowsCmdArg).join(" ");
|
|
79
114
|
return {
|
|
80
115
|
file: runtime.comspec?.trim() || process.env["ComSpec"]?.trim() || "cmd.exe",
|
|
81
|
-
args: ["/d", "/s", "/c",
|
|
116
|
+
args: ["/d", "/s", "/c", `"${commandLine}"`],
|
|
82
117
|
display,
|
|
118
|
+
windowsVerbatimArguments: true,
|
|
83
119
|
};
|
|
84
120
|
}
|
|
85
121
|
return {
|
|
@@ -161,8 +197,19 @@ function parseExtraUsageQuota(extraUsage) {
|
|
|
161
197
|
if (!record || record["is_enabled"] !== true) {
|
|
162
198
|
return undefined;
|
|
163
199
|
}
|
|
164
|
-
const
|
|
165
|
-
|
|
200
|
+
const utilization = record["utilization"];
|
|
201
|
+
const usedCredits = record["used_credits"];
|
|
202
|
+
const monthlyLimit = record["monthly_limit"];
|
|
203
|
+
const used = typeof utilization === "number" && Number.isFinite(utilization)
|
|
204
|
+
? utilization
|
|
205
|
+
: typeof usedCredits === "number" &&
|
|
206
|
+
Number.isFinite(usedCredits) &&
|
|
207
|
+
typeof monthlyLimit === "number" &&
|
|
208
|
+
Number.isFinite(monthlyLimit) &&
|
|
209
|
+
monthlyLimit > 0
|
|
210
|
+
? (usedCredits / monthlyLimit) * 100
|
|
211
|
+
: undefined;
|
|
212
|
+
if (used === undefined || used < 0 || used > 100) {
|
|
166
213
|
return undefined;
|
|
167
214
|
}
|
|
168
215
|
return { percentRemaining: Math.round(100 - used) };
|
|
@@ -217,46 +264,202 @@ function parseFableWeeklyWindow(limits) {
|
|
|
217
264
|
}
|
|
218
265
|
return undefined;
|
|
219
266
|
}
|
|
220
|
-
function
|
|
267
|
+
function readUsageWindow(root, snakeKey, camelKey) {
|
|
268
|
+
const hasSnakeKey = Object.hasOwn(root, snakeKey);
|
|
269
|
+
const hasCamelKey = Object.hasOwn(root, camelKey);
|
|
270
|
+
if (!hasSnakeKey && !hasCamelKey) {
|
|
271
|
+
return { state: "absent" };
|
|
272
|
+
}
|
|
273
|
+
if (hasSnakeKey && hasCamelKey && root[snakeKey] !== root[camelKey]) {
|
|
274
|
+
return { state: "malformed" };
|
|
275
|
+
}
|
|
276
|
+
const value = hasSnakeKey ? root[snakeKey] : root[camelKey];
|
|
277
|
+
if (value === null) {
|
|
278
|
+
return { state: "absent" };
|
|
279
|
+
}
|
|
280
|
+
const window = parseQuotaWindow(value);
|
|
281
|
+
return window ? { state: "present", window } : { state: "malformed" };
|
|
282
|
+
}
|
|
283
|
+
function findUsageWindows(data, options = {}) {
|
|
221
284
|
for (const root of getUsageRoots(data)) {
|
|
222
|
-
const fiveHour =
|
|
223
|
-
const sevenDay =
|
|
224
|
-
if (
|
|
285
|
+
const fiveHour = readUsageWindow(root, "five_hour", "fiveHour");
|
|
286
|
+
const sevenDay = readUsageWindow(root, "seven_day", "sevenDay");
|
|
287
|
+
if (fiveHour.state === "malformed" || sevenDay.state === "malformed") {
|
|
225
288
|
continue;
|
|
226
289
|
}
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
|
|
290
|
+
const fiveHourWindow = fiveHour.state === "present" ? fiveHour.window : undefined;
|
|
291
|
+
const sevenDayWindow = sevenDay.state === "present" ? sevenDay.window : undefined;
|
|
292
|
+
if (!fiveHourWindow && !sevenDayWindow) {
|
|
293
|
+
if (!options.allowSupplementalOnly) {
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
if (!parseExtraUsageQuota(root["extra_usage"]) && !parseFableWeeklyWindow(root["limits"])) {
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
230
300
|
return {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
...(extraUsage ? { extra_usage: extraUsage } : {}),
|
|
301
|
+
root,
|
|
302
|
+
...(fiveHourWindow ? { fiveHour: fiveHourWindow } : {}),
|
|
303
|
+
...(sevenDayWindow ? { sevenDay: sevenDayWindow } : {}),
|
|
235
304
|
};
|
|
236
305
|
}
|
|
237
306
|
return null;
|
|
238
307
|
}
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
308
|
+
/** Anthropic's 5-hour session window and its weekly windows (including the Fable weekly scope). */
|
|
309
|
+
const FIVE_HOUR_WINDOW_MS = 5 * 60 * 60_000;
|
|
310
|
+
const SEVEN_DAY_WINDOW_MS = 7 * 24 * 60 * 60_000;
|
|
311
|
+
/**
|
|
312
|
+
* Attaches fixed-window evidence derived from the window length and its reset. The 5h and weekly
|
|
313
|
+
* windows are assumed to reset on a fixed cycle; that is not verified against the provider. A
|
|
314
|
+
* window without a valid reset, or observed outside its inferred span, gets no evidence.
|
|
315
|
+
*/
|
|
316
|
+
function windowWithFixedEvidence(window, durationMs, observedAtMs) {
|
|
317
|
+
const fixedWindow = buildFixedWindowEvidence({
|
|
318
|
+
durationMs,
|
|
319
|
+
resetTimeIso: window.resetTimeIso,
|
|
320
|
+
observedAtMs,
|
|
321
|
+
});
|
|
322
|
+
return fixedWindow ? { ...window, fixedWindow } : window;
|
|
323
|
+
}
|
|
324
|
+
function parseUsageResponse(data, options = {}) {
|
|
325
|
+
const windows = findUsageWindows(data);
|
|
326
|
+
if (!windows?.fiveHour || !windows.sevenDay)
|
|
327
|
+
return null;
|
|
328
|
+
const extraUsage = options.includeExtraUsage
|
|
329
|
+
? parseExtraUsageQuota(windows.root["extra_usage"])
|
|
330
|
+
: undefined;
|
|
331
|
+
const observedAtMs = options.observedAtMs ?? Date.now();
|
|
332
|
+
return {
|
|
333
|
+
success: true,
|
|
334
|
+
five_hour: windowWithFixedEvidence(windows.fiveHour, FIVE_HOUR_WINDOW_MS, observedAtMs),
|
|
335
|
+
seven_day: windowWithFixedEvidence(windows.sevenDay, SEVEN_DAY_WINDOW_MS, observedAtMs),
|
|
336
|
+
...(extraUsage ? { extra_usage: extraUsage } : {}),
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
/** Display cap for saved reset segments and the displayed count; larger valid inventories are truncated, not hidden. */
|
|
340
|
+
const MAX_SAVED_RESET_SEGMENTS = 100;
|
|
341
|
+
/** An optional ISO date: absent/null is open (`undefined`), a bad string is invalid (`NaN`). */
|
|
342
|
+
function savedResetDateMs(value) {
|
|
343
|
+
if (value === undefined || value === null)
|
|
344
|
+
return undefined;
|
|
345
|
+
return typeof value === "string" ? Date.parse(value) : Number.NaN;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Independent of the quota windows: any malformed part only drops that grant (or the inventory).
|
|
349
|
+
* Identifiers, labels and every other field are discarded; unknown expiry stays absent.
|
|
350
|
+
*/
|
|
351
|
+
function parseSavedResets(raw, nowMs) {
|
|
352
|
+
const root = asRecord(raw);
|
|
353
|
+
if (root?.["eligible"] !== true || !Array.isArray(root["grants"]))
|
|
354
|
+
return undefined;
|
|
355
|
+
const grants = [];
|
|
356
|
+
for (const entry of root["grants"]) {
|
|
357
|
+
const grant = asRecord(entry);
|
|
358
|
+
if (!grant || grant["paused"] !== false)
|
|
359
|
+
continue;
|
|
360
|
+
const left = grant["resets_left"];
|
|
361
|
+
if (typeof left !== "number" || !Number.isSafeInteger(left) || left <= 0)
|
|
362
|
+
continue;
|
|
363
|
+
const startMs = savedResetDateMs(grant["starts_at"]);
|
|
364
|
+
const endMs = savedResetDateMs(grant["ends_at"]);
|
|
365
|
+
if (Number.isNaN(startMs) || Number.isNaN(endMs))
|
|
366
|
+
continue;
|
|
367
|
+
if (startMs !== undefined && startMs > nowMs)
|
|
368
|
+
continue;
|
|
369
|
+
if (endMs !== undefined && endMs <= nowMs)
|
|
370
|
+
continue;
|
|
371
|
+
const total = grant["resets_total"];
|
|
372
|
+
if (total !== undefined &&
|
|
373
|
+
(typeof total !== "number" || !Number.isSafeInteger(total) || total < left)) {
|
|
244
374
|
continue;
|
|
245
375
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
376
|
+
// Counts are clamped per grant so huge safe integers never grow the sum or the allocation.
|
|
377
|
+
grants.push({ count: Math.min(left, MAX_SAVED_RESET_SEGMENTS), endMs });
|
|
378
|
+
}
|
|
379
|
+
// Earliest known expiry first, unknown last; stable for equal expiries.
|
|
380
|
+
grants.sort((a, b) => (a.endMs ?? Infinity) - (b.endMs ?? Infinity) || 0);
|
|
381
|
+
const credits = [];
|
|
382
|
+
for (const grant of grants) {
|
|
383
|
+
const expiry = grant.endMs === undefined ? {} : { expiresAtIso: new Date(grant.endMs).toISOString() };
|
|
384
|
+
for (let n = grant.count; n > 0 && credits.length < MAX_SAVED_RESET_SEGMENTS; n -= 1) {
|
|
385
|
+
credits.push({ ...expiry });
|
|
386
|
+
}
|
|
255
387
|
}
|
|
256
|
-
return
|
|
388
|
+
return credits.length > 0 ? { availableCount: credits.length, credits } : undefined;
|
|
257
389
|
}
|
|
258
|
-
function
|
|
259
|
-
|
|
390
|
+
function parseOAuthUsageResponse(data, observedAtMs = Date.now()) {
|
|
391
|
+
const windows = findUsageWindows(data, { allowSupplementalOnly: true });
|
|
392
|
+
if (!windows)
|
|
393
|
+
return null;
|
|
394
|
+
const extraUsage = parseExtraUsageQuota(windows.root["extra_usage"]);
|
|
395
|
+
const fableWeekly = parseFableWeeklyWindow(windows.root["limits"]);
|
|
396
|
+
const savedResets = parseSavedResets(windows.root["cedar_ember"], observedAtMs);
|
|
397
|
+
return {
|
|
398
|
+
...(savedResets ? { saved_resets: savedResets } : {}),
|
|
399
|
+
success: true,
|
|
400
|
+
...(windows.fiveHour
|
|
401
|
+
? {
|
|
402
|
+
five_hour: windowWithFixedEvidence(windows.fiveHour, FIVE_HOUR_WINDOW_MS, observedAtMs),
|
|
403
|
+
}
|
|
404
|
+
: {}),
|
|
405
|
+
...(windows.sevenDay
|
|
406
|
+
? {
|
|
407
|
+
seven_day: windowWithFixedEvidence(windows.sevenDay, SEVEN_DAY_WINDOW_MS, observedAtMs),
|
|
408
|
+
}
|
|
409
|
+
: {}),
|
|
410
|
+
...(extraUsage ? { extra_usage: extraUsage } : {}),
|
|
411
|
+
...(fableWeekly ? { fable_weekly: fableWeekly } : {}),
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Parses one candidate config directory. `undefined` means the value is absent, which is not an
|
|
416
|
+
* error. `null` means it is present but cannot name a directory (not a string, empty, padded with
|
|
417
|
+
* whitespace, or relative), so the caller must fail closed rather than read another login.
|
|
418
|
+
*/
|
|
419
|
+
export function parseClaudeConfigDirectoryCandidate(value) {
|
|
420
|
+
if (value === undefined)
|
|
421
|
+
return undefined;
|
|
422
|
+
if (typeof value !== "string")
|
|
423
|
+
return null;
|
|
424
|
+
if (!value || value.trim() !== value || !isAbsolute(value))
|
|
425
|
+
return null;
|
|
426
|
+
return resolve(value);
|
|
427
|
+
}
|
|
428
|
+
function isSameConfigDirectory(left, right) {
|
|
429
|
+
return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* The directory the Claude CLI reads its login from. A directory the CLI reports is authoritative;
|
|
433
|
+
* otherwise CLAUDE_CONFIG_DIR names it, and with neither set it is the default `~/.claude`. An
|
|
434
|
+
* invalid value, or a reported directory that disagrees with CLAUDE_CONFIG_DIR, is unresolved, so
|
|
435
|
+
* no login is read in its place.
|
|
436
|
+
*/
|
|
437
|
+
function resolveClaudeConfigDirectory(reported, environment) {
|
|
438
|
+
const fromReport = parseClaudeConfigDirectoryCandidate(reported);
|
|
439
|
+
const fromEnvironment = parseClaudeConfigDirectoryCandidate(environment);
|
|
440
|
+
if (fromReport === null || fromEnvironment === null)
|
|
441
|
+
return { state: "unresolved" };
|
|
442
|
+
if (fromReport && fromEnvironment && !isSameConfigDirectory(fromReport, fromEnvironment)) {
|
|
443
|
+
return { state: "unresolved" };
|
|
444
|
+
}
|
|
445
|
+
const defaultDirectory = resolve(join(homedir(), ".claude"));
|
|
446
|
+
const path = fromReport ?? fromEnvironment ?? defaultDirectory;
|
|
447
|
+
return {
|
|
448
|
+
state: "resolved",
|
|
449
|
+
path,
|
|
450
|
+
// An explicit config directory may use a different macOS Keychain service,
|
|
451
|
+
// even when it names the default path; never guess that service's identity.
|
|
452
|
+
isDefault: fromEnvironment === undefined && isSameConfigDirectory(path, defaultDirectory),
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
/** The identity qualifier for a config directory: its resolved path, or a fixed word when none is bound. */
|
|
456
|
+
function claudeConfigDirectoryQualifier(configDirectory) {
|
|
457
|
+
return configDirectory?.state === "resolved" ? configDirectory.path : "unresolved";
|
|
458
|
+
}
|
|
459
|
+
function claudeCredentialsLocation(directory) {
|
|
460
|
+
return directory.isDefault
|
|
461
|
+
? CLAUDE_DEFAULT_CREDENTIALS_LOCATION
|
|
462
|
+
: CLAUDE_CUSTOM_CONFIG_DIRECTORY_LOCATION;
|
|
260
463
|
}
|
|
261
464
|
function getClaudeKeychainLocation() {
|
|
262
465
|
return `macOS Keychain service ${sanitizeDisplayText(CLAUDE_CODE_CREDENTIALS_SERVICE)}`;
|
|
@@ -308,10 +511,9 @@ function parseClaudeCredentialsAccessToken(content, options) {
|
|
|
308
511
|
const accessToken = extractClaudeCredentialsAccessToken(parsed);
|
|
309
512
|
return accessToken ? { accessToken } : { error: "missing" };
|
|
310
513
|
}
|
|
311
|
-
catch
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
};
|
|
514
|
+
catch {
|
|
515
|
+
// The parser's own message can quote a fragment of the token, so only a fixed reason is kept.
|
|
516
|
+
return { error: "invalid JSON" };
|
|
315
517
|
}
|
|
316
518
|
}
|
|
317
519
|
async function runCredentialCommand(file, args) {
|
|
@@ -321,6 +523,7 @@ async function runCredentialCommand(file, args) {
|
|
|
321
523
|
encoding: "utf8",
|
|
322
524
|
timeout: CLAUDE_COMMAND_TIMEOUT_MS,
|
|
323
525
|
maxBuffer: 1024 * 1024,
|
|
526
|
+
windowsHide: true,
|
|
324
527
|
}, (error, stdout, stderr) => {
|
|
325
528
|
const stdoutText = typeof stdout === "string" ? stdout : stdout.toString("utf8");
|
|
326
529
|
const stderrText = typeof stderr === "string" ? stderr : stderr.toString("utf8");
|
|
@@ -380,18 +583,18 @@ async function readClaudeCredentialsAccessTokenFromMacOSKeychain() {
|
|
|
380
583
|
: `Claude OAuth access token missing in ${location}.`,
|
|
381
584
|
};
|
|
382
585
|
}
|
|
383
|
-
async function readClaudeCredentialsAccessTokenFromFile() {
|
|
384
|
-
const
|
|
586
|
+
async function readClaudeCredentialsAccessTokenFromFile(directory) {
|
|
587
|
+
const location = claudeCredentialsLocation(directory);
|
|
385
588
|
try {
|
|
386
|
-
const content = await readFile(
|
|
589
|
+
const content = await readFile(join(directory.path, ".credentials.json"), "utf8");
|
|
387
590
|
const parsed = parseClaudeCredentialsAccessToken(content, { allowPlainText: false });
|
|
388
591
|
const accessToken = parsed.accessToken?.trim() ?? "";
|
|
389
592
|
if (!accessToken) {
|
|
390
593
|
return {
|
|
391
594
|
state: "unavailable",
|
|
392
595
|
detail: parsed.error && parsed.error !== "missing"
|
|
393
|
-
? `Could not parse Claude credentials
|
|
394
|
-
: `Claude OAuth access token missing in ${
|
|
596
|
+
? `Could not parse Claude credentials in ${location}: ${parsed.error}.`
|
|
597
|
+
: `Claude OAuth access token missing in ${location}.`,
|
|
395
598
|
};
|
|
396
599
|
}
|
|
397
600
|
return {
|
|
@@ -406,19 +609,27 @@ async function readClaudeCredentialsAccessTokenFromFile() {
|
|
|
406
609
|
if (code === "ENOENT") {
|
|
407
610
|
return {
|
|
408
611
|
state: "not-found",
|
|
409
|
-
location
|
|
612
|
+
location,
|
|
410
613
|
};
|
|
411
614
|
}
|
|
615
|
+
// Only a system error code is shown: a file system message can name the path it failed on.
|
|
616
|
+
const shownCode = typeof code === "string" && /^E[A-Z0-9]+$/u.test(code) ? code : "unknown";
|
|
412
617
|
return {
|
|
413
618
|
state: "unavailable",
|
|
414
|
-
detail: `Could not read Claude credentials
|
|
619
|
+
detail: `Could not read Claude credentials in ${location}: ${shownCode} error.`,
|
|
415
620
|
};
|
|
416
621
|
}
|
|
417
622
|
}
|
|
418
|
-
async function readClaudeOAuthAccessToken() {
|
|
623
|
+
async function readClaudeOAuthAccessToken(configDirectory) {
|
|
624
|
+
if (configDirectory.state !== "resolved") {
|
|
625
|
+
return { state: "unavailable", detail: CLAUDE_CONFIG_DIRECTORY_UNRESOLVED_DETAIL };
|
|
626
|
+
}
|
|
419
627
|
const locationsChecked = [];
|
|
420
628
|
const unavailableDetails = [];
|
|
421
|
-
|
|
629
|
+
// Only the default directory has a macOS Keychain entry, so a custom directory never reads it.
|
|
630
|
+
const keychainCredentials = configDirectory.isDefault
|
|
631
|
+
? await readClaudeCredentialsAccessTokenFromMacOSKeychain()
|
|
632
|
+
: null;
|
|
422
633
|
if (keychainCredentials?.state === "configured") {
|
|
423
634
|
return { ...keychainCredentials, source: "claude-credentials" };
|
|
424
635
|
}
|
|
@@ -428,7 +639,7 @@ async function readClaudeOAuthAccessToken() {
|
|
|
428
639
|
if (keychainCredentials?.state === "not-found") {
|
|
429
640
|
locationsChecked.push(keychainCredentials.location);
|
|
430
641
|
}
|
|
431
|
-
const fileCredentials = await readClaudeCredentialsAccessTokenFromFile();
|
|
642
|
+
const fileCredentials = await readClaudeCredentialsAccessTokenFromFile(configDirectory);
|
|
432
643
|
if (fileCredentials.state === "configured") {
|
|
433
644
|
return { ...fileCredentials, source: "claude-credentials" };
|
|
434
645
|
}
|
|
@@ -443,20 +654,17 @@ async function readClaudeOAuthAccessToken() {
|
|
|
443
654
|
detail: unavailableDetails[0] ?? getClaudeCredentialsNotFoundDetail(locationsChecked),
|
|
444
655
|
};
|
|
445
656
|
}
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
};
|
|
657
|
+
/**
|
|
658
|
+
* The Claude CLI's stored subscription token. It is read only when the CLI positively reports a
|
|
659
|
+
* first-party claude.ai login, because an absent or non-JSON status cannot prove whose token it is.
|
|
660
|
+
*/
|
|
661
|
+
async function readClaudeCliSubscriptionToken(localDiagnostics) {
|
|
662
|
+
if (localDiagnostics.claudeAiLoginVerified !== true) {
|
|
663
|
+
return { state: "unavailable", detail: CLAUDE_CLI_TOKEN_UNVERIFIED_DETAIL };
|
|
454
664
|
}
|
|
455
|
-
return
|
|
456
|
-
? await readClaudeOAuthAccessToken()
|
|
457
|
-
: { state: "unavailable" };
|
|
665
|
+
return await readClaudeOAuthAccessToken(localDiagnostics.configDirectory ?? { state: "unresolved" });
|
|
458
666
|
}
|
|
459
|
-
function fingerprintAccessToken(accessToken) {
|
|
667
|
+
export function fingerprintAccessToken(accessToken) {
|
|
460
668
|
return createHash("sha256").update(accessToken).digest("hex");
|
|
461
669
|
}
|
|
462
670
|
function parseRetryAfterMs(value, nowMs) {
|
|
@@ -493,6 +701,15 @@ function retainAnthropicOAuthCooldownForToken(tokenFingerprint) {
|
|
|
493
701
|
anthropicOAuthCooldowns.delete(fingerprint);
|
|
494
702
|
}
|
|
495
703
|
}
|
|
704
|
+
function rememberAnthropicOAuthQuota(tokenFingerprint, quota) {
|
|
705
|
+
const nowMs = Date.now();
|
|
706
|
+
for (const [fingerprint, entry] of anthropicOAuthRecent) {
|
|
707
|
+
if (nowMs - entry.checkedAtMs >= ANTHROPIC_OAUTH_REUSE_MS) {
|
|
708
|
+
anthropicOAuthRecent.delete(fingerprint);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
anthropicOAuthRecent.set(tokenFingerprint, { quota, checkedAtMs: nowMs });
|
|
712
|
+
}
|
|
496
713
|
function redactAccessTokenFromSanitizedDetail(detail, accessToken) {
|
|
497
714
|
const sanitizedDetail = sanitizeDisplayText(detail);
|
|
498
715
|
const sanitizedAccessToken = sanitizeDisplayText(accessToken);
|
|
@@ -507,24 +724,54 @@ function sanitizeAnthropicApiDetail(detail, accessToken) {
|
|
|
507
724
|
function sanitizeAnthropicRequestError(detail, accessToken) {
|
|
508
725
|
return redactAccessTokenFromSanitizedDetail(detail, accessToken);
|
|
509
726
|
}
|
|
510
|
-
|
|
727
|
+
/** The usage endpoint rejects unrecognized clients, so identify as the Claude CLI that owns the login. */
|
|
728
|
+
function claudeCodeUserAgent(cliVersion, enhanced) {
|
|
729
|
+
const version = (cliVersion ?? "").replace(/[^0-9A-Za-z.+-]/gu, "").slice(0, 48);
|
|
730
|
+
if (enhanced)
|
|
731
|
+
return version ? `claude-cli/${version} (external, cli)` : "claude-cli (external, cli)";
|
|
732
|
+
// The plain fallback keeps the identity the usage probe has always sent.
|
|
733
|
+
return version ? `claude-code/${version}` : "claude-code";
|
|
734
|
+
}
|
|
735
|
+
const RETRY_WITHOUT_ENHANCED = Symbol("retry usage request without cedar_ember");
|
|
736
|
+
/** Enhanced request, then one plain retry only when the enhanced form itself was rejected. */
|
|
737
|
+
async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion) {
|
|
738
|
+
const startedAtMs = Date.now();
|
|
739
|
+
const timeoutMs = requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
740
|
+
const enhanced = await requestAnthropicOAuthUsage(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, true);
|
|
741
|
+
if (enhanced !== RETRY_WITHOUT_ENHANCED)
|
|
742
|
+
return enhanced;
|
|
743
|
+
// The fallback shares the caller's one timeout budget rather than doubling it.
|
|
744
|
+
const remainingMs = timeoutMs - (Date.now() - startedAtMs);
|
|
745
|
+
if (remainingMs <= 0) {
|
|
746
|
+
return {
|
|
747
|
+
state: "unavailable",
|
|
748
|
+
detail: "Anthropic OAuth usage request timed out",
|
|
749
|
+
failureCategory: "provider_api",
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
// The plain request never yields the retry sentinel.
|
|
753
|
+
return (await requestAnthropicOAuthUsage(accessToken, tokenFingerprint, remainingMs, cliVersion, false));
|
|
754
|
+
}
|
|
755
|
+
async function requestAnthropicOAuthUsage(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion, enhanced) {
|
|
511
756
|
try {
|
|
512
|
-
return await fetchWithTimeout(ANTHROPIC_USAGE_URL, {
|
|
757
|
+
return await fetchWithTimeout(enhanced ? ANTHROPIC_USAGE_ENHANCED_URL : ANTHROPIC_USAGE_URL, {
|
|
513
758
|
request: {
|
|
514
759
|
headers: {
|
|
515
760
|
Authorization: `Bearer ${accessToken}`,
|
|
516
761
|
"anthropic-beta": ANTHROPIC_BETA_HEADER,
|
|
762
|
+
"User-Agent": claudeCodeUserAgent(cliVersion, enhanced),
|
|
517
763
|
},
|
|
518
764
|
},
|
|
519
765
|
timeoutMs: requestTimeoutMs,
|
|
520
766
|
consume: async (response, timeoutSignal) => {
|
|
521
767
|
if (response.status === 429) {
|
|
768
|
+
anthropicOAuthRecent.delete(tokenFingerprint);
|
|
522
769
|
const nowMs = Date.now();
|
|
523
770
|
const previousFailureCount = anthropicOAuthCooldowns.get(tokenFingerprint)?.failureCount ?? 0;
|
|
524
771
|
const durationMs = getAnthropicOAuthCooldownDurationMs(previousFailureCount, response.headers?.get?.("Retry-After") ?? null, nowMs);
|
|
525
772
|
anthropicOAuthCooldowns.set(tokenFingerprint, {
|
|
526
773
|
failureCount: previousFailureCount + 1,
|
|
527
|
-
blockedUntilMs: nowMs + durationMs,
|
|
774
|
+
blockedUntilMs: Math.ceil(nowMs + durationMs),
|
|
528
775
|
});
|
|
529
776
|
let detail = "";
|
|
530
777
|
try {
|
|
@@ -542,6 +789,7 @@ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint,
|
|
|
542
789
|
state: "unavailable",
|
|
543
790
|
detail: `${errorDetail} ${getAnthropicOAuthCooldownMessage(durationMs)}`,
|
|
544
791
|
failureCategory: "provider_api",
|
|
792
|
+
retryAtMs: Math.ceil(nowMs + durationMs),
|
|
545
793
|
};
|
|
546
794
|
}
|
|
547
795
|
anthropicOAuthCooldowns.delete(tokenFingerprint);
|
|
@@ -549,7 +797,14 @@ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint,
|
|
|
549
797
|
const authenticationFailure = response.status === 401 || response.status === 403;
|
|
550
798
|
let detail = "";
|
|
551
799
|
try {
|
|
552
|
-
|
|
800
|
+
const body = await response.text();
|
|
801
|
+
// A 403 naming a missing scope or user:profile is a real credential problem, never an enhanced-form rejection.
|
|
802
|
+
if (enhanced &&
|
|
803
|
+
(response.status === 400 ||
|
|
804
|
+
(response.status === 403 && !/scope|user:profile/iu.test(body)))) {
|
|
805
|
+
return RETRY_WITHOUT_ENHANCED;
|
|
806
|
+
}
|
|
807
|
+
detail = sanitizeAnthropicApiDetail(body, accessToken);
|
|
553
808
|
}
|
|
554
809
|
catch (error) {
|
|
555
810
|
if (timeoutSignal.aborted && !authenticationFailure)
|
|
@@ -601,7 +856,7 @@ async function performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint,
|
|
|
601
856
|
};
|
|
602
857
|
}
|
|
603
858
|
}
|
|
604
|
-
async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs) {
|
|
859
|
+
async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs, forcedOperationCache, cliVersion) {
|
|
605
860
|
const tokenFingerprint = fingerprintAccessToken(accessToken);
|
|
606
861
|
retainAnthropicOAuthCooldownForToken(tokenFingerprint);
|
|
607
862
|
const nowMs = Date.now();
|
|
@@ -610,25 +865,82 @@ async function queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeo
|
|
|
610
865
|
return {
|
|
611
866
|
state: "unavailable",
|
|
612
867
|
detail: getAnthropicOAuthCooldownMessage(cooldown.blockedUntilMs - nowMs),
|
|
868
|
+
failureCategory: "provider_api",
|
|
869
|
+
retryAtMs: cooldown.blockedUntilMs,
|
|
613
870
|
};
|
|
614
871
|
}
|
|
615
|
-
const
|
|
616
|
-
if (
|
|
617
|
-
|
|
872
|
+
const recent = forcedOperationCache ? undefined : anthropicOAuthRecent.get(tokenFingerprint);
|
|
873
|
+
if (recent &&
|
|
874
|
+
nowMs >= recent.checkedAtMs &&
|
|
875
|
+
nowMs - recent.checkedAtMs < ANTHROPIC_OAUTH_REUSE_MS) {
|
|
876
|
+
return { state: "success", quota: recent.quota };
|
|
877
|
+
}
|
|
878
|
+
let forcedResults;
|
|
879
|
+
if (forcedOperationCache) {
|
|
880
|
+
forcedResults = forcedOperationCache.get(anthropicForcedResultsKey);
|
|
881
|
+
if (!forcedResults) {
|
|
882
|
+
forcedResults = new Map();
|
|
883
|
+
forcedOperationCache.set(anthropicForcedResultsKey, forcedResults);
|
|
884
|
+
}
|
|
885
|
+
const existing = forcedResults.get(tokenFingerprint);
|
|
886
|
+
if (existing)
|
|
887
|
+
return await existing;
|
|
888
|
+
}
|
|
889
|
+
if (forcedResults) {
|
|
890
|
+
const existingForced = anthropicOAuthForcedInFlight.get(tokenFingerprint);
|
|
891
|
+
if (existingForced) {
|
|
892
|
+
forcedResults.set(tokenFingerprint, existingForced);
|
|
893
|
+
return await existingForced;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
else {
|
|
897
|
+
const existing = anthropicOAuthInFlight.get(tokenFingerprint);
|
|
898
|
+
if (existing)
|
|
899
|
+
return await existing;
|
|
618
900
|
}
|
|
619
|
-
const
|
|
901
|
+
const prior = forcedResults ? anthropicOAuthInFlight.get(tokenFingerprint) : undefined;
|
|
902
|
+
const inFlight = (async () => {
|
|
903
|
+
if (prior)
|
|
904
|
+
await prior;
|
|
905
|
+
const activeCooldown = anthropicOAuthCooldowns.get(tokenFingerprint);
|
|
906
|
+
const remaining = (activeCooldown?.blockedUntilMs ?? 0) - Date.now();
|
|
907
|
+
if (remaining > 0)
|
|
908
|
+
return {
|
|
909
|
+
state: "unavailable",
|
|
910
|
+
detail: getAnthropicOAuthCooldownMessage(remaining),
|
|
911
|
+
failureCategory: "provider_api",
|
|
912
|
+
retryAtMs: activeCooldown?.blockedUntilMs,
|
|
913
|
+
};
|
|
914
|
+
const result = await performAnthropicOAuthUsageRequest(accessToken, tokenFingerprint, requestTimeoutMs, cliVersion);
|
|
915
|
+
if (result.state === "success") {
|
|
916
|
+
rememberAnthropicOAuthQuota(tokenFingerprint, result.quota);
|
|
917
|
+
}
|
|
918
|
+
else {
|
|
919
|
+
const cached = anthropicOAuthRecent.get(tokenFingerprint);
|
|
920
|
+
if (cached?.quota.saved_resets) {
|
|
921
|
+
const { saved_resets: _savedResets, ...quota } = cached.quota;
|
|
922
|
+
anthropicOAuthRecent.set(tokenFingerprint, { ...cached, quota });
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
return result;
|
|
926
|
+
})();
|
|
620
927
|
anthropicOAuthInFlight.set(tokenFingerprint, inFlight);
|
|
928
|
+
if (forcedResults) {
|
|
929
|
+
forcedResults.set(tokenFingerprint, inFlight);
|
|
930
|
+
anthropicOAuthForcedInFlight.set(tokenFingerprint, inFlight);
|
|
931
|
+
}
|
|
621
932
|
try {
|
|
622
933
|
return await inFlight;
|
|
623
934
|
}
|
|
624
935
|
finally {
|
|
625
|
-
if (anthropicOAuthInFlight.get(tokenFingerprint) === inFlight)
|
|
936
|
+
if (anthropicOAuthInFlight.get(tokenFingerprint) === inFlight)
|
|
626
937
|
anthropicOAuthInFlight.delete(tokenFingerprint);
|
|
627
|
-
|
|
938
|
+
if (anthropicOAuthForcedInFlight.get(tokenFingerprint) === inFlight)
|
|
939
|
+
anthropicOAuthForcedInFlight.delete(tokenFingerprint);
|
|
628
940
|
}
|
|
629
941
|
}
|
|
630
|
-
export async function queryAnthropicQuotaWithOAuth(accessToken, requestTimeoutMs) {
|
|
631
|
-
const result = await queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs);
|
|
942
|
+
export async function queryAnthropicQuotaWithOAuth(accessToken, requestTimeoutMs, forcedOperationCache) {
|
|
943
|
+
const result = await queryAnthropicQuotaFromOAuthAccessToken(accessToken, requestTimeoutMs, forcedOperationCache);
|
|
632
944
|
return result.state === "success"
|
|
633
945
|
? result.quota
|
|
634
946
|
: {
|
|
@@ -673,6 +985,62 @@ function extractAuthBoolean(data) {
|
|
|
673
985
|
}
|
|
674
986
|
return undefined;
|
|
675
987
|
}
|
|
988
|
+
/**
|
|
989
|
+
* `auth status --json` reports how the login was made. Only a claude.ai subscription login on
|
|
990
|
+
* Anthropic's first-party API is the Claude Code account; any other reported method or provider is
|
|
991
|
+
* stale or unrelated. A field that is absent is not evidence either way.
|
|
992
|
+
*/
|
|
993
|
+
/**
|
|
994
|
+
* Positive evidence that the Claude CLI login is a first-party claude.ai subscription. Both fields
|
|
995
|
+
* must be reported; an absent field proves nothing, so a login without them cannot prove its identity.
|
|
996
|
+
*/
|
|
997
|
+
function hasFirstPartyClaudeAiLogin(payload) {
|
|
998
|
+
const record = asRecord(payload);
|
|
999
|
+
if (!record)
|
|
1000
|
+
return false;
|
|
1001
|
+
const method = record["authMethod"];
|
|
1002
|
+
const provider = record["apiProvider"];
|
|
1003
|
+
return (typeof method === "string" &&
|
|
1004
|
+
method.trim().toLowerCase() === "claude.ai" &&
|
|
1005
|
+
typeof provider === "string" &&
|
|
1006
|
+
provider.trim().toLowerCase() === "firstparty");
|
|
1007
|
+
}
|
|
1008
|
+
/** The only plan names shown. The CLI's `subscriptionType` is undocumented, so anything else is omitted. */
|
|
1009
|
+
const CLAUDE_PLAN_LABELS = new Map([
|
|
1010
|
+
["free", "Free"],
|
|
1011
|
+
["pro", "Pro"],
|
|
1012
|
+
["max", "Max"],
|
|
1013
|
+
["team", "Team"],
|
|
1014
|
+
["enterprise", "Enterprise"],
|
|
1015
|
+
["ultra", "Ultra"],
|
|
1016
|
+
]);
|
|
1017
|
+
/**
|
|
1018
|
+
* Display-only plan name from a verified login's `subscriptionType`; absent, null, or unknown gives none.
|
|
1019
|
+
* Bare name (e.g. "Max"): the card already names the provider, so the header reads `Anthropic · Max`,
|
|
1020
|
+
* the same shape as OpenAI's account header (`OpenAI · Pro`).
|
|
1021
|
+
*/
|
|
1022
|
+
function deriveClaudePlanLabel(payload) {
|
|
1023
|
+
const subscriptionType = asRecord(payload)?.["subscriptionType"];
|
|
1024
|
+
if (typeof subscriptionType !== "string")
|
|
1025
|
+
return undefined;
|
|
1026
|
+
return CLAUDE_PLAN_LABELS.get(subscriptionType.trim().toLowerCase());
|
|
1027
|
+
}
|
|
1028
|
+
function hasNonSubscriptionLogin(payload) {
|
|
1029
|
+
const record = asRecord(payload);
|
|
1030
|
+
if (!record)
|
|
1031
|
+
return false;
|
|
1032
|
+
const method = record["authMethod"];
|
|
1033
|
+
if (method !== undefined && method !== null) {
|
|
1034
|
+
if (typeof method !== "string" || method.trim().toLowerCase() !== "claude.ai")
|
|
1035
|
+
return true;
|
|
1036
|
+
}
|
|
1037
|
+
const provider = record["apiProvider"];
|
|
1038
|
+
if (provider !== undefined && provider !== null) {
|
|
1039
|
+
if (typeof provider !== "string" || provider.trim().toLowerCase() !== "firstparty")
|
|
1040
|
+
return true;
|
|
1041
|
+
}
|
|
1042
|
+
return false;
|
|
1043
|
+
}
|
|
676
1044
|
function hasUnsupportedCommandText(output) {
|
|
677
1045
|
const normalized = output.toLowerCase();
|
|
678
1046
|
return (normalized.includes("unknown command") ||
|
|
@@ -718,6 +1086,8 @@ async function runClaudeCommand(invocation) {
|
|
|
718
1086
|
encoding: "utf8",
|
|
719
1087
|
timeout: CLAUDE_COMMAND_TIMEOUT_MS,
|
|
720
1088
|
maxBuffer: 1024 * 1024,
|
|
1089
|
+
windowsHide: true,
|
|
1090
|
+
...(invocation.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
|
721
1091
|
}, (error, stdout, stderr) => {
|
|
722
1092
|
const stdoutText = typeof stdout === "string" ? stdout : stdout.toString("utf8");
|
|
723
1093
|
const stderrText = typeof stderr === "string" ? stderr : stderr.toString("utf8");
|
|
@@ -767,9 +1137,16 @@ function parseClaudeAuthStatusResult(result) {
|
|
|
767
1137
|
const payload = JSON.parse(trimmed);
|
|
768
1138
|
const auth = extractAuthBoolean(payload);
|
|
769
1139
|
if (auth === true) {
|
|
1140
|
+
if (hasNonSubscriptionLogin(payload)) {
|
|
1141
|
+
return {
|
|
1142
|
+
authStatus: "unknown",
|
|
1143
|
+
message: CLAUDE_NON_SUBSCRIPTION_LOGIN_MESSAGE,
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
770
1146
|
return {
|
|
771
1147
|
authStatus: "authenticated",
|
|
772
1148
|
jsonPayload: payload,
|
|
1149
|
+
claudeAiLoginVerified: hasFirstPartyClaudeAiLogin(payload),
|
|
773
1150
|
};
|
|
774
1151
|
}
|
|
775
1152
|
if (auth === false) {
|
|
@@ -817,6 +1194,9 @@ function mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics) {
|
|
|
817
1194
|
binaryPath: localDiagnostics.binaryPath,
|
|
818
1195
|
checkedCommands: localDiagnostics.checkedCommands,
|
|
819
1196
|
quota: localDiagnostics.localQuota,
|
|
1197
|
+
...(localDiagnostics.planLabel === undefined
|
|
1198
|
+
? {}
|
|
1199
|
+
: { planLabel: localDiagnostics.planLabel }),
|
|
820
1200
|
};
|
|
821
1201
|
}
|
|
822
1202
|
const diagnostics = {
|
|
@@ -893,7 +1273,14 @@ async function probeAnthropicLocalDiagnostics(options = {}) {
|
|
|
893
1273
|
message: parsedAuth.message,
|
|
894
1274
|
};
|
|
895
1275
|
}
|
|
1276
|
+
// The CLI's report wins; otherwise CLAUDE_CONFIG_DIR, then the default. The CLI inherits this
|
|
1277
|
+
// environment, so this is the directory it reads its login from.
|
|
1278
|
+
const configDirectory = resolveClaudeConfigDirectory(asRecord(parsedAuth.jsonPayload)?.["configDirectory"], process.env[CLAUDE_CONFIG_DIR_ENV]);
|
|
896
1279
|
const quota = parsedAuth.jsonPayload ? parseUsageResponse(parsedAuth.jsonPayload) : null;
|
|
1280
|
+
// Only a verified first-party login may name its plan; the same login answers the quota above.
|
|
1281
|
+
const planLabel = parsedAuth.claudeAiLoginVerified === true
|
|
1282
|
+
? deriveClaudePlanLabel(parsedAuth.jsonPayload)
|
|
1283
|
+
: undefined;
|
|
897
1284
|
if (quota) {
|
|
898
1285
|
return {
|
|
899
1286
|
installed: true,
|
|
@@ -902,6 +1289,10 @@ async function probeAnthropicLocalDiagnostics(options = {}) {
|
|
|
902
1289
|
binaryPath: binaryPathDisplay,
|
|
903
1290
|
checkedCommands,
|
|
904
1291
|
localQuota: quota,
|
|
1292
|
+
effectiveBinary: binaryPath,
|
|
1293
|
+
configDirectory,
|
|
1294
|
+
claudeAiLoginVerified: parsedAuth.claudeAiLoginVerified === true,
|
|
1295
|
+
...(planLabel === undefined ? {} : { planLabel }),
|
|
905
1296
|
};
|
|
906
1297
|
}
|
|
907
1298
|
return {
|
|
@@ -911,241 +1302,185 @@ async function probeAnthropicLocalDiagnostics(options = {}) {
|
|
|
911
1302
|
binaryPath: binaryPathDisplay,
|
|
912
1303
|
checkedCommands,
|
|
913
1304
|
message: CLAUDE_NO_LOCAL_QUOTA_MESSAGE,
|
|
1305
|
+
effectiveBinary: binaryPath,
|
|
1306
|
+
configDirectory,
|
|
1307
|
+
claudeAiLoginVerified: parsedAuth.claudeAiLoginVerified === true,
|
|
1308
|
+
...(planLabel === undefined ? {} : { planLabel }),
|
|
914
1309
|
};
|
|
915
1310
|
}
|
|
916
1311
|
export function clearAnthropicDiagnosticsCacheForTests() {
|
|
917
|
-
diagnosticsCache.clear();
|
|
918
|
-
localDiagnosticsCache.clear();
|
|
919
1312
|
anthropicOAuthCooldowns.clear();
|
|
920
1313
|
anthropicOAuthInFlight.clear();
|
|
1314
|
+
anthropicOAuthForcedInFlight.clear();
|
|
1315
|
+
anthropicOAuthRecent.clear();
|
|
921
1316
|
}
|
|
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
|
-
});
|
|
1317
|
+
const localDiagnosticsCacheKey = Symbol("anthropic local diagnostics");
|
|
1318
|
+
async function getAnthropicLocalDiagnostics(options = {}) {
|
|
1319
|
+
if (!options.operationCache)
|
|
1320
|
+
return await probeAnthropicLocalDiagnostics(options);
|
|
1321
|
+
let probes = options.operationCache.get(localDiagnosticsCacheKey);
|
|
1322
|
+
if (!probes) {
|
|
1323
|
+
probes = new Map();
|
|
1324
|
+
options.operationCache.set(localDiagnosticsCacheKey, probes);
|
|
1325
|
+
}
|
|
1326
|
+
const key = JSON.stringify([
|
|
1327
|
+
resolveAnthropicBinaryPath(options.binaryPath),
|
|
1328
|
+
process.env[CLAUDE_CONFIG_DIR_ENV],
|
|
1329
|
+
]);
|
|
1330
|
+
let probe = probes.get(key);
|
|
1331
|
+
if (!probe) {
|
|
1332
|
+
probe = probeAnthropicLocalDiagnostics(options);
|
|
1333
|
+
probes.set(key, probe);
|
|
1334
|
+
}
|
|
1335
|
+
return await probe;
|
|
1336
|
+
}
|
|
1337
|
+
async function readSavedResetsForLocalQuota(localDiagnostics, options) {
|
|
949
1338
|
try {
|
|
950
|
-
|
|
1339
|
+
const credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
|
|
1340
|
+
if (credentials.state !== "configured")
|
|
1341
|
+
return undefined;
|
|
1342
|
+
const result = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version);
|
|
1343
|
+
return result.state === "success" ? result.quota.saved_resets : undefined;
|
|
951
1344
|
}
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
if (latest?.inFlight === inFlight) {
|
|
955
|
-
localDiagnosticsCache.set(binaryPath, {
|
|
956
|
-
timestamp: latest.timestamp,
|
|
957
|
-
value: latest.value,
|
|
958
|
-
});
|
|
959
|
-
}
|
|
1345
|
+
catch {
|
|
1346
|
+
return undefined;
|
|
960
1347
|
}
|
|
961
1348
|
}
|
|
962
1349
|
export async function getAnthropicDiagnostics(options = {}) {
|
|
963
|
-
const
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
1350
|
+
const localDiagnostics = await getAnthropicLocalDiagnostics(options);
|
|
1351
|
+
if (localDiagnostics.localQuota) {
|
|
1352
|
+
// Local quota stays authoritative and needs no token. Saved resets are an optional extra read
|
|
1353
|
+
// with the same verified-login token gate; the result still has no account identity, so it is
|
|
1354
|
+
// never cached across accounts.
|
|
1355
|
+
const mapped = mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
|
|
1356
|
+
const savedResets = await readSavedResetsForLocalQuota(localDiagnostics, options);
|
|
1357
|
+
return savedResets && mapped.quota
|
|
1358
|
+
? { ...mapped, quota: { ...mapped.quota, saved_resets: savedResets } }
|
|
1359
|
+
: mapped;
|
|
973
1360
|
}
|
|
974
|
-
if (
|
|
975
|
-
return
|
|
1361
|
+
if (localDiagnostics.authStatus !== "authenticated") {
|
|
1362
|
+
return mapLocalDiagnosticsToAnthropicDiagnostics(localDiagnostics);
|
|
976
1363
|
}
|
|
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 = {
|
|
1364
|
+
const credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
|
|
1365
|
+
if (credentials.state !== "configured") {
|
|
1366
|
+
return {
|
|
1030
1367
|
installed: localDiagnostics.installed,
|
|
1031
1368
|
version: localDiagnostics.version,
|
|
1032
1369
|
authStatus: localDiagnostics.authStatus,
|
|
1033
|
-
quotaSupported:
|
|
1034
|
-
quotaSource:
|
|
1035
|
-
? "opencode-auth-oauth-api"
|
|
1036
|
-
: "claude-credentials-oauth-api",
|
|
1037
|
-
oauthCredentialSource: credentials.source,
|
|
1370
|
+
quotaSupported: false,
|
|
1371
|
+
quotaSource: "none",
|
|
1038
1372
|
binaryPath: localDiagnostics.binaryPath,
|
|
1039
1373
|
checkedCommands: localDiagnostics.checkedCommands,
|
|
1040
|
-
|
|
1374
|
+
message: buildAnthropicNoQuotaDiagnosticsMessage(credentials.detail),
|
|
1041
1375
|
};
|
|
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
1376
|
}
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1377
|
+
const credentialFingerprint = fingerprintAccessToken(credentials.accessToken);
|
|
1378
|
+
const fallbackQuota = await queryAnthropicQuotaFromOAuthAccessToken(credentials.accessToken, options.requestTimeoutMs, options.forceRefresh ? options.operationCache : undefined, localDiagnostics.version);
|
|
1379
|
+
if (fallbackQuota.state !== "success") {
|
|
1380
|
+
return {
|
|
1381
|
+
installed: localDiagnostics.installed,
|
|
1382
|
+
version: localDiagnostics.version,
|
|
1383
|
+
authStatus: localDiagnostics.authStatus,
|
|
1384
|
+
quotaSupported: false,
|
|
1385
|
+
quotaSource: "none",
|
|
1386
|
+
oauthCredentialSource: credentials.source,
|
|
1387
|
+
binaryPath: localDiagnostics.binaryPath,
|
|
1388
|
+
checkedCommands: localDiagnostics.checkedCommands,
|
|
1389
|
+
message: buildAnthropicNoQuotaDiagnosticsMessage(fallbackQuota.detail),
|
|
1390
|
+
credentialFingerprint,
|
|
1391
|
+
...(fallbackQuota.failureCategory !== undefined
|
|
1392
|
+
? { failureCategory: fallbackQuota.failureCategory }
|
|
1393
|
+
: {}),
|
|
1394
|
+
...(fallbackQuota.retryAtMs !== undefined ? { retryAtMs: fallbackQuota.retryAtMs } : {}),
|
|
1395
|
+
};
|
|
1066
1396
|
}
|
|
1397
|
+
return {
|
|
1398
|
+
installed: localDiagnostics.installed,
|
|
1399
|
+
version: localDiagnostics.version,
|
|
1400
|
+
authStatus: localDiagnostics.authStatus,
|
|
1401
|
+
quotaSupported: true,
|
|
1402
|
+
quotaSource: "claude-credentials-oauth-api",
|
|
1403
|
+
oauthCredentialSource: credentials.source,
|
|
1404
|
+
binaryPath: localDiagnostics.binaryPath,
|
|
1405
|
+
checkedCommands: localDiagnostics.checkedCommands,
|
|
1406
|
+
quota: fallbackQuota.quota,
|
|
1407
|
+
credentialFingerprint,
|
|
1408
|
+
// The plan belongs to the CLI login only when this quota came from that login's own token.
|
|
1409
|
+
...(credentials.source === "claude-credentials" && localDiagnostics.planLabel !== undefined
|
|
1410
|
+
? { planLabel: localDiagnostics.planLabel }
|
|
1411
|
+
: {}),
|
|
1412
|
+
};
|
|
1067
1413
|
}
|
|
1068
1414
|
export async function hasAnthropicCredentialsConfigured(options = {}) {
|
|
1069
1415
|
try {
|
|
1070
|
-
const
|
|
1071
|
-
// A login OpenCode could not return still counts, so it shows as an error.
|
|
1072
|
-
if (opencodeCredentials.state === "configured" || opencodeCredentials.state === "failed") {
|
|
1073
|
-
return true;
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1076
|
-
catch {
|
|
1077
|
-
// Fall back to the existing local Claude CLI probe.
|
|
1078
|
-
}
|
|
1079
|
-
try {
|
|
1080
|
-
const diagnostics = await getCachedAnthropicLocalDiagnostics(options);
|
|
1416
|
+
const diagnostics = await getAnthropicLocalDiagnostics(options);
|
|
1081
1417
|
return diagnostics.installed && diagnostics.authStatus === "authenticated";
|
|
1082
1418
|
}
|
|
1083
1419
|
catch {
|
|
1084
1420
|
return false;
|
|
1085
1421
|
}
|
|
1086
1422
|
}
|
|
1087
|
-
|
|
1423
|
+
/**
|
|
1424
|
+
* Identity of the Claude Agent provider's single Claude CLI login. Null when the CLI reports quota
|
|
1425
|
+
* itself (no account binding) or cannot be probed, so the caller must not cache it.
|
|
1426
|
+
*/
|
|
1427
|
+
export async function resolveClaudeAgentAccountIdentity(params) {
|
|
1088
1428
|
let localDiagnostics;
|
|
1089
1429
|
try {
|
|
1090
|
-
localDiagnostics = await
|
|
1430
|
+
localDiagnostics = await getAnthropicLocalDiagnostics({
|
|
1431
|
+
binaryPath: params.binaryPath,
|
|
1432
|
+
operationCache: params.operationCache,
|
|
1433
|
+
});
|
|
1091
1434
|
}
|
|
1092
1435
|
catch {
|
|
1093
1436
|
return null;
|
|
1094
1437
|
}
|
|
1095
|
-
// Claude CLI quota does not expose an account identity.
|
|
1096
|
-
// path process-local rather than risking reuse after a CLI account switch.
|
|
1438
|
+
// Claude CLI quota does not expose an account identity.
|
|
1097
1439
|
if (localDiagnostics.localQuota)
|
|
1098
1440
|
return null;
|
|
1099
|
-
const
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
:
|
|
1106
|
-
|
|
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;
|
|
1441
|
+
const identity = await claudeCliAccountIdentity(localDiagnostics, params.runtimeDetected);
|
|
1442
|
+
if (!identity)
|
|
1443
|
+
return null;
|
|
1444
|
+
return await composeResolvedAuthIdentities({
|
|
1445
|
+
providerId: "claude-agent",
|
|
1446
|
+
identities: [identity],
|
|
1447
|
+
qualifiers: [params.onlyCurrentModel ? "only-current-model" : "all-models"],
|
|
1448
|
+
});
|
|
1123
1449
|
}
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
return {
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1450
|
+
/**
|
|
1451
|
+
* The Claude CLI row's identity. A readable first-party CLI token keys it, because its quota and its
|
|
1452
|
+
* quota depends on that token. Otherwise the row shows only the CLI's install and sign-in
|
|
1453
|
+
* state, so that state keys it.
|
|
1454
|
+
*/
|
|
1455
|
+
async function claudeCliAccountIdentity(localDiagnostics, claudeCodeRuntimeDetected) {
|
|
1456
|
+
if (localDiagnostics.authStatus === "authenticated") {
|
|
1457
|
+
const credentials = await readClaudeCliSubscriptionToken(localDiagnostics);
|
|
1458
|
+
if (credentials.state === "configured") {
|
|
1459
|
+
return await deriveResolvedAuthIdentity({
|
|
1460
|
+
providerId: "anthropic:claude-cli-account",
|
|
1461
|
+
principal: { kind: "credential", value: credentials.accessToken },
|
|
1462
|
+
qualifiers: [
|
|
1463
|
+
localDiagnostics.effectiveBinary ?? "",
|
|
1464
|
+
claudeConfigDirectoryQualifier(localDiagnostics.configDirectory),
|
|
1465
|
+
// Preserve the existing cache identity for the previously non-excluded CLI login.
|
|
1466
|
+
"distinct",
|
|
1467
|
+
],
|
|
1468
|
+
});
|
|
1140
1469
|
}
|
|
1141
|
-
return null;
|
|
1142
|
-
}
|
|
1143
|
-
catch (err) {
|
|
1144
|
-
return {
|
|
1145
|
-
success: false,
|
|
1146
|
-
error: `Claude CLI probe failed: ${sanitizeDisplayText(err instanceof Error ? err.message : String(err))}`,
|
|
1147
|
-
};
|
|
1148
1470
|
}
|
|
1471
|
+
return await deriveResolvedAuthIdentity({
|
|
1472
|
+
providerId: "anthropic:claude-cli-state",
|
|
1473
|
+
principal: { kind: "stable-id", value: "claude-cli-state" },
|
|
1474
|
+
qualifiers: [
|
|
1475
|
+
localDiagnostics.installed ? "installed" : "missing",
|
|
1476
|
+
localDiagnostics.version ?? "",
|
|
1477
|
+
localDiagnostics.authStatus,
|
|
1478
|
+
localDiagnostics.effectiveBinary ?? "",
|
|
1479
|
+
claudeConfigDirectoryQualifier(localDiagnostics.configDirectory),
|
|
1480
|
+
localDiagnostics.claudeAiLoginVerified === true ? "verified" : "unverified",
|
|
1481
|
+
claudeCodeRuntimeDetected ? "detected" : "undetected",
|
|
1482
|
+
],
|
|
1483
|
+
});
|
|
1149
1484
|
}
|
|
1150
1485
|
export { parseOAuthUsageResponse, parseUsageResponse };
|
|
1151
1486
|
//# sourceMappingURL=anthropic.js.map
|