@indigoai-us/hq-cli 5.345.214 → 5.345.215

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 (200) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +180 -13
  4. package/dist/command-catalog.generated.js +221 -13
  5. package/dist/commands/agents.d.ts +51 -1
  6. package/dist/commands/agents.js +154 -2
  7. package/dist/commands/bot-jobs.d.ts +2 -15
  8. package/dist/commands/bot-jobs.js +2 -94
  9. package/dist/commands/bot-runtime.d.ts +46 -5
  10. package/dist/commands/bot-runtime.js +228 -18
  11. package/dist/commands/bot.d.ts +16 -9
  12. package/dist/commands/bot.js +231 -55
  13. package/dist/commands/capacity.d.ts +4 -1
  14. package/dist/commands/capacity.js +46 -10
  15. package/dist/commands/cloud.d.ts +66 -13
  16. package/dist/commands/cloud.js +121 -40
  17. package/dist/commands/company-restore.d.ts +23 -0
  18. package/dist/commands/company-restore.js +128 -0
  19. package/dist/commands/company.js +2 -0
  20. package/dist/commands/core-delegate-w1b.js +15 -1
  21. package/dist/commands/core-policy.js +67 -8
  22. package/dist/commands/daemon.js +5 -0
  23. package/dist/commands/files-browse.d.ts +11 -4
  24. package/dist/commands/files-browse.js +21 -4
  25. package/dist/commands/files.d.ts +1 -1
  26. package/dist/commands/files.js +25 -11
  27. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  28. package/dist/commands/integrations-auth-rules.js +79 -0
  29. package/dist/commands/integrations-connect.d.ts +10 -3
  30. package/dist/commands/integrations-connect.js +87 -13
  31. package/dist/commands/integrations-import.js +124 -12
  32. package/dist/commands/lanes.js +28 -11
  33. package/dist/commands/mesh.d.ts +2 -0
  34. package/dist/commands/mesh.js +60 -35
  35. package/dist/commands/sources.js +6 -0
  36. package/dist/commands/storage-offload.d.ts +12 -0
  37. package/dist/commands/storage-offload.js +41 -3
  38. package/dist/commands/sync-held.js +5 -2
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/lazy-commands.js +3 -5
  42. package/dist/lib/bot/config.d.ts +1 -0
  43. package/dist/lib/bot/config.js +10 -0
  44. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  45. package/dist/lib/bot/eventbridge-cron.js +104 -0
  46. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  47. package/dist/lib/bot/fleet-cron.js +35 -3
  48. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  49. package/dist/lib/bot/fleet-daemon.js +99 -1
  50. package/dist/lib/bot/fleet-local.d.ts +33 -1
  51. package/dist/lib/bot/fleet-local.js +215 -31
  52. package/dist/lib/bot/fleet-python.d.ts +3 -0
  53. package/dist/lib/bot/fleet-python.js +34 -4
  54. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  55. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  56. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  57. package/dist/lib/bot/legacy-provider-login.js +19 -2
  58. package/dist/lib/bot/probe.js +7 -1
  59. package/dist/lib/bot/prompt.js +1 -1
  60. package/dist/lib/bot/readiness.d.ts +8 -0
  61. package/dist/lib/bot/readiness.js +17 -3
  62. package/dist/lib/bot/run.js +20 -1
  63. package/dist/lib/bot/runtime/codex.js +1 -1
  64. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  65. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  66. package/dist/lib/bot/runtime/index.js +19 -9
  67. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  68. package/dist/lib/bot/runtime/types.d.ts +15 -0
  69. package/dist/lib/bot/runtime/types.js +9 -0
  70. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  71. package/dist/lib/bot/runtime-auth.js +94 -3
  72. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  73. package/dist/lib/bot/runtime-failure.js +43 -1
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/accounts.d.ts +8 -0
  76. package/dist/lib/capacity/accounts.js +19 -0
  77. package/dist/lib/capacity/available.d.ts +154 -0
  78. package/dist/lib/capacity/available.js +905 -0
  79. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  80. package/dist/lib/capacity/codex-availability.js +26 -1
  81. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  82. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  83. package/dist/lib/capacity/collectors/codex.js +10 -7
  84. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  85. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  86. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  87. package/dist/lib/capacity/collectors/grok.js +56 -5
  88. package/dist/lib/capacity/ledger.d.ts +37 -1
  89. package/dist/lib/capacity/ledger.js +207 -30
  90. package/dist/lib/capacity/project.d.ts +26 -0
  91. package/dist/lib/capacity/project.js +137 -8
  92. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  93. package/dist/lib/capacity/refusal-rows.js +61 -0
  94. package/dist/lib/capacity/refusal.d.ts +53 -2
  95. package/dist/lib/capacity/refusal.js +284 -65
  96. package/dist/lib/capacity/route.js +46 -11
  97. package/dist/lib/capacity/widget.d.ts +12 -1
  98. package/dist/lib/capacity/widget.js +91 -3
  99. package/dist/lib/daemon/catalog.js +11 -1
  100. package/dist/lib/daemon/resolver.d.ts +2 -0
  101. package/dist/lib/daemon/resolver.js +3 -0
  102. package/dist/lib/daemon/run.d.ts +9 -0
  103. package/dist/lib/daemon/run.js +54 -1
  104. package/dist/lib/daemon/server.d.ts +2 -0
  105. package/dist/lib/daemon/server.js +10 -1
  106. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  107. package/dist/lib/daemon/tcc-eperm.js +310 -0
  108. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  109. package/dist/lib/db/sqlite-binding.js +1 -1
  110. package/dist/lib/delivery/admission.d.ts +86 -0
  111. package/dist/lib/delivery/admission.js +148 -0
  112. package/dist/lib/delivery/artifacts.d.ts +105 -0
  113. package/dist/lib/delivery/artifacts.js +567 -0
  114. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  115. package/dist/lib/delivery/attempt-id.js +16 -0
  116. package/dist/lib/delivery/backup.d.ts +78 -0
  117. package/dist/lib/delivery/backup.js +343 -0
  118. package/dist/lib/delivery/cache.d.ts +29 -0
  119. package/dist/lib/delivery/cache.js +33 -0
  120. package/dist/lib/delivery/contracts.d.ts +142 -0
  121. package/dist/lib/delivery/contracts.js +289 -0
  122. package/dist/lib/delivery/credentials.d.ts +54 -0
  123. package/dist/lib/delivery/credentials.js +119 -0
  124. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  125. package/dist/lib/delivery/disposable-target.js +111 -0
  126. package/dist/lib/delivery/effects.d.ts +136 -0
  127. package/dist/lib/delivery/effects.js +541 -0
  128. package/dist/lib/delivery/enrollment.d.ts +146 -0
  129. package/dist/lib/delivery/enrollment.js +460 -0
  130. package/dist/lib/delivery/escalations.d.ts +51 -0
  131. package/dist/lib/delivery/escalations.js +60 -0
  132. package/dist/lib/delivery/identity.d.ts +25 -0
  133. package/dist/lib/delivery/identity.js +82 -0
  134. package/dist/lib/delivery/inbox.d.ts +116 -0
  135. package/dist/lib/delivery/inbox.js +260 -0
  136. package/dist/lib/delivery/lease.d.ts +80 -0
  137. package/dist/lib/delivery/lease.js +134 -0
  138. package/dist/lib/delivery/migrations.d.ts +255 -0
  139. package/dist/lib/delivery/migrations.js +823 -0
  140. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  141. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  142. package/dist/lib/delivery/mqtt.d.ts +63 -0
  143. package/dist/lib/delivery/mqtt.js +119 -0
  144. package/dist/lib/delivery/outbox.d.ts +95 -0
  145. package/dist/lib/delivery/outbox.js +187 -0
  146. package/dist/lib/delivery/provenance.d.ts +129 -0
  147. package/dist/lib/delivery/provenance.js +93 -0
  148. package/dist/lib/delivery/reconciler.d.ts +215 -0
  149. package/dist/lib/delivery/reconciler.js +703 -0
  150. package/dist/lib/delivery/restore.d.ts +35 -0
  151. package/dist/lib/delivery/restore.js +134 -0
  152. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  153. package/dist/lib/delivery/rpc/client.js +159 -0
  154. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  155. package/dist/lib/delivery/rpc/port.js +16 -0
  156. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  157. package/dist/lib/delivery/rpc/server.js +205 -0
  158. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  159. package/dist/lib/delivery/rpc/wire.js +143 -0
  160. package/dist/lib/delivery/store.d.ts +163 -0
  161. package/dist/lib/delivery/store.js +944 -0
  162. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  163. package/dist/lib/delivery/windows-service-install.js +892 -0
  164. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  165. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  166. package/dist/lib/delivery/workers/macos.d.ts +191 -0
  167. package/dist/lib/delivery/workers/macos.js +943 -0
  168. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  169. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  170. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  171. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  172. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  173. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  174. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  175. package/dist/lib/delivery/workers/windows-service.js +584 -0
  176. package/dist/lib/delivery/workers/windows.d.ts +251 -0
  177. package/dist/lib/delivery/workers/windows.js +594 -0
  178. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  179. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  180. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  181. package/dist/lib/hot-channels/signals-pass.js +71 -2
  182. package/dist/lib/hot-channels/signals-redo.js +10 -2
  183. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  184. package/dist/lib/install/provider-wrappers.js +68 -3
  185. package/dist/lib/lanes/watcher.js +35 -0
  186. package/dist/lib/signals/steps/extract.js +40 -4
  187. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  188. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  189. package/dist/utils/catalog-runtime-paths.js +53 -0
  190. package/dist/utils/cognito-callback-port.d.ts +14 -0
  191. package/dist/utils/cognito-callback-port.js +24 -0
  192. package/dist/utils/cognito-session.js +3 -3
  193. package/dist/utils/deleted-company-notice.d.ts +59 -0
  194. package/dist/utils/deleted-company-notice.js +156 -0
  195. package/dist/utils/files-browse-acl.js +1 -1
  196. package/dist/utils/login-browser.d.ts +1 -1
  197. package/dist/utils/login-browser.js +7 -5
  198. package/dist/utils/resident-package-preload.js +30 -15
  199. package/dist/utils/vault-api.js +7 -0
  200. package/package.json +7 -7
