@indigoai-us/hq-cli 5.345.223 → 5.345.225

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 (96) hide show
  1. package/CHANGELOG.md +66 -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 +78 -4
  5. package/dist/command-catalog.generated.js +94 -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 +67 -1
  24. package/dist/commands/lanes-hold.d.ts +2 -27
  25. package/dist/commands/lanes-hold.js +3 -75
  26. package/dist/commands/lanes-loop.js +1 -1
  27. package/dist/commands/lanes-session-start.js +2 -2
  28. package/dist/commands/mesh.d.ts +12 -0
  29. package/dist/commands/mesh.js +13 -4
  30. package/dist/commands/monitor.js +1 -1
  31. package/dist/commands/packs.js +1 -1
  32. package/dist/commands/whoami.d.ts +10 -17
  33. package/dist/commands/whoami.js +7 -79
  34. package/dist/data/command-states.json +13 -0
  35. package/dist/index.js +1 -1
  36. package/dist/lib/daemon/catalog.d.ts +8 -5
  37. package/dist/lib/daemon/catalog.js +13 -7
  38. package/dist/lib/daemon/config.d.ts +5 -0
  39. package/dist/lib/daemon/config.js +6 -0
  40. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  41. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  42. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  43. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  44. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  45. package/dist/lib/daemon/merge-sections.js +556 -0
  46. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  47. package/dist/lib/daemon/ops/policy.js +1 -1
  48. package/dist/lib/daemon/protocol.d.ts +1 -1
  49. package/dist/lib/daemon/protocol.js +0 -6
  50. package/dist/lib/daemon/run.js +73 -1
  51. package/dist/lib/daemon/selfcheck.js +2 -2
  52. package/dist/lib/daemon/server.d.ts +2 -4
  53. package/dist/lib/daemon/server.js +5 -48
  54. package/dist/lib/daemon/state-file.d.ts +74 -4
  55. package/dist/lib/daemon/state-file.js +159 -19
  56. package/dist/lib/daemon/supervisor.d.ts +1 -1
  57. package/dist/lib/daemon/updater.d.ts +2 -6
  58. package/dist/lib/daemon/updater.js +4 -11
  59. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  60. package/dist/lib/daemon/whoami-cache.js +244 -0
  61. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  62. package/dist/lib/hook-engine/coverage.js +71 -0
  63. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  64. package/dist/lib/hook-engine/reconcile.js +14 -8
  65. package/dist/lib/install/hook-target.d.ts +13 -3
  66. package/dist/lib/install/hook-target.js +14 -11
  67. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  68. package/dist/lib/lanes/monitor.d.ts +2 -0
  69. package/dist/lib/lanes/monitor.js +2 -1
  70. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  71. package/dist/lib/lanes/registry-flag.js +3 -2
  72. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  73. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  74. package/dist/lib/lanes/watcher-main.js +3 -3
  75. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  76. package/dist/lib/mesh/live/daemon/install.js +2 -2
  77. package/dist/lib/windows/install-followup.js +1 -1
  78. package/dist/utils/client-health-contract.d.ts +1 -0
  79. package/dist/utils/client-health-contract.js +5 -0
  80. package/dist/utils/client-health.d.ts +2 -0
  81. package/dist/utils/client-health.js +40 -0
  82. package/dist/utils/cognito-session.d.ts +2 -14
  83. package/dist/utils/cognito-session.js +2 -40
  84. package/dist/utils/daemon-cli-version.d.ts +13 -0
  85. package/dist/utils/daemon-cli-version.js +47 -0
  86. package/dist/utils/duplicate-command-usage.js +1 -1
  87. package/dist/utils/machine-token-cache.d.ts +21 -0
  88. package/dist/utils/machine-token-cache.js +49 -0
  89. package/dist/utils/resident-package-preload.js +4 -0
  90. package/dist/utils/whoami-identity.d.ts +54 -0
  91. package/dist/utils/whoami-identity.js +108 -0
  92. package/package.json +7 -7
  93. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  94. package/dist/lib/daemon/ops/memory.js +0 -65
  95. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  96. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Repository merge hold records (`hq lanes hold`, src/commands/lanes-hold.ts):
