@indigoai-us/hq-cli 5.345.212 → 5.345.215-beta.0

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 (161) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +442 -50
  4. package/dist/command-catalog.generated.js +541 -50
  5. package/dist/commands/agent-inbox.d.ts +11 -1
  6. package/dist/commands/agent-inbox.js +128 -38
  7. package/dist/commands/agent-kit.js +2 -2
  8. package/dist/commands/agents.d.ts +51 -1
  9. package/dist/commands/agents.js +154 -2
  10. package/dist/commands/bot-jobs.d.ts +2 -15
  11. package/dist/commands/bot-jobs.js +2 -94
  12. package/dist/commands/bot-runtime.d.ts +46 -5
  13. package/dist/commands/bot-runtime.js +228 -18
  14. package/dist/commands/bot.d.ts +16 -9
  15. package/dist/commands/bot.js +169 -51
  16. package/dist/commands/cloud.d.ts +66 -13
  17. package/dist/commands/cloud.js +120 -39
  18. package/dist/commands/company-restore.d.ts +23 -0
  19. package/dist/commands/company-restore.js +128 -0
  20. package/dist/commands/company.js +2 -0
  21. package/dist/commands/core-handoff.js +1 -0
  22. package/dist/commands/core-hq-session-native.js +2 -2
  23. package/dist/commands/core-pin-native.js +1 -1
  24. package/dist/commands/core-policy.js +1 -1
  25. package/dist/commands/core-resolve-company-native.js +1 -1
  26. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  27. package/dist/commands/core-sentry-report-fast.js +3 -1
  28. package/dist/commands/daemon.js +11 -1
  29. package/dist/commands/integrations-connect.d.ts +17 -4
  30. package/dist/commands/integrations-connect.js +224 -26
  31. package/dist/commands/lanes-link.js +10 -5
  32. package/dist/commands/lanes.js +26 -9
  33. package/dist/commands/rescue.js +13 -0
  34. package/dist/commands/secrets.d.ts +11 -0
  35. package/dist/commands/secrets.js +41 -7
  36. package/dist/commands/sources.js +6 -0
  37. package/dist/commands/storage-offload.d.ts +12 -0
  38. package/dist/commands/storage-offload.js +41 -3
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/index.js +2 -0
  42. package/dist/lazy-commands.js +2 -0
  43. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  44. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  45. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  46. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  47. package/dist/lib/agent-kit/inbox-state.js +261 -4
  48. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  49. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  50. package/dist/lib/agent-kit/run/inbox.js +4 -2
  51. package/dist/lib/agent-kit/skills.js +4 -1
  52. package/dist/lib/agent-kit/wake.d.ts +9 -1
  53. package/dist/lib/agent-kit/wake.js +10 -3
  54. package/dist/lib/bot/config.d.ts +1 -0
  55. package/dist/lib/bot/config.js +10 -0
  56. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  57. package/dist/lib/bot/eventbridge-cron.js +104 -0
  58. package/dist/lib/bot/fleet-cron.js +193 -14
  59. package/dist/lib/bot/fleet-download.d.ts +2 -0
  60. package/dist/lib/bot/fleet-download.js +23 -0
  61. package/dist/lib/bot/fleet-local.d.ts +34 -1
  62. package/dist/lib/bot/fleet-local.js +254 -37
  63. package/dist/lib/bot/fleet-python.d.ts +3 -0
  64. package/dist/lib/bot/fleet-python.js +34 -4
  65. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  66. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  67. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  68. package/dist/lib/bot/legacy-provider-login.js +19 -2
  69. package/dist/lib/bot/prompt.js +1 -1
  70. package/dist/lib/bot/readiness.d.ts +8 -0
  71. package/dist/lib/bot/readiness.js +17 -3
  72. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  73. package/dist/lib/bot/runtime-auth.js +94 -3
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  76. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  77. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  78. package/dist/lib/capacity/collectors/grok.js +56 -5
  79. package/dist/lib/core-utils/session-id.d.ts +1 -1
  80. package/dist/lib/core-utils/session-id.js +4 -0
  81. package/dist/lib/daemon/catalog.js +11 -1
  82. package/dist/lib/daemon/run.js +9 -1
  83. package/dist/lib/daemon/updater.d.ts +34 -2
  84. package/dist/lib/daemon/updater.js +51 -2
  85. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  86. package/dist/lib/db/sqlite-binding.js +1 -1
  87. package/dist/lib/delivery/artifacts.d.ts +99 -0
  88. package/dist/lib/delivery/artifacts.js +548 -0
  89. package/dist/lib/delivery/backup.d.ts +78 -0
  90. package/dist/lib/delivery/backup.js +343 -0
  91. package/dist/lib/delivery/cache.d.ts +29 -0
  92. package/dist/lib/delivery/cache.js +33 -0
  93. package/dist/lib/delivery/contracts.d.ts +142 -0
  94. package/dist/lib/delivery/contracts.js +289 -0
  95. package/dist/lib/delivery/credentials.d.ts +54 -0
  96. package/dist/lib/delivery/credentials.js +119 -0
  97. package/dist/lib/delivery/enrollment.d.ts +142 -0
  98. package/dist/lib/delivery/enrollment.js +382 -0
  99. package/dist/lib/delivery/identity.d.ts +25 -0
  100. package/dist/lib/delivery/identity.js +82 -0
  101. package/dist/lib/delivery/inbox.d.ts +116 -0
  102. package/dist/lib/delivery/inbox.js +260 -0
  103. package/dist/lib/delivery/migrations.d.ts +139 -0
  104. package/dist/lib/delivery/migrations.js +623 -0
  105. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  106. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  107. package/dist/lib/delivery/mqtt.d.ts +61 -0
  108. package/dist/lib/delivery/mqtt.js +112 -0
  109. package/dist/lib/delivery/outbox.d.ts +95 -0
  110. package/dist/lib/delivery/outbox.js +187 -0
  111. package/dist/lib/delivery/provenance.d.ts +129 -0
  112. package/dist/lib/delivery/provenance.js +93 -0
  113. package/dist/lib/delivery/reconciler.d.ts +151 -0
  114. package/dist/lib/delivery/reconciler.js +492 -0
  115. package/dist/lib/delivery/restore.d.ts +35 -0
  116. package/dist/lib/delivery/restore.js +134 -0
  117. package/dist/lib/delivery/store.d.ts +161 -0
  118. package/dist/lib/delivery/store.js +940 -0
  119. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  120. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  121. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  122. package/dist/lib/delivery/workers/macos.js +901 -0
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  124. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  125. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  126. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  127. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  128. package/dist/lib/delivery/workers/windows.js +608 -0
  129. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  130. package/dist/lib/doctor/checks/release-links.js +260 -24
  131. package/dist/lib/doctor/fix/apply.js +24 -8
  132. package/dist/lib/doctor/fix/remediation.js +15 -5
  133. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  134. package/dist/lib/install/provider-wrappers.js +68 -3
  135. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  136. package/dist/lib/lanes/autopilot-registry.js +59 -7
  137. package/dist/lib/lanes/links.d.ts +14 -0
  138. package/dist/lib/lanes/links.js +320 -25
  139. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  140. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  141. package/dist/main.js +3 -1
  142. package/dist/sentry-init.d.ts +2 -0
  143. package/dist/sentry-init.js +13 -2
  144. package/dist/sentry.d.ts +2 -0
  145. package/dist/sentry.js +5 -1
  146. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  147. package/dist/utils/cli-network-lifecycle.js +52 -0
  148. package/dist/utils/cognito-callback-port.d.ts +14 -0
  149. package/dist/utils/cognito-callback-port.js +24 -0
  150. package/dist/utils/cognito-session.js +3 -3
  151. package/dist/utils/deleted-company-notice.d.ts +59 -0
  152. package/dist/utils/deleted-company-notice.js +156 -0
  153. package/dist/utils/login-browser.d.ts +1 -1
  154. package/dist/utils/login-browser.js +7 -5
  155. package/dist/utils/resident-package-preload.js +30 -15
  156. package/dist/utils/safe-link.d.ts +63 -0
  157. package/dist/utils/safe-link.js +246 -0
  158. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  159. package/dist/utils/sentry-keepalive-transport.js +70 -0
  160. package/dist/utils/vault-api.js +7 -0
  161. package/package.json +7 -7
