@indigoai-us/hq-cli 5.345.212-beta.0 → 5.345.214

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 (119) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +308 -43
  4. package/dist/command-catalog.generated.js +373 -43
  5. package/dist/command-registration-plan.d.ts +15 -0
  6. package/dist/command-registration-plan.js +20 -1
  7. package/dist/commands/agent-inbox.d.ts +11 -1
  8. package/dist/commands/agent-inbox.js +128 -38
  9. package/dist/commands/agent-kit.js +2 -2
  10. package/dist/commands/agents.js +6 -1
  11. package/dist/commands/billing.js +17 -4
  12. package/dist/commands/core-handoff.js +1 -0
  13. package/dist/commands/core-hq-session-native.js +2 -2
  14. package/dist/commands/core-pin-native.js +1 -1
  15. package/dist/commands/core-policy.js +1 -1
  16. package/dist/commands/core-resolve-company-native.js +1 -1
  17. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  18. package/dist/commands/core-sentry-report-fast.js +3 -1
  19. package/dist/commands/daemon.js +68 -6
  20. package/dist/commands/files.js +2 -2
  21. package/dist/commands/integrations-api.d.ts +11 -0
  22. package/dist/commands/integrations-connect.d.ts +9 -1
  23. package/dist/commands/integrations-connect.js +154 -18
  24. package/dist/commands/integrations-core.d.ts +1 -1
  25. package/dist/commands/integrations-core.js +18 -10
  26. package/dist/commands/integrations.js +1 -1
  27. package/dist/commands/lanes-link.js +10 -5
  28. package/dist/commands/lanes.js +34 -16
  29. package/dist/commands/rescue.js +13 -0
  30. package/dist/commands/secrets.d.ts +11 -0
  31. package/dist/commands/secrets.js +41 -7
  32. package/dist/index.js +2 -0
  33. package/dist/lazy-commands.js +6 -1
  34. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  35. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  36. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  37. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  38. package/dist/lib/agent-kit/inbox-state.js +261 -4
  39. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  40. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  41. package/dist/lib/agent-kit/run/inbox.js +4 -2
  42. package/dist/lib/agent-kit/skills.js +4 -1
  43. package/dist/lib/agent-kit/wake.d.ts +9 -1
  44. package/dist/lib/agent-kit/wake.js +10 -3
  45. package/dist/lib/billing/usage-only.d.ts +4 -1
  46. package/dist/lib/billing/usage-only.js +7 -2
  47. package/dist/lib/bot/fleet-cron.js +193 -14
  48. package/dist/lib/bot/fleet-download.d.ts +2 -0
  49. package/dist/lib/bot/fleet-download.js +23 -0
  50. package/dist/lib/bot/fleet-local.d.ts +1 -0
  51. package/dist/lib/bot/fleet-local.js +41 -8
  52. package/dist/lib/capacity/ledger.d.ts +7 -0
  53. package/dist/lib/capacity/ledger.js +31 -1
  54. package/dist/lib/capacity/project.d.ts +1 -1
  55. package/dist/lib/capacity/project.js +13 -4
  56. package/dist/lib/capacity/route.d.ts +10 -0
  57. package/dist/lib/capacity/route.js +16 -0
  58. package/dist/lib/core-utils/session-id.d.ts +1 -1
  59. package/dist/lib/core-utils/session-id.js +4 -0
  60. package/dist/lib/daemon/install.d.ts +15 -0
  61. package/dist/lib/daemon/install.js +31 -0
  62. package/dist/lib/daemon/migrate.js +29 -4
  63. package/dist/lib/daemon/run.js +9 -1
  64. package/dist/lib/daemon/updater.d.ts +34 -2
  65. package/dist/lib/daemon/updater.js +51 -2
  66. package/dist/lib/doctor/__testing__/run-doctor.js +4 -0
  67. package/dist/lib/doctor/checks/jq.d.ts +27 -0
  68. package/dist/lib/doctor/checks/jq.js +82 -0
  69. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  70. package/dist/lib/doctor/checks/release-links.js +260 -24
  71. package/dist/lib/doctor/fix/apply.js +24 -8
  72. package/dist/lib/doctor/fix/remediation.js +15 -5
  73. package/dist/lib/doctor/registry.js +4 -0
  74. package/dist/lib/flag-snapshot-file.js +36 -8
  75. package/dist/lib/install/codex-targets.d.ts +52 -1
  76. package/dist/lib/install/codex-targets.js +77 -2
  77. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  78. package/dist/lib/lanes/autopilot-registry.js +59 -7
  79. package/dist/lib/lanes/links.d.ts +14 -0
  80. package/dist/lib/lanes/links.js +320 -25
  81. package/dist/lib/lanes/monitor.d.ts +4 -1
  82. package/dist/lib/lanes/monitor.js +47 -10
  83. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  84. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  85. package/dist/lib/lanes/spawn.js +8 -1
  86. package/dist/lib/lanes/watch.js +31 -0
  87. package/dist/lib/onboarding/checkpoint.d.ts +6 -0
  88. package/dist/lib/onboarding/checkpoint.js +6 -0
  89. package/dist/lib/onboarding/orchestrator.d.ts +3 -1
  90. package/dist/lib/onboarding/orchestrator.js +62 -9
  91. package/dist/lib/onboarding/types.d.ts +8 -0
  92. package/dist/lib/work-context/organize.d.ts +23 -1
  93. package/dist/lib/work-context/organize.js +25 -3
  94. package/dist/lib/work-context/reconcile.js +3 -2
  95. package/dist/main.js +3 -1
  96. package/dist/secrets-env-action.js +7 -5
  97. package/dist/sentry-init.d.ts +2 -0
  98. package/dist/sentry-init.js +13 -2
  99. package/dist/sentry.d.ts +2 -0
  100. package/dist/sentry.js +5 -1
  101. package/dist/startup-registration.js +7 -2
  102. package/dist/utils/billing-gate.d.ts +12 -16
  103. package/dist/utils/billing-gate.js +17 -18
  104. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  105. package/dist/utils/cli-network-lifecycle.js +52 -0
  106. package/dist/utils/install-tree-torn.d.ts +22 -4
  107. package/dist/utils/install-tree-torn.js +24 -0
  108. package/dist/utils/registration-plan-error.d.ts +22 -0
  109. package/dist/utils/registration-plan-error.js +27 -0
  110. package/dist/utils/safe-link.d.ts +63 -0
  111. package/dist/utils/safe-link.js +246 -0
  112. package/dist/utils/sentry-fingerprint.js +3 -0
  113. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  114. package/dist/utils/sentry-keepalive-transport.js +70 -0
  115. package/dist/utils/unauthorized-error.d.ts +36 -0
  116. package/dist/utils/unauthorized-error.js +105 -0
  117. package/dist/utils/vault-api.js +7 -5
  118. package/package.json +7 -7
  119. package/scripts/install-hook-engine.mjs +17 -0
