@indigoai-us/hq-cli 5.345.212 → 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 (66) hide show
  1. package/CHANGELOG.md +20 -0
  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/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/core-handoff.js +1 -0
  9. package/dist/commands/core-hq-session-native.js +2 -2
  10. package/dist/commands/core-pin-native.js +1 -1
  11. package/dist/commands/core-policy.js +1 -1
  12. package/dist/commands/core-resolve-company-native.js +1 -1
  13. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  14. package/dist/commands/core-sentry-report-fast.js +3 -1
  15. package/dist/commands/daemon.js +11 -1
  16. package/dist/commands/integrations-connect.d.ts +7 -1
  17. package/dist/commands/integrations-connect.js +137 -13
  18. package/dist/commands/lanes-link.js +10 -5
  19. package/dist/commands/rescue.js +13 -0
  20. package/dist/commands/secrets.d.ts +11 -0
  21. package/dist/commands/secrets.js +41 -7
  22. package/dist/index.js +2 -0
  23. package/dist/lazy-commands.js +2 -0
  24. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  25. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  26. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  27. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  28. package/dist/lib/agent-kit/inbox-state.js +261 -4
  29. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  30. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  31. package/dist/lib/agent-kit/run/inbox.js +4 -2
  32. package/dist/lib/agent-kit/skills.js +4 -1
  33. package/dist/lib/agent-kit/wake.d.ts +9 -1
  34. package/dist/lib/agent-kit/wake.js +10 -3
  35. package/dist/lib/bot/fleet-cron.js +193 -14
  36. package/dist/lib/bot/fleet-download.d.ts +2 -0
  37. package/dist/lib/bot/fleet-download.js +23 -0
  38. package/dist/lib/bot/fleet-local.d.ts +1 -0
  39. package/dist/lib/bot/fleet-local.js +41 -8
  40. package/dist/lib/core-utils/session-id.d.ts +1 -1
  41. package/dist/lib/core-utils/session-id.js +4 -0
  42. package/dist/lib/daemon/run.js +9 -1
  43. package/dist/lib/daemon/updater.d.ts +34 -2
  44. package/dist/lib/daemon/updater.js +51 -2
  45. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  46. package/dist/lib/doctor/checks/release-links.js +260 -24
  47. package/dist/lib/doctor/fix/apply.js +24 -8
  48. package/dist/lib/doctor/fix/remediation.js +15 -5
  49. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  50. package/dist/lib/lanes/autopilot-registry.js +59 -7
  51. package/dist/lib/lanes/links.d.ts +14 -0
  52. package/dist/lib/lanes/links.js +320 -25
  53. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  54. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  55. package/dist/main.js +3 -1
  56. package/dist/sentry-init.d.ts +2 -0
  57. package/dist/sentry-init.js +13 -2
  58. package/dist/sentry.d.ts +2 -0
  59. package/dist/sentry.js +5 -1
  60. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  61. package/dist/utils/cli-network-lifecycle.js +52 -0
  62. package/dist/utils/safe-link.d.ts +63 -0
  63. package/dist/utils/safe-link.js +246 -0
  64. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  65. package/dist/utils/sentry-keepalive-transport.js +70 -0
  66. 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);
@@ -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
  }
@@ -1084,12 +1084,14 @@ async function runMigrate(d, opts) {
1084
1084
  d.out("Nothing was changed. `hq daemon migrate --apply` takes them over.");
1085
1085
  }
