@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
@@ -15,7 +15,8 @@
15
15
  import * as fs from "node:fs";
16
16
  import * as os from "node:os";
17
17
  import * as path from "node:path";
18
- import { classifyRuntimeError, isRuntimeUsageLimit, usageLimitResetsAt } from "./runtime-failure.js";
18
+ import { recordUsageLimitRefusal } from "../capacity/refusal.js";
19
+ import { classifyRuntimeError, isReportedRuntimeError, isRuntimeUsageLimit, usageLimitResetsAt } from "./runtime-failure.js";
19
20
  import { runtimeDisplayName } from "./runtime-sign-in.js";
20
21
  import { RuntimeError, runRuntimeTurn, runtimeFor } from "./runtime/index.js";
21
22
  import { turnEnv } from "./run.js";
@@ -92,6 +93,11 @@ export async function probeBotRuntime(opts) {
92
93
  const cls = classifyRuntimeError(err);
93
94
  const limited = cls === "transient" && isRuntimeUsageLimit(raw);
94
95
  const resetsAt = limited ? usageLimitResetsAt(raw) : undefined;
96
+ // Only the runtime's own reported error records: raw stderr can be the
97
+ // model's progress text quoting a limit message.
98
+ if (limited && isReportedRuntimeError(err)) {
99
+ recordUsageLimitRefusal({ provider: opts.runtime, turnEnv: opts.env ?? process.env, text: raw });
100
+ }
95
101
  return {
96
102
  ok: false,
97
103
  class: cls,
@@ -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 {
@@ -16,6 +20,7 @@ export declare class GrokAcpClient {
16
20
  private readonly terminals;
17
21
  private sessionId;
18
22
  private text;
23
+ private prompting;
19
24
  private finished;
20
25
  constructor(options: GrokAcpClientOptions);
21
26
  start(): void;
@@ -9,6 +9,7 @@ export class GrokAcpClient {
9
9
  terminals = new Map();
10
10
  sessionId;
11
11
  text = "";
12
+ prompting = false;
12
13
  finished = false;
13
14
  constructor(options) {
14
15
  this.options = options;
@@ -16,7 +17,8 @@ export class GrokAcpClient {
16
17
  start() {
17
18
  this.request("initialize", {
18
19
  protocolVersion: 1,
19
- clientCapabilities: { terminal: true },
20
+ // Grok 1.0.77 fails to deserialize terminal/* replies when this is true.
21
+ clientCapabilities: {},
20
22
  }, (result) => this.authenticate(result));
21
23
  }
22
24
  receive(line) {
@@ -46,7 +48,10 @@ export class GrokAcpClient {
46
48
  this.pending.delete(message.id);
47
49
  if (message.error && typeof message.error === "object") {
48
50
  const error = message.error;
49
- this.fail(typeof error.message === "string" ? error.message : "Grok ACP request failed");
51
+ if (typeof error.message === "string" && error.message.trim())
52
+ this.fail(error.message, true);
53
+ else
54
+ this.fail("Grok ACP request failed");
50
55
  return;
51
56
  }
52
57
  const result = message.result && typeof message.result === "object" ? message.result : {};
@@ -83,11 +88,19 @@ export class GrokAcpClient {
83
88
  this.request("session/new", { cwd: this.options.cwd, mcpServers: [], _meta: { yoloMode: true } }, (result) => this.prompt(result));
84
89
  }
85
90
  prompt(result) {
86
- if (typeof result.sessionId !== "string" || !result.sessionId) {
91
+ const sessionId = typeof result.sessionId === "string" && result.sessionId
92
+ ? result.sessionId
93
+ : this.options.sessionId;
94
+ if (!sessionId) {
87
95
  this.fail("Grok ACP did not return a session ID");
88
96
  return;
89
97
  }
90
- this.sessionId = result.sessionId;
98
+ this.sessionId = sessionId;
99
+ // session/load replays the earlier conversation as agent_message_chunk
100
+ // updates before it answers. Start the reply buffer empty so only this
101
+ // turn's text is posted.
102
+ this.text = "";
103
+ this.prompting = true;
91
104
  this.request("session/prompt", { sessionId: this.sessionId, prompt: [{ type: "text", text: this.options.prompt }] }, (response) => this.complete(response));
92
105
  }
93
106
  receiveUpdate(message) {
@@ -96,13 +109,10 @@ export class GrokAcpClient {
96
109
  const content = update.content && typeof update.content === "object" ? update.content : {};
97
110
  if (update.sessionUpdate !== "agent_message_chunk" || typeof content.text !== "string")
98
111
  return;
112
+ // Ignore history replayed during session/load, before the prompt is sent.
113
+ if (!this.prompting)
114
+ return;
99
115
  this.text += content.text;
100
- this.options.onText(JSON.stringify({
101
- type: "assistant",
102
- message: { role: "assistant", content: [{ type: "text", text: content.text }] },
103
- parent_tool_use_id: null,
104
- session_id: this.sessionId,
105
- }));
106
116
  }
107
117
  complete(response) {
108
118
  if (!this.sessionId) {
@@ -114,15 +124,23 @@ export class GrokAcpClient {
114
124
  return;
115
125
  }
116
126
  this.finished = true;
127
+ if (this.text) {
128
+ this.options.onText(JSON.stringify({
129
+ type: "assistant",
130
+ message: { role: "assistant", content: [{ type: "text", text: this.text }] },
131
+ parent_tool_use_id: null,
132
+ session_id: this.sessionId,
133
+ }));
134
+ }
117
135
  this.notify("exit");
118
136
  this.options.onComplete(this.sessionId, this.text);
119
137
  }
120
- fail(message) {
138
+ fail(message, reportedByGrok = false) {
121
139
  if (this.finished)
122
140
  return;
123
141
  this.finished = true;
124
142
  this.pending.clear();
125
- this.options.onFailure(message);
143
+ this.options.onFailure(message, reportedByGrok);
126
144
  }
127
145
  async receiveRequest(message) {
128
146
  const method = message.method;
@@ -150,8 +168,8 @@ export class GrokAcpClient {
150
168
  return typeof candidate.optionId === "string" && /allow|approve/i.test(String(candidate.kind ?? candidate.name ?? ""));
151
169
  });
152
170
  if (!allow || typeof allow.optionId !== "string")
153
- return { outcome: "cancelled" };
154
- return { outcome: "selected", optionId: allow.optionId };
171
+ return { outcome: { outcome: "cancelled" } };
172
+ return { outcome: { outcome: "selected", optionId: allow.optionId } };
155
173
  }
156
174
  if (shortMethod === "terminal/create")
157
175
  return this.createTerminal(params);
@@ -112,7 +112,7 @@ export function createGrokRuntime(opts = {}) {
112
112
  resolveBinary: (env, cwd, platform) => resolveRuntimeBinary("grok", env, platform ?? process.platform, undefined, cwd),
113
113
  buildArgs(input) {
114
114
  if (input.platform === "win32") {
115
- const args = ["--no-auto-update", "agent", "--always-approve", "--no-subagents"];
115
+ const args = ["--no-auto-update", "agent", "--always-approve"];
116
116
  if (input.model)
117
117
  args.push("--model", input.model);
118
118
  args.push("--effort", input.effort?.trim() || "medium");
@@ -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;
@@ -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
@@ -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;