@indigoai-us/hq-cli 5.345.223 → 5.345.226

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 (130) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/assets/bot-workers/setup/context/quick-reference.md +2 -2
  3. package/assets/mesh-daemon/README.md +11 -12
  4. package/dist/command-catalog.generated.d.ts +156 -4
  5. package/dist/command-catalog.generated.js +191 -4
  6. package/dist/commands/cloud-provision.d.ts +4 -1
  7. package/dist/commands/cloud-provision.js +7 -3
  8. package/dist/commands/cloud-retire.js +1 -1
  9. package/dist/commands/core-delegate-w1b.js +3 -1
  10. package/dist/commands/core-delegate.d.ts +5 -0
  11. package/dist/commands/core-dm-bind-native.d.ts +5 -1
  12. package/dist/commands/core-dm-bind-native.js +4 -0
  13. package/dist/commands/core-job-notify-native.d.ts +5 -1
  14. package/dist/commands/core-job-notify-native.js +8 -2
  15. package/dist/commands/core-jobs-native.d.ts +27 -1
  16. package/dist/commands/core-jobs-native.js +49 -28
  17. package/dist/commands/core-pipeline-conductor-native.js +7 -7
  18. package/dist/commands/core-pipeline-driver-native.js +5 -5
  19. package/dist/commands/core-refresh-vault-access-native.d.ts +5 -0
  20. package/dist/commands/core-refresh-vault-access-native.js +3 -1
  21. package/dist/commands/core-work-mesh-bind-trusted-native.js +1 -1
  22. package/dist/commands/daemon.d.ts +2 -0
  23. package/dist/commands/daemon.js +68 -2
  24. package/dist/commands/deploy-domains.js +38 -2
  25. package/dist/commands/lanes-accounts.d.ts +14 -0
  26. package/dist/commands/lanes-accounts.js +119 -0
  27. package/dist/commands/lanes-hold.d.ts +2 -27
  28. package/dist/commands/lanes-hold.js +3 -75
  29. package/dist/commands/lanes-loop.js +1 -1
  30. package/dist/commands/lanes-move.js +10 -0
  31. package/dist/commands/lanes-session-start.js +2 -2
  32. package/dist/commands/lanes-shared.js +9 -0
  33. package/dist/commands/lanes.js +137 -12
  34. package/dist/commands/mesh.d.ts +12 -0
  35. package/dist/commands/mesh.js +13 -4
  36. package/dist/commands/monitor.js +1 -1
  37. package/dist/commands/packs.js +1 -1
  38. package/dist/commands/sync-held.d.ts +22 -0
  39. package/dist/commands/sync-held.js +167 -18
  40. package/dist/commands/whoami.d.ts +10 -17
  41. package/dist/commands/whoami.js +7 -79
  42. package/dist/data/command-states.json +13 -0
  43. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  44. package/dist/hq-cloud-sync-runner/package.json +1 -1
  45. package/dist/index.js +1 -1
  46. package/dist/lib/capacity/accounts.d.ts +4 -0
  47. package/dist/lib/capacity/accounts.js +4 -0
  48. package/dist/lib/capacity/route.js +14 -0
  49. package/dist/lib/capacity/sign-in.d.ts +18 -0
  50. package/dist/lib/capacity/sign-in.js +34 -1
  51. package/dist/lib/daemon/catalog.d.ts +9 -5
  52. package/dist/lib/daemon/catalog.js +14 -8
  53. package/dist/lib/daemon/config.d.ts +5 -0
  54. package/dist/lib/daemon/config.js +6 -0
  55. package/dist/lib/daemon/hook-requests.d.ts +76 -0
  56. package/dist/lib/daemon/hook-requests.js +481 -0
  57. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  58. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  59. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  60. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  61. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  62. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  63. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  64. package/dist/lib/daemon/merge-sections.js +556 -0
  65. package/dist/lib/daemon/ops/policy.d.ts +2 -2
  66. package/dist/lib/daemon/ops/policy.js +44 -5
  67. package/dist/lib/daemon/protocol.d.ts +1 -1
  68. package/dist/lib/daemon/protocol.js +0 -6
  69. package/dist/lib/daemon/run.js +110 -5
  70. package/dist/lib/daemon/selfcheck.js +2 -2
  71. package/dist/lib/daemon/server.d.ts +2 -4
  72. package/dist/lib/daemon/server.js +11 -49
  73. package/dist/lib/daemon/state-file.d.ts +74 -4
  74. package/dist/lib/daemon/state-file.js +159 -19
  75. package/dist/lib/daemon/supervisor.d.ts +3 -1
  76. package/dist/lib/daemon/updater.d.ts +2 -6
  77. package/dist/lib/daemon/updater.js +4 -11
  78. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  79. package/dist/lib/daemon/whoami-cache.js +244 -0
  80. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  81. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  82. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  83. package/dist/lib/hook-engine/coverage.js +71 -0
  84. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  85. package/dist/lib/hook-engine/reconcile.js +14 -8
  86. package/dist/lib/install/hook-target.d.ts +13 -3
  87. package/dist/lib/install/hook-target.js +14 -11
  88. package/dist/lib/lanes/account-company.d.ts +7 -1
  89. package/dist/lib/lanes/account-company.js +22 -4
  90. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  91. package/dist/lib/lanes/account-ownership.js +134 -0
  92. package/dist/lib/lanes/accounts.js +9 -2
  93. package/dist/lib/lanes/claude-balance.js +9 -3
  94. package/dist/lib/lanes/config.js +17 -0
  95. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  96. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  97. package/dist/lib/lanes/host-capacity.js +37 -0
  98. package/dist/lib/lanes/monitor.d.ts +2 -0
  99. package/dist/lib/lanes/monitor.js +2 -1
  100. package/dist/lib/lanes/reconcile.js +44 -3
  101. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  102. package/dist/lib/lanes/registry-flag.js +3 -2
  103. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  104. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  105. package/dist/lib/lanes/spawn.d.ts +0 -10
  106. package/dist/lib/lanes/spawn.js +51 -1
  107. package/dist/lib/lanes/types.d.ts +12 -0
  108. package/dist/lib/lanes/watcher-main.js +3 -3
  109. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  110. package/dist/lib/mesh/live/daemon/install.js +2 -2
  111. package/dist/lib/windows/install-followup.js +1 -1
  112. package/dist/utils/client-health-contract.d.ts +1 -0
  113. package/dist/utils/client-health-contract.js +5 -0
  114. package/dist/utils/client-health.d.ts +2 -0
  115. package/dist/utils/client-health.js +40 -0
  116. package/dist/utils/cognito-session.d.ts +2 -14
  117. package/dist/utils/cognito-session.js +2 -40
  118. package/dist/utils/daemon-cli-version.d.ts +13 -0
  119. package/dist/utils/daemon-cli-version.js +47 -0
  120. package/dist/utils/duplicate-command-usage.js +1 -1
  121. package/dist/utils/machine-token-cache.d.ts +21 -0
  122. package/dist/utils/machine-token-cache.js +49 -0
  123. package/dist/utils/resident-package-preload.js +4 -0
  124. package/dist/utils/whoami-identity.d.ts +54 -0
  125. package/dist/utils/whoami-identity.js +108 -0
  126. package/package.json +8 -8
  127. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  128. package/dist/lib/daemon/ops/memory.js +0 -65
  129. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  130. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * The daemon's state file: one JSON file, rewritten atomically after each