@@ -7,13 +7,42 @@
7
7
  * mirrored item whose id is not done, oldest first. This works the same
8
8
  * whether or not the kit acks on the server (`inboxAck`), so a woken bot can
9
9
  * always drain exactly what it has not handled yet and never reply twice.
10
+ *
11
+ * An id reaches done-ids.json only after the server confirmed its ack
12
+ * (feedback 3e376c49). Until then it sits in ack-pending.json, which is
13
+ * written BEFORE the ack is sent, so a failed ack or a killed process leaves a
14
+ * durable record. The next `hq agent inbox`, `hq agent inbox done`,
15
+ * `hq_inbox_read` or `hq_inbox_done` call retries those acks. An id in
16
+ * ack-pending.json stays visible: it counts as pending for the wake check and
17
+ * is listed with `ackPending: true`, so it can never be hidden while the
18
+ * server still holds it.
19
+ *
20
+ * A permanent refusal (400/403/404) is not retried forever: the id moves
21
+ * to ack-failed.json with the reason and is recorded handled locally, and the
22
+ * next listing shows it once with `ackFailed` before it drops out. A refusal
23
+ * the `done` output already listed is recorded as shown, so it is not repeated.
24
+ *
25
+ * Every read-modify-write of these files runs under the inbox mirror lock, so
26
+ * the MCP server and a CLI call cannot drop each other's update.
10
27
  */
11
28
  import * as fs from "node:fs";
12
29
  import * as path from "node:path";
13
- import { redactAgentInboxItem, scrubInboxMirror } from "./inbox-redact.js";
14
- import { writePrivateFile } from "./private-file.js";
30
+ import { redactAgentInboxItem, scrubInboxMirror, withInboxMirrorLock } from "./inbox-redact.js";
31
+ import { mkdirPrivate, writePrivateFile } from "./private-file.js";
15
32
  const DONE_IDS_NAME = "done-ids.json";
16
33
  const MAX_DONE_IDS = 5000;
34
+ export const ACK_PENDING_NAME = "ack-pending.json";
35
+ const MAX_ACK_PENDING_IDS = 1000;
36
+ export const ACK_FAILED_NAME = "ack-failed.json";
37
+ const MAX_ACK_FAILED = 500;
38
+ /**
39
+ * Hard ceiling on ack-failed.json, the same as MAX_DONE_IDS. Past it the
40
+ * oldest records not shown yet are dropped and counted, and the next listing
41
+ * reports the count (re-review of hq-cli #2520: the file had no hard cap).
42
+ */
43
+ export const MAX_ACK_FAILED_RECORDS = MAX_DONE_IDS;
44
+ /** How long a state update waits for the inbox lock before running without it. */
45
+ const STATE_LOCK_WAIT_MS = 10_000;
17
46
  const INBOX_JSONL = "inbox.jsonl";
