@indigoai-us/hq-cli 5.345.218 → 5.345.220

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 (138) hide show
  1. package/CHANGELOG.md +130 -0
  2. package/dist/command-catalog.generated.d.ts +94 -1
  3. package/dist/command-catalog.generated.js +114 -1
  4. package/dist/commands/agents.d.ts +22 -0
  5. package/dist/commands/agents.js +92 -1
  6. package/dist/commands/bot.d.ts +48 -0
  7. package/dist/commands/bot.js +108 -8
  8. package/dist/commands/cloud.d.ts +16 -0
  9. package/dist/commands/cloud.js +112 -102
  10. package/dist/commands/core-checkpoint-native.d.ts +13 -0
  11. package/dist/commands/core-checkpoint-native.js +167 -52
  12. package/dist/commands/core-hook-registration-plan.d.ts +8 -0
  13. package/dist/commands/core-hook-registration-plan.js +22 -0
  14. package/dist/commands/core.js +9 -0
  15. package/dist/commands/daemon.js +21 -2
  16. package/dist/commands/doctor.js +4 -0
  17. package/dist/commands/integrations.js +84 -3
  18. package/dist/commands/lanes-shared.d.ts +2 -0
  19. package/dist/commands/lanes-watch.js +28 -1
  20. package/dist/commands/lanes.d.ts +2 -0
  21. package/dist/commands/lanes.js +99 -9
  22. package/dist/commands/packs.js +23 -0
  23. package/dist/commands/pkg-update.d.ts +6 -0
  24. package/dist/commands/pkg-update.js +15 -7
  25. package/dist/commands/reindex.js +6 -0
  26. package/dist/commands/run.js +55 -45
  27. package/dist/commands/sources.js +3 -2
  28. package/dist/index.js +8 -0
  29. package/dist/lib/anywhere-person-setting.d.ts +2 -2
  30. package/dist/lib/anywhere-person-setting.js +2 -2
  31. package/dist/lib/bot/fleet-cron.js +5 -2
  32. package/dist/lib/bot/inflight.d.ts +9 -0
  33. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +51 -0
  34. package/dist/lib/bot/jobs/hot-signal-sync.js +90 -9
  35. package/dist/lib/bot/run.d.ts +29 -5
  36. package/dist/lib/bot/run.js +203 -1
  37. package/dist/lib/bot/signals-try-now.d.ts +76 -0
  38. package/dist/lib/bot/signals-try-now.js +111 -0
  39. package/dist/lib/capacity/collectors/claude-oauth.d.ts +22 -3
  40. package/dist/lib/capacity/collectors/claude-oauth.js +78 -22
  41. package/dist/lib/capacity/scheduler.d.ts +8 -0
  42. package/dist/lib/capacity/scheduler.js +5 -2
  43. package/dist/lib/daemon/anywhere-listener.d.ts +33 -1
  44. package/dist/lib/daemon/anywhere-listener.js +86 -4
  45. package/dist/lib/daemon/machine-check-owner.d.ts +21 -0
  46. package/dist/lib/daemon/machine-check-owner.js +95 -0
  47. package/dist/lib/daemon/machine-check-registration.d.ts +4 -0
  48. package/dist/lib/daemon/machine-check-registration.js +64 -0
  49. package/dist/lib/daemon/machine-checks.d.ts +144 -0
  50. package/dist/lib/daemon/machine-checks.js +412 -0
  51. package/dist/lib/daemon/run.js +35 -4
  52. package/dist/lib/daemon/runtime-notifications.d.ts +7 -0
  53. package/dist/lib/daemon/runtime-notifications.js +50 -0
  54. package/dist/lib/daemon/server.d.ts +2 -0
  55. package/dist/lib/daemon/server.js +6 -0
  56. package/dist/lib/daemon/state-file.d.ts +12 -1
  57. package/dist/lib/daemon/state-file.js +23 -1
  58. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +12 -0
  59. package/dist/lib/doctor/checks/fleet-hook-core.js +127 -0
  60. package/dist/lib/doctor/checks/host-core.js +3 -1
  61. package/dist/lib/doctor/checks/machine-checks.d.ts +16 -0
  62. package/dist/lib/doctor/checks/machine-checks.js +103 -0
  63. package/dist/lib/doctor/registry.js +4 -0
  64. package/dist/lib/doctor/types.d.ts +4 -0
  65. package/dist/lib/hook-engine/canary-gate.d.ts +64 -0
  66. package/dist/lib/hook-engine/canary-gate.js +147 -0
  67. package/dist/lib/hook-engine/coverage.d.ts +3 -1
  68. package/dist/lib/hook-engine/coverage.js +8 -2
  69. package/dist/lib/hook-engine/fleet-registration.d.ts +42 -0
  70. package/dist/lib/hook-engine/fleet-registration.js +168 -0
  71. package/dist/lib/hook-engine/reconcile.js +3 -2
  72. package/dist/lib/hook-engine/registration-identity.d.ts +33 -0
  73. package/dist/lib/hook-engine/registration-identity.js +97 -0
  74. package/dist/lib/hook-engine/registration.d.ts +1 -30
  75. package/dist/lib/hook-engine/registration.js +1 -88
  76. package/dist/lib/hook-engine/resolve.d.ts +2 -0
  77. package/dist/lib/hook-engine/resolve.js +7 -3
  78. package/dist/lib/hot-channels/alert.d.ts +10 -1
  79. package/dist/lib/hot-channels/alert.js +34 -7
  80. package/dist/lib/hot-channels/signals-claude-login.d.ts +53 -0
  81. package/dist/lib/hot-channels/signals-claude-login.js +96 -0
  82. package/dist/lib/hot-channels/signals-pass.d.ts +17 -0
  83. package/dist/lib/hot-channels/signals-pass.js +31 -3
  84. package/dist/lib/lanes/canonical-host.d.ts +8 -1
  85. package/dist/lib/lanes/canonical-host.js +9 -3
  86. package/dist/lib/lanes/machine-identity.d.ts +15 -0
  87. package/dist/lib/lanes/machine-identity.js +26 -0
  88. package/dist/lib/lanes/spawn.js +17 -3
  89. package/dist/lib/search-index/index.js +11 -1
  90. package/dist/lib/signals/engine.d.ts +1 -0
  91. package/dist/lib/signals/engine.js +7 -0
  92. package/dist/lib/signals/reply.d.ts +48 -0
  93. package/dist/lib/signals/reply.js +72 -11
  94. package/dist/lib/signals/steps/adapters.js +6 -0
  95. package/dist/lib/signals/steps/extract.d.ts +50 -3
  96. package/dist/lib/signals/steps/extract.js +100 -17
  97. package/dist/lib/signals/steps/types.d.ts +19 -0
  98. package/dist/lib/sync-core/engine-home.d.ts +6 -1
  99. package/dist/lib/sync-core/engine-home.js +13 -3
  100. package/dist/lib/sync-core/reconcile.js +1 -1
  101. package/dist/lib/sync-core/release-compare.d.ts +7 -0
  102. package/dist/lib/sync-core/release-compare.js +16 -0
  103. package/dist/lib/sync-core/release.d.ts +2 -1
  104. package/dist/lib/sync-core/release.js +2 -10
  105. package/dist/run/schema-env-overrides.d.ts +24 -0
  106. package/dist/run/schema-env-overrides.js +72 -0
  107. package/dist/utils/core-next-flag.d.ts +4 -0
  108. package/dist/utils/core-next-flag.js +22 -0
  109. package/dist/utils/core-next-kill.d.ts +16 -0
  110. package/dist/utils/core-next-kill.js +35 -0
  111. package/dist/utils/host-registration.d.ts +33 -23
  112. package/dist/utils/host-registration.js +90 -66
  113. package/package.json +14 -10
  114. package/scripts/check-function-manifest.mjs +5 -4
  115. package/dist/commands/__fixtures__/access-vault.d.ts +0 -95
  116. package/dist/commands/__fixtures__/access-vault.js +0 -166
  117. package/dist/commands/__fixtures__/make-tar.d.ts +0 -38
  118. package/dist/commands/__fixtures__/make-tar.js +0 -102
  119. package/dist/commands/secrets-public-types.test-d.d.ts +0 -2
  120. package/dist/commands/secrets-public-types.test-d.js +0 -18
  121. package/dist/lib/decisions/fixtures/us001.d.ts +0 -137
  122. package/dist/lib/decisions/fixtures/us001.js +0 -21
  123. package/dist/lib/doctor/__testing__/fake-hq-tree.d.ts +0 -226
  124. package/dist/lib/doctor/__testing__/fake-hq-tree.js +0 -408
  125. package/dist/lib/doctor/__testing__/run-doctor.d.ts +0 -8
  126. package/dist/lib/doctor/__testing__/run-doctor.js +0 -69
  127. package/dist/lib/fingerprint/fixtures.d.ts +0 -19
  128. package/dist/lib/fingerprint/fixtures.js +0 -61
  129. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.d.ts +0 -33
  130. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.js +0 -53
  131. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.d.ts +0 -38
  132. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.js +0 -64
  133. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.d.ts +0 -2
  134. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.js +0 -10
  135. package/dist/lib/test-utils/isolated-flag-company-context.d.ts +0 -3
  136. package/dist/lib/test-utils/isolated-flag-company-context.js +0 -18
  137. package/scripts/hook-engine-manifest.mjs +0 -22
  138. package/scripts/mesh-daemon-if-stale.mjs +0 -20
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The "Try now" offer from the bot's signals job (hot-signal-sync US-006 AC9).
3
+ *
4
+ * When the built-in signals job replies that a run failed or finished with
5
+ * problems, the reply asks the member for "Try now" (a decision button whose
6
+ * click sends the text "Try now", or the line `Say "Try now" to run signals
7
+ * again.`). The runner remembers that offer here, in the bot's own folder, so
8
+ * the member's answer is handled by code: one signals run for that company
9
+ * through the job's own entry point, not a model turn.
10
+ *
11
+ * One offer per bot (the latest reply wins). A Try now run takes the offer as
12
+ * it starts, so a second press can never start a second run off the same
13
+ * offer. A job reply that offers no Try now clears it; a "Running" reply
14
+ * (another run held the lock) leaves it. An offer older than
15
+ * `TRY_NOW_OFFER_TTL_MS` is ignored, so a "Try now" typed days later goes to
16
+ * the model as before.
17
+ *
18
+ * `lastRun` is the latest Try now run. Owner DMs are handled one at a time,
19
+ * so a second press sent while a run was going is only read after it ends; a
20
+ * press sent before `lastRun.finishedAt` is that kind of duplicate and gets a
21
+ * short reply with the run's result instead of another run.
22
+ */
23
+ import * as fs from "node:fs";
24
+ import * as path from "node:path";
25
+ const TRY_NOW_STATE_FILE = "signals-try-now.json";
26
+ /** How long a Try now offer stays answerable: until the next morning's run. */
27
+ export const TRY_NOW_OFFER_TTL_MS = 24 * 60 * 60 * 1000;
28
+ /**
29
+ * A press with no server send time (`receivedAt`) picked up this soon after a
30
+ * Try now run ended is taken as sent during it: it gets the run's result,
31
+ * never a second run. hq-pro-agents always sets `receivedAt`; this covers a
32
+ * delivery path that does not.
33
+ */
34
+ export const TRY_NOW_UNTIMED_GRACE_MS = 2 * 60 * 1000;
35
+ const isIso = (value) => typeof value === "string" && Number.isFinite(Date.parse(value));
36
+ export function readTryNowState(dir) {
37
+ let raw;
38
+ try {
39
+ raw = fs.readFileSync(path.join(dir, TRY_NOW_STATE_FILE), "utf8");
40
+ }
41
+ catch {
42
+ // No file: no offer was ever made.
43
+ return { v: 1, offer: null, lastRun: null };
44
+ }
45
+ try {
46
+ const parsed = JSON.parse(raw);
47
+ if (parsed?.v !== 1)
48
+ return { v: 1, offer: null, lastRun: null };
49
+ const o = parsed.offer;
50
+ const offer = o && typeof o.company === "string" && o.company && isIso(o.offeredAt)
51
+ ? { company: o.company, offeredAt: o.offeredAt, ...(typeof o.timeZone === "string" && o.timeZone ? { timeZone: o.timeZone } : {}) }
52
+ : null;
53
+ const r = parsed.lastRun;
54
+ const lastRun = r && typeof r.company === "string" && r.company && isIso(r.startedAt) && isIso(r.finishedAt) && typeof r.prose === "string"
55
+ ? { company: r.company, startedAt: r.startedAt, finishedAt: r.finishedAt, prose: r.prose }
56
+ : null;
57
+ return { v: 1, offer, lastRun };
58
+ }
59
+ catch (err) {
60
+ console.warn(`hq bot: ignoring unreadable ${TRY_NOW_STATE_FILE}: ${err instanceof Error ? err.message : String(err)}`);
61
+ return { v: 1, offer: null, lastRun: null };
62
+ }
63
+ }
64
+ function writeTryNowState(dir, state) {
65
+ const file = path.join(dir, TRY_NOW_STATE_FILE);
66
+ if (!state.offer && !state.lastRun) {
67
+ fs.rmSync(file, { force: true });
68
+ return;
69
+ }
70
+ const tmp = `${file}.${process.pid}.tmp`;
71
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
72
+ fs.renameSync(tmp, file);
73
+ }
74
+ export function readTryNowOffer(dir) {
75
+ return readTryNowState(dir).offer;
76
+ }
77
+ /** Set (or clear, with null) the offer; the last run is kept. */
78
+ export function writeTryNowOffer(dir, offer) {
79
+ writeTryNowState(dir, { ...readTryNowState(dir), offer });
80
+ }
81
+ /** Record the Try now run that just finished; the offer is kept. */
82
+ export function writeTryNowLastRun(dir, lastRun) {
83
+ writeTryNowState(dir, { ...readTryNowState(dir), lastRun });
84
+ }
85
+ function fresh(iso, nowMs) {
86
+ const at = Date.parse(iso);
87
+ return Number.isFinite(at) && nowMs - at <= TRY_NOW_OFFER_TTL_MS && at - nowMs <= TRY_NOW_OFFER_TTL_MS;
88
+ }
89
+ /**
90
+ * What a "Try now" sent at `pressedAtMs` means, read at `nowMs`:
91
+ * - `duplicate`: sent before the latest Try now run finished (it waited
92
+ * behind that run), so it answers that run and starts nothing;
93
+ * - `run`: sent after the open offer was made;
94
+ * - `none`: no open offer (none made, taken, expired, or made after this
95
+ * press was sent), so the model answers as before.
96
+ */
97
+ export function classifyTryNowPress(dir, pressedAtMs, nowMs, opts = {}) {
98
+ const { offer, lastRun } = readTryNowState(dir);
99
+ // Without the server's send time only the pickup time is known, and a
100
+ // press may have waited unpolled while the run went on: anything picked up
101
+ // within the grace after a run ended counts as sent during it.
102
+ const grace = opts.exact === false ? TRY_NOW_UNTIMED_GRACE_MS : 0;
103
+ if (lastRun && fresh(lastRun.finishedAt, nowMs) && pressedAtMs < Date.parse(lastRun.finishedAt) + grace) {
104
+ return { kind: "duplicate", lastRun };
105
+ }
106
+ if (offer && fresh(offer.offeredAt, nowMs) && pressedAtMs >= Date.parse(offer.offeredAt)) {
107
+ return { kind: "run", offer };
108
+ }
109
+ return { kind: "none" };
110
+ }
111
+ //# sourceMappingURL=signals-try-now.js.map
@@ -61,7 +61,11 @@ export declare const CLAUDE_OAUTH_REFRESH_BACKOFF_MS: number;
61
61
  export declare const CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS: number;