3
- * flag registry request the daemon's timed flag monitors share, that hooks
4
- * read instead of starting Node or calling the network.
3
+ * flag registry request the daemon's timed flag monitors share, and again
4
+ * after each refresh of the merge sections (every 15 s, merge-sections.ts),
5
+ * that hooks read instead of starting Node or calling the network.
5
6
  *
6
- * It holds three sections and nothing else:
7
+ * It holds these sections and nothing else:
7
8
  * - flags: every flag value the registry returned for the daemon's scope
8
9
  * (person, or one company uid), with the time the registry answered;
9
10
  * - vault_access: per company slug, the caller's role, whether the access
@@ -13,7 +14,18 @@
13
14
  * today (id, status, time, optional one-line summary, and for a finding
14
15
  * its text, cut to 4096 bytes, and a fingerprint the hook engine uses to
15
16
  * show it once). The finding text can name local paths, so like the rest
16
- * of the file it is never logged or sent.
17
+ * of the file it is never logged or sent;
18
+ * - lanes_monitor (optional, written only when the daemon computed it): per
19
+ * Claude senior session of an active lane, the active and uncovered lane
20
+ * ids, the Monitor calls that would cover the uncovered ones, and the
21
+ * reminder text (lanes-monitor-state.ts). It is what `hq lanes
22
+ * monitor-check` would answer, precomputed so the UserPromptSubmit hook
23
+ * starts no program. A missing or stale section means no reminder.
24
+ * - merge_holds and merge_approvals (merge-sections.ts): the repository
25
+ * merge holds with each owning company's hold flag, and per session the
26
+ * conduct decision queue and review gate the native merge check reads.
27
+ * Each has its own refreshed_at and a 60-second max age; a section that
28
+ * cannot be built is left out, which makes that check refuse merges.
17
29
  *
18
30
  * No token, key or other secret is written. The vault access list tells which
19
31
  * companies and paths a person can reach, so the file lives in the per-host
@@ -70,6 +82,13 @@ export function cutUtf8(text, maxBytes) {
70
82
  end -= 1;
71
83
  return bytes.subarray(0, end).toString("utf8");
72
84
  }
85
+ /** At most this many sessions are written into lanes_monitor. */
86
+ export const LANES_MONITOR_MAX_SESSIONS = 64;
87
+ /** The hook engine refuses an extra section larger than this (crates/hq-hook). */
88
+ export const LANES_MONITOR_READER_MAX_BYTES = 256 * 1024;
89
+ /** The writer keeps lanes_monitor, serialized, at or under this many bytes. */
90
+ export const LANES_MONITOR_MAX_BYTES = 192 * 1024;
91
+ export const LANES_MONITOR_SESSION_ID_RE = /^[A-Za-z0-9._-]+$/;
73
92
  /** `HQ_STATE_FILE` when set (tests and isolated daemons), else `<daemon folder>/hq-state.json`. */
74
93
  export function daemonStateFilePath(home, env = process.env) {
75
94
  const explicit = env.HQ_STATE_FILE?.trim();
@@ -202,6 +221,70 @@ function machineChecksOf(results) {
202
221
  }
203
222
  return out;
204
223
  }
