@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
@@ -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;
@@ -10,5 +10,7 @@ export declare function createResolver(registryPath: string, options?: {
10
10
  log?: (level: "info" | "warn" | "error", message: string) => void;
11
11
  readRegistry?: typeof readRegistry;
12
12
  readCompaniesManifest?: typeof readCompaniesManifestMap;
13
+ /** Sees fs errors the resolver falls back from (hqd watches it for macOS EPERM). */
14
+ onFsError?: (err: unknown) => void;
13
15
  }): (cwd: string) => ResolveResult;
14
16
  //# sourceMappingURL=resolver.d.ts.map
@@ -26,6 +26,7 @@ export function createResolver(registryPath, options = {}) {
26
26
  catch (err) {
27
27
  const code = err.code;
28
28
  if (code !== "ENOENT") {
29
+ options.onFsError?.(err);
29
30
  cache.clear();
30
31
  const detail = err instanceof Error ? err.message : String(err);
31
32
  options.log?.("warn", `hqd registry unavailable; using personal context: ${detail}`);
@@ -65,6 +66,8 @@ export function createResolver(registryPath, options = {}) {
65
66
  }
66
67
  catch (err) {
67
68
  const code = err.code;
69
+ if (code !== "ENOENT")
70
+ options.onFsError?.(err);
68
71
  currentManifestStamp = code === "ENOENT" ? "missing" : `unavailable:${code ?? "unknown"}`;
69
72
  }
70
73
  if (currentManifestStamp !== manifestStamp) {
@@ -123,6 +123,15 @@ export declare function restartsForParent(opts: {
123
123
  managed?: boolean;
124
124
  host?: HostApp;
125
125
  }): boolean;
126
+ /**
127
+ * A parent starts the daemon again after it exits with TCC_EPERM_EXIT_CODE.
128
+ * Only the OS unit (launchd KeepAlive) restarts on any exit code; an app that
129
+ * hosts the daemon restarts it on RESTART_EXIT_CODE only.
130
+ */
131
+ export declare function restartsAfterTccEpermExit(opts: {
132
+ managed?: boolean;
133
+ host?: HostApp;
134
+ }): boolean;
126
135
  /**
127
136
  * The desktop app runs sync itself, so the daemon's sync unit waits. When the
128
137
  * app hosts the daemon it has handed sync over, and the daemon runs it.
@@ -62,6 +62,7 @@ import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, SYNC_RUNNER_LEASE_
62
62
  import { STOP_ESCALATION_MS, SYNC_RUNNER_PERSIST_GRACE_MS, createSupervisor, planKey, } from "./supervisor.js";
63
63
  import { userToolDirs } from "./tools.js";
64
64
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
65
+ import { createTccEpermGuard, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
65
66
  import { daemonRunGuard } from "./lanes-reconcile-guard.js";
66
67
  export const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
67
68
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
@@ -490,6 +491,14 @@ export function desktopAppRunning(platform) {
490
491
  export function restartsForParent(opts) {
491
492
  return opts.managed === true || opts.host !== undefined;
492
493
  }
494
+ /**
495
+ * A parent starts the daemon again after it exits with TCC_EPERM_EXIT_CODE.
496
+ * Only the OS unit (launchd KeepAlive) restarts on any exit code; an app that
497
+ * hosts the daemon restarts it on RESTART_EXIT_CODE only.
498
+ */
499
+ export function restartsAfterTccEpermExit(opts) {
500
+ return opts.managed === true && opts.host === undefined;
501
+ }
493
502
  /**
494
503
  * The desktop app runs sync itself, so the daemon's sync unit waits. When the
495
504
  * app hosts the daemon it has handed sync over, and the daemon runs it.
@@ -1435,6 +1444,22 @@ export async function runDaemon(opts) {
1435
1444
  env,
1436
1445
  onError: (name) => log("warn", `hqd person setting read failed (${name}); keeping the last read value for up to ${HQD_PERSON_SETTING_GRACE_MS / 60_000} minutes`),
1437
1446
  }), { graceMs: HQD_PERSON_SETTING_GRACE_MS });
1447
+ // macOS can stop granting this process access to the HQ folder (TCC) after
1448
+ // HQ.app replaces its bundle. A fresh process gets access again, so trip,
1449
+ // report once, and exit for launchd's KeepAlive to start a new daemon.
1450
+ let daemonStopping = false;
1451
+ let tccEpermExit = () => { };
1452
+ let hqdRootForGuard;
1453
+ const tccEpermGuard = createTccEpermGuard({
1454
+ hqRoot: () => hqdRootForGuard,
1455
+ platform,
1456
+ daemonDir: paths.root,
1457
+ restartable: restartsAfterTccEpermExit(opts),
1458
+ isStopping: () => daemonStopping,
1459
+ log,
1460
+ report: reportTccEperm,
1461
+ exit: (code) => tccEpermExit(code),
1462
+ });
1438
1463
  const hqdListener = await startHqdRuntimeListener({
1439
1464
  isEnabled: async () => refreshHqdRuntimeDecision(async () => shouldStartHqd(await anywhereRuntimeAllowed(env, {
1440
1465
  refreshFlag: async () => {
@@ -1445,13 +1470,16 @@ export async function runDaemon(opts) {
1445
1470
  })), home, env, (error) => log("warn", `hqd runtime marker update failed: ${error.message ?? String(error)}`), (enabled) => syncHqdEnabledMarker(hqdSocketPath(home, env), enabled)),
1446
1471
  startServer: async () => {
1447
1472
  const startConfig = readDaemonConfig(paths.configPath);
1473
+ const hqRoot = startConfig.hqRoot ?? (env.HQ_ROOT?.trim() || undefined);
1474
+ hqdRootForGuard = hqRoot;
1448
1475
  return startHqdServer({
1449
1476
  socketPath: hqdSocketPath(home, env),
1450
1477
  registryPath: registryFile(registryDir(home, env)),
1451
- hqRoot: startConfig.hqRoot ?? (env.HQ_ROOT?.trim() || undefined),
1478
+ hqRoot,
1452
1479
  log,
1453
1480
  onShutdown: () => hqdShutdown?.(),
1454
1481
  reportError: reportHqdCrash,
1482
+ observeError: (err) => tccEpermGuard.observe(err),
1455
1483
  });
1456
1484
  },
1457
1485
  onServerChange: (server) => {
@@ -1480,6 +1508,8 @@ export async function runDaemon(opts) {
1480
1508
  if (stopping)
1481
1509
  return;
1482
1510
  stopping = true;
1511
+ daemonStopping = true;
1512
+ tccEpermGuard.dispose();
1483
1513
  log("info", `${why}; stopping services`);
1484
1514
  closeHqd();
1485
1515
  closeRuntimeWatchers();
@@ -1509,6 +1539,8 @@ export async function runDaemon(opts) {
1509
1539
  if (stopping)
1510
1540
  return;
1511
1541
  stopping = true;
1542
+ daemonStopping = true;
1543
+ tccEpermGuard.dispose();
1512
1544
  closeHqd();
1513
1545
  closeRuntimeWatchers();
1514
1546
  const released = supervisor.release();
@@ -1569,6 +1601,7 @@ export async function runDaemon(opts) {
1569
1601
  });
1570
1602
  };
1571
1603
  hqdShutdown = () => shutdown("hqd shutdown request");
1604
+ tccEpermExit = (code) => shutdown("macOS refused file access under the HQ root; exiting so launchd starts a fresh daemon", code);
1572
1605
  process.on("SIGTERM", () => shutdown("received SIGTERM"));
1573
1606
  process.on("SIGINT", () => shutdown("received SIGINT"));
1574
1607
  if (platform !== "win32")
@@ -1592,6 +1625,26 @@ export async function runDaemon(opts) {
1592
1625
  }
1593
1626
  });
1594
1627
  }
1628
+ /** Report one macOS file-access trip under a fixed fingerprint (counts only, no paths), then flush before the exit. */
1629
+ async function reportTccEperm(event) {
1630
+ try {
1631
+ const { Sentry, preloadSentrySdk } = await import("../../sentry.js");
1632
+ preloadSentrySdk();
1633
+ Sentry.withScope((scope) => {
1634
+ scope.setLevel("error");
1635
+ scope.setFingerprint([...TCC_EPERM_SENTRY_FINGERPRINT]);
1636
+ scope.setTag("component", "hqd");
1637
+ scope.setTag("hqd.event", event.event);
1638
+ scope.setTag("hqd.tcc_eperm.decision", event.decision);
1639
+ scope.setContext("hqd_tcc_eperm", { ...event });
1640
+ Sentry.captureMessage("hqd lost file access under the HQ root (macOS EPERM)");
1641
+ });
1642
+ await Sentry.flush(2_000);
1643
+ }
1644
+ catch (err) {
1645
+ process.stderr.write(`hqd could not report the file access failure: ${String(err)}\n`);
1646
+ }
1647
+ }
1595
1648
  /** Report an hqd op crash to the CLI's existing Sentry integration, tagged with the failing op. */
1596
1649
  function reportHqdCrash(op, err) {
1597
1650
  void import("../../sentry.js").then(({ Sentry }) => {
@@ -55,6 +55,8 @@ export interface HqdServerOptions {
55
55
  workerDispatch?: (request: RunWorkerRequest, hqRoot: string, env: NodeJS.ProcessEnv, now: Date) => Promise<Record<string, unknown>>;
56
56
  /** Crash reporter for internal op failures (US-012); run.ts wires Sentry here. */
57
57
  reportError?: (op: string, err: unknown) => void;
58
+ /** Sees every op failure before it is classified; run.ts watches it for macOS EPERM under the HQ root (tcc-eperm.ts). */
59
+ observeError?: (err: unknown) => void;
58
60
  }
59
61
  export interface HqdServer {
60
62
  socketPath: string;
@@ -306,7 +306,15 @@ export async function startHqdServer(opts) {
306
306
  const startedAtMs = (opts.now ?? (() => new Date()))().getTime();
307
307
  const sessions = new SessionRegistry(opts.now);
308
308
  const log = opts.log ?? (() => { });
309
- const resolve = createResolver(opts.registryPath ?? registryFile(), { hqRoot: opts.hqRoot, log });
309
+ const observeError = (err) => {
310
+ try {
311
+ opts.observeError?.(err);
312
+ }
313
+ catch (observeErr) {
314
+ log("warn", `hqd error observer failed: ${observeErr.message}`);
315
+ }
316
+ };
317
+ const resolve = createResolver(opts.registryPath ?? registryFile(), { hqRoot: opts.hqRoot, log, onFsError: observeError });
310
318
  const clock = opts.now ?? (() => new Date());
311
319
  const env = opts.env ?? process.env;
312
320
  const policyIndex = opts.hqRoot ? new PolicyIndex(opts.hqRoot, log) : null;
@@ -717,6 +725,7 @@ export async function startHqdServer(opts) {
717
725
  }
718
726
  };
719
727
  const fail = (err) => {
728
+ observeError(err);
720
729
  const error = err instanceof OpError ||
721
730
  err instanceof PolicyOpError ||
722
731
  err instanceof JournalOpError ||
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Self-recovery for a daemon that macOS privacy (TCC) has cut off from the
3
+ * HQ folder.
4
+ *
5
+ * After HQ.app updates itself, a daemon that was started from the old app
6
+ * bundle keeps running from the deleted bundle. macOS then refuses its file
7
+ * reads and writes under the HQ root with EPERM ("operation not permitted"),
8
+ * and every hqd op that touches companies/ fails until someone runs
9
+ * `launchctl kickstart -k`. A fresh process started by launchd is checked
10
+ * again and gets access.
11
+ *
12
+ * So: when hqd sees EPERM on reads (open, stat, readdir and the like) of paths
13
+ * under the HQ root, repeated across more than one path within a short window,
14
+ * it logs one structured event, reports
15
+ * it once to Sentry under a fixed fingerprint, and exits with
16
+ * TCC_EPERM_EXIT_CODE. The daemon's LaunchAgent has KeepAlive=true, so launchd
17
+ * starts it again (after its ThrottleInterval) whatever the exit code.
18
+ *
19
+ * It never exits for EPERM outside the HQ root, for EACCES, off macOS, while
20
+ * the daemon is already stopping, or when no service manager would start it
21
+ * again. A permission that stays revoked would otherwise restart the daemon
22
+ * forever, so after TCC_EPERM_MAX_EXITS exits within TCC_EPERM_EXIT_WINDOW_MS
23
+ * it stays up and writes FILES_ACCESS_NEEDED_MARKER, which `hq daemon status`
24
+ * reports as a warning while the daemon runs. It also stays up when it cannot
25
+ * write that exit record, since the backoff could never engage. A daemon that
26
+ * stayed up lists the HQ root every TCC_EPERM_PROBE_INTERVAL_MS; once that
27
+ * works it clears the marker and watches again.
28
+ */
29
+ /** sysexits EX_IOERR. Not 75 (RESTART_EXIT_CODE) and not one exit-cause.ts treats as permanent (77, 78, 126, 127). */
30
+ export declare const TCC_EPERM_EXIT_CODE = 74;
31
+ /** EPERM hits under the HQ root count toward a trip only inside this window. */
32
+ export declare const TCC_EPERM_WINDOW_MS = 60000;
33
+ /** Hits needed inside the window. */
34
+ export declare const TCC_EPERM_MIN_EVENTS = 3;
35
+ /** Distinct paths needed inside the window, so one odd file cannot trip it. */
36
+ export declare const TCC_EPERM_MIN_PATHS = 2;
37
+ /** Exits allowed inside TCC_EPERM_EXIT_WINDOW_MS before the daemon stays up instead. */
38
+ export declare const TCC_EPERM_MAX_EXITS = 3;
39
+ export declare const TCC_EPERM_EXIT_WINDOW_MS: number;
40
+ /** Under the daemon dir: timestamps of recent EPERM exits (the backoff record). */
41
+ export declare const TCC_EPERM_EXITS_FILE = "tcc-eperm-exits.json";
42
+ /** Under the daemon dir: present while hqd is up but cannot read the HQ folder. */
43
+ export declare const FILES_ACCESS_NEEDED_MARKER = "files-access-needed.json";
44
+ export declare const FILES_ACCESS_NEEDED_MESSAGE: string;
45
+ export declare const TCC_EPERM_SENTRY_FINGERPRINT: readonly string[];
46
+ export interface EpermHit {
47
+ path: string;
48
+ syscall?: string;
49
+ }
50
+ /**
51
+ * The EPERM hit `err` carries for a read under `hqRoot`, or null. Follows
52
+ * `cause` a few levels, since some ops wrap the fs error. EACCES is a plain
53
+ * permission bit, not TCC, and never counts; neither does an EPERM with no
54
+ * path (kill(2), for one) or from a syscall that does not read. The root's
55
+ * realpath is looked up only after an EPERM read is found, and is cached.
56
+ */
57
+ export declare function epermUnderRoot(err: unknown, hqRoot: string): EpermHit | null;
58
+ export interface EpermWindowOptions {
59
+ windowMs?: number;
60
+ minEvents?: number;
61
+ minPaths?: number;
62
+ }
63
+ export interface EpermWindowSummary {
64
+ hits: number;
65
+ distinctPaths: number;
66
+ syscalls: string[];
67
+ }
68
+ /** Sliding window of EPERM hits; `record` returns true once the window holds enough of them. */
69
+ export declare function createEpermWindow(options?: EpermWindowOptions): {
70
+ record(hit: EpermHit, at: number): boolean;
71
+ summary(): EpermWindowSummary;
72
+ };
73
+ export type EpermDecision = {
74
+ action: "exit";
75
+ code: number;
76
+ } | {
77
+ action: "stay";
78
+ reason: StayReason;
79
+ } | {
80
+ action: "ignore";
81
+ reason: "not-macos" | "stopping";
82
+ };
83
+ /** Why the daemon stays up. "exit-not-recorded": the backoff record could not be written, so an exit could loop forever. */
84
+ export type StayReason = "backoff" | "not-restartable" | "exit-not-recorded";
85
+ export interface EpermDecisionInput {
86
+ platform: NodeJS.Platform;
87
+ stopping: boolean;
88
+ /** A service manager starts the daemon again after it exits with any code (launchd KeepAlive). */
89
+ restartable: boolean;
90
+ /** Earlier EPERM exits, epoch ms. */
91
+ recentExits: readonly number[];
92
+ now: number;
93
+ maxExits?: number;
94
+ exitWindowMs?: number;
95
+ }
96
+ /** What a tripped window should do. */
97
+ export declare function decideEpermExit(input: EpermDecisionInput): EpermDecision;
98
+ export declare function readEpermExits(daemonDir: string): number[];
99
+ /** Add an exit at `now`, dropping ones older than the backoff window. */
100
+ export declare function recordEpermExit(daemonDir: string, now: number, exitWindowMs?: number): number[];
101
+ export declare function writeFilesAccessNeeded(daemonDir: string, now: number, reason: StayReason): void;
102
+ export declare function clearFilesAccessNeeded(daemonDir: string): void;
103
+ export declare function filesAccessNeeded(daemonDir: string): boolean;
104
+ /** The one structured event logged and reported per trip. Holds counts only: no paths, no file contents. */
105
+ export interface TccEpermEvent {
106
+ event: "hqd.tcc_eperm";
107
+ platform: NodeJS.Platform;
108
+ hits: number;
109
+ distinctPaths: number;
110
+ syscalls: string[];
111
+ windowMs: number;
112
+ decision: EpermDecision["action"];
113
+ reason?: string;
114
+ exitCode?: number;
115
+ exitsInWindow: number;
116
+ }
117
+ export interface TccEpermGuardDeps {
118
+ /** The HQ root hqd serves; undefined while none is configured. */
119
+ hqRoot: () => string | undefined;
120
+ platform: NodeJS.Platform;
121
+ /** The daemon's private dir (~/.hq/daemon): backoff record and status marker live here. */
122
+ daemonDir: string;
123
+ restartable: boolean;
124
+ isStopping: () => boolean;
125
+ log: (level: "info" | "warn" | "error", message: string) => void;
126
+ /** Report to Sentry; resolves once the report is flushed or given up on. */
127
+ report: (event: TccEpermEvent) => Promise<void>;
128
+ /** Stop the daemon with this exit code. */
129
+ exit: (code: number) => void;
130
+ now?: () => number;
131
+ window?: EpermWindowOptions;
132
+ maxExits?: number;
133
+ exitWindowMs?: number;
134
+ /** Throws while the HQ root cannot be read. Default: list the root. */
135
+ probe?: (hqRoot: string) => void;
136
+ /** How often a daemon that stayed up checks whether access came back. */
137
+ probeIntervalMs?: number;
138
+ /** Run `fn` every `ms`; returns a cancel. Default: an unref'd setInterval. */
139
+ schedule?: (fn: () => void, ms: number) => () => void;
140
+ }
141
+ export type TccEpermGuardState = "watching" | "exiting" | "access-needed";
142
+ export interface TccEpermGuard {
143
+ observe(err: unknown): void;
144
+ state(): TccEpermGuardState;
145
+ /** While access is needed: probe the HQ root, and on success clear the marker and watch again. True when it re-armed. */
146
+ checkAccess(): boolean;
147
+ /** Stop the access probe timer. Called when the daemon starts shutting down. */
148
+ dispose(): void;
149
+ }
150
+ /** A daemon that stayed up checks this often whether macOS gave the HQ folder back. */
151
+ export declare const TCC_EPERM_PROBE_INTERVAL_MS = 60000;
152
+ export declare function createTccEpermGuard(deps: TccEpermGuardDeps): TccEpermGuard;
153
+ //# sourceMappingURL=tcc-eperm.d.ts.map