@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
@@ -17,7 +17,8 @@ import * as crypto from "node:crypto";
17
17
  import * as fs from "node:fs";
18
18
  import * as os from "node:os";
19
19
  import * as path from "node:path";
20
- import { DIR_MODE, FILE_MODE, appendReadings, capacityRoot, readCollectorMark, } from "../ledger.js";
20
+ import { DIR_MODE, FILE_MODE, appendReadings, capacityRoot, EXPIRED_REASON, SIGN_IN_REVOKED_REASON, readCollectorMark, } from "../ledger.js";
21
+ import { grokTokenExpired, parseGrokExpiresAt, refreshGrokSession, } from "./grok-refresh.js";
21
22
  export const GROK_PARSER_VERSION = "grok-billing.1";
22
23
  export const GROK_PROVIDER = "grok";
23
24
  export const GROK_SOURCE = "grok-billing";
@@ -221,10 +222,11 @@ export async function collectGrok(options = {}) {
221
222
  writePoll(root, accountId, new Date(nowMs).toISOString());
222
223
  const endpoint = options.endpoint ?? GROK_BILLING_URL;
223
224
  const fetchImpl = options.fetchImpl ?? defaultGrokFetch;
225
+ const renewed = await renewExpiredGrokAuth(loaded.auth, options, nowMs);
224
226
  let status;
225
227
  let text;
226
228
  try {
227
- const response = await fetchImpl(endpoint, grokBillingInit(loaded.auth, cliVersion));
229
+ const response = await fetchImpl(endpoint, grokBillingInit(renewed.auth, cliVersion));
228
230
  status = response.status;
229
231
  text = status === 200 ? await response.text() : "";
230
232
  }
@@ -259,6 +261,44 @@ export async function collectGrok(options = {}) {
259
261
  const view = appendReadings(mapped.readings, mapped.failures, null, scoped);
260
262
  return { readings: mapped.readings, failures: mapped.failures, view, accountId };
261
263
  }
264
+ /** Renew an expired access token before the billing call. Leaves a fresh token untouched. */
265
+ async function renewExpiredGrokAuth(auth, options, nowMs) {
266
+ let refresh;
267
+ try {
268
+ refresh = await refreshGrokSession({
269
+ authFile: auth.file,
270
+ session: auth.session,
271
+ nowMs,
272
+ fetchImpl: options.refreshFetch,
273
+ listProcesses: options.listProcesses,
274
+ });
275
+ }
276
+ catch {
277
+ refresh = { outcome: "error", reason: "grok token refresh failed" };
278
+ }
279
+ if (refresh.outcome !== "refreshed")
280
+ return { auth, refresh };
281
+ return {
282
+ auth: {
283
+ ...auth,
284
+ bearer: refresh.accessToken,
285
+ session: { ...auth.session, accessToken: refresh.accessToken, expiresAtMs: null },
286
+ },
287
+ refresh,
288
+ };
289
+ }
290
+ /**
291
+ * Reason for a 401/403 from the billing endpoint. A lapsed token that still has
292
+ * a refresh token is expired, not signed out: the next collect (or the next
293
+ * grok run) renews it, so the owner is not sent to sign in again.
294
+ */
295
+ function grokRejectedReason(auth, refresh, nowMs) {
296
+ if (refresh.outcome === "revoked")
297
+ return SIGN_IN_REVOKED_REASON;
298
+ if (auth.session.refreshToken && grokTokenExpired(auth.session, nowMs))
299
+ return EXPIRED_REASON;
300
+ return "signed out: auth rejected";
301
+ }
262
302
  function ledgerOptions(options) {
263
303
  return { ...(options.ledger ?? {}) };
264
304
  }
@@ -314,7 +354,7 @@ function readGrokAuth(file, root) {
314
354
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
315
355
  return { error: "grok auth file is not an object" };
316
356
  }
317
- for (const value of Object.values(parsed)) {
357
+ for (const [entryKey, value] of Object.entries(parsed)) {
318
358
  if (!value || typeof value !== "object" || Array.isArray(value))
319
359
  continue;
320
360
  const record = value;
@@ -322,11 +362,21 @@ function readGrokAuth(file, root) {
322
362
  continue;
323
363
  const accountRaw = firstAccountKey(record, `home:${path.resolve(path.dirname(file))}`);
324
364
  const userId = typeof record.user_id === "string" && record.user_id.trim() ? record.user_id.trim() : null;
365
+ const text = (field) => typeof record[field] === "string" && record[field].trim() ? record[field].trim() : null;
325
366
  return {
326
367
  auth: {
327
368
  bearer: record.key,
328
369
  accountId: hashGrokMaterial(accountRaw, root),
329
370
  userId,
371
+ file,
372
+ session: {
373
+ entryKey,
374
+ accessToken: record.key,
375
+ refreshToken: text("refresh_token"),
376
+ expiresAtMs: parseGrokExpiresAt(record.expires_at),
377
+ issuer: text("oidc_issuer"),
378
+ clientId: text("oidc_client_id"),
379
+ },
330
380
  },
331
381
  };
332
382
  }
@@ -543,10 +593,11 @@ async function collectEnumeratedGrok(options) {
543
593
  accountLabels: account.labels,
544
594
  accountHome: account.homes[0],
545
595
  };
596
+ const renewed = await renewExpiredGrokAuth(account.auth, options, nowMs);
546
597
  let status;
547
598
  let text;
548
599
  try {
549
- const response = await fetchImpl(endpoint, grokBillingInit(account.auth, cliVersion));
600
+ const response = await fetchImpl(endpoint, grokBillingInit(renewed.auth, cliVersion));
550
601
  status = response.status;
551
602
  text = status === 200 ? await response.text() : "";
552
603
  }
@@ -555,7 +606,7 @@ async function collectEnumeratedGrok(options) {
555
606
  continue;
556
607
  }
557
608
  if (status === 401 || status === 403) {
558
- failures.push(failure(mapOptions, "signed out: auth rejected"));
609
+ failures.push(failure(mapOptions, grokRejectedReason(renewed.auth, renewed.refresh, nowMs)));
559
610
  continue;
560
611
  }
561
612
  if (status !== 200) {
@@ -104,6 +104,12 @@ export interface RateLimitResetCredit {
104
104
  expiresAt: number | null;
105
105
  title: string | null;
106
106
  description: string | null;
107
+ /** Resets left on this grant. Absent on Codex credits, which count one each. */
108
+ remaining?: number | null;
109
+ /** False when the grant is paused or blocked right now. */
110
+ usableNow?: boolean | null;
111
+ /** Provider limit ids the reset clears (Claude: five_hour, seven_day, seven_day_<model>). */
112
+ clears?: string[];
107
113
  }
108
114
  export interface RateLimitResetCredits {
109
115
  availableCount: number | null;
@@ -175,6 +181,8 @@ export interface NowAccount {
175
181
  * drift, HTTP error), absent once a later reading from the account lands.
176
182
  */
177
183
  lastError?: string;
184
+ /** Banked resets this account can spend to clear a limit early. Absent when never read. */
185
+ rateLimitResetCredits?: RateLimitResetCredits | null;
178
186
  limits: NowLimit[];
179
187
  }
180
188
  export interface NowProvider {
@@ -188,10 +196,16 @@ export interface NowProvider {
188
196
  /** Present when a reading or signed-out failure named an account. */
189
197
  accounts?: NowAccount[];
190
198
  }
199
+ /**
200
+ * Set by a rebuild that writes one reading per login. A view without it came
201
+ * from an older hq process, which restores the two-id split.
202
+ */
203
+ export declare const CAPACITY_VIEW_REVISION = 2;
191
204
  export interface NowView {
192
205
  machineId: string;
193
206
  hqCliVersion: string;
194
207
  generatedAt: string;
208
+ viewRevision?: number;
195
209
  providers: NowProvider[];
196
210
  }
197
211
  /** On/off mark for the resident collector. The directory alone is not the mark. */
@@ -326,6 +340,9 @@ export declare const nowViewJsonSchema: {
326
340
  readonly generatedAt: {
327
341
  readonly type: "string";
328
342
  };
343
+ readonly viewRevision: {
344
+ readonly type: "number";
345
+ };
329
346
  readonly providers: {
330
347
  readonly type: "array";
331
348
  readonly items: {
@@ -399,14 +416,33 @@ export declare function appendReading(input: ReadingInput, options?: LedgerOptio
399
416
  * Write every reading, parser failure, and optional provider meta, then
400
417
  * rebuild now.json once. appendReading stays the single-reading path.
401
418
  */
402
- export declare function appendReadings(readings: readonly ReadingInput[], failures?: readonly ParserFailureEvent[], meta?: ProviderMetaEvent | null, options?: LedgerOptions): NowView;
419
+ export declare function appendReadings(readings: readonly ReadingInput[], failures?: readonly ParserFailureEvent[], meta?: ProviderMetaEvent | readonly ProviderMetaEvent[] | null, options?: LedgerOptions): NowView;
403
420
  export declare function appendParserFailure(input: ParserFailureEvent, options?: LedgerOptions): NowView;
404
421
  export declare function appendProviderMeta(input: ProviderMetaEvent, options?: LedgerOptions): NowView;
405
422
  export declare function readNow(options?: LedgerOptions): NowView;
423
+ /**
424
+ * readNow for anything that routes. A view an older hq process wrote is rebuilt
425
+ * from the events first. With no events, or a busy lock, the view is returned as
426
+ * it stands.
427
+ */
428
+ export declare function readCurrentNow(options?: LedgerOptions): NowView;
406
429
  export declare function readLedgerEvents(options?: LedgerOptions): LedgerEvent[];
407
430
  export declare function readCollectorMark(options?: LedgerOptions): CollectorMark | null;
408
431
  export declare function setCollectorEnabled(enabled: boolean, options?: LedgerOptions): CollectorMark;
409
432
  export declare function rebuildNow(options?: LedgerOptions): NowView;
433
+ /**
434
+ * The newest refusal already on file for a limit, under any of a login's ids,
435
+ * from the last two event files. A hold that has ended is gone from now.json, so
436
+ * this is how a repeat refusal is told from a first one.
437
+ */
438
+ export declare function latestRefusalOnFile(input: {
439
+ provider: string;
440
+ accountIds: readonly string[];
441
+ limitId: string;
442
+ }, options?: LedgerOptions): {
443
+ observedAt: string;
444
+ resetsAt: string | null;
445
+ } | null;
410
446
  /** Newest uncleared parse or HTTP error among these accounts. */
411
447
  export declare function newestAccountError(accounts: readonly NowAccount[]): string | null;
412
448
  //# sourceMappingURL=ledger.d.ts.map
@@ -1,4 +1,7 @@
1
- import { codexSnapshotStale, hasCodexCreditRoom } from "./codex-availability.js";
1
+ import { canonicalCodexAccountId, codexSnapshotStale, hasCodexCreditRoom } from "./codex-availability.js";
2
+ import { AVAILABLE_FILE_NAME, availableForRebuild } from "./available.js";
3
+ import { mergeStoredView, readStoredIdentities } from "./project.js";
4
+ import { holdsInForce, holdsInForceById, refusalEnded } from "./refusal-rows.js";
2
5
  /**
3
6
  * Personal capacity ledger under ~/.hq/capacity/.
4
7
  *
@@ -88,6 +91,11 @@ export class LedgerRejected extends Error {
88
91
  this.name = "LedgerRejected";
89
92
  }
90
93
  }
94
+ /**
95
+ * Set by a rebuild that writes one reading per login. A view without it came
96
+ * from an older hq process, which restores the two-id split.
97
+ */
98
+ export const CAPACITY_VIEW_REVISION = 2;
91
99
  const limitSchema = {
92
100
  type: "object",
93
101
  additionalProperties: false,
@@ -151,6 +159,7 @@ export const nowViewJsonSchema = {
151
159
  machineId: { type: "string", minLength: 1 },
152
160
  hqCliVersion: { type: "string", minLength: 1 },
153
161
  generatedAt: { type: "string" },
162
+ viewRevision: { type: "number" },
154
163
  providers: {
155
164
  type: "array",
156
165
  items: {
@@ -263,7 +272,8 @@ export function appendReadings(readings, failures = [], meta = null, options) {
263
272
  const ctx = resolve(options);
264
273
  const known = knownReadingIds(ctx.root);
265
274
  const fresh = readings.filter((reading) => !known.has(reading.readingId));
266
- if (fresh.length === 0 && failures.length === 0 && !meta) {
275
+ const metas = meta === null ? [] : Array.isArray(meta) ? meta : [meta];
276
+ if (fresh.length === 0 && failures.length === 0 && metas.length === 0) {
267
277
  try {
268
278
  return readNow({ ...options, root: ctx.root });
269
279
  }
@@ -277,8 +287,8 @@ export function appendReadings(readings, failures = [], meta = null, options) {
277
287
  events.push(validateReading(reading));
278
288
  for (const failure of failures)
279
289
  events.push(validateParserFailure(failure));
280
- if (meta)
281
- events.push(validateProviderMeta(meta));
290
+ for (const entry of metas)
291
+ events.push(validateProviderMeta(entry));
282
292
  for (const event of events)
283
293
  writeEventLine(event, { ...options, root: ctx.root });
284
294
  rememberReadingIds(ctx.root, fresh.map((reading) => reading.readingId));
@@ -310,6 +320,24 @@ export function readNow(options) {
310
320
  throw new LedgerCorrupt();
311
321
  return parsed;
312
322
  }
323
+ /**
324
+ * readNow for anything that routes. A view an older hq process wrote is rebuilt
325
+ * from the events first. With no events, or a busy lock, the view is returned as
326
+ * it stands.
327
+ */
328
+ export function readCurrentNow(options) {
329
+ const view = readNow(options);
330
+ if (view.viewRevision === CAPACITY_VIEW_REVISION)
331
+ return view;
332
+ if (eventFileNames(resolve(options).root).length === 0)
333
+ return view;
334
+ try {
335
+ return rebuildNow(options);
336
+ }
337
+ catch {
338
+ return view;
339
+ }
340
+ }
313
341
  export function readLedgerEvents(options) {
314
342
  const root = resolve(options).root;
315
343
  if (!fs.existsSync(root))
@@ -352,8 +380,15 @@ export function rebuildNow(options) {
352
380
  try {
353
381
  deleteExpiredEvents(ctx.root, ctx.now, ctx.lockTtlSec * 1000);
354
382
  const events = eventsForRebuild(ctx.root, ctx.nowMs);
355
- const view = materialize(events, ctx);
383
+ const identities = readStoredIdentities(ctx.root);
384
+ const view = {
385
+ ...mergeStoredView(materialize(canonicalCodexEvents(events), ctx), {
386
+ identityFor: (accountId) => identities.get(accountId) ?? null,
387
+ }),
388
+ viewRevision: CAPACITY_VIEW_REVISION,
389
+ };
356
390
  writeNow(ctx.root, view, ctx.pid);
391
+ writeAvailableAfterRebuild(ctx, view, options);
357
392
  return view;
358
393
  }
359
394
  finally {
@@ -623,6 +658,34 @@ function eventsForRebuild(dir, nowMs) {
623
658
  atomicWriteText(dir, REBUILD_CHECKPOINT_FILE, `${JSON.stringify({ files, events: reduced })}\n`);
624
659
  return reduced;
625
660
  }
661
+ /**
662
+ * The newest refusal already on file for a limit, under any of a login's ids,
663
+ * from the last two event files. A hold that has ended is gone from now.json, so
664
+ * this is how a repeat refusal is told from a first one.
665
+ */
666
+ export function latestRefusalOnFile(input, options) {
667
+ const ctx = resolve(options);
668
+ if (!fs.existsSync(ctx.root))
669
+ return null;
670
+ let latest = null;
671
+ for (const name of eventFileNames(ctx.root).slice(-2)) {
672
+ for (const event of readCompleteSuffix(path.join(ctx.root, name), 0).events) {
673
+ if ("event" in event)
674
+ continue;
675
+ const reading = event;
676
+ if (reading.source !== "refusal" || reading.provider !== input.provider)
677
+ continue;
678
+ if (reading.limit.limitId !== input.limitId || !input.accountIds.includes(reading.accountId))
679
+ continue;
680
+ const at = Date.parse(reading.observedAt);
681
+ if (!(at <= ctx.nowMs))
682
+ continue;
683
+ if (!latest || at >= Date.parse(latest.observedAt))
684
+ latest = reading;
685
+ }
686
+ }
687
+ return latest ? { observedAt: latest.observedAt, resetsAt: latest.limit.resetsAt ?? null } : null;
688
+ }
626
689
  function eventFileNames(dir) {
627
690
  if (!fs.existsSync(dir))
628
691
  return [];
@@ -680,9 +743,12 @@ function reduceEvents(events, nowMs) {
680
743
  if (Number.isNaN(at))
681
744
  continue;
682
745
  if (isProviderMeta(event)) {
683
- const prev = latestMeta.get(event.provider);
746
+ // Keyed per account: Claude writes one provider_meta per account (banked
747
+ // resets differ by account), so a provider-only key kept just the last one.
748
+ const key = `${event.provider}\0${event.accountId ?? ""}`;
749
+ const prev = latestMeta.get(key);
684
750
  if (!prev || at >= Date.parse(prev.observedAt))
685
- latestMeta.set(event.provider, event);
751
+ latestMeta.set(key, event);
686
752
  continue;
687
753
  }
688
754
  if (isParserFailure(event)) {
@@ -799,6 +865,37 @@ function parseStoredLine(line) {
799
865
  return null;
800
866
  }
801
867
  }
868
+ /**
869
+ * Move a Codex home's events to one account id for this rebuild, when that home
870
+ * holds more than one id. The event files stay as written, so nothing is deleted
871
+ * and a second rebuild gives the same view. An event with no home follows its
872
+ * id's home when that id was only ever seen on one home; otherwise it keeps its
873
+ * id. A home with one id already has one reading per limit and keeps that id.
874
+ */
875
+ function canonicalCodexEvents(events) {
876
+ const homesById = new Map();
877
+ const idsByHome = new Map();
878
+ for (const event of events) {
879
+ if (event.provider !== "codex" || !event.accountId)
880
+ continue;
881
+ const raw = "accountHome" in event ? event.accountHome : undefined;
882
+ if (!raw)
883
+ continue;
884
+ const home = path.resolve(raw);
885
+ homesById.set(event.accountId, (homesById.get(event.accountId) ?? new Set()).add(home));
886
+ idsByHome.set(home, (idsByHome.get(home) ?? new Set()).add(event.accountId));
887
+ }
888
+ return events.map((event) => {
889
+ if (event.provider !== "codex" || !event.accountId)
890
+ return event;
891
+ const raw = "accountHome" in event ? event.accountHome : undefined;
892
+ const known = homesById.get(event.accountId);
893
+ const home = raw ? path.resolve(raw) : known?.size === 1 ? [...known][0] : undefined;
894
+ if (!home || (idsByHome.get(home)?.size ?? 0) < 2)
895
+ return event;
896
+ return { ...event, accountId: canonicalCodexAccountId(home) };
897
+ });
898
+ }
802
899
  function materialize(events, ctx) {
803
900
  const providers = new Map();
804
901
  const bucketFor = (provider) => {
@@ -850,14 +947,15 @@ function materialize(events, ctx) {
850
947
  const viewProviders = [...providers.entries()]
851
948
  .sort((a, b) => a[0].localeCompare(b[0]))
852
949
  .map(([provider, bucket]) => {
853
- const limits = [...bucket.limits.values()]
950
+ const limits = holdsInForceById([...bucket.limits.values()]
854
951
  .sort((a, b) => {
855
952
  const account = a.reading.accountId.localeCompare(b.reading.accountId);
856
953
  if (account !== 0)
857
954
  return account;
858
955
  return a.reading.limit.limitId.localeCompare(b.reading.limit.limitId);
859
956
  })
860
- .map((limit) => toNowLimit(limit, ctx.nowMs));
957
+ .map((limit) => toNowLimit(limit, ctx.nowMs)), ctx.nowMs)
958
+ .filter((limit) => !refusalEnded(limit, ctx.nowMs));
861
959
  if (provider === "codex") {
862
960
  for (const limit of limits) {
863
961
  if (codexSnapshotStale(limit, limits)) {
@@ -869,16 +967,7 @@ function materialize(events, ctx) {
869
967
  }
870
968
  }
871
969
  const failed = bucket.failure !== null && bucket.failure.at >= bucket.latestReadingAt;
872
- let state = "ok";
873
- for (const limit of limits) {
874
- if (provider === "codex" && codexSnapshotStale(limit, limits))
875
- continue;
876
- const availableState = provider === "codex" && limit.state === "exhausted"
877
- && hasCodexCreditRoom(limits.filter((row) => row.accountId === limit.accountId), ctx.nowMs)
878
- ? "ok" : limit.state;
879
- if (STATE_RANK[availableState] > STATE_RANK[state])
880
- state = availableState;
881
- }
970
+ let state = providerLimitsState(provider, limits, ctx.nowMs);
882
971
  if (failed)
883
972
  state = "unknown";
884
973
  // No mapped limit is never "ok". A labelled account's parse drift or HTTP
@@ -896,7 +985,7 @@ function materialize(events, ctx) {
896
985
  entry.rateLimitResetCredits = bucket.meta.rateLimitResetCredits;
897
986
  }
898
987
  const unscopedFailure = bucket.failure !== null && bucket.failure.at >= bucket.latestReadingAt;
899
- attachAccounts(entry, events, unscopedFailure);
988
+ attachAccounts(entry, events, unscopedFailure, ctx.nowMs);
900
989
  // With no limits, show the newest account error (parse drift, HTTP error)
901
990
  // that no later reading from that account has cleared.
902
991
  if (limits.length === 0 && entry.lastError === null)
@@ -932,14 +1021,37 @@ function eventAnnotated(event) {
932
1021
  const reading = event;
933
1022
  return Boolean(reading.accountLabel) || Boolean(reading.accountLabels && reading.accountLabels.length > 0);
934
1023
  }
935
- function attachAccounts(provider, events, unscopedFailure) {
1024
+ function providerLimitsState(provider, limits, nowMs) {
1025
+ let state = "ok";
1026
+ for (const limit of limits) {
1027
+ if (provider === "codex" && codexSnapshotStale(limit, limits))
1028
+ continue;
1029
+ const availableState = provider === "codex" && limit.state === "exhausted"
1030
+ && hasCodexCreditRoom(limits.filter((row) => row.accountId === limit.accountId), nowMs)
1031
+ ? "ok" : limit.state;
1032
+ if (STATE_RANK[availableState] > STATE_RANK[state])
1033
+ state = availableState;
1034
+ }
1035
+ return state;
1036
+ }
1037
+ function attachAccounts(provider, events, unscopedFailure, nowMs) {
936
1038
  const relevant = events.filter((event) => event.provider === provider.provider && eventAnnotated(event));
937
1039
  if (relevant.length === 0)
938
1040
  return;
939
- const accounts = clusterAccounts(provider, relevant);
1041
+ const accounts = clusterAccounts(provider, relevant, nowMs);
940
1042
  if (accounts.length === 0)
941
1043
  return;
1044
+ attachAccountResetCredits(accounts, events.filter((event) => event.provider === provider.provider));
942
1045
  provider.accounts = accounts;
1046
+ // A hold another id of its login has already answered is gone from the provider too.
1047
+ const inForce = new Set(accounts.flatMap((account) => account.limits));
1048
+ const clusteredIds = new Set(accounts.flatMap((account) => account.limits.map((limit) => limit.accountId)));
1049
+ const remaining = provider.limits.filter((limit) => inForce.has(limit) || !clusteredIds.has(limit.accountId));
1050
+ if (remaining.length !== provider.limits.length) {
1051
+ provider.limits = remaining;
1052
+ if (!unscopedFailure)
1053
+ provider.state = providerLimitsState(provider.provider, remaining, nowMs);
1054
+ }
943
1055
  if (unscopedFailure)
944
1056
  return;
945
1057
  const live = accounts.filter((account) => account.authState !== "expired" && account.authState !== "signed_out" && !account.signedOut);
@@ -963,7 +1075,32 @@ function attachAccounts(provider, events, unscopedFailure) {
963
1075
  provider.lastError = null;
964
1076
  }
965
1077
  }
966
- function clusterAccounts(provider, events) {
1078
+ /**
1079
+ * Banked resets belong to one account, not the provider: two Claude accounts can
1080
+ * hold different grants. The newest provider_meta for the account wins, so a read
1081
+ * that finds no grants (null) clears an earlier count.
1082
+ */
1083
+ function attachAccountResetCredits(accounts, events) {
1084
+ const newest = new Map();
1085
+ for (const event of events) {
1086
+ if (!isProviderMeta(event) || !event.accountId)
1087
+ continue;
1088
+ const at = Date.parse(event.observedAt);
1089
+ if (Number.isNaN(at))
1090
+ continue;
1091
+ const seen = newest.get(event.accountId);
1092
+ if (!seen || at >= seen.at)
1093
+ newest.set(event.accountId, { at, credits: event.rateLimitResetCredits });
1094
+ }
1095
+ if (newest.size === 0)
1096
+ return;
1097
+ for (const account of accounts) {
1098
+ const found = newest.get(account.accountId);
1099
+ if (found)
1100
+ account.rateLimitResetCredits = found.credits;
1101
+ }
1102
+ }
1103
+ function clusterAccounts(provider, events, nowMs) {
967
1104
  const seeds = [];
968
1105
  for (const event of events) {
969
1106
  const at = Date.parse(event.observedAt);
@@ -980,6 +1117,7 @@ function clusterAccounts(provider, events) {
980
1117
  at,
981
1118
  problem: problemFor(event.error),
982
1119
  failure: problemFor(event.error) ? null : event.error,
1120
+ refusal: false,
983
1121
  });
984
1122
  continue;
985
1123
  }
@@ -994,6 +1132,7 @@ function clusterAccounts(provider, events) {
994
1132
  at,
995
1133
  problem: null,
996
1134
  failure: null,
1135
+ refusal: reading.source === "refusal",
997
1136
  });
998
1137
  }
999
1138
  if (seeds.length === 0)
@@ -1046,6 +1185,7 @@ function clusterAccounts(provider, events) {
1046
1185
  let latestAt = Number.NEGATIVE_INFINITY;
1047
1186
  let latestDataAt = Number.NEGATIVE_INFINITY;
1048
1187
  let failure = null;
1188
+ let latestRefusalAt = Number.NEGATIVE_INFINITY;
1049
1189
  for (const seed of members) {
1050
1190
  for (const label of seed.labels) {
1051
1191
  if (!labels.includes(label))
@@ -1053,27 +1193,36 @@ function clusterAccounts(provider, events) {
1053
1193
  }
1054
1194
  if (seed.home && !homes.includes(seed.home))
1055
1195
  homes.push(seed.home);
1056
- if (!organization || seed.at >= organization.at)
1196
+ // Statusline readings carry no organization, so null says nothing about it.
1197
+ if (seed.organization && (!organization || seed.at >= organization.at)) {
1057
1198
  organization = { value: seed.organization, at: seed.at };
1199
+ }
1058
1200
  if (seed.problem && (!problem || seed.at >= problem.at)) {
1059
1201
  problem = { ...seed.problem, at: seed.at };
1060
1202
  }
1061
- if (!seed.problem && seed.at > latestReadingAt)
1203
+ if (!seed.problem && !seed.refusal && seed.at > latestReadingAt)
1062
1204
  latestReadingAt = seed.at;
1063
- if (seed.at > latestAt)
1205
+ // A refusal is not a reading: the figures on file are as old as they were.
1206
+ if (seed.refusal) {
1207
+ if (seed.at > latestRefusalAt)
1208
+ latestRefusalAt = seed.at;
1209
+ }
1210
+ else if (seed.at > latestAt)
1064
1211
  latestAt = seed.at;
1065
1212
  if (seed.failure !== null && (!failure || seed.at >= failure.at))
1066
1213
  failure = { error: seed.failure, at: seed.at };
1067
- if (seed.problem === null && seed.failure === null && seed.at > latestDataAt)
1214
+ if (seed.problem === null && seed.failure === null && !seed.refusal && seed.at > latestDataAt)
1068
1215
  latestDataAt = seed.at;
1069
1216
  }
1217
+ if (!Number.isFinite(latestAt))
1218
+ latestAt = latestRefusalAt;
1070
1219
  // The account's newest parse or HTTP error, until a later reading clears it.
1071
1220
  const accountError = failure && failure.at >= latestDataAt ? failure.error : null;
1072
1221
  const ordered = orderLabels(labels);
1073
1222
  const primary = ordered.find((label) => label !== "default") ?? ordered[0] ?? "default";
1074
1223
  const limitedIds = ids.filter((id) => provider.limits.some((limit) => limit.accountId === id));
1075
1224
  const accountId = limitedIds[0] ?? ids[0] ?? primary;
1076
- const limits = provider.limits.filter((limit) => ids.includes(limit.accountId));
1225
+ const limits = holdsInForce(provider.limits.filter((limit) => ids.includes(limit.accountId)), nowMs);
1077
1226
  const blocked = problem !== null && problem.at >= latestReadingAt;
1078
1227
  const expired = blocked && problem?.kind === "expired";
1079
1228
  const isSignedOut = blocked && problem?.kind === "signed_out";
@@ -1277,10 +1426,32 @@ function burnRate(history, nowMs) {
1277
1426
  return delta / hours;
1278
1427
  }
1279
1428
  let nowWriteSerial = 0;
1429
+ /**
1430
+ * available.json follows now.json under the same lock. It is derived, so it
1431
+ * never fails the rebuild. A process that cannot read the account registry or
1432
+ * find the HQ root keeps the last file rather than writing a roster of only the
1433
+ * default homes, and logs one line with fixed text. A write that fails for any
1434
+ * other reason also keeps the last file and logs, redacted.
1435
+ */
1436
+ function writeAvailableAfterRebuild(ctx, view, options = {}) {
1437
+ try {
1438
+ atomicViewWrite(ctx.root, AVAILABLE_FILE_NAME, availableForRebuild(view, ctx.root, ctx.now, options), ctx.pid);
1439
+ }
1440
+ catch (err) {
1441
+ // The cache is derived, so a write failure never fails the rebuild: the next
1442
+ // `hq capacity available` builds from now.json. Log it, redacted, so a
1443
+ // persistent failure is visible instead of silent.
1444
+ const reason = redactProviderTokens(err instanceof Error ? err.message : String(err));
1445
+ process.stderr.write(`hq capacity: available.json not updated: ${reason}\n`);
1446
+ }
1447
+ }
1280
1448
  function writeNow(dir, view, pid) {
1281
1449
  const body = `${JSON.stringify(view, null, 2)}\n`;
1282
1450
  assertNoProviderToken(body);
1283
- const dest = path.join(dir, NOW_FILE_NAME);
1451
+ atomicViewWrite(dir, NOW_FILE_NAME, body, pid);
1452
+ }
1453
+ function atomicViewWrite(dir, name, body, pid) {
1454
+ const dest = path.join(dir, name);
1284
1455
  // A fixed `.now.<pid>.tmp` disappeared before rename when rebuild ran in a
1285
1456
  // tight loop in one process (ENOENT on rename). Each write gets its own name.
1286
1457
  const tmp = path.join(dir, `.now.${pid}.${++nowWriteSerial}.${process.hrtime.bigint().toString(36)}.tmp`);
@@ -1380,6 +1551,9 @@ function validateProviderMeta(value) {
1380
1551
  expiresAt: row.expiresAt,
1381
1552
  title: row.title === null ? null : redactProviderTokens(row.title),
1382
1553
  description: row.description === null ? null : redactProviderTokens(row.description),
1554
+ ...(row.remaining !== undefined ? { remaining: row.remaining } : {}),
1555
+ ...(row.usableNow !== undefined ? { usableNow: row.usableNow } : {}),
1556
+ ...(row.clears !== undefined ? { clears: [...row.clears] } : {}),
1383
1557
  })),
1384
1558
  },
1385
1559
  };
@@ -1487,7 +1661,10 @@ function isResetCredits(value) {
1487
1661
  && (row.grantedAt === null || finiteNumber(row.grantedAt))
1488
1662
  && (row.expiresAt === null || finiteNumber(row.expiresAt))
1489
1663
  && (row.title === null || typeof row.title === "string")
1490
- && (row.description === null || typeof row.description === "string");
1664
+ && (row.description === null || typeof row.description === "string")
1665
+ && (row.remaining === undefined || row.remaining === null || finiteNumber(row.remaining))
1666
+ && (row.usableNow === undefined || row.usableNow === null || typeof row.usableNow === "boolean")
1667
+ && (row.clears === undefined || (Array.isArray(row.clears) && row.clears.every((id) => typeof id === "string")));
1491
1668
  });
1492
1669
  }
1493
1670
  function isParserFailure(value) {
@@ -9,4 +9,30 @@ export interface ProjectCapacityOptions {
9
9
  identityKeyForAccount?: (accountId: string) => string | null;
10
10
  }
11
11
  export declare function projectCapacityView(view: NowView, options: ProjectCapacityOptions): NowView;
12
+ export interface StoredIdentity {
13
+ identityKey: string | null;
14
+ organization: string | null;
15
+ }
16
+ /**
17
+ * Identity keys and organizations from the Claude profile cache, for the merge
18
+ * in the rebuild. Same file `claudeIdentityKeys` reads. ledger.ts cannot import
19
+ * the collector without an import cycle. A missing or unreadable file gives none.
20
+ */
21
+ export declare function readStoredIdentities(root: string): ReadonlyMap<string, StoredIdentity>;
22
+ /**
23
+ * The merge that belongs in now.json: accounts on one home or one identity key
24
+ * become one account, with the newest reading per limit id. Unlike
25
+ * projectCapacityView it needs no registry and drops no account, so it gives
26
+ * the same view whichever process rebuilds. A provider with nothing to merge is
27
+ * returned as is.
28
+ *
29
+ * Routing reads this view, so two rules hold. An account whose sign-in is not
30
+ * live stays its own row, because a merged account can hand a lane any of its
31
+ * homes. And homes merge on a profile id only with the same known organization:
32
+ * one profile id can hold separate seats with separate limits, so an unknown
33
+ * organization neither merges nor bridges, like a missing identity key.
34
+ */
35
+ export declare function mergeStoredView(view: NowView, options: {
36
+ identityFor: (accountId: string) => StoredIdentity | null;
37
+ }): NowView;
12
38
  //# sourceMappingURL=project.d.ts.map