224
+ function isLaneIdList(value) {
225
+ return Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0);
226
+ }
227
+ function lanesMonitorSessionOf(value) {
228
+ if (!isRecord(value) || value.engine !== "claude" || !isIsoTime(value.checked_at))
229
+ return null;
230
+ if (typeof value.reminder !== "string")
231
+ return null;
232
+ const active = value.active_lane_ids;
233
+ const uncovered = value.uncovered_lane_ids;
234
+ if (!isLaneIdList(active) || !isLaneIdList(uncovered))
235
+ return null;
236
+ const activeSet = new Set(active);
237
+ if (!uncovered.every((id) => activeSet.has(id)))
238
+ return null;
239
+ if (!Array.isArray(value.monitor_calls))
240
+ return null;
241
+ const calls = [];
242
+ for (const call of value.monitor_calls) {
243
+ if (!isRecord(call) || typeof call.command !== "string" || !call.command)
244
+ return null;
245
+ if (typeof call.timeout_ms !== "number" || !Number.isInteger(call.timeout_ms) || call.timeout_ms <= 0)
246
+ return null;
247
+ if (call.persistent !== false)
248
+ return null;
249
+ calls.push({ command: call.command, timeout_ms: call.timeout_ms, persistent: false });
250
+ }
251
+ return {
252
+ engine: "claude",
253
+ checked_at: value.checked_at,
254
+ active_lane_ids: [...active],
255
+ uncovered_lane_ids: [...uncovered],
256
+ monitor_calls: calls,
257
+ reminder: value.reminder,
258
+ };
259
+ }
260
+ /**
261
+ * The lanes_monitor section with only its documented fields, in key order, or
262
+ * null when any part of it is malformed (a bad session id or entry, an
263
+ * uncovered id that is not active, more than LANES_MONITOR_MAX_SESSIONS
264
+ * sessions, or more than LANES_MONITOR_READER_MAX_BYTES serialized). The whole
265
+ * section is dropped rather than part of it, so a reader never takes a partial
266
+ * answer for a complete one.
267
+ */
268
+ export function lanesMonitorSectionOf(value) {
269
+ if (!isRecord(value) || !isIsoTime(value.checked_at) || !isRecord(value.sessions))
270
+ return null;
271
+ const ids = Object.keys(value.sessions);
272
+ if (ids.length > LANES_MONITOR_MAX_SESSIONS)
273
+ return null;
274
+ const sessions = {};
275
+ for (const id of ids) {
276
+ if (!LANES_MONITOR_SESSION_ID_RE.test(id))
277
+ return null;
278
+ const entry = lanesMonitorSessionOf(value.sessions[id]);
279
+ if (!entry)
280
+ return null;
281
+ sessions[id] = entry;
282
+ }
283
+ const section = { checked_at: value.checked_at, sessions };
284
+ if (Buffer.byteLength(JSON.stringify(section), "utf8") > LANES_MONITOR_READER_MAX_BYTES)
285
+ return null;
286
+ return section;
287
+ }
205
288
  /** The exact bytes written: one line of JSON with the keys in schema order. */
206
289
  export function renderDaemonStateFile(state) {
207
290
  const scopes = {};
@@ -218,7 +301,12 @@ export function renderDaemonStateFile(state) {
218
301
  ? { refreshed_at: state.vault_access.refreshed_at, companies: state.vault_access.companies }
219
302
  : null,
220
303
  machine_checks: { results: machineChecksOf(state.machine_checks.results) },
304
+ ...(state.merge_holds ? { merge_holds: state.merge_holds } : {}),
305
+ ...(state.merge_approvals ? { merge_approvals: state.merge_approvals } : {}),
221
306
  };
307
+ const lanesMonitor = state.lanes_monitor ? lanesMonitorSectionOf(state.lanes_monitor) : null;
308
+ if (lanesMonitor)
309
+ ordered.lanes_monitor = lanesMonitor;
222
310
  return `${JSON.stringify(ordered)}\n`;
223
311
  }
224
312
  /**
@@ -297,6 +385,7 @@ export function readDaemonStateFile(file) {
297
385
  const checks = isRecord(parsed.machine_checks) && Array.isArray(parsed.machine_checks.results)
298
386
  ? machineChecksOf(parsed.machine_checks.results)
299
387
  : [];
388
+ const lanesMonitor = parsed.lanes_monitor === undefined ? null : lanesMonitorSectionOf(parsed.lanes_monitor);
300
389
  return {
301
390
  schema: DAEMON_STATE_SCHEMA,
302
391
  written_at: parsed.written_at,
@@ -306,6 +395,9 @@ export function readDaemonStateFile(file) {
306
395
  ? { refreshed_at: vault.refreshed_at, companies: vault.companies }
307
396
  : null,
308
397
  machine_checks: { results: checks },
398
+ ...(isRecord(parsed.merge_holds) ? { merge_holds: parsed.merge_holds } : {}),
399
+ ...(isRecord(parsed.merge_approvals) ? { merge_approvals: parsed.merge_approvals } : {}),
400
+ ...(lanesMonitor ? { lanes_monitor: lanesMonitor } : {}),
309
401
  };
310
402
  }
311
403
  /** `person`, a company uid, or null for a slug that resolves to no uid (its flags are not written). */
