@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
@@ -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);
@@ -369,6 +369,56 @@ export declare function listAgentJobs(token: string, agentUid: string): Promise<
369
369
  export declare function pauseAgentJob(token: string, agentUid: string, jobId: string): Promise<PauseJobResult>;
370
370
  export declare function resumeAgentJob(token: string, agentUid: string, jobId: string): Promise<ResumeJobResult>;
371
371
  export declare function cancelAgentJob(token: string, agentUid: string, jobId: string): Promise<CancelJobResult>;
372
+ /** In-place edit body for `POST /v1/agents/{uid}/jobs/{jobId}/update`. */
373
+ export interface JobUpdateBody {
374
+ name?: string;
375
+ prompt?: string;
376
+ context?: Record<string, unknown> | null;
377
+ script?: string | null;
378
+ schedule?: {
379
+ kind: "recurring";
380
+ cron: string;
381
+ timezone: string;
382
+ } | {
383
+ kind: "once";
384
+ at: string;
385
+ timezone: string;
386
+ };
387
+ }
388
+ export interface UpdateJobResult {
389
+ job: {
390
+ jobId: string;
391
+ } & Record<string, unknown>;
392
+ changed: string[];
393
+ appliesFrom?: string;
394
+ /** Set when the edit saved but the new schedule has not reached the scheduler yet. */
395
+ warning?: string;
396
+ }
397
+ export declare function updateAgentJob(token: string, agentUid: string, jobId: string, body: JobUpdateBody): Promise<UpdateJobResult>;
398
+ export interface JobUpdateOptions {
399
+ name?: string;
400
+ prompt?: string;
401
+ cron?: string;
402
+ at?: string;
403
+ tz?: string;
404
+ context?: string;
405
+ clearContext?: boolean;
406
+ script?: string;
407
+ clearScript?: boolean;
408
+ }
409
+ /**
410
+ * Build the edit body from `hq agents jobs update` flags. Pure: file reads
411
+ * (`--prompt-file`, `--script-file`) happen before this is called. Throws a
412
+ * plain Error with operator copy on a bad combination.
413
+ *
414
+ * `--cron` takes the stored six-field `cron(...)`/`rate(...)` form verbatim
415
+ * or a standard five-field expression, translated with the same rules local
416
+ * bot jobs use. A schedule change needs an explicit `--tz`: defaulting to
417
+ * the operator's machine zone would silently move a job that runs in another
418
+ * zone. `--tz` on its own is refused.
419
+ */
420
+ export declare function buildJobUpdateBody(opts: JobUpdateOptions, translateCron: (expr: string) => string): JobUpdateBody;
421
+ export declare function formatUpdateResult(result: UpdateJobResult): string;
372
422
  /**
373
423
  * Map a jobs-control HTTP error to a single operator-facing line. Pure so the
374
424
  * status/code → copy mapping is unit-tested without a process exit.
@@ -378,7 +428,7 @@ export declare function cancelAgentJob(token: string, agentUid: string, jobId: s
378
428
  * the agent is cross-company) must print a clear message and exit non-zero,
379
429
  * never throw a stack trace.
380
430
  */
381
- export declare function formatJobsHttpError(err: AgentsHttpError, jobId?: string, action?: "resume"): string;
431
+ export declare function formatJobsHttpError(err: AgentsHttpError, jobId?: string, action?: "resume" | "update"): string;
382
432
  /** Stable padEnd table: jobId, scheduleState, rate, lastRunOutcome, status. */
383
433
  export declare function formatJobsTable(jobs: AgentJobView[]): string;
384
434
  export declare function formatPauseResult(result: PauseJobResult): string;
@@ -31,6 +31,7 @@ import { runResidentCommandWithPackageLease, } from "../utils/resident-package-p
31
31
  import { waitForAgentTerminalSession } from "../lib/agents/terminal-wait.js";
32
32
  import chalk from "chalk";
33
33
  import { randomUUID } from "node:crypto";
34
+ import { readFileSync } from "node:fs";
34
35
  import * as readline from "node:readline";
35
36
  import { resolveVaultCredential } from "../utils/resolve-vault-credential.js";
36
37
  import { maxLength } from "../utils/table-width.js";
@@ -39,6 +40,7 @@ import { gateApiKeyCapabilities } from "../utils/api-key-command-gate.js";
39
40
  import { queueCliLimitNoticeEngagement, queueCliLimitNoticeExposure, } from "../utils/cli-telemetry.js";