@@ -1,4 +1,4 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { appendDropboxMessageAtPath } from "./dropbox.js";
@@ -24,7 +24,7 @@ export function resolveLinkSessionId(root, explicit, env = process.env) {
24
24
  throw new LaneLinkError("invalid_session_id", `Invalid session id: ${explicit}`);
25
25
  return explicit;
26
26
  }
27
- for (const key of ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"]) {
27
+ for (const key of ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID", "HQ_FLEET_SESSION_ID"]) {
28
28
  const candidate = env[key]?.replace(/\s/g, "");
29
29
  if (safeId(candidate))
30
30
  return candidate;
@@ -143,7 +143,11 @@ function bindSignalLaneSession(root, sid, env) {
143
143
  return;
144
144
  const dir = linkPath(root, lane.signal_link);
145
145
  const meta = readJson(path.join(dir, "meta.json"));
146
- if (lane.senior.kind !== "session" || lane.senior.id !== meta.conductor_session || sid === meta.conductor_session)
146
+ // A lane created by a conductor that later handed the link over still binds:
147
+ // its senior is a previous conductor of record, not an arbitrary session.
148
+ const previous = Array.isArray(meta.previous_conductors) ? meta.previous_conductors : [];
149
+ const seniorIsConductor = lane.senior.id === meta.conductor_session || previous.includes(lane.senior.id);
150
+ if (lane.senior.kind !== "session" || !seniorIsConductor || sid === meta.conductor_session || previous.includes(sid))
147
151
  return;
148
152
  const child = lane.lane_id;
149
153
  const at = new Date().toISOString();
@@ -187,6 +191,11 @@ function resolvePointer(root, sid, role, options) {
187
191
  if (role === "conductor" && link !== pointer.link) {
188
192
  throw new LaneLinkError("link_role_invalid", "A conductor can only consume or wait on its own link");
189
193
  }
194
+ // A conductor pointer is only a hint: after a handover the old session's
195
+ // pointer can survive (an interrupted adopt, or one recreated by hand).
196
+ // The link's meta names the one conductor of record.
197
+ if (role === "conductor")
198
+ assertConductorOfRecord(root, pointer.link, sid);
190
199
  if (role === "child") {
191
200
  if (options.link !== undefined && !safeId(options.link))
192
201
  throw new LaneLinkError("link_invalid", "Invalid --link");
@@ -196,6 +205,127 @@ function resolvePointer(root, sid, role, options) {
196
205
  }
197
206
  return { link, child };
198
207
  }
208
+ /** A handover token is good for a week: long enough for a handoff to be picked up. */
209
+ const HANDOVER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
210
+ function sha256(value) {
211
+ return createHash("sha256").update(value, "utf8").digest("hex");
212
+ }
213
+ function handoverTokenValid(handover, token, at) {
214
+ if (!token || !handover || typeof handover !== "object")
215
+ return false;
216
+ const record = handover;
217
+ if (typeof record.token_sha256 !== "string" || typeof record.expires !== "string")
218
+ return false;
219
+ const expires = Date.parse(record.expires);
220
+ if (!Number.isFinite(expires) || at.getTime() >= expires)
221
+ return false;
222
+ const expected = Buffer.from(record.token_sha256, "hex");
223
+ const actual = Buffer.from(sha256(token), "hex");
224
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
225
+ }
226
+ function isConductorOfRecord(meta, sid) {
227
+ return typeof meta.conductor_session === "string" && meta.conductor_session === sid;
228
+ }
229
+ function assertConductorOfRecord(root, link, sid, meta) {
230
+ const record = meta ?? readJson(path.join(rootDir(root), link, "meta.json"));
231
+ if (!isConductorOfRecord(record, sid)) {
232
+ throw new LaneLinkError("link_role_invalid", `This session no longer conducts ${link}; it was handed over to another session`);
233
+ }
234
+ }
235
+ /**
236
+ * Drop this session's pointer when it is stale: the link was closed (a close
237
+ * that failed mid-sweep leaves pointers behind), or, for a conductor pointer,
238
+ * the link was handed to another session.
239
+ */
240
+ function dropStalePointer(root, sid) {
241
+ const pointer = readPointer(root, sid);
242
+ if (!pointer)
243
+ return pointer;
244
+ let meta;
245
+ try {
246
+ meta = readJson(path.join(rootDir(root), pointer.link, "meta.json"));
247
+ }
248
+ catch {
249
+ return pointer;
250
+ }
251
+ if (!meta.closed && (pointer.role !== "conductor" || isConductorOfRecord(meta, sid)))
252
+ return pointer;
253
+ fs.rmSync(pointerPath(root, sid), { force: true });
254
+ return null;
255
+ }
256
+ /** Keep retrying a non-blocking stdin for this long in total before giving up. */
257
+ const STDIN_EAGAIN_LIMIT_MS = 30_000;
258
+ function sleepSync(milliseconds) {
259
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
260
+ }
261
+ /**
262
+ * Read all of stdin synchronously. `fs.readFileSync(0)` throws EAGAIN on a
263
+ * non-blocking stdin (some hosts hand one over) and EOF on a Windows console,
264
+ * so read in chunks: wait and retry on EAGAIN, and treat EOF as end of input.
265
+ */
266
+ export function readStdinSync(read = (fd, buffer) => fs.readSync(fd, buffer), sleep = sleepSync) {
267
+ const chunks = [];
268
+ const buffer = Buffer.alloc(64 * 1024);
269
+ let waited = 0;
270
+ for (;;) {
271
+ let count;
272
+ try {
273
+ count = read(0, buffer);
274
+ }
275
+ catch (error) {
276
+ const code = error.code;
277
+ if (code === "EOF")
278
+ break;
279
+ if (code === "EAGAIN" && waited < STDIN_EAGAIN_LIMIT_MS) {
280
+ sleep(10);
281
+ waited += 10;
282
+ continue;
283
+ }
284
+ throw error;
285
+ }
286
+ if (count === 0)
287
+ break;
288
+ chunks.push(Buffer.from(buffer.subarray(0, count)));
289
+ }
290
+ return Buffer.concat(chunks).toString("utf8");
291
+ }
292
+ /** `provided` is true when the caller passed a token at all, even an empty one. */
293
+ function readHandoverToken(options) {
294
+ if (options.tokenFile)
295
+ return { provided: true, token: fs.readFileSync(options.tokenFile, "utf8").trim() || undefined };
296
+ if (options.token === "-") {
297
+ const read = options.readStdin ?? (() => readStdinSync());
298
+ return { provided: true, token: read().trim() || undefined };
299
+ }
300
+ if (options.token === undefined)
301
+ return { provided: false, token: undefined };
302
+ return { provided: true, token: options.token.trim() || undefined };
303
+ }
304
+ /**
305
+ * Run fn on the conductor queue only while `sid` is the conductor of record.
306
+ * The check runs inside the queue lock, and adopt rebinds the conductor while
307
+ * holding the same lock, so a former conductor cannot drain a batch in the
308
+ * window around an adopt. Returns null when `sid` is not the conductor.
309
+ */
310
+ function withConductorQueue(root, link, sid, fn) {
311
+ const inbox = queueDir(root, link);
312
+ return withLinkQueueLock(inbox, () => {
313
+ if (!isConductorOfRecord(readJson(path.join(rootDir(root), link, "meta.json")), sid))
314
+ return null;
315
+ return fn(inbox);
316
+ });
317
+ }
318
+ function withLinkMetaLock(dir, fn) {
319
+ try {
320
+ return withLaneRecordFileLock(path.join(dir, "meta"), fn, { reclaimByAge: false });
321
+ }
322
+ catch (error) {
323
+ if (error instanceof LanesError && error.error === "store_lock_timeout") {
324
+ throw new LaneLinkError("link_busy", "Another session is changing this link; try again");
325
+ }
326
+ throw error;
327
+ }
328
+ }
199
329
  function queueDir(root, link, child) {
200
330
  return path.join(rootDir(root), link, child ? "children" : "up", ...(child ? [child] : []), "inbox");
201
331
  }
@@ -599,11 +729,27 @@ export async function runLaneLink(subcommand, options) {
599
729
  const pointer = readPointer(root, sid);
600
730
  if (!pointer)
601
731
  return {};
732
+ // A former conductor's leftover pointer must not drain the reports that now
733
+ // belong to the conductor of record.
602
734
  const target = hookMessage(root, pointer);
603
735
  if (options.ackMode !== undefined && options.ackMode !== "explicit")
604
736
  throw new LaneLinkError("ack_mode_invalid", "Unsupported acknowledgement mode");
605
- const claim = options.ackMode === "explicit" ? claimLinkQueue(target.inbox) : undefined;
606
- const messages = claim ? claim.messages : drainLinkQueue(target.inbox);
737
+ let claim;
738
+ let messages;
739
+ if (pointer.role === "conductor") {
740
+ await options.beforeConductorQueue?.();
741
+ const drained = withConductorQueue(root, pointer.link, sid, (inbox) => options.ackMode === "explicit"
742
+ ? { claim: claimLinkQueueUnlocked(inbox), messages: "" }
743
+ : { claim: undefined, messages: drainLinkQueueUnlocked(inbox) });
744
+ if (drained === null)
745
+ return {};
746
+ claim = drained.claim;
747
+ messages = claim ? claim.messages : drained.messages;
748
+ }
749
+ else {
750
+ claim = options.ackMode === "explicit" ? claimLinkQueue(target.inbox) : undefined;
751
+ messages = claim ? claim.messages : drainLinkQueue(target.inbox);
752
+ }
607
753
  if (!messages)
608
754
  return {};
609
755
  const receipt = claim ? { _hqLinkDelivery: { version: 1, sessionId: sid, link: pointer.link, child: pointer.name ?? null, claims: claim.claims } } : {};
@@ -627,12 +773,24 @@ export async function runLaneLink(subcommand, options) {
627
773
  throw new LaneLinkError("claim_owner_invalid", "Receipt does not match the current link/child binding");
628
774
  }
629
775
  const claims = options.claims?.split(",");
630
- acknowledgeLinkClaims(hookMessage(root, pointer).inbox, claims);
776
+ const target = hookMessage(root, pointer);
777
+ if (pointer.role === "conductor") {
778
+ // Check the conductor of record inside the queue lock, like read and
779
+ // _deliver: an adopt that commits after a check made outside the lock
780
+ // would let the former conductor consume claims owed to the new one.
781
+ await options.beforeConductorQueue?.();
782
+ const acked = withConductorQueue(root, pointer.link, currentSid, (inbox) => { acknowledgeLinkClaimsUnlocked(inbox, claims); return true; });
783
+ if (acked === null)
784
+ throw new LaneLinkError("link_role_invalid", `This session no longer conducts ${pointer.link}; it was handed over to another session`);
785
+ }
786
+ else {
787
+ acknowledgeLinkClaims(target.inbox, claims);
788
+ }
631
789
  return { output: { acknowledged: true, acceptance: "recipient_instruction_only" } };
632
790
  }
633
791
  if (subcommand === "open") {
634
792
  const sessionId = requireSid();
635
- const p = readPointer(root, sessionId);
793
+ const p = dropStalePointer(root, sessionId);
636
794
  if (p) {
637
795
  if (p.role !== "conductor")
638
796
  throw new LaneLinkError("session_already_child", `This session is already a child of ${p.link}; leave first`);
@@ -652,7 +810,7 @@ export async function runLaneLink(subcommand, options) {
652
810
  if (subcommand === "join") {
653
811
  const sessionId = requireSid();
654
812
  const dir = linkPath(root, options.link);
655
- if (readPointer(root, sessionId))
813
+ if (dropStalePointer(root, sessionId))
656
814
  throw new LaneLinkError("session_already_linked", "This session is already linked; leave first");
657
815
  const name = options.name || `s-${sessionId.replace(/[^A-Za-z0-9]/g, "").slice(0, 8)}`;
658
816
  if (!safeId(name) || name === "all")
@@ -725,9 +883,15 @@ export async function runLaneLink(subcommand, options) {
725
883
  // Preserve explicit-link validation errors before resolving ownership.
726
884
  if (role === "conductor" && options.link !== undefined)
727
885
  linkPath(root, options.link);
728
- const resolved = resolvePointer(root, requireSid(), role, options);
886
+ const sessionId = requireSid();
887
+ const resolved = resolvePointer(root, sessionId, role, options);
729
888
  linkPath(root, resolved.link);
730
- const text = drainLinkQueue(queueDir(root, resolved.link, role === "child" ? resolved.child : undefined));
889
+ if (role === "child")
890
+ return { output: { messages: drainLinkQueue(queueDir(root, resolved.link, resolved.child)) } };
891
+ await options.beforeConductorQueue?.();
892
+ const text = withConductorQueue(root, resolved.link, sessionId, (inbox) => drainLinkQueueUnlocked(inbox));
893
+ if (text === null)
894
+ throw new LaneLinkError("link_role_invalid", `This session no longer conducts ${resolved.link}; it was handed over to another session`);
731
895
  return { output: { messages: text } };
732
896
  }
733
897
  if (subcommand === "wait") {
@@ -746,7 +910,7 @@ export async function runLaneLink(subcommand, options) {
746
910
  if (!link)
747
911
  return { output: { link: null, children: [] } };
748
912
  const dir = linkPath(root, link);
749
- const meta = readJson(path.join(dir, "meta.json"));
913
+ const { handover: _handover, ...meta } = readJson(path.join(dir, "meta.json"));
750
914
  const unread = countPending(path.join(dir, "up", "inbox"));
751
915
  return { output: { ...meta, unread_reports: unread, quarantined_reports: countQuarantined(path.join(dir, "up", "inbox")), children: listChildren(root, dir) } };
752
916
  }
@@ -763,24 +927,155 @@ export async function runLaneLink(subcommand, options) {
763
927
  fs.rmdirSync(path.dirname(pointerPath(root, sessionId)));
764
928
  return { output: { link: pointer.link, left: child } };
765
929
  }
930
+ if (subcommand === "handover") {
931
+ // Only the conductor of record can authorize a successor. The pointer check
932
+ // in resolvePointer runs before the lock, so check meta again inside it: an
933
+ // adopt that finished in between makes this session a former conductor.
934
+ const sessionId = requireSid();
935
+ const pointer = resolvePointer(root, sessionId, "conductor", options);
936
+ const dir = linkPath(root, pointer.link);
937
+ const token = randomBytes(24).toString("hex");
938
+ const issued = now();
939
+ const expires = new Date(issued.getTime() + HANDOVER_TTL_MS).toISOString();
940
+ withLinkMetaLock(dir, () => {
941
+ const meta = readJson(path.join(dir, "meta.json"));
942
+ if (meta.closed)
943
+ throw new LaneLinkError("link_closed", `The link was closed: ${pointer.link}`);
944
+ assertConductorOfRecord(root, pointer.link, sessionId, meta);
945
+ atomicJson(path.join(dir, "meta.json"), { ...meta, handover: { token_sha256: sha256(token), issued: issued.toISOString(), expires } });
946
+ });
947
+ // The token is printed once. The successor should pass it on stdin or in a
948
+ // file, not on argv, where other processes can read it.
949
+ return { output: { link: pointer.link, token, expires, adopt: `hq lanes link adopt --link ${pointer.link} --token -` } };
950
+ }
951
+ if (subcommand === "adopt") {
952
+ const sessionId = requireSid();
953
+ const dir = linkPath(root, options.link);
954
+ const link = options.link;
955
+ const { provided: tokenProvided, token } = readHandoverToken(options);
956
+ const current = dropStalePointer(root, sessionId);
957
+ if (current?.role === "conductor" && current.link === link) {
958
+ return { output: { link, conductor_session: sessionId, adopted: false } };
959
+ }
960
+ if (current)
961
+ throw new LaneLinkError("session_already_linked", `This session is already a ${current.role} on ${current.link}; leave or close it first`);
962
+ return withLinkMetaLock(dir, () => {
963
+ const meta = readJson(path.join(dir, "meta.json"));
964
+ if (meta.closed)
965
+ throw new LaneLinkError("link_closed", `The link was closed: ${link}`);
966
+ const previous = typeof meta.conductor_session === "string" && safeId(meta.conductor_session) ? meta.conductor_session : "";
967
+ const held = previous ? readPointer(root, previous) : null;
968
+ const previousHolds = held?.role === "conductor" && held.link === link;
969
+ // A successor needs the handover token while the conductor of record
970
+ // still holds the link. Without one, it may only adopt a link that the
971
+ // previous conductor no longer holds. A child or any other linked session
972
+ // is refused above, so no session can take over a link it was not given.
973
+ if (previousHolds && !handoverTokenValid(meta.handover, token, now())) {
974
+ throw new LaneLinkError(tokenProvided ? "handover_token_invalid" : "link_owned", tokenProvided
975
+ ? `The handover token for ${link} is wrong, used, or expired; ask the conductor of record to run hq lanes link handover again`
976
+ : `Link ${link} is held by conductor session ${previous}; that session must run hq lanes link handover and pass you the token`);
977
+ }
978
+ const at = now().toISOString();
979
+ fs.mkdirSync(path.join(links, "by-session"), { recursive: true });
980
+ try {
981
+ fs.writeFileSync(pointerPath(root, sessionId), `conductor ${link}\n`, { mode: 0o600, flag: "wx" });
982
+ }
983
+ catch (error) {
984
+ if (error.code === "EEXIST")
985
+ throw new LaneLinkError("session_already_linked", "This session is already linked; leave first");
986
+ throw error;
987
+ }
988
+ const { handover: _used, ...rest } = meta;
989
+ const priorList = Array.isArray(meta.previous_conductors) ? meta.previous_conductors.filter((value) => typeof value === "string") : [];
990
+ // The recorded host session belongs to the previous conductor's host. Keep
991
+ // it only when this same session re-adopts; otherwise clear it so
992
+ // children's reports never wake the old host.
993
+ const sameSession = previous === sessionId;
994
+ const recordedHost = typeof meta.conductor_host_session === "string" ? meta.conductor_host_session : "";
995
+ const hostSession = options.hostSession ?? (sameSession ? recordedHost : "");
996
+ const hostCleared = options.hostSession === undefined && !sameSession && recordedHost !== "";
997
+ // Without --engine the link keeps its recorded engine.
998
+ const engine = options.engine || (typeof meta.engine === "string" && meta.engine) || "claude";
999
+ try {
1000
+ // Rebind while holding the conductor queue lock as well (lock order:
1001
+ // meta, then queue; queue holders never take the meta lock), so a
1002
+ // former conductor's read or delivery either drains before the
1003
+ // rebind or sees the new conductor and drains nothing.
1004
+ withLinkQueueLock(queueDir(root, link), () => {
1005
+ atomicJson(path.join(dir, "meta.json"), {
1006
+ ...rest,
1007
+ conductor_session: sessionId,
1008
+ conductor_host_session: hostSession,
1009
+ engine,
1010
+ previous_conductors: previous && !sameSession && !priorList.includes(previous) ? [...priorList, previous] : priorList,
1011
+ adopted: at,
1012
+ });
1013
+ });
1014
+ }
1015
+ catch (error) {
1016
+ fs.rmSync(pointerPath(root, sessionId), { force: true });
1017
+ throw error;
1018
+ }
1019
+ // Still inside the meta lock. If this step is lost (a crash), the old
1020
+ // pointer is harmless: every conductor command checks conductor_session.
1021
+ if (previousHolds)
1022
+ fs.rmSync(pointerPath(root, previous), { force: true });
1023
+ return {
1024
+ output: {
1025
+ link,
1026
+ conductor_session: sessionId,
1027
+ previous_conductor: previous && !sameSession ? previous : null,
1028
+ conductor_host_session: hostSession,
1029
+ engine,
1030
+ ...(hostCleared ? { host_session_cleared: true, note: "The previous conductor's host session was cleared; pass --host-session so children's reports can wake this session" } : {}),
1031
+ adopted: true,
1032
+ },
1033
+ };
1034
+ });
1035
+ }
766
1036
  if (subcommand === "close") {
767
- const pointer = resolvePointer(root, requireSid(), "conductor", options);
1037
+ const sessionId = requireSid();
1038
+ const pointer = resolvePointer(root, sessionId, "conductor", options);
768
1039
  const resolved = options.link ? { link: options.link } : pointer;
769
1040
  if (resolved.link !== pointer.link)
770
1041
  throw new LaneLinkError("link_role_invalid", "A conductor can only close its own link");
771
- const dir = linkPath(root, resolved.link);
772
- const bySession = path.join(links, "by-session");
773
- if (fs.existsSync(bySession))
774
- for (const file of fs.readdirSync(bySession)) {
775
- const [role, pointerLink] = fs.readFileSync(path.join(bySession, file), "utf8").trim().split(/\s+/);
776
- if ((role === "conductor" || role === "child") && pointerLink === resolved.link)
777
- fs.rmSync(path.join(bySession, file), { force: true });
778
- }
779
- if (fs.existsSync(bySession) && fs.readdirSync(bySession).length === 0)
780
- fs.rmdirSync(bySession);
781
- const meta = readJson(path.join(dir, "meta.json"));
782
- atomicJson(path.join(dir, "meta.json"), { ...meta, closed: now().toISOString() });
783
- return { output: { link: resolved.link, closed: true } };
1042
+ // Not linkPath: a link that is already closed may still need its sweep
1043
+ // finished. resolvePointer above already read this link's meta.
1044
+ const dir = path.join(links, resolved.link);
1045
+ // Under the meta lock, so a concurrent adopt cannot reopen the link under a
1046
+ // new conductor after this sweep removed every pointer.
1047
+ return withLinkMetaLock(dir, () => {
1048
+ const meta = readJson(path.join(dir, "meta.json"));
1049
+ assertConductorOfRecord(root, resolved.link, sessionId, meta);
1050
+ // Mark the link closed before removing pointers. A crash in between then
1051
+ // leaves a closed link with stray pointers, never an open link with no
1052
+ // conductor pointer that anyone could adopt without a token. A link that
1053
+ // is already closed had an earlier close fail mid-sweep: finish it.
1054
+ if (!meta.closed)
1055
+ atomicJson(path.join(dir, "meta.json"), { ...meta, closed: now().toISOString() });
1056
+ const bySession = path.join(links, "by-session");
1057
+ const own = path.basename(pointerPath(root, sessionId));
1058
+ // Remove this conductor's own pointer last, so a sweep that fails part
1059
+ // way still lets this session run close again to finish it.
1060
+ if (fs.existsSync(bySession))
1061
+ for (const file of [...fs.readdirSync(bySession).filter((name) => name !== own), own]) {
1062
+ let text;
1063
+ try {
1064
+ text = fs.readFileSync(path.join(bySession, file), "utf8");
1065
+ }
1066
+ catch (error) {
1067
+ if (error.code === "ENOENT")
1068
+ continue;
1069
+ throw error;
1070
+ }
1071
+ const [role, pointerLink] = text.trim().split(/\s+/);
1072
+ if ((role === "conductor" || role === "child") && pointerLink === resolved.link)
1073
+ fs.rmSync(path.join(bySession, file), { force: true });
1074
+ }
1075
+ if (fs.existsSync(bySession) && fs.readdirSync(bySession).length === 0)
1076
+ fs.rmdirSync(bySession);
1077
+ return { output: { link: resolved.link, closed: true, ...(meta.closed ? { sweep_finished: true } : {}) } };
1078
+ });
784
1079
  }
785
1080
  throw new LaneLinkError("subcommand_unknown", `Unknown lanes link subcommand: ${subcommand}`);
786
1081
  }
@@ -24,6 +24,16 @@ export interface OutpostPrunerInstallResult {
24
24
  enabled?: boolean;
25
25
  removed?: boolean;
26
26
  }
27
+ /** The pruner's systemd service unit; exported so tests can read its command line. */
28
+ export declare function renderOutpostPrunerService(opts: {
29
+ trigger: "pressure" | "daily";
30
+ nodeBinary: string;
31
+ hqBinary: string;
32
+ hqRoot: string;
33
+ home: string;
34
+ pathEnv: string;
35
+ flagEnvironment: string;
36
+ }): string;
27
37
  export declare function renderOutpostPrunerPressureTimer(): string;
28
38
  export declare function renderOutpostPrunerDailyTimer(): string;
29
39
  export declare function defaultOutpostPrunerSystemdDir(home?: string): string;
@@ -91,7 +91,8 @@ function unitPathEnv(hqBinary, nodeBinary) {
91
91
  ];
92
92
  return [...new Set(dirs)].filter(Boolean).join(":");
93
93
  }
94
- function renderService(opts) {
94
+ /** The pruner's systemd service unit; exported so tests can read its command line. */
95
+ export function renderOutpostPrunerService(opts) {
95
96
  const command = [
96
97
  opts.nodeBinary,
97
98
  opts.hqBinary,
@@ -183,9 +184,9 @@ export function installOutpostPrunerTimers(options) {
183
184
  ].join("\n");
184
185
  const pathEnv = unitPathEnv(hqBinary, nodeBinary);
185
186
  const units = [
186
- [OUTPOST_PRUNER_PRESSURE_SERVICE, renderService({ trigger: "pressure", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
187
+ [OUTPOST_PRUNER_PRESSURE_SERVICE, renderOutpostPrunerService({ trigger: "pressure", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
187
188
  [OUTPOST_PRUNER_PRESSURE_TIMER, renderOutpostPrunerPressureTimer()],
188
- [OUTPOST_PRUNER_DAILY_SERVICE, renderService({ trigger: "daily", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
189
+ [OUTPOST_PRUNER_DAILY_SERVICE, renderOutpostPrunerService({ trigger: "daily", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
189
190
  [OUTPOST_PRUNER_DAILY_TIMER, renderOutpostPrunerDailyTimer()],
190
191
  ];
191
192
  let written = false;
package/dist/main.js CHANGED
@@ -10,7 +10,7 @@ import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { Command } from "commander";
13
- import { finishSentrySession, initSentry, Sentry } from "./sentry.js";
13
+ import { closeSentryTransport, finishSentrySession, initSentry, Sentry } from "./sentry.js";
14
14
  import { addCommandBreadcrumb } from "./utils/command-breadcrumb.js";
15
15
  import { environmentalFsErrorMessage, filesystemErrorCaptureContext, filesystemErrorMessage, } from "./utils/environmental-error.js";
16
16
  import { syncStateLockMessage } from "./utils/sync-state-lock-error.js";
@@ -366,6 +366,8 @@ export async function runCli() {
366
366
  ...limitNoticeExposureFlushes,
367
367
  ...limitNoticeEngagementFlushes,
368
368
  ], releaseHealthTimeoutMs);
369
+ // The flush above is bounded; do not leave its keep-alive socket open.
370
+ closeSentryTransport();
369
371
  });
370
372
  // Last, so it wins over anything the (skipped) command path would have
371
373
  // set: the re-exec'd child's status IS this invocation's result.
@@ -5,6 +5,8 @@ type SentryBreadcrumb = Parameters<SentryModule["addBreadcrumb"]>[0];
5
5
  export declare function createFlaggedBeforeSend(beforeSend: NodeOptions["beforeSend"], skipManualOnlyReportsEnabled?: () => Promise<boolean>): NonNullable<NodeOptions["beforeSend"]>;
6
6
  export declare function initSentryRuntime(beforeSend: NodeOptions["beforeSend"], overrides?: Partial<Pick<NodeOptions, "transport">>, pendingBreadcrumbs?: readonly SentryBreadcrumb[]): SentryModule | undefined;
7
7
  export declare function finishSentryRuntimeSession(): void;
8
+ /** Close the transport's sockets once the final flush is done. */
9
+ export declare function closeSentryRuntimeTransport(): void;
8
10
  export declare function addSentryRuntimeBreadcrumb(breadcrumb: SentryBreadcrumb): void;
9
11
  export declare function flushSentryRuntime(timeoutMs: number): PromiseLike<boolean>;
10
12
  export {};
@@ -2,7 +2,8 @@ import { createRequire } from "node:module";
2
2
  import { BUNDLED_DSN } from "./sentry-dsn.generated.js";
3
3
  import { CLI_VERSION } from "./cli-version.js";
4
4
  import { beforeBreadcrumb } from "./utils/breadcrumb-buffer.js";
5
- import { residentProcessSkipsSentry } from "./utils/cli-network-lifecycle.js";
5
+ import { isScheduledShortRunCommand, residentProcessSkipsSentry } from "./utils/cli-network-lifecycle.js";
6
+ import { closeSentryTransportAgents, sentryHttpModule } from "./utils/sentry-keepalive-transport.js";
6
7
  import { getCachedSentryUser } from "./utils/sentry-identity.js";
7
8
  const requireRuntime = createRequire(import.meta.url);
8
9
  let sentryModule;
@@ -135,6 +136,8 @@ export function initSentryRuntime(beforeSend, overrides = {}, pendingBreadcrumbs
135
136
  beforeSend: createFlaggedBeforeSend(beforeSend),
136
137
  beforeBreadcrumb,
137
138
  integrations: (defaults) => defaults.filter((integration) => integration.name !== "ProcessSession"),
139
+ // One keep-alive connection, capped, instead of a new socket per envelope.
140
+ transportOptions: { httpModule: sentryHttpModule },
138
141
  ...overrides,
139
142
  });
140
143
  const user = getCachedSentryUser();
@@ -142,12 +145,20 @@ export function initSentryRuntime(beforeSend, overrides = {}, pendingBreadcrumbs
142
145
  sdk.setUser(user);
143
146
  for (const breadcrumb of pendingBreadcrumbs)
144
147
  sdk.addBreadcrumb(breadcrumb);
145
- sdk.startSession();
148
+ // A scheduled run (a daemon unit or timer, every 15 s to 6 h) sends only
149
+ // what it captures. Its release-health session was an envelope, and so a
150
+ // new ingest socket, on every clean run.
151
+ if (!isScheduledShortRunCommand(process.argv))
152
+ sdk.startSession();
146
153
  return sdk;
147
154
  }
148
155
  export function finishSentryRuntimeSession() {
149
156
  sentryModule?.endSession();
150
157
  }
158
+ /** Close the transport's sockets once the final flush is done. */
159
+ export function closeSentryRuntimeTransport() {
160
+ closeSentryTransportAgents();
161
+ }
151
162
  export function addSentryRuntimeBreadcrumb(breadcrumb) {
152
163
  sentryModule?.addBreadcrumb(breadcrumb);
153
164
  }
package/dist/sentry.d.ts CHANGED
@@ -26,5 +26,7 @@ export declare function epipeAwareBeforeSend(event: ErrorEvent, hint: EventHint)
26
26
  export declare function initSentry(overrides?: Partial<Pick<NodeOptions, "transport">>): void;
27
27
  /** Finish HQ's one per-invocation release-health session. */
28
28
  export declare function finishSentrySession(): void;
29
+ /** Close the Sentry transport's sockets after the run's final flush. */
30
+ export declare function closeSentryTransport(): void;
29
31
  export {};
30
32
  //# sourceMappingURL=sentry.d.ts.map
package/dist/sentry.js CHANGED
@@ -5,7 +5,7 @@ import { companySkillWrapperSentryTagsFor } from "./lib/company-skill-wrapper.js
5
5
  import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
6
6
  import { incompleteInstallCaptureContext, incompleteInstallMessage, } from "./utils/incomplete-install-error.js";
7
7
  import { installTreeTornSentryTagsFor, sentryFingerprintFor, sentryMcpCollisionContextFor, } from "./utils/sentry-fingerprint.js";
8
- import { finishSentryRuntimeSession, initSentryRuntime } from "./sentry-init.js";
8
+ import { closeSentryRuntimeTransport, finishSentryRuntimeSession, initSentryRuntime, } from "./sentry-init.js";
9
9
  const inertSentryScope = {
10
10
  setTag: () => inertSentryScope,
11
11
  setUser: () => inertSentryScope,
@@ -232,4 +232,8 @@ export function initSentry(overrides = {}) {
232
232
  export function finishSentrySession() {
233
233
  finishSentryRuntimeSession();
234
234
  }
235
+ /** Close the Sentry transport's sockets after the run's final flush. */
236
+ export function closeSentryTransport() {
237
+ closeSentryRuntimeTransport();
238
+ }
235
239
  //# sourceMappingURL=sentry.js.map
@@ -6,6 +6,15 @@ export declare function isHqDaemonRunCommand(argv: readonly string[]): boolean;
6
6
  */
7
7
  export declare function isLongLivedDaemonCommand(argv: readonly string[]): boolean;
8
8
  export declare function isLongLivedHelperCommand(argv: readonly string[]): boolean;
9
+ /**
10
+ * True for a scheduled short run. Such a run still reports errors, but it does
11
+ * not start a release-health session, so a run with nothing to report opens no
12
+ * connection to Sentry. One session per run was one new ingest socket per run:
13
+ * a 15 s reconcile timer alone left thousands of sockets in TIME_WAIT a day.
14
+ */
15
+ export declare function isScheduledShortRunCommand(argv: readonly string[], options?: {
16
+ interactive?: boolean;
17
+ }): boolean;
9
18
  /**
10
19
  * True when this process must not open the Sentry transport. `HQ_DAEMON_RESIDENT`
11
20
  * marks the long-running process the daemon started, including one whose
@@ -37,6 +37,58 @@ export function isLongLivedHelperCommand(argv) {
37
37
  const command = commandArgv(argv);
38
38
  return LONG_LIVED_HELPER_COMMANDS.some((prefix) => prefix.length <= command.length && prefix.every((part, index) => command[index] === part));
39
39
  }
40
+ /**
41
+ * Short commands that a scheduler runs again and again: the daemon's scheduled
42
+ * units (src/lib/daemon/catalog.ts) and the outpost systemd timers. Each run is
43
+ * a fresh process. Matched on argv, not on an environment mark, so a run that
44
+ * a daemon started before this release still matches once the new CLI is on
45
+ * disk. Leading `--hq-root <path>` after `core` is skipped.
46
+ */
47
+ const SCHEDULED_SHORT_RUN_COMMANDS = [
48
+ ["daemon", "service", "self-update"],
49
+ ["daemon", "service", "fleet-bots-update"],
50
+ ["daemon", "service", "sync-core-reconcile"],
51
+ ["daemon", "service", "sync-core-selfcheck"],
52
+ ["daemon", "service", "sync-core-manifest"],
53
+ ["runners", "reconcile"],
54
+ ["lanes", "reconcile"],
55
+ ["lanes", "outpost-pruner", "run"],
56
+ ["index", "sync"],
57
+ ["core", "jobs", "reconcile"],
58
+ ];
59
+ function withoutCoreHqRoot(command) {
60
+ if (command[0] !== "core")
61
+ return command;
62
+ const rest = command.slice(1);
63
+ while (rest[0] === "--hq-root" && rest.length >= 2)
64
+ rest.splice(0, 2);
65
+ return ["core", ...rest];
66
+ }
67
+ /**
68
+ * True for a scheduled short run. Such a run still reports errors, but it does
69
+ * not start a release-health session, so a run with nothing to report opens no
70
+ * connection to Sentry. One session per run was one new ingest socket per run:
71
+ * a 15 s reconcile timer alone left thousands of sockets in TIME_WAIT a day.
72
+ */
73
+ export function isScheduledShortRunCommand(argv, options = {}) {
74
+ // A person running one of these by hand keeps the normal session. Units and
75
+ // timers run with no terminal on stdin or stdout.
76
+ if (options.interactive ?? isInteractiveTerminal())
77
+ return false;
78
+ const command = withoutCoreHqRoot(commandArgv(argv));
79
+ if (command.includes("--dry-run"))
80
+ return false;
81
+ return SCHEDULED_SHORT_RUN_COMMANDS.some((prefix) => {
82
+ if (prefix.length > command.length || !prefix.every((part, index) => command[index] === part))
83
+ return false;
84
+ // Exact subcommand: `lanes reconcile install` is a setup command, not the timer run.
85
+ const next = command[prefix.length];
86
+ return next === undefined || next.startsWith("-");
87
+ });
88
+ }
89
+ function isInteractiveTerminal() {
90
+ return process.stdin.isTTY === true || process.stdout.isTTY === true;
91
+ }
40
92
  /**
41
93
  * True when this process must not open the Sentry transport. `HQ_DAEMON_RESIDENT`
42
94
  * marks the long-running process the daemon started, including one whose