@@ -360,6 +452,7 @@ export function createDaemonStateWriter(options) {
360
452
  const log = options.log ?? (() => { });
361
453
  let closed = false;
362
454
  let lastProblem;
455
+ let lanesMonitorProblem;
363
456
  // The file left from before the switch went off is removed once per off period.
364
457
  let removedWhileOff = false;
365
458
  const ownFile = options.defaultFile === undefined || path.resolve(options.defaultFile) === path.resolve(options.file);
@@ -373,7 +466,62 @@ export function createDaemonStateWriter(options) {
373
466
  log("info", "state file: written again");
374
467
  };
375
468
  const errorName = (error) => (error instanceof Error ? error.name : "UnknownError");
469
+ // The flags of the last registry request while the file is on; null before
470
+ // the first one and while it is off. Kept in memory only, never read back
471
+ // from the file.
472
+ let lastScopes = null;
473
+ /** Write the file; the problem to report, or undefined when it was written. */
474
+ const write = (now, scopes) => {
475
+ const merge = options.readMergeSections?.() ?? { merge_holds: null, merge_approvals: null };
476
+ let lanesMonitor = null;
477
+ try {
478
+ lanesMonitor = options.readLanesMonitor?.() ?? null;
479
+ if (lanesMonitorProblem)
480
+ log("info", "state file: lanes_monitor section computed again");
481
+ lanesMonitorProblem = undefined;
482
+ }
483
+ catch (error) {
484
+ // The hook reads a missing section as "no reminder"; the rest of the
485
+ // file is still written.
486
+ lanesMonitor = null;
487
+ const problem = errorName(error);
488
+ if (problem !== lanesMonitorProblem)
489
+ log("warn", `state file: lanes_monitor section left out (${problem})`);
490
+ lanesMonitorProblem = problem;
491
+ }
492
+ try {
493
+ writeDaemonStateFile(options.file, {
494
+ schema: DAEMON_STATE_SCHEMA,
495
+ written_at: now.toISOString(),
496
+ max_age_seconds: maxAgeSeconds,
497
+ flags: { scopes },
498
+ vault_access: options.readVaultAccess?.() ?? null,
499
+ machine_checks: { results: options.readMachineChecks?.() ?? [] },
500
+ merge_holds: merge.merge_holds,
501
+ merge_approvals: merge.merge_approvals,
502
+ ...(lanesMonitor ? { lanes_monitor: lanesMonitor } : {}),
503
+ }, { ...options.writeDeps, ...(options.defaultFile ? { defaultFile: options.defaultFile } : {}) });
504
+ }
505
+ catch (error) {
506
+ // Never the contents: the file holds the vault access list.
507
+ const code = error.code;
508
+ return `could not be written (${typeof code === "string" ? code : errorName(error)}); readers keep the previous file`;
509
+ }
510
+ return undefined;
511
+ };
376
512
  return {
513
+ refresh() {
514
+ if (closed || !lastScopes)
515
+ return;
516
+ try {
517
+ const problem = write(wallClock(), lastScopes);
518
+ if (problem)
519
+ report(problem);
520
+ }
521
+ catch {
522
+ // a failing section reader or log sink cannot reach the caller
523
+ }
524
+ },
377
525
  onRegistryRead(read, env) {
378
526
  if (closed)
379
527
  return;
@@ -381,6 +529,7 @@ export function createDaemonStateWriter(options) {
381
529
  const snapshot = !read.signedOut && read.errors.length === 0 ? read.client?.snapshot?.() ?? null : null;
382
530
  const off = (options.offReason ?? defaultOffReason)(read, env);
383
531
  if (off) {
532
+ lastScopes = null;
384
533
  let removed = "";
385
534
  if (!removedWhileOff && ownFile) {
386
535
  removedWhileOff = true;
@@ -401,25 +550,16 @@ export function createDaemonStateWriter(options) {
401
550
  // request: a file planted or loosened by another process is never
402
551
  // rewritten as the daemon's own, and when the daemon is signed out or
403
552
  // the request failed the flags are absent, so readers use each flag's
404
- // default.
553
+ // default. refresh() rewrites these same flags, with this request's
554
+ // fetched_at, until the next request.
405
555
  const scopes = {};
406
556
  if (snapshot && scope) {
407
557
  scopes[scope] = { fetched_at: now.toISOString(), values: daemonStateFlagValues(snapshot.flags) };
408
558
  }
409
- try {
410
- writeDaemonStateFile(options.file, {
411
- schema: DAEMON_STATE_SCHEMA,
412
- written_at: now.toISOString(),
413
- max_age_seconds: maxAgeSeconds,
414
- flags: { scopes },
415
- vault_access: options.readVaultAccess?.() ?? null,
416
- machine_checks: { results: options.readMachineChecks?.() ?? [] },
417
- }, { ...options.writeDeps, ...(options.defaultFile ? { defaultFile: options.defaultFile } : {}) });
418
- }
419
- catch (error) {
420
- // Never the contents: the file holds the vault access list.
421
- const code = error.code;
422
- report(`could not be written (${typeof code === "string" ? code : errorName(error)}); readers keep the previous file`);
559
+ lastScopes = scopes;
560
+ const problem = write(now, scopes);
561
+ if (problem) {
562
+ report(problem);
423
563
  return;
424
564
  }
425
565
  if (read.signedOut)
@@ -91,7 +91,7 @@ export interface SupervisedChild {
91
91
  on(event: "error", handler: (err: Error) => void): unknown;
92
92
  kill(signal?: NodeJS.Signals | number): boolean;
93
93
  }
94
- type UnitStatus = "running" | "waiting" | "unavailable" | "backoff" | "exited" | "idle" | "stopped" | "held";
94
+ type UnitStatus = "running" | "waiting" | "unavailable" | "backoff" | "exited" | "idle" | "stopped" | "held" | "paused";
95
95
  /**
96
96
  * Why a long-running unit is held down. `permanent`: the last exit had a cause
97
97
  * a restart cannot fix. `exhausted`: EPISODE_MAX_FAILURES failures without a
@@ -146,6 +146,8 @@ interface UnitState {
146
146
  lastRunAt?: number;
147
147
  nextRunAt?: number;
148
148
  lastResult?: "ok" | "failed";
149
+ /** Why the last run failed: one redacted, truncated line. Set for the in-process lanes reconcile. */
150
+ lastError?: string;
149
151
  lastHeartbeatAt?: string;
150
152
  lastPassResult?: ReturnType<typeof syncPassResult>;
151
153
  /** The pass-request folder the running child was started with; absent when it was not. */
@@ -16,6 +16,7 @@
16
16
  * and every service run the new version. The remote-control hosts notice an
17
17
  * updated Claude or Codex on disk themselves and restart once idle.
18
18
  */
19
+ import { daemonVersionFromBootstrapCommandLine } from "../../utils/daemon-cli-version.js";
19
20
  import type { SelfUpdateOutcome } from "../../utils/self-update.js";
20
21
  import type { HqCloudUpdateOutcome } from "./hq-cloud.js";
21
22
  import { type ToolInstall, type ToolName } from "./tools.js";
@@ -57,12 +58,7 @@ export interface UpdaterResult {
57
58
  }
58
59
  /** Only a strictly older, parseable daemon version triggers a restart, so a dev build never loops. */
59
60
  export declare function daemonIsOlderThanCli(running: string, installed: string): boolean;
60
- /**
61
- * The version a daemon handed to the staged child bootstrap that started this
62
- * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
63
- * Daemons have started units this way since 2026-10-05 (#1541).
64
- */
65
- export declare function daemonVersionFromBootstrapCommandLine(line: string | null): string | null;
61
+ export { daemonVersionFromBootstrapCommandLine };
66
62
  export interface RunningDaemonVersionDeps {
67
63
  /** Ask hqd; it listens only while HQ Anywhere is on, so this often fails. */
68
64
  ping: () => Promise<string>;
@@ -17,6 +17,7 @@
17
17
  * updated Claude or Codex on disk themselves and restart once idle.
18
18
  */
19
19
  import { spawnSync } from "node:child_process";
20
+ import { daemonVersionFromBootstrapCommandLine } from "../../utils/daemon-cli-version.js";
20
21
  import * as fs from "node:fs";
21
22
  import semver from "semver";
22
23
  import { locateTool, toolUpdateCommand } from "./tools.js";
@@ -26,17 +27,9 @@ export function daemonIsOlderThanCli(running, installed) {
26
27
  const i = semver.valid(installed);
27
28
  return r !== null && i !== null && semver.lt(r, i);
28
29
  }
29
- /**
30
- * The version a daemon handed to the staged child bootstrap that started this
31
- * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
32
- * Daemons have started units this way since 2026-10-05 (#1541).
33
- */
34
- export function daemonVersionFromBootstrapCommandLine(line) {
35
- if (!line)
36
- return null;
37
- const match = /hq-child-bootstrap\.m?js\s.*?(?:^|\s)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?=\s|$)/.exec(line);
38
- return match?.[1] ?? null;
39
- }
30
+ // Defined in the leaf module so client health can use it without importing the
31
+ // updater (resident daemon paths must not lazily import package modules).
32
+ export { daemonVersionFromBootstrapCommandLine };
40
33
  /**
41
34
  * The hq-cli version the running daemon was started from. hqd first; then the
42
35
  * version a newer daemon puts in the unit's environment; then the version an
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The daemon's cached `hq whoami` answer (hq-core-rust US-036).
3
+ *
4
+ * CLI commands that need the signed-in identity used to start `hq whoami
5
+ * --json` as a child, which loads the whole CLI and makes network calls. The
6
+ * daemon is already running on most machines, so it keeps the answer in
7
+ * `<daemon folder>/whoami.json` and those commands read the file instead.
8
+ *
9
+ * The file holds the identity `hq whoami --json` prints without `planLimits`:
10
+ * email, Cognito subject, delegated person, `prs_*`/`agt_*` uids, machine
11
+ * username and session expiry. No token is written. Like the state file it is
12
+ * 0600 in the per-host daemon folder and its contents are never logged.
13
+ *
14
+ * A reader uses the file only when it is current and still describes this
15
+ * session: the schema matches, it is younger than its stated maximum age, and
16
+ * the token source, subject, delegated subject, email, machine username and
17
+ * agent uid equal what the local token caches and machine credentials say now. The session fields that change with time
18
+ * (`authenticated`, `sessionExpiresAt`, `sessionExpiring`) are taken from the
19
+ * local caches, never from the file. Anything else (no daemon, a bot or a
20
+ * Windows box without one, a sign-in as someone else) reads as no answer, and
21
+ * the caller falls back to running `hq whoami` as before.
22
+ *
23
+ * The daemon refreshes the file on an in-process timer. The person-uid lookup
24
+ * is its only network call: once per signed-in subject, retried at most every
25
+ * 30 minutes while it has no answer.
26
+ */
27
+ import { type WhoamiIdentity, type WhoamiTokenIdentity } from "../../utils/whoami-identity.js";
28
+ export declare const WHOAMI_CACHE_SCHEMA = "hq-whoami.v1";
29
+ export declare const WHOAMI_CACHE_FILE = "whoami.json";
30
+ /** Written into the file; a reader ignores the file past this age. */
31
+ export declare const WHOAMI_CACHE_MAX_AGE_SECONDS = 1800;
32
+ /** How often the daemon rewrites the file. */
33
+ export declare const WHOAMI_CACHE_REFRESH_MS: number;
34
+ /** How long the daemon waits before asking again for a person uid it could not get. */
35
+ export declare const WHOAMI_PERSON_UID_RETRY_MS: number;
36
+ export interface WhoamiCacheFile {
37
+ schema: typeof WHOAMI_CACHE_SCHEMA;
38
+ written_at: string;
39
+ max_age_seconds: number;
40
+ identity: WhoamiIdentity;
41
+ }
42
+ /**
43
+ * `HQ_WHOAMI_CACHE_FILE` when set in `env` or in this process (tests and
44
+ * isolated daemons), else `<daemon folder>/whoami.json` for this home.
45
+ */
46
+ export declare function whoamiCachePath(home?: string, env?: NodeJS.ProcessEnv): string;
47
+ /** The file, or null when it is not a complete, current-schema, unexpired file at `now`. */
48
+ export declare function parseWhoamiCache(text: string, now?: Date): WhoamiCacheFile | null;
49
+ export interface ReadCachedWhoamiOptions {
50
+ home?: string;
51
+ env?: NodeJS.ProcessEnv;
52
+ now?: Date;
53
+ /** This session's identity from the local token caches (no network). Read only when the file exists. */
54
+ local: () => WhoamiIdentity;
55
+ /** Test seam for the file read. */
56
+ readFile?: (file: string) => string | null;
57
+ }
58
+ /**
59
+ * The daemon's whoami answer for this session, or null when the caller
60
+ * should run `hq whoami` itself (see the file comment).
61
+ */
62
+ export declare function readCachedWhoami(options: ReadCachedWhoamiOptions): WhoamiIdentity | null;
63
+ /**
64
+ * What `hq whoami` (plain, or `--json`) would print for `identity`, for
65
+ * callers that parse that output. `--json` matches the command's own output
66
+ * with `planLimits` unknown (null); the plain form carries the identity lines
67
+ * only, without the plan or deleted-company notices.
68
+ */
69
+ export declare function renderCachedWhoami(identity: WhoamiIdentity, json: boolean): string;
70
+ export interface WhoamiCacheWriterOptions {
71
+ home: string;
72
+ env: NodeJS.ProcessEnv;
73
+ log: (level: "info" | "warn" | "error", message: string) => void;
74
+ /** Builds the identity; `readPersonUid` is called only for an authenticated person session. */
75
+ build: (readPersonUid: (token: WhoamiTokenIdentity) => Promise<string | null>) => Promise<WhoamiIdentity>;
76
+ /** The network person-uid lookup (`hq whoami`'s own). */
77
+ lookupPersonUid: (token: WhoamiTokenIdentity) => Promise<string | null>;
78
+ intervalMs?: number;
79
+ now?: () => number;
80
+ schedule?: (callback: () => void, delayMs: number) => () => void;
81
+ write?: (file: string, text: string) => void;
82
+ }
83
+ export interface WhoamiCacheWriter {
84
+ /** Rewrite the file now. Resolves when written; a failure is logged, never thrown. */
85
+ refresh(): Promise<void>;
86
+ close(): void;
87
+ }
88
+ /** The daemon side: write the file at start and on an in-process timer. */
89
+ export declare function startWhoamiCacheWriter(options: WhoamiCacheWriterOptions): WhoamiCacheWriter;
90
+ /**
91
+ * For CLI commands that used to run `hq whoami [--json]`: that command's
92
+ * output from the daemon's cached answer, or null when there is no usable
93
+ * answer and the caller should run `hq whoami` itself.
94
+ */
95
+ export declare function daemonWhoamiOutput(json: boolean, env?: NodeJS.ProcessEnv): string | null;
96
+ //# sourceMappingURL=whoami-cache.d.ts.map
@@ -0,0 +1,244 @@
1
+ /**
2
+ * The daemon's cached `hq whoami` answer (hq-core-rust US-036).
3
+ *
4
+ * CLI commands that need the signed-in identity used to start `hq whoami
5
+ * --json` as a child, which loads the whole CLI and makes network calls. The
6
+ * daemon is already running on most machines, so it keeps the answer in
7
+ * `<daemon folder>/whoami.json` and those commands read the file instead.
8
+ *
9
+ * The file holds the identity `hq whoami --json` prints without `planLimits`:
10
+ * email, Cognito subject, delegated person, `prs_*`/`agt_*` uids, machine
11
+ * username and session expiry. No token is written. Like the state file it is
12
+ * 0600 in the per-host daemon folder and its contents are never logged.
13
+ *
14
+ * A reader uses the file only when it is current and still describes this
15
+ * session: the schema matches, it is younger than its stated maximum age, and
16
+ * the token source, subject, delegated subject, email, machine username and
17
+ * agent uid equal what the local token caches and machine credentials say now. The session fields that change with time
18
+ * (`authenticated`, `sessionExpiresAt`, `sessionExpiring`) are taken from the
19
+ * local caches, never from the file. Anything else (no daemon, a bot or a
20
+ * Windows box without one, a sign-in as someone else) reads as no answer, and
21
+ * the caller falls back to running `hq whoami` as before.
22
+ *
23
+ * The daemon refreshes the file on an in-process timer. The person-uid lookup
24
+ * is its only network call: once per signed-in subject, retried at most every
25
+ * 30 minutes while it has no answer.
26
+ */
27
+ import * as os from "node:os";
28
+ import * as path from "node:path";
29
+ import { daemonPaths, readStoreFile, StoreRefusedError, writeStoreFile } from "./paths.js";
30
+ import { localWhoamiIdentity } from "../../utils/whoami-identity.js";
31
+ export const WHOAMI_CACHE_SCHEMA = "hq-whoami.v1";
32
+ export const WHOAMI_CACHE_FILE = "whoami.json";
33
+ /** Written into the file; a reader ignores the file past this age. */
34
+ export const WHOAMI_CACHE_MAX_AGE_SECONDS = 1800;
35
+ /** How often the daemon rewrites the file. */
36
+ export const WHOAMI_CACHE_REFRESH_MS = 5 * 60_000;
37
+ /** How long the daemon waits before asking again for a person uid it could not get. */
38
+ export const WHOAMI_PERSON_UID_RETRY_MS = 30 * 60_000;
39
+ const MAX_FILE_BYTES = 64 * 1024;
40
+ /** A file dated this far in the future is treated as unreadable. */
41
+ const FUTURE_SKEW_MS = 60_000;
42
+ /**
43
+ * `HQ_WHOAMI_CACHE_FILE` when set in `env` or in this process (tests and
44
+ * isolated daemons), else `<daemon folder>/whoami.json` for this home.
45
+ */
46
+ export function whoamiCachePath(home = os.homedir(), env = process.env) {
47
+ const explicit = env.HQ_WHOAMI_CACHE_FILE?.trim() || process.env.HQ_WHOAMI_CACHE_FILE?.trim();
48
+ if (explicit)
49
+ return explicit;
50
+ return path.join(daemonPaths(home, env).root, WHOAMI_CACHE_FILE);
51
+ }
52
+ function isRecord(value) {
53
+ return typeof value === "object" && value !== null && !Array.isArray(value);
54
+ }
55
+ const stringOrNull = (value) => value === null || typeof value === "string";
56
+ function parseIdentity(value) {
57
+ if (!isRecord(value) || value.schemaVersion !== 1)
58
+ return null;
59
+ if (typeof value.authenticated !== "boolean")
60
+ return null;
61
+ if (value.tokenSource !== "machine" && value.tokenSource !== "person")
62
+ return null;
63
+ for (const key of ["email", "sub", "delegatedEmail", "delegatedSub", "personUid", "agentUid", "username", "sessionExpiresAt"]) {
64
+ if (!stringOrNull(value[key]))
65
+ return null;
66
+ }
67
+ if (value.sessionExpiring !== null && typeof value.sessionExpiring !== "boolean")
68
+ return null;
69
+ return {
70
+ schemaVersion: 1,
71
+ authenticated: value.authenticated,
72
+ tokenSource: value.tokenSource,
73
+ email: value.email,
74
+ sub: value.sub,
75
+ delegatedEmail: value.delegatedEmail,
76
+ delegatedSub: value.delegatedSub,
77
+ personUid: value.personUid,
78
+ agentUid: value.agentUid,
79
+ username: value.username,
80
+ sessionExpiresAt: value.sessionExpiresAt,
81
+ sessionExpiring: value.sessionExpiring,
82
+ };
83
+ }
84
+ /** The file, or null when it is not a complete, current-schema, unexpired file at `now`. */
85
+ export function parseWhoamiCache(text, now = new Date()) {
86
+ let parsed;
87
+ try {
88
+ parsed = JSON.parse(text);
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ if (!isRecord(parsed) || parsed.schema !== WHOAMI_CACHE_SCHEMA)
94
+ return null;
95
+ if (typeof parsed.written_at !== "string" || typeof parsed.max_age_seconds !== "number")
96
+ return null;
97
+ const writtenAt = Date.parse(parsed.written_at);
98
+ if (!Number.isFinite(writtenAt) || !Number.isFinite(parsed.max_age_seconds) || parsed.max_age_seconds <= 0)
99
+ return null;
100
+ const age = now.getTime() - writtenAt;
101
+ if (age < -FUTURE_SKEW_MS || age > parsed.max_age_seconds * 1000)
102
+ return null;
103
+ const identity = parseIdentity(parsed.identity);
104
+ if (!identity)
105
+ return null;
106
+ return { schema: WHOAMI_CACHE_SCHEMA, written_at: parsed.written_at, max_age_seconds: parsed.max_age_seconds, identity };
107
+ }
108
+ /**
109
+ * The daemon's whoami answer for this session, or null when the caller
110
+ * should run `hq whoami` itself (see the file comment).
111
+ */
112
+ export function readCachedWhoami(options) {
113
+ const file = whoamiCachePath(options.home ?? options.env?.HOME ?? os.homedir(), options.env ?? process.env);
114
+ let text;
115
+ try {
116
+ text = options.readFile ? options.readFile(file) : readStoreFile(file, MAX_FILE_BYTES)?.text ?? null;
117
+ }
118
+ catch {
119
+ return null;
120
+ }
121
+ if (text === null)
122
+ return null;
123
+ const cached = parseWhoamiCache(text, options.now ?? new Date());
124
+ if (!cached)
125
+ return null;
126
+ let local;
127
+ try {
128
+ local = options.local();
129
+ }
130
+ catch {
131
+ return null;
132
+ }
133
+ const identity = cached.identity;
134
+ if (local.tokenSource !== identity.tokenSource
135
+ || local.sub !== identity.sub
136
+ || local.email !== identity.email
137
+ || local.delegatedSub !== identity.delegatedSub
138
+ || local.delegatedEmail !== identity.delegatedEmail
139
+ || local.username !== identity.username
140
+ // A re-enrolled machine can keep its username and get a new agt_* uid.
141
+ || local.agentUid !== identity.agentUid)
142
+ return null;
143
+ return {
144
+ ...identity,
145
+ authenticated: local.authenticated,
146
+ sessionExpiresAt: local.sessionExpiresAt,
147
+ sessionExpiring: local.sessionExpiring,
148
+ personUid: local.authenticated ? identity.personUid : null,
149
+ };
150
+ }
151
+ /**
152
+ * What `hq whoami` (plain, or `--json`) would print for `identity`, for
153
+ * callers that parse that output. `--json` matches the command's own output
154
+ * with `planLimits` unknown (null); the plain form carries the identity lines
155
+ * only, without the plan or deleted-company notices.
156
+ */
157
+ export function renderCachedWhoami(identity, json) {
158
+ if (json)
159
+ return `${JSON.stringify({ ...identity, planLimits: null }, null, 2)}\n`;
160
+ if (identity.tokenSource === "machine") {
161
+ return `Machine identity ${identity.username ?? "unknown"}${identity.agentUid ? ` (agent ${identity.agentUid})` : ""} — sessions mint automatically\ntoken source: machine\n`;
162
+ }
163
+ if (identity.sessionExpiresAt === null)
164
+ return "Not logged in. Run 'hq login' to authenticate.\n";
165
+ if (!identity.authenticated) {
166
+ return `Session expired for ${identity.email ?? "unknown"}. Run 'hq login' to re-authenticate.\ntoken source: person\n`;
167
+ }
168
+ return `Logged in as ${identity.email ?? "unknown"}${identity.sub ? ` (${identity.sub})` : ""}\ntoken source: person\n`;
169
+ }
170
+ /** The daemon side: write the file at start and on an in-process timer. */
171
+ export function startWhoamiCacheWriter(options) {
172
+ const now = options.now ?? Date.now;
173
+ const file = whoamiCachePath(options.home, options.env);
174
+ const write = options.write ?? ((target, text) => writeStoreFile(target, text, { create: true }));
175
+ const schedule = options.schedule ?? ((callback, delayMs) => {
176
+ const timer = setInterval(callback, delayMs);
177
+ timer.unref();
178
+ return () => clearInterval(timer);
179
+ });
180
+ // One person-uid lookup per subject; a missing answer is asked again after WHOAMI_PERSON_UID_RETRY_MS.
181
+ let memo = null;
182
+ let closed = false;
183
+ let inFlight = null;
184
+ let lastError = null;
185
+ const personUid = async (token) => {
186
+ const key = `${token.sub ?? ""}|${token.entityUid ?? ""}`;
187
+ if (memo && memo.key === key && (memo.personUid !== null || now() - memo.at < WHOAMI_PERSON_UID_RETRY_MS))
188
+ return memo.personUid;
189
+ const found = await options.lookupPersonUid(token);
190
+ memo = { key, personUid: found, at: now() };
191
+ return found;
192
+ };
193
+ const refresh = () => {
194
+ if (closed)
195
+ return Promise.resolve();
196
+ if (inFlight)
197
+ return inFlight;
198
+ inFlight = (async () => {
199
+ try {
200
+ const identity = await options.build(personUid);
201
+ if (closed)
202
+ return;
203
+ const body = {
204
+ schema: WHOAMI_CACHE_SCHEMA,
205
+ written_at: new Date(now()).toISOString(),
206
+ max_age_seconds: WHOAMI_CACHE_MAX_AGE_SECONDS,
207
+ identity,
208
+ };
209
+ write(file, `${JSON.stringify(body, null, 2)}\n`);
210
+ lastError = null;
211
+ }
212
+ catch (error) {
213
+ const message = error instanceof StoreRefusedError ? error.code : error instanceof Error ? error.name : "UnknownError";
214
+ if (message !== lastError)
215
+ options.log("warn", `could not refresh the cached whoami answer (${message}); CLI commands run hq whoami instead`);
216
+ lastError = message;
217
+ }
218
+ })().finally(() => {
219
+ inFlight = null;
220
+ });
221
+ return inFlight;
222
+ };
223
+ void refresh();
224
+ const cancel = schedule(() => { void refresh(); }, options.intervalMs ?? WHOAMI_CACHE_REFRESH_MS);
225
+ return {
226
+ refresh,
227
+ close() {
228
+ if (closed)
229
+ return;
230
+ closed = true;
231
+ cancel();
232
+ },
233
+ };
234
+ }
235
+ /**
236
+ * For CLI commands that used to run `hq whoami [--json]`: that command's
237
+ * output from the daemon's cached answer, or null when there is no usable
238
+ * answer and the caller should run `hq whoami` itself.
239
+ */
240
+ export function daemonWhoamiOutput(json, env = process.env) {
241
+ const identity = readCachedWhoami({ env, local: () => localWhoamiIdentity(env) });
242
+ return identity ? renderCachedWhoami(identity, json) : null;
243
+ }
244
+ //# sourceMappingURL=whoami-cache.js.map