tokenusage-cli 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,508 +1,508 @@
1
- const os = require("node:os");
2
- const path = require("node:path");
3
- const fs = require("node:fs");
4
- const cp = require("node:child_process");
5
-
6
- const { readJson } = require("./fs");
7
- const { resolveTrackerPaths } = require("./tracker-paths");
8
- const { probeOpenclawSessionPluginState } = require("./openclaw-session-plugin");
9
-
10
- const OPENAI_AUTH_CLAIM = "https://api.openai.com/auth";
11
- const MACOS_SECURITY_BIN = "/usr/bin/security";
12
- const CLAUDE_CODE_KEYCHAIN_SERVICES = ["Claude Code-credentials"];
13
- // On Linux and Windows, Claude Code persists the same OAuth payload as a plain
14
- // JSON file instead of the macOS Keychain — at ~/.claude/.credentials.json on
15
- // Linux and %USERPROFILE%\.claude\.credentials.json on Windows (both resolve via
16
- // os.homedir()). The payload shape is identical:
17
- // { claudeAiOauth: { accessToken, subscriptionType, ... } }
18
- const CLAUDE_CODE_CREDENTIALS_FILE = ".credentials.json";
19
- // Platforms where Claude Code stores credentials in the plain JSON file above
20
- // rather than the macOS Keychain.
21
- const CLAUDE_CODE_CREDENTIALS_FILE_PLATFORMS = new Set(["linux", "win32"]);
22
- // Refresh slightly before wall-clock expiry so Limits does not spend a request
23
- // that Anthropic answers with 429 for a real-but-expired Claude Code token.
24
- const CLAUDE_TOKEN_EXPIRY_SKEW_MS = 60_000;
25
-
26
- function usesClaudeCodeCredentialsFile(platform) {
27
- return CLAUDE_CODE_CREDENTIALS_FILE_PLATFORMS.has(platform);
28
- }
29
-
30
- function normalizeString(value) {
31
- if (typeof value !== "string") return null;
32
- const trimmed = value.trim();
33
- return trimmed.length > 0 ? trimmed : null;
34
- }
35
-
36
- function normalizeScalarToString(value) {
37
- if (value === null || value === undefined) return null;
38
- if (typeof value === "string") return normalizeString(value);
39
- if (typeof value === "number") {
40
- if (!Number.isFinite(value)) return null;
41
- return normalizeString(String(value));
42
- }
43
- if (typeof value === "boolean") return value ? "true" : "false";
44
- return null;
45
- }
46
-
47
- function base64UrlDecodeToString(value) {
48
- if (typeof value !== "string" || value.length === 0) return null;
49
- const padLen = (4 - (value.length % 4)) % 4;
50
- const padded = value + "=".repeat(padLen);
51
- const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
52
- try {
53
- return Buffer.from(base64, "base64").toString("utf8");
54
- } catch (_e) {
55
- return null;
56
- }
57
- }
58
-
59
- function decodeJwtPayload(token) {
60
- const jwt = normalizeString(token);
61
- if (!jwt) return null;
62
- const parts = jwt.split(".");
63
- if (parts.length < 2) return null;
64
- const decoded = base64UrlDecodeToString(parts[1]);
65
- if (!decoded) return null;
66
- try {
67
- return JSON.parse(decoded);
68
- } catch (_e) {
69
- return null;
70
- }
71
- }
72
-
73
- function extractOpenAiAuthNamespace(payload) {
74
- if (!payload || typeof payload !== "object") return null;
75
- const ns = payload[OPENAI_AUTH_CLAIM];
76
- if (!ns || typeof ns !== "object" || Array.isArray(ns)) return null;
77
- return ns;
78
- }
79
-
80
- function extractChatgptSubscriptionFromPayload(payload) {
81
- const ns = extractOpenAiAuthNamespace(payload);
82
- if (!ns) return null;
83
-
84
- const planType = normalizeString(ns.chatgpt_plan_type);
85
- const activeStart = normalizeString(ns.chatgpt_subscription_active_start);
86
- const activeUntil = normalizeString(ns.chatgpt_subscription_active_until);
87
- const lastChecked = normalizeString(ns.chatgpt_subscription_last_checked);
88
-
89
- if (!planType && !activeStart && !activeUntil && !lastChecked) return null;
90
- return { planType, activeStart, activeUntil, lastChecked };
91
- }
92
-
93
- function mergeSubscription(primary, secondary) {
94
- if (!primary && !secondary) return null;
95
- const a = primary || {};
96
- const b = secondary || {};
97
- return {
98
- planType: a.planType || b.planType || null,
99
- activeStart: a.activeStart || b.activeStart || null,
100
- activeUntil: a.activeUntil || b.activeUntil || null,
101
- lastChecked: a.lastChecked || b.lastChecked || null,
102
- };
103
- }
104
-
105
- function isDisplayablePlanType(planType) {
106
- const normalized = normalizeString(planType);
107
- if (!normalized) return false;
108
- const v = normalized.toLowerCase();
109
- if (v === "free" || v === "none" || v === "unknown") return false;
110
- return true;
111
- }
112
-
113
- function resolveCodexHome({ home, env }) {
114
- const explicit = normalizeString(env?.CODEX_HOME);
115
- return explicit ? path.resolve(explicit) : path.join(home, ".codex");
116
- }
117
-
118
- function resolveOpencodeDataDir({ home, env }) {
119
- const explicit = normalizeString(env?.XDG_DATA_HOME);
120
- const base = explicit ? path.resolve(explicit) : path.join(home, ".local", "share");
121
- return path.join(base, "opencode");
122
- }
123
-
124
- async function detectCodexChatgptSubscription({ home, env }) {
125
- const codexHome = resolveCodexHome({ home, env });
126
- const authPath = path.join(codexHome, "auth.json");
127
- const auth = await readJson(authPath);
128
- if (!auth || typeof auth !== "object") return null;
129
-
130
- const accessPayload = decodeJwtPayload(auth?.tokens?.access_token);
131
- const idPayload = decodeJwtPayload(auth?.tokens?.id_token);
132
-
133
- const accessInfo = extractChatgptSubscriptionFromPayload(accessPayload);
134
- const idInfo = extractChatgptSubscriptionFromPayload(idPayload);
135
- const merged = mergeSubscription(accessInfo, idInfo);
136
- if (!merged || !isDisplayablePlanType(merged.planType)) return null;
137
-
138
- return {
139
- tool: "codex",
140
- provider: "openai",
141
- product: "chatgpt",
142
- planType: merged.planType,
143
- activeStart: merged.activeStart,
144
- activeUntil: merged.activeUntil,
145
- lastChecked: merged.lastChecked,
146
- };
147
- }
148
-
149
- async function detectOpencodeChatgptSubscription({ home, env }) {
150
- const dataDir = resolveOpencodeDataDir({ home, env });
151
- const authPath = path.join(dataDir, "auth.json");
152
- const auth = await readJson(authPath);
153
- if (!auth || typeof auth !== "object") return null;
154
-
155
- const accessPayload = decodeJwtPayload(auth?.openai?.access);
156
- const info = extractChatgptSubscriptionFromPayload(accessPayload);
157
- if (!info || !isDisplayablePlanType(info.planType)) return null;
158
-
159
- return {
160
- tool: "opencode",
161
- provider: "openai",
162
- product: "chatgpt",
163
- planType: info.planType,
164
- activeStart: info.activeStart,
165
- activeUntil: info.activeUntil,
166
- lastChecked: info.lastChecked,
167
- };
168
- }
169
-
170
- // Match Claude Code 2.1.267's account derivation. A service-only lookup may
171
- // select credentials from an older installation before the current account.
172
- function resolveClaudeKeychainAccount({ env = process.env, userInfo = os.userInfo } = {}) {
173
- let account;
174
- try { account = env.USER || userInfo().username; } catch (_error) { return "claude-code-user"; }
175
- return typeof account === "string" && /^[a-zA-Z0-9._-]+$/.test(account)
176
- ? account : "claude-code-user";
177
- }
178
-
179
- function probeMacosKeychainGenericPassword({ service, securityRunner, timeoutMs, env } = {}) {
180
- const svc = normalizeString(service);
181
- if (!svc) return false;
182
-
183
- const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
184
- if (runner === cp.spawnSync && !fs.existsSync(MACOS_SECURITY_BIN)) return false;
185
-
186
- const result = runner(MACOS_SECURITY_BIN, ["find-generic-password", "-s", svc, "-a", resolveClaudeKeychainAccount({ env })], {
187
- stdio: "ignore",
188
- timeout: Number.isFinite(timeoutMs) ? timeoutMs : 2000,
189
- });
190
-
191
- if (!result || result.error) return false;
192
- return result.status === 0;
193
- }
194
-
195
- function readMacosKeychainPassword({ service, securityRunner, timeoutMs, env } = {}) {
196
- const svc = normalizeString(service);
197
- if (!svc) return null;
198
-
199
- const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
200
- if (runner === cp.spawnSync && !fs.existsSync(MACOS_SECURITY_BIN)) return null;
201
-
202
- const result = runner(MACOS_SECURITY_BIN, ["find-generic-password", "-s", svc, "-a", resolveClaudeKeychainAccount({ env }), "-w"], {
203
- stdio: ["ignore", "pipe", "ignore"],
204
- timeout: Number.isFinite(timeoutMs) ? timeoutMs : 2000,
205
- encoding: "utf8",
206
- });
207
-
208
- if (!result || result.error) return null;
209
- if (result.status !== 0) return null;
210
-
211
- const stdout =
212
- typeof result.stdout === "string"
213
- ? result.stdout
214
- : Buffer.isBuffer(result.stdout)
215
- ? result.stdout.toString("utf8")
216
- : "";
217
- const trimmed = stdout.trim();
218
- return trimmed.length > 0 ? trimmed : null;
219
- }
220
-
221
- function readClaudeCodeCredentialsFile({ home, fsReader } = {}) {
222
- const homeDir = typeof home === "string" && home ? home : os.homedir();
223
- const credPath = path.join(homeDir, ".claude", CLAUDE_CODE_CREDENTIALS_FILE);
224
- const reader = typeof fsReader === "function" ? fsReader : fs.readFileSync;
225
- try {
226
- return reader(credPath, "utf8");
227
- } catch (_e) {
228
- return null;
229
- }
230
- }
231
-
232
- function detectClaudeCodeCredentialsPresence({ platform = process.platform, securityRunner, home, fsReader, env } = {}) {
233
- if (platform === "darwin") {
234
- for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
235
- const present = probeMacosKeychainGenericPassword({
236
- service,
237
- securityRunner,
238
- env,
239
- });
240
- if (!present) continue;
241
-
242
- // Existence-only probe: do not read secrets or infer paid tier.
243
- return {
244
- tool: "claude",
245
- provider: "anthropic",
246
- product: "credentials",
247
- planType: "present",
248
- };
249
- }
250
- return null;
251
- }
252
-
253
- if (!usesClaudeCodeCredentialsFile(platform)) return null;
254
-
255
- // Linux/Windows: credentials live in the .credentials.json file (mode 0600 on
256
- // Linux; user-profile ACLs on Windows). Existence-only: just check that the
257
- // file is readable and contains the OAuth key.
258
- const raw = readClaudeCodeCredentialsFile({ home, fsReader });
259
- if (!raw) return null;
260
- try {
261
- const payload = JSON.parse(raw);
262
- if (payload?.claudeAiOauth && typeof payload.claudeAiOauth === "object") {
263
- return {
264
- tool: "claude",
265
- provider: "anthropic",
266
- product: "credentials",
267
- planType: "present",
268
- };
269
- }
270
- } catch (_e) {
271
- // fall through
272
- }
273
- return null;
274
- }
275
-
276
- function parseClaudeOauthExpiryMs(value) {
277
- if (typeof value === "number") {
278
- if (!Number.isFinite(value)) return null;
279
- if (value <= 0) return 0;
280
- return value < 1e12 ? value * 1000 : value;
281
- }
282
- if (typeof value === "string") {
283
- const trimmed = value.trim();
284
- if (!trimmed) return null;
285
- if (/^-?\d+(\.\d+)?$/.test(trimmed)) return parseClaudeOauthExpiryMs(Number(trimmed));
286
- const ms = Date.parse(trimmed);
287
- return Number.isFinite(ms) ? ms : null;
288
- }
289
- return null;
290
- }
291
-
292
- function extractClaudeCodeOauth(payload, nowMs = Date.now()) {
293
- const oauth = payload?.claudeAiOauth;
294
- const accessToken = normalizeString(oauth?.accessToken);
295
- if (!accessToken) return null;
296
- const expiresAtMs = parseClaudeOauthExpiryMs(oauth?.expiresAt);
297
- if (expiresAtMs != null && expiresAtMs <= nowMs + CLAUDE_TOKEN_EXPIRY_SKEW_MS) return null;
298
- return { accessToken, expiresAtMs };
299
- }
300
-
301
- function extractClaudeKeychainSubscription(payload) {
302
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
303
-
304
- const oauth = payload.claudeAiOauth;
305
- if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) return null;
306
-
307
- const subscriptionType = normalizeScalarToString(oauth.subscriptionType);
308
- const rateLimitTier = normalizeScalarToString(oauth.rateLimitTier);
309
-
310
- if (!subscriptionType) return null;
311
- return { subscriptionType, rateLimitTier };
312
- }
313
-
314
- function detectClaudeCodeSubscriptionDetails({ platform = process.platform, securityRunner, home, fsReader, env } = {}) {
315
- const rawPayloads = [];
316
- if (platform === "darwin") {
317
- for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
318
- const raw = readMacosKeychainPassword({ service, securityRunner, env });
319
- if (raw) rawPayloads.push(raw);
320
- }
321
- } else if (usesClaudeCodeCredentialsFile(platform)) {
322
- const raw = readClaudeCodeCredentialsFile({ home, fsReader });
323
- if (raw) rawPayloads.push(raw);
324
- } else {
325
- return null;
326
- }
327
-
328
- for (const raw of rawPayloads) {
329
- let payload;
330
- try {
331
- payload = JSON.parse(raw);
332
- } catch (_e) {
333
- continue;
334
- }
335
-
336
- const info = extractClaudeKeychainSubscription(payload);
337
- if (!info) continue;
338
-
339
- return {
340
- tool: "claude",
341
- provider: "anthropic",
342
- product: "subscription",
343
- planType: info.subscriptionType,
344
- rateLimitTier: info.rateLimitTier,
345
- };
346
- }
347
-
348
- return null;
349
- }
350
-
351
- async function collectLocalSubscriptions({
352
- home = os.homedir(),
353
- env = process.env,
354
- platform = process.platform,
355
- securityRunner,
356
- probeKeychain = false,
357
- probeKeychainDetails = false,
358
- } = {}) {
359
- const out = [];
360
-
361
- const codex = await detectCodexChatgptSubscription({ home, env });
362
- if (codex) out.push(codex);
363
-
364
- const opencode = await detectOpencodeChatgptSubscription({ home, env });
365
- if (opencode) out.push(opencode);
366
-
367
- if (probeKeychainDetails) {
368
- const claude = detectClaudeCodeSubscriptionDetails({ platform, securityRunner, home, env });
369
- if (claude) out.push(claude);
370
- else if (probeKeychain) {
371
- const present = detectClaudeCodeCredentialsPresence({ platform, securityRunner, home, env });
372
- if (present) out.push(present);
373
- }
374
- } else if (probeKeychain) {
375
- const claude = detectClaudeCodeCredentialsPresence({ platform, securityRunner, home, env });
376
- if (claude) out.push(claude);
377
- }
378
-
379
- const openclaw = await detectOpenclawSessionIntegration({ home, env });
380
- if (openclaw) out.push(openclaw);
381
-
382
- // Gemini: no stable local subscription/tier signal found yet.
383
- return out;
384
- }
385
-
386
- async function detectOpenclawSessionIntegration({ home, env }) {
387
- const { trackerDir } = await resolveTrackerPaths({ home });
388
- let state = null;
389
- try {
390
- state = await probeOpenclawSessionPluginState({ home, trackerDir, env });
391
- } catch (_err) {
392
- return null;
393
- }
394
-
395
- if (!state?.configured) return null;
396
-
397
- return {
398
- tool: "openclaw",
399
- provider: "openclaw",
400
- product: "session_plugin",
401
- planType: "enabled",
402
- };
403
- }
404
-
405
- // Returns the live OAuth token plus its expiry stamp. The expiry doubles as a
406
- // rotation marker for the 429 cool-down: it changes on every refresh and, unlike
407
- // the token itself, is not a secret, so nothing derived from a credential has to
408
- // be written to disk.
409
- function readClaudeCodeOauthToken({
410
- platform = process.platform,
411
- securityRunner,
412
- home,
413
- fsReader,
414
- env,
415
- nowMs = Date.now(),
416
- } = {}) {
417
- if (platform === "darwin") {
418
- for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
419
- try {
420
- const raw = readMacosKeychainPassword({ service, securityRunner, env });
421
- if (!raw) continue;
422
- const oauth = extractClaudeCodeOauth(JSON.parse(raw), nowMs);
423
- if (oauth) return oauth;
424
- } catch (_e) {
425
- continue;
426
- }
427
- }
428
- return null;
429
- }
430
-
431
- if (!usesClaudeCodeCredentialsFile(platform)) return null;
432
-
433
- // Linux/Windows: Claude Code stores the OAuth payload as a JSON file
434
- // (mode 0600 on Linux; user-profile ACLs on Windows).
435
- const raw = readClaudeCodeCredentialsFile({ home, fsReader });
436
- if (!raw) return null;
437
- try {
438
- return extractClaudeCodeOauth(JSON.parse(raw), nowMs);
439
- } catch (_e) {
440
- return null;
441
- }
442
- }
443
-
444
- function readClaudeCodeAccessToken(options = {}) {
445
- return readClaudeCodeOauthToken(options)?.accessToken ?? null;
446
- }
447
-
448
- async function readCodexAccessToken({ home, env } = {}) {
449
- try {
450
- const codexHome = resolveCodexHome({ home, env });
451
- const authPath = path.join(codexHome, "auth.json");
452
- const auth = await readJson(authPath);
453
- return normalizeString(auth?.tokens?.access_token);
454
- } catch (_e) {
455
- return null;
456
- }
457
- }
458
-
459
- // Returns the access token + ChatGPT account id + plan type + auth.json path so callers can
460
- // also trigger a refresh if the tokens are stale (issue #52: stale tokens → wham 401 →
461
- // "Fetch failed" error after ~7-8 days of not running `codex`).
462
- async function readCodexAuthBundle({ home, env } = {}) {
463
- try {
464
- const codexHome = resolveCodexHome({ home, env });
465
- const authPath = path.join(codexHome, "auth.json");
466
- const auth = await readJson(authPath);
467
- if (!auth || typeof auth !== "object") return null;
468
-
469
- const accessToken = normalizeString(auth?.tokens?.access_token);
470
- if (!accessToken) return null;
471
-
472
- const accessPayload = decodeJwtPayload(auth?.tokens?.access_token);
473
- const idPayload = decodeJwtPayload(auth?.tokens?.id_token);
474
- const accountId =
475
- normalizeString(auth?.tokens?.account_id) ||
476
- normalizeString(extractOpenAiAuthNamespace(accessPayload)?.chatgpt_account_id) ||
477
- normalizeString(extractOpenAiAuthNamespace(idPayload)?.chatgpt_account_id) ||
478
- null;
479
-
480
- const accessInfo = extractChatgptSubscriptionFromPayload(accessPayload);
481
- const idInfo = extractChatgptSubscriptionFromPayload(idPayload);
482
- const merged = mergeSubscription(accessInfo, idInfo);
483
- const planType = merged?.planType ? merged.planType.toLowerCase() : null;
484
-
485
- return {
486
- accessToken,
487
- accountId,
488
- planType,
489
- refreshToken: normalizeString(auth?.tokens?.refresh_token) || null,
490
- lastRefresh: normalizeString(auth?.last_refresh) || null,
491
- authPath,
492
- authJson: auth,
493
- };
494
- } catch (_e) {
495
- return null;
496
- }
497
- }
498
-
499
- module.exports = {
500
- resolveClaudeKeychainAccount,
501
- collectLocalSubscriptions,
502
- detectClaudeCodeCredentialsPresence,
503
- detectClaudeCodeSubscriptionDetails,
504
- readClaudeCodeAccessToken,
505
- readClaudeCodeOauthToken,
506
- readCodexAccessToken,
507
- readCodexAuthBundle,
508
- };
1
+ const os = require("node:os");
2
+ const path = require("node:path");
3
+ const fs = require("node:fs");
4
+ const cp = require("node:child_process");
5
+
6
+ const { readJson } = require("./fs");
7
+ const { resolveTrackerPaths } = require("./tracker-paths");
8
+ const { probeOpenclawSessionPluginState } = require("./openclaw-session-plugin");
9
+
10
+ const OPENAI_AUTH_CLAIM = "https://api.openai.com/auth";
11
+ const MACOS_SECURITY_BIN = "/usr/bin/security";
12
+ const CLAUDE_CODE_KEYCHAIN_SERVICES = ["Claude Code-credentials"];
13
+ // On Linux and Windows, Claude Code persists the same OAuth payload as a plain
14
+ // JSON file instead of the macOS Keychain — at ~/.claude/.credentials.json on
15
+ // Linux and %USERPROFILE%\.claude\.credentials.json on Windows (both resolve via
16
+ // os.homedir()). The payload shape is identical:
17
+ // { claudeAiOauth: { accessToken, subscriptionType, ... } }
18
+ const CLAUDE_CODE_CREDENTIALS_FILE = ".credentials.json";
19
+ // Platforms where Claude Code stores credentials in the plain JSON file above
20
+ // rather than the macOS Keychain.
21
+ const CLAUDE_CODE_CREDENTIALS_FILE_PLATFORMS = new Set(["linux", "win32"]);
22
+ // Refresh slightly before wall-clock expiry so Limits does not spend a request
23
+ // that Anthropic answers with 429 for a real-but-expired Claude Code token.
24
+ const CLAUDE_TOKEN_EXPIRY_SKEW_MS = 60_000;
25
+
26
+ function usesClaudeCodeCredentialsFile(platform) {
27
+ return CLAUDE_CODE_CREDENTIALS_FILE_PLATFORMS.has(platform);
28
+ }
29
+
30
+ function normalizeString(value) {
31
+ if (typeof value !== "string") return null;
32
+ const trimmed = value.trim();
33
+ return trimmed.length > 0 ? trimmed : null;
34
+ }
35
+
36
+ function normalizeScalarToString(value) {
37
+ if (value === null || value === undefined) return null;
38
+ if (typeof value === "string") return normalizeString(value);
39
+ if (typeof value === "number") {
40
+ if (!Number.isFinite(value)) return null;
41
+ return normalizeString(String(value));
42
+ }
43
+ if (typeof value === "boolean") return value ? "true" : "false";
44
+ return null;
45
+ }
46
+
47
+ function base64UrlDecodeToString(value) {
48
+ if (typeof value !== "string" || value.length === 0) return null;
49
+ const padLen = (4 - (value.length % 4)) % 4;
50
+ const padded = value + "=".repeat(padLen);
51
+ const base64 = padded.replace(/-/g, "+").replace(/_/g, "/");
52
+ try {
53
+ return Buffer.from(base64, "base64").toString("utf8");
54
+ } catch (_e) {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ function decodeJwtPayload(token) {
60
+ const jwt = normalizeString(token);
61
+ if (!jwt) return null;
62
+ const parts = jwt.split(".");
63
+ if (parts.length < 2) return null;
64
+ const decoded = base64UrlDecodeToString(parts[1]);
65
+ if (!decoded) return null;
66
+ try {
67
+ return JSON.parse(decoded);
68
+ } catch (_e) {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ function extractOpenAiAuthNamespace(payload) {
74
+ if (!payload || typeof payload !== "object") return null;
75
+ const ns = payload[OPENAI_AUTH_CLAIM];
76
+ if (!ns || typeof ns !== "object" || Array.isArray(ns)) return null;
77
+ return ns;
78
+ }
79
+
80
+ function extractChatgptSubscriptionFromPayload(payload) {
81
+ const ns = extractOpenAiAuthNamespace(payload);
82
+ if (!ns) return null;
83
+
84
+ const planType = normalizeString(ns.chatgpt_plan_type);
85
+ const activeStart = normalizeString(ns.chatgpt_subscription_active_start);
86
+ const activeUntil = normalizeString(ns.chatgpt_subscription_active_until);
87
+ const lastChecked = normalizeString(ns.chatgpt_subscription_last_checked);
88
+
89
+ if (!planType && !activeStart && !activeUntil && !lastChecked) return null;
90
+ return { planType, activeStart, activeUntil, lastChecked };
91
+ }
92
+
93
+ function mergeSubscription(primary, secondary) {
94
+ if (!primary && !secondary) return null;
95
+ const a = primary || {};
96
+ const b = secondary || {};
97
+ return {
98
+ planType: a.planType || b.planType || null,
99
+ activeStart: a.activeStart || b.activeStart || null,
100
+ activeUntil: a.activeUntil || b.activeUntil || null,
101
+ lastChecked: a.lastChecked || b.lastChecked || null,
102
+ };
103
+ }
104
+
105
+ function isDisplayablePlanType(planType) {
106
+ const normalized = normalizeString(planType);
107
+ if (!normalized) return false;
108
+ const v = normalized.toLowerCase();
109
+ if (v === "free" || v === "none" || v === "unknown") return false;
110
+ return true;
111
+ }
112
+
113
+ function resolveCodexHome({ home, env }) {
114
+ const explicit = normalizeString(env?.CODEX_HOME);
115
+ return explicit ? path.resolve(explicit) : path.join(home, ".codex");
116
+ }
117
+
118
+ function resolveOpencodeDataDir({ home, env }) {
119
+ const explicit = normalizeString(env?.XDG_DATA_HOME);
120
+ const base = explicit ? path.resolve(explicit) : path.join(home, ".local", "share");
121
+ return path.join(base, "opencode");
122
+ }
123
+
124
+ async function detectCodexChatgptSubscription({ home, env }) {
125
+ const codexHome = resolveCodexHome({ home, env });
126
+ const authPath = path.join(codexHome, "auth.json");
127
+ const auth = await readJson(authPath);
128
+ if (!auth || typeof auth !== "object") return null;
129
+
130
+ const accessPayload = decodeJwtPayload(auth?.tokens?.access_token);
131
+ const idPayload = decodeJwtPayload(auth?.tokens?.id_token);
132
+
133
+ const accessInfo = extractChatgptSubscriptionFromPayload(accessPayload);
134
+ const idInfo = extractChatgptSubscriptionFromPayload(idPayload);
135
+ const merged = mergeSubscription(accessInfo, idInfo);
136
+ if (!merged || !isDisplayablePlanType(merged.planType)) return null;
137
+
138
+ return {
139
+ tool: "codex",
140
+ provider: "openai",
141
+ product: "chatgpt",
142
+ planType: merged.planType,
143
+ activeStart: merged.activeStart,
144
+ activeUntil: merged.activeUntil,
145
+ lastChecked: merged.lastChecked,
146
+ };
147
+ }
148
+
149
+ async function detectOpencodeChatgptSubscription({ home, env }) {
150
+ const dataDir = resolveOpencodeDataDir({ home, env });
151
+ const authPath = path.join(dataDir, "auth.json");
152
+ const auth = await readJson(authPath);
153
+ if (!auth || typeof auth !== "object") return null;
154
+
155
+ const accessPayload = decodeJwtPayload(auth?.openai?.access);
156
+ const info = extractChatgptSubscriptionFromPayload(accessPayload);
157
+ if (!info || !isDisplayablePlanType(info.planType)) return null;
158
+
159
+ return {
160
+ tool: "opencode",
161
+ provider: "openai",
162
+ product: "chatgpt",
163
+ planType: info.planType,
164
+ activeStart: info.activeStart,
165
+ activeUntil: info.activeUntil,
166
+ lastChecked: info.lastChecked,
167
+ };
168
+ }
169
+
170
+ // Match Claude Code 2.1.267's account derivation. A service-only lookup may
171
+ // select credentials from an older installation before the current account.
172
+ function resolveClaudeKeychainAccount({ env = process.env, userInfo = os.userInfo } = {}) {
173
+ let account;
174
+ try { account = env.USER || userInfo().username; } catch (_error) { return "claude-code-user"; }
175
+ return typeof account === "string" && /^[a-zA-Z0-9._-]+$/.test(account)
176
+ ? account : "claude-code-user";
177
+ }
178
+
179
+ function probeMacosKeychainGenericPassword({ service, securityRunner, timeoutMs, env } = {}) {
180
+ const svc = normalizeString(service);
181
+ if (!svc) return false;
182
+
183
+ const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
184
+ if (runner === cp.spawnSync && !fs.existsSync(MACOS_SECURITY_BIN)) return false;
185
+
186
+ const result = runner(MACOS_SECURITY_BIN, ["find-generic-password", "-s", svc, "-a", resolveClaudeKeychainAccount({ env })], {
187
+ stdio: "ignore",
188
+ timeout: Number.isFinite(timeoutMs) ? timeoutMs : 2000,
189
+ });
190
+
191
+ if (!result || result.error) return false;
192
+ return result.status === 0;
193
+ }
194
+
195
+ function readMacosKeychainPassword({ service, securityRunner, timeoutMs, env } = {}) {
196
+ const svc = normalizeString(service);
197
+ if (!svc) return null;
198
+
199
+ const runner = typeof securityRunner === "function" ? securityRunner : cp.spawnSync;
200
+ if (runner === cp.spawnSync && !fs.existsSync(MACOS_SECURITY_BIN)) return null;
201
+
202
+ const result = runner(MACOS_SECURITY_BIN, ["find-generic-password", "-s", svc, "-a", resolveClaudeKeychainAccount({ env }), "-w"], {
203
+ stdio: ["ignore", "pipe", "ignore"],
204
+ timeout: Number.isFinite(timeoutMs) ? timeoutMs : 2000,
205
+ encoding: "utf8",
206
+ });
207
+
208
+ if (!result || result.error) return null;
209
+ if (result.status !== 0) return null;
210
+
211
+ const stdout =
212
+ typeof result.stdout === "string"
213
+ ? result.stdout
214
+ : Buffer.isBuffer(result.stdout)
215
+ ? result.stdout.toString("utf8")
216
+ : "";
217
+ const trimmed = stdout.trim();
218
+ return trimmed.length > 0 ? trimmed : null;
219
+ }
220
+
221
+ function readClaudeCodeCredentialsFile({ home, fsReader } = {}) {
222
+ const homeDir = typeof home === "string" && home ? home : os.homedir();
223
+ const credPath = path.join(homeDir, ".claude", CLAUDE_CODE_CREDENTIALS_FILE);
224
+ const reader = typeof fsReader === "function" ? fsReader : fs.readFileSync;
225
+ try {
226
+ return reader(credPath, "utf8");
227
+ } catch (_e) {
228
+ return null;
229
+ }
230
+ }
231
+
232
+ function detectClaudeCodeCredentialsPresence({ platform = process.platform, securityRunner, home, fsReader, env } = {}) {
233
+ if (platform === "darwin") {
234
+ for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
235
+ const present = probeMacosKeychainGenericPassword({
236
+ service,
237
+ securityRunner,
238
+ env,
239
+ });
240
+ if (!present) continue;
241
+
242
+ // Existence-only probe: do not read secrets or infer paid tier.
243
+ return {
244
+ tool: "claude",
245
+ provider: "anthropic",
246
+ product: "credentials",
247
+ planType: "present",
248
+ };
249
+ }
250
+ return null;
251
+ }
252
+
253
+ if (!usesClaudeCodeCredentialsFile(platform)) return null;
254
+
255
+ // Linux/Windows: credentials live in the .credentials.json file (mode 0600 on
256
+ // Linux; user-profile ACLs on Windows). Existence-only: just check that the
257
+ // file is readable and contains the OAuth key.
258
+ const raw = readClaudeCodeCredentialsFile({ home, fsReader });
259
+ if (!raw) return null;
260
+ try {
261
+ const payload = JSON.parse(raw);
262
+ if (payload?.claudeAiOauth && typeof payload.claudeAiOauth === "object") {
263
+ return {
264
+ tool: "claude",
265
+ provider: "anthropic",
266
+ product: "credentials",
267
+ planType: "present",
268
+ };
269
+ }
270
+ } catch (_e) {
271
+ // fall through
272
+ }
273
+ return null;
274
+ }
275
+
276
+ function parseClaudeOauthExpiryMs(value) {
277
+ if (typeof value === "number") {
278
+ if (!Number.isFinite(value)) return null;
279
+ if (value <= 0) return 0;
280
+ return value < 1e12 ? value * 1000 : value;
281
+ }
282
+ if (typeof value === "string") {
283
+ const trimmed = value.trim();
284
+ if (!trimmed) return null;
285
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) return parseClaudeOauthExpiryMs(Number(trimmed));
286
+ const ms = Date.parse(trimmed);
287
+ return Number.isFinite(ms) ? ms : null;
288
+ }
289
+ return null;
290
+ }
291
+
292
+ function extractClaudeCodeOauth(payload, nowMs = Date.now()) {
293
+ const oauth = payload?.claudeAiOauth;
294
+ const accessToken = normalizeString(oauth?.accessToken);
295
+ if (!accessToken) return null;
296
+ const expiresAtMs = parseClaudeOauthExpiryMs(oauth?.expiresAt);
297
+ if (expiresAtMs != null && expiresAtMs <= nowMs + CLAUDE_TOKEN_EXPIRY_SKEW_MS) return null;
298
+ return { accessToken, expiresAtMs };
299
+ }
300
+
301
+ function extractClaudeKeychainSubscription(payload) {
302
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
303
+
304
+ const oauth = payload.claudeAiOauth;
305
+ if (!oauth || typeof oauth !== "object" || Array.isArray(oauth)) return null;
306
+
307
+ const subscriptionType = normalizeScalarToString(oauth.subscriptionType);
308
+ const rateLimitTier = normalizeScalarToString(oauth.rateLimitTier);
309
+
310
+ if (!subscriptionType) return null;
311
+ return { subscriptionType, rateLimitTier };
312
+ }
313
+
314
+ function detectClaudeCodeSubscriptionDetails({ platform = process.platform, securityRunner, home, fsReader, env } = {}) {
315
+ const rawPayloads = [];
316
+ if (platform === "darwin") {
317
+ for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
318
+ const raw = readMacosKeychainPassword({ service, securityRunner, env });
319
+ if (raw) rawPayloads.push(raw);
320
+ }
321
+ } else if (usesClaudeCodeCredentialsFile(platform)) {
322
+ const raw = readClaudeCodeCredentialsFile({ home, fsReader });
323
+ if (raw) rawPayloads.push(raw);
324
+ } else {
325
+ return null;
326
+ }
327
+
328
+ for (const raw of rawPayloads) {
329
+ let payload;
330
+ try {
331
+ payload = JSON.parse(raw);
332
+ } catch (_e) {
333
+ continue;
334
+ }
335
+
336
+ const info = extractClaudeKeychainSubscription(payload);
337
+ if (!info) continue;
338
+
339
+ return {
340
+ tool: "claude",
341
+ provider: "anthropic",
342
+ product: "subscription",
343
+ planType: info.subscriptionType,
344
+ rateLimitTier: info.rateLimitTier,
345
+ };
346
+ }
347
+
348
+ return null;
349
+ }
350
+
351
+ async function collectLocalSubscriptions({
352
+ home = os.homedir(),
353
+ env = process.env,
354
+ platform = process.platform,
355
+ securityRunner,
356
+ probeKeychain = false,
357
+ probeKeychainDetails = false,
358
+ } = {}) {
359
+ const out = [];
360
+
361
+ const codex = await detectCodexChatgptSubscription({ home, env });
362
+ if (codex) out.push(codex);
363
+
364
+ const opencode = await detectOpencodeChatgptSubscription({ home, env });
365
+ if (opencode) out.push(opencode);
366
+
367
+ if (probeKeychainDetails) {
368
+ const claude = detectClaudeCodeSubscriptionDetails({ platform, securityRunner, home, env });
369
+ if (claude) out.push(claude);
370
+ else if (probeKeychain) {
371
+ const present = detectClaudeCodeCredentialsPresence({ platform, securityRunner, home, env });
372
+ if (present) out.push(present);
373
+ }
374
+ } else if (probeKeychain) {
375
+ const claude = detectClaudeCodeCredentialsPresence({ platform, securityRunner, home, env });
376
+ if (claude) out.push(claude);
377
+ }
378
+
379
+ const openclaw = await detectOpenclawSessionIntegration({ home, env });
380
+ if (openclaw) out.push(openclaw);
381
+
382
+ // Gemini: no stable local subscription/tier signal found yet.
383
+ return out;
384
+ }
385
+
386
+ async function detectOpenclawSessionIntegration({ home, env }) {
387
+ const { trackerDir } = await resolveTrackerPaths({ home });
388
+ let state = null;
389
+ try {
390
+ state = await probeOpenclawSessionPluginState({ home, trackerDir, env });
391
+ } catch (_err) {
392
+ return null;
393
+ }
394
+
395
+ if (!state?.configured) return null;
396
+
397
+ return {
398
+ tool: "openclaw",
399
+ provider: "openclaw",
400
+ product: "session_plugin",
401
+ planType: "enabled",
402
+ };
403
+ }
404
+
405
+ // Returns the live OAuth token plus its expiry stamp. The expiry doubles as a
406
+ // rotation marker for the 429 cool-down: it changes on every refresh and, unlike
407
+ // the token itself, is not a secret, so nothing derived from a credential has to
408
+ // be written to disk.
409
+ function readClaudeCodeOauthToken({
410
+ platform = process.platform,
411
+ securityRunner,
412
+ home,
413
+ fsReader,
414
+ env,
415
+ nowMs = Date.now(),
416
+ } = {}) {
417
+ if (platform === "darwin") {
418
+ for (const service of CLAUDE_CODE_KEYCHAIN_SERVICES) {
419
+ try {
420
+ const raw = readMacosKeychainPassword({ service, securityRunner, env });
421
+ if (!raw) continue;
422
+ const oauth = extractClaudeCodeOauth(JSON.parse(raw), nowMs);
423
+ if (oauth) return oauth;
424
+ } catch (_e) {
425
+ continue;
426
+ }
427
+ }
428
+ return null;
429
+ }
430
+
431
+ if (!usesClaudeCodeCredentialsFile(platform)) return null;
432
+
433
+ // Linux/Windows: Claude Code stores the OAuth payload as a JSON file
434
+ // (mode 0600 on Linux; user-profile ACLs on Windows).
435
+ const raw = readClaudeCodeCredentialsFile({ home, fsReader });
436
+ if (!raw) return null;
437
+ try {
438
+ return extractClaudeCodeOauth(JSON.parse(raw), nowMs);
439
+ } catch (_e) {
440
+ return null;
441
+ }
442
+ }
443
+
444
+ function readClaudeCodeAccessToken(options = {}) {
445
+ return readClaudeCodeOauthToken(options)?.accessToken ?? null;
446
+ }
447
+
448
+ async function readCodexAccessToken({ home, env } = {}) {
449
+ try {
450
+ const codexHome = resolveCodexHome({ home, env });
451
+ const authPath = path.join(codexHome, "auth.json");
452
+ const auth = await readJson(authPath);
453
+ return normalizeString(auth?.tokens?.access_token);
454
+ } catch (_e) {
455
+ return null;
456
+ }
457
+ }
458
+
459
+ // Returns the access token + ChatGPT account id + plan type + auth.json path so callers can
460
+ // also trigger a refresh if the tokens are stale (issue #52: stale tokens → wham 401 →
461
+ // "Fetch failed" error after ~7-8 days of not running `codex`).
462
+ async function readCodexAuthBundle({ home, env } = {}) {
463
+ try {
464
+ const codexHome = resolveCodexHome({ home, env });
465
+ const authPath = path.join(codexHome, "auth.json");
466
+ const auth = await readJson(authPath);
467
+ if (!auth || typeof auth !== "object") return null;
468
+
469
+ const accessToken = normalizeString(auth?.tokens?.access_token);
470
+ if (!accessToken) return null;
471
+
472
+ const accessPayload = decodeJwtPayload(auth?.tokens?.access_token);
473
+ const idPayload = decodeJwtPayload(auth?.tokens?.id_token);
474
+ const accountId =
475
+ normalizeString(auth?.tokens?.account_id) ||
476
+ normalizeString(extractOpenAiAuthNamespace(accessPayload)?.chatgpt_account_id) ||
477
+ normalizeString(extractOpenAiAuthNamespace(idPayload)?.chatgpt_account_id) ||
478
+ null;
479
+
480
+ const accessInfo = extractChatgptSubscriptionFromPayload(accessPayload);
481
+ const idInfo = extractChatgptSubscriptionFromPayload(idPayload);
482
+ const merged = mergeSubscription(accessInfo, idInfo);
483
+ const planType = merged?.planType ? merged.planType.toLowerCase() : null;
484
+
485
+ return {
486
+ accessToken,
487
+ accountId,
488
+ planType,
489
+ refreshToken: normalizeString(auth?.tokens?.refresh_token) || null,
490
+ lastRefresh: normalizeString(auth?.last_refresh) || null,
491
+ authPath,
492
+ authJson: auth,
493
+ };
494
+ } catch (_e) {
495
+ return null;
496
+ }
497
+ }
498
+
499
+ module.exports = {
500
+ resolveClaudeKeychainAccount,
501
+ collectLocalSubscriptions,
502
+ detectClaudeCodeCredentialsPresence,
503
+ detectClaudeCodeSubscriptionDetails,
504
+ readClaudeCodeAccessToken,
505
+ readClaudeCodeOauthToken,
506
+ readCodexAccessToken,
507
+ readCodexAuthBundle,
508
+ };