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

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 (161) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +442 -50
  4. package/dist/command-catalog.generated.js +541 -50
  5. package/dist/commands/agent-inbox.d.ts +11 -1
  6. package/dist/commands/agent-inbox.js +128 -38
  7. package/dist/commands/agent-kit.js +2 -2
  8. package/dist/commands/agents.d.ts +51 -1
  9. package/dist/commands/agents.js +154 -2
  10. package/dist/commands/bot-jobs.d.ts +2 -15
  11. package/dist/commands/bot-jobs.js +2 -94
  12. package/dist/commands/bot-runtime.d.ts +46 -5
  13. package/dist/commands/bot-runtime.js +228 -18
  14. package/dist/commands/bot.d.ts +16 -9
  15. package/dist/commands/bot.js +169 -51
  16. package/dist/commands/cloud.d.ts +66 -13
  17. package/dist/commands/cloud.js +120 -39
  18. package/dist/commands/company-restore.d.ts +23 -0
  19. package/dist/commands/company-restore.js +128 -0
  20. package/dist/commands/company.js +2 -0
  21. package/dist/commands/core-handoff.js +1 -0
  22. package/dist/commands/core-hq-session-native.js +2 -2
  23. package/dist/commands/core-pin-native.js +1 -1
  24. package/dist/commands/core-policy.js +1 -1
  25. package/dist/commands/core-resolve-company-native.js +1 -1
  26. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  27. package/dist/commands/core-sentry-report-fast.js +3 -1
  28. package/dist/commands/daemon.js +11 -1
  29. package/dist/commands/integrations-connect.d.ts +17 -4
  30. package/dist/commands/integrations-connect.js +224 -26
  31. package/dist/commands/lanes-link.js +10 -5
  32. package/dist/commands/lanes.js +26 -9
  33. package/dist/commands/rescue.js +13 -0
  34. package/dist/commands/secrets.d.ts +11 -0
  35. package/dist/commands/secrets.js +41 -7
  36. package/dist/commands/sources.js +6 -0
  37. package/dist/commands/storage-offload.d.ts +12 -0
  38. package/dist/commands/storage-offload.js +41 -3
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/index.js +2 -0
  42. package/dist/lazy-commands.js +2 -0
  43. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  44. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  45. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  46. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  47. package/dist/lib/agent-kit/inbox-state.js +261 -4
  48. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  49. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  50. package/dist/lib/agent-kit/run/inbox.js +4 -2
  51. package/dist/lib/agent-kit/skills.js +4 -1
  52. package/dist/lib/agent-kit/wake.d.ts +9 -1
  53. package/dist/lib/agent-kit/wake.js +10 -3
  54. package/dist/lib/bot/config.d.ts +1 -0
  55. package/dist/lib/bot/config.js +10 -0
  56. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  57. package/dist/lib/bot/eventbridge-cron.js +104 -0
  58. package/dist/lib/bot/fleet-cron.js +193 -14
  59. package/dist/lib/bot/fleet-download.d.ts +2 -0
  60. package/dist/lib/bot/fleet-download.js +23 -0
  61. package/dist/lib/bot/fleet-local.d.ts +34 -1
  62. package/dist/lib/bot/fleet-local.js +254 -37
  63. package/dist/lib/bot/fleet-python.d.ts +3 -0
  64. package/dist/lib/bot/fleet-python.js +34 -4
  65. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  66. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  67. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  68. package/dist/lib/bot/legacy-provider-login.js +19 -2
  69. package/dist/lib/bot/prompt.js +1 -1
  70. package/dist/lib/bot/readiness.d.ts +8 -0
  71. package/dist/lib/bot/readiness.js +17 -3
  72. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  73. package/dist/lib/bot/runtime-auth.js +94 -3
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  76. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  77. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  78. package/dist/lib/capacity/collectors/grok.js +56 -5
  79. package/dist/lib/core-utils/session-id.d.ts +1 -1
  80. package/dist/lib/core-utils/session-id.js +4 -0
  81. package/dist/lib/daemon/catalog.js +11 -1
  82. package/dist/lib/daemon/run.js +9 -1
  83. package/dist/lib/daemon/updater.d.ts +34 -2
  84. package/dist/lib/daemon/updater.js +51 -2
  85. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  86. package/dist/lib/db/sqlite-binding.js +1 -1
  87. package/dist/lib/delivery/artifacts.d.ts +99 -0
  88. package/dist/lib/delivery/artifacts.js +548 -0
  89. package/dist/lib/delivery/backup.d.ts +78 -0
  90. package/dist/lib/delivery/backup.js +343 -0
  91. package/dist/lib/delivery/cache.d.ts +29 -0
  92. package/dist/lib/delivery/cache.js +33 -0
  93. package/dist/lib/delivery/contracts.d.ts +142 -0
  94. package/dist/lib/delivery/contracts.js +289 -0
  95. package/dist/lib/delivery/credentials.d.ts +54 -0
  96. package/dist/lib/delivery/credentials.js +119 -0
  97. package/dist/lib/delivery/enrollment.d.ts +142 -0
  98. package/dist/lib/delivery/enrollment.js +382 -0
  99. package/dist/lib/delivery/identity.d.ts +25 -0
  100. package/dist/lib/delivery/identity.js +82 -0
  101. package/dist/lib/delivery/inbox.d.ts +116 -0
  102. package/dist/lib/delivery/inbox.js +260 -0
  103. package/dist/lib/delivery/migrations.d.ts +139 -0
  104. package/dist/lib/delivery/migrations.js +623 -0
  105. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  106. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  107. package/dist/lib/delivery/mqtt.d.ts +61 -0
  108. package/dist/lib/delivery/mqtt.js +112 -0
  109. package/dist/lib/delivery/outbox.d.ts +95 -0
  110. package/dist/lib/delivery/outbox.js +187 -0
  111. package/dist/lib/delivery/provenance.d.ts +129 -0
  112. package/dist/lib/delivery/provenance.js +93 -0
  113. package/dist/lib/delivery/reconciler.d.ts +151 -0
  114. package/dist/lib/delivery/reconciler.js +492 -0
  115. package/dist/lib/delivery/restore.d.ts +35 -0
  116. package/dist/lib/delivery/restore.js +134 -0
  117. package/dist/lib/delivery/store.d.ts +161 -0
  118. package/dist/lib/delivery/store.js +940 -0
  119. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  120. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  121. package/dist/lib/delivery/workers/macos.d.ts +176 -0
  122. package/dist/lib/delivery/workers/macos.js +901 -0
  123. package/dist/lib/delivery/workers/windows-boundary.d.ts +453 -0
  124. package/dist/lib/delivery/workers/windows-boundary.js +693 -0
  125. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  126. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  127. package/dist/lib/delivery/workers/windows.d.ts +241 -0
  128. package/dist/lib/delivery/workers/windows.js +608 -0
  129. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  130. package/dist/lib/doctor/checks/release-links.js +260 -24
  131. package/dist/lib/doctor/fix/apply.js +24 -8
  132. package/dist/lib/doctor/fix/remediation.js +15 -5
  133. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  134. package/dist/lib/install/provider-wrappers.js +68 -3
  135. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  136. package/dist/lib/lanes/autopilot-registry.js +59 -7
  137. package/dist/lib/lanes/links.d.ts +14 -0
  138. package/dist/lib/lanes/links.js +320 -25
  139. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  140. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  141. package/dist/main.js +3 -1
  142. package/dist/sentry-init.d.ts +2 -0
  143. package/dist/sentry-init.js +13 -2
  144. package/dist/sentry.d.ts +2 -0
  145. package/dist/sentry.js +5 -1
  146. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  147. package/dist/utils/cli-network-lifecycle.js +52 -0
  148. package/dist/utils/cognito-callback-port.d.ts +14 -0
  149. package/dist/utils/cognito-callback-port.js +24 -0
  150. package/dist/utils/cognito-session.js +3 -3
  151. package/dist/utils/deleted-company-notice.d.ts +59 -0
  152. package/dist/utils/deleted-company-notice.js +156 -0
  153. package/dist/utils/login-browser.d.ts +1 -1
  154. package/dist/utils/login-browser.js +7 -5
  155. package/dist/utils/resident-package-preload.js +30 -15
  156. package/dist/utils/safe-link.d.ts +63 -0
  157. package/dist/utils/safe-link.js +246 -0
  158. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  159. package/dist/utils/sentry-keepalive-transport.js +70 -0
  160. package/dist/utils/vault-api.js +7 -0
  161. package/package.json +7 -7
