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

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 (241) hide show
  1. package/CHANGELOG.md +206 -1
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  4. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  5. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  6. package/dist/command-catalog.generated.d.ts +105 -10
  7. package/dist/command-catalog.generated.js +127 -10
  8. package/dist/command-help.js +3 -1
  9. package/dist/command-registration-plan.d.ts +6 -0
  10. package/dist/command-registration-plan.js +1 -0
  11. package/dist/commands/auth.d.ts +1 -1
  12. package/dist/commands/auth.js +11 -52
  13. package/dist/commands/bot.js +75 -10
  14. package/dist/commands/capacity.d.ts +4 -1
  15. package/dist/commands/capacity.js +46 -10
  16. package/dist/commands/cloud-demote.d.ts +19 -4
  17. package/dist/commands/cloud-demote.js +85 -12
  18. package/dist/commands/cloud-provision.d.ts +5 -1
  19. package/dist/commands/cloud-provision.js +6 -2
  20. package/dist/commands/cloud.d.ts +36 -0
  21. package/dist/commands/cloud.js +110 -27
  22. package/dist/commands/core-delegate-w1b.js +15 -1
  23. package/dist/commands/core-policy.js +67 -8
  24. package/dist/commands/core.js +1 -0
  25. package/dist/commands/daemon.js +9 -1
  26. package/dist/commands/dm.js +7 -0
  27. package/dist/commands/doctor-usage.d.ts +8 -0
  28. package/dist/commands/doctor-usage.js +20 -0
  29. package/dist/commands/doctor.js +7 -1
  30. package/dist/commands/env.d.ts +18 -0
  31. package/dist/commands/env.js +82 -0
  32. package/dist/commands/files-browse.d.ts +11 -4
  33. package/dist/commands/files-browse.js +21 -4
  34. package/dist/commands/files.d.ts +1 -1
  35. package/dist/commands/files.js +25 -11
  36. package/dist/commands/install-global.js +2 -2
  37. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  38. package/dist/commands/integrations-auth-rules.js +79 -0
  39. package/dist/commands/integrations-import.js +124 -12
  40. package/dist/commands/lanes.js +102 -26
  41. package/dist/commands/logout.d.ts +7 -0
  42. package/dist/commands/logout.js +41 -34
  43. package/dist/commands/mesh.d.ts +2 -0
  44. package/dist/commands/mesh.js +60 -35
  45. package/dist/commands/sources.d.ts +8 -2
  46. package/dist/commands/sources.js +65 -9
  47. package/dist/commands/sync-held.js +5 -2
  48. package/dist/commands/whoami.js +26 -1
  49. package/dist/data/command-states.json +15 -0
  50. package/dist/index.js +52 -4
  51. package/dist/lazy-commands.js +5 -6
  52. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  53. package/dist/lib/anywhere-person-setting.js +6 -3
  54. package/dist/lib/billing/usage-card.d.ts +25 -4
  55. package/dist/lib/billing/usage-card.js +76 -9
  56. package/dist/lib/billing/usage-cost.d.ts +3 -3
  57. package/dist/lib/billing/usage-cost.js +35 -13
  58. package/dist/lib/billing/usage-only.js +4 -2
  59. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  60. package/dist/lib/billing/usage-rate-card.js +3 -0
  61. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  62. package/dist/lib/bot/fleet-cron.js +126 -7
  63. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  64. package/dist/lib/bot/fleet-daemon.js +99 -1
  65. package/dist/lib/bot/inflight.d.ts +9 -0
  66. package/dist/lib/bot/inflight.js +10 -0
  67. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  68. package/dist/lib/bot/probe.js +7 -1
  69. package/dist/lib/bot/run.js +20 -1
  70. package/dist/lib/bot/runtime/codex.js +1 -1
  71. package/dist/lib/bot/runtime/grok-acp.d.ts +6 -1
  72. package/dist/lib/bot/runtime/grok-acp.js +32 -14
  73. package/dist/lib/bot/runtime/grok.js +1 -1
  74. package/dist/lib/bot/runtime/index.js +19 -9
  75. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  76. package/dist/lib/bot/runtime/types.d.ts +15 -0
  77. package/dist/lib/bot/runtime/types.js +9 -0
  78. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  79. package/dist/lib/bot/runtime-failure.js +43 -1
  80. package/dist/lib/capacity/accounts.d.ts +8 -0
  81. package/dist/lib/capacity/accounts.js +19 -0
  82. package/dist/lib/capacity/available.d.ts +154 -0
  83. package/dist/lib/capacity/available.js +905 -0
  84. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  85. package/dist/lib/capacity/codex-availability.js +26 -1
  86. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  87. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  88. package/dist/lib/capacity/collectors/codex.js +10 -7
  89. package/dist/lib/capacity/ledger.d.ts +37 -1
  90. package/dist/lib/capacity/ledger.js +207 -30
  91. package/dist/lib/capacity/project.d.ts +26 -0
  92. package/dist/lib/capacity/project.js +137 -8
  93. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  94. package/dist/lib/capacity/refusal-rows.js +61 -0
  95. package/dist/lib/capacity/refusal.d.ts +53 -2
  96. package/dist/lib/capacity/refusal.js +284 -65
  97. package/dist/lib/capacity/route.js +46 -11
  98. package/dist/lib/capacity/widget.d.ts +12 -1
  99. package/dist/lib/capacity/widget.js +91 -3
  100. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  101. package/dist/lib/daemon/flag-monitor.js +17 -6
  102. package/dist/lib/daemon/flag.d.ts +65 -1
  103. package/dist/lib/daemon/flag.js +190 -40
  104. package/dist/lib/daemon/ops/policy.js +62 -5
  105. package/dist/lib/daemon/paths.d.ts +72 -2
  106. package/dist/lib/daemon/paths.js +154 -3
  107. package/dist/lib/daemon/resolver.d.ts +2 -0
  108. package/dist/lib/daemon/resolver.js +3 -0
  109. package/dist/lib/daemon/run.d.ts +9 -0
  110. package/dist/lib/daemon/run.js +79 -21
  111. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  112. package/dist/lib/daemon/selfcheck.js +40 -1
  113. package/dist/lib/daemon/server.d.ts +5 -1
  114. package/dist/lib/daemon/server.js +17 -23
  115. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  116. package/dist/lib/daemon/state-file-switch.js +88 -0
  117. package/dist/lib/daemon/state-file.d.ts +198 -0
  118. package/dist/lib/daemon/state-file.js +419 -0
  119. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  120. package/dist/lib/daemon/tcc-eperm.js +310 -0
  121. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  122. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  123. package/dist/lib/delivery/admission.d.ts +86 -0
  124. package/dist/lib/delivery/admission.js +148 -0
  125. package/dist/lib/delivery/artifacts.d.ts +7 -1
  126. package/dist/lib/delivery/artifacts.js +29 -10
  127. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  128. package/dist/lib/delivery/attempt-id.js +16 -0
  129. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  130. package/dist/lib/delivery/disposable-target.js +111 -0
  131. package/dist/lib/delivery/effects.d.ts +136 -0
  132. package/dist/lib/delivery/effects.js +541 -0
  133. package/dist/lib/delivery/enrollment.d.ts +21 -17
  134. package/dist/lib/delivery/enrollment.js +83 -5
  135. package/dist/lib/delivery/escalations.d.ts +51 -0
  136. package/dist/lib/delivery/escalations.js +60 -0
  137. package/dist/lib/delivery/lease.d.ts +80 -0
  138. package/dist/lib/delivery/lease.js +134 -0
  139. package/dist/lib/delivery/migrations.d.ts +120 -4
  140. package/dist/lib/delivery/migrations.js +215 -15
  141. package/dist/lib/delivery/mqtt.d.ts +2 -0
  142. package/dist/lib/delivery/mqtt.js +7 -0
  143. package/dist/lib/delivery/reconciler.d.ts +65 -1
  144. package/dist/lib/delivery/reconciler.js +224 -13
  145. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  146. package/dist/lib/delivery/rpc/client.js +159 -0
  147. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  148. package/dist/lib/delivery/rpc/port.js +16 -0
  149. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  150. package/dist/lib/delivery/rpc/server.js +205 -0
  151. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  152. package/dist/lib/delivery/rpc/wire.js +143 -0
  153. package/dist/lib/delivery/store.d.ts +2 -0
  154. package/dist/lib/delivery/store.js +4 -0
  155. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  156. package/dist/lib/delivery/windows-service-install.js +892 -0
  157. package/dist/lib/delivery/workers/macos.d.ts +16 -1
  158. package/dist/lib/delivery/workers/macos.js +54 -12
  159. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  160. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  161. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  162. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  163. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  164. package/dist/lib/delivery/workers/windows-service.js +584 -0
  165. package/dist/lib/delivery/workers/windows.d.ts +32 -22
  166. package/dist/lib/delivery/workers/windows.js +50 -64
  167. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  168. package/dist/lib/doctor/checks/host-core.js +269 -0
  169. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  170. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  171. package/dist/lib/doctor/registry.js +4 -0
  172. package/dist/lib/environment/profile.d.ts +239 -0
  173. package/dist/lib/environment/profile.js +251 -0
  174. package/dist/lib/hook-engine/reconcile.js +39 -13
  175. package/dist/lib/hook-engine/registration.d.ts +9 -0
  176. package/dist/lib/hook-engine/registration.js +19 -0
  177. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  178. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  179. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  180. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  181. package/dist/lib/hot-channels/alert.d.ts +2 -0
  182. package/dist/lib/hot-channels/alert.js +8 -1
  183. package/dist/lib/hot-channels/contract.d.ts +12 -0
  184. package/dist/lib/hot-channels/contract.js +7 -0
  185. package/dist/lib/hot-channels/loop.js +1 -0
  186. package/dist/lib/hot-channels/run.d.ts +6 -0
  187. package/dist/lib/hot-channels/run.js +4 -0
  188. package/dist/lib/hot-channels/signals-pass.d.ts +74 -1
  189. package/dist/lib/hot-channels/signals-pass.js +82 -41
  190. package/dist/lib/hot-channels/signals-redo.js +10 -2
  191. package/dist/lib/install/claude-targets.d.ts +12 -1
  192. package/dist/lib/install/claude-targets.js +57 -5
  193. package/dist/lib/install/codex-targets.d.ts +2 -2
  194. package/dist/lib/install/codex-targets.js +36 -6
  195. package/dist/lib/install/hook-target.d.ts +3 -0
  196. package/dist/lib/install/hook-target.js +11 -0
  197. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  198. package/dist/lib/lanes/canonical-host.js +65 -0
  199. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  200. package/dist/lib/lanes/host-capacity.js +29 -3
  201. package/dist/lib/lanes/watcher.js +35 -0
  202. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  203. package/dist/lib/mesh/live/daemon/run.js +5 -2
  204. package/dist/lib/mesh/live/flush.d.ts +5 -1
  205. package/dist/lib/mesh/live/flush.js +12 -6
  206. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  207. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  208. package/dist/lib/mesh/live/spool.d.ts +7 -0
  209. package/dist/lib/mesh/live/spool.js +25 -0
  210. package/dist/lib/person-setting-cache.d.ts +38 -0
  211. package/dist/lib/person-setting-cache.js +98 -0
  212. package/dist/lib/safe-store.d.ts +245 -0
  213. package/dist/lib/safe-store.js +777 -0
  214. package/dist/lib/signals/engine.d.ts +29 -2
  215. package/dist/lib/signals/engine.js +103 -4
  216. package/dist/lib/signals/reply.js +73 -18
  217. package/dist/lib/signals/steps/adapters.js +7 -2
  218. package/dist/lib/signals/steps/extract.d.ts +13 -0
  219. package/dist/lib/signals/steps/extract.js +122 -6
  220. package/dist/main.js +46 -3
  221. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  222. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  223. package/dist/utils/auth-expiry.d.ts +8 -0
  224. package/dist/utils/auth-expiry.js +53 -0
  225. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  226. package/dist/utils/catalog-runtime-paths.js +53 -0
  227. package/dist/utils/cli-telemetry.d.ts +21 -0
  228. package/dist/utils/cli-telemetry.js +34 -0
  229. package/dist/utils/command-usage.d.ts +275 -0
  230. package/dist/utils/command-usage.js +797 -0
  231. package/dist/utils/files-browse-acl.js +1 -1
  232. package/dist/utils/hook-trust.d.ts +7 -0
  233. package/dist/utils/hook-trust.js +31 -4
  234. package/dist/utils/host-registration.d.ts +126 -0
  235. package/dist/utils/host-registration.js +378 -0
  236. package/dist/utils/resident-package-preload.js +2 -0
  237. package/package.json +10 -8
  238. package/scripts/bench-core.mjs +1096 -0
  239. package/scripts/check-function-manifest.mjs +702 -0
  240. package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
  241. package/dist/lib/delivery/workers/windows-boundary.js +0 -693
