@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
@@ -590,5 +590,20 @@ export declare const REGISTRATION_PLAN: readonly [{
590
590
  readonly exportName: "registerListingsCommand";
591
591
  }];
592
592
  export declare function registerAllCommands(program: Command): Promise<void>;
593
+ /**
594
+ * Every top-level alias in the generated command catalog, mapped to the plan
595
+ * root that registers it. registerCommandRoot resolves through this map so a
596
+ * caller that passes an alias still finds the plan.
597
+ *
598
+ * This matters when an install is replaced while `hq` starts (self-update on an
599
+ * Outpost): the running process has already loaded the OLD command catalog, so
600
+ * its lazy loader asks for the old root name, but this module is imported from
601
+ * the NEW tree. When a root is renamed and its old name kept as an alias (hq
602
+ * lanes -> hq runners, hq-cli #2490), the old name must still reach the new
603
+ * plan (Sentry HQ-CLI-GM). The map lives here, not in the catalog, because the
604
+ * catalog module is already cached from the old tree in that case.
605
+ * lazy-registration-parity.test.ts keeps this map equal to the catalog.
606
+ */
607
+ export declare const ROOT_ALIASES: ReadonlyMap<string, string>;
593
608
  export declare function registerCommandRoot(program: Command, root: string): Promise<boolean>;
594
609
  //# sourceMappingURL=command-registration-plan.d.ts.map