1086
1086
  async function runServiceSelfUpdate(d) {
1087
- const [{ daemonSelfUpdate }, { hostToolUpdater, runDaemonUpdater, updaterEnv }, { TOOL_NAMES }, { cliSelfUpdatable }, { updateManagedHqCloud },] = await Promise.all([
1087
+ const [{ daemonSelfUpdate }, { hostToolUpdater, resolveRunningDaemonVersion, runDaemonUpdater, updaterEnv }, { TOOL_NAMES }, { cliSelfUpdatable }, { updateManagedHqCloud }, { pingHqdVersion }, { CLI_VERSION },] = await Promise.all([
1088
1088
  import("../utils/self-update.js"),
1089
1089
  import("../lib/daemon/updater.js"),
1090
1090
  import("../lib/daemon/tools.js"),
1091
1091
  import("../lib/daemon/run.js"),
1092
1092
  import("../lib/daemon/hq-cloud.js"),
1093
+ import("../lib/daemon/convergence.js"),
1094
+ import("../cli-version.js"),
1093
1095
  ]);
1094
1096
  const { paths, detected } = currentHost(d);
1095
1097
  const env = updaterEnv(d.env);
@@ -1100,6 +1102,14 @@ async function runServiceSelfUpdate(d) {
1100
1102
  updateHqCloud: async () => updateManagedHqCloud(paths.root, env),
1101
1103
  hqCloudUnits: hqCloudUnits(detected.type, enabledServices(detected.type, readDaemonConfig(paths.configPath))),
1102
1104
  requestDaemonRestart: () => writeControlRequest(paths.requestsDir, { action: "restart-daemon", deferUntilSyncIdle: true }),
1105
+ // A daemon started before this release keeps its old code until it restarts.
1106
+ installedCliVersion: CLI_VERSION,
1107
+ // hqd answers only while HQ Anywhere is on; the fallbacks cover the rest.
1108
+ runningDaemonVersion: () => resolveRunningDaemonVersion({
1109
+ ping: () => pingHqdVersion(hqdSocketPath(d.home, d.env, d.platform)),
1110
+ env: d.env,
1111
+ parentCommandLine: () => processCommandLine(process.ppid),
1112
+ }),
1103
1113
  requestRestart: (unit) => writeControlRequest(paths.requestsDir, { action: "restart", unit }),
1104
1114
  log: d.out,
1105
1115
  });
@@ -120,7 +120,7 @@ export declare function consoleIntegrationsUrl(companySlug: string | undefined,
120
120
  * credentials — but only the console can collect them, so say what is needed
121
121
  * and hand the page over rather than restating the refusal and stopping.
122
122
  */
123
- export declare function bringYourOwnClientHandoff(target: ConnectTarget, opts: ConnectOptions, reason: string, redirectUri?: string): Promise<null>;
123
+ export declare function bringYourOwnClientHandoff(target: ConnectTarget, opts: ConnectOptions, reason: string, redirectUri?: string, resolveEndpoint?: () => Promise<string | undefined>): Promise<null>;
124
124
  /**
125
125
  * Google issues "Desktop app" and "Web application" OAuth clients with the
126
126
  * same client-id shape, but only a Web application client accepts HQ's hosted
@@ -135,5 +135,11 @@ export interface ConnectOwnership {
135
135
  viewerPersonUid?: string;
136
136
  }
137
137
  export declare function findAlreadyConnected(connections: readonly AdminConnection[], app: string, ownership?: ConnectOwnership): AdminConnection | undefined;
138
+ /**
139
+ * `connect --help` text for the `--json` stdout shapes. A sign-in that does
140
+ * not finish in this command prints exactly one JSON line on stdout, and
141
+ * `setup` says which of these it is.
142
+ */
143
+ export declare const CONNECT_JSON_HELP = "\n--json output when the sign-in does not finish in this command (for example\nwith --link-only) is one JSON line on stdout. \"setup\" says which it is:\n {\"app\",\"setup\":\"sign-in-link\",\"authorizationUrl\"}\n Open authorizationUrl; the sign-in finishes on the HQ console.\n {\"app\",\"setup\":\"own-oauth-app\",\"callbackUrl\",\"command\"}\n Register callbackUrl with the provider, then run command with your\n app's client id (and its secret on stdin).\n {\"app\",\"setup\":\"console\",\"url\"?,\"serverAddress\"?}\n Finish on the console page at url (left out when the console address\n is unknown). serverAddress is the MCP endpoint to enter there.\nA finished connect prints the install result instead. Confirm any of the\nthree with `hq integrations list`.\n";
138
144
  export declare function registerConnectCommands(integrations: Command): void;
139
145
  //# sourceMappingURL=integrations-connect.d.ts.map