@indigoai-us/hq-cli 5.345.215-beta.0 → 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 (124) hide show
  1. package/CHANGELOG.md +65 -1
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +46 -6
  4. package/dist/command-catalog.generated.js +53 -6
  5. package/dist/commands/bot.js +64 -6
  6. package/dist/commands/capacity.d.ts +4 -1
  7. package/dist/commands/capacity.js +46 -10
  8. package/dist/commands/cloud.js +1 -1
  9. package/dist/commands/core-delegate-w1b.js +15 -1
  10. package/dist/commands/core-policy.js +67 -8
  11. package/dist/commands/daemon.js +5 -0
  12. package/dist/commands/files-browse.d.ts +11 -4
  13. package/dist/commands/files-browse.js +21 -4
  14. package/dist/commands/files.d.ts +1 -1
  15. package/dist/commands/files.js +25 -11
  16. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  17. package/dist/commands/integrations-auth-rules.js +79 -0
  18. package/dist/commands/integrations-import.js +124 -12
  19. package/dist/commands/lanes.js +2 -2
  20. package/dist/commands/mesh.d.ts +2 -0
  21. package/dist/commands/mesh.js +60 -35
  22. package/dist/commands/sync-held.js +5 -2
  23. package/dist/lazy-commands.js +3 -5
  24. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  25. package/dist/lib/bot/fleet-cron.js +35 -3
  26. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  27. package/dist/lib/bot/fleet-daemon.js +99 -1
  28. package/dist/lib/bot/probe.js +7 -1
  29. package/dist/lib/bot/run.js +20 -1
  30. package/dist/lib/bot/runtime/codex.js +1 -1
  31. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  32. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  33. package/dist/lib/bot/runtime/index.js +19 -9
  34. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  35. package/dist/lib/bot/runtime/types.d.ts +15 -0
  36. package/dist/lib/bot/runtime/types.js +9 -0
  37. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  38. package/dist/lib/bot/runtime-failure.js +43 -1
  39. package/dist/lib/capacity/accounts.d.ts +8 -0
  40. package/dist/lib/capacity/accounts.js +19 -0
  41. package/dist/lib/capacity/available.d.ts +154 -0
  42. package/dist/lib/capacity/available.js +905 -0
  43. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  44. package/dist/lib/capacity/codex-availability.js +26 -1
  45. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  46. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  47. package/dist/lib/capacity/collectors/codex.js +10 -7
  48. package/dist/lib/capacity/ledger.d.ts +37 -1
  49. package/dist/lib/capacity/ledger.js +207 -30
  50. package/dist/lib/capacity/project.d.ts +26 -0
  51. package/dist/lib/capacity/project.js +137 -8
  52. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  53. package/dist/lib/capacity/refusal-rows.js +61 -0
  54. package/dist/lib/capacity/refusal.d.ts +53 -2
  55. package/dist/lib/capacity/refusal.js +284 -65
  56. package/dist/lib/capacity/route.js +46 -11
  57. package/dist/lib/capacity/widget.d.ts +12 -1
  58. package/dist/lib/capacity/widget.js +91 -3
  59. package/dist/lib/daemon/resolver.d.ts +2 -0
  60. package/dist/lib/daemon/resolver.js +3 -0
  61. package/dist/lib/daemon/run.d.ts +9 -0
  62. package/dist/lib/daemon/run.js +54 -1
  63. package/dist/lib/daemon/server.d.ts +2 -0
  64. package/dist/lib/daemon/server.js +10 -1
  65. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  66. package/dist/lib/daemon/tcc-eperm.js +310 -0
  67. package/dist/lib/delivery/admission.d.ts +86 -0
  68. package/dist/lib/delivery/admission.js +148 -0
  69. package/dist/lib/delivery/artifacts.d.ts +7 -1
  70. package/dist/lib/delivery/artifacts.js +29 -10
  71. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  72. package/dist/lib/delivery/attempt-id.js +16 -0
  73. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  74. package/dist/lib/delivery/disposable-target.js +111 -0
  75. package/dist/lib/delivery/effects.d.ts +136 -0
  76. package/dist/lib/delivery/effects.js +541 -0
  77. package/dist/lib/delivery/enrollment.d.ts +21 -17
  78. package/dist/lib/delivery/enrollment.js +83 -5
  79. package/dist/lib/delivery/escalations.d.ts +51 -0
  80. package/dist/lib/delivery/escalations.js +60 -0
  81. package/dist/lib/delivery/lease.d.ts +80 -0
  82. package/dist/lib/delivery/lease.js +134 -0
  83. package/dist/lib/delivery/migrations.d.ts +120 -4
  84. package/dist/lib/delivery/migrations.js +215 -15
  85. package/dist/lib/delivery/mqtt.d.ts +2 -0
  86. package/dist/lib/delivery/mqtt.js +7 -0
  87. package/dist/lib/delivery/reconciler.d.ts +65 -1
  88. package/dist/lib/delivery/reconciler.js +224 -13
  89. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  90. package/dist/lib/delivery/rpc/client.js +159 -0
  91. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  92. package/dist/lib/delivery/rpc/port.js +16 -0
  93. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  94. package/dist/lib/delivery/rpc/server.js +205 -0
  95. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  96. package/dist/lib/delivery/rpc/wire.js +143 -0
  97. package/dist/lib/delivery/store.d.ts +2 -0
  98. package/dist/lib/delivery/store.js +4 -0
  99. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  100. package/dist/lib/delivery/windows-service-install.js +892 -0
  101. package/dist/lib/delivery/workers/macos.d.ts +16 -1
  102. package/dist/lib/delivery/workers/macos.js +54 -12
  103. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  104. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  105. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  106. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  107. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  108. package/dist/lib/delivery/workers/windows-service.js +584 -0
  109. package/dist/lib/delivery/workers/windows.d.ts +32 -22
  110. package/dist/lib/delivery/workers/windows.js +50 -64
  111. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  112. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  113. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  114. package/dist/lib/hot-channels/signals-pass.js +71 -2
  115. package/dist/lib/hot-channels/signals-redo.js +10 -2
  116. package/dist/lib/lanes/watcher.js +35 -0
  117. package/dist/lib/signals/steps/extract.js +40 -4
  118. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  119. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  120. package/dist/utils/catalog-runtime-paths.js +53 -0
  121. package/dist/utils/files-browse-acl.js +1 -1
  122. package/package.json +7 -7
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +0 -453
  124. 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 {
@@ -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;
@@ -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;
@@ -0,0 +1,154 @@
1
+ import type { LaneProvider } from "../lanes/types.js";
2
+ import type { CapacityAccount } from "./accounts.js";
3
+ import { type LedgerOptions, type NowView } from "./ledger.js";
4
+ export declare const AVAILABLE_SCHEMA_VERSION = "hq-available-ai.v1";
5
+ export declare const AVAILABLE_FILE_NAME = "available.json";
6
+ export declare const FRESH_WAIT_MS = 3000;
7
+ export declare const STATUS_PROBE_TIMEOUT_MS = 2500;
8
+ export declare const COLLECT_MARK = ".available-collect.lock";
9
+ export declare const COLLECT_MARK_TTL_MS = 60000;
10
+ export type AvailableFreshness = "fresh" | "refreshing" | "stale";
11
+ export type Availability = "ready" | "likely_ready" | "low" | "used_up" | "needs_sign_in" | "not_installed";
12
+ export type TrancheKind = "plan" | "scoped_model" | "extra_usage" | "credits" | "api_key";
13
+ export type AvailableEngine = "model_cli" | "lane" | "fleet";
14
+ export type AvailableHolder = "cli_home" | "bot_own" | "none";
15
+ export type AvailableConfidence = "fetched" | "observed" | "inferred" | "unknown";
16
+ export interface AvailableOption {
17
+ optionId: string;
18
+ provider: LaneProvider;
19
+ account: {
20
+ id: string;
21
+ label: string;
22
+ organization: string | null;
23
+ };
24
+ tranche: {
25
+ kind: TrancheKind;
26
+ scope: string | null;
27
+ paid: boolean;
28
+ };
29
+ availability: Availability;
30
+ leftPercent: number | null;
31
+ backAt: string | null;
32
+ reading: {
33
+ ageSeconds: number | null;
34
+ confidence: AvailableConfidence;
35
+ };
36
+ usableBy: AvailableEngine[];
37
+ holder: AvailableHolder;
38
+ models: string[];
39
+ reason: string;
40
+ nextStep: {
41
+ kind: "use" | "sign_in" | "wait" | "install";
42
+ label: string;
43
+ };
44
+ }
45
+ export interface AvailableDocument {
46
+ schemaVersion: typeof AVAILABLE_SCHEMA_VERSION;
47
+ generatedAt: string;
48
+ freshness: AvailableFreshness;
49
+ best: string | null;
50
+ nextBackAt: string | null;
51
+ options: AvailableOption[];
52
+ }
53
+ /**
54
+ * Which engines may run a tranche. model_cli follows `hq bot switch-account`,
55
+ * which takes all three runtimes. Fleet excludes Grok, because switch-account
56
+ * refuses it there, and Claude plan logins, which the owner parked on
57
+ * 2026-11-05: no new offer, no removal, a running Fleet Claude bot is untouched.
58
+ * `lane` is added per account, when a lane account is enabled on its home.
59
+ */
60
+ export declare const USABLE_BY: Record<LaneProvider, Record<TrancheKind, readonly AvailableEngine[]>>;
61
+ export interface BuildAvailableInput {
62
+ view: NowView;
63
+ accounts: readonly CapacityAccount[];
64
+ now: Date;
65
+ collectorEnabled: boolean | null;
66
+ includeOther?: boolean;
67
+ freshness?: AvailableFreshness;
68
+ }
69
+ export declare function buildAvailableDocument(input: BuildAvailableInput): AvailableDocument;
70
+ /** The bytes for available.json. Refuses any value shaped like a provider token. */
71
+ export declare function serializeAvailable(document: AvailableDocument): string;
72
+ /**
73
+ * Raised by a rebuild that cannot read the account registry or the HQ root. Its
74
+ * message is fixed text: no path, no config content.
75
+ */
76
+ export declare class RosterUnavailable extends Error {
77
+ constructor();
78
+ }
79
+ /**
80
+ * The HQ tree whose registry a resolved root reads. Walks up from the root and
81
+ * returns the nearest folder that has a lanes config, so an explicit root with
82
+ * a lanes config always wins. A folder that only looks like an HQ tree
83
+ * (`isHqRoot`) is not enough to stop the walk: a copy of the hq-core template
84
+ * inside HQ (repos/public/hq-core, an hq-core-staging worktree) or a route
85
+ * folder named companies/ has the same markers but no registry, and reading it
86
+ * would drop the registry accounts and bring back a default home the registry
87
+ * turned off. When no folder on the way has a lanes config, the outermost HQ
88
+ * tree on the path is used (a fresh install, an empty registry). Null when no
89
+ * folder on the way is an HQ tree.
90
+ */
91
+ export declare function registryHqRoot(resolved: string): string | null;
92
+ /**
93
+ * The account roster from the registry, or null when the HQ root cannot be
94
+ * found or the registry cannot be read. Null is not "no registry": a resolved
95
+ * HQ root with no lanes config is a known, empty registry and returns the
96
+ * default homes. Callers must not stand the default homes in for null, because
97
+ * that drops registry accounts on custom homes and brings back a default home
98
+ * the registry turned off for work.
99
+ *
100
+ * HQ_ROOT or CLAUDE_PROJECT_DIR is trusted when it names any existing folder.
101
+ * A folder with no lanes config is often a subfolder of an HQ tree (a session
102
+ * opened in `repos/...`, `companies/x` or a template copy such as
103
+ * `repos/public/hq-core`), so the registry is read from the nearest enclosing
104
+ * folder with a lanes config, else the outermost enclosing HQ tree
105
+ * (registryHqRoot). A folder with no enclosing HQ tree is a wrong root, not an
106
+ * empty registry, so it is null too.
107
+ */
108
+ export declare function registryRoster(options?: LedgerOptions): CapacityAccount[] | null;
109
+ /**
110
+ * The document a rebuild writes. Called under the now.json lock. Throws
111
+ * RosterUnavailable when the registry or HQ root cannot be read: a writer that
112
+ * cannot see the registry would write a partial roster marked fresh, so it
113
+ * keeps the last file instead. Readers rebuild from a newer now.json when they
114
+ * can read the registry themselves (readAvailable).
115
+ */
116
+ export declare function availableForRebuild(view: NowView, root: string, now: Date, options?: LedgerOptions): string;
117
+ export type SignInAnswer = "signed_in" | "signed_out" | "not_installed" | "no_answer";
118
+ /** Asks a tool's own status command. Keeps only the answer, never its output. */
119
+ export type StatusProbe = (provider: LaneProvider, home: string) => Promise<SignInAnswer>;
120
+ export declare const defaultStatusProbe: StatusProbe;
121
+ /** Rows with no ledger at all, from each tool's status command. */
122
+ export declare function buildAvailableFromStatus(input: {
123
+ accounts: readonly CapacityAccount[];
124
+ now: Date;
125
+ probe: StatusProbe;
126
+ includeOther?: boolean;
127
+ }): Promise<AvailableDocument>;
128
+ export interface AvailableDeps {
129
+ probe?: StatusProbe;
130
+ /** Starts one background collect that owns the mark holding the token. Tests replace it. */
131
+ startCollect?: (options: LedgerOptions, token: string) => void;
132
+ sleep?: (ms: number) => Promise<void>;
133
+ /** Wall clock for the --fresh budget. */
134
+ clock?: () => number;
135
+ }
136
+ export declare const defaultStartCollect: (options: LedgerOptions, token: string) => void;
137
+ /** The env variable that hands a collect its mark's token, so it frees only its own mark. */
138
+ export declare const COLLECT_TOKEN_ENV = "HQ_CAPACITY_COLLECT_TOKEN";
139
+ /**
140
+ * Remove the single-flight mark once a collect finishes, so the next read need
141
+ * not wait out the TTL. The collect subprocess calls this with the token it was
142
+ * started with. A mark with another token belongs to a later collect (this one
143
+ * outlived the TTL and was reclaimed), so it is left alone. With no token
144
+ * nothing is removed.
145
+ */
146
+ export declare function releaseCollectMark(options: LedgerOptions, token: string | undefined): void;
147
+ /** What `hq capacity available` prints. Never throws for a bad or missing ledger. */
148
+ export declare function readAvailable(input: {
149
+ options: LedgerOptions;
150
+ includeOther?: boolean;
151
+ fresh?: boolean;
152
+ }, deps?: AvailableDeps): Promise<AvailableDocument>;
153
+ export declare function formatAvailableText(document: AvailableDocument): string;
154
+ //# sourceMappingURL=available.d.ts.map