62
62
  /** Try a refresh when the token is this close to expiry, so one tick does not land on a stale token. */
63
63
  export declare const CLAUDE_OAUTH_REFRESH_PREFLIGHT_MS: number;
64
- export declare const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 10000;
64
+ /**
65
+ * Claude refresh tokens are single use. A refresh the server completed but whose
66
+ * response we abandoned leaves the stored token dead, so this limit is generous.
67
+ */
68
+ export declare const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 30000;
65
69
  export declare const CLAUDE_OAUTH_REFRESH_LAST_FILE = "claude-oauth-refresh-last.json";
66
70
  export interface ClaudeOAuthFetchInit {
67
71
  method: "GET";
@@ -137,14 +141,24 @@ export interface WriteClaudeCredentialsResult {
137
141
  error?: string;
138
142
  }
139
143
  export type WriteClaudeCredentials = (request: WriteClaudeCredentialsRequest) => Promise<WriteClaudeCredentialsResult>;
144
+ /**
145
+ * Reads the refresh token currently stored for a home. `null` = stored item has no
146
+ * refresh token; `undefined` = the item could not be read. Never logged.
147
+ */
148
+ export type ReadStoredClaudeRefreshToken = (request: {
149
+ home: string;
150
+ service: string;
151
+ platform: NodeJS.Platform;
152
+ }) => string | null | undefined;
140
153
  /**
141
154
  * One row per lane the gate must consider.
142
155
  * - `isLive` is true for state ∈ {queued, running, awaiting_input}: a running
143
156
  * Claude Code may hold the home; a refresh would race and get invalid_grant.
144
157
  * - `isAuthFailed` is true when the lane terminated with reason
145
158
  * `provider_auth_failed` (src/lib/lanes/watcher.ts classifies 401/403 that
146
- * way). The gate treats this as proof the account is already signed out and
147
- * records revoked without hitting the token endpoint.
159
+ * way). The refresh gate no longer treats this as proof of revocation: the
160
+ * lane may have failed on an older token. Only invalid_grant from the token
161
+ * endpoint marks a refresh token revoked.
148
162
  * - `home` is the resolved per-host provider home for the account; the gate
149
163
  * compares it to the home being refreshed with `canonicalHomePath` (realpath,
150
164
  * lower case on darwin) so symlinks and case differences do not slip through;
@@ -225,6 +239,11 @@ export interface CollectClaudeOAuthOptions {
225
239
  * preserving all sibling fields (including `mcpOAuth`).
226
240
  */
227
241
  writeCredentials?: WriteClaudeCredentials;
242
+ /**
243
+ * Re-reads the stored refresh token before an invalid_grant is recorded as revoked,
244
+ * so a token another process rotated in the meantime is not marked dead.
245
+ */
246
+ readStoredRefreshToken?: ReadStoredClaudeRefreshToken;
228
247
  /** Returns homes that live lanes are using. Default implementation reads `hq runners list --json`. */
229
248
  listLiveLanes?: ListLiveLanes;
230
249
  /** Returns processes whose `CLAUDE_CONFIG_DIR` identifies a home. Default reads `ps -ewwo pid,command`. */
@@ -68,7 +68,11 @@ export const CLAUDE_OAUTH_REFRESH_BACKOFF_MS = 10 * 60 * 1000;
68
68
  export const CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS = 60 * 60 * 1000;
69
69
  /** Try a refresh when the token is this close to expiry, so one tick does not land on a stale token. */
70
70
  export const CLAUDE_OAUTH_REFRESH_PREFLIGHT_MS = 10 * 60 * 1000;
71
- export const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 10_000;
71
+ /**
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.
74
+ */
75
+ export const CLAUDE_OAUTH_REFRESH_TIMEOUT_MS = 30_000;
72
76
  export const CLAUDE_OAUTH_REFRESH_LAST_FILE = "claude-oauth-refresh-last.json";
73
77
  const SESSION_MINUTES = 5 * 60;
74
78
  const WEEKLY_MINUTES = 7 * 24 * 60;
@@ -1718,6 +1722,7 @@ const defaultWriteClaudeCredentials = async (request) => {
1718
1722
  // the item so the write uses the SAME selector and does not create a second entry.
1719
1723
  let selector = null;
1720
1724
  let preRead = spawnSync("security", ["find-generic-password", "-s", request.service, "-a", username, "-w"], spawnOpts);
1725
+ const firstReadStatus = preRead.status;
1721
1726
  if (preRead.status === 0) {
1722
1727
  selector = "sa";
1723
1728
  }
@@ -1744,8 +1749,15 @@ const defaultWriteClaudeCredentials = async (request) => {
1744
1749
  return { ok: false, raceDetected: true };
1745
1750
  }
1746
1751
  }
1752
+ else if (firstReadStatus === 44 && preRead.status === 44) {
1753
+ // Both selectors confirmed the item does not exist (exit 44), so there is
1754
+ // nothing to race with or duplicate. The endpoint has already rotated the
1755
+ // refresh token; writing it keeps the only valid token instead of losing it.
1756
+ selector = "sa";
1757
+ }
1747
1758
  else if (request.previousRefreshToken) {
1748
- // Fail closed: a refresh race check needs a readable prior item.
1759
+ // Unreadable for another reason (timeout, prompt, locked Keychain). Writing
1760
+ // blind could duplicate the item or clobber a newer token, so fail closed.
1749
1761
  return { ok: false, raceDetected: true };
1750
1762
  }
1751
1763
  const body = JSON.stringify(request.document);
@@ -1800,6 +1812,49 @@ const defaultWriteClaudeCredentials = async (request) => {
1800
1812
  return { ok: false, error: message };
1801
1813
  }
1802
1814
  };