@@ -1,7 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { readFleetLocalGatewayState } from "./fleet-local.js";
4
- import { isPidAlive } from "./status.js";
4
+ import semver from "semver";
5
+ import { isPidAlive, readBotStatus } from "./status.js";
5
6
  export const BOT_READINESS_VALUES = ["creating", "installing", "starting", "ready", "offline"];
6
7
  export const BOT_SETUP_STEPS = [
7
8
  { step: "install", label: "Installing on this Mac" },
@@ -52,6 +53,18 @@ export function readBotSetupStep(dir, alive = isPidAlive) {
52
53
  return null;
53
54
  return BOT_SETUP_STEPS.some((entry) => entry.step === marker.step) ? marker.step : null;
54
55
  }
56
+ export const FLEET_STATUS_READY_MIN_VERSION = "0.4.30";
57
+ export function fleetStatusCarriesReady(engineVersion) {
58
+ const version = semver.coerce(engineVersion ?? "");
59
+ return version !== null && semver.gte(version, FLEET_STATUS_READY_MIN_VERSION);
60
+ }
61
+ export function fleetGatewayReadyForChat(gateway, status, statusCarriesReady) {
62
+ if (!gateway || gateway.gatewayState !== "running" || !gateway.ready)
63
+ return false;
64
+ if (!statusCarriesReady)
65
+ return true;
66
+ return status !== null && status !== undefined && status.pid === gateway.pid && status.ready === true;
67
+ }
55
68
  export function deriveBotReadiness(facts) {
56
69
  if (facts.setupStep === "identity")
57
70
  return "creating";
@@ -62,7 +75,7 @@ export function deriveBotReadiness(facts) {
62
75
  if (!facts.fleet)
63
76
  return "ready";
64
77
  const current = facts.livePid === undefined || facts.livePid === null || facts.gateway?.pid === facts.livePid;
65
- if (current && facts.gateway?.gatewayState === "running" && facts.gateway.ready)
78
+ if (current && fleetGatewayReadyForChat(facts.gateway, facts.status, facts.statusCarriesReady === true))
66
79
  return "ready";
67
80
  return "starting";
68
81
  }
@@ -86,7 +99,8 @@ export async function waitForGatewayReady(agentUid, opts) {
86
99
  const running = gateway !== null && gateway.pid !== null && alive(gateway.pid);
87
100
  if (running)
88
101
  seenPid = gateway.pid;
89
- if (running && gateway.gatewayState === "running" && gateway.ready) {
102
+ const status = opts.botDir ? readBotStatus(opts.botDir) : null;
103
+ if (running && fleetGatewayReadyForChat(gateway, status, opts.statusCarriesReady === true)) {
90
104
  return { ready: true, readyAt: gateway.readyAt, timedOut: false, failed: null, waitedMs: now() - started };
91
105
  }
92
106
  if (running && gateway.gatewayState === "startup_failed") {
@@ -55,6 +55,7 @@ import { resolveExecutiveBot } from "./executive.js";
55
55
  import { handOverExecutiveJobs } from "./jobs/executive-handover.js";
56
56
  import { createMeetingDetect, defaultMeetingDetectDeps, resolveDetectedMeeting } from "./jobs/meeting-detect.js";
57
57
  import { botAuthEnv, describeBotAuth, formatBotAuth } from "./runtime-auth.js";
58
+ import { recordUsageLimitRefusal } from "../capacity/refusal.js";
58
59
  import { ownerContextBlock } from "./owner-context.js";
59
60
  import { randomUUID } from "node:crypto";
60
61
  import { hasPromotionHold } from "./promotion-hold.js";
@@ -97,7 +98,7 @@ import { drainBotEvents } from "./events.js";
97
98
  import { clearPendingJobCompletion, isCompletionDue, isCompletionExpired, isCompletionForOtherAgent, readPendingJobCompletions, recordPendingJobCompletion } from "./job-completions.js";
98
99
  import { SIGN_IN_CHECK_FRESH_MS, SIGN_IN_CHECK_MS, SIGN_IN_RETRY_MS, signInNeededText, signedOutExcerpt, } from "./runtime-sign-in.js";
99
100
  import { checkRuntimeSignIn } from "./runtime-sign-in-check.js";
100
- import { classifyRuntimeError, classifyRuntimeFailure, isRuntimeUsageLimit, usageLimitResetsAt, runtimeDidNotFinishText, runtimeFailureReason, runtimeFailureText, runtimeRepairNotice, withRetrySuggestion, } from "./runtime-failure.js";
101
+ import { classifyRuntimeError, classifyRuntimeFailure, isReportedRuntimeError, isRuntimeUsageLimit, usageLimitResetsAt, runtimeDidNotFinishText, runtimeFailureReason, runtimeFailureText, runtimeRepairNotice, withRetrySuggestion, } from "./runtime-failure.js";
101
102
  import { HQ_BOT_AGENT_UID_ENV } from "../../commands/onboard-bot-membership.js";
102
103
  import { captureHeartbeatIdentityMismatch, identityMismatchMessage, isHeartbeatIdentityMismatch, } from "../heartbeat-identity.js";
103
104
  import { clearBotSession, ensureBotCompanyScope, readBotSession, writeBotSession } from "./session.js";
@@ -875,6 +876,8 @@ export async function runBot(deps) {
875
876
  return await stoppedDuringStartup();
876
877
  // ── Heartbeat loop ─────────────────────────────────────────────────────────
877
878
  const failures = new FailureWindow(FAILURE_WINDOW_MS, FAILURE_LIMIT);
879
+ /** The environment each scope's latest turn really ran with. */
880
+ const turnEnvByScope = new Map();
878
881
  let modelHealth = "ok";
879
882
  /**
880
883
  * FAILURE_LIMIT model failures inside the window: hold model turns for a
@@ -1259,6 +1262,7 @@ export async function runBot(deps) {
1259
1262
  // resets). Claude gets the full hook set via its payload session id;
1260
1263
  // Codex/Grok only see HQ_SESSION_ID.
1261
1264
  const sid = session?.sessionId ?? randomUUID();
1265
+ turnEnvByScope.delete(sessionScope);
1262
1266
  let env;
1263
1267
  try {
1264
1268
  // The bot's own login or account, when set. A missing one fails the
@@ -1268,6 +1272,7 @@ export async function runBot(deps) {
1268
1272
  catch (err) {
1269
1273
  throw new CompanyBindingError(`I can't answer yet: ${err instanceof Error ? err.message : String(err)} I did not use anyone else's login; this work is still pending.`);
1270
1274
  }
1275
+ turnEnvByScope.set(sessionScope, env);
1271
1276
  let bind = { env };
1272
1277
  if (companySlug) {
1273
1278
  try {
@@ -1413,6 +1418,20 @@ export async function runBot(deps) {
1413
1418
  const prior = readStatus()?.brainUsage;
1414
1419
  const since = prior && prior.runtime === config.runtime ? prior.since : now().toISOString();
1415
1420
  setStatus({ brainUsage: { state: "exhausted", runtime: config.runtime, since, ...(resetsAt ? { resetsAt } : {}) } });
1421
+ // So nothing else is sent to this account: the login this turn really ran
1422
+ // on. bot.json can change with no restart (`hq bot login`), so the config
1423
+ // from process start cannot say which one that was. Same gate as a probe.
1424
+ // Only the runtime's own reported error records: raw stderr can be the
1425
+ // model's progress text quoting a limit message.
1426
+ const ranOn = turnEnvByScope.get(sessionScope);
1427
+ if (classifyRuntimeError(err) === "transient") {
1428
+ if (!isReportedRuntimeError(err))
1429
+ log("info", "usage limit not recorded in the capacity ledger: the runtime did not report it as its own error");
1430
+ else if (ranOn)
1431
+ recordUsageLimitRefusal({ provider: config.runtime, turnEnv: ranOn, text: excerpt, hqRoot: config.hqRoot, log });
1432
+ else
1433
+ log("warn", "usage limit not recorded in the capacity ledger: this turn never started on a login");
1434
+ }
1416
1435
  }
1417
1436
  const cls = classifyRuntimeError(err);
1418
1437
  log("error", `model turn failed (${count}/${FAILURE_LIMIT} in window, ${cls}): ${excerpt}`);
@@ -342,7 +342,7 @@ export function createCodexRuntime() {
342
342
  const fromFile = extra.outputFileText?.trim();
343
343
  const text = (fromFile || lastMessage || "").trim();
344
344
  if (!text) {
345
- throw new RuntimeError(`codex produced no reply${errorMessage ? `: ${errorMessage.slice(0, 200)}` : ""}`, (errorMessage ?? stdout.slice(-400)).slice(0, 400), null, errorMessage ? {} : { excerptIsOutputTail: true });
345
+ throw new RuntimeError(`codex produced no reply${errorMessage ? `: ${errorMessage.slice(0, 200)}` : ""}`, (errorMessage ?? stdout.slice(-400)).slice(0, 400), null, errorMessage ? { excerptIsReportedError: true } : { excerptIsOutputTail: true });
346
346
  }
347
347
  return { text, sessionId };
348
348
  },
@@ -6,7 +6,11 @@ export interface GrokAcpClientOptions {
6
6
  send: (message: Record<string, unknown>) => void;
7
7
  onText: (line: string) => void;
8
8
  onComplete: (sessionId: string, text: string) => void;
9
- onFailure: (message: string) => void;
9
+ /**
10
+ * `reportedByGrok` is true only for a JSON-RPC error response from Grok, the
11
+ * tool's own structured error. hq's own failure messages pass false.
12
+ */
13
+ onFailure: (message: string, reportedByGrok: boolean) => void;
10
14
  }
11
15
  /** A minimal ACP client for Grok's documented stdio runtime. */
12
16
  export declare class GrokAcpClient {
@@ -46,7 +46,10 @@ export class GrokAcpClient {
46
46
  this.pending.delete(message.id);
47
47
  if (message.error && typeof message.error === "object") {
48
48
  const error = message.error;
49
- this.fail(typeof error.message === "string" ? error.message : "Grok ACP request failed");
49
+ if (typeof error.message === "string" && error.message.trim())
50
+ this.fail(error.message, true);
51
+ else
52
+ this.fail("Grok ACP request failed");
50
53
  return;
51
54
  }
52
55
  const result = message.result && typeof message.result === "object" ? message.result : {};
@@ -117,12 +120,12 @@ export class GrokAcpClient {
117
120
  this.notify("exit");
118
121
  this.options.onComplete(this.sessionId, this.text);
119
122
  }
120
- fail(message) {
123
+ fail(message, reportedByGrok = false) {
121
124
  if (this.finished)
122
125
  return;
123
126
  this.finished = true;
124
127
  this.pending.clear();
125
- this.options.onFailure(message);
128
+ this.options.onFailure(message, reportedByGrok);
126
129
  }
127
130
  async receiveRequest(message) {
128
131
  const method = message.method;
@@ -100,6 +100,7 @@ export const defaultSpawn = (command, args, options) => new Promise((resolve, re
100
100
  });
101
101
  let stopping = false;
102
102
  let protocolComplete = false;
103
+ let protocolError;
103
104
  const signalTree = (sig, pids) => {
104
105
  for (const p of pids) {
105
106
  try {
@@ -244,8 +245,10 @@ export const defaultSpawn = (command, args, options) => new Promise((resolve, re
244
245
  kill();
245
246
  }, STOP_SETTLE_GRACE_MS).unref?.();
246
247
  },
247
- onFailure: (message) => {
248
+ onFailure: (message, reportedByGrok) => {
248
249
  stderr += `\n[hq bot] ${message}`;
250
+ if (reportedByGrok)
251
+ protocolError = message;
249
252
  stopping = true;
250
253
  child.stdin?.end();
251
254
  setTimeout(() => {
@@ -296,6 +299,15 @@ export const defaultSpawn = (command, args, options) => new Promise((resolve, re
296
299
  protocol.start();
297
300
  else if (options.stdin !== undefined)
298
301
  child.stdin?.end(options.stdin);
302
+ // A protocol turn (Grok ACP) succeeded only when the protocol said so: an
303
+ // unfinished turn is a failure whatever the exit code, and a finished one is
304
+ // a success even if hq had to stop the process. Both settle paths use this,
305
+ // so a Grok process that exits 0 while something it started still holds
306
+ // stdout open (the exit path below) cannot turn a refusal into a success.
307
+ const turnOutcome = (code, signal) => ({
308
+ code: protocol ? (protocolComplete ? 0 : 1) : code,
309
+ signal: protocolComplete ? null : signal,
310
+ });
299
311
  // A stopped process can exit while something it started (and we could not
300
312
  // reach) still holds stdout open; settle shortly after the exit instead of
301
313
  // waiting for that pipe.
@@ -311,7 +323,7 @@ export const defaultSpawn = (command, args, options) => new Promise((resolve, re
311
323
  child.stderr?.destroy();
312
324
  if (partial)
313
325
  emit(partial);
314
- resolve({ code, signal, stdout, stderr });
326
+ resolve({ ...turnOutcome(code, signal), stdout, stderr, ...(protocolError !== undefined ? { protocolError } : {}) });
315
327
  }, STOP_SETTLE_GRACE_MS).unref?.();
316
328
  });
317
329
  child.on("close", (code, signal) => {
@@ -321,12 +333,7 @@ export const defaultSpawn = (command, args, options) => new Promise((resolve, re
321
333
  cleanup();
322
334
  if (partial)
323
335
  emit(partial);
324
- resolve({
325
- code: protocol ? (protocolComplete ? 0 : 1) : code,
326
- signal: protocolComplete ? null : signal,
327
- stdout,
328
- stderr,
329
- });
336
+ resolve({ ...turnOutcome(code, signal), stdout, stderr, ...(protocolError !== undefined ? { protocolError } : {}) });
330
337
  });
331
338
  });
332
339
  /** Time limit for the short helper commands a turn may run (`--version`, the bundled model catalog). */
@@ -502,7 +509,9 @@ export async function runRuntimeTurn(runtime, input, deps = {}) {
502
509
  const ev = parseJsonLine(line);
503
510
  return ev !== null && (ev.type === "system" || ev.type === "assistant" || ev.type === "result");
504
511
  });
505
- const reason = runtime.failureReason?.(result.stdout, result.stderr);
512
+ // A JSON-RPC error Grok sent over ACP (Windows) is the tool's own reported
513
+ // error, even though hq also writes it into stderr for the log.
514
+ const reason = result.protocolError?.trim() || runtime.failureReason?.(result.stdout, result.stderr);
506
515
  // Streaming runtimes write JSON events to stdout: never show those to a
507
516
  // person as the reason. stderr, then a plain description, instead.
508
517
  const stdoutIsEvents = result.stdout.split("\n").some((line) => parseJsonLine(line) !== null);
@@ -516,6 +525,7 @@ export async function runRuntimeTurn(runtime, input, deps = {}) {
516
525
  : `${runtime.binary} exited with code ${result.code}`;
517
526
  throw new RuntimeError(`${runtime.binary} exited with ${result.code ?? `signal ${result.signal}`}${reason ? `: ${reason.slice(0, 200)}` : ""}${fallbackFailure ? ` (${fallbackFailure})` : ""}`, reason ? reason.slice(0, 400) : fallback, result.code, {
518
527
  ...(!reason && stdoutTail ? { excerptIsOutputTail: true } : {}),
528
+ ...(reason ? { excerptIsReportedError: true } : {}),
519
529
  durationMs,
520
530
  sawStreamEvent,
521
531
  binaryPath: binary,
@@ -88,7 +88,7 @@ export function messagesStreamResult(stdout, runtimeName) {
88
88
  throw new RuntimeError(`${runtimeName} returned non-JSON output`, stdout.trim().slice(-400), null, { excerptIsOutputTail: true });
89
89
  if (result?.is_error === true) {
90
90
  const detail = typeof result.result === "string" && result.result ? result.result : (resultErrors(result) ?? String(result.subtype ?? "error"));
91
- throw new RuntimeError(`${runtimeName} reported an error: ${detail.slice(0, 200)}`, detail.slice(0, 400), null);
91
+ throw new RuntimeError(`${runtimeName} reported an error: ${detail.slice(0, 200)}`, detail.slice(0, 400), null, { excerptIsReportedError: true });
92
92
  }
93
93
  const text = (typeof result?.result === "string" && result.result.trim() ? result.result : lastText) ?? "";
94
94
  if (typeof result?.session_id === "string")
@@ -122,7 +122,7 @@ function grokTokenStreamResult(stdout, runtimeName) {
122
122
  }
123
123
  else if (ev.type === "error" && typeof ev.message === "string") {
124
124
  const detail = ev.message;
125
- throw new RuntimeError(`${runtimeName} reported an error: ${detail.slice(0, 200)}`, detail.slice(0, 400), null);
125
+ throw new RuntimeError(`${runtimeName} reported an error: ${detail.slice(0, 200)}`, detail.slice(0, 400), null, { excerptIsReportedError: true });
126
126
  }
127
127
  }
128
128
  return saw ? { text, sessionId } : null;
@@ -91,6 +91,12 @@ export interface SpawnResult {
91
91
  signal: NodeJS.Signals | null;
92
92
  stdout: string;
93
93
  stderr: string;
94
+ /**
95
+ * The error the runtime itself reported over a spawn protocol (Grok ACP on
96
+ * Windows: a JSON-RPC error response). hq also appends it to `stderr` for the
97
+ * log, but it is the tool's structured output, not raw stderr text.
98
+ */
99
+ protocolError?: string;
94
100
  }
95
101
  export interface SpawnOptions {
96
102
  cwd: string;
@@ -128,6 +134,14 @@ export declare class RuntimeError extends Error {
128
134
  * must never decide what went wrong; only the message may.
129
135
  */
130
136
  readonly excerptIsOutputTail: boolean;
137
+ /**
138
+ * True when `stderrExcerpt` is the error the runtime reported in its own
139
+ * structured output (a `result` event with `is_error`, a `turn.failed` or an
140
+ * `error` event, or a JSON-RPC error Grok sent over ACP on Windows), not raw
141
+ * stderr. Raw stderr can carry the model's own
142
+ * progress text, so it alone never records a refusal in the capacity ledger.
143
+ */
144
+ readonly excerptIsReportedError: boolean;
131
145
  /** How long the runtime process lived, in ms, when known. */
132
146
  readonly durationMs: number | undefined;
133
147
  /** True when stdout carried at least one stream event (`system`, `assistant`, `result`): the turn started. */
@@ -140,6 +154,7 @@ export declare class RuntimeError extends Error {
140
154
  started?: boolean;
141
155
  aborted?: boolean;
142
156
  excerptIsOutputTail?: boolean;
157
+ excerptIsReportedError?: boolean;
143
158
  durationMs?: number;
144
159
  sawStreamEvent?: boolean;
145
160
  binaryPath?: string;
@@ -19,6 +19,14 @@ export class RuntimeError extends Error {
19
19
  * must never decide what went wrong; only the message may.
20
20
  */
21
21
  excerptIsOutputTail;
22
+ /**
23
+ * True when `stderrExcerpt` is the error the runtime reported in its own
24
+ * structured output (a `result` event with `is_error`, a `turn.failed` or an
25
+ * `error` event, or a JSON-RPC error Grok sent over ACP on Windows), not raw
26
+ * stderr. Raw stderr can carry the model's own
27
+ * progress text, so it alone never records a refusal in the capacity ledger.
28
+ */
29
+ excerptIsReportedError;
22
30
  /** How long the runtime process lived, in ms, when known. */
23
31
  durationMs;
24
32
  /** True when stdout carried at least one stream event (`system`, `assistant`, `result`): the turn started. */
@@ -35,6 +43,7 @@ export class RuntimeError extends Error {
35
43
  this.started = opts.started ?? true;
36
44
  this.aborted = opts.aborted ?? false;
37
45
  this.excerptIsOutputTail = opts.excerptIsOutputTail ?? false;
46
+ this.excerptIsReportedError = opts.excerptIsReportedError ?? false;
38
47
  this.durationMs = opts.durationMs;
39
48
  this.sawStreamEvent = opts.sawStreamEvent ?? false;
40
49
  this.binaryPath = opts.binaryPath;
@@ -72,6 +72,12 @@ export type SpawnInteractive = (command: string, args: string[], env: NodeJS.Pro
72
72
  };
73
73
  /** Runs the vendor's own login/logout with the terminal attached. Its output goes to the terminal only, never to HQ's log. */
74
74
  export declare const defaultSpawnInteractive: SpawnInteractive;
75
+ /**
76
+ * A browser sign-in with no terminal (the desktop app's Switch account): the
77
+ * vendor CLI opens the browser itself and exits when the sign-in completes.
78
+ * Nothing it prints is shown or logged. Bounded so an abandoned sign-in ends.
79
+ */
80
+ export declare const defaultSpawnBrowserSignIn: SpawnInteractive;
75
81
  /** Logout runs quietly: nothing it prints is shown or logged. */
76
82
  export declare const defaultSpawnQuiet: SpawnInteractive;
77
83
  /**
@@ -83,6 +89,7 @@ export declare function signInBotRuntime(dir: string, runtime: BotLoginRuntime,
83
89
  spawn?: SpawnInteractive;
84
90
  quietSpawn?: SpawnInteractive;
85
91
  env?: NodeJS.ProcessEnv;
92
+ preserveCredentialOnFailure?: boolean;
86
93
  }): {
87
94
  home: string;
88
95
  created: boolean;
@@ -98,6 +105,29 @@ export declare function signOutBotRuntime(dir: string, runtime: BotLoginRuntime,
98
105
  removed: boolean;
99
106
  vendorLogout: "ok" | "failed" | "skipped";
100
107
  };
108
+ /**
109
+ * Move an existing own login to <auth>/<runtime>.previous. The vendor logout
110
+ * does not run: on macOS the Claude credential is a keychain item keyed by
111
+ * the live path, and logging that path out would delete the login the files
112
+ * are supposed to keep. Returns false when the bot had no login for this runtime.
113
+ *
114
+ * A kill during the later browser sign-in leaves both directories. That is an
115
+ * unfinished sign-in, so the held login is put back. It is deleted only when
116
+ * a commit marker says the new sign-in finished.
117
+ */
118
+ export declare function holdPreviousBotLogin(dir: string, runtime: BotLoginRuntime, _deps?: {
119
+ spawn?: SpawnInteractive;
120
+ env?: NodeJS.ProcessEnv;
121
+ }): boolean;
122
+ /** Put a held login back. Removes whatever the failed sign-in left in the live folder. */
123
+ export declare function restoreHeldBotLogin(dir: string, runtime: BotLoginRuntime): void;
124
+ /**
125
+ * Drop a held login after the new one succeeded. The marker is written first,
126
+ * so a kill while the hold is being removed does not look like an unfinished
127
+ * sign-in and put the old login back over the new one. Does not sign the new
128
+ * login out.
129
+ */
130
+ export declare function discardHeldBotLogin(dir: string, runtime: BotLoginRuntime): void;
101
131
  /** True for the model-session files of a bot dir (owner DM, other DMs, rooms, jobs). */
102
132
  export declare function isBotSessionFile(name: string): boolean;
103
133
  export interface SessionSetAside {
@@ -134,6 +134,15 @@ export const defaultSpawnInteractive = (command, args, env) => {
134
134
  const r = spawnSync(command, args, { stdio: "inherit", env });
135
135
  return { status: r.status, ...(r.error ? { error: r.error } : {}) };
136
136
  };
137
+ /**
138
+ * A browser sign-in with no terminal (the desktop app's Switch account): the
139
+ * vendor CLI opens the browser itself and exits when the sign-in completes.
140
+ * Nothing it prints is shown or logged. Bounded so an abandoned sign-in ends.
141
+ */
142
+ export const defaultSpawnBrowserSignIn = (command, args, env) => {
143
+ const r = spawnSync(command, args, { stdio: ["ignore", "ignore", "ignore"], env, timeout: 8 * 60_000 });
144
+ return { status: r.status, ...(r.error ? { error: r.error } : {}) };
145
+ };
137
146
  /** Logout runs quietly: nothing it prints is shown or logged. */
138
147
  export const defaultSpawnQuiet = (command, args, env) => {
139
148
  const r = spawnSync(command, args, { stdio: ["ignore", "ignore", "ignore"], env, timeout: 30_000 });
@@ -176,9 +185,13 @@ export function signInBotRuntime(dir, runtime, deps = {}) {
176
185
  if (r.error || r.status !== 0) {
177
186
  // A first sign-in that failed leaves nothing behind.
178
187
  if (created) {
179
- // A keychain item keyed by this folder may already exist: sign it out first.
180
- const { command: out, args: outArgs } = VENDOR_LOGOUT[runtime];
181
- (deps.quietSpawn ?? defaultSpawnQuiet)(out, outArgs, withProviderHomeEnv(deps.env ?? process.env, runtime, home));
188
+ // A held previous login's keychain item is keyed by this same path.
189
+ // Logging it out would delete that login. Only a first sign-in, which
190
+ // had nothing to keep, signs the partial folder out.
191
+ if (!deps.preserveCredentialOnFailure) {
192
+ const { command: out, args: outArgs } = VENDOR_LOGOUT[runtime];
193
+ (deps.quietSpawn ?? defaultSpawnQuiet)(out, outArgs, withProviderHomeEnv(deps.env ?? process.env, runtime, home));
194
+ }
182
195
  fs.rmSync(home, { recursive: true, force: true });
183
196
  }
184
197
  const why = r.error?.code === "ENOENT" ? `${command} is not installed` : `${command} ${args.join(" ")} did not finish (exit ${r.status ?? "signal"})`;
@@ -204,6 +217,84 @@ export function signOutBotRuntime(dir, runtime, deps = {}) {
204
217
  fs.rmSync(home, { recursive: true, force: true });
205
218
  return { removed: true, vendorLogout: "ok" };
206
219
  }
220
+ /** Sibling of the live login folder. Never passed to the vendor logout. */
221
+ function heldBotLoginPath(dir, runtime) {
222
+ return `${botOwnAuthHome(dir, runtime)}.previous`;
223
+ }
224
+ function refuseSymlink(p) {
225
+ try {
226
+ if (fs.lstatSync(p).isSymbolicLink())
227
+ throw new Error(`refusing to touch ${p}: it is a symbolic link`);
228
+ }
229
+ catch (err) {
230
+ if (err.code !== "ENOENT" && !(err instanceof Error && err.message.startsWith("refusing to touch")))
231
+ throw err;
232
+ }
233
+ }
234
+ /** Written only after the new sign-in has stored its credential. */
235
+ function heldCommitPath(dir, runtime) {
236
+ return `${heldBotLoginPath(dir, runtime)}.committed`;
237
+ }
238
+ /**
239
+ * Move an existing own login to <auth>/<runtime>.previous. The vendor logout
240
+ * does not run: on macOS the Claude credential is a keychain item keyed by
241
+ * the live path, and logging that path out would delete the login the files
242
+ * are supposed to keep. Returns false when the bot had no login for this runtime.
243
+ *
244
+ * A kill during the later browser sign-in leaves both directories. That is an
245
+ * unfinished sign-in, so the held login is put back. It is deleted only when
246
+ * a commit marker says the new sign-in finished.
247
+ */
248
+ export function holdPreviousBotLogin(dir, runtime, _deps = {}) {
249
+ const home = botOwnAuthHome(dir, runtime);
250
+ const hold = heldBotLoginPath(dir, runtime);
251
+ const marker = heldCommitPath(dir, runtime);
252
+ assertOwnAuthHome(dir, home);
253
+ refuseSymlink(hold);
254
+ refuseSymlink(marker);
255
+ if (fs.existsSync(marker)) {
256
+ if (fs.existsSync(hold))
257
+ fs.rmSync(hold, { recursive: true, force: true });
258
+ fs.rmSync(marker, { force: true });
259
+ }
260
+ else if (fs.existsSync(hold) && fs.existsSync(home)) {
261
+ fs.rmSync(home, { recursive: true, force: true });
262
+ fs.renameSync(hold, home);
263
+ }
264
+ else if (fs.existsSync(hold)) {
265
+ fs.renameSync(hold, home);
266
+ }
267
+ if (!fs.existsSync(home))
268
+ return false;
269
+ fs.renameSync(home, hold);
270
+ return true;
271
+ }
272
+ /** Put a held login back. Removes whatever the failed sign-in left in the live folder. */
273
+ export function restoreHeldBotLogin(dir, runtime) {
274
+ const home = botOwnAuthHome(dir, runtime);
275
+ const hold = heldBotLoginPath(dir, runtime);
276
+ assertOwnAuthHome(dir, home);
277
+ refuseSymlink(hold);
278
+ if (!fs.existsSync(hold))
279
+ return;
280
+ fs.rmSync(home, { recursive: true, force: true });
281
+ fs.renameSync(hold, home);
282
+ }
283
+ /**
284
+ * Drop a held login after the new one succeeded. The marker is written first,
285
+ * so a kill while the hold is being removed does not look like an unfinished
286
+ * sign-in and put the old login back over the new one. Does not sign the new
287
+ * login out.
288
+ */
289
+ export function discardHeldBotLogin(dir, runtime) {
290
+ const hold = heldBotLoginPath(dir, runtime);
291
+ const marker = heldCommitPath(dir, runtime);
292
+ refuseSymlink(hold);
293
+ refuseSymlink(marker);
294
+ fs.writeFileSync(marker, "ok", { mode: 0o600 });
295
+ fs.rmSync(hold, { recursive: true, force: true });
296
+ fs.rmSync(marker, { force: true });
297
+ }
207
298
  /** True for the model-session files of a bot dir (owner DM, other DMs, rooms, jobs). */
208
299
  export function isBotSessionFile(name) {
209
300
  return name === "session.json" || /^session-(dm|room|job)-[A-Za-z0-9._-]+\.json$/.test(name);
@@ -44,6 +44,29 @@ export declare function classifyRuntimeFailure(text: string | undefined | null):
44
44
  export declare function isRuntimeUsageLimit(text: string | undefined | null): boolean;
45
45
  /** When a usage limit resets, as the tool wrote it ("9pm (Asia/Dhaka)"), or undefined. */
46
46
  export declare function usageLimitResetsAt(text: string | undefined | null): string | undefined;
47
+ /**
48
+ * True when a failed turn's excerpt is the error the runtime reported in its
49
+ * own structured output (RuntimeError.excerptIsReportedError), not raw stderr.
50
+ * Raw stderr can hold the model's own words, which may quote a limit message,
51
+ * so only a reported error records a refusal in the capacity ledger.
52
+ */
53
+ export declare function isReportedRuntimeError(err: unknown): boolean;
54
+ /**
55
+ * What a usage-limit sentence says it is about: "You've hit your session limit"
56
+ * is the session, "your Fable limit" is that one model, and "your usage limit"
57
+ * names no window. A sentence that names none must not be read as weekly, and a
58
+ * word that is not a known model name must not excuse every other model.
59
+ */
60
+ export declare function usageLimitWindow(text: string | undefined | null): {
61
+ kind: "session";
62
+ } | {
63
+ kind: "weekly";
64
+ } | {
65
+ kind: "model";
66
+ model: string;
67
+ } | {
68
+ kind: "usage";
69
+ };
47
70
  export declare function isBunProcessError(text: string | undefined | null): boolean;
48
71
  /** A process that exits non-zero this soon, with no stream event, never started its turn. */
49
72
  export declare const RUNTIME_CRASH_MAX_MS = 5000;
@@ -52,7 +52,7 @@ const MODEL_UNSUPPORTED = /there'?s an issue with the selected model|\bnot_found
52
52
  * limit", "You're out of extra usage" and "Spending cap reached"; those three
53
53
  * wordings are remembered, not captured from a live account.
54
54
  */
55
- const USAGE_LIMIT = /\byou(?:['’]?ve| have) (?:hit|reached) your (?:[\w'’-]+ ){0,3}limit\b|\b(?:usage|session|weekly|daily|monthly|5-hour) limit (?:reached|exceeded)\b|\byou['’]?re out of (?:[\w-]+ )?usage\b|\bspending cap reached\b/i;
55
+ const USAGE_LIMIT = /\byou(?:['’]?ve| have) (?:hit|reached) your (?:[\w'’.-]+ ){0,3}limit\b|\b(?:usage|session|weekly|daily|monthly|5-hour) limit (?:reached|exceeded)\b|\byou['’]?re out of (?:[\w-]+ )?usage\b|\bspending cap reached\b/i;
56
56
  /**
57
57
  * Limits that a "You've hit your … limit" sentence can name but that are not
58
58
  * the plan running out: a short rate limit ("You've hit your rate limit. Try
@@ -102,6 +102,48 @@ export function usageLimitResetsAt(text) {
102
102
  return undefined;
103
103
  return USAGE_LIMIT_RESET.exec(t)?.[1]?.trim() || undefined;
104
104
  }
105
+ /**
106
+ * True when a failed turn's excerpt is the error the runtime reported in its
107
+ * own structured output (RuntimeError.excerptIsReportedError), not raw stderr.
108
+ * Raw stderr can hold the model's own words, which may quote a limit message,
109
+ * so only a reported error records a refusal in the capacity ledger.
110
+ */
111
+ export function isReportedRuntimeError(err) {
112
+ return Boolean(err && typeof err === "object" && err.excerptIsReportedError === true);
113
+ }
114
+ /** Only these name a model. "Max plan", "Pro", "Codex" or "spending" do not. */
115
+ const KNOWN_MODEL_WORD = /^(?:claude-)?(fable|opus|sonnet|haiku)(?:-[\w.-]+)?$|^((?:gpt|grok)-\d[\w.-]*)$/;
116
+ const USAGE_LIMIT_SESSION = new Set(["session", "5-hour", "5h", "hourly"]);
117
+ const USAGE_LIMIT_WEEKLY = new Set(["weekly", "7-day", "week"]);
118
+ /**
119
+ * What a usage-limit sentence says it is about: "You've hit your session limit"
120
+ * is the session, "your Fable limit" is that one model, and "your usage limit"
121
+ * names no window. A sentence that names none must not be read as weekly, and a
122
+ * word that is not a known model name must not excuse every other model.
123
+ */
124
+ export function usageLimitWindow(text) {
125
+ const all = new RegExp(USAGE_LIMIT.source, "gi");
126
+ for (const match of (text ?? "").matchAll(all)) {
127
+ if (NOT_PLAN_USAGE.test(match[0]))
128
+ continue;
129
+ const words = match[0].toLowerCase()
130
+ .replace(/^.*?\byour\s+/, "")
131
+ .replace(/\blimit\b.*$/, "")
132
+ .split(/\s+/)
133
+ .filter(Boolean);
134
+ for (const word of words) {
135
+ const known = KNOWN_MODEL_WORD.exec(word);
136
+ if (known)
137
+ return { kind: "model", model: known[1] ?? known[2] ?? word };
138
+ }
139
+ if (words.some((word) => USAGE_LIMIT_SESSION.has(word)))
140
+ return { kind: "session" };
141
+ if (words.some((word) => USAGE_LIMIT_WEEKLY.has(word)))
142
+ return { kind: "weekly" };
143
+ return { kind: "usage" };
144
+ }
145
+ return { kind: "usage" };
146
+ }
105
147
  /**
106
148
  * Bun's process-level error line (Claude Code is a Bun-compiled binary):
107
149
  * "error: An unknown error occurred (Unexpected)". The excerpt joins stderr
@@ -9,6 +9,8 @@ export interface BotStatusFile {
9
9
  pid: number;
10
10
  state: BotState;
11
11
  runtime: BotRuntimeId;
12
+ ready?: boolean | null;
13
+ readyAt?: string | null;
12
14
  startedAt: string;
13
15
  lastActivityAt: string;
14
16
  /** Model-CLI restarts since this process started. */
@@ -33,4 +33,12 @@ export interface ListCapacityAccountsOptions {
33
33
  export declare function defaultProviderHome(provider: LaneProvider, home?: string): string;
34
34
  export declare function listCapacityAccounts(options?: ListCapacityAccountsOptions): CapacityAccount[];
35
35
  export declare function registryAccountIds(hqRoot: string, provider: string): string[];
36
+ /**
37
+ * Homes the registry names only with `enabled: false`. An explicit off wins over
38
+ * the implicit default entry that listCapacityAccounts adds for the same home.
39
+ */
40
+ export declare function homesOffForWork(options?: ListCapacityAccountsOptions): Array<{
41
+ provider: LaneProvider;
42
+ home: string;
43
+ }>;
36
44
  //# sourceMappingURL=accounts.d.ts.map
@@ -67,6 +67,25 @@ export function registryAccountIds(hqRoot, provider) {
67
67
  const config = loadLanesConfig(hqRoot);
68
68
  return Object.keys(config.providers[provider].accounts);
69
69
  }
70
+ /**
71
+ * Homes the registry names only with `enabled: false`. An explicit off wins over
72
+ * the implicit default entry that listCapacityAccounts adds for the same home.
73
+ */
74
+ export function homesOffForWork(options = {}) {
75
+ const config = resolveConfig(options);
76
+ const hostname = options.hostname ?? os.hostname();
77
+ const off = [];
78
+ for (const provider of LANE_PROVIDERS) {
79
+ const entries = Object.values(config?.providers[provider]?.accounts ?? {}).filter((account) => account !== undefined);
80
+ const homeOf = (account) => path.resolve(effectiveAccountHome(account, hostname).home);
81
+ const on = new Set(entries.filter((account) => account.enabled).map(homeOf));
82
+ for (const account of entries) {
83
+ if (!account.enabled && !on.has(homeOf(account)))
84
+ off.push({ provider, home: homeOf(account) });
85
+ }
86
+ }
87
+ return off;
88
+ }
70
89
  function resolveConfig(options) {
71
90
  if (options.config === null)
72
91
  return null;