@indigoai-us/hq-cli 5.345.208 → 5.345.210

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 (126) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/assets/scaffold/core/scripts/derive-trigger-facts.sh +22 -3
  3. package/dist/command-catalog.generated.d.ts +33 -8
  4. package/dist/command-catalog.generated.js +40 -8
  5. package/dist/command-registration-plan.d.ts +2 -2
  6. package/dist/command-registration-plan.js +1 -1
  7. package/dist/commands/access.js +11 -5
  8. package/dist/commands/agents.d.ts +8 -0
  9. package/dist/commands/agents.js +5 -0
  10. package/dist/commands/bot.d.ts +8 -0
  11. package/dist/commands/bot.js +67 -7
  12. package/dist/commands/channels.js +4 -0
  13. package/dist/commands/cloud.d.ts +83 -2
  14. package/dist/commands/cloud.js +161 -31
  15. package/dist/commands/company.d.ts +9 -0
  16. package/dist/commands/company.js +44 -14
  17. package/dist/commands/core-checkpoint-native.js +21 -0
  18. package/dist/commands/core-derive-trigger-facts-native.js +14 -3
  19. package/dist/commands/core-generate-workers-registry-fast.d.ts +1 -1
  20. package/dist/commands/core-generate-workers-registry-fast.js +7 -1
  21. package/dist/commands/core-job-run-native.d.ts +8 -0
  22. package/dist/commands/core-job-run-native.js +11 -3
  23. package/dist/commands/core-jobs-native.js +1 -1
  24. package/dist/commands/core-register-project-native.js +31 -1
  25. package/dist/commands/core-scan-packages-fast.d.ts +1 -1
  26. package/dist/commands/core-scan-packages-fast.js +8 -1
  27. package/dist/commands/core.js +12 -3
  28. package/dist/commands/dm-attach.d.ts +10 -0
  29. package/dist/commands/dm-attach.js +33 -5
  30. package/dist/commands/integrations-connect.js +47 -2
  31. package/dist/commands/lanes-session-start.d.ts +17 -0
  32. package/dist/commands/lanes-session-start.js +281 -13
  33. package/dist/commands/lanes-watch.js +11 -3
  34. package/dist/commands/lanes.d.ts +4 -0
  35. package/dist/commands/lanes.js +95 -22
  36. package/dist/commands/library.d.ts +10 -0
  37. package/dist/commands/library.js +30 -3
  38. package/dist/commands/meetings.d.ts +42 -0
  39. package/dist/commands/meetings.js +157 -12
  40. package/dist/commands/mesh.js +3 -0
  41. package/dist/commands/monitor.d.ts +6 -0
  42. package/dist/commands/monitor.js +29 -19
  43. package/dist/commands/onboard.js +8 -1
  44. package/dist/commands/sources.js +7 -3
  45. package/dist/index.js +9 -0
  46. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  47. package/dist/lanes-monitor-check-argv.js +2 -2
  48. package/dist/lanes-session-start-argv.d.ts +4 -1
  49. package/dist/lanes-session-start-argv.js +5 -2
  50. package/dist/lib/bot/fleet-daemon.d.ts +101 -0
  51. package/dist/lib/bot/fleet-daemon.js +227 -0
  52. package/dist/lib/bot/fleet-local.d.ts +26 -0
  53. package/dist/lib/bot/fleet-local.js +51 -2
  54. package/dist/lib/bot/index.d.ts +1 -0
  55. package/dist/lib/bot/index.js +1 -0
  56. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +4 -0
  57. package/dist/lib/bot/jobs/hot-signal-sync.js +8 -1
  58. package/dist/lib/bot/log.js +3 -1
  59. package/dist/lib/bot/probe.js +2 -0
  60. package/dist/lib/bot/run.js +28 -3
  61. package/dist/lib/bot/runtime-failure.d.ts +4 -2
  62. package/dist/lib/bot/runtime-failure.js +9 -1
  63. package/dist/lib/bot/status.d.ts +17 -0
  64. package/dist/lib/bot/status.js +53 -2
  65. package/dist/lib/capacity/collectors/claude-oauth.d.ts +5 -5
  66. package/dist/lib/capacity/collectors/claude-oauth.js +6 -6
  67. package/dist/lib/core-utils/native-scaffold-help.d.ts +16 -0
  68. package/dist/lib/core-utils/native-scaffold-help.js +26 -0
  69. package/dist/lib/core-utils/session-company.d.ts +25 -8
  70. package/dist/lib/core-utils/session-company.js +59 -17
  71. package/dist/lib/daemon/catalog.d.ts +25 -1
  72. package/dist/lib/daemon/catalog.js +29 -2
  73. package/dist/lib/daemon/run.d.ts +0 -1
  74. package/dist/lib/daemon/run.js +3 -11
  75. package/dist/lib/daemon/server.js +26 -7
  76. package/dist/lib/daemon/supervisor.js +1 -1
  77. package/dist/lib/daemon/tools.js +17 -1
  78. package/dist/lib/db/sqlite-binding.js +2 -1
  79. package/dist/lib/doctor/checks/bots.d.ts +2 -0
  80. package/dist/lib/doctor/checks/bots.js +11 -0
  81. package/dist/lib/doctor/checks/runtime-health.js +3 -2
  82. package/dist/lib/doctor/checks/work-context.js +5 -2
  83. package/dist/lib/hook-engine/resolve.d.ts +1 -1
  84. package/dist/lib/hook-engine/resolve.js +4 -1
  85. package/dist/lib/hot-channels/adapters/meeting-providers.d.ts +2 -0
  86. package/dist/lib/hot-channels/adapters/meeting-providers.js +13 -2
  87. package/dist/lib/lanes/index.d.ts +1 -1
  88. package/dist/lib/lanes/index.js +1 -1
  89. package/dist/lib/lanes/monitor.d.ts +14 -0
  90. package/dist/lib/lanes/monitor.js +51 -10
  91. package/dist/lib/lanes/outpost-dispatch.d.ts +3 -0
  92. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  93. package/dist/lib/lanes/store.d.ts +1 -1
  94. package/dist/lib/lanes/store.js +2 -1
  95. package/dist/lib/mesh/client.js +7 -1
  96. package/dist/lib/mesh/live/backfill-held.d.ts +3 -0
  97. package/dist/lib/mesh/live/backfill-held.js +167 -7
  98. package/dist/lib/mesh/live/flush.d.ts +7 -0
  99. package/dist/lib/mesh/live/flush.js +10 -1
  100. package/dist/lib/monitor.d.ts +9 -0
  101. package/dist/lib/monitor.js +33 -7
  102. package/dist/lib/onboarding/orchestrator.js +269 -132
  103. package/dist/lib/onboarding/types.d.ts +2 -0
  104. package/dist/lib/scaffold-cli-floor.js +2 -1
  105. package/dist/lib/signals/failure-alert.js +3 -1
  106. package/dist/lib/work-context/organize.d.ts +6 -0
  107. package/dist/lib/work-context/organize.js +28 -0
  108. package/dist/lib/work-context/paths.d.ts +9 -0
  109. package/dist/lib/work-context/paths.js +15 -0
  110. package/dist/lib/work-context/prd-sync.js +2 -1
  111. package/dist/runners-alias.d.ts +54 -0
  112. package/dist/runners-alias.js +86 -0
  113. package/dist/utils/install-tree-torn.js +5 -3
  114. package/dist/utils/npm-install-flags.d.ts +27 -0
  115. package/dist/utils/npm-install-flags.js +68 -0
  116. package/dist/utils/package-use-lease.js +1 -1
  117. package/dist/utils/qmd-native-binding-error.js +2 -1
  118. package/dist/utils/self-update.js +2 -1
  119. package/dist/utils/staged-install.js +2 -1
  120. package/dist/utils/staged-npm-install.js +2 -1
  121. package/dist/utils/upload-author.d.ts +2 -1
  122. package/dist/utils/upload-author.js +9 -5
  123. package/dist/utils/version-check.js +2 -1
  124. package/dist/utils/version-gate.js +7 -6
  125. package/package.json +7 -7
  126. package/scripts/install-hook-engine.mjs +7 -3