1815
+ function refreshTokenFromDocumentText(text) {
1816
+ let parsed;
1817
+ try {
1818
+ parsed = JSON.parse(text.replace(/\n$/, ""));
1819
+ }
1820
+ catch {
1821
+ // Unparseable item: report it as unreadable so the caller does not act on it.
1822
+ return undefined;
1823
+ }
1824
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
1825
+ return undefined;
1826
+ const oauth = parsed.claudeAiOauth;
1827
+ if (!oauth || typeof oauth !== "object" || Array.isArray(oauth))
1828
+ return null;
1829
+ const record = oauth;
1830
+ if (typeof record.refreshToken === "string")
1831
+ return record.refreshToken;
1832
+ if (typeof record.refresh_token === "string")
1833
+ return record.refresh_token;
1834
+ return null;
1835
+ }
1836
+ const defaultReadStoredRefreshToken = (request) => {
1837
+ if (request.platform === "darwin") {
1838
+ const username = os.userInfo().username;
1839
+ const spawnOpts = { encoding: "utf8", timeout: CLAUDE_OAUTH_SECURITY_TIMEOUT_MS, windowsHide: true };
1840
+ for (const args of [
1841
+ ["find-generic-password", "-s", request.service, "-a", username, "-w"],
1842
+ ["find-generic-password", "-s", request.service, "-w"],
1843
+ ]) {
1844
+ const read = spawnSync("security", args, spawnOpts);
1845
+ if (read.status === 0 && typeof read.stdout === "string")
1846
+ return refreshTokenFromDocumentText(read.stdout);
1847
+ }
1848
+ return undefined;
1849
+ }
1850
+ try {
1851
+ return refreshTokenFromDocumentText(fs.readFileSync(path.join(request.home, ".credentials.json"), "utf8"));
1852
+ }
1853
+ catch {
1854
+ // Missing or unreadable file: unknown, so the caller keeps its own judgement.
1855
+ return undefined;
1856
+ }
1857
+ };
1803
1858
  const HQ_CLI_PACKAGE_NAME = "@indigoai-us/hq-cli";