18
47
  export function readDoneIds(paths) {
19
48
  try {
@@ -24,7 +53,32 @@ export function readDoneIds(paths) {
24
53
  return new Set();
25
54
  }
26
55
  }
56
+ /**
57
+ * Run a state update under the inbox mirror lock (feedback 3e376c49 review:
58
+ * two processes interleaving read-modify-write could drop an id). If the lock
59
+ * cannot be taken in time the update still runs: losing a write is worse than
60
+ * a rare overlap. Not reentrant: never call a locked helper from inside `fn`.
61
+ */
62
+ function withStateLock(paths, fn) {
63
+ try {
64
+ mkdirPrivate(paths.inboxDir);
65
+ }
66
+ catch {
67
+ /* the write below reports a real filesystem fault */
68
+ }
69
+ let ran = false;
70
+ let out;
71
+ withInboxMirrorLock(paths.inboxDir, STATE_LOCK_WAIT_MS, () => {
72
+ ran = true;
73
+ out = fn();
74
+ return true;
75
+ });
76
+ return ran ? out : fn();
77
+ }
27
78
  export function markInboxDone(paths, ids) {
79
+ return withStateLock(paths, () => markInboxDoneUnlocked(paths, ids));
80
+ }
81
+ function markInboxDoneUnlocked(paths, ids) {
28
82
  const done = readDoneIds(paths);
29
83
  const added = [];
30
84
  for (const id of ids) {
@@ -36,6 +90,199 @@ export function markInboxDone(paths, ids) {
36
90
  writePrivateFile(path.join(paths.inboxDir, DONE_IDS_NAME), JSON.stringify([...done].slice(-MAX_DONE_IDS)), 0o600);
37
91
  return added;
38
92
  }
93
+ /**
94
+ * Ids marked handled by the bot whose server ack is not confirmed yet, oldest
95
+ * first. A missing or unreadable file is an empty list.
96
+ */
97
+ export function readAckPending(paths) {
98
+ try {
99
+ const raw = JSON.parse(fs.readFileSync(path.join(paths.inboxDir, ACK_PENDING_NAME), "utf8"));
100
+ return Array.isArray(raw) ? [...new Set(raw.filter((x) => typeof x === "string"))] : [];
101
+ }
102
+ catch {
103
+ return [];
104
+ }
105
+ }
106
+ function writeAckPending(paths, ids) {
107
+ writePrivateFile(path.join(paths.inboxDir, ACK_PENDING_NAME), JSON.stringify(ids.slice(-MAX_ACK_PENDING_IDS)), 0o600);
108
+ }
109
+ /** Record ids as awaiting a server ack. Call before the ack is sent. */
110
+ export function addAckPending(paths, ids) {
111
+ withStateLock(paths, () => {
112
+ const current = readAckPending(paths);
113
+ const have = new Set(current);
114
+ const next = [...current];
115
+ for (const id of ids) {
116
+ if (!have.has(id)) {
117
+ have.add(id);
118
+ next.push(id);
119
+ }
120
+ }
121
+ if (next.length !== current.length)
122
+ writeAckPending(paths, next);
123
+ });
124
+ }
125
+ /**
126
+ * The server confirmed the ack for `id`: record it as done, then drop it from
127
+ * ack-pending.json, under one lock. In that order, so a kill between the two
128
+ * writes leaves the id visible and re-acked (idempotent) rather than hidden.
129
+ */
130
+ export function confirmInboxAck(paths, id) {
131
+ return withStateLock(paths, () => {
132
+ const added = markInboxDoneUnlocked(paths, [id]).length > 0;
133
+ const current = readAckPending(paths);
134
+ if (current.includes(id))
135
+ writeAckPending(paths, current.filter((x) => x !== id));
136
+ return added;
137
+ });
138
+ }
139
+ function isAckFailedRecord(r) {
140
+ return !!r && typeof r === "object" && typeof r.id === "string" && typeof r.reason === "string";
141
+ }
142
+ function parseAckFailed(raw) {
143
+ if (Array.isArray(raw))
144
+ return { records: raw.filter(isAckFailedRecord), dropped: 0 };
145
+ if (!raw || typeof raw !== "object" || !Array.isArray(raw.records))
146
+ return undefined;
147
+ const { records, dropped } = raw;
148
+ return {
149
+ records: records.filter(isAckFailedRecord),
150
+ dropped: typeof dropped === "number" && Number.isSafeInteger(dropped) && dropped > 0 ? dropped : 0,
151
+ };
152
+ }
153
+ /**
154
+ * Read ack-failed.json. A missing file is empty. A file that cannot be read or
155
+ * parsed reads as empty too; with `moveAside` (the locked writers) it is first
156
+ * renamed to ack-failed.json.corrupt-<timestamp>, so the write that follows
157
+ * does not overwrite the records in it (re-review of hq-cli #2520).
158
+ */
159
+ function readAckFailedState(paths, moveAside) {
160
+ const file = path.join(paths.inboxDir, ACK_FAILED_NAME);
161
+ let state;
162
+ try {
163
+ state = parseAckFailed(JSON.parse(fs.readFileSync(file, "utf8")));
164
+ }
165
+ catch (err) {
166
+ if (err.code === "ENOENT")
167
+ return { records: [], dropped: 0 };
168
+ }
169
+ if (state)
170
+ return state;
171
+ if (moveAside)
172
+ moveAsideUnreadable(file);
173
+ return { records: [], dropped: 0 };
174
+ }
175
+ function moveAsideUnreadable(file) {
176
+ // No ":" in the name: it is not allowed in a Windows file name.
177
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
178
+ let target = `${file}.corrupt-${stamp}`;
179
+ for (let n = 1; fs.existsSync(target); n++)
180
+ target = `${file}.corrupt-${stamp}-${n}`;
181
+ try {
182
+ fs.renameSync(file, target);
183
+ }
184
+ catch {
185
+ /* the write that follows reports a real filesystem fault */
186
+ }
187
+ }
188
+ export function readAckFailed(paths) {
189
+ return readAckFailedState(paths, false).records;
190
+ }
191
+ /**
192
+ * Write ack-failed.json. Past MAX_ACK_FAILED records the oldest records
193
+ * already shown are trimmed first, so up to MAX_ACK_PENDING_IDS refusals
194
+ * before one listing all reach the caller (recheck of hq-cli #2520: 600
195
+ * pending ids refused with 403 lost 100). Past the hard ceiling
196
+ * MAX_ACK_FAILED_RECORDS the oldest records not shown yet are dropped too,
197
+ * and counted in `dropped` for the next listing to report.
198
+ */
199
+ function writeAckFailed(paths, state) {
200
+ let records = state.records;
201
+ let excess = records.length - MAX_ACK_FAILED;
202
+ if (excess > 0) {
203
+ records = records.filter((r) => {
204
+ if (excess > 0 && r.reported) {
205
+ excess -= 1;
206
+ return false;
207
+ }
208
+ return true;
209
+ });
210
+ }
211
+ let dropped = state.dropped;
212
+ let over = records.length - MAX_ACK_FAILED_RECORDS;
213
+ if (over > 0) {
214
+ records = records.filter((r) => {
215
+ if (over > 0 && !r.reported) {
216
+ over -= 1;
217
+ dropped += 1;
218
+ return false;
219
+ }
220
+ return true;
221
+ });
222
+ }
223
+ writePrivateFile(path.join(paths.inboxDir, ACK_FAILED_NAME), JSON.stringify({ version: 1, dropped, records }), 0o600);
224
+ }
225
+ /**
226
+ * The server refused these acks permanently (400/403/404). Stop retrying
227
+ * them: record them in ack-failed.json with the reason, record them handled
228
+ * locally (the bot already answered them), and drop them from
229
+ * ack-pending.json, all in one locked read and one write per file. With
230
+ * `reported`, the caller has already shown them (the `done` output lists the
231
+ * refused ids), so no listing repeats them; otherwise the next listing shows
232
+ * each once with its reason.
233
+ */
234
+ export function recordAckFailures(paths, failures, options = {}) {
235
+ if (failures.length === 0)
236
+ return;
237
+ const at = (options.now ?? new Date()).toISOString();
238
+ const latest = new Map(failures.map((f) => [f.id, f.reason]));
239
+ withStateLock(paths, () => {
240
+ const state = readAckFailedState(paths, true);
241
+ const added = [...latest].map(([id, reason]) => ({ id, reason, at, ...(options.reported ? { reported: true } : {}) }));
242
+ writeAckFailed(paths, { records: [...state.records.filter((r) => !latest.has(r.id)), ...added], dropped: state.dropped });
243
+ markInboxDoneUnlocked(paths, [...latest.keys()]);
244
+ const current = readAckPending(paths);
245
+ if (current.some((id) => latest.has(id)))
246
+ writeAckPending(paths, current.filter((x) => !latest.has(x)));
247
+ });
248
+ }
249
+ /** One refused ack; see recordAckFailures. The next listing shows it once. */
250
+ export function recordAckFailed(paths, id, reason, now = new Date()) {
251
+ recordAckFailures(paths, [{ id, reason }], { now });
252
+ }
253
+ /**
254
+ * Most refused acks one listing takes. A pretty-printed record is about 130 to
255
+ * 290 characters (the id length varies), so 100 come to at most about 30,000,
256
+ * inside hq_inbox_read's 40,000-character clamp next to the rest of the
257
+ * listing. The remainder stays unreported for the next read instead of being
258
+ * retired unseen (recheck of hq-cli #2520).
259
+ */
260
+ export const ACK_FAILED_LISTING_LIMIT = 100;
261
+ /**
262
+ * Permanently refused acks not shown yet, oldest first and at most `limit` of
263
+ * them, marked as shown. A listing calls this once, so each one is visible
264
+ * exactly once with its reason; any beyond `limit` wait for the next listing.
265
+ * `more` and `dropped` are read inside the same lock, so they are exact.
266
+ */
267
+ export function takeAckFailureListing(paths, limit = ACK_FAILED_LISTING_LIMIT) {
268
+ return withStateLock(paths, () => {
269
+ const state = readAckFailedState(paths, true);
270
+ const unshown = state.records.filter((r) => !r.reported);
271
+ const taken = new Set(unshown.slice(0, Math.max(0, limit)));
272
+ if (taken.size > 0 || state.dropped > 0) {
273
+ writeAckFailed(paths, { records: state.records.map((r) => (taken.has(r) ? { ...r, reported: true } : r)), dropped: 0 });
274
+ }
275
+ return {
276
+ ackFailed: [...taken].map(({ reported: _reported, ...r }) => r),
277
+ more: unshown.length - taken.size,
278
+ dropped: state.dropped,
279
+ };
280
+ });
281
+ }
282
+ /** How many permanently refused acks have not been shown yet. */
283
+ export function countUnreportedAckFailures(paths) {
284
+ return readAckFailed(paths).filter((r) => !r.reported).length;
285
+ }
39
286
  /** Every mirrored entry, oldest first, de-duplicated by id (last write wins). */
40
287
  export function readMirroredInbox(paths) {
41
288
  // Files written before credential redaction are rewritten here. A failed
@@ -70,9 +317,14 @@ export function readMirroredInbox(paths) {
70
317
  }
71
318
  return [...byId.values()];
72
319
  }
320
+ /**
321
+ * Mirrored items the wake check and the listings treat as pending: not done,
322
+ * or handled but with a server ack still unconfirmed (ack-pending.json).
323
+ */
73
324
  export function pendingInbox(paths) {
74
325
  const done = readDoneIds(paths);
75
- return readMirroredInbox(paths).filter((e) => !done.has(e.id));
326
+ const ackPending = new Set(readAckPending(paths));
327
+ return readMirroredInbox(paths).filter((e) => !done.has(e.id) || ackPending.has(e.id));
76
328
  }
77
329
  /**
78
330
  * The file references on an inbox entry (a mirrored kit entry or a bot
@@ -116,7 +368,7 @@ export function inboxEntryAttachments(e) {
116
368
  * as a bot is concerned — omitting them made an agent answer "no image came
117
369
  * through" for a DM that carried a screenshot.
118
370
  */
119
- export function summarizeInboxEntry(e, done) {
371
+ export function summarizeInboxEntry(e, done, ackPending = false, ackFailed) {
120
372
  const pick = (...keys) => {
121
373
  for (const k of keys)
122
374
  if (typeof e[k] === "string" && e[k])
@@ -136,6 +388,11 @@ export function summarizeInboxEntry(e, done) {
136
388
  text: pick("text", "body"),
137
389
  ...(attachments.length ? { attachments } : {}),
138
390
  done,
391
+ // Handled by the bot, but the server has not confirmed the ack yet. Do not
392
+ // reply again; `hq agent inbox done <id>` (or hq_inbox_done) retries it.
393
+ ...(ackPending ? { ackPending: true } : {}),
394
+ // The server refused this ack permanently; it is not retried. Shown once.
395
+ ...(ackFailed ? { ackFailed } : {}),
139
396
  };
140
397
  }
141
398
  /** Notes for a server inbox body that cannot certify a complete read. */
@@ -16,7 +16,7 @@
16
16
  * tool result.
17
17
  */
18
18
  import type { ExternalMachineCreds } from "../creds.js";
19
- import { type FetchServerInboxDeps } from "../inbox-fetch.js";
19
+ import { type AckServerInboxDeps, type FetchServerInboxDeps } from "../inbox-fetch.js";
20
20
  import type { AgentKitPaths } from "../paths.js";
21
21
  import { type McpTool } from "./jsonrpc.js";
22
22
  export interface HqRunResult {
@@ -63,8 +63,8 @@ export interface McpToolClients {
63
63
  body: unknown;
64
64
  retryAfterSeconds?: number;
65
65
  }>;
66
- /** Test seam for hq_inbox_read's bounded retry (sleep, jitter source, per-attempt deadline). */
67
- inboxRetry?: Pick<FetchServerInboxDeps, "sleep" | "random" | "timeoutMs">;
66
+ /** Test seam for the bounded retry in hq_inbox_read and hq_inbox_done (sleep, jitter source, per-attempt and batch deadline). */
67
+ inboxRetry?: Pick<FetchServerInboxDeps, "sleep" | "random" | "timeoutMs"> & Pick<AckServerInboxDeps, "deadlineMs">;
68
68
  }
69
69
  export declare function clampOutput(text: string, max?: number): string;
70
70
  /** Vault paths are company-anchored and must not escape. */
@@ -19,15 +19,20 @@ import { CLI_VERSION } from "../../../cli-version.js";
19
19
  import { peekIdToken } from "../../../utils/id-token.js";
20
20
  import { PERSON_AGENT_AUDIENCE_MESSAGE, callerMayUseAudience, defaultAudienceFor, isAgentUid, isRecipientUid } from "../../../lib/notify-recipient.js";
21
21
  import { tokenIsMachinePrincipal } from "../../../lib/caller-principal.js";
22
- import { annotateInboxAttempts, fetchServerInboxWithRetry, resolveAgentInboxTimeoutMs } from "../inbox-fetch.js";
22
+ import { AGENT_INBOX_READ_BUDGET_MS, annotateInboxAttempts, completeInboxItems, fetchServerInboxWithinBudget, formatInboxAckFailure, resolveAgentInboxAckDeadlineMs, resolveAgentInboxTimeoutMs, retryPendingInboxAcks, } from "../inbox-fetch.js";
23
23
  import { redactAgentInboxItem } from "../inbox-redact.js";
24
- import { markInboxDone, mergeAgentInbox, readDoneIds, summarizeInboxEntry } from "../inbox-state.js";
24
+ import { mergeAgentInbox, readAckPending, readDoneIds, summarizeInboxEntry, takeAckFailureListing } from "../inbox-state.js";
25
25
  import { AttachmentCompanyUnresolvedError, fetchChatAttachment } from "./attachments.js";
26
26
  import { errorResult, McpToolInputError, textResult } from "./jsonrpc.js";
27
27
  const MAX_TOOL_OUTPUT_CHARS = 40_000;
28
28
  const ATTACHMENTS_HINT = "Some messages carry files. For each entry in a message's `attachments` whose vaultPath starts with chat/attachments/, " +
29
29
  "call hq_attachment_fetch with that vaultPath and companyUid to download it; hq_files_read cannot open message attachments. " +
30
30
  "Anything else (a folder or shared vault path) is not a chat attachment: use hq_files_list / hq_files_read for those.";
31
+ const ACK_PENDING_HINT = "Messages with ackPending: true were already handled, but the server has not confirmed the ack yet. Do not reply to them again; " +
32
+ "call hq_inbox_done with their ids to retry the ack (repeating it is safe).";
33
+ const ACK_FAILED_HINT = "The server permanently refused the ack for the ackFailed items (reason given). They were already handled: do not reply again. " +
34
+ "They are not retried and are listed only this once. When ackFailedMore is set, that many more are listed by the next read. " +
35
+ "When ackFailedDropped is set, that many older refusals were dropped without being listed (too many were waiting); those items were handled too.";
31
36
  function str(args, key, opts = {}) {
32
37
  const v = args[key];
33
38
  if (v === undefined || v === null) {
@@ -79,6 +84,17 @@ function fromRun(r, label) {
79
84
  export function buildAgentMcpTools(clients) {
80
85
  const { creds } = clients;
81
86
  const company = creds.companySlug;
87
+ /** Bounded, once-retried ack of one inbox id, under one batch deadline (feedback 3e376c49). */
88
+ const inboxAckDeps = () => ({
89
+ timeoutMs: resolveAgentInboxTimeoutMs(process.env),
90
+ deadlineMs: resolveAgentInboxAckDeadlineMs(process.env),
91
+ ...clients.inboxRetry,
92
+ mint: (signal) => clients.getToken(signal),
93
+ post: (token, id, signal) => clients.apiJson(token, `/v1/agents/${encodeURIComponent(creds.entityUid)}/inbox/${encodeURIComponent(id)}/ack`, {
94
+ method: "POST",
95
+ signal,
96
+ }),
97
+ });
82
98
  return [
83
99
  {
84
100
  name: "hq_whoami",
@@ -286,16 +302,28 @@ export function buildAgentMcpTools(clients) {
286
302
  handler: async (args) => {
287
303
  const limit = int(args, "limit", { min: 1, max: 100, fallback: 20 });
288
304
  const includeDone = args.include_done === true;
305
+ // Feedback 3e376c49: first retry acks an earlier hq_inbox_done could
306
+ // not confirm, so the server does not keep holding a handled item.
307
+ // The whole call stays inside AGENT_INBOX_READ_BUDGET_MS (45 s), under
308
+ // the 60 s tool timeout MCP clients commonly apply.
309
+ const readStartedAt = Date.now();
310
+ const ackRetry = await retryPendingInboxAcks(clients.paths, inboxAckDeps());
289
311
  const done = readDoneIds(clients.paths);
312
+ const ackPending = new Set(readAckPending(clients.paths));
313
+ // Acks the server refused permanently: shown once with the reason, never
314
+ // retried. At most ACK_FAILED_LISTING_LIMIT per read, so the list always
315
+ // fits the output clamp; the rest are left for the next read.
316
+ const { ackFailed, more: ackFailedMore, dropped: ackFailedDropped } = takeAckFailureListing(clients.paths);
317
+ const ackFailedById = new Map(ackFailed.map((f) => [f.id, f.reason]));
290
318
  // Same bounded, once-retried server read as `hq agent inbox`.
291
319
  let attempts = 1;
292
320
  const merged = await mergeAgentInbox(clients.paths, async () => {
293
- const outcome = await fetchServerInboxWithRetry({
321
+ const outcome = await fetchServerInboxWithinBudget({
294
322
  timeoutMs: resolveAgentInboxTimeoutMs(process.env),
295
323
  ...clients.inboxRetry,
296
324
  mint: (signal) => clients.getToken(signal),
297
325
  fetch: (token, signal) => clients.apiJson(token, `/v1/agents/${encodeURIComponent(creds.entityUid)}/inbox`, { signal }),
298
- });
326
+ }, AGENT_INBOX_READ_BUDGET_MS - (Date.now() - readStartedAt));
299
327
  attempts = outcome.attempts;
300
328
  if (!outcome.ok)
301
329
  throw outcome.error;
@@ -303,19 +331,30 @@ export function buildAgentMcpTools(clients) {
303
331
  });
304
332
  const { entries, note: serverNote, source, stale, attempts: attemptsMade } = annotateInboxAttempts(merged, attempts);
305
333
  const byId = new Map(entries.map((e) => [e.id, e]));
334
+ // An item whose ack is unconfirmed stays listed with ackPending: true.
306
335
  const rows = [...byId.values()]
307
- .filter((e) => includeDone || !done.has(e.id))
336
+ .filter((e) => includeDone || !done.has(e.id) || ackPending.has(e.id) || ackFailedById.has(e.id))
308
337
  .slice(0, limit)
309
- .map((e) => summarizeInboxEntry(redactAgentInboxItem(e), done.has(e.id)));
338
+ .map((e) => summarizeInboxEntry(redactAgentInboxItem(e), done.has(e.id) && !ackPending.has(e.id), ackPending.has(e.id), ackFailedById.get(e.id)));
310
339
  const hasFiles = rows.some((r) => r.attachments?.length);
340
+ // clampOutput cuts from the end, and the ackFailed records above are
341
+ // already marked reported. So the ack state and the notes go ahead of
342
+ // `messages`: long messages can be truncated, but a permanent refusal
343
+ // is never retired unseen (recheck of hq-cli #2520, minor 1).
311
344
  return textResult(clampOutput(JSON.stringify({
312
345
  count: rows.length,
313
346
  source,
314
347
  stale,
315
348
  ...(attemptsMade !== undefined ? { attempts: attemptsMade } : {}),
316
- messages: rows,
349
+ ...(ackFailed.length ? { ackFailed } : {}),
350
+ ...(ackFailed.length || ackFailedDropped > 0 ? { ackFailedHint: ACK_FAILED_HINT } : {}),
351
+ ...(ackFailedMore > 0 ? { ackFailedMore } : {}),
352
+ ...(ackFailedDropped > 0 ? { ackFailedDropped } : {}),
353
+ ...(ackPending.size ? { ackPending: [...ackPending], ackPendingHint: ACK_PENDING_HINT } : {}),
354
+ ...(ackRetry?.acked.length ? { ackRetried: ackRetry.acked } : {}),
317
355
  ...(serverNote ? { note: serverNote } : {}),
318
356
  ...(hasFiles ? { attachmentsHint: ATTACHMENTS_HINT } : {}),
357
+ messages: rows,
319
358
  }, null, 2)));
320
359
  },
321
360
  },
@@ -366,7 +405,7 @@ export function buildAgentMcpTools(clients) {
366
405
  },
367
406
  {
368
407
  name: "hq_inbox_done",
369
- description: "Mark inbox items handled (after replying) so they stop showing as pending and the wake hook stops retrying.",
408
+ description: "Mark inbox items handled (after replying) so they stop showing as pending and the wake hook stops retrying. An item is recorded handled only once the server confirms its ack; an unconfirmed one is reported (complete: false, ackPending), stays listed with ackPending: true, and is retried by the next hq_inbox_read or hq_inbox_done.",
370
409
  inputSchema: {
371
410
  type: "object",
372
411
  properties: { ids: { type: "array", items: { type: "string" }, description: "Item ids from hq_inbox_read" } },
@@ -379,23 +418,27 @@ export function buildAgentMcpTools(clients) {
379
418
  if (!/^[A-Za-z0-9._:-]{1,200}$/.test(id))
380
419
  throw new McpToolInputError(`invalid id ${JSON.stringify(id)}`);
381
420
  }
382
- const added = markInboxDone(clients.paths, ids);
383
- const acked = [];
384
- const failed = [];
385
- try {
386
- const token = await clients.getToken();
387
- for (const id of ids) {
388
- const res = await clients.apiJson(token, `/v1/agents/${encodeURIComponent(creds.entityUid)}/inbox/${encodeURIComponent(id)}/ack`, { method: "POST" });
389
- if (res.status >= 200 && res.status < 300)
390
- acked.push(id);
391
- else
392
- failed.push(`${id} (${res.status})`);
393
- }
394
- }
395
- catch (err) {
396
- failed.push(`ack skipped: ${err instanceof Error ? err.message : String(err)}`);
397
- }
398
- return textResult(JSON.stringify({ marked: added.length, alreadyDone: ids.length - added.length, serverAcked: acked.length, ...(failed.length ? { ackFailures: failed } : {}) }, null, 2));
421
+ // Same flow as `hq agent inbox done` (feedback 3e376c49): an id is
422
+ // recorded done only after its ack is confirmed; until then it is kept
423
+ // in ack-pending.json, stays listed, and is retried by the next read or
424
+ // done. `complete: false` means a requested ack is not confirmed;
425
+ // calling this again is safe because the server ack is idempotent.
426
+ const result = await completeInboxItems(clients.paths, ids, inboxAckDeps());
427
+ return textResult(JSON.stringify({
428
+ marked: result.marked.length,
429
+ alreadyDone: result.alreadyDone.length,
430
+ serverAcked: result.acked.length - result.retriedAcked.length,
431
+ complete: result.requestedComplete,
432
+ ...(result.retriedAcked.length ? { retriedAcked: result.retriedAcked } : {}),
433
+ // ackFailures keeps the strings this tool always returned
434
+ // ("<id> (<status>)", "ack skipped: …"); ackFailureDetails is the
435
+ // structured form, the same as `hq agent inbox done --json`.
436
+ ...(result.failed.length
437
+ ? { ackFailures: result.failed.map(formatInboxAckFailure), ackFailureDetails: result.failed }
438
+ : {}),
439
+ ...(result.ackPending.length ? { ackPending: result.ackPending } : {}),
440
+ ...(result.ackFailed.length ? { ackFailed: result.ackFailed } : {}),
441
+ }, null, 2));
399
442
  },
400
443
  },
401
444
  {
@@ -20,7 +20,7 @@ import * as fs from "node:fs";
20
20
  import * as path from "node:path";
21
21
  import { vaultApiFetch } from "../../../utils/vault-api.js";
22
22
  import { writeComponentStatus } from "../creds.js";
23
- import { pendingInbox } from "../inbox-state.js";
23
+ import { pendingInbox, readAckPending } from "../inbox-state.js";
24
24
  import { redactAgentInboxItem, scrubInboxMirror, withInboxMirrorLock } from "../inbox-redact.js";
25
25
  import { mkdirPrivate, writePrivateFile } from "./../private-file.js";
26
26
  import { createAgentKitInboxBackoffFlagReader } from "../inbox-poll-backoff-flag.js";
@@ -278,7 +278,9 @@ async function maybeWake(deps, freshCount) {
278
278
  const reason = shouldWake(config, currentWakeState(deps.paths), freshCount, pending.length, now);
279
279
  if (!reason)
280
280
  return;
281
- const notice = buildWakeNotice(deps.agentUid, reason, pending.map((e) => e.id), now);
281
+ // Ids handled but not yet acked are marked, so a URL-wake bot acting on
282
+ // messageIds alone does not answer them twice (feedback 3e376c49 review).
283
+ const notice = buildWakeNotice(deps.agentUid, reason, pending.map((e) => e.id), now, readAckPending(deps.paths));
282
284
  try {
283
285
  await (deps.fireWake ?? fireWake)(config, notice, { paths: deps.paths, agentUid: deps.agentUid, log: deps.log, now: deps.now, resolveHeaderSecrets: createWakeSecretResolver(deps.companySlug, deps.getToken, deps.apiBaseUrl) });
284
286
  }
@@ -34,9 +34,12 @@ mentions, jobs). Work through them like this:
34
34
  hq agent inbox # pending messages, oldest first (id, sender uid, channelId, text)
35
35
  hq dm <channelId> "reply" # message came from a channel or group: answer in it
36
36
  hq dm <sender-uid> "reply" # otherwise: answer the sender privately
37
- hq agent inbox done <id> [id…] # mark handled so it is never answered twice
37
+ hq agent inbox done <id> [id…] # mark handled so it is never answered twice (exit 3 = server ack not confirmed; it is retried)
38
38
  \`\`\`
39
39
 
40
+ An item listed with \`ackPending: true\` ("handled; server ack not confirmed") was already
41
+ answered: do not reply again. Run \`hq agent inbox done <id>\` to retry its ack.
42
+
40
43
  Reply where the message arrived. A message with a \`channelId\` was posted in a
41
44
  channel or group DM, and the answer belongs there, not in a private DM to the
42
45
  sender. Do not reply to another bot's greeting, thanks or sign-off that asks
@@ -45,10 +45,18 @@ export interface WakeNotice {
45
45
  reason: "new" | "retry" | "test";
46
46
  pending: number;
47
47
  messageIds: string[];
48
+ /**
49
+ * Ids in messageIds that the bot already handled but whose server ack is
50
+ * not confirmed yet (ack-pending.json). Do not reply to these again; run
51
+ * `hq agent inbox done <id>` to retry the ack. Absent when there are none.
52
+ */
53
+ ackPending?: string[];
48
54
  at: string;
49
55
  instructions: string;
50
56
  }
51
57
  export declare const WAKE_INSTRUCTIONS: string;
58
+ /** Added when the notice lists ids whose server ack is not confirmed yet. */
59
+ export declare const WAKE_ACK_PENDING_INSTRUCTIONS: string;
52
60
  export declare function wakePath(paths: Pick<AgentKitPaths, "agentDir">): string;
53
61
  export declare function validateWakeUrl(raw: string): string;
54
62
  /** Origin plus a masked path: enough to recognise, not enough to call. */
@@ -67,7 +75,7 @@ export interface WakeDeps {
67
75
  spawnImpl?: typeof spawn;
68
76
  pidAlive?: (pid: number | undefined) => boolean;
69
77
  }
70
- export declare function buildWakeNotice(agentUid: string, reason: WakeNotice["reason"], ids: string[], now: Date): WakeNotice;
78
+ export declare function buildWakeNotice(agentUid: string, reason: WakeNotice["reason"], ids: string[], now: Date, ackPendingIds?: readonly string[]): WakeNotice;
71
79
  /**
72
80
  * Decide whether to wake now: always on new mail, otherwise only when items
73
81
  * are still pending and the last wake is older than retryMs.
@@ -59,6 +59,9 @@ export const WAKE_INSTRUCTIONS = "New HQ messages are waiting. Run `hq agent inb
59
59
  "arrived: if it has a channelId, post in that channel with `hq dm <channelId> \"…\"`; otherwise reply to the " +
60
60
  "sender with `hq dm <sender-uid> \"…\"` (or hq_dm_send). Do not reply to another bot's greeting, thanks or " +
61
61
  "sign-off that asks for nothing. Then mark each handled with `hq agent inbox done <id>` (or hq_inbox_done).";
62
+ /** Added when the notice lists ids whose server ack is not confirmed yet. */
63
+ export const WAKE_ACK_PENDING_INSTRUCTIONS = "Ids in ackPending were already answered; their server ack is not confirmed. Do not reply to them again: " +
64
+ "run `hq agent inbox done <id>` (or hq_inbox_done) to retry the ack.";
62
65
  export function wakePath(paths) {
63
66
  return path.join(paths.agentDir, WAKE_FILE_NAME);
64
67
  }
@@ -160,15 +163,19 @@ function pidAlive(pid) {
160
163
  return false;
161
164
  }
162
165
  }
163
- export function buildWakeNotice(agentUid, reason, ids, now) {
166
+ export function buildWakeNotice(agentUid, reason, ids, now, ackPendingIds = []) {
167
+ const messageIds = ids.slice(0, 50);
168
+ const ackPendingSet = new Set(ackPendingIds);
169
+ const ackPending = messageIds.filter((id) => ackPendingSet.has(id));
164
170
  return {
165
171
  event: "hq.inbox.pending",
166
172
  agentUid,
167
173
  reason,
168
174
  pending: ids.length,
169
- messageIds: ids.slice(0, 50),
175
+ messageIds,
176
+ ...(ackPending.length ? { ackPending } : {}),
170
177
  at: now.toISOString(),
171
- instructions: WAKE_INSTRUCTIONS,
178
+ instructions: ackPending.length ? `${WAKE_INSTRUCTIONS} ${WAKE_ACK_PENDING_INSTRUCTIONS}` : WAKE_INSTRUCTIONS,
172
179
  };
173
180
  }
174
181
  /**
@@ -127,7 +127,10 @@ export declare function usageIncludedSentence(card?: UsageCard): string;
127
127
  export declare function usageOnlyUpgradeLines(card?: UsageCard): string[];
128
128
  /** The `Plan:` orientation line (`hq whoami --plan`) for a usage-only company. */
129
129
  export declare function usageOnlyPlanLine(card?: UsageCard): string;
130
- /** Agent boxes on usage pricing, priced by size from the card. */
130
+ /**
131
+ * Agent boxes on usage pricing, priced by size from the card, plus the
132
+ * agent-run meter when the card lists one.
133
+ */
131
134
  export declare function usageOnlyBoxSentence(card?: UsageCard): string;
132
135
  /**
133
136
  * A refusal that a legacy account answers by upgrading its plan. On usage
@@ -331,9 +331,14 @@ export function usageOnlyPlanLine(card = BUNDLED_USAGE_CARD) {
331
331
  return (`Plan: usage pricing — ${formatCardUsd(card.includedUsd)} of usage included each month. ` +
332
332
  "See `hq billing usage`.");
333
333
  }
334
- /** Agent boxes on usage pricing, priced by size from the card. */
334
+ /**
335
+ * Agent boxes on usage pricing, priced by size from the card, plus the
336
+ * agent-run meter when the card lists one.
337
+ */
335
338
  export function usageOnlyBoxSentence(card = BUNDLED_USAGE_CARD) {
336
- return `Agent boxes on usage pricing are billed by size: ${formatBoxQuotes(card)}.`;
339
+ const run = card.meters.find((m) => m.id === "agent-run");
340
+ const perRun = run ? `, plus ${formatCardUsd(run.unitUsd)} per agent run` : "";
341
+ return `Agent boxes on usage pricing are billed by size: ${formatBoxQuotes(card)}${perRun}.`;
337
342
  }
338
343
  /**
339
344
  * A refusal that a legacy account answers by upgrading its plan. On usage