@@ -147,8 +147,27 @@ async function executePlan(program, steps) {
147
147
  export async function registerAllCommands(program) {
148
148
  await executePlan(program, REGISTRATION_PLAN);
149
149
  }
150
+ /**
151
+ * Every top-level alias in the generated command catalog, mapped to the plan
152
+ * root that registers it. registerCommandRoot resolves through this map so a
153
+ * caller that passes an alias still finds the plan.
154
+ *
155
+ * This matters when an install is replaced while `hq` starts (self-update on an
156
+ * Outpost): the running process has already loaded the OLD command catalog, so
157
+ * its lazy loader asks for the old root name, but this module is imported from
158
+ * the NEW tree. When a root is renamed and its old name kept as an alias (hq
159
+ * lanes -> hq runners, hq-cli #2490), the old name must still reach the new
160
+ * plan (Sentry HQ-CLI-GM). The map lives here, not in the catalog, because the
161
+ * catalog module is already cached from the old tree in that case.
162
+ * lazy-registration-parity.test.ts keeps this map equal to the catalog.
163
+ */
164
+ export const ROOT_ALIASES = new Map([
165
+ ["master-sync", "reindex"],
166
+ ["lanes", "runners"],
167
+ ]);
150
168
  export async function registerCommandRoot(program, root) {
151
- const steps = REGISTRATION_PLAN.filter((step) => step.root === root);
169
+ const planRoot = ROOT_ALIASES.get(root) ?? root;
170
+ const steps = REGISTRATION_PLAN.filter((step) => step.root === planRoot);
152
171
  if (steps.length === 0)
153
172
  return false;
154
173
  await executePlan(program, steps);
@@ -2,8 +2,18 @@
2
2
  * `hq agent inbox` — what a woken bot runs to see and clear its HQ mail.
3
3
  *
4
4
  * hq agent inbox [--all] [--json] pending items (oldest first), or all
5
- * hq agent inbox done <id...> mark handled locally and ack on the server
5
+ * hq agent inbox done <id...> [--json] ack on the server, then mark handled locally
6
+ * (exit 1: invalid id; exit 3: an ack is unconfirmed and
7
+ * kept in ack-pending.json for the next call to retry)
6
8
  */
7
9
  import { Command } from "commander";
10
+ /** `hq agent inbox done` exit code: an id failed validation; nothing was sent or recorded. */
11
+ export declare const AGENT_INBOX_DONE_EXIT_INVALID_ID = 1;
12
+ /**
13
+ * `hq agent inbox done` exit code: at least one requested id has no confirmed
14
+ * server ack. It is kept in ack-pending.json, still listed, and retried by the
15
+ * next `hq agent inbox` or `done` call. Rerunning `done` is safe.
16
+ */
17
+ export declare const AGENT_INBOX_DONE_EXIT_ACK_UNCONFIRMED = 3;
8
18
  export declare function registerAgentInboxCommand(agent: Command): void;
9
19
  //# sourceMappingURL=agent-inbox.d.ts.map
@@ -2,18 +2,28 @@
2
2
  * `hq agent inbox` — what a woken bot runs to see and clear its HQ mail.
3
3
  *
4
4
  * hq agent inbox [--all] [--json] pending items (oldest first), or all
5
- * hq agent inbox done <id...> mark handled locally and ack on the server
5
+ * hq agent inbox done <id...> [--json] ack on the server, then mark handled locally
6
+ * (exit 1: invalid id; exit 3: an ack is unconfirmed and
7
+ * kept in ack-pending.json for the next call to retry)
6
8
  */
7
9
  import chalk from "chalk";
8
10
  import * as os from "node:os";
9
11
  import { ensureCognitoToken } from "../utils/cognito-session.js";
10
12
  import { vaultApiFetch } from "../utils/vault-api.js";
11
- import { annotateInboxAttempts, fetchServerInboxWithRetry, parseRetryAfterSeconds, resolveAgentInboxTimeoutMs } from "../lib/agent-kit/inbox-fetch.js";
13
+ import { AGENT_INBOX_READ_BUDGET_MS, annotateInboxAttempts, completeInboxItems, describeInboxAckFailure, fetchServerInboxWithinBudget, formatInboxAckFailure, parseRetryAfterSeconds, resolveAgentInboxAckDeadlineMs, resolveAgentInboxTimeoutMs, retryPendingInboxAcks, } from "../lib/agent-kit/inbox-fetch.js";
12
14
  import { redactAgentInboxItem } from "../lib/agent-kit/inbox-redact.js";
13
- import { markInboxDone, mergeAgentInbox, readDoneIds, summarizeInboxEntry } from "../lib/agent-kit/inbox-state.js";
15
+ import { MAX_ACK_FAILED_RECORDS, mergeAgentInbox, readAckPending, readDoneIds, summarizeInboxEntry, takeAckFailureListing } from "../lib/agent-kit/inbox-state.js";
14
16
  import { agentKitPaths } from "../lib/agent-kit/paths.js";
15
17
  import { requireExternalCreds } from "./agent-kit.js";
16
18
  const ID_RE = /^[A-Za-z0-9._:-]{1,200}$/;
19
+ /** `hq agent inbox done` exit code: an id failed validation; nothing was sent or recorded. */
20
+ export const AGENT_INBOX_DONE_EXIT_INVALID_ID = 1;
21
+ /**
22
+ * `hq agent inbox done` exit code: at least one requested id has no confirmed
23
+ * server ack. It is kept in ack-pending.json, still listed, and retried by the
24
+ * next `hq agent inbox` or `done` call. Rerunning `done` is safe.
25
+ */
26
+ export const AGENT_INBOX_DONE_EXIT_ACK_UNCONFIRMED = 3;
17
27
  export function registerAgentInboxCommand(agent) {
18
28
  const inbox = agent
19
29
  .command("inbox")
@@ -23,12 +33,20 @@ export function registerAgentInboxCommand(agent) {
23
33
  .action(async (opts) => {
24
34
  const paths = agentKitPaths(os.homedir(), process.env);
25
35
  const creds = requireExternalCreds(paths);
26
- const done = readDoneIds(paths);
27
36
  // Pin the enrolled machine identity and API, as `done` does below, so the
28
37
  // mint cannot fall through to a person session or another API base.
29
- process.env.HQ_MACHINE_CREDS_FILE = paths.machineCredsPath;
30
- process.env.HQ_REQUIRE_MACHINE_IDENTITY = "1";
31
- process.env.HQ_VAULT_API_URL = creds.apiBaseUrl;
38
+ pinMachineIdentity(paths, creds);
39
+ // The whole read (ack retry plus server read) stays inside one budget.
40
+ const readStartedAt = Date.now();
41
+ // Feedback 3e376c49: retry acks an earlier `done` could not confirm, so a
42
+ // failed or killed `done` does not leave the server holding the item.
43
+ const ackRetry = await retryPendingInboxAcks(paths, ackDeps(creds));
44
+ const done = readDoneIds(paths);
45
+ const ackPending = new Set(readAckPending(paths));
46
+ // Acks the server refused permanently: shown once with the reason, never retried.
47
+ // At most ACK_FAILED_LISTING_LIMIT per call; the rest wait for the next one.
48
+ const { ackFailed, more: ackFailedMore, dropped: ackFailedDropped } = takeAckFailureListing(paths);
49
+ const ackFailedById = new Map(ackFailed.map((f) => [f.id, f.reason]));
32
50
  // Merged with the server, never the local mirror alone: a dead kit
33
51
  // poller would otherwise make this command answer confidently with
34
52
  // yesterday's mail and no sign anything was wrong. The server read is
@@ -36,7 +54,7 @@ export function registerAgentInboxCommand(agent) {
36
54
  // 503 with Retry-After or a hung socket does not become a fallback.
37
55
  let attempts = 1;
38
56
  const merged = await mergeAgentInbox(paths, async () => {
39
- const outcome = await fetchServerInboxWithRetry({
57
+ const outcome = await fetchServerInboxWithinBudget({
40
58
  timeoutMs: resolveAgentInboxTimeoutMs(process.env),
41
59
  mint: (signal) => ensureCognitoToken({ tokenSource: "machine", interactive: false, signal }),
42
60
  fetch: async (token, signal) => {
@@ -55,16 +73,18 @@ export function registerAgentInboxCommand(agent) {
55
73
  ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
56
74
  };
57
75
  },
58
- });
76
+ }, AGENT_INBOX_READ_BUDGET_MS - (Date.now() - readStartedAt));
59
77
  attempts = outcome.attempts;
60
78
  if (!outcome.ok)
61
79
  throw outcome.error;
62
80
  return outcome.response;
63
81
  });
64
82
  const { entries, note, source, stale, attempts: attemptsMade } = annotateInboxAttempts(merged, attempts);
83
+ // An id with an unconfirmed ack stays listed (marked ackPending) so it is
84
+ // never hidden while the server may still hold it.
65
85
  const rows = entries
66
- .filter((e) => opts.all || !done.has(e.id))
67
- .map((e) => summarizeInboxEntry(redactAgentInboxItem(e), done.has(e.id)));
86
+ .filter((e) => opts.all || !done.has(e.id) || ackPending.has(e.id) || ackFailedById.has(e.id))
87
+ .map((e) => summarizeInboxEntry(redactAgentInboxItem(e), done.has(e.id) && !ackPending.has(e.id), ackPending.has(e.id), ackFailedById.get(e.id)));
68
88
  if (opts.json) {
69
89
  console.log(JSON.stringify({
70
90
  count: rows.length,
@@ -73,11 +93,31 @@ export function registerAgentInboxCommand(agent) {
73
93
  ...(attemptsMade !== undefined ? { attempts: attemptsMade } : {}),
74
94
  messages: rows,
75
95
  ...(note ? { note } : {}),
96
+ ...(ackRetry?.acked.length ? { ackRetried: ackRetry.acked } : {}),
97
+ ...(ackPending.size ? { ackPending: [...ackPending] } : {}),
98
+ ...(ackFailed.length ? { ackFailed } : {}),
99
+ ...(ackFailedMore > 0 ? { ackFailedMore } : {}),
100
+ ...(ackFailedDropped > 0 ? { ackFailedDropped } : {}),
76
101
  }, null, 2));
77
102
  return;
78
103
  }
79
104
  if (note)
80
105
  console.error(chalk.yellow(note));
106
+ if (ackFailed.length) {
107
+ console.error(chalk.yellow(`The server refused the ack for ${ackFailed.map((f) => `${f.id} (${f.reason})`).join(", ")}. ` +
108
+ "It is not retried and is listed only this once."));
109
+ }
110
+ if (ackFailedMore > 0) {
111
+ console.error(chalk.yellow(`${ackFailedMore} more refused ack(s) are waiting and will be listed by the next \`hq agent inbox\` call.`));
112
+ }
113
+ if (ackFailedDropped > 0) {
114
+ console.error(chalk.yellow(`${ackFailedDropped} older refused ack(s) were dropped without being listed: more than ${MAX_ACK_FAILED_RECORDS} were waiting. ` +
115
+ "Those items were already handled."));
116
+ }
117
+ if (ackPending.size) {
118
+ console.error(chalk.yellow(`${ackPending.size} handled item(s) still await a server ack (do not reply again): ${[...ackPending].join(" ")}. ` +
119
+ "Retry with: hq agent inbox done <id>"));
120
+ }
81
121
  if (rows.length === 0) {
82
122
  console.log(note
83
123
  ? "No matching messages can be confirmed; the server inbox could not be read completely."
@@ -85,7 +125,11 @@ export function registerAgentInboxCommand(agent) {
85
125
  return;
86
126
  }
87
127
  for (const r of rows) {
88
- const state = r.done ? chalk.dim(" (done)") : "";
128
+ const state = r.ackPending
129
+ ? chalk.yellow(" (handled; server ack not confirmed)")
130
+ : r.ackFailed
131
+ ? chalk.yellow(` (handled; server refused the ack: ${r.ackFailed})`)
132
+ : r.done ? chalk.dim(" (done)") : "";
89
133
  console.log(`${chalk.bold(r.id)}${state} ${r.channel ?? "?"} from ${r.from}${r.fromUid ? ` <${r.fromUid}>` : ""} ${r.at ?? ""}`);
90
134
  if (r.text)
91
135
  console.log(` ${r.text.replace(/\n/g, "\n ")}`);
@@ -101,39 +145,85 @@ export function registerAgentInboxCommand(agent) {
101
145
  });
102
146
  inbox
103
147
  .command("done <ids...>")
104
- .description("Mark inbox items handled and ack them on the server")
105
- .action(async (ids) => {
148
+ .description(`Mark inbox items handled and ack them on the server. Exit ${AGENT_INBOX_DONE_EXIT_INVALID_ID}: invalid id (nothing sent); ` +
149
+ `exit ${AGENT_INBOX_DONE_EXIT_ACK_UNCONFIRMED}: a server ack is not confirmed (kept in ack-pending and retried; rerunning is safe)`)
150
+ .option("--json", "Print machine-readable JSON")
151
+ .action(async (ids, opts) => {
106
152
  const bad = ids.filter((id) => !ID_RE.test(id));
107
153
  if (bad.length) {
108
- console.error(chalk.red(`Invalid id(s): ${bad.join(", ")}`));
109
- process.exit(1);
154
+ if (opts.json) {
155
+ console.log(JSON.stringify({ error: "invalid_id", invalidIds: bad, complete: false, exitCode: AGENT_INBOX_DONE_EXIT_INVALID_ID }, null, 2));
156
+ }
157
+ else {
158
+ console.error(chalk.red(`Invalid id(s): ${bad.join(", ")}`));
159
+ }
160
+ process.exit(AGENT_INBOX_DONE_EXIT_INVALID_ID);
110
161
  }
111
162
  const paths = agentKitPaths(os.homedir(), process.env);
112
163
  const creds = requireExternalCreds(paths);
113
- const added = markInboxDone(paths, ids);
114
- process.env.HQ_MACHINE_CREDS_FILE = paths.machineCredsPath;
115
- process.env.HQ_REQUIRE_MACHINE_IDENTITY = "1";
116
- process.env.HQ_VAULT_API_URL = creds.apiBaseUrl;
117
- let acked = 0;
118
- try {
119
- const token = await ensureCognitoToken({ tokenSource: "machine", interactive: false });
120
- for (const id of ids) {
121
- const res = await vaultApiFetch({
122
- token,
123
- baseUrl: creds.apiBaseUrl,
124
- path: `/v1/agents/${encodeURIComponent(creds.entityUid)}/inbox/${encodeURIComponent(id)}/ack`,
125
- method: "POST",
126
- });
127
- if (res.ok)
128
- acked += 1;
129
- else
130
- console.error(chalk.yellow(`server ack ${id} → ${res.status}`));
131
- }
164
+ pinMachineIdentity(paths, creds);
165
+ // Feedback 3e376c49: an id is recorded done only after the server
166
+ // confirms its ack. Until then it is kept in ack-pending.json (written
167
+ // before the first POST, so a kill mid-batch keeps it), stays visible in
168
+ // `hq agent inbox`, and is retried by the next read or done call. The
169
+ // whole batch runs under one deadline. The server ack is idempotent, so a
170
+ // rerun cannot double-complete.
171
+ const result = await completeInboxItems(paths, ids, ackDeps(creds));
172
+ const exitCode = result.requestedComplete ? 0 : AGENT_INBOX_DONE_EXIT_ACK_UNCONFIRMED;
173
+ if (exitCode !== 0)
174
+ process.exitCode = exitCode;
175
+ if (opts.json) {
176
+ console.log(JSON.stringify({
177
+ marked: result.marked.length,
178
+ alreadyDone: result.alreadyDone.length,
179
+ serverAcked: result.acked.length - result.retriedAcked.length,
180
+ complete: result.requestedComplete,
181
+ acked: result.acked,
182
+ ...(result.retriedAcked.length ? { retriedAcked: result.retriedAcked } : {}),
183
+ ...(result.failed.length
184
+ ? { ackFailures: result.failed.map(formatInboxAckFailure), ackFailureDetails: result.failed }
185
+ : {}),
186
+ ...(result.ackPending.length ? { ackPending: result.ackPending } : {}),
187
+ ...(result.ackFailed.length ? { ackFailed: result.ackFailed } : {}),
188
+ exitCode,
189
+ }, null, 2));
190
+ return;
191
+ }
192
+ for (const f of result.failed)
193
+ console.error(chalk.yellow(`server ack not confirmed: ${describeInboxAckFailure(f)}`));
194
+ console.log(`Marked ${result.marked.length} handled (${result.alreadyDone.length} already done); server acked ${result.acked.length} of ${result.acked.length + result.failed.length}.`);
195
+ if (result.ackFailed.length) {
196
+ console.error(chalk.yellow(`The server refused the ack for ${result.ackFailed.join(" ")} (a permanent answer); it is not retried.`));
132
197
  }
133
- catch (err) {
134
- console.error(chalk.yellow(`server ack skipped: ${err instanceof Error ? err.message : String(err)}`));
198
+ if (result.ackPending.length) {
199
+ console.error(chalk.yellow(`${result.ackPending.length} handled item(s) still await a server ack and stay listed as pending: ${result.ackPending.join(" ")}. ` +
200
+ "The next `hq agent inbox` or `hq agent inbox done` retries them (repeating an ack is safe)."));
135
201
  }
136
- console.log(`Marked ${added.length} handled (${ids.length - added.length} already done); server acked ${acked}.`);
137
202
  });
138
203
  }
204
+ /** Pin the enrolled machine identity and API so a mint cannot fall through to a person session. */
205
+ function pinMachineIdentity(paths, creds) {
206
+ process.env.HQ_MACHINE_CREDS_FILE = paths.machineCredsPath;
207
+ process.env.HQ_REQUIRE_MACHINE_IDENTITY = "1";
208
+ process.env.HQ_VAULT_API_URL = creds.apiBaseUrl;
209
+ }
210
+ /** Bounded, once-retried ack of one inbox id, under one batch deadline. */
211
+ function ackDeps(creds) {
212
+ return {
213
+ timeoutMs: resolveAgentInboxTimeoutMs(process.env),
214
+ deadlineMs: resolveAgentInboxAckDeadlineMs(process.env),
215
+ mint: (signal) => ensureCognitoToken({ tokenSource: "machine", interactive: false, signal }),
216
+ post: async (token, id, signal) => {
217
+ const res = await vaultApiFetch({
218
+ token,
219
+ baseUrl: creds.apiBaseUrl,
220
+ path: `/v1/agents/${encodeURIComponent(creds.entityUid)}/inbox/${encodeURIComponent(id)}/ack`,
221
+ method: "POST",
222
+ signal,
223
+ });
224
+ const retryAfterSeconds = parseRetryAfterSeconds(res.headers?.get?.("retry-after"));
225
+ return { status: res.status, body: undefined, ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}) };
226
+ },
227
+ };
228
+ }
139
229
  //# sourceMappingURL=agent-inbox.js.map
@@ -37,7 +37,7 @@ import { fallbackStatus, rebootCrontabLine, ensureRebootCrontab, shouldUseFallba
37
37
  import { serviceLogPath } from "../lib/agent-kit/paths.js";
38
38
  import { runResidentCommandWithPackageLease } from "../utils/resident-package-preload.js";
39
39
  import { spawn } from "node:child_process";
40
- import { pendingInbox } from "../lib/agent-kit/inbox-state.js";
40
+ import { pendingInbox, readAckPending } from "../lib/agent-kit/inbox-state.js";
41
41
  import { parseHeaderSecrets, buildWakeNotice, clearWakeConfig, currentWakeState, DEFAULT_WAKE_RETRY_MS, describeWake, fireWake, readWakeConfig, validateWakeUrl, writeWakeConfig, } from "../lib/agent-kit/wake.js";
42
42
  import { runSyncLoop } from "../lib/agent-kit/run/sync.js";
43
43
  import { resolveHqBinary, resolveNodeBinary, } from "../lib/mesh/live/daemon/install.js";
@@ -462,7 +462,7 @@ export function registerAgentKitCommand(agent) {
462
462
  throw new Error("No wake configured. Run hq agent kit wake set-url --stdin (or set-command).");
463
463
  const log = createKitLogger(paths, "wake", { echo: false });
464
464
  const ids = pendingInbox(paths).map((e) => e.id);
465
- const result = await fireWake(config, buildWakeNotice(creds.entityUid, "test", ids, new Date()), { paths, agentUid: creds.entityUid, log, resolveHeaderSecrets: createWakeSecretResolver(creds.companySlug, runtime.getToken, creds.apiBaseUrl) });
465
+ const result = await fireWake(config, buildWakeNotice(creds.entityUid, "test", ids, new Date(), readAckPending(paths)), { paths, agentUid: creds.entityUid, log, resolveHeaderSecrets: createWakeSecretResolver(creds.companySlug, runtime.getToken, creds.apiBaseUrl) });
466
466
  console.log(result.ok ? chalk.green(result.detail) : chalk.red(result.detail));
467
467
  if (!result.ok)
468
468
  process.exit(1);
@@ -1694,7 +1694,12 @@ export function registerAgentsCommand(program) {
1694
1694
  if (err instanceof AgentsHttpError &&
1695
1695
  err.status === 402 &&
1696
1696
  err.billing) {
1697
- await surfaceBillingBlocked(token, err.billing, err.message);
1697
+ // US-034: the plan picks the sentence. Asked after the link is
1698
+ // minted and bounded like the 403 path: at most 3 s, then legacy copy.
1699
+ await surfaceBillingBlocked(token, err.billing, err.message, async () => isUsageOnly(await fetchCompanyPricingPlan(token, companyUid, {
1700
+ timeoutMs: 2000,
1701
+ deadlineMs: 3000,
1702
+ }).catch(() => null)));
1698
1703
  process.exit(1);
1699
1704
  }
1700
1705
  throw err;
@@ -31,7 +31,7 @@ import { mintPaymentLink } from "../utils/billing-gate.js";
31
31
  import { openUsageSwitch } from "../utils/team-upgrade.js";
32
32
  import { registerBillingSponsorCommands } from "./billing-sponsor.js";
33
33
  import { fetchCompanyPricingPlan, isUsageOnly, pricingPlanFromBody, readBillingState, usageOnlyUpgradeLines, } from "../lib/billing/usage-only.js";
34
- import { fetchUsageCard } from "../lib/billing/usage-card.js";
34
+ import { fetchUsageCard, formatCardUsd } from "../lib/billing/usage-card.js";
35
35
  import { accountStatusLines } from "../lib/billing/billing-status-lines.js";
36
36
  import { registerBillingUsageCommand } from "./billing-usage.js";
37
37
  const CHARGED_ON = {
@@ -202,18 +202,31 @@ export function registerBillingCommand(program) {
202
202
  (scheduled.phase === "preview" ? " (preview window open)." : "."));
203
203
  }
204
204
  }
205
+ const state = readBillingState(summary);
206
+ const onUsage = !!state && (state.kind === "usage" || state.kind === "usage-trial");
207
+ const card = onUsage ? (await fetchUsageCard()).card : null;
205
208
  const pm = summary.defaultPaymentMethod;
206
209
  if (pm?.present) {
207
210
  const detail = pm.brand && pm.last4 ? `${pm.brand} ••••${pm.last4}` : "on file";
208
211
  console.log(`${chalk.bold("Card")}: ${detail}`);
209
212
  }
213
+ else if (state && card && state.view !== "full") {
214
+ // US-034: a member cannot add the company card (hq-pro's org card
215
+ // capture is owner or admin only), and the member view carries no
216
+ // money figures.
217
+ console.log(`${chalk.bold("Card")}: ${chalk.yellow("no card on file")} — ask an owner or admin to add a card.`);
218
+ }
219
+ else if (state && card) {
220
+ // US-034: usage pricing asks for a card past the included usage.
221
+ console.log(`${chalk.bold("Card")}: ${chalk.yellow("no card on file")} — ` +
222
+ `HQ asks for a card once usage this month passes ${formatCardUsd(card.includedUsd)}. ` +
223
+ "Hosted boxes bill to a card; add one with `hq billing checkout`.");
224
+ }
210
225
  else {
211
226
  console.log(`${chalk.bold("Card")}: ${chalk.yellow("no card on file")} — ` +
212
227
  `run \`hq billing checkout\` to add one before provisioning paid resources.`);
213
228
  }
214
- const state = readBillingState(summary);
215
- if (state && (state.kind === "usage" || state.kind === "usage-trial")) {
216
- const { card } = await fetchUsageCard();
229
+ if (state && card) {
217
230
  for (const line of accountStatusLines(state, card))
218
231
  console.log(line);
219
232
  }
@@ -35,6 +35,7 @@ const SESSION_ID_ENV_KEYS = [
35
35
  "CODEX_SESSION_ID",
36
36
  "CODEX_THREAD_ID",
37
37
  "GROK_SESSION_ID",
38
+ "HQ_FLEET_SESSION_ID",
38
39
  ];
39
40
  function validSessionId(value) {
40
41
  return value !== "" && value !== "." && value !== ".." && /^[A-Za-z0-9._-]+$/.test(value);
@@ -6,7 +6,7 @@ import { createRequire } from "node:module";
6
6
  import { spawn, spawnSync } from "node:child_process";
7
7
  import { awkCannotOpenFileDiagnostic } from "../lib/core-utils/awk-diagnostics.js";
8
8
  import { shellDisplayPath } from "../lib/core-utils/shell-display-path.js";
9
- import { validSessionId, resolveSessionId as resolveSharedSessionId } from "../lib/core-utils/session-id.js";
9
+ import { SESSION_ID_ENV_KEYS, validSessionId, resolveSessionId as resolveSharedSessionId } from "../lib/core-utils/session-id.js";
10
10
  export const HQ_SESSION_ASSET = "core/scripts/hq-session.sh";
11
11
  const requireSessionDependency = createRequire(import.meta.url);
12
12
  export const HQ_SESSION_HELP = [
@@ -715,7 +715,7 @@ export function executeHqSession(argv, context, overrides = {}) {
715
715
  return {
716
716
  code: 1,
717
717
  stdout: "",
718
- stderr: "hq-session: no current session — no session id in the environment (HQ_SESSION_ID, CLAUDE_CODE_SESSION_ID, CLAUDE_SESSION_ID, CODEX_SESSION_ID, CODEX_THREAD_ID) and workspace/sessions/.current is missing or invalid. Is master-hook installed? Pass --session-id <id> to target a session explicitly.\n",
718
+ stderr: `hq-session: no current session — no session id in the environment (${SESSION_ID_ENV_KEYS.join(", ")}) and workspace/sessions/.current is missing or invalid. Is master-hook installed? Pass --session-id <id> to target a session explicitly.\n`,
719
719
  };
720
720
  }
721
721
  const target = path.join(root, "workspace", "sessions", sessionId, "meta.yaml");
@@ -20,7 +20,7 @@ export const PIN_HELP = `# hq-pin.sh — anchor the current session to one goal
20
20
  #
21
21
  # Storage: workspace/sessions/<sid>/pin.md plus \`pin: <goal>\` in the session's
22
22
  `;
23
- const SESSION_ENV_KEYS = ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"];
23
+ const SESSION_ENV_KEYS = ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID", "HQ_FLEET_SESSION_ID"];
24
24
  const stamp = (date) => date.toISOString().replace(/\.\d{3}Z$/, "Z");
25
25
  function normalizeId(value) { return value.replace(/[\t\n\v\f\r ]/g, ""); }
26
26
  function validId(value) { return value !== "" && value !== "." && value !== ".." && /^[A-Za-z0-9._-]+$/.test(value); }
@@ -769,7 +769,7 @@ function resolvePolicyTarget(target, root, cwd) {
769
769
  }
770
770
  function sessionCompanySlug(root, env) {
771
771
  const valid = (candidate) => candidate !== '' && candidate !== '.' && candidate !== '..' && /^[A-Za-z0-9._-]+$/.test(candidate);
772
- const candidates = ['HQ_SESSION_ID', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_SESSION_ID', 'CODEX_SESSION_ID', 'CODEX_THREAD_ID', 'GROK_SESSION_ID'];
772
+ const candidates = ['HQ_SESSION_ID', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_SESSION_ID', 'CODEX_SESSION_ID', 'CODEX_THREAD_ID', 'GROK_SESSION_ID', 'HQ_FLEET_SESSION_ID'];
773
773
  let sessionId = '';
774
774
  for (const variable of candidates) {
775
775
  const value = (env[variable] ?? '').replace(/[\s\u00a0]+/g, '');
@@ -114,7 +114,7 @@ function validSessionId(value) {
114
114
  return value !== "" && value !== "." && value !== ".." && /^[A-Za-z0-9._-]+$/.test(value);
115
115
  }
116
116
  function sessionId(root, env, fileSystem) {
117
- for (const name of ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"]) {
117
+ for (const name of ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID", "HQ_FLEET_SESSION_ID"]) {
118
118
  const value = (env[name] ?? "").replace(/[ \t\n\v\f\r]/g, "");
119
119
  if (validSessionId(value))
120
120
  return value;
@@ -4,6 +4,8 @@ export type FastSentryReportDependencies = {
4
4
  initSentry: (overrides?: Partial<Pick<NodeOptions, "transport">>) => void;
5
5
  finishSentrySession: () => void;
6
6
  flushSentry: (timeoutMs: number) => PromiseLike<boolean>;
7
+ /** Close the transport's keep-alive sockets after the flush. */
8
+ closeSentryTransport?: () => void;
7
9
  addCommandBreadcrumb: () => void;
8
10
  report: typeof reportSentryEvent;
9
11
  };
@@ -1,6 +1,6 @@
1
1
  import { settleWithin } from "../utils/settle-with-timeout.js";
2
2
  import { beforeSend } from "../sentry-before-send.js";
3
- import { addSentryRuntimeBreadcrumb, flushSentryRuntime, finishSentryRuntimeSession, initSentryRuntime, } from "../sentry-init.js";
3
+ import { addSentryRuntimeBreadcrumb, closeSentryRuntimeTransport, flushSentryRuntime, finishSentryRuntimeSession, initSentryRuntime, } from "../sentry-init.js";
4
4
  import { addCommandBreadcrumb } from "../utils/command-breadcrumb.js";
5
5
  import { reportSentryEvent } from "../lib/core-utils/sentry-report.js";
6
6
  const SENTRY_FINALIZATION_TIMEOUT_MS = 500;
@@ -8,6 +8,7 @@ const defaultDependencies = {
8
8
  initSentry: (overrides) => { initSentryRuntime(beforeSend, overrides); },
9
9
  finishSentrySession: finishSentryRuntimeSession,
10
10
  flushSentry: flushSentryRuntime,
11
+ closeSentryTransport: closeSentryRuntimeTransport,
11
12
  addCommandBreadcrumb: () => addCommandBreadcrumb(process.argv.slice(2), addSentryRuntimeBreadcrumb),
12
13
  report: reportSentryEvent,
13
14
  };
@@ -49,6 +50,7 @@ export function runSentryReportFast(args, stdin, _cwd, hqRoot, _commandName, _hq
49
50
  return dependencies.report(stdin, { dryRun: false, timeoutMs, hqRoot }).then(async (result) => {
50
51
  dependencies.finishSentrySession();
51
52
  await settleWithin([Promise.resolve(dependencies.flushSentry(SENTRY_FINALIZATION_TIMEOUT_MS))], SENTRY_FINALIZATION_TIMEOUT_MS);
53
+ dependencies.closeSentryTransport?.();
52
54
  return result.code;
53
55
  });
54
56
  }