40
41
  import { vaultApiFetch, getCompanyUid } from "../utils/vault-api.js";
41
42
  import { consoleOrigin } from "./integrations-connect.js";
43
+ import { toEventBridgeCron } from "../lib/bot/eventbridge-cron.js";
42
44
  import { launchSessionManagerPlugin, SessionManagerPluginLaunchError, TerminalSessionTimeoutError, } from "@indigoai-us/hq-cloud/outposts/node";
43
45
  import { peekIdToken } from "../utils/id-token.js";
44
46
  import { canOfferTeamUpgrade, formatUpgradeRefusal, isPlanGateError, offerUpgradeLink, } from "../utils/plan-gate-error.js";
@@ -909,6 +911,94 @@ export async function cancelAgentJob(token, agentUid, jobId) {
909
911
  method: "POST",
910
912
  });
911
913
  }
914
+ export async function updateAgentJob(token, agentUid, jobId, body) {
915
+ return agentsRequest({
916
+ token,
917
+ path: `/v1/agents/${encodeURIComponent(agentUid)}/jobs/${encodeURIComponent(jobId)}/update`,
918
+ method: "POST",
919
+ body: { ...body },
920
+ });
921
+ }
922
+ /**
923
+ * Build the edit body from `hq agents jobs update` flags. Pure: file reads
924
+ * (`--prompt-file`, `--script-file`) happen before this is called. Throws a
925
+ * plain Error with operator copy on a bad combination.
926
+ *
927
+ * `--cron` takes the stored six-field `cron(...)`/`rate(...)` form verbatim
928
+ * or a standard five-field expression, translated with the same rules local
929
+ * bot jobs use. A schedule change needs an explicit `--tz`: defaulting to
930
+ * the operator's machine zone would silently move a job that runs in another
931
+ * zone. `--tz` on its own is refused.
932
+ */
933
+ export function buildJobUpdateBody(opts, translateCron) {
934
+ const body = {};
935
+ if (opts.name !== undefined)
936
+ body.name = opts.name;
937
+ if (opts.prompt !== undefined) {
938
+ if (!opts.prompt.trim())
939
+ throw new Error("--prompt cannot be empty.");
940
+ body.prompt = opts.prompt;
941
+ }
942
+ if (opts.cron !== undefined && opts.at !== undefined) {
943
+ throw new Error("Pass --cron or --at, not both.");
944
+ }
945
+ if (opts.tz !== undefined && opts.cron === undefined && opts.at === undefined) {
946
+ throw new Error("--tz changes the schedule, so pass --cron or --at with it.");
947
+ }
948
+ const timezone = opts.tz?.trim() ?? "";
949
+ if ((opts.cron !== undefined || opts.at !== undefined) && !timezone) {
950
+ throw new Error("Pass --tz <IANA timezone> with --cron or --at (for example --tz America/New_York), so the job's zone never changes by accident.");
951
+ }
952
+ if (opts.cron !== undefined) {
953
+ body.schedule = { kind: "recurring", cron: translateCron(opts.cron), timezone };
954
+ }
955
+ else if (opts.at !== undefined) {
956
+ const at = new Date(opts.at);
957
+ if (Number.isNaN(at.getTime())) {
958
+ throw new Error(`--at "${opts.at}" is not a date and time (use ISO-8601, e.g. 2026-12-01T09:00:00Z).`);
959
+ }
960
+ body.schedule = { kind: "once", at: at.toISOString(), timezone };
961
+ }
962
+ if (opts.context !== undefined && opts.clearContext) {
963
+ throw new Error("Pass --context or --clear-context, not both.");
964
+ }
965
+ if (opts.context !== undefined) {
966
+ let parsed;
967
+ try {
968
+ parsed = JSON.parse(opts.context);
969
+ }
970
+ catch {
971
+ throw new Error("--context must be a JSON object.");
972
+ }
973
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
974
+ throw new Error("--context must be a JSON object.");
975
+ }
976
+ body.context = parsed;
977
+ }
978
+ else if (opts.clearContext) {
979
+ body.context = null;
980
+ }
981
+ if (opts.script !== undefined && opts.clearScript) {
982
+ throw new Error("Pass --script-file or --clear-script, not both.");
983
+ }
984
+ if (opts.script !== undefined) {
985
+ if (!opts.script.trim())
986
+ throw new Error("The --script-file is empty.");
987
+ body.script = opts.script;
988
+ }
989
+ else if (opts.clearScript) {
990
+ body.script = null;
991
+ }
992
+ if (Object.keys(body).length === 0) {
993
+ throw new Error("Nothing to change. Pass --prompt, --prompt-file, --name, --cron, --at, --context or --script-file.");
994
+ }
995
+ return body;
996
+ }
997
+ export function formatUpdateResult(result) {
998
+ if (result.changed.length === 0)
999
+ return `${result.job.jobId} already matches; nothing changed.`;
1000
+ return `Updated ${result.job.jobId} (${result.changed.join(", ")}). Applies from the next run.`;
1001
+ }
912
1002
  /**
913
1003
  * Map a jobs-control HTTP error to a single operator-facing line. Pure so the
914
1004
  * status/code → copy mapping is unit-tested without a process exit.
@@ -943,8 +1033,14 @@ export function formatJobsHttpError(err, jobId, action) {
943
1033
  const id = jobId ?? extractQuotedJobId(err.message) ?? "unknown";
944
1034
  return `Job '${id}' not found.`;
945
1035
  }
1036
+ if (action === "update" && err.status === 404) {
1037
+ return "Agent not found or not accessible, or this HQ server cannot edit jobs yet.";
1038
+ }
946
1039
  if (err.status === 404)
947
1040
  return "Agent not found or not accessible.";
1041
+ if (err.code === "JOB_EDIT_BOX_CRON" || err.code === "JOB_EDIT_CONFLICT") {
1042
+ return err.message;
1043
+ }
948
1044
  if (err.code === "JOBS_SCHEDULER_UNAVAILABLE" ||
949
1045
  err.code === "SCHEDULE_DELETE_FAILED") {
950
1046
  return `${err.code}: ${err.message}`;
@@ -2090,7 +2186,7 @@ export function registerAgentsCommand(program) {
2090
2186
  // this file; keyed HQ_API_KEY rewrites /v1/agents → /v1/keys/agents.
2091
2187
  const jobs = agents
2092
2188
  .command("jobs")
2093
- .description("List, pause, resume, or cancel an agent's scheduled jobs");
2189
+ .description("List, edit, pause, resume, or delete an agent's scheduled jobs");
2094
2190
  jobs
2095
2191
  .command("list <agentUid>")
2096
2192
  .description("List an agent's scheduled jobs")
@@ -2142,9 +2238,65 @@ export function registerAgentsCommand(program) {
2142
2238
  failJobs(err, jobId, "resume");
2143
2239
  }
2144
2240
  });
2241
+ jobs
2242
+ .command("update <agentUid> <jobId>")
2243
+ .alias("edit")
2244
+ .description("Edit a job in place (instructions, schedule, name). Only the options you pass change; the job keeps its id and status, and the change applies from the next run.")
2245
+ .option("--company <slug>", "Company slug (to resolve an agent by name/slug)")
2246
+ .option("--prompt <text>", "New instructions")
2247
+ .option("--prompt-file <path>", "Read the new instructions from a file")
2248
+ .option("--name <label>", "Short label for the job")
2249
+ .option("--cron <expr>", 'New recurring schedule: "0 9 * * 1-5" or cron(...)/rate(...)')
2250
+ .option("--at <iso8601>", "New one-time run instant")
2251
+ .option("--tz <IANA>", "Timezone for --cron/--at (required with them)")
2252
+ .option("--context <json>", "Replace the JSON context handed to the agent at run time")
2253
+ .option("--clear-context", "Remove the job's context")
2254
+ .option("--script-file <path>", "Replace the precondition script with this file")
2255
+ .option("--clear-script", "Remove the job's precondition script")
2256
+ .option("--json", "Emit raw JSON")
2257
+ .action(async function (agentUid, jobId, opts) {
2258
+ let body;
2259
+ try {
2260
+ if (opts.prompt !== undefined && opts.promptFile !== undefined) {
2261
+ throw new Error("Pass --prompt or --prompt-file, not both.");
2262
+ }
2263
+ const prompt = opts.promptFile !== undefined ? readFileSync(opts.promptFile, "utf8") : opts.prompt;
2264
+ const script = opts.scriptFile !== undefined ? readFileSync(opts.scriptFile, "utf8") : undefined;
2265
+ body = buildJobUpdateBody({
2266
+ ...(prompt !== undefined ? { prompt } : {}),
2267
+ ...(opts.name !== undefined ? { name: opts.name } : {}),
2268
+ ...(opts.cron !== undefined ? { cron: opts.cron } : {}),
2269
+ ...(opts.at !== undefined ? { at: opts.at } : {}),
2270
+ ...(opts.tz !== undefined ? { tz: opts.tz } : {}),
2271
+ ...(opts.context !== undefined ? { context: opts.context } : {}),
2272
+ ...(opts.clearContext ? { clearContext: true } : {}),
2273
+ ...(script !== undefined ? { script } : {}),
2274
+ ...(opts.clearScript ? { clearScript: true } : {}),
2275
+ }, toEventBridgeCron);
2276
+ }
2277
+ catch (err) {
2278
+ console.error(chalk.red(err instanceof Error ? err.message : String(err)));
2279
+ process.exit(1);
2280
+ }
2281
+ const { token, targetUid } = await resolveJobsTargetOrExit(agentUid, companyOf(this));
2282
+ try {
2283
+ const result = await updateAgentJob(token, targetUid, jobId, body);
2284
+ if (opts.json) {
2285
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
2286
+ return;
2287
+ }
2288
+ console.log(chalk.green(formatUpdateResult(result)));
2289
+ if (result.warning)
2290
+ console.error(chalk.yellow(result.warning));
2291
+ }
2292
+ catch (err) {
2293
+ failJobs(err, jobId, "update");
2294
+ }
2295
+ });
2145
2296
  jobs
2146
2297
  .command("cancel <agentUid> <jobId>")
2147
- .description("Cancel a job and delete its schedule")
2298
+ .alias("delete")
2299
+ .description("Delete a job for good (active or paused) and its schedule")
2148
2300
  .option("--company <slug>", "Company slug (to resolve an agent by name/slug)")
2149
2301
  .action(async function (agentUid, jobId) {
2150
2302
  const { token, targetUid } = await resolveJobsTargetOrExit(agentUid, companyOf(this));
@@ -20,29 +20,16 @@ import { type LocalJobsApi } from "../lib/bot/local-jobs.js";
20
20
  import { type BotJobRecord, type CreateJobInput } from "../lib/bot/api.js";
21
21
  import { type BotConfig, type BotKind } from "../lib/bot/config.js";
22
22
  import { type FleetCronJob, type FleetCronOps } from "../lib/bot/fleet-cron.js";
23
+ import { BotJobsError, toEventBridgeCron } from "../lib/bot/eventbridge-cron.js";
24
+ export { BotJobsError, toEventBridgeCron };
23
25
  /** Mirrors hq-pro-agents `MIN_RECURRING_INTERVAL_SECONDS`. */
