@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
@@ -17,6 +17,7 @@ import { codexSnapshotStale, hasCodexCreditRoom } from "./codex-availability.js"
17
17
  import { canonicalizeHome } from "../lanes/config.js";
18
18
  import { LANE_PROVIDERS } from "../lanes/types.js";
19
19
  import { capacityLoginCommand } from "./ledger.js";
20
+ import { isRateLimitHold, isRefusalHold, refusalEnded } from "./refusal-rows.js";
20
21
  /** All lane providers, in the stable order boss-route uses for ranking ties. */
21
22
  export const ROUTE_PROVIDERS = LANE_PROVIDERS;
22
23
  /** Lane states that count against an account's live load. */
@@ -73,6 +74,9 @@ export function providerForModel(model) {
73
74
  }
74
75
  /** True when the limit should factor into the pick for this request. */
75
76
  export function limitApplies(provider, limit, model) {
77
+ // A refusal that named no window stops the account for every model.
78
+ if (limit.kind === "unknown" && isRefusalHold(limit))
79
+ return true;
76
80
  if (!LIMIT_KINDS.has(limit.kind))
77
81
  return false;
78
82
  if (limit.kind !== "weekly_scoped")
@@ -83,8 +87,25 @@ export function limitApplies(provider, limit, model) {
83
87
  return false;
84
88
  return model.toLowerCase().includes(String(limit.scope).toLowerCase());
85
89
  }
90
+ function longestExhausted(rows) {
91
+ const endOf = (row) => {
92
+ const at = row.limit.resetsAt ? Date.parse(row.limit.resetsAt) : Number.NaN;
93
+ return Number.isFinite(at) ? at : Number.POSITIVE_INFINITY;
94
+ };
95
+ let longest;
96
+ for (const row of rows) {
97
+ // On a tie the real row names the limit.
98
+ if (!longest || endOf(row) > endOf(longest)
99
+ || (endOf(row) === endOf(longest) && isRefusalHold(longest.limit) && !isRefusalHold(row.limit))) {
100
+ longest = row;
101
+ }
102
+ }
103
+ return longest;
104
+ }
86
105
  /** Human label for the limit a reason or binding row quotes. */
87
106
  export function labelLimit(limit) {
107
+ if (limit.kind === "unknown" && isRefusalHold(limit))
108
+ return isRateLimitHold(limit) ? "rate limit" : "usage limit";
88
109
  if (limit.kind === "session")
89
110
  return "session (5h)";
90
111
  if (limit.kind === "weekly_all")
@@ -97,14 +118,18 @@ export function laneAccountFor(provider, homes, lanesConfig) {
97
118
  if (!homes || homes.length === 0)
98
119
  return null;
99
120
  const wanted = new Set(homes.map((h) => safeCanonical(h)));
121
+ // A merged login can name several homes. Prefer one a lane can run on.
122
+ let usageOnly = null;
100
123
  for (const [id, cfg] of Object.entries(accounts)) {
101
124
  if (!cfg?.home)
102
125
  continue;
103
- if (wanted.has(safeCanonical(cfg.home))) {
104
- return { id, enabled: cfg.enabled !== false };
105
- }
126
+ if (!wanted.has(safeCanonical(cfg.home)))
127
+ continue;
128
+ if (cfg.enabled !== false)
129
+ return { id, enabled: true };
130
+ usageOnly ??= { id, enabled: false };
106
131
  }
107
- return null;
132
+ return usageOnly;
108
133
  }
109
134
  function safeCanonical(home) {
110
135
  try {
@@ -412,7 +437,9 @@ export function pickAccount(input) {
412
437
  });
413
438
  continue;
414
439
  }
415
- const applicable = (account.limits ?? []).filter((l) => limitApplies(providerId, l, model));
440
+ // A refusal whose time is up is gone: the real readings answer again.
441
+ const applicable = (account.limits ?? [])
442
+ .filter((l) => limitApplies(providerId, l, model) && !refusalEnded(l, nowMs));
416
443
  const viewRows = applicable.map((limit) => {
417
444
  const resetMs = limit.resetsAt ? Date.parse(limit.resetsAt) : NaN;
418
445
  const resetPassed = limit.state === "reset-pending"
@@ -447,13 +474,19 @@ export function pickAccount(input) {
447
474
  continue;
448
475
  }
449
476
  }
450
- const exhausted = viewRows.find((row) => !row.resetPassed
477
+ const exhaustedRows = viewRows.filter((row) => !row.resetPassed
451
478
  && row.readAge <= LIMIT_STALE_MS
452
479
  && !(providerId === "codex" && codexSnapshotStale(row.limit, account.limits ?? []))
453
480
  && (row.limit.state === "exhausted" || (typeof row.used === "number" && row.used >= 100)));
481
+ // The limit that lasts longest is the one that says when the account is back,
482
+ // so a short hold cannot hide a real used-up limit.
483
+ const exhausted = longestExhausted(exhaustedRows);
454
484
  if (exhausted) {
455
- const codexCredits = providerId === "codex" && hasCodexCreditRoom(account.limits ?? [], nowMs);
456
- const extraRoom = providerId === "claude" && hasExtraUsageRoom(account);
485
+ // Credits and extra usage do not help with a 429: the next lane would go
486
+ // straight back to the account that just refused one.
487
+ const rateLimited = exhaustedRows.some((row) => isRateLimitHold(row.limit));
488
+ const codexCredits = !rateLimited && providerId === "codex" && hasCodexCreditRoom(account.limits ?? [], nowMs);
489
+ const extraRoom = !rateLimited && providerId === "claude" && hasExtraUsageRoom(account);
457
490
  if (codexCredits || (extraRoom && input.allowExtraUsage === true)) {
458
491
  const live = liveLaneCount(lanes, providerId, laneMatch.id);
459
492
  const weekly = applicable.find((l) => l.kind === "weekly_all");
@@ -492,9 +525,11 @@ export function pickAccount(input) {
492
525
  }
493
526
  skipped.push({
494
527
  ...base,
495
- reason: extraRoom
496
- ? `${labelLimit(exhausted.limit)} used up; extra usage is on`
497
- : `${labelLimit(exhausted.limit)} used up`,
528
+ reason: isRateLimitHold(exhausted.limit)
529
+ ? "rate limited"
530
+ : extraRoom
531
+ ? `${labelLimit(exhausted.limit)} used up; extra usage is on`
532
+ : `${labelLimit(exhausted.limit)} used up`,
498
533
  ...(extraRoom
499
534
  ? { fix: "pass --allow-extra-usage to run on paid extra usage" }
500
535
  : {}),
@@ -5,7 +5,7 @@
5
5
  * or account ids. The clock and time zone are arguments so tests can pin both.
6
6
  */
7
7
  import type { CapacityAccount } from "./accounts.js";
8
- import { type NowView } from "./ledger.js";
8
+ import { type NowAccount, type NowView, type RateLimitResetCredit } from "./ledger.js";
9
9
  export interface CapacityWidgetInput {
10
10
  view?: NowView;
11
11
  accounts?: readonly CapacityAccount[];
@@ -19,4 +19,15 @@ export interface CapacityWidgetInput {
19
19
  }
20
20
  export declare function capacityWidgetTimeZone(env?: NodeJS.ProcessEnv): string;
21
21
  export declare function renderCapacityWidget(input: CapacityWidgetInput): string;
22
+ /** Banked resets still on the account, newest read. Expired grants are dropped. */
23
+ export declare function bankedResets(account: NowAccount, nowMs: number): RateLimitResetCredit[];
24
+ /** The model a weekly_scoped limit counts (Claude's "Fable" weekly), if the account has one. */
25
+ export declare function accountScopeName(account: NowAccount): string | null;
26
+ /**
27
+ * Plain name for what one grant resets, from the limits it clears. Claude's own
28
+ * labels run long ("New model launch: one Fable reset for Max, ..."), so the label
29
+ * is the last resort. `seven_day_overage_included` is the model-scoped weekly
30
+ * limit (the account's weekly_scoped row, e.g. Fable).
31
+ */
32
+ export declare function resetGrantName(credit: RateLimitResetCredit, scopeName?: string | null): string;
22
33
  //# sourceMappingURL=widget.d.ts.map
@@ -115,19 +115,101 @@ function renderAccount(provider, account, input) {
115
115
  '<div class="acct">',
116
116
  `<div class="ah"><span class="an" style="color:var(--text-secondary)">${esc(name)}${usage}</span><span class="pill" style="${PILL_STYLE.muted}">${pill}</span></div>`,
117
117
  `<div class="as">${esc(lastReadLine(account, input.timeZone))}</div>`,
118
+ ...resetRows(account, input),
118
119
  "</div>",
119
120
  ].join("\n");
120
121
  }
121
122
  const limits = visibleLimits(account.limits);
122
- const pill = statusPill(limits);
123
+ const pill = statusPill(limits, account, input.nowMs);
123
124
  const rows = limits.map((limit) => renderLimit(limit, input));
124
125
  return [
125
126
  '<div class="acct">',
126
127
  `<div class="ah"><span class="an">${esc(name)}${usage}</span><span class="pill" style="${PILL_STYLE[pill.tone]}">${esc(pill.text)}</span></div>`,
127
128
  ...rows,
129
+ ...resetRows(account, input),
128
130
  "</div>",
129
131
  ].join("\n");
130
132
  }
133
+ /** Banked resets still on the account, newest read. Expired grants are dropped. */
134
+ export function bankedResets(account, nowMs) {
135
+ const credits = account.rateLimitResetCredits?.credits ?? [];
136
+ return credits.filter((credit) => {
137
+ const left = credit.remaining ?? (credit.status === "used" ? 0 : 1);
138
+ if (left <= 0)
139
+ return false;
140
+ return credit.expiresAt === null || credit.expiresAt > nowMs;
141
+ });
142
+ }
143
+ function bankedCount(credits) {
144
+ return credits.reduce((sum, credit) => sum + (credit.remaining ?? 1), 0);
145
+ }
146
+ const MODEL_SCOPED_EXCLUDES = new Set(["seven_day", "seven_day_oauth_apps", "seven_day_overage_included"]);
147
+ /** The model a weekly_scoped limit counts (Claude's "Fable" weekly), if the account has one. */
148
+ export function accountScopeName(account) {
149
+ const scoped = account.limits.find((limit) => limit.kind === "weekly_scoped" && limit.scope?.trim());
150
+ return scoped?.scope?.trim() ?? null;
151
+ }
152
+ /**
153
+ * Plain name for what one grant resets, from the limits it clears. Claude's own
154
+ * labels run long ("New model launch: one Fable reset for Max, ..."), so the label
155
+ * is the last resort. `seven_day_overage_included` is the model-scoped weekly
156
+ * limit (the account's weekly_scoped row, e.g. Fable).
157
+ */
158
+ export function resetGrantName(credit, scopeName = null) {
159
+ const clears = credit.clears ?? [];
160
+ if (clears.includes("seven_day"))
161
+ return "Full weekly reset";
162
+ const models = clears
163
+ .filter((id) => id.startsWith("seven_day_") && !MODEL_SCOPED_EXCLUDES.has(id))
164
+ .map((id) => id.slice("seven_day_".length))
165
+ .map((model) => model.charAt(0).toUpperCase() + model.slice(1));
166
+ if (clears.includes("seven_day_overage_included"))
167
+ models.unshift(scopeName ?? "Model");
168
+ if (models.length > 0)
169
+ return `${[...new Set(models)].join(", ")}-only reset`;
170
+ if (clears.includes("five_hour"))
171
+ return "Session reset";
172
+ if (credit.title)
173
+ return credit.title;
174
+ return "Reset";
175
+ }
176
+ /** True when a banked reset would clear this used-up limit. */
177
+ function resetCovers(credit, limit) {
178
+ const clears = credit.clears ?? [];
179
+ if (clears.length === 0) {
180
+ if (credit.resetType === "session")
181
+ return limit.kind === "session";
182
+ return limit.kind === "weekly_all" || limit.kind === "weekly_scoped";
183
+ }
184
+ if (limit.kind === "session")
185
+ return clears.includes("five_hour");
186
+ if (limit.kind === "weekly_all")
187
+ return clears.includes("seven_day");
188
+ if (limit.kind === "weekly_scoped") {
189
+ const scope = limit.scope?.trim().toLowerCase();
190
+ return clears.includes("seven_day_overage_included") || (scope ? clears.includes(`seven_day_${scope}`) : false);
191
+ }
192
+ return false;
193
+ }
194
+ function resetRows(account, input) {
195
+ const credits = bankedResets(account, input.nowMs);
196
+ if (credits.length === 0)
197
+ return [];
198
+ const count = bankedCount(credits);
199
+ const parts = credits.map((credit) => {
200
+ const left = credit.remaining ?? 1;
201
+ const name = resetGrantName(credit, accountScopeName(account));
202
+ const expiry = credit.expiresAt === null ? "" : `, expires ${shortDate(credit.expiresAt, input.timeZone)}`;
203
+ const paused = credit.usableNow === false ? ", not usable right now" : "";
204
+ return `${left > 1 ? `${left} \u00d7 ` : ""}${name}${expiry}${paused}`;
205
+ });
206
+ return [
207
+ `<div class="row"><span>Resets banked</span><span class="as" style="grid-column:2 / span 3;color:var(--text-primary)"><i class="ti ti-rotate-clockwise" aria-hidden="true"></i> ${count} \u00b7 ${esc(parts.join("; "))}</span></div>`,
208
+ ];
209
+ }
210
+ function shortDate(ms, timeZone) {
211
+ return new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", ...(timeZone ? { timeZone } : {}) }).format(new Date(ms));
212
+ }
131
213
  function renderLimit(limit, input) {
132
214
  const percent = shownPercent(limit.usedPercent);
133
215
  const color = barColor(limit.usedPercent);
@@ -146,10 +228,16 @@ function renderFooter(readTime, stale) {
146
228
  "</div>",
147
229
  ].join("\n");
148
230
  }
149
- function statusPill(limits) {
231
+ function statusPill(limits, account, nowMs = Date.now()) {
150
232
  const exhausted = pickExhausted(limits);
151
- if (exhausted)
233
+ if (exhausted) {
234
+ const credits = account ? bankedResets(account, nowMs) : [];
235
+ const used = limits.filter((limit) => limit.state === "exhausted");
236
+ if (credits.length > 0 && used.every((limit) => credits.some((credit) => resetCovers(credit, limit)))) {
237
+ return { text: `${usedUpText(exhausted)}, reset banked`, tone: "warning" };
238
+ }
152
239
  return { text: usedUpText(exhausted), tone: "danger" };
240
+ }
153
241
  const highest = limits.reduce((max, limit) => {
154
242
  if (typeof limit.usedPercent !== "number" || !Number.isFinite(limit.usedPercent))
155
243
  return max;
@@ -1,3 +1,5 @@
1
+ /** How often every daemon flag monitor asks the registry again. */
2
+ export declare const DAEMON_FLAG_REFRESH_INTERVAL_MS = 30000;
1
3
  export interface BoundedDaemonFlagMonitorOptions {
2
4
  read: () => Promise<boolean>;
3
5
  /** Registry default, also used for absent rows and stale reads. */
@@ -5,6 +7,12 @@ export interface BoundedDaemonFlagMonitorOptions {
5
7
  now?: () => number;
6
8
  onChange?: (enabled: boolean) => void;
7
9
  onReadError?: (error: unknown) => void;
10
+ /**
11
+ * Run the 30-second refresh on a shared timer instead of this monitor's own,
12
+ * so monitors reading from one DaemonFlagSnapshotSource refresh on the same
13
+ * tick and share its registry request. Returns the cancel function.
14
+ */
15
+ scheduleRefresh?: (tick: () => void) => () => void;
8
16
  }
9
17
  export interface BoundedDaemonFlagMonitor {
10
18
  enabled(): Promise<boolean>;
@@ -1,5 +1,7 @@
1
1
  import { performance } from "node:perf_hooks";
2
- const HQ_ANYWHERE_FLAG_REFRESH_INTERVAL_MS = 30_000;
2
+ /** How often every daemon flag monitor asks the registry again. */
3
+ export const DAEMON_FLAG_REFRESH_INTERVAL_MS = 30_000;
4
+ const HQ_ANYWHERE_FLAG_REFRESH_INTERVAL_MS = DAEMON_FLAG_REFRESH_INTERVAL_MS;
3
5
  const HQ_ANYWHERE_FLAG_MAX_STALENESS_MS = 60_000;
4
6
  /**
5
7
  * Refreshes a long-running daemon's flag independently of incoming requests.
@@ -64,11 +66,21 @@ export function createBoundedDaemonFlagMonitor(options) {
64
66
  });
65
67
  return refreshInFlight;
66
68
  };
67
- const refreshTimer = setInterval(() => {
69
+ const tick = () => {
70
+ if (closed)
71
+ return;
68
72
  expireIfStale();
69
73
  void refresh();
70
- }, HQ_ANYWHERE_FLAG_REFRESH_INTERVAL_MS);
71
- refreshTimer.unref?.();
74
+ };
75
+ let cancelRefresh;
76
+ if (options.scheduleRefresh) {
77
+ cancelRefresh = options.scheduleRefresh(tick);
78
+ }
79
+ else {
80
+ const refreshTimer = setInterval(tick, HQ_ANYWHERE_FLAG_REFRESH_INTERVAL_MS);
81
+ refreshTimer.unref?.();
82
+ cancelRefresh = () => clearInterval(refreshTimer);
83
+ }
72
84
  void refresh();
73
85
  return {
74
86
  async enabled() {
@@ -95,8 +107,7 @@ export function createBoundedDaemonFlagMonitor(options) {
95
107
  },
96
108
  close() {
97
109
  closed = true;
98
- if (refreshTimer)
99
- clearInterval(refreshTimer);
110
+ cancelRefresh();
100
111
  if (expiryTimer)
101
112
  clearTimeout(expiryTimer);
102
113
  },
@@ -2,17 +2,39 @@
2
2
  * Feature flags read by the daemon. The daemon runs for weeks, so each read
3
3
  * asks the registry again instead of holding a per-process answer, and it
4
4
  * reads as each flag's fallback unless the registry or a local override decides it.
5
+ *
6
+ * The daemon's timed monitors pass one shared DaemonFlagSnapshotSource, so the
7
+ * flags they watch are decided from one registry request per refresh interval
8
+ * instead of one request per flag.
5
9
  */
6
- import { type FlagClientOptions, type FlagResolution } from "@indigoai-us/hq-flags-client";
10
+ import { type FlagClientOptions, type FlagResolution, type FlagSnapshot } from "@indigoai-us/hq-flags-client";
7
11
  /** Outposts hand running services to the next daemon on a CLI update instead of restarting them all. */
8
12
  export declare const SUPERVISOR_HANDOFF_FLAG = "daemon.supervisor-handoff";
9
13
  /** Self-updates build the new CLI beside the running one and swap it in, so `hq` never disappears mid-update. */
10
14
  export declare const STAGED_SELF_UPDATE_FLAG = "cli.staged-self-update";
15
+ /**
16
+ * How long a loaded registry snapshot may answer further daemon flag reads
17
+ * that arrive between refresh ticks: the monitors' first reads at daemon
18
+ * start, a restarted hqd server's first read, and a request-driven refresh.
19
+ * It is the most a shared read can add to the time a flag change takes to
20
+ * reach one of those reads. A refresh tick never uses it: each tick discards
21
+ * the held snapshot and any request already in flight, so the tick's reads are
22
+ * decided from a request sent on that tick, as they were before sharing.
23
+ *
24
+ * One case differs from a monitor on its own timer: a monitor whose first
25
+ * read is still pending when the shared tick arrives skips that tick (its
26
+ * refresh joins its own pending read), so its next refresh is up to one
27
+ * pending read later than 30 seconds after its first. That applies to the hqd
28
+ * runtime gate just after the server starts, not to the kill switches.
29
+ */
30
+ export declare const DAEMON_FLAG_SNAPSHOT_TTL_MS = 5000;
11
31
  export interface DaemonFlagClient {
12
32
  ready(): Promise<void>;
13
33
  explain(flagKey: string, options?: {
14
34
  fallback?: boolean;
15
35
  }): FlagResolution;
36
+ /** Every flag the registry returned, for the daemon's state file. The registry client has it; a test client may not. */
37
+ snapshot?(): FlagSnapshot | null;
16
38
  close(): void;
17
39
  }
18
40
  export interface ReadDaemonFlagOptions {
@@ -26,6 +48,48 @@ export interface ReadDaemonFlagOptions {
26
48
  onError?: (error: unknown) => void;
27
49
  /** Reject a failed registry read so the daemon monitor can distinguish it from an explicit OFF. */
28
50
  throwOnError?: boolean;
51
+ /**
52
+ * Share one registry request with the daemon's other timed flag reads. The
53
+ * request is made with the options of whichever read starts it, so every
54
+ * read on one source must use the same env, createClient and getToken.
55
+ */
56
+ snapshots?: DaemonFlagSnapshotSource;
57
+ }
58
+ /** One registry request's outcome, before any single flag is decided from it. */
59
+ export interface DaemonFlagRegistryRead {
60
+ /** No usable token: the flag reads as its fallback without reaching the registry. */
61
+ signedOut: boolean;
62
+ /** Every failure the request reported, first one first. Empty means the snapshot loaded. */
63
+ errors: unknown[];
64
+ client?: DaemonFlagClient;
65
+ }
66
+ export interface DaemonFlagSnapshotSource {
67
+ /** One refresh timer for every monitor on this source, so their reads land on the same tick. */
68
+ schedule(tick: () => void): () => void;
69
+ /** Used by readDaemonFlag: the shared registry request for this env. */
70
+ load(env: NodeJS.ProcessEnv, options: ReadDaemonFlagOptions): Promise<DaemonFlagRegistryRead>;
71
+ close(): void;
72
+ }
73
+ export interface DaemonFlagSnapshotSourceOptions {
74
+ ttlMs?: number;
75
+ intervalMs?: number;
76
+ now?: () => number;
77
+ /**
78
+ * Told about every shared registry request when it finishes, before the
79
+ * reads waiting on it decide. The daemon's state file is written from here,
80
+ * so it costs no request of its own. It cannot change or delay a read: it
81
+ * runs synchronously and whatever it throws is dropped.
82
+ */
83
+ onRead?: (read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv) => void;
29
84
  }
85
+ /**
86
+ * Share registry requests between the daemon's timed flag reads.
87
+ *
88
+ * Reads that arrive while a request is in flight join it, and a loaded
89
+ * snapshot answers further reads for `ttlMs`. A failed or signed-out request
90
+ * is handed to the reads that joined it and is never kept, so the next read
91
+ * asks again and each flag keeps its own failure behavior.
92
+ */
93
+ export declare function createDaemonFlagSnapshotSource(options?: DaemonFlagSnapshotSourceOptions): DaemonFlagSnapshotSource;
30
94
  export declare function readDaemonFlag(flagKey: string, options?: ReadDaemonFlagOptions): Promise<boolean>;
31
95
  //# sourceMappingURL=flag.d.ts.map