1804
1859
  const LOADER_FLAGS_WITH_VALUE = new Set(["--import", "--loader", "--experimental-loader", "--require", "-r", "--conditions", "-C"]);
1805
1860
  const LOADER_FLAGS_BARE = new Set(["--experimental-strip-types", "--experimental-transform-types"]);
@@ -2290,8 +2345,6 @@ async function attemptClaudeTokenRefresh(ctx) {
2290
2345
  }
2291
2346
  const resolvedHome = path.resolve(ctx.home);
2292
2347
  const targetHome = canonicalHomePath(ctx.home) ?? resolvedHome;
2293
- // Exact match, for the auth-failed short circuit, which records the home as revoked.
2294
- const sameHome = (candidate) => typeof candidate === "string" && candidate.length > 0 && canonicalHomePath(candidate) === targetHome;
2295
2348
  // Blocking match: a path that cannot be resolved might be this home, so it blocks.
2296
2349
  const mayHoldHome = (candidate) => {
2297
2350
  if (typeof candidate !== "string" || candidate.length === 0)
@@ -2299,24 +2352,11 @@ async function attemptClaudeTokenRefresh(ctx) {
2299
2352
  const canonical = canonicalHomePath(candidate);
2300
2353
  return canonical === null || canonical === targetHome;
2301
2354
  };
2302
- // Addendum 1: if the lane watcher classified a 401/403 on this home as
2303
- // provider_auth_failed, treat the account as already signed out and record
2304
- // revoked immediately. No token endpoint call, no response body stored.
2305
- const authFailedHere = liveLanes.find((lane) => lane.isAuthFailed && sameHome(lane.home));
2306
- if (authFailedHere) {
2307
- const fingerprint = tokenFingerprint(ctx.refreshToken);
2308
- const now = new Date(ctx.nowMs).toISOString();
2309
- recordRefresh(ctx.root, key, {
2310
- attemptedAt: now,
2311
- outcome: "revoked",
2312
- errorClass: "revoked",
2313
- revokedRefreshTokenFingerprint: fingerprint,
2314
- backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_REVOKED_BACKOFF_MS).toISOString(),
2315
- }, (file) => {
2316
- file.revokedTokens[fingerprint] = now;
2317
- });
2318
- return { outcome: "revoked", errorClass: "revoked" };
2319
- }
2355
+ // A finished lane that ended with provider_auth_failed on this home is NOT
2356
+ // proof that the refresh token stored now is dead: the lane may have failed
2357
+ // on an older token, or on an access token that a refresh would renew.
2358
+ // Marking the current token revoked from that signal signed fresh sign-ins
2359
+ // out. Only the token endpoint's own answer below decides revoked.
2320
2360
  if (liveLanes.some((lane) => lane.isLive && mayHoldHome(lane.home))) {
2321
2361
  recordRefresh(ctx.root, key, { attemptedAt: new Date(ctx.nowMs).toISOString(), outcome: "skipped-live" });
2322
2362
  return { outcome: "skipped-live" };
@@ -2426,6 +2466,20 @@ async function attemptClaudeTokenRefresh(ctx) {
2426
2466
  || /\b(revoked|invalid)\b/.test(errField)
2427
2467
  || /\b(revoked|invalid)\b/.test(descField);
2428
2468
  if (revokedHit) {
2469
+ // Another process (Claude Code, a lane) may have rotated the token between
2470
+ // our read and this POST. Then our copy is stale, not the account.
2471
+ const service = ctx.service || claudeKeychainServiceName(ctx.home);
2472
+ const stored = ctx.readStoredRefreshToken({ home: ctx.home, service, platform: ctx.platform });
2473
+ if (typeof stored === "string" && stored.length > 0 && stored !== ctx.refreshToken) {
2474
+ // Back off so a store that keeps disagreeing with the read path cannot make
2475
+ // the collector POST a dead token every tick without ever deciding.
2476
+ recordRefresh(ctx.root, key, {
2477
+ attemptedAt: new Date(ctx.nowMs).toISOString(),
2478
+ outcome: "skipped-race",
2479
+ backoffUntil: new Date(ctx.nowMs + CLAUDE_OAUTH_REFRESH_BACKOFF_MS).toISOString(),
2480
+ });
2481
+ return { outcome: "skipped-race" };
2482
+ }
2429
2483
  const fingerprint = tokenFingerprint(ctx.refreshToken);
2430
2484
  const now = new Date(ctx.nowMs).toISOString();
2431
2485
  const errorClass = errField === "invalid_grant" ? "invalid_grant" : "revoked";
@@ -2588,7 +2642,9 @@ async function maybeRefreshAccount(params) {
2588
2642
  const tokenEndpoint = options.tokenEndpoint ?? CLAUDE_OAUTH_REFRESH_URL;
2589
2643
  const listLiveLanes = options.listLiveLanes ?? defaultListLiveLanes;
2590
2644
  const listProcesses = options.listProcesses ?? defaultListProcesses;
2645
+ const readStoredRefreshToken = options.readStoredRefreshToken ?? defaultReadStoredRefreshToken;
2591
2646
  return attemptClaudeTokenRefresh({
2647
+ readStoredRefreshToken,
2592
2648
  root,
2593
2649
  home,
2594
2650
  service,
@@ -7,6 +7,14 @@ export declare const REBUILD_TICK_MS = 60000;
7
7
  export declare const POLL_TICK_MS: number;
8
8
  export declare const CODEX_DIR_POLL_MS = 15000;
9
9
  export declare const SPOOL_POLL_MS = 15000;
10
+ export declare const RUN_TIMEOUT_MS: {
11
+ readonly "codex-tail": 15000;
12
+ readonly "codex-app-server": 30000;
13
+ readonly "claude-statusline": 10000;
14
+ readonly "claude-oauth": 180000;
15
+ readonly grok: 30000;
16
+ readonly rebuild: 10000;
17
+ };
10
18
  export interface CapacityTimers {
11
19
  setTimeout(fn: () => void, ms: number): unknown;
12
20
  clearTimeout(handle: unknown): void;
@@ -22,11 +22,14 @@ export const REBUILD_TICK_MS = 60_000;
22
22
  export const POLL_TICK_MS = 5 * 60_000;
23
23
  export const CODEX_DIR_POLL_MS = 15_000;
24
24
  export const SPOOL_POLL_MS = 15_000;
25
- const RUN_TIMEOUT_MS = {
25
+ export const RUN_TIMEOUT_MS = {
26
26
  "codex-tail": 15_000,
27
27
  "codex-app-server": 30_000,
28
28
  "claude-statusline": 10_000,
29
- "claude-oauth": 30_000,
29
+ // Must stay well above CLAUDE_OAUTH_REFRESH_TIMEOUT_MS plus Keychain reads. A run
30
+ // marked timed out keeps going, so a short budget lets a second run POST the same
31
+ // single-use refresh token and get the account marked revoked.
32
+ "claude-oauth": 180_000,
30
33
  grok: 30_000,
31
34
  rebuild: 10_000,
32
35
  };
@@ -1,16 +1,48 @@
1
+ import type { DaemonFlagRegistryRead } from "./flag.js";
1
2
  import type { HqdServer } from "./server.js";
3
+ /**
4
+ * How often the listener checks again when no event has arrived. It is a
5
+ * correctness fallback only, for an event that was missed or a change no event
6
+ * reports (a person opting in while hqd is closed). Changes are normally
7
+ * picked up from the daemon's events: a shared registry read whose HQ
8
+ * Anywhere answer changed, or the running hqd server's runtime gate changing.
9
+ */
10
+ export declare const HQD_LISTENER_FALLBACK_MS: number;
2
11
  export interface HqdRuntimeListenerOptions {
3
12
  isEnabled: () => Promise<boolean>;
4
13
  startServer: () => Promise<HqdServer>;
5
14
  onServerChange?: (server: HqdServer | null) => void;
6
- intervalMs?: number;
15
+ /** Delay of the fallback check. Default HQD_LISTENER_FALLBACK_MS. */
16
+ fallbackMs?: number;
7
17
  schedule?: (callback: () => void, delayMs: number) => () => void;
18
+ /**
19
+ * Subscribe to the events that may change the decision. Called once, before
20
+ * the first check, so no event is lost while the listener starts. Returns
21
+ * the unsubscribe.
22
+ */
23
+ subscribe?: (notify: () => void) => () => void;
8
24
  log?: (error: unknown) => void;
9
25
  }
10
26
  export interface HqdRuntimeListener {
11
27
  refresh(): Promise<void>;
28
+ /** An event says the decision may have changed: check now, or again right after a check in progress. */
29
+ notify(): void;
12
30
  close(): Promise<void>;
13
31
  }
14
32
  /** Keep the local hqd listener aligned with the live flag and person setting. */
15
33
  export declare function startHqdRuntimeListener(options: HqdRuntimeListenerOptions): Promise<HqdRuntimeListener>;
34
+ /** A small fan-out from the daemon's event sources to the hqd listener. */
35
+ export interface HqdRuntimeEvents {
36
+ emit(): void;
37
+ subscribe(notify: () => void): () => void;
38
+ }
39
+ export declare function createHqdRuntimeEvents(): HqdRuntimeEvents;
40
+ /**
41
+ * An observer for the daemon's shared registry reads (flag.ts `onRead`) that
42
+ * calls `onChange` when the HQ Anywhere runtime answer differs from the last
43
+ * read's: the registry value, a sign-in or sign-out, or the local override
44
+ * file. A failed read says nothing and is skipped. The first answer counts as
45
+ * a change, so a decision the listener made before the first read is checked.
46
+ */
47
+ export declare function observeHqdRuntimeFlag(onChange: () => void): (read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv) => void;
16
48
  //# sourceMappingURL=anywhere-listener.d.ts.map
@@ -1,6 +1,16 @@
1
+ import { readLocalOverride } from "@indigoai-us/hq-flags-client";
2
+ import { HQ_ANYWHERE_RUNTIME_FLAG } from "../anywhere-runtime-flag-key.js";
3
+ /**
4
+ * How often the listener checks again when no event has arrived. It is a
5
+ * correctness fallback only, for an event that was missed or a change no event
6
+ * reports (a person opting in while hqd is closed). Changes are normally
7
+ * picked up from the daemon's events: a shared registry read whose HQ
8
+ * Anywhere answer changed, or the running hqd server's runtime gate changing.
9
+ */
10
+ export const HQD_LISTENER_FALLBACK_MS = 10 * 60_000;
1
11
  /** Keep the local hqd listener aligned with the live flag and person setting. */
2
12
  export async function startHqdRuntimeListener(options) {
3
- const intervalMs = options.intervalMs ?? 60_000;
13
+ const fallbackMs = options.fallbackMs ?? HQD_LISTENER_FALLBACK_MS;
4
14
  const log = options.log ?? (() => { });
5
15
  const schedule = options.schedule ?? ((callback, delayMs) => {
6
16
  const timer = setInterval(callback, delayMs);
@@ -10,11 +20,15 @@ export async function startHqdRuntimeListener(options) {
10
20
  let server = null;
11
21
  let closed = false;
12
22
  let inFlight = null;
23
+ // An event arrived while a check was in progress: that check may have read
24
+ // the state from before the change, so one more check follows it.
25
+ let again = false;
13
26
  const refresh = () => {
14
27
  if (closed)
15
28
  return Promise.resolve();
16
29
  if (inFlight)
17
30
  return inFlight;
31
+ again = false;
18
32
  inFlight = (async () => {
19
33
  let enabled = false;
20
34
  try {
@@ -53,19 +67,35 @@ export async function startHqdRuntimeListener(options) {
53
67
  }
54
68
  })().finally(() => {
55
69
  inFlight = null;
70
+ if (again && !closed)
71
+ void refresh();
56
72
  });
57
73
  return inFlight;
58
74
  };
75
+ const notify = () => {
76
+ if (closed)
77
+ return;
78
+ if (inFlight) {
79
+ again = true;
80
+ return;
81
+ }
82
+ void refresh();
83
+ };
84
+ const unsubscribe = options.subscribe?.(notify) ?? (() => { });
59
85
  await refresh();
60
- if (closed)
61
- return { refresh, close: async () => { } };
62
- const cancel = schedule(() => { void refresh(); }, intervalMs);
86
+ if (closed) {
87
+ unsubscribe();
88
+ return { refresh, notify, close: async () => { } };
89
+ }
90
+ const cancel = schedule(() => { void refresh(); }, fallbackMs);
63
91
  return {
64
92
  refresh,
93
+ notify,
65
94
  async close() {
66
95
  if (closed)
67
96
  return;
68
97
  closed = true;
98
+ unsubscribe();
69
99
  cancel();
70
100
  await inFlight;
71
101
  const current = server;
@@ -76,4 +106,56 @@ export async function startHqdRuntimeListener(options) {
76
106
  },
77
107
  };
78
108
  }
109
+ export function createHqdRuntimeEvents() {
110
+ const listeners = new Set();
111
+ return {
112
+ emit() {
113
+ for (const notify of [...listeners]) {
114
+ try {
115
+ notify();
116
+ }
117
+ catch {
118
+ // one listener cannot stop the others
119
+ }
120
+ }
121
+ },
122
+ subscribe(notify) {
123
+ const entry = () => notify();
124
+ listeners.add(entry);
125
+ return () => { listeners.delete(entry); };
126
+ },
127
+ };
128
+ }
129
+ /**
130
+ * An observer for the daemon's shared registry reads (flag.ts `onRead`) that
131
+ * calls `onChange` when the HQ Anywhere runtime answer differs from the last
132
+ * read's: the registry value, a sign-in or sign-out, or the local override
133
+ * file. A failed read says nothing and is skipped. The first answer counts as
134
+ * a change, so a decision the listener made before the first read is checked.
135
+ */
136
+ export function observeHqdRuntimeFlag(onChange) {
137
+ let last;
138
+ return (read, env) => {
139
+ let answer;
140
+ try {
141
+ const override = readLocalOverride(HQ_ANYWHERE_RUNTIME_FLAG, env);
142
+ if (read.signedOut) {
143
+ answer = `signed-out|${String(override)}`;
144
+ }
145
+ else {
146
+ if (read.errors.length > 0 || !read.client)
147
+ return;
148
+ const resolution = read.client.explain(HQ_ANYWHERE_RUNTIME_FLAG, { fallback: true });
149
+ answer = `${resolution.source}:${String(resolution.value)}|${String(override)}`;
150
+ }
151
+ }
152
+ catch {
153
+ return;
154
+ }
155
+ if (answer === last)
156
+ return;
157
+ last = answer;
158
+ onChange();
159
+ };
160
+ }
79
161
  //# sourceMappingURL=anywhere-listener.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * How old the daemon's machine-check results file may be and still count as
3
+ * proof the schedule is running: two hourly intervals plus the first delay,
4
+ * so one late or skipped batch does not flip the owner.
5
+ */
6
+ export declare const MACHINE_CHECK_RESULTS_FRESH_MS: number;
7
+ /** Internal, offline protocol shared with the legacy dispatcher. */
8
+ export declare function machineCheckOwner(env?: NodeJS.ProcessEnv, home?: string, options?: {
9
+ now?: Date;
10
+ platform?: NodeJS.Platform;
11
+ }): {
12
+ schema: "hq-machine-check-owner.v1";
13
+ owner: "daemon" | "legacy";
14
+ reason: string;
15
+ checks: {
16
+ id: string;
17
+ path: string;
18
+ event: import("./machine-checks.js").MachineCheckEvent;
19
+ }[];
20
+ };
21
+ //# sourceMappingURL=machine-check-owner.d.ts.map
@@ -0,0 +1,95 @@
1
+ import * as os from "node:os";
2
+ import * as path from "node:path";
3
+ import { daemonPresenceLabel, readHeartbeat, heartbeatFile } from "./heartbeat.js";
4
+ import { MACHINE_CHECKS, MACHINE_CHECKS_FIRST_DELAY_MS, MACHINE_CHECKS_INTERVAL_MS, MACHINE_CHECKS_RESULT_FILE, machineChecksScheduleOn, } from "./machine-checks.js";
5
+ import { daemonPaths, readStoreFile } from "./paths.js";
6
+ import { readDaemonConfig } from "./config.js";
7
+ import { sameHqRoot } from "../hook-engine/registration-identity.js";
8
+ import { nativeSessionStartRegistered } from "./machine-check-registration.js";
9
+ import { codexEnvEvidence, grokEnvEvidence } from "../doctor/platform.js";
10
+ /**
11
+ * How old the daemon's machine-check results file may be and still count as
12
+ * proof the schedule is running: two hourly intervals plus the first delay,
13
+ * so one late or skipped batch does not flip the owner.
14
+ */
15
+ export const MACHINE_CHECK_RESULTS_FRESH_MS = 2 * MACHINE_CHECKS_INTERVAL_MS + MACHINE_CHECKS_FIRST_DELAY_MS;
16
+ function errorName(error) {
17
+ return error instanceof Error ? error.code ?? error.name : "UnknownError";
18
+ }
19
+ /**
20
+ * The session's harness: `HQ_HARNESS` when set, else the Codex or Grok runtime
21
+ * variables (the same markers `lanes` uses for the orchestrator engine), else
22
+ * Claude. Claude stays the default because `CLAUDECODE=1` is not always set.
23
+ */
24
+ function sessionHarness(env) {
25
+ const named = env.HQ_HARNESS?.trim().toLowerCase();
26
+ if (named)
27
+ return named;
28
+ if (codexEnvEvidence(env).length > 0)
29
+ return "codex";
30
+ if (grokEnvEvidence(env).length > 0)
31
+ return "grok";
32
+ return "claude";
33
+ }
34
+ /**
35
+ * Decide who runs the machine checks, offline and fail-safe. "daemon" only
36
+ * when every host-local signal shows the schedule is really running here:
37
+ * not Windows (checks start with /bin/bash), the rollout flag is on with no
38
+ * kill switch, the daemon heartbeat file is fresh, and the schedule wrote its
39
+ * results file (which needs a resolved HQ root) within the freshness window.
40
+ * Anything that cannot be observed answers "legacy" with the reason.
41
+ */
42
+ function decideOwner(env, home, now, platform) {
43
+ if (platform === "win32")
44
+ return { owner: "legacy", reason: "windows: machine checks need /bin/bash" };
45
+ if (!machineChecksScheduleOn(env, home))
46
+ return { owner: "legacy", reason: "core.next is off or a kill switch is set" };
47
+ const sessionRoot = env.HQ_ROOT?.trim();
48
+ let daemonRoot;
49
+ try {
50
+ daemonRoot = readDaemonConfig(daemonPaths(home, env).configPath).hqRoot;
51
+ }
52
+ catch { /* fail safe */ }
53
+ if (!sessionRoot || !daemonRoot || !sameHqRoot(sessionRoot, daemonRoot))
54
+ return { owner: "legacy", reason: "session HQ root differs from daemon HQ root" };
55
+ const host = sessionHarness(env);
56
+ if ((host !== "claude" && host !== "codex") || !nativeSessionStartRegistered(sessionRoot, home, host, env)) {
57
+ return { owner: "legacy", reason: "no native SessionStart for this host and HQ root" };
58
+ }
59
+ let beat;
60
+ try {
61
+ beat = readHeartbeat(heartbeatFile(home, env));
62
+ }
63
+ catch (error) {
64
+ return { owner: "legacy", reason: `daemon heartbeat unreadable (${errorName(error)})` };
65
+ }
66
+ if (!beat)
67
+ return { owner: "legacy", reason: "daemon heartbeat missing: daemon not running" };
68
+ if (daemonPresenceLabel(beat, now) !== "daemon live")
69
+ return { owner: "legacy", reason: "daemon heartbeat stale" };
70
+ let results;
71
+ try {
72
+ results = readStoreFile(path.join(daemonPaths(home, env).root, MACHINE_CHECKS_RESULT_FILE), 256 * 1024);
73
+ }
74
+ catch (error) {
75
+ return { owner: "legacy", reason: `machine-check results unreadable (${errorName(error)})` };
76
+ }
77
+ if (!results)
78
+ return { owner: "legacy", reason: "no machine-check results: schedule has not run with an HQ root" };
79
+ const age = now.getTime() - results.mtimeMs;
80
+ if (!Number.isFinite(age) || age > MACHINE_CHECK_RESULTS_FRESH_MS) {
81
+ return { owner: "legacy", reason: "machine-check results stale" };
82
+ }
83
+ return { owner: "daemon", reason: "daemon live and schedule results fresh" };
84
+ }
85
+ /** Internal, offline protocol shared with the legacy dispatcher. */
86
+ export function machineCheckOwner(env = process.env, home = env.HOME || env.USERPROFILE || os.homedir(), options = {}) {
87
+ const decided = decideOwner(env, home, options.now ?? new Date(), options.platform ?? process.platform);
88
+ return {
89
+ schema: "hq-machine-check-owner.v1",
90
+ owner: decided.owner,
91
+ reason: decided.reason,
92
+ checks: MACHINE_CHECKS.map(({ id, path: file, event }) => ({ id, path: file, event })),
93
+ };
94
+ }
95
+ //# sourceMappingURL=machine-check-owner.js.map
@@ -0,0 +1,4 @@
1
+ export type MachineCheckHost = "claude" | "codex" | "grok";
2
+ export declare function nativeSessionStartRegistered(root: string, home: string, host: MachineCheckHost, env: NodeJS.ProcessEnv): boolean;
3
+ export declare function anyNativeSessionStartRegistered(root: string, home: string, env: NodeJS.ProcessEnv): boolean;
4
+ //# sourceMappingURL=machine-check-registration.d.ts.map