@indigoai-us/hq-cli 5.345.263 → 5.345.267

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 (83) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-grant.sh +4 -48
  3. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +16 -10
  4. package/assets/scaffold/core/scripts/hq-delegate-send.sh +17 -1
  5. package/contracts/host-canary-release.json +7 -7
  6. package/dist/command-catalog.generated.d.ts +67 -1
  7. package/dist/command-catalog.generated.js +83 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/bot.d.ts +2 -0
  11. package/dist/commands/bot.js +4 -3
  12. package/dist/commands/core-delegate-w1b.js +21 -40
  13. package/dist/commands/core-delegate.js +11 -8
  14. package/dist/commands/files-browse.d.ts +83 -4
  15. package/dist/commands/files-browse.js +404 -54
  16. package/dist/commands/groups.js +2 -2
  17. package/dist/commands/skill.js +15 -0
  18. package/dist/commands/sync-held.d.ts +11 -0
  19. package/dist/commands/sync-held.js +65 -1
  20. package/dist/commands/sync-telemetry-report.d.ts +5 -0
  21. package/dist/commands/sync-telemetry-report.js +239 -0
  22. package/dist/commands/sync-telemetry.d.ts +47 -0
  23. package/dist/commands/sync-telemetry.js +309 -0
  24. package/dist/index.js +107 -43
  25. package/dist/lib/agent-kit/mcp/tools.js +2 -2
  26. package/dist/lib/agent-kit/skills.js +12 -6
  27. package/dist/lib/bot/runnable.d.ts +17 -7
  28. package/dist/lib/bot/runnable.js +17 -10
  29. package/dist/lib/capacity/available.js +6 -2
  30. package/dist/lib/capacity/collectors/claude-oauth.d.ts +10 -256
  31. package/dist/lib/capacity/collectors/claude-oauth.js +19 -1078
  32. package/dist/lib/capacity/ledger.d.ts +12 -1
  33. package/dist/lib/capacity/ledger.js +15 -5
  34. package/dist/lib/capacity/route.d.ts +2 -0
  35. package/dist/lib/capacity/route.js +21 -4
  36. package/dist/lib/capacity/scheduler.js +2 -3
  37. package/dist/lib/capacity/sign-in.js +4 -4
  38. package/dist/lib/daemon/merge-sections.d.ts +44 -9
  39. package/dist/lib/daemon/merge-sections.js +234 -37
  40. package/dist/lib/daemon/ops/skill-command.d.ts +2 -0
  41. package/dist/lib/daemon/ops/skill-command.js +7 -1
  42. package/dist/lib/daemon/run.js +1 -0
  43. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +2 -1
  44. package/dist/lib/doctor/checks/antigravity-wiring.js +75 -3
  45. package/dist/lib/doctor/checks/hook-engine.d.ts +2 -0
  46. package/dist/lib/doctor/checks/hook-engine.js +100 -1
  47. package/dist/lib/doctor/checks/host-core.d.ts +1 -1
  48. package/dist/lib/doctor/checks/host-core.js +19 -7
  49. package/dist/lib/doctor/fix/process-identity.d.ts +2 -0
  50. package/dist/lib/doctor/fix/process-identity.js +5 -2
  51. package/dist/lib/hook-engine/coverage.d.ts +19 -10
  52. package/dist/lib/hook-engine/coverage.js +116 -25
  53. package/dist/lib/hook-engine/native-precompact-compatibility.json +8 -1
  54. package/dist/lib/hook-engine/native-stop-compatibility.json +8 -4
  55. package/dist/lib/hook-engine/reconcile.js +60 -2
  56. package/dist/lib/install/antigravity-targets.d.ts +22 -0
  57. package/dist/lib/install/antigravity-targets.js +82 -0
  58. package/dist/lib/signals/reply.js +25 -5
  59. package/dist/lib/signals/steps/extract.d.ts +28 -4
  60. package/dist/lib/signals/steps/extract.js +124 -10
  61. package/dist/lib/sync-core/release.d.ts +1 -1
  62. package/dist/lib/sync-core/release.js +2 -2
  63. package/dist/main.js +8 -3
  64. package/dist/sentry-init.d.ts +7 -1
  65. package/dist/sentry-init.js +6 -2
  66. package/dist/sentry.d.ts +7 -0
  67. package/dist/sentry.js +16 -1
  68. package/dist/started-version.d.ts +13 -0
  69. package/dist/started-version.js +34 -0
  70. package/dist/startup-registration.d.ts +9 -9
  71. package/dist/startup-registration.js +42 -18
  72. package/dist/utils/client-health.d.ts +1 -0
  73. package/dist/utils/client-health.js +54 -11
  74. package/dist/utils/core-next-kill.d.ts +9 -0
  75. package/dist/utils/core-next-kill.js +22 -0
  76. package/dist/utils/host-registration.d.ts +4 -2
  77. package/dist/utils/host-registration.js +55 -7
  78. package/dist/utils/install-tree-recovery-markers.d.ts +45 -0
  79. package/dist/utils/install-tree-recovery-markers.js +70 -0
  80. package/dist/utils/install-tree-torn.d.ts +102 -5
  81. package/dist/utils/install-tree-torn.js +199 -2
  82. package/dist/utils/sentry-fingerprint.js +3 -0
  83. package/package.json +7 -7
@@ -8,22 +8,9 @@
8
8
  * header. This module does not invoke the claude CLI except
9
9
  * `claude --version` when the caller does not pass cliVersion.
10
10
  *
11
- * US-014 wires in a token-refresh gate. The gate uses two seams,
12
- * `defaultListLiveLanes` and `defaultListProcesses`, to decide whether a
13
- * refresh is safe (no running Claude Code holds the home). Both seams
14
- * FAIL CLOSED: an error, a timeout, or an unexpected JSON shape returns an
15
- * error-signalling throw and the caller records `skipped-live` /
16
- * `skipped-process` and does NOT rotate the refresh token.
17
- *
18
- * Residual blind spot on darwin: `ps -axo pid=,command=` cannot read a
19
- * child process's environment, so on darwin a running `claude` process is
20
- * conservatively treated as holding the DEFAULT home AND blocking any
21
- * non-default home refresh. A sibling that sets `CLAUDE_CONFIG_DIR` to a
22
- * different home still blocks the gate; this is the safe side of the
23
- * precision/safety tradeoff. On linux `/proc/<pid>/environ` lets the gate
24
- * read the per-process `CLAUDE_CONFIG_DIR`, so it only blocks the matching
25
- * home. Windows and other platforms get no process gate; the lane gate is
26
- * authoritative there.
11
+ * It never refreshes a token. Claude refresh tokens are single use, so a
12
+ * refresh from here raced Claude Code's own refresh and signed accounts out.
13
+ * An expired access token is reported as expired until Claude Code renews it.
27
14
  *
28
15
  * The legacy shape (seven_day_opus populated, no limits[]) is drift.
29
16
  * observedAt is the response time. One collect appends every account's
@@ -34,9 +21,8 @@ import * as crypto from "node:crypto";
34
21
  import * as fs from "node:fs";
35
22
  import * as os from "node:os";
36
23
  import * as path from "node:path";
37
- import { DIR_MODE, FILE_MODE, appendReadings, capacityRoot, EXPIRED_REASON, SIGN_IN_REVOKED_REASON, readCollectorMark, redactProviderTokens, } from "../ledger.js";
24
+ import { DIR_MODE, FILE_MODE, appendReadings, capacityRoot, CLAUDE_EXPIRED_REASON, SIGN_IN_REVOKED_REASON, readCollectorMark, } from "../ledger.js";
38
25
  import { hashClaudeAccountId } from "./claude-statusline.js";
39
- import { REMOTE_LANE_READ_ENV } from "../../lanes/outpost-dispatch.js";
40
26
  export const CLAUDE_OAUTH_PARSER_VERSION = "claude-oauth-usage.1";
41
27
  export const CLAUDE_OAUTH_PROVIDER = "claude";