@@ -25,6 +25,7 @@ import * as fs from "node:fs";
25
25
  import * as path from "node:path";
26
26
  import { InvalidArgumentError } from "commander";
27
27
  import chalk from "chalk";
28
+ import { printDeletedCompanyNotices } from "../utils/deleted-company-notice.js";
28
29
  import { SOURCE_CHANNELS, assertSourceChannel, resolveEntity, listAvailableEntities, listSources, getSource, VaultClient, } from "@indigoai-us/hq-cloud";
29
30
  import { ensureCognitoToken, ensureCognitoIdToken, buildVaultConfig, DEFAULT_COGNITO, DEFAULT_HQ_ROOT, } from "../utils/cognito-session.js";
30
31
  import { getCompanyUid, vaultApiFetch } from "../utils/vault-api.js";
@@ -221,6 +222,11 @@ async function runEntities(options) {
221
222
  const accessToken = await resolveAccessToken();
222
223
  const vaultConfig = buildVaultConfig(accessToken);
223
224
  const entities = await listAvailableEntities({ vaultConfig });
225
+ // An empty list may mean the person's company was deleted. Say so on stderr;
226
+ // stdout (including --json) is unchanged.
227
+ if (entities.length === 0) {
228
+ await printDeletedCompanyNotices({ token: accessToken });
229
+ }
224
230
  if (format === "json") {
225
231
  process.stdout.write(JSON.stringify(entities, null, 2) + "\n");
226
232
  return;
@@ -335,8 +335,20 @@ export interface SyncRecord {
335
335
  /**
336
336
  * `companies/<slug>/<rest>` belongs to that company's vault at key `<rest>`.
337
337
  * Every other path belongs to the personal vault at its HQ-root-relative path.
338
+ * The match is exact-case, the same as companyForPointer. Callers pass a path
339
+ * from hqRelative (below), which spells the HQ companies folder as `companies`.
338
340
  */
339
341
  export declare function resolveOffloadTarget(rel: string): OffloadTarget;
342
+ /**
343
+ * companiesOnDisk is the on-disk name of `<HQ root>/companies` (from native
344
+ * realpath). On a case-insensitive volume whose folder is spelled, say,
345
+ * `Companies`, native realpath returns that spelling, and this maps it back
346
+ * to `companies` so it stays a company path (this is the macOS intent of
347
+ * #2475). On a case-sensitive volume a `COMPANIES/` folder is a different
348
+ * folder, its first segment never equals the on-disk name `companies`, so it
349
+ * stays personal.
350
+ */
351
+ export declare function canonicalCompaniesRel(rel: string, companiesOnDisk: string | null): string;
340
352
  /** Whether current-file offload can run with the installed HQ sync. */
341
353
  export declare function currentSyncReady(deps: Pick<OffloadDeps, "syncExcludesOffload" | "syncHoldsPlaceholders">): boolean;
342
354
  export declare function storageScriptPath(hqRoot: string): string;
@@ -518,14 +518,49 @@ export function s3VaultObjectStore(bucket, s3, opts = {}) {
518
518
  /**
519
519
  * `companies/<slug>/<rest>` belongs to that company's vault at key `<rest>`.
520
520
  * Every other path belongs to the personal vault at its HQ-root-relative path.
521
+ * The match is exact-case, the same as companyForPointer. Callers pass a path
522
+ * from hqRelative (below), which spells the HQ companies folder as `companies`.
521
523
  */
522
524
  export function resolveOffloadTarget(rel) {
523
525
  const posix = toPosix(rel);
524
- const m = /^companies\/([^/]+)\/(.+)$/i.exec(posix);
526
+ const m = /^companies\/([^/]+)\/(.+)$/.exec(posix);
525
527
  if (m)
526
528
  return { vault: "company", slug: m[1], key: m[2] };
527
529
  return { vault: "personal", key: posix };
528
530
  }
531
+ /**
532
+ * companiesOnDisk is the on-disk name of `<HQ root>/companies` (from native
533
+ * realpath). On a case-insensitive volume whose folder is spelled, say,
534
+ * `Companies`, native realpath returns that spelling, and this maps it back
535
+ * to `companies` so it stays a company path (this is the macOS intent of
536
+ * #2475). On a case-sensitive volume a `COMPANIES/` folder is a different
537
+ * folder, its first segment never equals the on-disk name `companies`, so it
538
+ * stays personal.
539
+ */
540
+ export function canonicalCompaniesRel(rel, companiesOnDisk) {
541
+ const slash = rel.indexOf("/");
542
+ const first = slash === -1 ? rel : rel.slice(0, slash);
543
+ if (first !== "companies" && companiesOnDisk !== null && first === companiesOnDisk) {
544
+ const rest = slash === -1 ? "" : rel.slice(slash);
545
+ return `companies${rest}`;
546
+ }
547
+ return rel;
548
+ }
549
+ /** HQ-root-relative path of `abs`, with the companies folder spelled `companies`. */
550
+ function hqRelative(realRoot, abs) {
551
+ const rel = toPosix(path.relative(realRoot, abs));
552
+ let companiesOnDisk = null;
553
+ try {
554
+ const companiesReal = fs.realpathSync.native(path.join(realRoot, "companies"));
555
+ // A symlinked companies folder pointing elsewhere is not renamed.
556
+ if (path.dirname(companiesReal) === realRoot)
557
+ companiesOnDisk = path.basename(companiesReal);
558
+ }
559
+ catch {
560
+ // Missing or unreadable: leave the relative path unchanged.
561
+ }
562
+ return canonicalCompaniesRel(rel, companiesOnDisk);
563
+ }
529
564
  /** Whether current-file offload can run with the installed HQ sync. */
530
565
  export function currentSyncReady(deps) {
531
566
  return deps.syncExcludesOffload() && deps.syncHoldsPlaceholders?.() === true;
@@ -599,6 +634,8 @@ export function worktreeHoldsAllCopy(held) {
599
634
  export function selectHistoryBlobs(blobs, minBytes) {
600
635
  // A blob may have both personal and company names. Never send any such
601
636
  // content to the personal store; historical paths need no longer exist.
637
+ // History paths are git tree names, not on-disk spellings, and excluding a
638
+ // blob keeps it in local history, so a case-insensitive exclusion is the safe direction.
602
639
  return blobs.filter((b) => !b.in_head && b.bytes >= minBytes && b.paths.length > 0 &&
603
640
  b.paths.every((p) => !/^companies(?:\/|$)/i.test(toPosix(path.posix.normalize(toPosix(p))))));
604
641
  }
@@ -677,7 +714,7 @@ export async function offloadCurrentFile(rel, store, deps, fsOps = durablePlaceh
677
714
  if (store.vault !== "personal")
678
715
  throw new Error("Offload only writes to your personal vault.");
679
716
  const abs = containedPath(deps.hqRoot, rel);
680
- rel = toPosix(path.relative(fs.realpathSync.native(deps.hqRoot), abs));
717
+ rel = hqRelative(fs.realpathSync.native(deps.hqRoot), abs);
681
718
  if (resolveOffloadTarget(rel).vault === "company") {
682
719
  throw new Error(`'${rel}' is a company file. Company files are never uploaded to your personal vault.`);
683
720
  }
@@ -1063,7 +1100,7 @@ async function planCurrentFiles(rels, opts, deps, openVault) {
1063
1100
  for (const candidate of rels) {
1064
1101
  const abs = containedPath(deps.hqRoot, candidate);
1065
1102
  // Canonicalise discovery output too, not just explicit path arguments.
1066
- const rel = toPosix(path.relative(fs.realpathSync.native(deps.hqRoot), abs));
1103
+ const rel = hqRelative(fs.realpathSync.native(deps.hqRoot), abs);
1067
1104
  if (skippedByName(rel))
1068
1105
  continue;
1069
1106
  let st;
@@ -1557,6 +1594,7 @@ async function downloadVerified(download, key, dest, expect) {
1557
1594
  }
1558
1595
  /** Company slug for a company-vault placeholder, checked against its key. */
1559
1596
  export function companyForPointer(pointer) {
1597
+ // Must stay exact-case, matching resolveOffloadTarget.
1560
1598
  const m = /^companies\/([^/]+)\/(.+)$/.exec(pointer.path);
1561
1599
  if (!m || (!isCompanyOffloadCopy(pointer) && m[2] !== pointer.key)) {
1562
1600
  throw new Error(`Placeholder for '${pointer.path}' names company vault key '${pointer.key}', which does not match its location. Nothing was changed.`);
@@ -30,6 +30,7 @@
30
30
  * in package.json — revert that line to `^5.20.0` (or whatever the
31
31
  * published cut is) once US-004 ships to npm.
32
32
  */
33
+ import { printDeletedCompanyNotices } from "../utils/deleted-company-notice.js";
33
34
  import { isAccessDeniedError, accessDeniedKeyOf, reportAccessDenied, accessDeniedCompanyOf, } from "../utils/access-denied-hint.js";
34
35
  import chalk from "chalk";
35
36
  import * as fs from "node:fs";
@@ -243,6 +244,10 @@ export function registerSyncModeCommand(syncCmd) {
243
244
  }
244
245
  const rows = await showSyncModes({ vaultClient: client });
245
246
  console.log(formatShowTable(rows));
247
+ // No memberships may mean the person's company was deleted.
248
+ if (rows.length === 0) {
249
+ await printDeletedCompanyNotices({ token: accessToken });
250
+ }
246
251
  return;
247
252
  }
248
253
  if (!modeArg) {
@@ -9,6 +9,7 @@ import { colorizePlanLimitNotice, fetchPlanLimitStatus, renderPlanLine, renderPl
9
9
  import { resolveCompanyFlagGate, } from "../lib/flag-registry.js";
10
10
  import { queuePlanLimitInviteTeammateExposure } from "../utils/cli-telemetry.js";
11
11
  import { resolveCallerPersonUid } from "../utils/vault-api.js";
12
+ import { printDeletedCompanyNotices } from "../utils/deleted-company-notice.js";
12
13
  export const CLI_LIMIT_INVITE_TEAMMATE_FLAG = "cli.limit-invite-teammate-v1";
13
14
  /**
14
15
  * Resolves the person represented by an ID token without pairing a delegated
@@ -228,6 +229,9 @@ export function registerWhoamiCommand(program) {
228
229
  const { email, sub } = resolveWhoamiIdentity(peekIdToken(cached.idToken));
229
230
  console.log(`Logged in as ${email ?? 'unknown'}${sub ? ` (${sub})` : ''}`);
230
231
  await printPlanBlock(opts.company);
232
+ // Person sessions only: a deleted company is otherwise invisible here.
233
+ // Bounded like the person-uid lookup, on stderr, and never a failure.
234
+ await printDeletedCompanyNotices({ timeoutMs: PERSON_UID_LOOKUP_TIMEOUT_MS });
231
235
  }
232
236
  catch (error) {
233
237
  console.error(chalk.red('Error:'), error instanceof Error ? error.message : 'Unknown error');
package/dist/index.js CHANGED
@@ -73,6 +73,7 @@ async function runMainWithInstallTreeRecovery() {
73
73
  sentry.Sentry.captureException(error, installTree.installTreeTornCaptureContext(error));
74
74
  sentry.finishSentrySession();
75
75
  await sentry.Sentry.flush(2_000);
76
+ sentry.closeSentryTransport();
76
77
  process.exitCode = 1;
77
78
  return;
78
79
  }
@@ -124,6 +125,7 @@ const recoverFastImport = async (load, options = {}) => {
124
125
  sentry.Sentry.captureException(error, installTree.installTreeTornCaptureContext(error));
125
126
  sentry.finishSentrySession();
126
127
  await sentry.Sentry.flush(2_000);
128
+ sentry.closeSentryTransport();
127
129
  return { reexecStatus: 1 };
128
130
  }
129
131
  }
@@ -33,6 +33,8 @@ export async function registerCommandRoot(program, root) {
33
33
  function commandDefinition(command) {
34
34
  const stub = new Command(command.name)
35
35
  .description(command.description);
36
+ if (command.summary)
37
+ stub.summary(command.summary);
36
38
  if (command.helpOption === false)
37
39
  stub.helpOption(false);
38
40
  for (const alias of command.aliases)
@@ -22,7 +22,8 @@
22
22
  * Pure apart from the injected `sleep`/`random`, so tests drive it with fake
23
23
  * timers.
24
24
  */
25
- import type { MergedInbox } from "./inbox-state.js";
25
+ import { type MergedInbox } from "./inbox-state.js";
26
+ import type { AgentKitPaths } from "./paths.js";
26
27
  /** Env override for the per-attempt deadline; values under the floor are raised to it. */
27
28
  export declare const AGENT_INBOX_TIMEOUT_ENV = "HQ_AGENT_INBOX_TIMEOUT_MS";
28
29
  /** Delay before the one retry when the server sent no usable `Retry-After`. */
@@ -50,6 +51,11 @@ export interface FetchServerInboxDeps {
50
51
  random?: () => number;
51
52
  /** Per-attempt deadline covering mint plus GET. */
52
53
  timeoutMs?: number;
54
+ /**
55
+ * Overall cancel signal (a batch deadline). It cuts an in-flight attempt
56
+ * short and suppresses the retry once aborted.
57
+ */
58
+ signal?: AbortSignal;
53
59
  }
54
60
  export type FetchServerInboxOutcome = {
55
61
  ok: true;
@@ -76,6 +82,121 @@ export declare function parseRetryAfterSeconds(header: string | null | undefined
76
82
  * response or the last error, plus how many attempts were made.
77
83
  */
78
84
  export declare function fetchServerInboxWithRetry(deps: FetchServerInboxDeps): Promise<FetchServerInboxOutcome>;
85
+ /** Env override for the total time one batch of acks may take. */
86
+ export declare const AGENT_INBOX_ACK_DEADLINE_ENV = "HQ_AGENT_INBOX_ACK_DEADLINE_MS";
87
+ /** Default total time for one batch of acks (`done` with many ids). */
88
+ export declare const AGENT_INBOX_ACK_DEADLINE_MS = 60000;
89
+ /** Budget for retrying unconfirmed acks at the start of an inbox read. */
90
+ export declare const AGENT_INBOX_READ_ACK_RETRY_MS = 10000;
91
+ /**
92
+ * Total time for one inbox read: the ack retry plus the bounded server read.
93
+ * Kept under the 60 s tool timeout MCP clients commonly apply to
94
+ * hq_inbox_read, with room for the local work around it.
95
+ */
96
+ export declare const AGENT_INBOX_READ_BUDGET_MS = 45000;
97
+ export declare function isPermanentAckStatus(status: number): boolean;
98
+ /** The inbox read's total budget passed before the server answered. */
99
+ export declare class InboxReadBudgetError extends Error {
100
+ readonly budgetMs: number;
101
+ constructor(budgetMs: number);
102
+ }
103
+ /**
104
+ * fetchServerInboxWithRetry under one total budget: the in-flight attempt is
105
+ * cut at the budget and the retry delay never waits past it. Never throws.
106
+ */
107
+ export declare function fetchServerInboxWithinBudget(deps: FetchServerInboxDeps, budgetMs: number): Promise<FetchServerInboxOutcome>;
108
+ /** The batch deadline passed before this id's ack was confirmed. */
109
+ export declare class InboxAckDeadlineError extends Error {
110
+ readonly deadlineMs: number;
111
+ constructor(deadlineMs: number);
112
+ }
113
+ /** Batch deadline from the env; values under the kit floor are raised to it. */
114
+ export declare function resolveAgentInboxAckDeadlineMs(env?: NodeJS.ProcessEnv): number;
115
+ export interface AckServerInboxDeps extends Omit<FetchServerInboxDeps, "fetch"> {
116
+ /** POST the ack for `id` with `token`. Must not throw on a non-2xx status. */
117
+ post: (token: string, id: string, signal: AbortSignal) => Promise<InboxFetchResponse>;
118
+ /**
119
+ * Total time for the whole batch. Once it passes, the in-flight ack is cut
120
+ * short and every remaining id is reported unconfirmed with `deferred: true`
121
+ * (feedback 3e376c49 review: N ids x ~65 s could outlive a host's timeout).
122
+ */
123
+ deadlineMs?: number;
124
+ /** Called right after each confirmed (2xx) ack, before the next id is sent. */
125
+ onAcked?: (id: string) => void;
126
+ }
127
+ export interface InboxAckFailure {
128
+ id: string;
129
+ /** Final HTTP status, when the server answered. */
130
+ status?: number;
131
+ /** Error message, when no answer arrived (mint failure, timeout, transport, deadline). Never response bytes. */
132
+ error?: string;
133
+ attempts: number;
134
+ /** True when the batch deadline passed before this ack was sent. */
135
+ deferred?: true;
136
+ /** True for a 400/403/404: not retried; the id moves to ack-failed.json. */
137
+ permanent?: true;
138
+ }
139
+ export interface InboxAckResult {
140
+ acked: string[];
141
+ failed: InboxAckFailure[];
142
+ /** True only when every id got a 2xx ack from the server. */
143
+ complete: boolean;
144
+ }
145
+ /**
146
+ * Ack each id on the server with the same bounded, once-retried attempt as the
147
+ * inbox read (feedback 3e376c49). Before, `hq agent inbox done` and
148
+ * `hq_inbox_done` sent one unbounded POST per id with no retry and reported a
149
+ * transient failure only as a warning line, so automation could not tell a
150
+ * completed ack from a lost one. The server ack is idempotent (processed
151
+ * marker, then delete pending), so retrying after a lost response, or the
152
+ * caller rerunning `done`, cannot double-complete an item. Never throws.
153
+ */
154
+ export declare function ackServerInboxItems(ids: string[], deps: AckServerInboxDeps): Promise<InboxAckResult>;
155
+ /** One-line description of an ack failure for a person or a log. */
156
+ export declare function describeInboxAckFailure(f: InboxAckFailure): string;
157
+ /**
158
+ * The `ackFailures` string format `hq_inbox_done` has always returned, kept so
159
+ * existing parsers keep working: `"<id> (<status>)"` for an HTTP answer, and
160
+ * `"ack skipped: <id>: <message>"` when no answer arrived. Structured detail
161
+ * is in `ackFailureDetails`. `hq agent inbox done --json` uses the same two
162
+ * fields, so both surfaces have one shape.
163
+ */
164
+ export declare function formatInboxAckFailure(f: InboxAckFailure): string;
165
+ export interface InboxDoneOutcome extends InboxAckResult {
166
+ /** Requested ids newly recorded in done-ids.json (confirmed by the server). */
167
+ marked: string[];
168
+ /** Requested ids that were already in done-ids.json before this call. */
169
+ alreadyDone: string[];
170
+ /** Ids from an earlier call whose ack was confirmed on this one. */
171
+ retriedAcked: string[];
172
+ /** Ids still awaiting a confirmed ack after this call (durable in ack-pending.json). */
173
+ ackPending: string[];
174
+ /** Ids the server refused permanently on this call; moved to ack-failed.json and no longer retried. */
175
+ ackFailed: string[];
176
+ /** True when every REQUESTED id is confirmed; earlier ids still pending show in `ackPending`. */
177
+ requestedComplete: boolean;
178
+ }
179
+ /**
180
+ * `hq agent inbox done` / `hq_inbox_done` (feedback 3e376c49): record the ids
181
+ * in ack-pending.json first, ack them plus any ids an earlier call left
182
+ * unconfirmed, and move each id to done-ids.json only after its 2xx. A failed
183
+ * ack, the batch deadline or a killed process leaves the id in
184
+ * ack-pending.json, where it stays visible and is retried by the next read or
185
+ * done call. Never throws on a network failure.
186
+ */
187
+ export declare function completeInboxItems(paths: Pick<AgentKitPaths, "inboxDir">, ids: string[], deps: Omit<AckServerInboxDeps, "onAcked">): Promise<InboxDoneOutcome>;
188
+ /**
189
+ * Retry the acks an earlier `done` left unconfirmed, at the start of an inbox
190
+ * read. Returns undefined when nothing was pending. Bounded by
191
+ * AGENT_INBOX_READ_ACK_RETRY_MS (or a smaller batch deadline) so a read stays
192
+ * quick when the server is down.
193
+ */
194
+ export declare function retryPendingInboxAcks(paths: Pick<AgentKitPaths, "inboxDir">, deps: Omit<AckServerInboxDeps, "onAcked">): Promise<{
195
+ acked: string[];
196
+ failed: InboxAckFailure[];
197
+ ackPending: string[];
198
+ ackFailed: string[];
199
+ } | undefined>;
79
200
  /** Suffix added to the degradation note when the retry also failed. */
80
201
  export declare const AGENT_INBOX_AFTER_ATTEMPTS_SUFFIX = " (after 2 attempts)";
81
202
  export interface AnnotatedInbox extends MergedInbox {
@@ -23,6 +23,7 @@
23
23
  * timers.
24
24
  */
25
25
  import { networkTransportErrorCode } from "../../utils/network-transport-error.js";
26
+ import { addAckPending, confirmInboxAck, readAckPending, readDoneIds, recordAckFailures } from "./inbox-state.js";
26
27
  import { KIT_REQUEST_TIMEOUT_MIN_MS, KIT_REQUEST_TIMEOUT_MS, KitRequestTimeoutError, withRequestTimeout } from "./run/request-timeout.js";
27
28
  /** Env override for the per-attempt deadline; values under the floor are raised to it. */
28
29
  export const AGENT_INBOX_TIMEOUT_ENV = "HQ_AGENT_INBOX_TIMEOUT_MS";
@@ -98,22 +99,233 @@ export async function fetchServerInboxWithRetry(deps) {
98
99
  const last = attempts >= AGENT_INBOX_MAX_ATTEMPTS;
99
100
  let retryAfterSeconds;
100
101
  try {
101
- const res = await withRequestTimeout(timeoutMs, undefined, async (signal) => {
102
+ const res = await withRequestTimeout(timeoutMs, deps.signal, async (signal) => {
102
103
  const token = await deps.mint(signal);
103
104
  return deps.fetch(token, signal);
104
105
  });
105
- if (last || !isRetryableInboxStatus(res.status)) {
106
+ if (last || deps.signal?.aborted || !isRetryableInboxStatus(res.status)) {
106
107
  return { ok: true, response: { status: res.status, body: res.body }, attempts };
107
108
  }
108
109
  retryAfterSeconds = res.retryAfterSeconds;
109
110
  }
110
111
  catch (err) {
111
- if (last || !isRetryableInboxError(err))
112
+ if (last || deps.signal?.aborted || !isRetryableInboxError(err))
112
113
  return { ok: false, error: err, attempts };
113
114
  }
114
115
  await sleep(retryDelayMs(retryAfterSeconds, random));
116
+ if (deps.signal?.aborted)
117
+ return { ok: false, error: deps.signal.reason, attempts };
115
118
  }
116
119
  }
120
+ /** Env override for the total time one batch of acks may take. */
121
+ export const AGENT_INBOX_ACK_DEADLINE_ENV = "HQ_AGENT_INBOX_ACK_DEADLINE_MS";
122
+ /** Default total time for one batch of acks (`done` with many ids). */
123
+ export const AGENT_INBOX_ACK_DEADLINE_MS = 60_000;
124
+ /** Budget for retrying unconfirmed acks at the start of an inbox read. */
125
+ export const AGENT_INBOX_READ_ACK_RETRY_MS = 10_000;
126
+ /**
127
+ * Total time for one inbox read: the ack retry plus the bounded server read.
128
+ * Kept under the 60 s tool timeout MCP clients commonly apply to
129
+ * hq_inbox_read, with room for the local work around it.
130
+ */
131
+ export const AGENT_INBOX_READ_BUDGET_MS = 45_000;
132
+ /**
133
+ * Ack answers that will not change on a retry. An id refused this way leaves
134
+ * ack-pending.json for ack-failed.json instead of being retried forever.
135
+ */
136
+ // 401 is absent on purpose: it is about the token, not the item, and one bad or
137
+ // revoked mint must not retire every pending id. A 409 is not final either.
138
+ // Both stay in ack-pending.json and are retried by the next read or done.
139
+ const PERMANENT_ACK_STATUSES = new Set([400, 403, 404]);
140
+ export function isPermanentAckStatus(status) {
141
+ return PERMANENT_ACK_STATUSES.has(status);
142
+ }
143
+ /** The inbox read's total budget passed before the server answered. */
144
+ export class InboxReadBudgetError extends Error {
145
+ budgetMs;
146
+ constructor(budgetMs) {
147
+ super(`inbox read budget (${budgetMs}ms) reached`);
148
+ this.budgetMs = budgetMs;
149
+ this.name = "InboxReadBudgetError";
150
+ }
151
+ }
152
+ /**
153
+ * fetchServerInboxWithRetry under one total budget: the in-flight attempt is
154
+ * cut at the budget and the retry delay never waits past it. Never throws.
155
+ */
156
+ export async function fetchServerInboxWithinBudget(deps, budgetMs) {
157
+ const budget = Math.max(1, Math.floor(budgetMs));
158
+ const controller = new AbortController();
159
+ const startedAt = Date.now();
160
+ const timer = setTimeout(() => controller.abort(new InboxReadBudgetError(budget)), budget);
161
+ const baseSleep = deps.sleep ?? defaultSleep;
162
+ try {
163
+ return await fetchServerInboxWithRetry({
164
+ ...deps,
165
+ signal: controller.signal,
166
+ sleep: (ms) => baseSleep(Math.max(0, Math.min(ms, startedAt + budget - Date.now()))),
167
+ });
168
+ }
169
+ finally {
170
+ clearTimeout(timer);
171
+ }
172
+ }
173
+ /** The batch deadline passed before this id's ack was confirmed. */
174
+ export class InboxAckDeadlineError extends Error {
175
+ deadlineMs;
176
+ constructor(deadlineMs) {
177
+ super(`ack batch deadline (${deadlineMs}ms) reached`);
178
+ this.deadlineMs = deadlineMs;
179
+ this.name = "InboxAckDeadlineError";
180
+ }
181
+ }
182
+ /** Batch deadline from the env; values under the kit floor are raised to it. */
183
+ export function resolveAgentInboxAckDeadlineMs(env = process.env) {
184
+ const raw = env[AGENT_INBOX_ACK_DEADLINE_ENV]?.trim();
185
+ if (!raw)
186
+ return AGENT_INBOX_ACK_DEADLINE_MS;
187
+ const n = Number(raw);
188
+ if (!Number.isFinite(n))
189
+ return AGENT_INBOX_ACK_DEADLINE_MS;
190
+ return Math.max(KIT_REQUEST_TIMEOUT_MIN_MS, Math.floor(n));
191
+ }
192
+ /**
193
+ * Ack each id on the server with the same bounded, once-retried attempt as the
194
+ * inbox read (feedback 3e376c49). Before, `hq agent inbox done` and
195
+ * `hq_inbox_done` sent one unbounded POST per id with no retry and reported a
196
+ * transient failure only as a warning line, so automation could not tell a
197
+ * completed ack from a lost one. The server ack is idempotent (processed
198
+ * marker, then delete pending), so retrying after a lost response, or the
199
+ * caller rerunning `done`, cannot double-complete an item. Never throws.
200
+ */
201
+ export async function ackServerInboxItems(ids, deps) {
202
+ const { post, deadlineMs, onAcked, ...rest } = deps;
203
+ const acked = [];
204
+ const failed = [];
205
+ const baseSleep = rest.sleep ?? defaultSleep;
206
+ const batch = new AbortController();
207
+ const startedAt = Date.now();
208
+ const timer = deadlineMs !== undefined
209
+ ? setTimeout(() => batch.abort(new InboxAckDeadlineError(deadlineMs)), deadlineMs)
210
+ : undefined;
211
+ // A retry delay never waits past the batch deadline.
212
+ const sleep = deadlineMs === undefined
213
+ ? baseSleep
214
+ : (ms) => baseSleep(Math.max(0, Math.min(ms, startedAt + deadlineMs - Date.now())));
215
+ try {
216
+ for (const id of ids) {
217
+ if (batch.signal.aborted) {
218
+ failed.push({ id, error: errorMessage(batch.signal.reason), attempts: 0, deferred: true });
219
+ continue;
220
+ }
221
+ const outcome = await fetchServerInboxWithRetry({
222
+ ...rest,
223
+ sleep,
224
+ signal: batch.signal,
225
+ fetch: (token, signal) => post(token, id, signal),
226
+ });
227
+ if (outcome.ok && outcome.response.status >= 200 && outcome.response.status < 300) {
228
+ acked.push(id);
229
+ onAcked?.(id);
230
+ }
231
+ else if (outcome.ok) {
232
+ const status = outcome.response.status;
233
+ failed.push({ id, status, attempts: outcome.attempts, ...(isPermanentAckStatus(status) ? { permanent: true } : {}) });
234
+ }
235
+ else {
236
+ failed.push({ id, error: errorMessage(outcome.error), attempts: outcome.attempts });
237
+ }
238
+ }
239
+ }
240
+ finally {
241
+ if (timer)
242
+ clearTimeout(timer);
243
+ }
244
+ return { acked, failed, complete: failed.length === 0 };
245
+ }
246
+ function errorMessage(err) {
247
+ return err instanceof Error ? err.message : String(err);
248
+ }
249
+ /** One-line description of an ack failure for a person or a log. */
250
+ export function describeInboxAckFailure(f) {
251
+ const why = f.status !== undefined ? `HTTP ${f.status}` : (f.error ?? "unknown error");
252
+ return `${f.id} (${why}${f.attempts > 1 ? `, after ${f.attempts} attempts` : ""})`;
253
+ }
254
+ /**
255
+ * The `ackFailures` string format `hq_inbox_done` has always returned, kept so
256
+ * existing parsers keep working: `"<id> (<status>)"` for an HTTP answer, and
257
+ * `"ack skipped: <id>: <message>"` when no answer arrived. Structured detail
258
+ * is in `ackFailureDetails`. `hq agent inbox done --json` uses the same two
259
+ * fields, so both surfaces have one shape.
260
+ */
261
+ export function formatInboxAckFailure(f) {
262
+ return f.status !== undefined ? `${f.id} (${f.status})` : `ack skipped: ${f.id}: ${f.error ?? "unknown error"}`;
263
+ }
264
+ /**
265
+ * `hq agent inbox done` / `hq_inbox_done` (feedback 3e376c49): record the ids
266
+ * in ack-pending.json first, ack them plus any ids an earlier call left
267
+ * unconfirmed, and move each id to done-ids.json only after its 2xx. A failed
268
+ * ack, the batch deadline or a killed process leaves the id in
269
+ * ack-pending.json, where it stays visible and is retried by the next read or
270
+ * done call. Never throws on a network failure.
271
+ */
272
+ export async function completeInboxItems(paths, ids, deps) {
273
+ const doneBefore = readDoneIds(paths);
274
+ const earlier = readAckPending(paths).filter((id) => !ids.includes(id));
275
+ addAckPending(paths, ids);
276
+ const marked = [];
277
+ const result = await ackServerInboxItems([...ids, ...earlier], {
278
+ ...deps,
279
+ onAcked: (id) => {
280
+ if (confirmInboxAck(paths, id) && ids.includes(id))
281
+ marked.push(id);
282
+ },
283
+ });
284
+ const requested = new Set(ids);
285
+ // The done output lists these ids, so they count as shown: no listing
286
+ // repeats them, and a bot that only calls done does not grow ack-failed.json.
287
+ const ackFailed = settlePermanentFailures(paths, result.failed, { reported: true });
288
+ return {
289
+ ...result,
290
+ marked,
291
+ alreadyDone: ids.filter((id) => doneBefore.has(id)),
292
+ retriedAcked: result.acked.filter((id) => !requested.has(id)),
293
+ ackPending: readAckPending(paths),
294
+ ackFailed,
295
+ requestedComplete: result.failed.every((f) => !requested.has(f.id)),
296
+ };
297
+ }
298
+ /**
299
+ * Move permanently refused ids from ack-pending.json to ack-failed.json in one
300
+ * locked write, not one rewrite per id. Returns their ids.
301
+ */
302
+ function settlePermanentFailures(paths, failed, options) {
303
+ const permanent = failed.filter((f) => f.permanent && f.status !== undefined);
304
+ recordAckFailures(paths, permanent.map((f) => ({ id: f.id, reason: `HTTP ${f.status}` })), options);
305
+ return permanent.map((f) => f.id);
306
+ }
307
+ /**
308
+ * Retry the acks an earlier `done` left unconfirmed, at the start of an inbox
309
+ * read. Returns undefined when nothing was pending. Bounded by
310
+ * AGENT_INBOX_READ_ACK_RETRY_MS (or a smaller batch deadline) so a read stays
311
+ * quick when the server is down.
312
+ */
313
+ export async function retryPendingInboxAcks(paths, deps) {
314
+ const pending = readAckPending(paths);
315
+ if (pending.length === 0)
316
+ return undefined;
317
+ const deadlineMs = Math.min(deps.deadlineMs ?? AGENT_INBOX_READ_ACK_RETRY_MS, AGENT_INBOX_READ_ACK_RETRY_MS);
318
+ const result = await ackServerInboxItems(pending, {
319
+ ...deps,
320
+ deadlineMs,
321
+ onAcked: (id) => {
322
+ confirmInboxAck(paths, id);
323
+ },
324
+ });
325
+ // Not in any output yet: the next listing shows them.
326
+ const ackFailed = settlePermanentFailures(paths, result.failed, { reported: false });
327
+ return { acked: result.acked, failed: result.failed, ackPending: readAckPending(paths), ackFailed };
328
+ }
117
329
  /** Suffix added to the degradation note when the retry also failed. */
118
330
  export const AGENT_INBOX_AFTER_ATTEMPTS_SUFFIX = ` (after ${AGENT_INBOX_MAX_ATTEMPTS} attempts)`;
119
331
  /**
@@ -18,7 +18,7 @@ import * as fs from "node:fs";
18
18
  import * as path from "node:path";
19
19
  import { writePrivateFile } from "./private-file.js";
20
20
  const INBOX_JSONL_NAME = "inbox.jsonl";
21
- const STATE_FILES = new Set(["seen-ids.json", "done-ids.json"]);
21
+ const STATE_FILES = new Set(["seen-ids.json", "done-ids.json", "ack-pending.json", "ack-failed.json"]);
22
22
  const LOCK_DIR_NAME = ".inbox-write.lock";
23
23
  const LOCK_STALE_MS = 30_000;
24
24
  const ACTING_CONTEXT_KEYS = ["mode", "ownerPersonUid", "ownerRole", "expiresAt"];