@@ -2,8 +2,11 @@
2
2
  * Dependency-free argv matcher for the `hq lanes session-start` fast route.
3
3
  * Imported statically by src/index.ts, so it must not import anything.
4
4
  */
5
- /** Exactly `hq lanes session-start` with no options (the SessionStart hook form). */
5
+ /**
6
+ * Exactly `hq runners session-start` or the deprecated `hq lanes session-start`
7
+ * alias, with no options (the SessionStart hook form).
8
+ */
6
9
  export function isLaneSessionStartFastRequest(argv) {
7
- return argv.length === 4 && argv[2] === "lanes" && argv[3] === "session-start";
10
+ return argv.length === 4 && (argv[2] === "runners" || argv[2] === "lanes") && argv[3] === "session-start";
8
11
  }
9
12
  //# sourceMappingURL=lanes-session-start-argv.js.map
@@ -0,0 +1,101 @@
1
+ /**
2
+ * HQ Fleet bots under `hq daemon` on macOS.
3
+ *
4
+ * The HQ Fleet Runtime registers each bot's gateway as its own LaunchAgent
5
+ * whose program is the runtime's `python`. macOS reports every such login
6
+ * item as a new background item from an unknown developer. On a Mac that runs
7
+ * `hq daemon` (one login item, registered through the HQ app), the daemon runs
8
+ * the gateways itself as `fleet-bots:<name>` units instead, and any LaunchAgent
9
+ * the runtime left behind is unloaded and deleted.
10
+ *
11
+ * Other platforms, and a Mac without `hq daemon`, keep the runtime's own
12
+ * service path.
13
+ */
14
+ import { type BotConfig } from "./config.js";
15
+ import { type FleetLocalControlDeps, type FleetLocalServiceAction } from "./fleet-local.js";
16
+ import type { FleetBotPlan } from "../daemon/catalog.js";
17
+ import { type DaemonPaths } from "../daemon/paths.js";
18
+ export declare const FLEET_BOT_UNIT_PREFIX = "fleet-bots:";
19
+ export declare function fleetBotUnitId(name: string): string;
20
+ export interface FleetDaemonHost {
21
+ platform?: NodeJS.Platform;
22
+ home?: string;
23
+ paths?: DaemonPaths;
24
+ env?: NodeJS.ProcessEnv;
25
+ }
26
+ /**
27
+ * `hq daemon` runs this Mac's HQ Fleet bots: it is installed here, or the
28
+ * desktop app hosts it. `HQ_FLEET_BOTS_SERVICE=runtime` keeps the runtime's
29
+ * own LaunchAgents instead.
30
+ */
31
+ export declare function fleetBotsManagedByDaemon(host?: FleetDaemonHost): boolean;
32
+ export type LaunchctlRun = (args: string[]) => {
33
+ status: number | null;
34
+ };
35
+ export interface RemoveLaunchAgentDeps {
36
+ home?: string;
37
+ uid?: number;
38
+ launchctl?: LaunchctlRun;
39
+ }
40
+ /**
41
+ * Unload and delete the LaunchAgent the runtime registered for this bot, so the
42
+ * daemon's copy is the only one. True when a plist was there and is gone now;
43
+ * a plist that cannot be deleted stays, and the caller sees it still there.
44
+ */
45
+ export declare function removeFleetBotLaunchAgent(agentUid: string, deps?: RemoveLaunchAgentDeps): boolean;
46
+ export interface FleetBot {
47
+ name: string;
48
+ dir: string;
49
+ config: BotConfig;
50
+ }
51
+ export declare function listFleetBots(root?: string): FleetBot[];
52
+ export declare function findFleetBotByAgent(agentUid: string, root?: string): FleetBot | null;
53
+ export interface PlanFleetBotsDeps extends RemoveLaunchAgentDeps {
54
+ platform?: NodeJS.Platform;
55
+ root?: string;
56
+ fleetHome?: string;
57
+ env?: NodeJS.ProcessEnv;
58
+ log?: (message: string) => void;
59
+ /** The daemon's own pid: a gateway under it is left alone. */
60
+ daemonPid?: number;
61
+ /** `ps -o ppid=,command= -p <pid>` (tests). */
62
+ ps?: (pid: number) => {
63
+ ppid: number;
64
+ command: string;
65
+ } | null;
66
+ kill?: (pid: number, signal: NodeJS.Signals) => void;
67
+ }
68
+ /**
69
+ * The pid of this bot's gateway when it runs outside the daemon (the runtime's
70
+ * LaunchAgent, a detached fallback, or a manual `gateway run`); null when there
71
+ * is none, or when the running one descends from the daemon.
72
+ */
73
+ export declare function gatewayOutsideDaemon(agentUid: string, deps: {
74
+ fleetHome?: string;
75
+ daemonPid: number;
76
+ ps?: (pid: number) => {
77
+ ppid: number;
78
+ command: string;
79
+ } | null;
80
+ }): number | null;
81
+ /**
82
+ * The daemon's view of every HQ Fleet bot on this machine. On macOS this also
83
+ * retires each bot's own LaunchAgent, so the daemon can start the gateway
84
+ * without a second copy racing it; a plist that survives the attempt keeps the
85
+ * unit waiting.
86
+ */
87
+ export declare function planFleetBots(deps?: PlanFleetBotsDeps): FleetBotPlan[];
88
+ export interface ControlFleetBotDeps extends FleetLocalControlDeps, FleetDaemonHost {
89
+ root?: string;
90
+ uid?: number;
91
+ launchctl?: LaunchctlRun;
92
+ alive?: (pid: number) => boolean;
93
+ }
94
+ /**
95
+ * `controlFleetLocalBot` for a bot the daemon runs: the runtime's service
96
+ * commands become daemon requests, and `install`/`start` also retire the
97
+ * bot's own LaunchAgent. Elsewhere the runtime's own service path runs as
98
+ * before.
99
+ */
100
+ export declare function controlFleetBot(agentUid: string, action: FleetLocalServiceAction, deps?: ControlFleetBotDeps): Record<string, unknown>;
101
+ //# sourceMappingURL=fleet-daemon.d.ts.map
@@ -0,0 +1,227 @@
1
+ /**
2
+ * HQ Fleet bots under `hq daemon` on macOS.
3
+ *
4
+ * The HQ Fleet Runtime registers each bot's gateway as its own LaunchAgent
5
+ * whose program is the runtime's `python`. macOS reports every such login
6
+ * item as a new background item from an unknown developer. On a Mac that runs
7
+ * `hq daemon` (one login item, registered through the HQ app), the daemon runs
8
+ * the gateways itself as `fleet-bots:<name>` units instead, and any LaunchAgent
9
+ * the runtime left behind is unloaded and deleted.
10
+ *
11
+ * Other platforms, and a Mac without `hq daemon`, keep the runtime's own
12
+ * service path.
13
+ */
14
+ import { spawnSync } from "node:child_process";
15
+ import * as fs from "node:fs";
16
+ import * as os from "node:os";
17
+ import * as path from "node:path";
18
+ import { HQ_FLEET_RUNTIME_ENGINE_ID, patchBotConfig, readBotConfig } from "./config.js";
19
+ import { defaultPathEntries } from "./daemon.js";
20
+ import { controlFleetLocalBot, fleetLocalGatewayPid, fleetLocalGatewayProcess, fleetLocalLaunchAgentLabel, fleetLocalLaunchAgentPlist, removeFleetLocalEmbeddedRuntime, } from "./fleet-local.js";
21
+ import { botsRoot } from "./paths.js";
22
+ import { isPidAlive } from "./status.js";
23
+ import { askDaemonToStart, askDaemonToStop, daemonUnitInstalled, hostedDaemonRunning } from "../daemon/handoff.js";
24
+ import { daemonPaths } from "../daemon/paths.js";
25
+ import { isDaemonProcess } from "../daemon/lock.js";
26
+ export const FLEET_BOT_UNIT_PREFIX = "fleet-bots:";
27
+ export function fleetBotUnitId(name) {
28
+ return `${FLEET_BOT_UNIT_PREFIX}${name}`;
29
+ }
30
+ /**
31
+ * `hq daemon` runs this Mac's HQ Fleet bots: it is installed here, or the
32
+ * desktop app hosts it. `HQ_FLEET_BOTS_SERVICE=runtime` keeps the runtime's
33
+ * own LaunchAgents instead.
34
+ */
35
+ export function fleetBotsManagedByDaemon(host = {}) {
36
+ const platform = host.platform ?? process.platform;
37
+ if (platform !== "darwin")
38
+ return false;
39
+ if ((host.env ?? process.env).HQ_FLEET_BOTS_SERVICE?.trim() === "runtime")
40
+ return false;
41
+ const home = host.home ?? os.homedir();
42
+ const paths = host.paths ?? daemonPaths(home);
43
+ return daemonUnitInstalled({ platform, home, windowsTaskName: "", windowsTaskExists: () => false }) || hostedDaemonRunning(paths);
44
+ }
45
+ function defaultLaunchctl(args) {
46
+ return spawnSync("launchctl", args, { encoding: "utf8", windowsHide: true, timeout: 15_000 });
47
+ }
48
+ /**
49
+ * Unload and delete the LaunchAgent the runtime registered for this bot, so the
50
+ * daemon's copy is the only one. True when a plist was there and is gone now;
51
+ * a plist that cannot be deleted stays, and the caller sees it still there.
52
+ */
53
+ export function removeFleetBotLaunchAgent(agentUid, deps = {}) {
54
+ const home = deps.home ?? os.homedir();
55
+ const plist = fleetLocalLaunchAgentPlist(agentUid, home);
56
+ if (!fs.existsSync(plist))
57
+ return false;
58
+ const uid = deps.uid ?? process.getuid?.() ?? 0;
59
+ (deps.launchctl ?? defaultLaunchctl)(["bootout", `gui/${uid}/${fleetLocalLaunchAgentLabel(agentUid)}`]);
60
+ try {
61
+ fs.rmSync(plist, { force: true });
62
+ }
63
+ catch {
64
+ return false;
65
+ }
66
+ return true;
67
+ }
68
+ export function listFleetBots(root = botsRoot()) {
69
+ if (!fs.existsSync(root))
70
+ return [];
71
+ return fs
72
+ .readdirSync(root, { withFileTypes: true })
73
+ .filter((d) => d.isDirectory())
74
+ .map((d) => ({ name: d.name, dir: path.join(root, d.name), config: readBotConfig(path.join(root, d.name)) }))
75
+ .filter((b) => b.config !== null && b.config.engine?.id === HQ_FLEET_RUNTIME_ENGINE_ID)
76
+ .sort((a, b) => a.name.localeCompare(b.name));
77
+ }
78
+ export function findFleetBotByAgent(agentUid, root = botsRoot()) {
79
+ return listFleetBots(root).find((b) => b.config.agentUid === agentUid) ?? null;
80
+ }
81
+ function defaultPs(pid) {
82
+ const result = spawnSync("ps", ["-o", "ppid=,command=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000 });
83
+ const line = result.stdout?.trim();
84
+ if (result.status !== 0 || !line)
85
+ return null;
86
+ const match = /^(\d+)\s+(.*)$/.exec(line);
87
+ return match ? { ppid: Number(match[1]), command: match[2] } : null;
88
+ }
89
+ /**
90
+ * The pid of this bot's gateway when it runs outside the daemon (the runtime's
91
+ * LaunchAgent, a detached fallback, or a manual `gateway run`); null when there
92
+ * is none, or when the running one descends from the daemon.
93
+ */
94
+ export function gatewayOutsideDaemon(agentUid, deps) {
95
+ const pid = fleetLocalGatewayPid(agentUid, deps);
96
+ if (pid === null || !isPidAlive(pid))
97
+ return null;
98
+ const ps = deps.ps ?? defaultPs;
99
+ const own = ps(pid);
100
+ // The pid file may name a pid the OS reused for something else.
101
+ if (!own || !/hq_fleet_cli|hq-fleet/.test(own.command))
102
+ return null;
103
+ let current = own.ppid;
104
+ for (let hops = 0; hops < 6 && current > 1; hops += 1) {
105
+ if (current === deps.daemonPid)
106
+ return null;
107
+ current = ps(current)?.ppid ?? 0;
108
+ }
109
+ return pid;
110
+ }
111
+ /**
112
+ * The daemon's view of every HQ Fleet bot on this machine. On macOS this also
113
+ * retires each bot's own LaunchAgent, so the daemon can start the gateway
114
+ * without a second copy racing it; a plist that survives the attempt keeps the
115
+ * unit waiting.
116
+ */
117
+ export function planFleetBots(deps = {}) {
118
+ const platform = deps.platform ?? process.platform;
119
+ const home = deps.home ?? os.homedir();
120
+ const env = deps.env ?? process.env;
121
+ return listFleetBots(deps.root ?? botsRoot(home, env)).map(({ name, config }) => {
122
+ let legacyAgent;
123
+ let outsideGateway;
124
+ if (platform === "darwin") {
125
+ if (removeFleetBotLaunchAgent(config.agentUid, { home, uid: deps.uid, launchctl: deps.launchctl })) {
126
+ deps.log?.(`retired the HQ Fleet LaunchAgent for ${name}; hq daemon runs its gateway now`);
127
+ }
128
+ if (fs.existsSync(fleetLocalLaunchAgentPlist(config.agentUid, home)))
129
+ legacyAgent = fleetLocalLaunchAgentLabel(config.agentUid);
130
+ // A gateway the LaunchAgent (or a detached fallback) left running holds
131
+ // the profile, and the runtime refuses to start a second one. Ask it to
132
+ // exit; the unit waits until it has.
133
+ const outside = gatewayOutsideDaemon(config.agentUid, { fleetHome: deps.fleetHome, daemonPid: deps.daemonPid ?? process.pid, ps: deps.ps });
134
+ if (outside !== null) {
135
+ outsideGateway = outside;
136
+ try {
137
+ (deps.kill ?? ((pid, signal) => process.kill(pid, signal)))(outside, "SIGTERM");
138
+ deps.log?.(`asked the gateway for ${name} started outside hq daemon (pid ${outside}) to exit`);
139
+ }
140
+ catch {
141
+ /* already gone */
142
+ }
143
+ }
144
+ }
145
+ const gateway = fleetLocalGatewayProcess(config.agentUid, {
146
+ fleetHome: deps.fleetHome,
147
+ platform,
148
+ pathEntries: defaultPathEntries(home),
149
+ basePath: env.PATH ?? "",
150
+ });
151
+ return {
152
+ name,
153
+ gateway,
154
+ authPending: config.fleetAuthPending === true,
155
+ installPending: config.fleetServiceInstallPending === true,
156
+ ...(legacyAgent ? { legacyAgent } : {}),
157
+ ...(outsideGateway !== undefined ? { outsideGateway } : {}),
158
+ };
159
+ });
160
+ }
161
+ function unitState(paths, unitId, alive) {
162
+ try {
163
+ const state = JSON.parse(fs.readFileSync(paths.statePath, "utf8"));
164
+ if (!alive(state.pid))
165
+ return null;
166
+ const unit = state.units.find((u) => u.id === unitId);
167
+ return unit ? { status: unit.status, ...(unit.reason ? { reason: unit.reason } : {}), ...(unit.pid !== undefined ? { pid: unit.pid } : {}) } : null;
168
+ }
169
+ catch {
170
+ return null;
171
+ }
172
+ }
173
+ /**
174
+ * `controlFleetLocalBot` for a bot the daemon runs: the runtime's service
175
+ * commands become daemon requests, and `install`/`start` also retire the
176
+ * bot's own LaunchAgent. Elsewhere the runtime's own service path runs as
177
+ * before.
178
+ */
179
+ export function controlFleetBot(agentUid, action, deps = {}) {
180
+ const platform = deps.platform ?? process.platform;
181
+ const home = deps.home ?? os.homedir();
182
+ const paths = deps.paths ?? daemonPaths(home);
183
+ const bot = fleetBotsManagedByDaemon({ platform, home, paths, env: deps.env }) ? findFleetBotByAgent(agentUid, deps.root) : null;
184
+ if (!bot)
185
+ return controlFleetLocalBot(agentUid, action, deps);
186
+ const unit = fleetBotUnitId(bot.name);
187
+ const agent = { home, uid: deps.uid, launchctl: deps.launchctl };
188
+ switch (action) {
189
+ case "install":
190
+ case "start": {
191
+ removeFleetBotLaunchAgent(agentUid, agent);
192
+ if (action === "install")
193
+ removeFleetLocalEmbeddedRuntime(agentUid, deps);
194
+ patchBotConfig(bot.dir, { fleetServiceInstallPending: false, enabled: true });
195
+ askDaemonToStart(paths, unit);
196
+ return { ok: true, unit, summary: `${action === "install" ? "installed under" : "started by"} hq daemon (${unit})` };
197
+ }
198
+ case "restart":
199
+ removeFleetBotLaunchAgent(agentUid, agent);
200
+ askDaemonToStart(paths, unit);
201
+ return { ok: true, unit, summary: `restarted by hq daemon (${unit})` };
202
+ case "stop":
203
+ removeFleetBotLaunchAgent(agentUid, agent);
204
+ askDaemonToStop(paths, unit);
205
+ return { ok: true, unit, summary: `stopped by hq daemon (${unit})` };
206
+ case "status": {
207
+ const alive = deps.alive ?? ((pid) => isDaemonProcess(pid));
208
+ const state = unitState(paths, unit, alive);
209
+ const pid = fleetLocalGatewayPid(agentUid, deps);
210
+ const running = pid !== null && isPidAlive(pid);
211
+ return {
212
+ ok: true,
213
+ unit,
214
+ running,
215
+ pid: running ? pid : null,
216
+ state: state?.status ?? "unknown",
217
+ ...(state?.reason ? { reason: state.reason } : {}),
218
+ summary: running ? `running under hq daemon (pid ${pid})` : `not running (${state?.reason ?? state?.status ?? "hq daemon is not running"})`,
219
+ };
220
+ }
221
+ case "remove":
222
+ removeFleetBotLaunchAgent(agentUid, agent);
223
+ askDaemonToStop(paths, unit);
224
+ return controlFleetLocalBot(agentUid, action, deps);
225
+ }
226
+ }
227
+ //# sourceMappingURL=fleet-daemon.js.map
@@ -302,6 +302,32 @@ export declare function fleetLocalServiceInstalled(agentUid: string, deps?: {
302
302
  platform?: NodeJS.Platform;
303
303
  home?: string;
304
304
  }): boolean | null;
305
+ /** The launchd label the HQ Fleet Runtime registers a bot's own gateway under. */
306
+ export declare function fleetLocalLaunchAgentLabel(agentUid: string): string;
307
+ export declare function fleetLocalLaunchAgentPlist(agentUid: string, home?: string): string;
308
+ export interface FleetLocalGatewayProcess {
309
+ file: string;
310
+ args: string[];
311
+ env: Record<string, string>;
312
+ cwd: string;
313
+ }
314
+ /**
315
+ * The bot's gateway as a process for an outside supervisor: the command,
316
+ * environment and working directory the runtime writes into its own
317
+ * LaunchAgent, with `--external-supervisor` so the runtime hands restarts back
318
+ * to the supervisor instead of relaunching itself. The gateway is the direct
319
+ * child (the LaunchAgent's stderr-timestamp wrapper is left out), so the
320
+ * supervisor's signals reach it and a forced stop cannot orphan it. Null when
321
+ * the profile or its runtime is not fully installed.
322
+ */
323
+ export declare function fleetLocalGatewayProcess(agentUid: string, deps?: {
324
+ fleetHome?: string;
325
+ platform?: NodeJS.Platform;
326
+ pathEntries?: readonly string[];
327
+ basePath?: string;
328
+ }): FleetLocalGatewayProcess | null;
329
+ /** After a service install: drop the profile's own copy of the runtime once the shared one runs it. */
330
+ export declare function removeFleetLocalEmbeddedRuntime(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome" | "platform">): void;
305
331
  export declare function fleetLocalProfileNeedsAdoption(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome" | "platform"> & {
306
332
  release?: FleetLocalReleasePin;
307
333
  }): boolean;
@@ -12,6 +12,7 @@ import semver from "semver";
12
12
  import { CLI_VERSION } from "../../cli-version.js";
13
13
  import { ensureCognitoToken } from "../../utils/cognito-session.js";
14
14
  import { vaultApiFetch } from "../../utils/vault-api.js";
15
+ import { HQ_CLI_NPM_UPDATE_COMMAND } from "../../utils/npm-install-flags.js";
15
16
  /** The model the HQ Fleet Runtime asks for when a Claude bot names none. */
16
17
  export const FLEET_CLAUDE_DEFAULT_MODEL = "claude-opus-5-5";
17
18
  /**
@@ -367,7 +368,7 @@ export function fleetLocalCliCompatibilityWarning(manifest, release = HQ_FLEET_L
367
368
  if (!required || !current || semver.gte(current, required))
368
369
  return null;
369
370
  return `HQ Fleet Local ${release.version} asks for hq CLI ${minimum} or newer; this is ${cliVersion}. ` +
370
- "Update with `npm install -g @indigoai-us/hq-cli` if the bot misbehaves.";
371
+ `Update with \`${HQ_CLI_NPM_UPDATE_COMMAND}\` if the bot misbehaves.`;
371
372
  }
372
373
  /** `gh auth token` fallback for the release download token. */
373
374
  export const FLEET_RELEASE_TOKEN_TIMEOUT_MS = 15_000;
@@ -1049,7 +1050,55 @@ export function fleetLocalServiceInstalled(agentUid, deps = {}) {
1049
1050
  if (platform !== "darwin")
1050
1051
  return null;
1051
1052
  const home = deps.home ?? os.homedir();
1052
- return fs.existsSync(path.join(home, "Library", "LaunchAgents", `ai.hq-fleet.gateway-${profileName(agentUid)}.plist`));
1053
+ return fs.existsSync(fleetLocalLaunchAgentPlist(agentUid, home));
1054
+ }
1055
+ /** The launchd label the HQ Fleet Runtime registers a bot's own gateway under. */
1056
+ export function fleetLocalLaunchAgentLabel(agentUid) {
1057
+ return `ai.hq-fleet.gateway-${profileName(agentUid)}`;
1058
+ }
1059
+ export function fleetLocalLaunchAgentPlist(agentUid, home = os.homedir()) {
1060
+ return path.join(home, "Library", "LaunchAgents", `${fleetLocalLaunchAgentLabel(agentUid)}.plist`);
1061
+ }
1062
+ /**
1063
+ * The bot's gateway as a process for an outside supervisor: the command,
1064
+ * environment and working directory the runtime writes into its own
1065
+ * LaunchAgent, with `--external-supervisor` so the runtime hands restarts back
1066
+ * to the supervisor instead of relaunching itself. The gateway is the direct
1067
+ * child (the LaunchAgent's stderr-timestamp wrapper is left out), so the
1068
+ * supervisor's signals reach it and a forced stop cannot orphan it. Null when
1069
+ * the profile or its runtime is not fully installed.
1070
+ */
1071
+ export function fleetLocalGatewayProcess(agentUid, deps = {}) {
1072
+ if (!/^agt_[A-Za-z0-9_-]+$/.test(agentUid))
1073
+ return null;
1074
+ const root = deps.fleetHome ?? fleetHome();
1075
+ const platform = deps.platform ?? process.platform;
1076
+ const profileDir = profileRoot(agentUid, root);
1077
+ const shared = sharedRuntimeFromMarker(profileDir, root, platform);
1078
+ const runtimeDir = shared?.runtimeDir ?? path.join(profileDir, "runtime");
1079
+ const python = venvExecutable(runtimeDir, "python", platform);
1080
+ if (![python, path.join(profileDir, "profile.json")].every((item) => fs.existsSync(item)))
1081
+ return null;
1082
+ const bin = path.dirname(python);
1083
+ const pathParts = [bin, ...(deps.pathEntries ?? []), ...(deps.basePath ?? "").split(path.delimiter)].filter(Boolean);
1084
+ return {
1085
+ file: python,
1086
+ args: ["-m", "hq_fleet_cli.main", "--profile", profileName(agentUid), "gateway", "run", "--external-supervisor"],
1087
+ env: {
1088
+ PATH: [...new Set(pathParts)].join(path.delimiter),
1089
+ VIRTUAL_ENV: runtimeDir,
1090
+ HQ_FLEET_HOME: profileDir,
1091
+ HQ_FLEET_SUPERVISED_CHILD: "1",
1092
+ },
1093
+ cwd: profileDir,
1094
+ };
1095
+ }
1096
+ /** After a service install: drop the profile's own copy of the runtime once the shared one runs it. */
1097
+ export function removeFleetLocalEmbeddedRuntime(agentUid, deps = {}) {
1098
+ if (!/^agt_[A-Za-z0-9_-]+$/.test(agentUid))
1099
+ return;
1100
+ const platform = deps.platform ?? process.platform;
1101
+ removeEmbeddedRuntime(profileRoot(agentUid, deps.fleetHome ?? fleetHome()), platform);
1053
1102
  }
1054
1103
  export function fleetLocalProfileNeedsAdoption(agentUid, deps = {}) {
1055
1104
  if (!/^agt_[A-Za-z0-9_-]+$/.test(agentUid))
@@ -26,6 +26,7 @@ export * from "./lock.js";
26
26
  export * from "./display-name.js";
27
27
  export * from "./decisions.js";
28
28
  export * from "./fleet-local.js";
29
+ export * from "./fleet-daemon.js";
29
30
  export * from "./fleet-owner-companies.js";
30
31
  export * from "./fleet-python.js";
31
32
  //# sourceMappingURL=index.d.ts.map
@@ -26,6 +26,7 @@ export * from "./lock.js";
26
26
  export * from "./display-name.js";
27
27
  export * from "./decisions.js";
28
28
  export * from "./fleet-local.js";
29
+ export * from "./fleet-daemon.js";
29
30
  export * from "./fleet-owner-companies.js";
30
31
  export * from "./fleet-python.js";
31
32
  //# sourceMappingURL=index.js.map
@@ -82,6 +82,10 @@ export declare function currentHotSignalSyncCompany(config: Pick<BotConfig, "com
82
82
  * The local bot folder, other than `dir`, that already has the hot-signal-sync
83
83
  * job for `company` (or registered it once, even if its owner removed it
84
84
  * since). Null = none. Unreadable folders are skipped.
85
+ *
86
+ * Only a live bot can hold a company: a folder with no readable bot.json (the
87
+ * bot was removed, or only leftovers remain) or a bot turned off
88
+ * (`enabled: false`) does not count, so its companies go to a bot that runs.
85
89
  */
86
90
  export declare function otherBotWithHotSignalSync(dir: string, company: string, botDirs: readonly string[]): string | null;
87
91
  /**
@@ -40,7 +40,7 @@ import { signalsAlertKey } from "../../hot-channels/alert.js";
40
40
  import { JOB_RUN_OPTIONS_CONTEXT_KEY } from "../job-run.js";
41
41
  import { localDate, runRecordRel } from "../../signals/engine.js";
42
42
  import { formatJobErrorReply, formatLockedReply, formatRunReply, timeInWords } from "../../signals/reply.js";
43
- import { effectiveBotCompanies, effectiveBotKind } from "../config.js";
43
+ import { effectiveBotCompanies, effectiveBotKind, readBotConfig } from "../config.js";
44
44
  import { ensureLocalJob, readLocalJobs, removeLocalJobsWhere, withJobsLock } from "../local-jobs.js";
45
45
  export const HOT_SIGNAL_SYNC_JOB_KIND = "hot-signal-sync";
46
46
  /**
@@ -186,12 +186,19 @@ export function currentHotSignalSyncCompany(config, activeCompany) {
186
186
  * The local bot folder, other than `dir`, that already has the hot-signal-sync
187
187
  * job for `company` (or registered it once, even if its owner removed it
188
188
  * since). Null = none. Unreadable folders are skipped.
189
+ *
190
+ * Only a live bot can hold a company: a folder with no readable bot.json (the
191
+ * bot was removed, or only leftovers remain) or a bot turned off
192
+ * (`enabled: false`) does not count, so its companies go to a bot that runs.
189
193
  */
190
194
  export function otherBotWithHotSignalSync(dir, company, botDirs) {
191
195
  const self = path.resolve(dir);
192
196
  for (const other of botDirs) {
193
197
  if (path.resolve(other) === self)
194
198
  continue;
199
+ const otherConfig = readBotConfig(other);
200
+ if (!otherConfig || otherConfig.enabled === false)
201
+ continue;
195
202
  const registered = readMarker(other).registered;
196
203
  if (registered[markerKey(company)] || registered[fleetMarkerKey(company)])
197
204
  return other;
@@ -45,8 +45,10 @@ export function botLogLine(level, message, now = () => new Date()) {
45
45
  }
46
46
  export function appendBotLog(dir, line) {
47
47
  rotateBotLogIfNeeded(dir);
48
- const logPath = ensureBotLog(dir);
49
48
  try {
49
+ // Creating the log can fail too (a full disk): a log line is never worth
50
+ // an exception in the bot loop that wrote it.
51
+ const logPath = ensureBotLog(dir);
50
52
  fs.appendFileSync(logPath, line.endsWith("\n") ? line : `${line}\n`);
51
53
  }
52
54
  catch {
@@ -37,6 +37,8 @@ export function probeFailureText(cls, runtime, usageLimit) {
37
37
  return `${tool} on this computer is out of date for this model. Update ${tool}, then check again.`;
38
38
  case "model-unsupported":
39
39
  return `This model isn't available in ${tool} here. Choose a different model, then check again.`;
40
+ case "billing":
41
+ return `${tool} account is out of credits. Top up its billing, then check again.`;
40
42
  case "transient":
41
43
  return `${tool} is busy or out of reach right now. Check again in a few minutes.`;
42
44
  case "not-installed":
@@ -101,7 +101,7 @@ import { classifyRuntimeError, classifyRuntimeFailure, isRuntimeUsageLimit, usag
101
101
  import { HQ_BOT_AGENT_UID_ENV } from "../../commands/onboard-bot-membership.js";
102
102
  import { captureHeartbeatIdentityMismatch, identityMismatchMessage, isHeartbeatIdentityMismatch, } from "../heartbeat-identity.js";
103
103
  import { clearBotSession, ensureBotCompanyScope, readBotSession, writeBotSession } from "./session.js";
104
- import { defaultBotStatus, patchBotStatus, readBotStatus } from "./status.js";
104
+ import { createBotStatusWriter, defaultBotStatus, readBotStatus } from "./status.js";
105
105
  import { CLI_VERSION } from "../../cli-version.js";
106
106
  import { CLI_UPDATE_RESTART_EXIT_CODE, describeCliUpdate } from "./cli-update.js";
107
107
  import { createInboxMqttWakeFlagReader, createInboxPollBackoffFlagReader, safeErrorClass } from "./inbox-poll-backoff-flag.js";
@@ -469,7 +469,18 @@ export async function runBot(deps) {
469
469
  const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;
470
470
  const exit = deps.exit ?? ((code) => process.exit(code));
471
471
  const fallback = () => defaultBotStatus(pid, config.runtime, now);
472
- const setStatus = (patch) => patchBotStatus(dir, patch, fallback, now);
472
+ // status.json is a report: a failed write (a full disk) is logged once and
473
+ // retried with the next update, never thrown into the loop that made it.
474
+ const setStatus = createBotStatusWriter(dir, fallback, {
475
+ now,
476
+ onWriteError: (err, first) => {
477
+ if (!first)
478
+ return;
479
+ const code = err?.code;
480
+ log("warn", `could not write status.json (${typeof code === "string" ? code : "error"}); the bot keeps running and retries with its next update`);
481
+ },
482
+ onRecovered: () => log("info", "status.json writes work again"),
483
+ });
473
484
  let state = "starting";
474
485
  let stopping = false;
475
486
  /** Aborts the model turns in progress (owner stop). */
@@ -1008,6 +1019,17 @@ export async function runBot(deps) {
1008
1019
  log("warn", `could not say that ${runtime.id} needs a sign-in: ${err instanceof Error ? err.message : String(err)}`);
1009
1020
  }
1010
1021
  };
1022
+ // A loop that throws must not leave the bot half alive: an inbox loop that
1023
+ // died while the heartbeat went on looked online and read nothing until a
1024
+ // person restarted it (feedback b3320cb6). End the bot as failed with a
1025
+ // non-zero code instead, so it reads offline and its supervisor (launchd
1026
+ // KeepAlive / systemd on-failure) starts a fresh process that polls again.
1027
+ const loopFailed = (which) => (err) => {
1028
+ if (stopping || state !== "running")
1029
+ return;
1030
+ const message = err instanceof Error ? err.message : String(err);
1031
+ void finish("failed", 1, `${which} loop stopped: ${message}`);
1032
+ };
1011
1033
  const heartbeatLoop = (async () => {
1012
1034
  let heartbeatFails = 0;
1013
1035
  while (!stopping && state === "running") {
@@ -1056,6 +1078,7 @@ export async function runBot(deps) {
1056
1078
  }
1057
1079
  }
1058
1080
  })();
1081
+ void heartbeatLoop.catch(loopFailed("heartbeat"));
1059
1082
  // ── Inbox loop ─────────────────────────────────────────────────────────────
1060
1083
  const attempts = new Map();
1061
1084
  const inboxBackoffSteps = [inboxIntervalMs, 10_000, 20_000, 30_000];
@@ -3208,8 +3231,10 @@ export async function runBot(deps) {
3208
3231
  await finish("stopped", 0, mode === "drain" ? "drain completed (running turns finished)" : "stop requested");
3209
3232
  };
3210
3233
  onStopRequest = (mode) => { void stop(mode); };
3234
+ // See loopFailed: an inbox loop that throws ends the bot, never just itself.
3235
+ void inboxLoop.catch(loopFailed("inbox"));
3211
3236
  void inboxLoop.then(() => { if (hasPromotionHold(dir))
3212
- void stop("drain"); });
3237
+ void stop("drain"); }, () => undefined);
3213
3238
  setStatus({ canDrainForPromotion: true });
3214
3239
  void Promise.allSettled([heartbeatLoop, inboxLoop]).then(() => {
3215
3240
  if (state !== "running")
@@ -8,7 +8,7 @@
8
8
  * fallback copy told the person to check the sign-in even when the cause was
9
9
  * something else. Now every failure is classified here, the person gets one
10
10
  * plain sentence plus one next step, and the raw text goes only to the bot
11
- * log. For the four repairable classes the DM also carries a machine-readable
11
+ * log. For repairable classes the DM also carries a machine-readable
12
12
  * `runtime-repair` block in its `richContent` so the desktop can render a
13
13
  * repair card; the plain body stays the fallback.
14
14
  *
@@ -23,6 +23,8 @@ export type RuntimeFailureClass =
23
23
  | "cli-outdated"
24
24
  /** The model id is unknown, retired, or not available to this account. */
25
25
  | "model-unsupported"
26
+ /** The provider account needs billing attention or more credits. */
27
+ | "billing"
26
28
  /** Network trouble, a rate or usage limit, an overloaded service, or a timeout. */
27
29
  | "transient"
28
30
  /** The tool is not installed (or not on PATH) on this computer. */
@@ -32,7 +34,7 @@ export type RuntimeFailureClass =
32
34
  /** Anything else. Neutral copy; never blames the sign-in. */
33
35
  | "unknown";
34
36
  /** The classes that get a repair card in the DM. */
35
- export type RuntimeRepairClass = Extract<RuntimeFailureClass, "signed-out" | "cli-outdated" | "model-unsupported" | "transient" | "runtime-crashed">;
37
+ export type RuntimeRepairClass = Extract<RuntimeFailureClass, "signed-out" | "cli-outdated" | "model-unsupported" | "transient" | "runtime-crashed" | "billing">;
36
38
  /** The one thing the person can do about it. The desktop maps each to a button. */
37
39
  export type RuntimeRepairAction = "signIn" | "update" | "switchModel" | "tryAgain" | "restart";
38
40
  export declare const RUNTIME_REPAIR_ACTIONS: Record<RuntimeRepairClass, RuntimeRepairAction>;