42
28
  export const CLAUDE_OAUTH_SOURCE = "oauth-usage";
@@ -59,20 +45,13 @@ export const CLAUDE_OAUTH_FETCH_TIMEOUT_MS = 10_000;
59
45
  export const CLAUDE_OAUTH_SECURITY_TIMEOUT_MS = 5_000;
60
46
  export const CLAUDE_OAUTH_POLL_FILE = "claude-oauth-last-call.json";
61
47
  export const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials";
62
- /** Claude Code's refresh endpoint. The URL and the client_id are the ones Claude Code itself posts. */
63
- export const CLAUDE_OAUTH_REFRESH_URL = "https://console.anthropic.com/v1/oauth/token";
64
- export const CLAUDE_OAUTH_REFRESH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
65
- /** Minimum gap between refresh attempts for one home when the previous attempt did not revoke. */
66
- export const CLAUDE_OAUTH_REFRESH_BACKOFF_MS = 10 * 60 * 1000;
67
- /** Minimum gap between refresh attempts for one home after an invalid_grant. */
68
- export const CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS = 60 * 60 * 1000;
69
- /** Try a refresh when the token is this close to expiry, so one tick does not land on a stale token. */
70
- export const CLAUDE_OAUTH_REFRESH_PREFLIGHT_MS = 10 * 60 * 1000;
71
48
  /**
72
- * Claude refresh tokens are single use. A refresh the server completed but whose
73
- * response we abandoned leaves the stored token dead, so this limit is generous.
49
+ * A token this close to expiry is treated as expired and not sent. A usage
50
+ * 401 marks the account revoked; a token sent in its last seconds (or under
51
+ * clock skew) could be refused while its refresh token still works, and the
52
+ * collector would sign out a healthy account.
74
53
  */
75
- export const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 30_000;
54
+ export const CLAUDE_OAUTH_EXPIRY_SKEW_MS = 2 * 60 * 1000;
76
55
  export const CLAUDE_OAUTH_REFRESH_LAST_FILE = "claude-oauth-refresh-last.json";
77
56
  const SESSION_MINUTES = 5 * 60;
78
57
  const WEEKLY_MINUTES = 7 * 24 * 60;
@@ -222,10 +201,7 @@ function resetMeta(context, credits) {
222
201
  return event;
223
202
  }