24
26
  export declare const MIN_RECURRING_INTERVAL_SECONDS: number;
25
27
  /** Mirrors hq-pro-agents `DEFAULT_MAX_ACTIVE_JOBS_PER_AGENT`. */
26
28
  export declare const MAX_ACTIVE_JOBS_PER_AGENT = 25;
27
29
  /** Mirrors hq-pro-agents `MAX_PROMPT_BYTES`. */
28
30
  export declare const MAX_PROMPT_BYTES: number;
29
- export declare class BotJobsError extends Error {
30
- readonly expected: true;
31
- }
32
31
  /** The machine's own IANA zone, so "9am" means 9am where the owner lives. */
33
32
  export declare function machineTimezone(): string;
34
- /**
35
- * Standard 5-field cron → the six-field `cron(...)` string a job is stored as.
36
- *
37
- * The stored form (the six-field cron syntax hosted agent jobs also use, so
38
- * local and hosted jobs share one format; the function keeps its historical
39
- * name) has SIX fields (a trailing year), numbers its days of week
40
- * 1–7 with SUNDAY = 1 (standard cron uses 0–6 with SUNDAY = 0), and refuses
41
- * `*` in BOTH the day-of-month and day-of-week fields — exactly one must be
42
- * `?`. An expression that is already `cron(...)` or `rate(...)` is passed
43
- * through untouched.
44
- */
45
- export declare function toEventBridgeCron(expr: string): string;
46
33
  /**
47
34
  * The smallest gap a recurring expression can produce, in seconds, or null
48
35
  * when it is not a recognised rate()/cron() form. Mirrors hq-pro-agents