@@ -29,7 +29,7 @@
29
29
  * Fixes are returned as commands for the caller to preview and run with the
30
30
  * user's yes (the /hq-cost skill does that).
31
31
  */
32
- import { BUNDLED_USAGE_CARD, SELF_HOSTED_GUIDE_URL, formatFreeItems } from "./usage-card.js";
32
+ import { BUNDLED_USAGE_CARD, SELF_HOSTED_GUIDE_URL, formatCardUsd, formatFreeItems, meterRateText, readMeterDisplayFields, } from "./usage-card.js";
33
33
  import { BUNDLED_USAGE_METER_RATES, USAGE_MONTHLY_ALLOWANCE_USD, } from "./usage-rate-card.js";
34
34
  /** Bytes per billed GB. Storage is billed like S3: 1 GB = 2^30 bytes. */
35
35
  export const BYTES_PER_GB = 1024 ** 3;
@@ -177,13 +177,19 @@ export function meterReadingsFromStatement(body) {
177
177
  if (typeof line.key !== "string" || !STATEMENT_KEYS.has(line.key))
178
178
  continue;
179
179
  const key = line.key;
180
+ const quote = readMeterDisplayFields(line);
180
181
  const measured = line.status === "measured" || line.status === "partial";
181
182
  const usage = line.usage;
182
183
  if (!measured || typeof usage !== "number" || !Number.isFinite(usage) || usage < 0) {
183
- byKey.set(key, { key, value: null, state: "not-available" });
184
+ byKey.set(key, { key, value: null, state: "not-available", ...quote });
184
185
  continue;
185
186
  }
186
- const reading = { key, value: key === "storage" ? usage / bytesPerGb : usage, state: "measured" };
187
+ const reading = {
188
+ key,
189
+ value: key === "storage" ? usage / bytesPerGb : usage,
190
+ state: "measured",
191
+ ...quote,
192
+ };
187
193
  const cost = centsField(line.costCents);
188
194
  const projected = centsField(line.projectedCostCents);
189
195
  if (cost !== null && projected !== null) {
@@ -270,32 +276,38 @@ export function computeBill(usage, rates = BUNDLED_USAGE_METER_RATES, cardAllowa
270
276
  let incomplete = false;
271
277
  const meters = rates.map((rate) => {
272
278
  const reading = byKey.get(rate.key) ?? { key: rate.key, value: null, state: "not-available" };
279
+ const quoted = (cost) => ({
280
+ ...cost,
281
+ ...(reading.displayPer !== undefined ? { displayPer: reading.displayPer } : {}),
282
+ ...(reading.displayUsd !== undefined ? { displayUsd: reading.displayUsd } : {}),
283
+ ...(reading.displayText !== undefined ? { displayText: reading.displayText } : {}),
284
+ });
273
285
  if (reading.state !== "measured" || reading.value === null) {
274
286
  incomplete = true;
275
- return { ...pick(rate), value: null, state: reading.state, monthToDateUsd: null, projectedUsd: null };
287
+ return quoted({ ...pick(rate), value: null, state: reading.state, monthToDateUsd: null, projectedUsd: null });
276
288
  }
277
289
  if (reading.accrued) {
278
290
  const { monthToDateUsd: m, projectedUsd: p, waived } = reading.accrued;
279
291
  mtd += m;
280
292
  projected += p;
281
- return {
293
+ return quoted({
282
294
  ...pick(rate),
283
295
  value: reading.value,
284
296
  state: "measured",
285
297
  monthToDateUsd: round2(m),
286
298
  projectedUsd: round2(p),
287
299
  ...(waived ? { waivedInTrial: true } : {}),
288
- };
300
+ });
289
301
  }
290
302
  if (rate.waivedInTrial && usage.trialActive === true) {
291
- return { ...pick(rate), value: reading.value, state: "measured", monthToDateUsd: 0, projectedUsd: 0, waivedInTrial: true };
303
+ return quoted({ ...pick(rate), value: reading.value, state: "measured", monthToDateUsd: 0, projectedUsd: 0, waivedInTrial: true });
292
304
  }
293
305
  const full = reading.value * rate.unitUsd;
294
306
  const m = rate.kind === "gauge" ? full * (daysElapsed / daysInMonth) : full;
295
307
  const p = rate.kind === "gauge" ? full : full * (daysInMonth / daysElapsed);
296
308
  mtd += m;
297
309
  projected += p;
298
- return { ...pick(rate), value: reading.value, state: "measured", monthToDateUsd: round2(m), projectedUsd: round2(p) };
310
+ return quoted({ ...pick(rate), value: reading.value, state: "measured", monthToDateUsd: round2(m), projectedUsd: round2(p) });
299
311
  });
300
312
  return {
301
313
  meters,
@@ -310,7 +322,15 @@ export function computeBill(usage, rates = BUNDLED_USAGE_METER_RATES, cardAllowa
310
322
  };
311
323
  }
312
324
  function pick(rate) {
313
- return { key: rate.key, displayName: rate.displayName, unit: rate.unit, unitUsd: rate.unitUsd };
325
+ return {
326
+ key: rate.key,
327
+ displayName: rate.displayName,
328
+ unit: rate.unit,
329
+ unitUsd: rate.unitUsd,
330
+ ...(rate.displayPer !== undefined ? { displayPer: rate.displayPer } : {}),
331
+ ...(rate.displayUsd !== undefined ? { displayUsd: rate.displayUsd } : {}),
332
+ ...(rate.displayText !== undefined ? { displayText: rate.displayText } : {}),
333
+ };
314
334
  }
315
335
  function gb(n) {
316
336
  return n >= 10 ? n.toFixed(0) : n >= 1 ? n.toFixed(1) : n.toFixed(2);
@@ -405,13 +425,13 @@ export function findDrivers(usage, bill) {
405
425
  if (secrets?.projectedUsd && secrets.value) {
406
426
  drivers.push({
407
427
  meter: "secret",
408
- summary: `Secrets: ${secrets.value} stored at ${usd(secrets.unitUsd)} each a month (${usd(secrets.projectedUsd)}).`,
428
+ summary: `Secrets: ${secrets.value} stored at ${formatCardUsd(secrets.unitUsd)} each a month (${usd(secrets.projectedUsd)}).`,
409
429
  projectedUsd: secrets.projectedUsd,
410
430
  fixes: [
411
431
  {
412
432
  id: "remove-unused-secrets",
413
433
  title: "Remove secrets nothing uses any more",
414
- detail: `Each secret you delete saves ${usd(secrets.unitUsd)} a month. HQ does not record when a secret was last read, ` +
434
+ detail: `Each secret you delete saves ${formatCardUsd(secrets.unitUsd)} a month. HQ does not record when a secret was last read, ` +
415
435
  "so the list shows when each was last changed; you pick which to delete, one at a time. This cannot be undone.",
416
436
  preview: [`hq secrets${companyFlag(scope)}${personalFlag(scope)} list`],
417
437
  // --force skips the CLI's own TTY prompt. Run it only for a name the
@@ -511,9 +531,11 @@ export function buildReport(usage, rates) {
511
531
  };
512
532
  }
513
533
  function rateText(m) {
514
- const price = m.unitUsd >= 1 ? usd(m.unitUsd) : `$${m.unitUsd.toFixed(2)}`;
534
+ const price = meterRateText(m);
535
+ if (m.displayText)
536
+ return price;
515
537
  const trial = m.key === "vault" && !m.waivedInTrial ? ", waived during the trial" : "";
516
- return `${price} per ${m.unit}${trial}`;
538
+ return `${price}${trial}`;
517
539
  }
518
540
  function valueText(m) {
519
541
  if (m.state === "not-available")
@@ -22,7 +22,7 @@
22
22
  * they saw before, and an account is only told about usage pricing when the
23
23
  * server said so.
24
24
  */
25
- import { BUNDLED_USAGE_CARD, formatBoxQuotes, formatCardUsd, } from "./usage-card.js";
25
+ import { BUNDLED_USAGE_CARD, formatBoxQuotes, formatCardUsd, meterRateText, } from "./usage-card.js";
26
26
  // Static imports on purpose: resident command paths (agents, daemon, ...) may
27
27
  // not lazy-load packages (src/utils/resident-package-preload.test.ts).
28
28
  // vault-api loads plan-limit-nag with a dynamic import, so there is no
@@ -337,7 +337,9 @@ export function usageOnlyPlanLine(card = BUNDLED_USAGE_CARD) {
337
337
  */
338
338
  export function usageOnlyBoxSentence(card = BUNDLED_USAGE_CARD) {
339
339
  const run = card.meters.find((m) => m.id === "agent-run");
340
- const perRun = run ? `, plus ${formatCardUsd(run.unitUsd)} per agent run` : "";
340
+ const perRun = run
341
+ ? `, plus ${run.displayText ? meterRateText(run) : `${formatCardUsd(run.unitUsd)} per agent run`}`
342
+ : "";
341
343
  return `Agent boxes on usage pricing are billed by size: ${formatBoxQuotes(card)}${perRun}.`;
342
344
  }
343
345
  /**
@@ -11,7 +11,7 @@
11
11
  * or counter) are priced here; an unknown feed meter is left out of the bill
12
12
  * rather than billed with a guessed shape.
13
13
  */
14
- import { type UsageCard } from "./usage-card.js";
14
+ import { type MeterDisplayFields, type UsageCard } from "./usage-card.js";
15
15
  export type UsageMeterKey = "member-sync" | "integration-call" | "hq-mcp-call" | "agent-run" | "storage" | "secret" | "vault";
16
16
  /**
17
17
  * Gauges are billed on the amount held (GB, secrets, vaults) for the month.
@@ -19,7 +19,7 @@ export type UsageMeterKey = "member-sync" | "integration-call" | "hq-mcp-call" |
19
19
  * month end.
20
20
  */
21
21
  export type UsageMeterKind = "gauge" | "counter";
22
- export interface UsageMeterRate {
22
+ export interface UsageMeterRate extends MeterDisplayFields {
23
23
  readonly key: UsageMeterKey;
24
24
  readonly displayName: string;
25
25
  /** What one billed unit is, in words. */
@@ -37,6 +37,9 @@ export function ratesFromCard(card) {
37
37
  unitUsd: m.unitUsd,
38
38
  kind: METER_KINDS[m.id],
39
39
  ...(m.waivedInTrial ? { waivedInTrial: true } : {}),
40
+ ...(m.displayPer !== undefined ? { displayPer: m.displayPer } : {}),
41
+ ...(m.displayUsd !== undefined ? { displayUsd: m.displayUsd } : {}),
42
+ ...(m.displayText !== undefined ? { displayText: m.displayText } : {}),
40
43
  });
41
44
  }
42
45
  return out;
@@ -73,6 +73,12 @@ export declare const FLEET_HOT_SIGNAL_SYNC_NAME = "hot-signal-sync";
73
73
  export declare const FLEET_HOT_SIGNAL_SYNC_SCHEDULE = "30 6 * * *";
74
74
  export declare function fleetHotSignalSyncScript(company: string): string;
75
75
  export declare function companyOfHotSignalSyncJob(job: FleetCronJob): string | null;
76
+ /**
77
+ * pnpm global installs land the CLI under `.../pnpm/global/vN/<hash>/...`.
78
+ * That hash folder is removed on the next CLI update. The stable launcher is
79
+ * `.../pnpm/bin/hq`. Empty when `hqBinary` is not a pnpm package entry.
80
+ */
81
+ export declare function fleetPnpmHqLauncher(hqBinary: string): string;
76
82
  export declare function renderFleetHotSignalSyncScript(input: {
77
83
  nodeBinary: string;
78
84
  hqBinary: string;
@@ -85,6 +91,8 @@ export declare function renderFleetHotSignalSyncScript(input: {
85
91
  * the job these bots ran before the engine.
86
92
  */
87
93
  signalsEngine?: boolean;
94
+ /** Override the baked pnpm `bin/hq` fallback. Tests pass this. */
95
+ hqLauncher?: string;
88
96
  }): string;
89
97
  export interface EnsureFleetHotSignalSyncInput {
90
98
  dir: string;
@@ -5,6 +5,7 @@ import { effectiveBotCompanies, effectiveBotKind } from "./config.js";
5
5
  import { fleetLocalRuntimePython, stderrTail } from "./fleet-local.js";
6
6
  import { readLocalJobs, withJobsLock, writeLocalJobs } from "./local-jobs.js";
7
7
  import { signInCommand } from "./runtime-sign-in.js";
8
+ import { SIGNALS_FAILURE_PREFIX } from "../hot-channels/alert.js";
8
9
  import { currentHotSignalSyncCompany, forgetHotSignalSyncRegistrationsExcept, hotSignalSyncJobCompany, fleetHotSignalSyncRegistered, markFleetHotSignalSyncRegistered, otherBotWithHotSignalSync, } from "./jobs/hot-signal-sync.js";
9
10
  const RESULT_MARKER = "@@HQ_FLEET_CRON@@";
10
11
  export const FLEET_CRON_BRIDGE = [
@@ -340,6 +341,9 @@ def classify(out, err, code):
340
341
  text = ANSI.sub('', (err or '') + '\n' + (out or ''))
341
342
  if re.search(r"HQ session has expired|not signed in to HQ|Sign in to HQ first|run .hq login", text, re.I):
342
343
  return 'you are signed out of HQ', FIXES['hq_signed_out']
344
+ # Before the plain claude checks: a Codex main bot is told why Claude Code is needed.
345
+ if re.search(r'claude-logged-out-codex-bot', text, re.I):
346
+ return "your main bot runs on Codex, but signals from hot-channel sync need Claude Code, which is not installed or not signed in on this computer", FIXES['codex_bot_needs_claude']
343
347
  if re.search(r'claude could not start:.*\bENOENT\b|spawn claude ENOENT', text, re.I):
344
348
  return 'Claude Code is not installed on this computer', FIXES['claude_missing']
345
349
  if re.search(r'claude-logged-out|claude (reported it )?is not logged in|claude could not start', text, re.I):
@@ -350,26 +354,93 @@ def classify(out, err, code):
350
354
  if re.match(r'^sources/[A-Za-z0-9._/-]+\.md$', key) and '..' not in key:
351
355
  return 'Claude ran out of time on one document', FIXES['claude_timeout_key'].replace('KEY', key)
352
356
  return 'Claude ran out of time on one document', FIXES['claude_timeout']
357
+ # The other signals-pass codes; the run ledger stores the bare code as the error.
358
+ if re.search(r'claude-usage-limit|claude is out of usage', text, re.I):
359
+ return 'Claude is out of usage on this account', FIXES['claude_usage_limit']
360
+ if re.search(r'claude-bad-output', text, re.I):
361
+ return 'Claude gave replies the signals step could not read', FIXES['claude_bad_output']
362
+ if re.search(r'claude-provider-error', text, re.I):
363
+ return 'Claude reported an error', FIXES['claude_provider_error']
353
364
  if re.search(r'fetch failed|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|socket hang up', text, re.I):
354
365
  return 'HQ could not reach the network', FIXES['network']
355
366
  line = last_error_line(out, err)
356
367
  if line:
357
368
  return line, FIXES['other']
358
- return 'hq stopped with exit code %d and gave no reason' % code, FIXES['unknown']
369
+ if output_lines(out) or output_lines(err):
370
+ return 'hq stopped with exit code %d and printed no error (its output is in the log)' % code, FIXES['unknown']
371
+ return 'hq stopped with exit code %d and printed nothing' % code, FIXES['unknown']
372
+ `;
373
+ /**
374
+ * Python helper for the flag-off script: the signals-failure alerts that
375
+ * `hq sources sync` printed to stderr on a run that still exited 0 (the text
376
+ * of formatSignalsFailureAlert in lib/hot-channels/alert.ts, found by
377
+ * SIGNALS_FAILURE_PREFIX anywhere in a line, so a prefix the writer adds does
378
+ * not hide it). Only alerts with an "Error:" line count: the signals pass or
379
+ * the channel failed. A clean run that found no signals has no error and stays
380
+ * in the log. Returns one "<adapter> landed N sources and generated M signals"
381
+ * per failed alert and their errors. The connection id and the person are left out.
382
+ */
383
+ const HOT_SIGNAL_SYNC_SIGNALS_FAILURES = String.raw `SIGNALS_FAILURE = re.compile(re.escape(SIGNALS_FAILURE_PREFIX) + r'.*?: (\S+)(?: \([^)]*\))? landed (\d+ sources?) and generated (\d+ signals?)\.$')
384
+ ALERT_ERROR = re.compile(r'^\W*Error: (.+)$')
385
+
386
+ def signals_failures(err):
387
+ found, errors = [], []
388
+ lines = output_lines(err)
389
+ for i, line in enumerate(lines):
390
+ m = SIGNALS_FAILURE.search(line)
391
+ if not m:
392
+ continue
393
+ error = next((e.group(1) for e in (ALERT_ERROR.match(f) for f in lines[i + 1:i + 3]) if e), '')
394
+ if not error:
395
+ continue
396
+ found.append('%s landed %s and generated %s' % (m.group(1), m.group(2), m.group(3)))
397
+ errors.append(error)
398
+ return found, errors
359
399
  `;
360
400
  /** How a run ended, for the log line after it: `exit 1` or `signal 9`. */
361
401
  const HOT_SIGNAL_SYNC_RUN_END = String.raw `def run_end(code):
362
402
  return 'signal %d' % -code if code < 0 else 'exit %d' % code
363
403
  `;
404
+ /**
405
+ * pnpm global installs land the CLI under `.../pnpm/global/vN/<hash>/...`.
406
+ * That hash folder is removed on the next CLI update. The stable launcher is
407
+ * `.../pnpm/bin/hq`. Empty when `hqBinary` is not a pnpm package entry.
408
+ */
409
+ export function fleetPnpmHqLauncher(hqBinary) {
410
+ const normalized = hqBinary.replace(/\\/g, "/");
411
+ const match = /^(.*)\/pnpm\/global\/v\d+\/[^/]+\/node_modules\/@indigoai-us\/hq-cli\/dist\/index\.js$/i.exec(normalized);
412
+ return match ? `${match[1]}/pnpm/bin/hq` : "";
413
+ }
414
+ const HOT_SIGNAL_SYNC_HQ_ARGV = String.raw `def hq_argv():
415
+ if os.path.isfile(HQ):
416
+ return [NODE, HQ]
417
+ if LAUNCHER and os.path.isfile(LAUNCHER):
418
+ return [LAUNCHER]
419
+ found = shutil.which('hq')
420
+ if found:
421
+ return [found]
422
+ home = os.path.expanduser('~')
423
+ for rel in ('Library/pnpm/bin/hq', '.local/share/pnpm/hq'):
424
+ p = os.path.join(home, rel)
425
+ if os.path.isfile(p):
426
+ return [p]
427
+ raise FileNotFoundError(HQ)
428
+ `;
364
429
  export function renderFleetHotSignalSyncScript(input) {
365
430
  const plainSync = input.signalsEngine === false;
431
+ // The plain sync's ledger lines record `scheduled` for this job. The CLI
432
+ // that writes this script runs it (HQ is its own entry), but a fallback
433
+ // launcher can be an older hq without --trigger; the script then runs
434
+ // LEGACY_ARGS, the same command without it.
435
+ const legacyArgs = ["sources", "sync", "--company", input.company, "--hq-root", input.hqRoot];
366
436
  const args = plainSync
367
- ? ["sources", "sync", "--company", input.company, "--hq-root", input.hqRoot]
437
+ ? ["sources", "sync", "--trigger", "scheduled", "--company", input.company, "--hq-root", input.hqRoot]
368
438
  : ["signals", "run", "--trigger", "job", "--company", input.company, "--hq-root", input.hqRoot, "--report-found"];
369
439
  const syncCommand = `hq sources sync --company ${input.company}`;
370
440
  const fixes = {
371
441
  hq_signed_out: "run `hq login`.",
372
442
  claude_signed_out: `run \`${signInCommand("claude")}\`.`,
443
+ codex_bot_needs_claude: `sign in to Claude Code here (\`${signInCommand("claude")}\`).`,
373
444
  claude_missing: `install Claude Code (\`npm install -g @anthropic-ai/claude-code\`), then run \`${signInCommand("claude")}\`.`,
374
445
  claude_timeout_key: `run \`hq sources signals --company ${input.company} --key KEY\` to retry that document.`,
375
446
  claude_timeout: "the next run retries the document.",
@@ -377,6 +448,10 @@ export function renderFleetHotSignalSyncScript(input) {
377
448
  signal: `run \`${syncCommand}\` to see whether it happens again.`,
378
449
  other: `run \`${syncCommand}\` to see the full error.`,
379
450
  unknown: `run \`${syncCommand}\` to see what goes wrong.`,
451
+ // DATE becomes the run's date when the script starts.
452
+ claude_usage_limit: `wait for your Claude usage to reset, then run \`hq sources signals --company ${input.company} --since DATE\` to build the missing signals.`,
453
+ claude_bad_output: `run \`hq sources signals --company ${input.company} --since DATE\` to try those documents again.`,
454
+ claude_provider_error: `run \`hq sources signals --company ${input.company} --since DATE\` to try again and see the full error.`,
380
455
  };
381
456
  // One header per run, so an alert's start time finds its entry in the log,
382
457
  // and one line after it with how the run ended.
@@ -389,14 +464,35 @@ export function renderFleetHotSignalSyncScript(input) {
389
464
  // failed, with the job's time, the reason, one fix step and the log. The
390
465
  // plain script exits non-zero after a failed run (128 + N after signal N, as
391
466
  // a shell does), so the job's status is not `ok`: Fleet records a no-agent
392
- // job from its exit code.
467
+ // job from its exit code. A run that exits 0 after its signals pass failed
468
+ // prints the signals-failure alert to stderr only, since the CLI has no DM
469
+ // sender; the script finds that alert and sends the owner the same three
470
+ // lines (US-018 AC1). A clean run that landed sources and found no signals
471
+ // also raises the alert, but with no error; it stays in the log. The exit
472
+ // code stays 0: the sync itself finished.
473
+ const launcher = input.hqLauncher ?? fleetPnpmHqLauncher(input.hqBinary);
474
+ // HQ is often the pnpm hash folder's dist/index.js. That path dies on the
475
+ // next CLI update (feedback_614121bf). Prefer it while it exists so tests
476
+ // and `node <entry>` callers stay unchanged; otherwise run the stable
477
+ // launcher without node (it is a shell/cmd shim, not JS).
393
478
  const run = plainSync
394
479
  ? [
395
- " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
480
+ " command = hq_argv() + ARGS",
481
+ " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
482
+ " note = ''",
483
+ // Commander rejects the option before the sync starts, so the retry is
484
+ // the only run that does any work.
485
+ " if result.returncode != 0 and \"unknown option '--trigger'\" in result.stderr:",
486
+ " note = 'This hq has no --trigger option; ran the sync without it.\\n'",
487
+ " command = hq_argv() + LEGACY_ARGS",
488
+ " result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
396
489
  " with open(LOG, 'a', encoding='utf-8') as log:",
397
490
  header,
491
+ " log.write(note)",
398
492
  " log.write(result.stderr)",
399
493
  " log.write(result.stdout)",
494
+ " if result.returncode != 0 and not output_lines(result.stderr) and not output_lines(result.stdout):",
495
+ " log.write('hq printed nothing. Command: ' + shlex.join(command) + '\\n')",
400
496
  footer,
401
497
  " if result.returncode != 0:",
402
498
  " reason, fix = classify(result.stdout, result.stderr, result.returncode)",
@@ -404,24 +500,47 @@ export function renderFleetHotSignalSyncScript(input) {
404
500
  " sys.stdout.write('Fix: ' + fix + '\\n')",
405
501
  " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
406
502
  " sys.exit(128 - result.returncode if result.returncode < 0 else result.returncode)",
503
+ " found, errors = signals_failures(result.stderr)",
504
+ " if found:",
505
+ " reasons, fixes = [], []",
506
+ " for error in errors:",
507
+ " reason, fix = classify('', error, 1)",
508
+ " if reason not in reasons:",
509
+ " reasons.append(reason)",
510
+ " if fix not in fixes:",
511
+ " fixes.append(fix)",
512
+ ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} landed sources but the signals step failed: `)} + '; '.join(found) + '. Cause: ' + '; '.join(reasons) + '.\\n')`,
513
+ " sys.stdout.write('Fix: ' + ' Also, '.join(fixes) + '\\n')",
514
+ " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
407
515
  ]
408
516
  : [
409
517
  " with open(LOG, 'a', encoding='utf-8') as log:",
410
518
  header,
411
519
  " log.flush()",
412
- " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=log, encoding='utf-8', errors='replace')",
520
+ " result = subprocess.run(hq_argv() + ARGS, stdout=subprocess.PIPE, stderr=log, encoding='utf-8', errors='replace')",
413
521
  footer,
414
522
  " sys.stdout.write(result.stdout)",
415
523
  ];
416
524
  return [
417
- plainSync ? "import json, os, re, signal, subprocess, sys, time, urllib.parse" : "import subprocess, sys, time",
525
+ plainSync ? "import json, os, re, shlex, shutil, signal, subprocess, sys, time, urllib.parse" : "import os, shutil, subprocess, sys, time",
418
526
  `NODE = ${JSON.stringify(input.nodeBinary)}`,
419
527
  `HQ = ${JSON.stringify(input.hqBinary)}`,
528
+ `LAUNCHER = ${JSON.stringify(launcher)}`,
420
529
  `ARGS = ${JSON.stringify(args)}`,
421
530
  `LOG = ${JSON.stringify(input.logFile)}`,
422
531
  "STARTED = time.localtime()",
423
532
  HOT_SIGNAL_SYNC_RUN_END,
424
- ...(plainSync ? [`FIXES = ${JSON.stringify(fixes)}`, HOT_SIGNAL_SYNC_ALERT_HELPERS] : []),
533
+ HOT_SIGNAL_SYNC_HQ_ARGV,
534
+ ...(plainSync
535
+ ? [
536
+ `LEGACY_ARGS = ${JSON.stringify(legacyArgs)}`,
537
+ `FIXES = ${JSON.stringify(fixes)}`,
538
+ "FIXES = dict((k, v.replace('DATE', time.strftime('%Y-%m-%d', STARTED))) for k, v in FIXES.items())",
539
+ HOT_SIGNAL_SYNC_ALERT_HELPERS,
540
+ `SIGNALS_FAILURE_PREFIX = ${JSON.stringify(SIGNALS_FAILURE_PREFIX)}`,
541
+ HOT_SIGNAL_SYNC_SIGNALS_FAILURES,
542
+ ]
543
+ : []),
425
544
  "try:",
426
545
  ...run,
427
546
  "except OSError as exc:",
@@ -29,6 +29,52 @@ export interface FleetDaemonHost {
29
29
  * own LaunchAgents instead.
30
30
  */
31
31
  export declare function fleetBotsManagedByDaemon(host?: FleetDaemonHost): boolean;
32
+ /**
33
+ * Whether a bot handed to hq daemon now would be picked up:
34
+ * - `not-used`: the daemon does not run this Mac's bots; the runtime's own service does.
35
+ * - `running`: a live daemon holds the lock (a hosted daemon included).
36
+ * - `stopped`: the daemon's login item is installed, so bots are handed to it,
37
+ * but no daemon is running to read the request.
38
+ */
39
+ export type FleetBotDaemonState = "not-used" | "running" | "stopped";
40
+ export declare function fleetBotDaemonState(host?: FleetDaemonHost & {
41
+ alive?: (pid: number) => boolean;
42
+ }): FleetBotDaemonState;
43
+ /** The one sentence a person sees when hq daemon is off and could not be started. */
44
+ export declare function fleetDaemonStoppedMessage(name: string): string;
45
+ /** hq daemon is installed here but not running, and starting it did not bring it up. */
46
+ export declare class FleetDaemonStoppedError extends Error {
47
+ readonly expected: true;
48
+ readonly reason: "daemon-stopped";
49
+ constructor(name: string);
50
+ }
51
+ /** `hq daemon start` waits up to 15 s for the daemon itself; this bounds the whole command. */
52
+ export declare const FLEET_DAEMON_START_TIMEOUT_MS = 45000;
53
+ /** How long to look for a live daemon after `hq daemon start` returned. */
54
+ export declare const FLEET_DAEMON_LIVE_WAIT_MS = 20000;
55
+ /** Side effects of {@link ensureFleetBotDaemon}; tests replace them. */
56
+ export declare const fleetDaemonSeams: {
57
+ startDaemon: (timeoutMs: number) => {
58
+ ok: boolean;
59
+ detail: string;
60
+ };
61
+ sleep: (ms: number) => void;
62
+ startTimeoutMs: number;
63
+ liveWaitMs: number;
64
+ pollMs: number;
65
+ };
66
+ export interface EnsureFleetDaemonDeps extends FleetDaemonHost {
67
+ alive?: (pid: number) => boolean;
68
+ log?: (message: string) => void;
69
+ }
70
+ /**
71
+ * Before a bot is handed to hq daemon: make sure a daemon is running to pick
72
+ * it up. When the daemon's login item is installed but no daemon is live
73
+ * (unloaded after a failed update, for one), run `hq daemon start` and wait,
74
+ * bounded, for a live daemon. Throws {@link FleetDaemonStoppedError} when it
75
+ * still is not up, so the caller never reports a hand-off nobody will read.
76
+ */
77
+ export declare function ensureFleetBotDaemon(name: string, deps?: EnsureFleetDaemonDeps): "untouched" | "started";
32
78
  export type LaunchctlRun = (args: string[]) => {
33
79
  status: number | null;
34
80
  };
@@ -22,7 +22,9 @@ import { botsRoot } from "./paths.js";
22
22
  import { isPidAlive } from "./status.js";
23
23
  import { askDaemonToStart, askDaemonToStop, daemonUnitInstalled, hostedDaemonRunning } from "../daemon/handoff.js";
24
24
  import { daemonPaths } from "../daemon/paths.js";
25
- import { isDaemonProcess } from "../daemon/lock.js";
25
+ import { isDaemonProcess, runningDaemonPid } from "../daemon/lock.js";
26
+ import { resolveHqBinary } from "../mesh/live/daemon/install.js";
27
+ import { blockingSleep } from "../service-manager/launchd.js";
26
28
  export const FLEET_BOT_UNIT_PREFIX = "fleet-bots:";
27
29
  export function fleetBotUnitId(name) {
28
30
  return `${FLEET_BOT_UNIT_PREFIX}${name}`;
@@ -42,6 +44,97 @@ export function fleetBotsManagedByDaemon(host = {}) {
42
44
  const paths = host.paths ?? daemonPaths(home);
43
45
  return daemonUnitInstalled({ platform, home, windowsTaskName: "", windowsTaskExists: () => false }) || hostedDaemonRunning(paths);
44
46
  }
47
+ export function fleetBotDaemonState(host = {}) {
48
+ const platform = host.platform ?? process.platform;
49
+ if (platform !== "darwin")
50
+ return "not-used";
51
+ if ((host.env ?? process.env).HQ_FLEET_BOTS_SERVICE?.trim() === "runtime")
52
+ return "not-used";
53
+ const home = host.home ?? os.homedir();
54
+ const paths = host.paths ?? daemonPaths(home);
55
+ if (runningDaemonPid(paths.lockPath, host.alive ?? ((pid) => isDaemonProcess(pid))) !== null)
56
+ return "running";
57
+ return daemonUnitInstalled({ platform, home, windowsTaskName: "", windowsTaskExists: () => false }) ? "stopped" : "not-used";
58
+ }
59
+ /** The one sentence a person sees when hq daemon is off and could not be started. */
60
+ export function fleetDaemonStoppedMessage(name) {
61
+ const who = name.trim() || "the bot";
62
+ return (`HQ's background service (hq daemon) is off on this Mac and could not be turned on, so ${who} can't start. ` +
63
+ "Try again, or run `hq daemon start` and check `hq daemon logs`; restart your Mac if it keeps happening.");
64
+ }
65
+ /** hq daemon is installed here but not running, and starting it did not bring it up. */
66
+ export class FleetDaemonStoppedError extends Error {
67
+ expected = true;
68
+ reason = "daemon-stopped";
69
+ constructor(name) {
70
+ super(fleetDaemonStoppedMessage(name));
71
+ this.name = "FleetDaemonStoppedError";
72
+ }
73
+ }
74
+ /** `hq daemon start` waits up to 15 s for the daemon itself; this bounds the whole command. */
75
+ export const FLEET_DAEMON_START_TIMEOUT_MS = 45_000;
76
+ /** How long to look for a live daemon after `hq daemon start` returned. */
77
+ export const FLEET_DAEMON_LIVE_WAIT_MS = 20_000;
78
+ const FLEET_DAEMON_LIVE_POLL_MS = 500;
79
+ /** Run `hq daemon start` with this CLI, bounded. Never throws. */
80
+ function defaultStartDaemon(timeoutMs) {
81
+ let entry;
82
+ try {
83
+ entry = resolveHqBinary();
84
+ }
85
+ catch (err) {
86
+ return { ok: false, detail: err.message };
87
+ }
88
+ const r = spawnSync(process.execPath, [entry, "daemon", "start"], {
89
+ encoding: "utf8",
90
+ windowsHide: true,
91
+ timeout: timeoutMs,
92
+ stdio: ["ignore", "pipe", "pipe"],
93
+ env: { ...process.env, HQ_NO_UPDATE_CHECK: "1", HQ_NO_ENSURE_HQ_DESKTOP: "1" },
94
+ });
95
+ if (r.error)
96
+ return { ok: false, detail: r.error.message };
97
+ const detail = (r.stderr || r.stdout || "").trim().replace(/\s+/g, " ").slice(0, 400);
98
+ return { ok: r.status === 0, detail: r.status === 0 ? detail : `exit ${r.status ?? r.signal}: ${detail}` };
99
+ }
100
+ /** Side effects of {@link ensureFleetBotDaemon}; tests replace them. */
101
+ export const fleetDaemonSeams = {
102
+ startDaemon: defaultStartDaemon,
103
+ sleep: blockingSleep,
104
+ startTimeoutMs: FLEET_DAEMON_START_TIMEOUT_MS,
105
+ liveWaitMs: FLEET_DAEMON_LIVE_WAIT_MS,
106
+ pollMs: FLEET_DAEMON_LIVE_POLL_MS,
107
+ };
108
+ /**
109
+ * Before a bot is handed to hq daemon: make sure a daemon is running to pick
110
+ * it up. When the daemon's login item is installed but no daemon is live
111
+ * (unloaded after a failed update, for one), run `hq daemon start` and wait,
112
+ * bounded, for a live daemon. Throws {@link FleetDaemonStoppedError} when it
113
+ * still is not up, so the caller never reports a hand-off nobody will read.
114
+ */
115
+ export function ensureFleetBotDaemon(name, deps = {}) {
116
+ const home = deps.home ?? os.homedir();
117
+ const paths = deps.paths ?? daemonPaths(home);
118
+ const alive = deps.alive ?? ((pid) => isDaemonProcess(pid));
119
+ const host = { platform: deps.platform, home, paths, env: deps.env, alive };
120
+ if (fleetBotDaemonState(host) !== "stopped")
121
+ return "untouched";
122
+ deps.log?.("hq daemon runs this Mac's bots but is not running; starting it (hq daemon start)");
123
+ const started = fleetDaemonSeams.startDaemon(fleetDaemonSeams.startTimeoutMs);
124
+ if (!started.ok)
125
+ deps.log?.(`hq daemon start failed: ${started.detail}`);
126
+ for (let waited = 0;; waited += fleetDaemonSeams.pollMs) {
127
+ if (runningDaemonPid(paths.lockPath, alive) !== null) {
128
+ deps.log?.("hq daemon is running again");
129
+ return "started";
130
+ }
131
+ if (waited >= fleetDaemonSeams.liveWaitMs)
132
+ break;
133
+ fleetDaemonSeams.sleep(fleetDaemonSeams.pollMs);
134
+ }
135
+ deps.log?.(`hq daemon did not come up within ${Math.round(fleetDaemonSeams.liveWaitMs / 1000)}s; not handing ${name || "the bot"} to it`);
136
+ throw new FleetDaemonStoppedError(name);
137
+ }
45
138
  function defaultLaunchctl(args) {
46
139
  return spawnSync("launchctl", args, { encoding: "utf8", windowsHide: true, timeout: 15_000 });
47
140
  }
@@ -196,6 +289,11 @@ export function controlFleetBot(agentUid, action, deps = {}) {
196
289
  return controlFleetLocalBot(agentUid, action, deps);
197
290
  const unit = fleetBotUnitId(bot.name);
198
291
  const agent = { home, uid: deps.uid, launchctl: deps.launchctl };
292
+ // A start request a stopped daemon never reads leaves the bot offline while
293
+ // this reports success. Bring the daemon up first, or fail before changing anything.
294
+ if (action === "install" || action === "start" || action === "restart") {
295
+ ensureFleetBotDaemon(bot.name, { platform, home, paths, env: deps.env, ...(deps.alive ? { alive: deps.alive } : {}) });
296
+ }
199
297
  switch (action) {
200
298
  case "install":
201
299
  case "start": {
@@ -112,6 +112,15 @@ export interface InflightTurn {
112
112
  silenceable?: boolean;
113
113
  }
114
114
  export declare function botInflightPath(dir: string): string;
115
+ /**
116
+ * Whether a bot is answering right now. A legacy runner records each turn in
117
+ * its in-flight marker; an HQ Fleet gateway only reports how many turns it is
118
+ * running (`active_agents`), so its start time is unknown.
119
+ */
120
+ export declare function botBusyState(processAlive: boolean, turns: readonly InflightTurn[], fleetActiveTurns?: number): {
121
+ busy: boolean;
122
+ busySince: string | null;
123
+ };
115
124
  /** Every turn that was in progress, oldest first. */
116
125
  export declare function readInflightTurns(dir: string, options?: {
117
126
  strictIo?: boolean;
@@ -23,6 +23,16 @@ function isTurn(raw) {
23
23
  const t = raw;
24
24
  return t?.v === 1 && typeof t.messageId === "string" && Boolean(t.target);
25
25
  }
26
+ /**
27
+ * Whether a bot is answering right now. A legacy runner records each turn in
28
+ * its in-flight marker; an HQ Fleet gateway only reports how many turns it is
29
+ * running (`active_agents`), so its start time is unknown.
30
+ */
31
+ export function botBusyState(processAlive, turns, fleetActiveTurns = 0) {
32
+ if (!processAlive)
33
+ return { busy: false, busySince: null };
34
+ return { busy: turns.length > 0 || fleetActiveTurns > 0, busySince: turns[0]?.startedAt ?? null };
35
+ }
26
36
  /** Every turn that was in progress, oldest first. */
27
37
  export function readInflightTurns(dir, options = {}) {
28
38
  try {
@@ -38,7 +38,7 @@ import * as fs from "node:fs";
38
38
  import * as path from "node:path";
39
39
  import { signalsAlertKey } from "../../hot-channels/alert.js";
40
40
  import { JOB_RUN_OPTIONS_CONTEXT_KEY } from "../job-run.js";
41
- import { localDate, runRecordRel } from "../../signals/engine.js";
41
+ import { localDate, raiseStoppedRunAlert, runRecordRel } from "../../signals/engine.js";
42
42
  import { formatJobErrorReply, formatLockedReply, formatRunReply, timeInWords } from "../../signals/reply.js";
43
43
  import { effectiveBotCompanies, effectiveBotKind, readBotConfig } from "../config.js";
44
44
  import { ensureLocalJob, readLocalJobs, removeLocalJobsWhere, withJobsLock } from "../local-jobs.js";
@@ -377,6 +377,17 @@ async function runSignalsEngineJob(input) {
377
377
  return { ok: false, text: reply.text, report: null, reply };
378
378
  }
379
379
  const timeZone = input.timeZone ?? "UTC";
380
+ // US-018 AC1: a run that hung or died left today's record `running` (or
381
+ // `failed` with no alert sent), and the end-of-run alert never fired for it.
382
+ // Check it before this run replaces the record; one alert per stopped run.
383
+ // Yesterday's record is checked too: a hung morning run usually has no
384
+ // later fire that day, so the next morning's fire is the first to see it.
385
+ if (input.sendAlert) {
386
+ const senders = { sendOwnerDm: input.sendAlert, ...(input.log ? { log: input.log } : {}) };
387
+ for (const daysAgo of [1, 0]) {
388
+ await raiseStoppedRunAlert({ hqRoot: input.hqRoot, company: input.company, now: input.now, senders, daysAgo });
389
+ }
390
+ }
380
391
  if (input.retry) {
381
392
  const today = readTodaysRecord(input.hqRoot, input.company, input.now());
382
393
  if (today && (today.status === "complete" || today.status === "partial")) {