224
203
  export async function collectClaudeOAuth(inputOptions = {}) {
225
- const options = {
226
- ...inputOptions,
227
- listLiveLanes: memoizeListLiveLanes(inputOptions.listLiveLanes ?? defaultListLiveLanes),
228
- };
204
+ const options = inputOptions;
229
205
  const ledger = ledgerOptions(options);
230
206
  const root = ledger.root ?? capacityRoot(ledger.env, ledger.home);
231
207
  const scoped = { ...ledger, root };
@@ -308,7 +284,7 @@ export async function collectClaudeOAuth(inputOptions = {}) {
308
284
  continue;
309
285
  writeAccountPoll(root, account.accountId, new Date(nowMs).toISOString());
310
286
  const meta = account.metadata;
311
- let currentToken = account.token;
287
+ const currentToken = account.token;
312
288
  let currentBlocked = account.blocked;
313
289
  // Honour the persisted revoked marker, but only when its fingerprint
314
290
  // matches the refresh token we are about to use. A stale marker means the
@@ -322,37 +298,10 @@ export async function collectClaudeOAuth(inputOptions = {}) {
322
298
  else if (revokedMarker === "stale") {
323
299
  clearAccountRevoked(root, account.accountId);
324
300
  }
325
- const needsRefresh = (currentBlocked === EXPIRED_REASON
326
- || currentBlocked === "unavailable: token_expired"
327
- || shouldAttemptRefresh(meta.expiresAt, nowMs))
328
- && !!meta.refreshToken
329
- && currentBlocked !== SIGN_IN_REVOKED_REASON;
330
- if (needsRefresh) {
331
- const refreshResult = await maybeRefreshAccount({
332
- options,
333
- root,
334
- home: meta.home,
335
- service: meta.service,
336
- platform: meta.platform,
337
- refreshToken: meta.refreshToken,
338
- expiresAt: meta.expiresAt,
339
- previousDocument: meta.credentialDocument,
340
- nowMs,
341
- });
342
- if (refreshResult?.outcome === "refreshed" && refreshResult.newAccessToken) {
343
- currentToken = refreshResult.newAccessToken;
344
- // A refresh renews the token but does not grant scopes the sign-in
345
- // lacked. Re-check the profile scope before clearing the block.
346
- const refreshedScopes = refreshResult.newScopes && refreshResult.newScopes.length > 0
347
- ? refreshResult.newScopes
348
- : meta.scopes;
349
- currentBlocked = hasProfileScope(refreshedScopes) ? undefined : "unavailable: missing_scope";
350
- }
351
- else if (refreshResult?.outcome === "revoked" || refreshResult?.outcome === "skipped-revoked") {
352
- currentBlocked = SIGN_IN_REVOKED_REASON;
353
- markAccountRevoked(root, account.accountId, nowMs, meta.refreshToken);
354
- }
355
- }
301
+ // No token refresh here. Claude refresh tokens are single use, so a
302
+ // refresh from this collector raced Claude Code's own refresh and signed
303
+ // accounts out. An expired access token stays reported as expired until
304
+ // Claude Code renews it the next time it runs on this account.
356
305
  if (currentBlocked) {
357
306
  failures.push(failure(mapContext, credentialBlockReason(currentBlocked)));
358
307
  continue;
@@ -485,48 +434,8 @@ async function collectEnumeratedClaude(options, scoped, root, clock, cliVersion)
485
434
  else if (enumRevokedMarker === "stale") {
486
435
  clearAccountRevoked(root, account.accountId);
487
436
  }
488
- // Refresh gate: fire before the usage fetch when the stored token is
489
- // expired or close to expiry. Successful refresh clears the block and
490
- // lets the usage fetch proceed with the new token.
491
- const needsRefresh = (account.blocked === EXPIRED_REASON
492
- || account.blocked === "unavailable: token_expired"
493
- || shouldAttemptRefresh(account.expiresAt, nowMs))
494
- && account.refreshToken
495
- && account.blocked !== SIGN_IN_REVOKED_REASON;
496
- if (needsRefresh) {
497
- const refreshResult = await maybeRefreshAccount({
498
- options,
499
- root,
500
- home,
501
- service: account.service,
502
- platform: account.platform,
503
- refreshToken: account.refreshToken,
504
- expiresAt: account.expiresAt,
505
- previousDocument: account.credentialDocument,
506
- nowMs,
507
- });
508
- if (refreshResult) {
509
- if (refreshResult.outcome === "refreshed" && refreshResult.newAccessToken) {
510
- account.token = refreshResult.newAccessToken;
511
- if (refreshResult.newExpiresAt !== undefined)
512
- account.expiresAt = refreshResult.newExpiresAt;
513
- if (refreshResult.newRefreshToken)
514
- account.refreshToken = refreshResult.newRefreshToken;
515
- if (refreshResult.newScopes && refreshResult.newScopes.length > 0)
516
- account.scopes = refreshResult.newScopes;
517
- // A refresh renews the token but does not grant scopes the sign-in
518
- // lacked. Re-check the profile scope before clearing the block.
519
- account.blocked = hasProfileScope(account.scopes)
520
- ? null
521
- : credentialBlockReason("unavailable: missing_scope");
522
- }
523
- else if (refreshResult.outcome === "revoked" || refreshResult.outcome === "skipped-revoked") {
524
- account.blocked = SIGN_IN_REVOKED_REASON;
525
- markAccountRevoked(root, account.accountId, nowMs, account.refreshToken);
526
- }
527
- // Other outcomes (skipped-live/process/race/backoff, error) keep whatever block the parser set.
528
- }
529
- }
437
+ // No token refresh here; see collectClaudeOAuth. An expired access token
438
+ // stays expired until Claude Code renews it on its next run.
530
439
  if (account.blocked) {
531
440
  failures.push(failure(mapContext, account.blocked));
532
441
  continue;
@@ -749,7 +658,7 @@ function credentialBlockReason(blocked) {
749
658
  if (blocked.startsWith("signed out:") || blocked.startsWith("expired:"))
750
659
  return blocked;
751
660
  if (blocked === "unavailable: token_expired")
752
- return EXPIRED_REASON;
661
+ return CLAUDE_EXPIRED_REASON;
753
662
  if (blocked === "unavailable: missing_scope")
754
663
  return "signed out: missing profile scope";
755
664
  if (blocked === "unavailable: auth")
@@ -1143,7 +1052,7 @@ function isExpired(expiresAt, nowMs) {
1143
1052
  if (expiresAt === null)
1144
1053
  return false;
1145
1054
  const ms = expiresAt < 1e12 ? expiresAt * 1000 : expiresAt;
1146
- return ms <= nowMs;
1055
+ return ms <= nowMs + CLAUDE_OAUTH_EXPIRY_SKEW_MS;
1147
1056
  }
1148
1057
  function classifySecurity(result) {
1149
1058
  if (result.timedOut)
@@ -1631,17 +1540,6 @@ export function readClaudeRefreshLast(root, home) {
1631
1540
  const file = readRefreshLast(root);
1632
1541
  return file.homes[refreshLastKey(home)] ?? null;
1633
1542
  }
1634
- function refreshInBackoff(entry, nowMs) {
1635
- if (!entry || !entry.backoffUntil)
1636
- return false;
1637
- const at = Date.parse(entry.backoffUntil);
1638
- return !Number.isNaN(at) && nowMs < at;
1639
- }
1640
- function refreshTokenPersistentlyRevoked(file, token) {
1641
- if (!token)
1642
- return false;
1643
- return Object.prototype.hasOwnProperty.call(file.revokedTokens, tokenFingerprint(token));
1644
- }
1645
1543
  function markAccountRevoked(root, accountId, nowMs, refreshToken) {
1646
1544
  const file = readRefreshLast(root);
1647
1545
  const entry = { at: new Date(nowMs).toISOString() };
@@ -1697,961 +1595,4 @@ export function revokedMarkerForCurrentCredential(root, accountId, refreshToken)
1697
1595
  return "match";
1698
1596
  return entry.fingerprint === tokenFingerprint(refreshToken) ? "match" : "stale";
1699
1597
  }
1700
- const defaultRefreshFetch = async (url, init) => {
1701
- const response = await fetch(url, init);
1702
- return {
1703
- status: response.status,
1704
- text: () => response.text(),
1705
- headers: { get: (name) => response.headers.get(name) },
1706
- };
1707
- };
1708
- const defaultWriteClaudeCredentials = async (request) => {
1709
- if (request.platform === "darwin") {
1710
- const username = os.userInfo().username;
1711
- const spawnOpts = {
1712
- encoding: "utf8",
1713
- timeout: CLAUDE_OAUTH_SECURITY_TIMEOUT_MS,
1714
- windowsHide: true,
1715
- };
1716
- // Try the strict selector first; fall back to -s only. Record which selector found
1717
- // the item so the write uses the SAME selector and does not create a second entry.
1718
- let selector = null;
1719
- let preRead = spawnSync("security", ["find-generic-password", "-s", request.service, "-a", username, "-w"], spawnOpts);
1720
- const firstReadStatus = preRead.status;
1721
- if (preRead.status === 0) {
1722
- selector = "sa";
1723
- }
1724
- else {
1725
- preRead = spawnSync("security", ["find-generic-password", "-s", request.service, "-w"], spawnOpts);
1726
- if (preRead.status === 0)
1727
- selector = "s";
1728
- }
1729
- if (selector !== null && typeof preRead.stdout === "string") {
1730
- try {
1731
- const parsed = JSON.parse(preRead.stdout.replace(/\n$/, ""));
1732
- const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" && !Array.isArray(parsed.claudeAiOauth)
1733
- ? parsed.claudeAiOauth
1734
- : null;
1735
- const current = oauth
1736
- ? (typeof oauth.refreshToken === "string" ? oauth.refreshToken : (typeof oauth.refresh_token === "string" ? oauth.refresh_token : null))
1737
- : null;
1738
- if (request.previousRefreshToken && current && current !== request.previousRefreshToken) {
1739
- return { ok: false, raceDetected: true };
1740
- }
1741
- }
1742
- catch {
1743
- if (request.previousRefreshToken)
1744
- return { ok: false, raceDetected: true };
1745
- }
1746
- }
1747
- else if (firstReadStatus === 44 && preRead.status === 44) {
1748
- // Both selectors confirmed the item does not exist (exit 44), so there is
1749
- // nothing to race with or duplicate. The endpoint has already rotated the
1750
- // refresh token; writing it keeps the only valid token instead of losing it.
1751
- selector = "sa";
1752
- }
1753
- else if (request.previousRefreshToken) {
1754
- // Unreadable for another reason (timeout, prompt, locked Keychain). Writing
1755
- // blind could duplicate the item or clobber a newer token, so fail closed.
1756
- return { ok: false, raceDetected: true };
1757
- }
1758
- const body = JSON.stringify(request.document);
1759
- // `security add-generic-password` only takes the secret as `-w <value>`
1760
- // on argv, so the credential JSON is visible to `ps` for the duration of
1761
- // this call. Claude Code writes its own Keychain item the same way; this
1762
- // matches that exposure rather than adding a new one.
1763
- const writeArgs = selector === "s"
1764
- ? ["add-generic-password", "-U", "-s", request.service, "-w", body]
1765
- : ["add-generic-password", "-U", "-s", request.service, "-a", username, "-w", body];
1766
- const wrote = spawnSync("security", writeArgs, spawnOpts);
1767
- if (wrote.status !== 0) {
1768
- const message = redactProviderTokens(`security add-generic-password exit ${wrote.status}: ${wrote.stderr ?? ""}`);
1769
- return { ok: false, error: message };
1770
- }
1771
- return { ok: true };
1772
- }
1773
- const file = path.join(request.home, ".credentials.json");
1774
- let current = null;
1775
- try {
1776
- const text = fs.readFileSync(file, "utf8");
1777
- const parsed = JSON.parse(text);
1778
- const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" && !Array.isArray(parsed.claudeAiOauth)
1779
- ? parsed.claudeAiOauth
1780
- : null;
1781
- current = oauth
1782
- ? (typeof oauth.refreshToken === "string" ? oauth.refreshToken : (typeof oauth.refresh_token === "string" ? oauth.refresh_token : null))
1783
- : null;
1784
- }
1785
- catch {
1786
- // no prior file is fine, we are writing anew
1787
- }
1788
- if (request.previousRefreshToken && current && current !== request.previousRefreshToken) {
1789
- return { ok: false, raceDetected: true };
1790
- }
1791
- try {
1792
- fs.mkdirSync(request.home, { recursive: true, mode: 0o700 });
1793
- const body = `${JSON.stringify(request.document, null, 2)}\n`;
1794
- const tmp = path.join(request.home, `.credentials.json.${process.pid}.tmp`);
1795
- fs.writeFileSync(tmp, body, { mode: 0o600 });
1796
- fs.renameSync(tmp, file);
1797
- try {
1798
- fs.chmodSync(file, 0o600);
1799
- }
1800
- catch {
1801
- // best-effort on a filesystem that does not honour chmod
1802
- }
1803
- return { ok: true };
1804
- }
1805
- catch (error) {
1806
- const message = redactProviderTokens(error instanceof Error ? error.message : "write credentials failed");
1807
- return { ok: false, error: message };
1808
- }
1809
- };
1810
- function refreshTokenFromDocumentText(text) {
1811
- let parsed;
1812
- try {
1813
- parsed = JSON.parse(text.replace(/\n$/, ""));
1814
- }
1815
- catch {
1816
- // Unparseable item: report it as unreadable so the caller does not act on it.
1817
- return undefined;
1818
- }
1819
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1820
- return undefined;
1821
- const oauth = parsed.claudeAiOauth;
1822
- if (!oauth || typeof oauth !== "object" || Array.isArray(oauth))
1823
- return null;
1824
- const record = oauth;
1825
- if (typeof record.refreshToken === "string")
1826
- return record.refreshToken;
1827
- if (typeof record.refresh_token === "string")
1828
- return record.refresh_token;
1829
- return null;
1830
- }
1831
- const defaultReadStoredRefreshToken = (request) => {
1832
- if (request.platform === "darwin") {
1833
- const username = os.userInfo().username;
1834
- const spawnOpts = { encoding: "utf8", timeout: CLAUDE_OAUTH_SECURITY_TIMEOUT_MS, windowsHide: true };
1835
- for (const args of [
1836
- ["find-generic-password", "-s", request.service, "-a", username, "-w"],
1837
- ["find-generic-password", "-s", request.service, "-w"],
1838
- ]) {
1839
- const read = spawnSync("security", args, spawnOpts);
1840
- if (read.status === 0 && typeof read.stdout === "string")
1841
- return refreshTokenFromDocumentText(read.stdout);
1842
- }
1843
- return undefined;
1844
- }
1845
- try {
1846
- return refreshTokenFromDocumentText(fs.readFileSync(path.join(request.home, ".credentials.json"), "utf8"));
1847
- }
1848
- catch {
1849
- // Missing or unreadable file: unknown, so the caller keeps its own judgement.
1850
- return undefined;
1851
- }
1852
- };
1853
- const HQ_CLI_PACKAGE_NAME = "@indigoai-us/hq-cli";
1854
- const LOADER_FLAGS_WITH_VALUE = new Set(["--import", "--loader", "--experimental-loader", "--require", "-r", "--conditions", "-C"]);
1855
- const LOADER_FLAGS_BARE = new Set(["--experimental-strip-types", "--experimental-transform-types"]);
1856
- /**
1857
- * Node flags that load a TypeScript runner (tsx and similar). A dev run of the TS
1858
- * source needs them again in the child or `node src/index.ts` fails; compiled `.js`
1859
- * entries get none. Other exec flags (`--inspect`, memory limits) are not copied.
1860
- */
1861
- function loaderArgsForSource(entry, execArgv) {
1862
- if (!/\.(?:[cm]?ts|tsx)$/.test(entry))
1863
- return [];
1864
- const out = [];
1865
- for (let i = 0; i < execArgv.length; i += 1) {
1866
- const arg = execArgv[i];
1867
- const eq = arg.indexOf("=");
1868
- const flag = eq === -1 ? arg : arg.slice(0, eq);
1869
- if (LOADER_FLAGS_BARE.has(arg)) {
1870
- out.push(arg);
1871
- continue;
1872
- }
1873
- if (!LOADER_FLAGS_WITH_VALUE.has(flag))
1874
- continue;
1875
- if (eq !== -1) {
1876
- out.push(arg);
1877
- }
1878
- else if (i + 1 < execArgv.length) {
1879
- out.push(arg, execArgv[i + 1]);
1880
- i += 1;
1881
- }
1882
- }
1883
- return out;
1884
- }
1885
- /**
1886
- * How to re-invoke the running hq CLI without a PATH lookup. When argv[1] is
1887
- * the entry of an installed hq-cli package, run it with the same node binary;
1888
- * the collector runs under launchd and lane workers where PATH may be empty.
1889
- * Falls back to `hq` on PATH when this process is not the hq CLI (tests,
1890
- * embedders). Exported for tests.
1891
- */
1892
- export function resolveHqInvocation(argv = process.argv, execPath = process.execPath, execArgv = process.execArgv) {
1893
- const entry = argv[1];
1894
- if (entry) {
1895
- try {
1896
- const real = fs.realpathSync(entry);
1897
- let dir = path.dirname(real);
1898
- for (let depth = 0; depth < 4; depth += 1) {
1899
- const manifest = path.join(dir, "package.json");
1900
- if (fs.existsSync(manifest)) {
1901
- const parsed = JSON.parse(fs.readFileSync(manifest, "utf8"));
1902
- if (parsed.name === HQ_CLI_PACKAGE_NAME) {
1903
- return { command: execPath, args: [...loaderArgsForSource(real, execArgv), real] };
1904
- }
1905
- break;
1906
- }
1907
- const parent = path.dirname(dir);
1908
- if (parent === dir)
1909
- break;
1910
- dir = parent;
1911
- }
1912
- }
1913
- catch {
1914
- // Unresolvable entry: fall through to the PATH lookup below.
1915
- }
1916
- }
1917
- return { command: "hq", args: [] };
1918
- }
1919
- /** Output cap for the `hq ... --json` reads behind the refresh gates. */
1920
- const HQ_JSON_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
1921
- const HQ_JSON_TIMEOUT_MS = 30_000;
1922
- /**
1923
- * Run `hq ... --json` and parse stdout. Async on purpose: the collector runs inside the mesh
1924
- * daemon, and a synchronous read that takes 15-30 s on a loaded machine froze the daemon's
1925
- * event loop (MQTT keepalive, owner heartbeat) for the whole read.
1926
- * Exported for tests; `invocation` defaults to {@link resolveHqInvocation}.
1927
- */
1928
- export function execHqJson(args, invocation = resolveHqInvocation(), env = process.env) {
1929
- const label = `hq ${args.join(" ")}`;
1930
- return new Promise((resolve, reject) => {
1931
- execFile(invocation.command, [...invocation.args, ...args], {
1932
- env,
1933
- encoding: "utf8",
1934
- // The lane list takes ~2.5 s on an idle machine and grows with lane history. Under heavy
1935
- // load (load average ~95 on 18 cores) the same read took 16-18 s, so 15 s still failed the
1936
- // gate closed on every collect and every Claude home stayed expired.
1937
- timeout: HQ_JSON_TIMEOUT_MS,
1938
- // `hq runners list --json` grows with lane history (6.8 MB on a busy machine). The 1 MiB
1939
- // default made the live-lane gate fail closed on every collect.
1940
- maxBuffer: HQ_JSON_MAX_BUFFER_BYTES,
1941
- // SIGTERM can be trapped, and execFile waits for the child to exit before calling back.
1942
- killSignal: "SIGKILL",
1943
- windowsHide: true,
1944
- }, (error, stdout) => {
1945
- if (error) {
1946
- const failure = error;
1947
- const code = failure.code;
1948
- if (code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
1949
- reject(new Error(`${label} output exceeded ${HQ_JSON_MAX_BUFFER_BYTES} bytes`));
1950
- }
1951
- else if (failure.killed) {
1952
- reject(new Error(`${label} timed out`));
1953
- }
1954
- else if (typeof code === "number") {
1955
- reject(new Error(`${label} exit ${code}`));
1956
- }
1957
- else if (failure.signal) {
1958
- reject(new Error(`${label} killed by ${failure.signal}`));
1959
- }
1960
- else {
1961
- reject(new Error(`${label} failed to spawn: ${failure.message}`));
1962
- }
1963
- return;
1964
- }
1965
- if (!stdout) {
1966
- reject(new Error(`${label} empty stdout`));
1967
- return;
1968
- }
1969
- try {
1970
- resolve(JSON.parse(stdout));
1971
- }
1972
- catch (parseError) {
1973
- reject(new Error(`${label} invalid JSON: ${parseError.message}`));
1974
- }
1975
- });
1976
- });
1977
- }
1978
- /**
1979
- * Parse `hq runners list --json` payload into typed rows.
1980
- * Exported for tests; fail-closed semantics live in defaultListLiveLanes.
1981
- */
1982
- export function parseLanesListPayload(payload) {
1983
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
1984
- throw new Error("lanes list: payload is not an object");
1985
- }
1986
- const lanes = payload.lanes;
1987
- if (!Array.isArray(lanes))
1988
- throw new Error("lanes list: missing lanes array");
1989
- const out = [];
1990
- for (const item of lanes) {
1991
- if (!item || typeof item !== "object" || Array.isArray(item)) {
1992
- throw new Error("lanes list: row is not an object");
1993
- }
1994
- out.push(item);
1995
- }
1996
- return out;
1997
- }
1998
- /**
1999
- * Parse `hq runners accounts list --json` payload into typed rows.
2000
- * Exported for tests; fail-closed semantics live in defaultListLiveLanes.
2001
- */
2002
- export function parseAccountsListPayload(payload) {
2003
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
2004
- throw new Error("lanes accounts list: payload is not an object");
2005
- }
2006
- const accounts = payload.accounts;
2007
- if (!Array.isArray(accounts))
2008
- throw new Error("lanes accounts list: missing accounts array");
2009
- const out = [];
2010
- for (const item of accounts) {
2011
- if (!item || typeof item !== "object" || Array.isArray(item)) {
2012
- throw new Error("lanes accounts list: row is not an object");
2013
- }
2014
- out.push(item);
2015
- }
2016
- return out;
2017
- }
2018
- /**
2019
- * Join lanes rows against accounts rows to produce LiveLane records.
2020
- * Exported for tests.
2021
- */
2022
- export function buildLiveLanesFromPayloads(lanes, accounts) {
2023
- const homeByAccount = new Map();
2024
- for (const acct of accounts) {
2025
- const id = typeof acct.id === "string" ? acct.id : null;
2026
- if (!id)
2027
- continue;
2028
- const effective = typeof acct.effective_home === "string" && acct.effective_home.trim()
2029
- ? acct.effective_home.trim()
2030
- : (typeof acct.home === "string" && acct.home.trim() ? acct.home.trim() : null);
2031
- if (effective)
2032
- homeByAccount.set(id, effective);
2033
- }
2034
- const out = [];
2035
- for (const row of lanes) {
2036
- const state = typeof row.state === "string" ? row.state : "";
2037
- const terminalReason = typeof row.terminal_reason === "string" ? row.terminal_reason : null;
2038
- const detailsObj = row.terminal_details && typeof row.terminal_details === "object" && !Array.isArray(row.terminal_details)
2039
- ? row.terminal_details
2040
- : null;
2041
- const detailAccount = detailsObj && typeof detailsObj.account === "string" ? detailsObj.account : null;
2042
- const detailProvider = detailsObj && typeof detailsObj.provider === "string" ? detailsObj.provider : null;
2043
- const laneAccount = typeof row.account === "string" ? row.account : null;
2044
- const laneProvider = typeof row.provider === "string" ? row.provider : "";
2045
- const isLive = state === "running" || state === "queued" || state === "awaiting_input";
2046
- const isAuthFailed = terminalReason === "provider_auth_failed";
2047
- if (!isLive && !isAuthFailed)
2048
- continue;
2049
- const account = isAuthFailed ? (detailAccount ?? laneAccount) : laneAccount;
2050
- const provider = (isAuthFailed ? (detailProvider ?? laneProvider) : laneProvider) || "claude";
2051
- if (provider !== "claude")
2052
- continue;
2053
- const home = account ? homeByAccount.get(account) ?? null : null;
2054
- out.push({ home, account, provider, state, reason: terminalReason, isLive, isAuthFailed });
2055
- }
2056
- return out;
2057
- }
2058
- /**
2059
- * Fail-closed enumeration of live Claude lanes and auth-failed lanes.
2060
- * Throws on hq call failure or unexpected JSON shape; callers skip the refresh.
2061
- */
2062
- const defaultListLiveLanes = async () => {
2063
- // The gate only needs lanes that use this host's Claude homes. Skip the Outpost mirror
2064
- // refresh (a network round trip per Outpost); cached mirror rows are still listed.
2065
- const env = { ...process.env, [REMOTE_LANE_READ_ENV]: "1" };
2066
- const invocation = resolveHqInvocation();
2067
- const [lanesPayload, accountsPayload] = await Promise.all([
2068
- execHqJson(["runners", "list", "--json"], invocation, env),
2069
- execHqJson(["runners", "accounts", "list", "--json"], invocation, env),
2070
- ]);
2071
- const lanes = parseLanesListPayload(lanesPayload);
2072
- const accounts = parseAccountsListPayload(accountsPayload);
2073
- return buildLiveLanesFromPayloads(lanes, accounts);
2074
- };
2075
- /**
2076
- * Share one lane read across every home in a collect. Without this each expired home ran its
2077
- * own pair of `hq runners ... --json` reads, so one slow machine turned into N timeouts per
2078
- * collect. A failure is shared too: the next home fails closed without waiting again.
2079
- * Exported for tests.
2080
- */
2081
- export function memoizeListLiveLanes(list) {
2082
- let pending = null;
2083
- return () => {
2084
- pending ??= list();
2085
- return pending;
2086
- };
2087
- }
2088
- /**
2089
- * Parse `ps -axo pid=,command=` into rows that mention the `claude` executable.
2090
- * Exported for tests. Returned rows carry `probe: "command-only"` so the gate
2091
- * knows it cannot read per-process CLAUDE_CONFIG_DIR on darwin.
2092
- */
2093
- export function parsePsClaudeOutput(stdout) {
2094
- const out = [];
2095
- const self = process.pid;
2096
- for (const rawLine of stdout.split("\n")) {
2097
- const line = rawLine.replace(/\s+$/, "");
2098
- if (!line)
2099
- continue;
2100
- const match = /^\s*(\d+)\s+(.*)$/.exec(line);
2101
- if (!match)
2102
- continue;
2103
- const pid = Number(match[1]);
2104
- if (!Number.isFinite(pid) || pid === self)
2105
- continue;
2106
- const command = match[2];
2107
- // Match the executable segment only. Avoid "/claude-code/other", "my-claude-wrapper", etc.
2108
- // Accepts: "claude ...", "/usr/local/bin/claude ...", "node .../claude ..."
2109
- const exec = /(?:^|\/|\s)claude(?:$|\s)/.test(command) ? "claude" : null;
2110
- if (!exec)
2111
- continue;
2112
- // Skip our own hq subcommands if any ever shell out to `claude ...`
2113
- if (/\bhq\s+/.test(command))
2114
- continue;
2115
- out.push({ pid, env: {}, probe: "command-only" });
2116
- }
2117
- return out;
2118
- }
2119
- /** Pid to full command line, from `ps -ww -o pid=,command= -p <pids>`. Exported for tests. */
2120
- export function parsePsCommandLines(stdout) {
2121
- const lines = new Map();
2122
- for (const rawLine of stdout.split("\n")) {
2123
- const match = /^\s*(\d+) (.*)$/.exec(rawLine.replace(/\s+$/, ""));
2124
- if (match)
2125
- lines.set(Number(match[1]), match[2]);
2126
- }
2127
- return lines;
2128
- }
2129
- /**
2130
- * Upgrade darwin command-only rows with each process's environment. `ps -wwE` prints a
2131
- * same-user process's command line followed by its environment, unquoted and space separated.
2132
- * Only the text after the exact command line (read separately with `ps -ww`) is treated as the
2133
- * environment, so a prompt argument that mentions CLAUDE_CONFIG_DIR= or HOME= is never read as
2134
- * env. A row becomes `probe: "env"` only when:
2135
- * - the `-E` line starts with the command line plus a space, and the rest starts with NAME=;
2136
- * - CLAUDE_CONFIG_DIR= appears at most once in that rest, and its value is absolute and
2137
- * names an existing directory (the value runs to the next ` NAME=` or the end of line).
2138
- * Anything else stays command-only, which blocks every home. A pid missing from the output
2139
- * is dropped only when it is known to have exited; otherwise it stays command-only.
2140
- * Exported for tests.
2141
- */
2142
- export function parsePsEnvOutput(envStdout, commandLines, rows, options = {}) {
2143
- const isDirectory = options.isDirectory ?? defaultIsDirectory;
2144
- const isAlive = options.isAlive ?? defaultIsAlive;
2145
- const envLines = parsePsCommandLines(envStdout);
2146
- const blocked = (pid) => ({ pid, env: {}, probe: "command-only" });
2147
- const out = [];
2148
- for (const row of rows) {
2149
- const command = commandLines.get(row.pid);
2150
- const line = envLines.get(row.pid);
2151
- if (command === undefined || line === undefined) {
2152
- if (isAlive(row.pid))
2153
- out.push(blocked(row.pid));
2154
- continue;
2155
- }
2156
- if (!line.startsWith(`${command} `)) {
2157
- // No visible env (another user's or a protected process), or the pid was reused.
2158
- out.push(blocked(row.pid));
2159
- continue;
2160
- }
2161
- const env = line.slice(command.length + 1);
2162
- if (!/^[A-Za-z_][A-Za-z0-9_]*=/.test(env)) {
2163
- out.push(blocked(row.pid));
2164
- continue;
2165
- }
2166
- const mentions = env.split("CLAUDE_CONFIG_DIR=").length - 1;
2167
- const match = /(?:^| )CLAUDE_CONFIG_DIR=(.*?)(?= [A-Za-z_][A-Za-z0-9_]*=|$)/.exec(env);
2168
- if (mentions === 0) {
2169
- // The default config dir is HOME/.claude for this process. HOME must be one absolute
2170
- // value; an unset HOME falls back to the collector's own home.
2171
- const homes = [...env.matchAll(/(?:^| )HOME=(.*?)(?= [A-Za-z_][A-Za-z0-9_]*=|$)/g)].map((m) => m[1]);
2172
- if (homes.length === 0) {
2173
- out.push({ pid: row.pid, env: {}, probe: "env" });
2174
- }
2175
- else if (homes.length === 1 && path.isAbsolute(homes[0])) {
2176
- out.push({ pid: row.pid, env: { HOME: homes[0] }, probe: "env" });
2177
- }
2178
- else {
2179
- out.push(blocked(row.pid));
2180
- }
2181
- }
2182
- else if (mentions === 1 && match && path.isAbsolute(match[1]) && isDirectory(match[1])) {
2183
- out.push({ pid: row.pid, env: { CLAUDE_CONFIG_DIR: match[1] }, probe: "env" });
2184
- }
2185
- else {
2186
- out.push(blocked(row.pid));
2187
- }
2188
- }
2189
- return out;
2190
- }
2191
- /** Default config dir of an env-probed process with CLAUDE_CONFIG_DIR unset. Exported for tests. */
2192
- export function processDefaultConfigDir(proc) {
2193
- const home = typeof proc.env.HOME === "string" && path.isAbsolute(proc.env.HOME) ? proc.env.HOME : os.homedir();
2194
- return path.join(home, ".claude");
2195
- }
2196
- function defaultIsAlive(pid) {
2197
- try {
2198
- process.kill(pid, 0);
2199
- return true;
2200
- }
2201
- catch (error) {
2202
- return error.code !== "ESRCH";
2203
- }
2204
- }
2205
- /**
2206
- * Canonical form of a home directory for comparison: symlinks resolved by the OS, and lower
2207
- * case on darwin, where APFS is case-insensitive by default. Null when the path cannot be
2208
- * resolved. Exported for tests.
2209
- */
2210
- export function canonicalHomePath(dir, platform = process.platform) {
2211
- try {
2212
- const real = fs.realpathSync.native(path.resolve(dir));
2213
- return platform === "darwin" ? real.toLowerCase() : real;
2214
- }
2215
- catch {
2216
- return null;
2217
- }
2218
- }
2219
- function defaultIsDirectory(dir) {
2220
- try {
2221
- return fs.statSync(dir).isDirectory();
2222
- }
2223
- catch {
2224
- return false;
2225
- }
2226
- }
2227
- function runPs(args) {
2228
- const result = spawnSync("ps", [...args], {
2229
- encoding: "utf8",
2230
- timeout: 5_000,
2231
- // Full command lines for every process can pass the 1 MiB default on a busy machine.
2232
- maxBuffer: HQ_JSON_MAX_BUFFER_BYTES,
2233
- windowsHide: true,
2234
- stdio: ["ignore", "pipe", "pipe"],
2235
- });
2236
- if (result.error)
2237
- throw new Error(`ps failed to spawn: ${result.error.message}`);
2238
- if (result.signal)
2239
- throw new Error(`ps killed by ${result.signal}`);
2240
- if (typeof result.status !== "number")
2241
- throw new Error("ps no exit status");
2242
- // `ps -p` exits 1 both when no pid still exists and on a real error. Accept exit 1 only with
2243
- // empty stderr; parsePsEnvOutput then keeps any pid that is not known to be gone as blocking.
2244
- const quietNoMatch = args.includes("-p") && result.status === 1 && !(result.stderr ?? "").trim();
2245
- if (result.status !== 0 && !quietNoMatch)
2246
- throw new Error(`ps exit ${result.status}`);
2247
- return result.stdout ?? "";
2248
- }
2249
- /**
2250
- * Fail-closed enumeration of running Claude Code processes.
2251
- *
2252
- * linux: /proc/<pid>/environ gives us per-process CLAUDE_CONFIG_DIR; absent
2253
- * value means the process holds the default home.
2254
- * darwin: `ps -axo` finds claude processes, then `ps -wwE` reads their
2255
- * environment (same user only). Rows whose environment cannot be read stay
2256
- * `probe: "command-only"`; the gate treats such a row as holding the default
2257
- * home AND blocking every non-default home.
2258
- * other platforms: return []. The lane gate is authoritative there.
2259
- *
2260
- * Throws on ps/readdir failure so the caller skips refresh.
2261
- */
2262
- const defaultListProcesses = async () => {
2263
- if (process.platform === "linux") {
2264
- const procDir = "/proc";
2265
- let entries;
2266
- try {
2267
- entries = fs.readdirSync(procDir);
2268
- }
2269
- catch (error) {
2270
- throw new Error(`readdir /proc failed: ${error.message}`);
2271
- }
2272
- const out = [];
2273
- for (const entry of entries) {
2274
- if (!/^\d+$/.test(entry))
2275
- continue;
2276
- const pid = Number(entry);
2277
- if (pid === process.pid)
2278
- continue;
2279
- let cmdline;
2280
- try {
2281
- cmdline = fs.readFileSync(path.join(procDir, entry, "cmdline"), "utf8");
2282
- }
2283
- catch {
2284
- continue;
2285
- }
2286
- const argv0 = cmdline.split("\0")[0] ?? "";
2287
- const base = argv0.split("/").pop() ?? "";
2288
- if (base !== "claude")
2289
- continue;
2290
- let envText;
2291
- try {
2292
- envText = fs.readFileSync(path.join(procDir, entry, "environ"), "utf8");
2293
- }
2294
- catch {
2295
- // Running process we cannot inspect: fail closed by raising.
2296
- throw new Error(`read /proc/${entry}/environ failed`);
2297
- }
2298
- const match = /(?:^|\0)CLAUDE_CONFIG_DIR=([^\0]+)/.exec(envText);
2299
- const homeMatch = /(?:^|\0)HOME=([^\0]+)/.exec(envText);
2300
- const procEnv = {};
2301
- if (match && match[1])
2302
- procEnv.CLAUDE_CONFIG_DIR = match[1];
2303
- if (homeMatch && homeMatch[1])
2304
- procEnv.HOME = homeMatch[1];
2305
- out.push({ pid, env: procEnv, probe: "env" });
2306
- }
2307
- return out;
2308
- }
2309
- if (process.platform === "darwin") {
2310
- const rows = parsePsClaudeOutput(runPs(["-axo", "pid=,command="]));
2311
- if (rows.length === 0)
2312
- return rows;
2313
- const pids = rows.map((row) => String(row.pid)).join(",");
2314
- const commandLines = parsePsCommandLines(runPs(["-ww", "-o", "pid=,command=", "-p", pids]));
2315
- return parsePsEnvOutput(runPs(["-wwE", "-o", "pid=,command=", "-p", pids]), commandLines, rows);
2316
- }
2317
- return [];
2318
- };
2319
- async function attemptClaudeTokenRefresh(ctx) {
2320
- const preFile = readRefreshLast(ctx.root);
2321
- const key = refreshLastKey(ctx.home);
2322
- const entry = preFile.homes[key];
2323
- if (refreshInBackoff(entry, ctx.nowMs))
2324
- return { outcome: "skipped-backoff" };
2325
- if (refreshTokenPersistentlyRevoked(preFile, ctx.refreshToken))
2326
- return { outcome: "skipped-revoked" };
2327
- let liveLanes;
2328
- try {
2329
- liveLanes = await ctx.listLiveLanes();
2330
- }
2331
- catch (error) {
2332
- const message = redactProviderTokens(error instanceof Error ? error.message : "listLiveLanes failed");
2333
- recordRefresh(ctx.root, key, {
2334
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2335
- outcome: "skipped-live-check-failed",
2336
- errorMessage: message,
2337
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2338
- });
2339
- return { outcome: "skipped-live-check-failed", errorMessage: message };
2340
- }
2341
- const resolvedHome = path.resolve(ctx.home);
2342
- const targetHome = canonicalHomePath(ctx.home) ?? resolvedHome;
2343
- // Blocking match: a path that cannot be resolved might be this home, so it blocks.
2344
- const mayHoldHome = (candidate) => {
2345
- if (typeof candidate !== "string" || candidate.length === 0)
2346
- return false;
2347
- const canonical = canonicalHomePath(candidate);
2348
- return canonical === null || canonical === targetHome;
2349
- };
2350
- // A finished lane that ended with provider_auth_failed on this home is NOT
2351
- // proof that the refresh token stored now is dead: the lane may have failed
2352
- // on an older token, or on an access token that a refresh would renew.
2353
- // Marking the current token revoked from that signal signed fresh sign-ins
2354
- // out. Only the token endpoint's own answer below decides revoked.
2355
- if (liveLanes.some((lane) => lane.isLive && mayHoldHome(lane.home))) {
2356
- recordRefresh(ctx.root, key, { attemptedAt: new Date(ctx.nowMs).toISOString(), outcome: "skipped-live" });
2357
- return { outcome: "skipped-live" };
2358
- }
2359
- let procs;
2360
- try {
2361
- procs = await ctx.listProcesses();
2362
- }
2363
- catch (error) {
2364
- const message = redactProviderTokens(error instanceof Error ? error.message : "listProcesses failed");
2365
- recordRefresh(ctx.root, key, {
2366
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2367
- outcome: "skipped-process-check-failed",
2368
- errorMessage: message,
2369
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2370
- });
2371
- return { outcome: "skipped-process-check-failed", errorMessage: message };
2372
- }
2373
- const defaultHome = path.join(os.homedir(), ".claude");
2374
- const isDefaultHome = targetHome === (canonicalHomePath(defaultHome) ?? path.resolve(defaultHome));
2375
- const procBlocks = procs.some((proc) => {
2376
- if (proc.probe === "env") {
2377
- const dir = typeof proc.env.CLAUDE_CONFIG_DIR === "string" ? proc.env.CLAUDE_CONFIG_DIR : "";
2378
- // A real env read. With CLAUDE_CONFIG_DIR unset the process holds HOME/.claude for its
2379
- // own HOME (the collector's home when HOME was not read). Claude Code adds no keychain
2380
- // suffix without CLAUDE_CONFIG_DIR, so such a process may also use the default keychain
2381
- // item; it keeps blocking the collector's default home too.
2382
- // Compare the process's default dir the same way as the collector's: a dir that does not
2383
- // exist yet is compared by its resolved path, so a missing ~/.claude does not block every home.
2384
- if (!dir) {
2385
- const procDefault = processDefaultConfigDir(proc);
2386
- return isDefaultHome || targetHome === (canonicalHomePath(procDefault) ?? path.resolve(procDefault));
2387
- }
2388
- return mayHoldHome(dir);
2389
- }
2390
- // command-only (darwin): we cannot read the per-process env. Conservatively
2391
- // treat the row as holding the default home AND blocking non-default homes.
2392
- return true;
2393
- });
2394
- if (procBlocks) {
2395
- recordRefresh(ctx.root, key, { attemptedAt: new Date(ctx.nowMs).toISOString(), outcome: "skipped-process" });
2396
- return { outcome: "skipped-process" };
2397
- }
2398
- let status;
2399
- let text;
2400
- try {
2401
- const response = await ctx.refreshFetch(ctx.tokenEndpoint, {
2402
- method: "POST",
2403
- headers: {
2404
- "content-type": "application/json",
2405
- Accept: "application/json",
2406
- },
2407
- body: JSON.stringify({
2408
- grant_type: "refresh_token",
2409
- refresh_token: ctx.refreshToken,
2410
- client_id: CLAUDE_OAUTH_REFRESH_CLIENT_ID,
2411
- }),
2412
- redirect: "manual",
2413
- signal: AbortSignal.timeout(CLAUDE_OAUTH_REFRESH_TIMEOUT_MS),
2414
- });
2415
- status = response.status;
2416
- try {
2417
- text = await response.text();
2418
- }
2419
- catch {
2420
- text = "";
2421
- }
2422
- }
2423
- catch (error) {
2424
- const isTimeout = error instanceof Error
2425
- && (error.name === "TimeoutError" || error.name === "AbortError" || /timeout/i.test(error.message));
2426
- const errorClass = isTimeout ? "timeout" : "network";
2427
- recordRefresh(ctx.root, key, {
2428
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2429
- outcome: "error",
2430
- errorClass,
2431
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2432
- });
2433
- return { outcome: "error", errorClass };
2434
- }
2435
- // Parse the response body ONLY to classify. The parsed error/error_description
2436
- // is NEVER persisted; only a fixed classification string and the HTTP status.
2437
- let parsedErrorField = null;
2438
- let parsedErrorDescription = null;
2439
- let bodyIsJson = false;
2440
- let parsedBody = null;
2441
- if (text) {
2442
- try {
2443
- const maybe = JSON.parse(text);
2444
- if (maybe && typeof maybe === "object" && !Array.isArray(maybe)) {
2445
- parsedBody = maybe;
2446
- bodyIsJson = true;
2447
- if (typeof parsedBody.error === "string")
2448
- parsedErrorField = parsedBody.error;
2449
- if (typeof parsedBody.error_description === "string")
2450
- parsedErrorDescription = parsedBody.error_description;
2451
- }
2452
- }
2453
- catch {
2454
- // non-JSON body is not stored; we only know we got a status back
2455
- }
2456
- }
2457
- if (status === 400 || status === 401) {
2458
- const errField = (parsedErrorField ?? "").toLowerCase();
2459
- const descField = (parsedErrorDescription ?? "").toLowerCase();
2460
- const revokedHit = errField === "invalid_grant"
2461
- || /\b(revoked|invalid)\b/.test(errField)
2462
- || /\b(revoked|invalid)\b/.test(descField);
2463
- if (revokedHit) {
2464
- // Another process (Claude Code, a lane) may have rotated the token between
2465
- // our read and this POST. Then our copy is stale, not the account.
2466
- const service = ctx.service || claudeKeychainServiceName(ctx.home);
2467
- const stored = ctx.readStoredRefreshToken({ home: ctx.home, service, platform: ctx.platform });
2468
- if (typeof stored === "string" && stored.length > 0 && stored !== ctx.refreshToken) {
2469
- // Back off so a store that keeps disagreeing with the read path cannot make
2470
- // the collector POST a dead token every tick without ever deciding.
2471
- recordRefresh(ctx.root, key, {
2472
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2473
- outcome: "skipped-race",
2474
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2475
- });
2476
- return { outcome: "skipped-race" };
2477
- }
2478
- const fingerprint = tokenFingerprint(ctx.refreshToken);
2479
- const now = new Date(ctx.nowMs).toISOString();
2480
- const errorClass = errField === "invalid_grant" ? "invalid_grant" : "revoked";
2481
- recordRefresh(ctx.root, key, {
2482
- attemptedAt: now,
2483
- outcome: "revoked",
2484
- errorClass,
2485
- revokedRefreshTokenFingerprint: fingerprint,
2486
- httpStatus: status,
2487
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS).toISOString(),
2488
- }, (file) => {
2489
- file.revokedTokens[fingerprint] = now;
2490
- });
2491
- return { outcome: "revoked", errorClass, httpStatus: status };
2492
- }
2493
- }
2494
- if (status !== 200) {
2495
- const errorClass = "server_error";
2496
- recordRefresh(ctx.root, key, {
2497
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2498
- outcome: "error",
2499
- errorClass,
2500
- httpStatus: status,
2501
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2502
- });
2503
- return { outcome: "error", errorClass, httpStatus: status };
2504
- }
2505
- if (!bodyIsJson || !parsedBody) {
2506
- recordRefresh(ctx.root, key, {
2507
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2508
- outcome: "error",
2509
- errorClass: "shape",
2510
- httpStatus: status,
2511
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2512
- });
2513
- return { outcome: "error", errorClass: "shape", httpStatus: status };
2514
- }
2515
- const body = parsedBody;
2516
- const accessToken = typeof body.access_token === "string" && body.access_token.trim() ? body.access_token : "";
2517
- if (!accessToken) {
2518
- recordRefresh(ctx.root, key, {
2519
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2520
- outcome: "error",
2521
- errorClass: "shape",
2522
- httpStatus: status,
2523
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2524
- });
2525
- return { outcome: "error", errorClass: "shape", httpStatus: status };
2526
- }
2527
- const newRefresh = typeof body.refresh_token === "string" && body.refresh_token.trim() ? body.refresh_token : ctx.refreshToken;
2528
- const expiresIn = typeof body.expires_in === "number" && Number.isFinite(body.expires_in) ? body.expires_in : null;
2529
- if (expiresIn === null) {
2530
- // Missing expires_in used to fall back to the previous (expired) expiresAt,
2531
- // which lets a bogus response rotate the stored refresh token forever.
2532
- // Treat as a failed refresh instead.
2533
- recordRefresh(ctx.root, key, {
2534
- attemptedAt: new Date(ctx.nowMs).toISOString(),
2535
- outcome: "error",
2536
- errorClass: "shape",
2537
- httpStatus: status,
2538
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2539
- });
2540
- return { outcome: "error", errorClass: "shape", httpStatus: status };
2541
- }
2542
- const newExpiresAt = ctx.nowMs + expiresIn * 1000;
2543
- let scopesOut = null;
2544
- if (Array.isArray(body.scopes)) {
2545
- scopesOut = body.scopes.filter((s) => typeof s === "string");
2546
- }
2547
- else if (typeof body.scope === "string") {
2548
- scopesOut = body.scope.split(/\s+/).filter((s) => s.length > 0);
2549
- }
2550
- const document = buildRefreshedDocument(ctx.previousDocument, {
2551
- accessToken,
2552
- refreshToken: newRefresh,
2553
- expiresAt: newExpiresAt,
2554
- scopes: scopesOut,
2555
- });
2556
- const writeResult = await ctx.writeCredentials({
2557
- home: ctx.home,
2558
- service: ctx.service ?? "",
2559
- platform: ctx.platform,
2560
- document,
2561
- previousRefreshToken: ctx.refreshToken,
2562
- });
2563
- const now = new Date(ctx.nowMs).toISOString();
2564
- if (!writeResult.ok && writeResult.raceDetected) {
2565
- recordRefresh(ctx.root, key, { attemptedAt: now, outcome: "skipped-race" });
2566
- return { outcome: "skipped-race" };
2567
- }
2568
- if (!writeResult.ok) {
2569
- const message = writeResult.error ?? "writeCredentials failed";
2570
- recordRefresh(ctx.root, key, {
2571
- attemptedAt: now,
2572
- outcome: "error",
2573
- errorMessage: message,
2574
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2575
- });
2576
- return { outcome: "error", errorMessage: message };
2577
- }
2578
- const tokenExpiresAt = newExpiresAt !== null && Number.isFinite(newExpiresAt)
2579
- ? new Date(newExpiresAt < 1e12 ? newExpiresAt * 1000 : newExpiresAt).toISOString()
2580
- : undefined;
2581
- recordRefresh(ctx.root, key, { attemptedAt: now, outcome: "refreshed", tokenExpiresAt });
2582
- return {
2583
- outcome: "refreshed",
2584
- newAccessToken: accessToken,
2585
- newExpiresAt: newExpiresAt ?? undefined,
2586
- newRefreshToken: newRefresh,
2587
- newScopes: scopesOut,
2588
- };
2589
- }
2590
- function recordRefresh(root, key, entry, mutate) {
2591
- const file = readRefreshLast(root);
2592
- file.homes[key] = entry;
2593
- if (mutate)
2594
- mutate(file);
2595
- writeRefreshLast(root, file);
2596
- }
2597
- function buildRefreshedDocument(previous, update) {
2598
- const base = previous ? { ...previous } : {};
2599
- const existing = base.claudeAiOauth && typeof base.claudeAiOauth === "object" && !Array.isArray(base.claudeAiOauth)
2600
- ? { ...base.claudeAiOauth }
2601
- : {};
2602
- existing.accessToken = update.accessToken;
2603
- existing.refreshToken = update.refreshToken;
2604
- if (update.expiresAt !== null)
2605
- existing.expiresAt = update.expiresAt;
2606
- if (update.scopes && update.scopes.length > 0)
2607
- existing.scopes = [...update.scopes];
2608
- base.claudeAiOauth = existing;
2609
- return base;
2610
- }
2611
- function expiresAtFromDocument(document) {
2612
- const oauth = document.claudeAiOauth;
2613
- if (!oauth || typeof oauth !== "object" || Array.isArray(oauth))
2614
- return null;
2615
- const value = oauth.expiresAt;
2616
- return typeof value === "number" && Number.isFinite(value) ? value : null;
2617
- }
2618
- function shouldAttemptRefresh(expiresAt, nowMs) {
2619
- if (expiresAt === null)
2620
- return false;
2621
- const ms = expiresAt < 1e12 ? expiresAt * 1000 : expiresAt;
2622
- return ms <= nowMs + CLAUDE_OAUTH_REFRESH_PREFLIGHT_MS;
2623
- }
2624
- /**
2625
- * Gate wrapper used by both the direct and enumerated collect paths.
2626
- * Returns null when the gate did not trip (no refresh token, not near expiry,
2627
- * no home info). Otherwise returns the refresh result.
2628
- */
2629
- async function maybeRefreshAccount(params) {
2630
- const { options, root, home, service, platform, refreshToken, expiresAt, previousDocument, nowMs } = params;
2631
- if (!refreshToken || !home)
2632
- return null;
2633
- if (!shouldAttemptRefresh(expiresAt, nowMs))
2634
- return null;
2635
- const writeCredentials = options.writeCredentials ?? defaultWriteClaudeCredentials;
2636
- const refreshFetch = options.refreshFetch ?? defaultRefreshFetch;
2637
- const tokenEndpoint = options.tokenEndpoint ?? CLAUDE_OAUTH_REFRESH_URL;
2638
- const listLiveLanes = options.listLiveLanes ?? defaultListLiveLanes;
2639
- const listProcesses = options.listProcesses ?? defaultListProcesses;
2640
- const readStoredRefreshToken = options.readStoredRefreshToken ?? defaultReadStoredRefreshToken;
2641
- return attemptClaudeTokenRefresh({
2642
- readStoredRefreshToken,
2643
- root,
2644
- home,
2645
- service,
2646
- platform,
2647
- refreshToken,
2648
- previousDocument,
2649
- writeCredentials,
2650
- refreshFetch,
2651
- tokenEndpoint,
2652
- listLiveLanes,
2653
- listProcesses,
2654
- nowMs,
2655
- });
2656
- }
2657
1598
  //# sourceMappingURL=claude-oauth.js.map