3
+ * their location, their format and the parser that accepts or refuses one.
4
+ * Kept apart from the command so the daemon (merge-sections.ts) can read hold
5
+ * records without loading the lanes runtime.
6
+ */
7
+ import type { LaneCompanyRef } from "./types.js";
8
+ export declare const LANES_REPO_MERGE_HOLD_FLAG = "lanes.repo-merge-hold";
9
+ export declare const LANES_REVIEW_BEFORE_MERGE_FLAG = "lanes.review-before-merge";
10
+ export declare const REPO_MERGE_HOLDS_REL: string;
11
+ export declare const HOLD_SCHEMA_VERSION = "hq-lanes-repo-merge-hold.v1";
12
+ export declare const HOLD_HISTORY_CAP = 50;
13
+ export interface HoldHistoryEntry {
14
+ set_at: string;
15
+ until: string;
16
+ reason: string;
17
+ set_by_lane: string | null;
18
+ set_by_session: string | null;
19
+ released_at?: string;
20
+ released_reason?: string;
21
+ }
22
+ export interface RepoMergeHold {
23
+ schema_version: typeof HOLD_SCHEMA_VERSION;
24
+ repo: string;
25
+ company: LaneCompanyRef;
26
+ reason: string;
27
+ set_at: string;
28
+ until: string;
29
+ set_by_lane: string | null;
30
+ set_by_session: string | null;
31
+ released_at?: string;
32
+ released_reason?: string;
33
+ history: HoldHistoryEntry[];
34
+ }
35
+ /** `<hqRoot>/workspace/lanes/holds/<owner>__<repo>.json`. */
36
+ export declare function holdFilePath(hqRoot: string, repo: string): string;
37
+ /** A hold record as `hq lanes hold` accepts it; throws LanesError for any other value. */
38
+ export declare function parseHold(raw: unknown, file: string): RepoMergeHold;
39
+ //# sourceMappingURL=repo-merge-hold.d.ts.map
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Repository merge hold records (`hq lanes hold`, src/commands/lanes-hold.ts):
3
+ * their location, their format and the parser that accepts or refuses one.
4
+ * Kept apart from the command so the daemon (merge-sections.ts) can read hold
5
+ * records without loading the lanes runtime.
6
+ */
7
+ import * as path from "node:path";
8
+ import { LanesError } from "./errors.js";
9
+ import { canonicalRepo } from "./merge-command.js";
10
+ import { assertNoSecretText } from "./text-scan.js";
11
+ export const LANES_REPO_MERGE_HOLD_FLAG = "lanes.repo-merge-hold";
12
+ export const LANES_REVIEW_BEFORE_MERGE_FLAG = "lanes.review-before-merge";
13
+ export const REPO_MERGE_HOLDS_REL = path.join("workspace", "lanes", "holds");
14
+ export const HOLD_SCHEMA_VERSION = "hq-lanes-repo-merge-hold.v1";
15
+ export const HOLD_HISTORY_CAP = 50;
16
+ function fail(error, message, details = {}) {
17
+ throw new LanesError(error, message, details);
18
+ }
19
+ /** `<hqRoot>/workspace/lanes/holds/<owner>__<repo>.json`. */
20
+ export function holdFilePath(hqRoot, repo) {
21
+ const [owner, repository] = canonicalRepo(repo).split("/");
22
+ return path.join(hqRoot, REPO_MERGE_HOLDS_REL, `${owner}__${repository}.json`);
23
+ }
24
+ function isObject(value) {
25
+ return value !== null && typeof value === "object" && !Array.isArray(value);
26
+ }
27
+ function isCanonicalTimestamp(value) {
28
+ if (typeof value !== "string")
29
+ return false;
30
+ const timestamp = Date.parse(value);
31
+ return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
32
+ }
33
+ /** A hold record as `hq lanes hold` accepts it; throws LanesError for any other value. */
34
+ export function parseHold(raw, file) {
35
+ if (!isObject(raw))
36
+ return fail("repo_hold_invalid", "Merge hold record must be an object", { path: file });
37
+ const company = raw.company;
38
+ const history = raw.history;
39
+ if (raw.schema_version !== HOLD_SCHEMA_VERSION || typeof raw.repo !== "string" ||
40
+ !isObject(company) || typeof company.slug !== "string" || !company.slug.trim() ||
41
+ typeof company.uid !== "string" || !company.uid.trim() ||
42
+ typeof raw.reason !== "string" || !raw.reason.trim() ||
43
+ !isCanonicalTimestamp(raw.set_at) || !isCanonicalTimestamp(raw.until) ||
44
+ !(raw.set_by_lane === null || typeof raw.set_by_lane === "string") ||
45
+ !(raw.set_by_session === null || typeof raw.set_by_session === "string") ||
46
+ !Array.isArray(history) || history.length > HOLD_HISTORY_CAP ||
47
+ (raw.released_at !== undefined && !isCanonicalTimestamp(raw.released_at)) ||
48
+ (raw.released_reason !== undefined && typeof raw.released_reason !== "string")) {
49
+ return fail("repo_hold_invalid", "Merge hold record has invalid fields", { path: file });
50
+ }
51
+ let repo;
52
+ try {
53
+ repo = canonicalRepo(raw.repo);
54
+ }
55
+ catch {
56
+ return fail("repo_hold_invalid", "Merge hold record has an invalid repository", { path: file });
57
+ }
58
+ if (repo !== raw.repo)
59
+ return fail("repo_hold_invalid", "Merge hold repository is not canonical", { path: file });
60
+ if ((raw.released_at === undefined) !== (raw.released_reason === undefined)) {
61
+ return fail("repo_hold_invalid", "Released merge hold must include both release fields", { path: file });
62
+ }
63
+ if (raw.released_at !== undefined && (!raw.released_reason || !raw.released_reason.trim())) {
64
+ return fail("repo_hold_invalid", "Released merge hold is missing its reason", { path: file });
65
+ }
66
+ assertNoSecretText("hold.reason", raw.reason);
67
+ if (typeof raw.released_reason === "string")
68
+ assertNoSecretText("hold.released_reason", raw.released_reason);
69
+ for (const entry of history) {
70
+ if (!isObject(entry) || !isCanonicalTimestamp(entry.set_at) || !isCanonicalTimestamp(entry.until) ||
71
+ typeof entry.reason !== "string" || !entry.reason.trim() ||
72
+ !(entry.set_by_lane === null || typeof entry.set_by_lane === "string") ||
73
+ !(entry.set_by_session === null || typeof entry.set_by_session === "string") ||
74
+ (entry.released_at !== undefined && !isCanonicalTimestamp(entry.released_at)) ||
75
+ (entry.released_reason !== undefined && typeof entry.released_reason !== "string")) {
76
+ return fail("repo_hold_invalid", "Merge hold history has invalid entries", { path: file });
77
+ }
78
+ if ((entry.released_at === undefined) !== (entry.released_reason === undefined)) {
79
+ return fail("repo_hold_invalid", "Merge hold history release fields are incomplete", { path: file });
80
+ }
81
+ if (entry.released_reason !== undefined && !entry.released_reason.trim()) {
82
+ return fail("repo_hold_invalid", "Merge hold history release reason is empty", { path: file });
83
+ }
84
+ assertNoSecretText("hold.history.reason", entry.reason);
85
+ if (typeof entry.released_reason === "string")
86
+ assertNoSecretText("hold.history.released_reason", entry.released_reason);
87
+ }
88
+ return raw;
89
+ }
90
+ //# sourceMappingURL=repo-merge-hold.js.map
@@ -22,7 +22,7 @@ export function watcherMainDeps(hqRoot, laneId, env = process.env, repairDispatc
22
22
  spawnRepair: (root, lane, input) => spawnEnvelopeRepairViaCurrentCli(root, lane, input, { ...repairDispatchDeps, env }),
23
23
  deliverLaneSeniorMessage: async (seniorLaneId, text) => deliverLaneSeniorMessage(cliEntry, seniorLaneId, text),
24
24
  recoverQueuedMessages: async () => {
25
- const result = spawnSync(liveNodeBinary(), [cliEntry, "lanes", "_recover-queued-messages", laneId], {
25
+ const result = spawnSync(liveNodeBinary(), [cliEntry, "runners", "_recover-queued-messages", laneId], {
26
26
  env,
27
27
  encoding: "utf8",
28
28
  timeout: 120_000,
@@ -37,7 +37,7 @@ export function watcherMainDeps(hqRoot, laneId, env = process.env, repairDispatc
37
37
  await new Promise((resolve, reject) => {
38
38
  const child = spawn(liveNodeBinary(), [
39
39
  cliEntry,
40
- "lanes",
40
+ "runners",
41
41
  "_keep-alive-terminal-trigger",
42
42
  scheduledLaneId,
43
43
  String(version),
@@ -55,7 +55,7 @@ export function watcherMainDeps(hqRoot, laneId, env = process.env, repairDispatc
55
55
  };
56
56
  }
57
57
  function deliverLaneSeniorMessage(cliEntry, laneId, text) {
58
- const result = spawnSync(liveNodeBinary(), [cliEntry, "lanes", "message", laneId, "--text", text], {
58
+ const result = spawnSync(liveNodeBinary(), [cliEntry, "runners", "message", laneId, "--text", text], {
59
59
  env: process.env,
60
60
  encoding: "utf8",
61
61
  timeout: 120_000,
@@ -106,7 +106,7 @@ export function formatCliMismatchLine(input) {
106
106
  const recordedAt = recordedEntry || "(none)";
107
107
  const currentAt = input.currentEntry || "(none)";
108
108
  return (`daemon hq ${recordedLabel} at ${recordedAt} does not match this CLI ` +
109
- `${input.currentVersion} at ${currentAt}. Run hq mesh daemon install to repoint it.`);
109
+ `${input.currentVersion} at ${currentAt}. Run hq daemon install to repoint it.`);
110
110
  }
111
111
  export function formatCliIdentityLines(report) {
112
112
  const lines = [];
@@ -350,7 +350,7 @@ export function repairMeshUnitFromOtherHome(opts = {}) {
350
350
  repaired: true,
351
351
  action: "removed",
352
352
  from: other.from,
353
- message: `${found} Stopped it. Start the real one with: hq mesh daemon install`,
353
+ message: `${found} Stopped it. Start the real one with: hq daemon install`,
354
354
  };
355
355
  }
356
356
  const env = opts.env ?? process.env;
@@ -374,7 +374,7 @@ export function repairMeshUnitFromOtherHome(opts = {}) {
374
374
  repaired: false,
375
375
  action: "removed",
376
376
  from: other.from,
377
- message: `${found} Stopped it, but starting the real one failed: ${error instanceof Error ? error.message : String(error)}. Run: hq mesh daemon install`,
377
+ message: `${found} Stopped it, but starting the real one failed: ${error instanceof Error ? error.message : String(error)}. Run: hq daemon install`,
378
378
  };
379
379
  }
380
380
  }
@@ -20,7 +20,7 @@ export function isInstallFollowupSkipped(argv, env) {
20
20
  const args = argv.slice(2).filter((arg) => arg !== "--verbose");
21
21
  if (args[0] === "mesh" && args[1] === "daemon")
22
22
  return true;
23
- if (args[0] === "daemon" && (args[1] === "run" || args[1] === "install"))
23
+ if (args[0] === "daemon" && (args[1] === "run" || args[1] === "install" || args[1] === "service"))
24
24
  return true;
25
25
  return false;
26
26
  }
@@ -157,6 +157,7 @@ export interface ClientHealthHeartbeat {
157
157
  daemonHqCloudUpdateOutcome?: ClientHealthDaemonHqCloudUpdateOutcome;
158
158
  daemonHqCloudUpdateTarget?: string;
159
159
  daemonHqCloudUpdateErrorClass?: ClientHealthDaemonHqCloudUpdateErrorClass;
160
+ daemonCliVersion?: string;
160
161
  /** Absent on older clients / non-sync-outcome events. See {@link ClientHealthLocalFilesOverview}. */
161
162
  localFilesOverview?: ClientHealthLocalFilesOverview;
162
163
  }
@@ -328,6 +328,11 @@ export function parseClientHealthHeartbeat(input) {
328
328
  heartbeat.daemonHqCloudUpdateTarget = target;
329
329
  }
330
330
  copyKnownOptionalEnum(heartbeat, "daemonHqCloudUpdateErrorClass", raw.daemonHqCloudUpdateErrorClass, CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_ERROR_CLASSES);
331
+ if (raw.daemonCliVersion !== undefined) {
332
+ const daemonCliVersion = copyValidOptionalDiagnostic("daemonCliVersion", raw.daemonCliVersion, assertVersion);
333
+ if (daemonCliVersion !== undefined)
334
+ heartbeat.daemonCliVersion = daemonCliVersion;
335
+ }
331
336
  if (raw.localFilesOverview !== undefined) {
332
337
  heartbeat.localFilesOverview = parseClientHealthLocalFilesOverview("localFilesOverview", raw.localFilesOverview);
333
338
  }
@@ -179,6 +179,7 @@ export interface BuildCliHeartbeatInput {
179
179
  */
180
180
  localFilesOverview?: ClientHealthLocalFilesOverview | null;
181
181
  syncEngine?: CliSyncEngine | null;
182
+ daemonCliVersion?: string | null;
182
183
  }
183
184
  export interface CliSyncEngine {
184
185
  release: string;
@@ -212,6 +213,7 @@ export interface ClientHealthDeps {
212
213
  /** US-016: overridable for tests; defaults to {@link collectLocalFilesOverview}. */
213
214
  localFilesOverview?: () => ClientHealthLocalFilesOverview;
214
215
  syncEngine?: () => CliSyncEngine | null;
216
+ daemonCliVersion?: () => Promise<string | null>;
215
217
  /** Override for {@link JOURNAL_OBSERVATION_TTL_MS}. */
216
218
  journalObservationTtlMs?: number;
217
219
  /** Override for {@link JOURNAL_OBSERVATION_LOCK_STALE_MS}. */
@@ -40,6 +40,7 @@ import { getStateDir, listJournals } from "@indigoai-us/hq-cloud";
40
40
  import { isExpiring, isMachineIdentity, loadCachedTokens, } from "./cognito-session.js";
41
41
  import { vaultApiFetch } from "./vault-api.js";
42
42
  import { collectVersions } from "./feedback-versions.js";
43
+ import { resolveDaemonCliVersion } from "./daemon-cli-version.js";
43
44
  import { isAuthError } from "./auth-error.js";
44
45
  import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, parseClientHealthHeartbeat, } from "./client-health-contract.js";
45
46
  import { collectLocalFilesOverview } from "./local-files-overview.js";
@@ -508,6 +509,9 @@ export function buildCliHeartbeat(input) {
508
509
  if (SEMVER.test(engineVersion))
509
510
  versions.syncEngine = engineVersion;
510
511
  }
512
+ if (input.daemonCliVersion && SEMVER.test(input.daemonCliVersion)) {
513
+ heartbeat.daemonCliVersion = input.daemonCliVersion;
514
+ }
511
515
  return heartbeat;
512
516
  }
513
517
  const defaultPoster = (heartbeat, token, signal) => vaultApiFetch({
@@ -674,6 +678,16 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
674
678
  catch {
675
679
  syncEngine = null;
676
680
  }
681
+ // Bounded on its own budget so a slow parent-process lookup (up to 2 s on
682
+ // Windows) leaves the field off instead of using up the whole
683
+ // contribution bound and dropping the heartbeat.
684
+ let daemonCliVersion = null;
685
+ try {
686
+ daemonCliVersion = await valueWithin((deps.daemonCliVersion ?? processDaemonCliVersion)(), DAEMON_CLI_VERSION_BUDGET_MS);
687
+ }
688
+ catch {
689
+ daemonCliVersion = null;
690
+ }
677
691
  const heartbeat = buildCliHeartbeat({
678
692
  kind,
679
693
  state,
@@ -684,6 +698,7 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
684
698
  localFilesOverview,
685
699
  failureReason,
686
700
  syncEngine,
701
+ daemonCliVersion,
687
702
  });
688
703
  if (!heartbeat)
689
704
  return;
@@ -706,6 +721,31 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
706
721
  // Health contribution is best effort and must never affect a CLI command.
707
722
  }
708
723
  }
724
+ /**
725
+ * How long one heartbeat waits for the daemon CLI version. Well inside
726
+ * {@link CLIENT_HEALTH_TIMEOUT_MS}. The lookup is memoised per process, so a
727
+ * value that misses this budget is still used by later heartbeats.
728
+ */
729
+ const DAEMON_CLI_VERSION_BUDGET_MS = 300;
730
+ /** Resolve with `work`'s value, or null if it rejects or takes longer than `ms`. */
731
+ function valueWithin(work, ms) {
732
+ return new Promise((resolve) => {
733
+ const timer = setTimeout(() => resolve(null), ms);
734
+ timer.unref?.();
735
+ work.then((value) => {
736
+ clearTimeout(timer);
737
+ resolve(value);
738
+ }, () => {
739
+ clearTimeout(timer);
740
+ resolve(null);
741
+ });
742
+ });
743
+ }
744
+ let daemonCliVersionPromise;
745
+ function processDaemonCliVersion() {
746
+ daemonCliVersionPromise ??= resolveDaemonCliVersion().catch(() => null);
747
+ return daemonCliVersionPromise;
748
+ }
709
749
  // ─── Command wiring ──────────────────────────────────────────────────────────
710
750
  let invocationPromise;
711
751
  /**
@@ -20,6 +20,8 @@
20
20
  */
21
21
  import { isExpiring, isMachineIdentity, type CognitoAuthConfig, type CognitoTokens, type ClientInfo, type VaultServiceConfig } from "@indigoai-us/hq-cloud";
22
22
  import { hasPersonCachedSession, isMachineCredsFileEnvSet, wantsMachineCognitoTokens, type CognitoTokenSource } from "./machine-principal-state.js";
23
+ import { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir } from "./machine-token-cache.js";
24
+ export { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir };
23
25
  import { HQ_NO_BROWSER_LOGIN_ENV, type InteractiveCallerInput } from "./interactive-caller.js";
24
26
  import { loadCachedTokens, personTokenCacheFile, readPersonTokenFile } from "./person-token-cache.js";
25
27
  export { loadCachedTokens, personTokenCacheFile, readPersonTokenFile };
@@ -33,7 +35,6 @@ export type CognitoActorKind = "human" | "agent" | "unknown";
33
35
  * Default: the work-mesh daemon state dir (`~/.hq/work-mesh/daemon`), so a
34
36
  * machine mint never overwrites a person's `~/.hq/cognito-tokens.json`.
35
37
  */
36
- export declare const HQ_MACHINE_TOKEN_STATE_DIR_ENV = "HQ_MACHINE_TOKEN_STATE_DIR";
37
38
  export declare const DEFAULT_COGNITO: CognitoAuthConfig;
38
39
  export declare const DEFAULT_VAULT_API_URL: string;
39
40
  /**
@@ -93,14 +94,6 @@ export declare function resolveDefaultHqRoot(opts?: {
93
94
  platform?: NodeJS.Platform;
94
95
  }): string;
95
96
  export declare const DEFAULT_HQ_ROOT: string;
96
- /**
97
- * Directory used as `HQ_STATE_DIR` while minting/caching machine Cognito
98
- * tokens. Never the person's `~/.hq` — agent boxes write under the daemon
99
- * state dir so a mint cannot clobber a human login cache.
100
- */
101
- export declare function machineTokenStateDir(home?: string, env?: NodeJS.ProcessEnv): string;
102
- /** Absolute path of the machine-token cache file (daemon state dir). */
103
- export declare function machineTokenCacheFile(home?: string, env?: NodeJS.ProcessEnv): string;
104
97
  /** Default machine-creds path hq-cloud also checks when the env is unset. */
105
98
  export declare function defaultMachineCredsFile(home?: string): string;
106
99
  export type EnsureCognitoTokenOptions = {
@@ -181,11 +174,6 @@ export declare function refreshActivePersonTokens(cached: CognitoTokens, env?: N
181
174
  export declare function refreshActivePersonTokensForClientHealth(cached: CognitoTokens, signal: AbortSignal): Promise<CognitoTokens>;
182
175
  /** Derive actor kind from an ID token's custom:entity* claims (no verify). */
183
176
  export declare function actorKindFromIdToken(idToken: string | undefined): CognitoActorKind;
184
- /**
185
- * Peek the machine-token cache under the daemon state dir without minting.
186
- * Used by doctor; never logs token material.
187
- */
188
- export declare function loadMachineCachedTokens(home?: string, env?: NodeJS.ProcessEnv): CognitoTokens | null;
189
177
  /**
190
178
  * Report token source + actor kind for `hq mesh daemon doctor`. Does not mint
191
179
  * or hit the network. Machine identity without a readable cache still reports
@@ -28,8 +28,8 @@ import chalk from "chalk";
28
28
  import { isExpiring, refreshTokens, saveCachedTokens, browserLogin, detectHqCoreVersion, isMachineIdentity, getValidMachineTokens, CognitoRefreshError, accessTokenFingerprint, invalidateCachedTokensByFingerprint, } from "@indigoai-us/hq-cloud";
29
29
  import { hasPersonCachedSession, isMachineCredsFileEnvSet, probeMachineIdentity, wantsMachineCognitoTokens, } from "./machine-principal-state.js";
30
30
  import { CLI_NAME, CLI_VERSION } from "../cli-version.js";
31
- import { daemonDir } from "../lib/mesh/live/daemon/paths.js";
32
- import { workMeshRoot } from "../lib/mesh/live/paths.js";
31
+ import { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir, } from "./machine-token-cache.js";
32
+ export { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir };
33
33
  import { defaultHqRootFallback, hqDiscoveryCandidates, pathForPlatform, } from "./hq-root-resolver.js";
34
34
  import { acquireLockFileExclusively } from "./exclusive-lock.js";
35
35
  import { interactiveLoginConfig, resolveCognitoCallbackPort } from "./cognito-callback-port.js";
@@ -46,7 +46,6 @@ export { hasPersonCachedSession, isMachineCredsFileEnvSet, wantsMachineCognitoTo
46
46
  * Default: the work-mesh daemon state dir (`~/.hq/work-mesh/daemon`), so a
47
47
  * machine mint never overwrites a person's `~/.hq/cognito-tokens.json`.
48
48
  */
49
- export const HQ_MACHINE_TOKEN_STATE_DIR_ENV = "HQ_MACHINE_TOKEN_STATE_DIR";
50
49
  export const DEFAULT_COGNITO = {
51
50
  region: process.env.AWS_REGION ?? "us-east-1",
52
51
  userPoolDomain: process.env.HQ_COGNITO_DOMAIN ?? "vault-indigo-hq-prod",
@@ -230,21 +229,6 @@ function isHqRoot(dir, p = path) {
230
229
  }
231
230
  }
232
231
  export const DEFAULT_HQ_ROOT = resolveDefaultHqRoot();
233
- /**
234
- * Directory used as `HQ_STATE_DIR` while minting/caching machine Cognito
235
- * tokens. Never the person's `~/.hq` — agent boxes write under the daemon
236
- * state dir so a mint cannot clobber a human login cache.
237
- */
238
- export function machineTokenStateDir(home = os.homedir(), env = process.env) {
239
- const override = env[HQ_MACHINE_TOKEN_STATE_DIR_ENV]?.trim();
240
- if (override)
241
- return override;
242
- return daemonDir(workMeshRoot(home, env), home, env);
243
- }
244
- /** Absolute path of the machine-token cache file (daemon state dir). */
245
- export function machineTokenCacheFile(home = os.homedir(), env = process.env) {
246
- return path.join(machineTokenStateDir(home, env), "cognito-tokens.json");
247
- }
248
232
  /** Default machine-creds path hq-cloud also checks when the env is unset. */
249
233
  export function defaultMachineCredsFile(home = os.homedir()) {
250
234
  return path.join(home, ".hq-agent", "machine-creds.json");
@@ -662,28 +646,6 @@ export function actorKindFromIdToken(idToken) {
662
646
  }
663
647
  return "human";
664
648
  }
665
- /**
666
- * Peek the machine-token cache under the daemon state dir without minting.
667
- * Used by doctor; never logs token material.
668
- */
669
- export function loadMachineCachedTokens(home = os.homedir(), env = process.env) {
670
- const file = machineTokenCacheFile(home, env);
671
- try {
672
- if (!fs.existsSync(file))
673
- return null;
674
- const raw = JSON.parse(fs.readFileSync(file, "utf8"));
675
- if (typeof raw.accessToken !== "string" ||
676
- typeof raw.idToken !== "string" ||
677
- raw.accessToken.length === 0 ||
678
- raw.idToken.length === 0) {
679
- return null;
680
- }
681
- return raw;
682
- }
683
- catch {
684
- return null;
685
- }
686
- }
687
649
  /**
688
650
  * Report token source + actor kind for `hq mesh daemon doctor`. Does not mint
689
651
  * or hit the network. Machine identity without a readable cache still reports
@@ -0,0 +1,13 @@
1
+ export declare const PARENT_COMMAND_LINE_TIMEOUT_MS = 2000;
2
+ export interface DaemonCliVersionDeps {
3
+ env?: NodeJS.ProcessEnv;
4
+ parentCommandLine?: () => Promise<string | null>;
5
+ }
6
+ /**
7
+ * The version a daemon handed to the staged child bootstrap that started this
8
+ * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
9
+ * Daemons have started units this way since 2026-10-05 (#1541).
10
+ */
11
+ export declare function daemonVersionFromBootstrapCommandLine(line: string | null): string | null;
12
+ export declare function resolveDaemonCliVersion(deps?: DaemonCliVersionDeps): Promise<string | null>;
13
+ //# sourceMappingURL=daemon-cli-version.d.ts.map
@@ -0,0 +1,47 @@
1
+ import { execFile } from "node:child_process";
2
+ const SEMVER = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
3
+ export const PARENT_COMMAND_LINE_TIMEOUT_MS = 2_000;
4
+ function readParentCommandLine() {
5
+ const pid = Math.trunc(process.ppid);
6
+ const [cmd, args] = process.platform === "win32"
7
+ ? [
8
+ "powershell.exe",
9
+ [
10
+ "-NoProfile",
11
+ "-NonInteractive",
12
+ "-Command",
13
+ `(Get-CimInstance Win32_Process -Filter "ProcessId=${pid}").CommandLine`,
14
+ ],
15
+ ]
16
+ : ["ps", ["-ww", "-o", "args=", "-p", String(pid)]];
17
+ return new Promise((resolve) => {
18
+ const child = execFile(cmd, args, { encoding: "utf8", windowsHide: true, timeout: PARENT_COMMAND_LINE_TIMEOUT_MS }, (error, stdout) => {
19
+ const line = error ? "" : String(stdout).trim();
20
+ resolve(line || null);
21
+ });
22
+ child.unref?.();
23
+ });
24
+ }
25
+ /**
26
+ * The version a daemon handed to the staged child bootstrap that started this
27
+ * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
28
+ * Daemons have started units this way since 2026-10-05 (#1541).
29
+ */
30
+ export function daemonVersionFromBootstrapCommandLine(line) {
31
+ if (!line)
32
+ return null;
33
+ const match = /hq-child-bootstrap\.m?js\s.*?(?:^|\s)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?=\s|$)/.exec(line);
34
+ return match?.[1] ?? null;
35
+ }
36
+ export async function resolveDaemonCliVersion(deps = {}) {
37
+ const env = deps.env ?? process.env;
38
+ if (!env.HQ_DAEMON_UNIT?.trim())
39
+ return null;
40
+ const fromEnv = env.HQ_DAEMON_CLI_VERSION?.trim();
41
+ if (fromEnv)
42
+ return SEMVER.test(fromEnv) ? fromEnv : null;
43
+ const line = await (deps.parentCommandLine ?? readParentCommandLine)();
44
+ const fromBootstrap = daemonVersionFromBootstrapCommandLine(line);
45
+ return fromBootstrap !== null && SEMVER.test(fromBootstrap) ? fromBootstrap : null;
46
+ }
47
+ //# sourceMappingURL=daemon-cli-version.js.map
@@ -31,7 +31,7 @@ export const DUPLICATE_COMMANDS = [
31
31
  { command: "sync mode", countedAs: ["sync mode"], owner: "daemon sync mode" },
32
32
  { command: "packages install", countedAs: ["packages install"], owner: "install" },
33
33
  { command: "packages list", countedAs: ["packages list", "packages ls"], owner: "packs list" },
34
- { command: "packages update", countedAs: ["packages update"], owner: null },
34
+ { command: "packages update", countedAs: ["packages update"], owner: "packs update" },
35
35
  { command: "packages remove", countedAs: ["packages remove"], owner: "remove" },
36
36
  ];
37
37
  /** Default window. */
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The machine-token cache location and reader, without any network code, so
3
+ * network-free callers (the daemon's cached whoami check in native commands)
4
+ * can read it. Re-exported by cognito-session.ts.
5
+ */
6
+ import type { CognitoTokens } from "@indigoai-us/hq-cloud";
7
+ export declare const HQ_MACHINE_TOKEN_STATE_DIR_ENV = "HQ_MACHINE_TOKEN_STATE_DIR";
8
+ /**
9
+ * Directory used as `HQ_STATE_DIR` while minting/caching machine Cognito
10
+ * tokens. Never the person's `~/.hq` — agent boxes write under the daemon
11
+ * state dir so a mint cannot clobber a human login cache.
12
+ */
13
+ export declare function machineTokenStateDir(home?: string, env?: NodeJS.ProcessEnv): string;
14
+ /** Absolute path of the machine-token cache file (daemon state dir). */
15
+ export declare function machineTokenCacheFile(home?: string, env?: NodeJS.ProcessEnv): string;
16
+ /**
17
+ * Peek the machine-token cache under the daemon state dir without minting.
18
+ * Used by doctor; never logs token material.
19
+ */
20
+ export declare function loadMachineCachedTokens(home?: string, env?: NodeJS.ProcessEnv): CognitoTokens | null;
21
+ //# sourceMappingURL=machine-token-cache.d.ts.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The machine-token cache location and reader, without any network code, so
3
+ * network-free callers (the daemon's cached whoami check in native commands)
4
+ * can read it. Re-exported by cognito-session.ts.
5
+ */
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import { daemonDir } from "../lib/mesh/live/daemon/paths.js";
10
+ import { workMeshRoot } from "../lib/mesh/live/paths.js";
11
+ export const HQ_MACHINE_TOKEN_STATE_DIR_ENV = "HQ_MACHINE_TOKEN_STATE_DIR";
12
+ /**
13
+ * Directory used as `HQ_STATE_DIR` while minting/caching machine Cognito
14
+ * tokens. Never the person's `~/.hq` — agent boxes write under the daemon
15
+ * state dir so a mint cannot clobber a human login cache.
16
+ */
17
+ export function machineTokenStateDir(home = os.homedir(), env = process.env) {
18
+ const override = env[HQ_MACHINE_TOKEN_STATE_DIR_ENV]?.trim();
19
+ if (override)
20
+ return override;
21
+ return daemonDir(workMeshRoot(home, env), home, env);
22
+ }
23
+ /** Absolute path of the machine-token cache file (daemon state dir). */
24
+ export function machineTokenCacheFile(home = os.homedir(), env = process.env) {
25
+ return path.join(machineTokenStateDir(home, env), "cognito-tokens.json");
26
+ }
27
+ /**
28
+ * Peek the machine-token cache under the daemon state dir without minting.
29
+ * Used by doctor; never logs token material.
30
+ */
31
+ export function loadMachineCachedTokens(home = os.homedir(), env = process.env) {
32
+ const file = machineTokenCacheFile(home, env);
33
+ try {
34
+ if (!fs.existsSync(file))
35
+ return null;
36
+ const raw = JSON.parse(fs.readFileSync(file, "utf8"));
37
+ if (typeof raw.accessToken !== "string" ||
38
+ typeof raw.idToken !== "string" ||
39
+ raw.accessToken.length === 0 ||
40
+ raw.idToken.length === 0) {
41
+ return null;
42
+ }
43
+ return raw;
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ //# sourceMappingURL=machine-token-cache.js.map
@@ -64,6 +64,8 @@ export const RESIDENT_PACKAGE_MODULES = {
64
64
  "../utils/plan-gate-error.js", "../utils/deleted-company-notice.js",
65
65
  "../lib/daemon/mcp-oauth.js",
66
66
  "../commands/lanes.js",
67
+ "../utils/whoami-identity.js",
68
+ "../commands/whoami.js",
67
69
  "commander",
68
70
  "@modelcontextprotocol/sdk/client/index.js",
69
71
  "@modelcontextprotocol/sdk/client/streamableHttp.js",
@@ -271,6 +273,8 @@ const LOADERS = {
271
273
  () => import("../utils/deleted-company-notice.js"),
272
274
  () => import("../lib/daemon/mcp-oauth.js"),
273
275
  () => import("../commands/lanes.js"),
276
+ () => import("../utils/whoami-identity.js"),
277
+ () => import("../commands/whoami.js"),
274
278
  () => import("commander"),
275
279
  () => import("@modelcontextprotocol/sdk/client/index.js"),
276
280
  () => import("@modelcontextprotocol/sdk/client/streamableHttp.js"),
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The identity `hq whoami --json` prints, built from the local token caches.
3
+ *
4
+ * Shared by `hq whoami` itself and by the daemon's cached answer
5
+ * (src/lib/daemon/whoami-cache.ts), so both report the same fields the same
6
+ * way. Building it reads local files only; the one network lookup, the
7
+ * person's `prs_*` uid, is passed in by the caller.
8
+ */
9
+ import { loadCachedTokens } from '@indigoai-us/hq-cloud';
10
+ import { loadMachineCachedTokens } from './machine-token-cache.js';
11
+ export interface WhoamiTokenIdentity {
12
+ email?: string;
13
+ sub?: string;
14
+ delegatedEmail?: string;
15
+ delegatedSub?: string;
16
+ entityType?: string;
17
+ entityUid?: string;
18
+ }
19
+ export interface WhoamiDisplayIdentity {
20
+ email?: string;
21
+ sub?: string;
22
+ }
23
+ /** Every `hq whoami --json` field except `planLimits`. */
24
+ export interface WhoamiIdentity {
25
+ schemaVersion: 1;
26
+ authenticated: boolean;
27
+ tokenSource: 'machine' | 'person';
28
+ email: string | null;
29
+ sub: string | null;
30
+ delegatedEmail: string | null;
31
+ delegatedSub: string | null;
32
+ personUid: string | null;
33
+ agentUid: string | null;
34
+ username: string | null;
35
+ sessionExpiresAt: string | null;
36
+ sessionExpiring: boolean | null;
37
+ }
38
+ type CachedTokens = ReturnType<typeof loadCachedTokens>;
39
+ /**
40
+ * Resolves the person represented by an ID token without pairing a delegated
41
+ * email with the token subject of the delegating machine.
42
+ */
43
+ export declare function resolveWhoamiIdentity(identity: WhoamiTokenIdentity): WhoamiDisplayIdentity;
44
+ export declare function peekWhoamiTokenIdentity(idToken: string): WhoamiTokenIdentity;
45
+ /**
46
+ * The whoami identity for `machine` (the effective token source) and the
47
+ * cached person tokens. `readPersonUid` runs only for an authenticated person
48
+ * session; it is the caller's network lookup, or a cached value.
49
+ */
50
+ export declare function buildWhoamiIdentity(machine: boolean, cached: CachedTokens, readPersonUid: (identity: WhoamiTokenIdentity) => Promise<string | null> | string | null, readMachineTokens?: typeof loadMachineCachedTokens): Promise<WhoamiIdentity>;
51
+ /** The local part of the whoami identity: no network, `personUid` null. */
52
+ export declare function localWhoamiIdentity(env?: NodeJS.ProcessEnv): WhoamiIdentity;
53
+ export {};
54
+ //# sourceMappingURL=whoami-identity.d.ts.map