@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
@@ -4,6 +4,7 @@ import * as path from "node:path";
4
4
  import { effectiveBotCompanies, effectiveBotKind } from "./config.js";
5
5
  import { fleetLocalRuntimePython, stderrTail } from "./fleet-local.js";
6
6
  import { readLocalJobs, withJobsLock, writeLocalJobs } from "./local-jobs.js";
7
+ import { signInCommand } from "./runtime-sign-in.js";
7
8
  import { currentHotSignalSyncCompany, forgetHotSignalSyncRegistrationsExcept, hotSignalSyncJobCompany, fleetHotSignalSyncRegistered, markFleetHotSignalSyncRegistered, otherBotWithHotSignalSync, } from "./jobs/hot-signal-sync.js";
8
9
  const RESULT_MARKER = "@@HQ_FLEET_CRON@@";
9
10
  export const FLEET_CRON_BRIDGE = [
@@ -216,35 +217,213 @@ export function companyOfHotSignalSyncJob(job) {
216
217
  const match = /^hot-signal-sync-([a-z0-9][a-z0-9_-]*)\.py$/i.exec(path.basename(job.script));
217
218
  return match ? match[1] : null;
218
219
  }
220
+ /**
221
+ * Python helpers for the flag-off script's failure alert. No backticks and no
222
+ * `${` here: the text is a raw template. Fix steps come in through FIXES.
223
+ *
224
+ * - scheduled_time(): the job's own daily time from the Fleet cron store next
225
+ * to the script (<profile>/scripts/<script>.py, <profile>/cron/jobs.json),
226
+ * so a time moved with `hq sources schedule --at` or `hq bot jobs
227
+ * --reschedule` shows. Disabled entries are skipped. When the store or a
228
+ * daily schedule cannot be read, the time this run started.
229
+ * - redact(): the credential patterns of utils/redact-error-text.ts (and the
230
+ * secret query and fragment values and opaque path segments of
231
+ * utils/redact-url.ts), applied to any line of hq's
232
+ * output before it goes into the owner's DM.
233
+ * - classify(): one short reason and one fix step from what hq printed.
234
+ */
235
+ const HOT_SIGNAL_SYNC_ALERT_HELPERS = String.raw `ANSI = re.compile(r'\x1b\[[0-9;]*m')
236
+ REASON_MAX = 200
237
+
238
+ def scheduled_time():
239
+ try:
240
+ here = os.path.abspath(__file__)
241
+ store = os.path.join(os.path.dirname(os.path.dirname(here)), 'cron', 'jobs.json')
242
+ with open(store, encoding='utf-8') as f:
243
+ data = json.load(f)
244
+ jobs = data.get('jobs', []) if isinstance(data, dict) else data
245
+ if isinstance(jobs, dict):
246
+ jobs = list(jobs.values())
247
+ for job in jobs:
248
+ if not isinstance(job, dict) or os.path.basename(str(job.get('script') or '')) != os.path.basename(here):
249
+ continue
250
+ if job.get('enabled') is False or str(job.get('state') or '').lower() in ('disabled', 'paused'):
251
+ continue
252
+ schedule = job.get('schedule')
253
+ expr = schedule.get('expr') if isinstance(schedule, dict) else schedule
254
+ m = re.match(r'^(\d{1,2})\s+(\d{1,2})\s+\*\s+\*\s+\*$', str(expr or '').strip())
255
+ if m and int(m.group(2)) < 24 and int(m.group(1)) < 60:
256
+ return '%02d:%02d' % (int(m.group(2)), int(m.group(1)))
257
+ except Exception:
258
+ pass
259
+ return time.strftime('%H:%M', STARTED)
260
+
261
+ SECRET_LABEL = re.compile(r'''\b(password|secret|client[_-]?secret|api[_-]?key|(?:id|access|refresh)[_-]?token|token|authorization)\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s&"'<>;,}]+)''', re.I)
262
+ SECRET_QUERY = re.compile(r'''([?&;#](?:[A-Za-z0-9_.-]*(?:key|token|secret|password|signature|credentials?)|pass|pwd|sig|auth|authorization|session|code|[A-Za-z0-9_.-]*[_-]code)=)[^&#\s"'<>]+''', re.I)
263
+
264
+ URL_IN_TEXT = re.compile(r'''\b[a-z][a-z0-9+.-]*://[^\s<>"'\x60]+''', re.I)
265
+ URL_PARTS = re.compile(r'^([a-z][a-z0-9+.-]*://[^/?#]*)([^?#]*)(.*)$', re.I | re.S)
266
+ SECRET_PATH_LABEL = re.compile(r'^(?:access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|x?mcpkey|client[_-]?secret|token|key|secret|password|pass|pwd|auth|authorization|sig|signature|credential|credentials|session)[=_-].+$', re.I | re.S)
267
+
268
+ def opaque_segment(segment):
269
+ # isOpaqueCapabilitySegment in utils/redact-url.ts, for a webhook or
270
+ # capability URL whose secret is a path segment.
271
+ if SECRET_PATH_LABEL.match(segment):
272
+ return True
273
+ n = len(segment)
274
+ letter = re.search(r'[A-Za-z]', segment) is not None
275
+ digit = re.search(r'[0-9]', segment) is not None
276
+ long_hex = n >= 24 and re.match(r'^[A-Fa-f0-9]+$', segment) is not None
277
+ long_b64 = n >= 32 and re.match(r'^[A-Za-z0-9_-]+$', segment) is not None and letter and (digit or re.search(r'[A-Z_-]', segment) is not None)
278
+ return (n >= 20 and letter and digit) or long_hex or long_b64
279
+
280
+ def redact_url_path(match):
281
+ url = match.group(0)
282
+ tail = re.search(r'[),.;!?]+$', url)
283
+ punct = tail.group(0) if tail else ''
284
+ url = url[:len(url) - len(punct)]
285
+ head, route, rest = URL_PARTS.match(url).groups()
286
+ route = '/'.join('[REDACTED]' if opaque_segment(urllib.parse.unquote(s)) else s for s in route.split('/'))
287
+ return head + route + rest + punct
288
+
289
+ def redact(text):
290
+ # User info runs to the last @ before the host, so a raw @ in a password
291
+ # does not leave the rest of it visible.
292
+ text = re.sub(r'(\b[a-z][a-z0-9+.-]*://)[^/\s?#]*@', r'\1[REDACTED]@', text, flags=re.I)
293
+ text = URL_IN_TEXT.sub(redact_url_path, text)
294
+ text = SECRET_QUERY.sub(lambda m: m.group(1) + '[REDACTED]', text)
295
+ # The output is split into lines before redact() runs, so a private key
296
+ # arrives one line at a time: mask its BEGIN/END lines, and a body line that
297
+ # starts with a DER key header (MII, MIG, MHc) or the OpenSSH key magic.
298
+ text = re.sub(r'-----(?:BEGIN|END)[A-Z0-9 ]*PRIVATE KEY-----', '[REDACTED]', text)
299
+ text = re.sub(r'\b(?:MII|MIG|MHc|b3BlbnNzaC1rZXktdjE)[A-Za-z0-9+/]{20,}={0,2}', '[REDACTED]', text)
300
+ text = re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', text)
301
+ text = re.sub(r'\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]+', '[REDACTED]', text, flags=re.I)
302
+ text = SECRET_LABEL.sub(lambda m: m.group(1) + '=[REDACTED]', text)
303
+ text = re.sub(r'\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b', '[REDACTED]', text)
304
+ text = re.sub(r'\b(?:hqk_|xox[abprs]-|github_pat_|gh[pousr]_)[A-Za-z0-9_-]+\b', '[REDACTED]', text, flags=re.I)
305
+ text = re.sub(r'\bsk-ant-[A-Za-z0-9_-]+', '[REDACTED]', text)
306
+ text = re.sub(r'\bAKIA[0-9A-Z]{16}\b', '[REDACTED]', text)
307
+ return re.sub(r'\s+', ' ', text).strip()
308
+
309
+ ERRORISH = re.compile(r'\b(?:fail(?:ed|ure|s)?|errors?|stopped|could not|cannot|denied|unauthori[sz]ed|forbidden|refused|invalid|expired|timed out|not found)\b', re.I)
310
+
311
+ def output_lines(source):
312
+ return [l.strip() for l in ANSI.sub('', source or '').splitlines() if l.strip()]
313
+
314
+ def last_error_line(out, err):
315
+ # A recognised error (a line hq marks with its error cross, or one that says
316
+ # it failed) wins over a stdout failure line, which wins over a plain stderr
317
+ # warning such as a skipped event.
318
+ errs, outs = output_lines(err), output_lines(out)
319
+ for lines in (
320
+ [l for l in errs if l.startswith('✗') or ERRORISH.search(l)],
321
+ [l for l in outs if ERRORISH.search(l)],
322
+ errs,
323
+ ):
324
+ for line in reversed(lines):
325
+ clean = redact(line.lstrip('✗').strip())[:REASON_MAX].rstrip('. ')
326
+ if clean:
327
+ return clean
328
+ return ''
329
+
330
+ def signal_name(number):
331
+ try:
332
+ return signal.Signals(number).name
333
+ except Exception:
334
+ return ''
335
+
336
+ def classify(out, err, code):
337
+ if code < 0:
338
+ name = signal_name(-code)
339
+ return 'hq was stopped by signal %d%s' % (-code, ' (' + name + ')' if name else ''), FIXES['signal']
340
+ text = ANSI.sub('', (err or '') + '\n' + (out or ''))
341
+ if re.search(r"HQ session has expired|not signed in to HQ|Sign in to HQ first|run .hq login", text, re.I):
342
+ return 'you are signed out of HQ', FIXES['hq_signed_out']
343
+ if re.search(r'claude could not start:.*\bENOENT\b|spawn claude ENOENT', text, re.I):
344
+ return 'Claude Code is not installed on this computer', FIXES['claude_missing']
345
+ if re.search(r'claude-logged-out|claude (reported it )?is not logged in|claude could not start', text, re.I):
346
+ return 'Claude is signed out on this computer', FIXES['claude_signed_out']
347
+ timed_out = re.search(r'claude timed out after \d+ ?ms on (\S+)', text, re.I)
348
+ if timed_out or re.search(r'claude-timeout', text, re.I):
349
+ key = timed_out.group(1).rstrip('.,;:)\'"') if timed_out else ''
350
+ if re.match(r'^sources/[A-Za-z0-9._/-]+\.md$', key) and '..' not in key:
351
+ return 'Claude ran out of time on one document', FIXES['claude_timeout_key'].replace('KEY', key)
352
+ return 'Claude ran out of time on one document', FIXES['claude_timeout']
353
+ if re.search(r'fetch failed|ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|socket hang up', text, re.I):
354
+ return 'HQ could not reach the network', FIXES['network']
355
+ line = last_error_line(out, err)
356
+ if line:
357
+ return line, FIXES['other']
358
+ return 'hq stopped with exit code %d and gave no reason' % code, FIXES['unknown']
359
+ `;
360
+ /** How a run ended, for the log line after it: `exit 1` or `signal 9`. */
361
+ const HOT_SIGNAL_SYNC_RUN_END = String.raw `def run_end(code):
362
+ return 'signal %d' % -code if code < 0 else 'exit %d' % code
363
+ `;
219
364
  export function renderFleetHotSignalSyncScript(input) {
220
- const args = input.signalsEngine === false
365
+ const plainSync = input.signalsEngine === false;
366
+ const args = plainSync
221
367
  ? ["sources", "sync", "--company", input.company, "--hq-root", input.hqRoot]
222
368
  : ["signals", "run", "--trigger", "job", "--company", input.company, "--hq-root", input.hqRoot, "--report-found"];
369
+ const syncCommand = `hq sources sync --company ${input.company}`;
370
+ const fixes = {
371
+ hq_signed_out: "run `hq login`.",
372
+ claude_signed_out: `run \`${signInCommand("claude")}\`.`,
373
+ claude_missing: `install Claude Code (\`npm install -g @anthropic-ai/claude-code\`), then run \`${signInCommand("claude")}\`.`,
374
+ claude_timeout_key: `run \`hq sources signals --company ${input.company} --key KEY\` to retry that document.`,
375
+ claude_timeout: "the next run retries the document.",
376
+ network: `check this computer's connection. The next run retries, or run \`${syncCommand}\` now.`,
377
+ signal: `run \`${syncCommand}\` to see whether it happens again.`,
378
+ other: `run \`${syncCommand}\` to see the full error.`,
379
+ unknown: `run \`${syncCommand}\` to see what goes wrong.`,
380
+ };
381
+ // One header per run, so an alert's start time finds its entry in the log,
382
+ // and one line after it with how the run ended.
383
+ const header = ` log.write('=== ' + time.strftime('%Y-%m-%d %H:%M:%S %z', STARTED) + ${JSON.stringify(` hot-signal-sync for ${input.company} ===`)} + '\\n')`;
384
+ const footer = " log.write('=== ' + run_end(result.returncode) + ' ===\\n')";
223
385
  // The engine prints only when it finds new signals (--report-found), so its
224
- // stdout goes to the owner's DM as is. The plain sync prints a report every
225
- // run, so with the flag off its stdout goes to the log and the owner hears
226
- // only about a run that failed (for example, nobody signed in or the signals
227
- // pass failed). The script exits with hq's code, so the job's status is not
228
- // `ok` after a failed run: Fleet records a no-agent job from its exit code.
229
- const deliver = input.signalsEngine === false
386
+ // stdout goes to the owner's DM as is, and its stderr streams to the log
387
+ // while it runs. The plain sync prints a report every run, so with the flag
388
+ // off both streams go to the log and the owner hears only about a run that
389
+ // failed, with the job's time, the reason, one fix step and the log. The
390
+ // plain script exits non-zero after a failed run (128 + N after signal N, as
391
+ // a shell does), so the job's status is not `ok`: Fleet records a no-agent
392
+ // job from its exit code.
393
+ const run = plainSync
230
394
  ? [
395
+ " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8', errors='replace')",
231
396
  " with open(LOG, 'a', encoding='utf-8') as log:",
397
+ header,
398
+ " log.write(result.stderr)",
232
399
  " log.write(result.stdout)",
400
+ footer,
233
401
  " if result.returncode != 0:",
234
- ` sys.stdout.write(${JSON.stringify(`The 06:30 hot-channel sync for ${input.company} did not finish. Details are in `)} + LOG + '\\n')`,
235
- " sys.exit(result.returncode)",
402
+ " reason, fix = classify(result.stdout, result.stderr, result.returncode)",
403
+ ` sys.stdout.write('The ' + scheduled_time() + ${JSON.stringify(` hot-channel sync for ${input.company} did not finish: `)} + reason + '.\\n')`,
404
+ " sys.stdout.write('Fix: ' + fix + '\\n')",
405
+ " sys.stdout.write('Log: ' + LOG + ' (run started ' + time.strftime('%Y-%m-%d %H:%M', STARTED) + ')\\n')",
406
+ " sys.exit(128 - result.returncode if result.returncode < 0 else result.returncode)",
236
407
  ]
237
- : [" sys.stdout.write(result.stdout)"];
408
+ : [
409
+ " with open(LOG, 'a', encoding='utf-8') as log:",
410
+ header,
411
+ " log.flush()",
412
+ " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=log, encoding='utf-8', errors='replace')",
413
+ footer,
414
+ " sys.stdout.write(result.stdout)",
415
+ ];
238
416
  return [
239
- "import subprocess, sys",
417
+ plainSync ? "import json, os, re, signal, subprocess, sys, time, urllib.parse" : "import subprocess, sys, time",
240
418
  `NODE = ${JSON.stringify(input.nodeBinary)}`,
241
419
  `HQ = ${JSON.stringify(input.hqBinary)}`,
242
420
  `ARGS = ${JSON.stringify(args)}`,
243
421
  `LOG = ${JSON.stringify(input.logFile)}`,
422
+ "STARTED = time.localtime()",
423
+ HOT_SIGNAL_SYNC_RUN_END,
424
+ ...(plainSync ? [`FIXES = ${JSON.stringify(fixes)}`, HOT_SIGNAL_SYNC_ALERT_HELPERS] : []),
244
425
  "try:",
245
- " with open(LOG, 'a', encoding='utf-8') as log:",
246
- " result = subprocess.run([NODE, HQ, *ARGS], stdout=subprocess.PIPE, stderr=log, text=True)",
247
- ...deliver,
426
+ ...run,
248
427
  "except OSError as exc:",
249
428
  " with open(LOG, 'a', encoding='utf-8') as log:",
250
429
  " log.write('hot-signal-sync could not run hq: ' + str(exc) + '\\n')",
@@ -28,6 +28,8 @@ export interface FleetDownloadOptions {
28
28
  * the server told us its size, the sizes match.
29
29
  */
30
30
  export declare function downloadFleetFile(url: string, destination: string, options?: FleetDownloadOptions): Promise<string>;
31
+ export declare const FLEET_DOWNLOAD_PREFERRED_MAX_RESUMES = 1;
32
+ export declare function downloadFleetFileFromSources(urls: readonly string[], destination: string, options?: FleetDownloadOptions, accept?: (file: string) => boolean): Promise<string>;
31
33
  /** sha256 of a file on disk, streamed. */
32
34
  export declare function fileSha256(file: string): string;
33
35
  //# sourceMappingURL=fleet-download.d.ts.map
@@ -266,6 +266,29 @@ export async function downloadFleetFile(url, destination, options = {}) {
266
266
  const cause = lastFailure instanceof Error ? lastFailure.message : String(lastFailure ?? "unknown error");
267
267
  throw expectedError(`Could not download ${name} after ${maxResumes + 1} attempts (${cause}). Check your internet connection and retry; the download continues where it stopped.`);
268
268
  }
269
+ export const FLEET_DOWNLOAD_PREFERRED_MAX_RESUMES = 1;
270
+ export async function downloadFleetFileFromSources(urls, destination, options = {}, accept) {
271
+ if (urls.length === 0)
272
+ throw expectedError(`Could not download ${path.basename(destination)}: no download source.`);
273
+ let failure = null;
274
+ for (const [index, url] of urls.entries()) {
275
+ const last = index === urls.length - 1;
276
+ const maxResumes = last
277
+ ? options.maxResumes
278
+ : Math.min(options.maxResumes ?? FLEET_DOWNLOAD_MAX_RESUMES, FLEET_DOWNLOAD_PREFERRED_MAX_RESUMES);
279
+ try {
280
+ const file = await downloadFleetFile(url, destination, { ...options, ...(maxResumes !== undefined ? { maxResumes } : {}) });
281
+ if (last || !accept || accept(file))
282
+ return file;
283
+ fs.rmSync(file, { force: true });
284
+ failure = expectedError(`Could not download ${path.basename(destination)}: a download source returned the wrong file.`);
285
+ }
286
+ catch (error) {
287
+ failure = error;
288
+ }
289
+ }
290
+ throw failure;
291
+ }
269
292
  /** sha256 of a file on disk, streamed. */
270
293
  export function fileSha256(file) {
271
294
  const hash = crypto.createHash("sha256");
@@ -273,6 +273,7 @@ export declare function installTargetFleetLocalDistribution(deps?: Omit<FleetLoc
273
273
  target?: FleetLocalTargetRelease;
274
274
  now?: () => number;
275
275
  }): Promise<FleetLocalInstallation>;
276
+ export declare function fleetReleaseCdnLinkName(name: string): string;
276
277
  /** What an install is doing right now, for a progress bar or a log line. */
277
278
  export type FleetInstallProgress = {
278
279
  phase: "download-start";
@@ -7,7 +7,7 @@ import * as zlib from "node:zlib";
7
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
8
  import { HQ_FLEET_RUNTIME_ENGINE_ID, } from "./config.js";
9
9
  import { withBotLock } from "./lock.js";
10
- import { downloadFleetFile, fileSha256 } from "./fleet-download.js";
10
+ import { downloadFleetFileFromSources, fileSha256 } from "./fleet-download.js";
11
11
  import { ensureFleetPython, fleetUvEnv } from "./fleet-python.js";
12
12
  import semver from "semver";
13
13
  import { CLI_VERSION } from "../../cli-version.js";
@@ -421,8 +421,11 @@ export async function lookupHqFleetReleaseLinks(release, deps = {}) {
421
421
  const body = (await response.json());
422
422
  const links = new Map();
423
423
  for (const asset of body.assets ?? []) {
424
- if (typeof asset.name === "string" && typeof asset.url === "string")
424
+ if (typeof asset.name === "string" && typeof asset.url === "string") {
425
425
  links.set(asset.name, asset.url);
426
+ if (typeof asset.cdnUrl === "string")
427
+ links.set(fleetReleaseCdnLinkName(asset.name), asset.cdnUrl);
428
+ }
426
429
  }
427
430
  return links.size > 0 ? { links, reason: null } : { links: null, reason: "not_published" };
428
431
  }
@@ -551,8 +554,11 @@ export function parseFleetLocalReleasePointer(body, now = Date.now()) {
551
554
  const links = new Map();
552
555
  for (const asset of Array.isArray(record.assets) ? record.assets : []) {
553
556
  const entry = asset;
554
- if (typeof entry?.name === "string" && typeof entry.url === "string")
557
+ if (typeof entry?.name === "string" && typeof entry.url === "string") {
555
558
  links.set(entry.name, entry.url);
559
+ if (typeof entry.cdnUrl === "string")
560
+ links.set(fleetReleaseCdnLinkName(entry.name), entry.cdnUrl);
561
+ }
556
562
  }
557
563
  const expires = typeof record.expiresInSeconds === "number" && record.expiresInSeconds > 0 ? record.expiresInSeconds : 0;
558
564
  return {
@@ -712,6 +718,21 @@ function trustedReleaseLink(url) {
712
718
  return false;
713
719
  }
714
720
  }
721
+ export function fleetReleaseCdnLinkName(name) {
722
+ return `cdn:${name}`;
723
+ }
724
+ function trustedReleaseCdnLink(url) {
725
+ try {
726
+ const parsed = new URL(url);
727
+ return parsed.protocol === "https:" && parsed.hostname.endsWith(".cloudfront.net");
728
+ }
729
+ catch {
730
+ return false;
731
+ }
732
+ }
733
+ function releaseCdnDisabled(env = process.env) {
734
+ return env.HQ_FLEET_RELEASE_CDN?.trim().toLowerCase() === "off";
735
+ }
715
736
  export const FLEET_LOCAL_METADATA_DOWNLOAD_TIMEOUT_MS = 30_000;
716
737
  /** One machine-wide lock: concurrent creates and adopts share one download instead of repeating it. */
717
738
  export const FLEET_LOCAL_DISTRIBUTION_LOCK_NAME = "hq-fleet-local-distribution";
@@ -737,6 +758,12 @@ function discardDownloads(target) {
737
758
  }
738
759
  async function downloadReleaseFiles(release, fetcher, resolve, cachedRuntime, target, onProgress, stallMs) {
739
760
  fs.mkdirSync(target, { recursive: true, mode: 0o700 });
761
+ const pinned = new Map([
762
+ [release.artifact, release.artifactSha256],
763
+ [release.runtimeArtifact, release.runtimeArtifactSha256],
764
+ ["release-manifest.json", release.manifestSha256],
765
+ ["release-manifest.sig", release.signatureSha256],
766
+ ]);
740
767
  const downloaded = new Map();
741
768
  const wanted = RELEASE_FILE_NAMES(release).filter((name) => {
742
769
  if (name === release.runtimeArtifact && cachedRuntime) {
@@ -747,7 +774,8 @@ async function downloadReleaseFiles(release, fetcher, resolve, cachedRuntime, ta
747
774
  });
748
775
  const sources = wanted.map((name) => ({ name, ...resolve(name) }));
749
776
  onProgress?.({ phase: "download-start", files: wanted.length });
750
- await Promise.all(sources.map(async ({ name, url, headers }) => {
777
+ await Promise.all(sources.map(async ({ name, urls, headers }) => {
778
+ const url = urls.at(-1);
751
779
  if (url.startsWith("file:")) {
752
780
  const destination = path.join(target, name);
753
781
  fs.copyFileSync(fileURLToPath(url), destination);
@@ -756,12 +784,12 @@ async function downloadReleaseFiles(release, fetcher, resolve, cachedRuntime, ta
756
784
  downloaded.set(name, destination);
757
785
  return;
758
786
  }
759
- const file = await downloadFleetFile(url, path.join(target, name), {
787
+ const file = await downloadFleetFileFromSources(urls, path.join(target, name), {
760
788
  fetch: fetcher,
761
789
  ...(headers ? { headers } : {}),
762
790
  ...(stallMs !== undefined ? { stallMs } : {}),
763
791
  onProgress: (progress) => onProgress?.({ phase: "download", file: name, received: progress.received, total: progress.total }),
764
- });
792
+ }, (candidate) => fileSha256(candidate) === pinned.get(name));
765
793
  downloaded.set(name, file);
766
794
  }));
767
795
  return {
@@ -782,7 +810,12 @@ async function downloadFleetLocalReleaseFromHq(release, fetcher, links, cachedRu
782
810
  throw expectedError(`HQ Fleet Local ${release.tag} returned an untrusted download link for ${name}.`);
783
811
  }
784
812
  }
785
- return downloadReleaseFiles(release, fetcher, (name) => ({ url: links.get(name) }), cachedRuntime, target, onProgress, stallMs);
813
+ const cdnUsable = !releaseCdnDisabled();
814
+ return downloadReleaseFiles(release, fetcher, (name) => {
815
+ const cdn = cdnUsable ? links.get(fleetReleaseCdnLinkName(name)) : undefined;
816
+ const candidates = cdn && trustedReleaseCdnLink(cdn) ? [cdn] : [];
817
+ return { urls: [...candidates, links.get(name)] };
818
+ }, cachedRuntime, target, onProgress, stallMs);
786
819
  }
787
820
  async function downloadFleetLocalRelease(release, fetcher, token, cachedRuntime, target, onProgress, stallMs) {
788
821
  const headers = {
@@ -810,7 +843,7 @@ async function downloadFleetLocalRelease(release, fetcher, token, cachedRuntime,
810
843
  throw expectedError(`HQ Fleet Local ${release.tag} returned an untrusted asset URL for ${name}.`);
811
844
  }
812
845
  }
813
- return downloadReleaseFiles(release, fetcher, (name) => ({ url: assets.get(name), headers: { ...headers, Accept: "application/octet-stream" } }), cachedRuntime, target, onProgress, stallMs);
846
+ return downloadReleaseFiles(release, fetcher, (name) => ({ urls: [assets.get(name)], headers: { ...headers, Accept: "application/octet-stream" } }), cachedRuntime, target, onProgress, stallMs);
814
847
  }
815
848
  function installedFiles(dir, release) {
816
849
  const archive = path.join(dir, release.artifact);
@@ -1,4 +1,4 @@
1
- export declare const SESSION_ID_ENV_KEYS: readonly ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"];
1
+ export declare const SESSION_ID_ENV_KEYS: readonly ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID", "HQ_FLEET_SESSION_ID"];
2
2
  export declare function validSessionId(value: string): boolean;
3
3
  export declare function sessionIdFromEnv(env: NodeJS.ProcessEnv): string;
4
4
  /** Resolve the caller's session before using the global, last-writer-wins .current fallback. */
@@ -1,5 +1,8 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
+ // Same order as hq-core core/scripts/lib/session-id.sh (hq-core-staging #1818).
4
+ // HQ_FLEET_SESSION_ID is the only id an HQ Fleet scheduled job has. It ranks
5
+ // after the harness ids, which the scope guard sees in its hook payload.
3
6
  export const SESSION_ID_ENV_KEYS = [
4
7
  "HQ_SESSION_ID",
5
8
  "CLAUDE_CODE_SESSION_ID",
@@ -7,6 +10,7 @@ export const SESSION_ID_ENV_KEYS = [
7
10
  "CODEX_SESSION_ID",
8
11
  "CODEX_THREAD_ID",
9
12
  "GROK_SESSION_ID",
13
+ "HQ_FLEET_SESSION_ID",
10
14
  ];
11
15
  export function validSessionId(value) {
12
16
  return Boolean(value) && value !== "." && value !== ".." && /^[A-Za-z0-9._-]+$/.test(value);
@@ -575,7 +575,15 @@ export function prepareUnitStart(unit, log, alive) {
575
575
  * an on-failure unit down. The daemon's updater handles CLI updates.
576
576
  */
577
577
  export function unitProcessEnv(base, unit) {
578
- const env = { ...base, ...unit.env, HQ_DAEMON_UNIT: unit.id, HQ_NO_UPDATE_CHECK: "1" };
578
+ // HQ_DAEMON_CLI_VERSION tells the updater unit which release this daemon
579
+ // runs when hqd (HQ Anywhere) is off, so it can replace an older daemon.
580
+ const env = {
581
+ ...base,
582
+ ...unit.env,
583
+ HQ_DAEMON_UNIT: unit.id,
584
+ HQ_DAEMON_CLI_VERSION: CLI_VERSION,
585
+ HQ_NO_UPDATE_CHECK: "1",
586
+ };
579
587
  for (const key of DAEMON_CHILD_ONE_SHOT_KEYS)
580
588
  delete env[key];
581
589
  // Scheduled hq commands stay eligible for Sentry. The resident mark goes only
@@ -11,8 +11,9 @@
11
11
  * 3. Install or update the daemon's own hq-cloud (sync and the outpost
12
12
  * heartbeat run from it when it is newer than the CLI's bundled copy), and
13
13
  * restart sync and the heartbeat right after it changes.
14
- * 4. After a CLI update, ask the daemon to restart itself so the supervisor and
15
- * every service run the new version. The remote-control hosts notice an
14
+ * 4. After a CLI update, or when the running daemon reports an older version
15
+ * than the CLI on disk, ask the daemon to restart itself so the supervisor
16
+ * and every service run the new version. The remote-control hosts notice an
16
17
  * updated Claude or Codex on disk themselves and restart once idle.
17
18
  */
18
19
  import type { SelfUpdateOutcome } from "../../utils/self-update.js";
@@ -36,6 +37,15 @@ export interface UpdaterDeps {
36
37
  /** The units on this machine that run hq-cloud code, restarted after it updates. */
37
38
  hqCloudUnits: readonly string[];
38
39
  requestDaemonRestart: () => void;
40
+ /**
41
+ * The version of the hq CLI on disk (this process's own; the daemon starts
42
+ * each unit from the installed CLI) and a probe for the version the running
43
+ * daemon reports. When the daemon is older it is restarted even though this
44
+ * run updated nothing: the CLI may have been replaced by the desktop app,
45
+ * `hq update` or npm while a daemon from an older release kept running.
46
+ */
47
+ installedCliVersion?: string;
48
+ runningDaemonVersion?: () => Promise<string | null>;
39
49
  /** Restart one unit (a restart request to the running daemon). */
40
50
  requestRestart: (unit: string) => void;
41
51
  log: (line: string) => void;
@@ -45,6 +55,28 @@ export interface UpdaterResult {
45
55
  /** Tools whose version changed in this run. */
46
56
  updated: ToolName[];
47
57
  }
58
+ /** Only a strictly older, parseable daemon version triggers a restart, so a dev build never loops. */
59
+ export declare function daemonIsOlderThanCli(running: string, installed: string): boolean;
60
+ /**
61
+ * The version a daemon handed to the staged child bootstrap that started this
62
+ * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
63
+ * Daemons have started units this way since 2026-10-05 (#1541).
64
+ */
65
+ export declare function daemonVersionFromBootstrapCommandLine(line: string | null): string | null;
66
+ export interface RunningDaemonVersionDeps {
67
+ /** Ask hqd; it listens only while HQ Anywhere is on, so this often fails. */
68
+ ping: () => Promise<string>;
69
+ env: NodeJS.ProcessEnv;
70
+ /** The command line of this unit's parent process (the child bootstrap). */
71
+ parentCommandLine: () => string | null;
72
+ }
73
+ /**
74
+ * The hq-cli version the running daemon was started from. hqd first; then the
75
+ * version a newer daemon puts in the unit's environment; then the version an
76
+ * older daemon passed to the child bootstrap, which covers daemons from before
77
+ * this release on machines with HQ Anywhere off.
78
+ */
79
+ export declare function resolveRunningDaemonVersion(deps: RunningDaemonVersionDeps): Promise<string | null>;
48
80
  export declare function runDaemonUpdater(deps: UpdaterDeps): Promise<UpdaterResult>;
49
81
  /**
50
82
  * The variables for the updater's own CLI update. Every supervised service
@@ -11,13 +11,55 @@
11
11
  * 3. Install or update the daemon's own hq-cloud (sync and the outpost
12
12
  * heartbeat run from it when it is newer than the CLI's bundled copy), and
13
13
  * restart sync and the heartbeat right after it changes.
14
- * 4. After a CLI update, ask the daemon to restart itself so the supervisor and
15
- * every service run the new version. The remote-control hosts notice an
14
+ * 4. After a CLI update, or when the running daemon reports an older version
15
+ * than the CLI on disk, ask the daemon to restart itself so the supervisor
16
+ * and every service run the new version. The remote-control hosts notice an
16
17
  * updated Claude or Codex on disk themselves and restart once idle.
17
18
  */
18
19
  import { spawnSync } from "node:child_process";
19
20
  import * as fs from "node:fs";
21
+ import semver from "semver";
20
22
  import { locateTool, toolUpdateCommand } from "./tools.js";
23
+ /** Only a strictly older, parseable daemon version triggers a restart, so a dev build never loops. */
24
+ export function daemonIsOlderThanCli(running, installed) {
25
+ const r = semver.valid(running);
26
+ const i = semver.valid(installed);
27
+ return r !== null && i !== null && semver.lt(r, i);
28
+ }
29
+ /**
30
+ * The version a daemon handed to the staged child bootstrap that started this
31
+ * unit: `<node> <...>/hq-child-bootstrap.mjs <prefix> <version> [args]`.
32
+ * Daemons have started units this way since 2026-10-05 (#1541).
33
+ */
34
+ export function daemonVersionFromBootstrapCommandLine(line) {
35
+ if (!line)
36
+ return null;
37
+ const match = /hq-child-bootstrap\.m?js\s.*?(?:^|\s)(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)(?=\s|$)/.exec(line);
38
+ return match?.[1] ?? null;
39
+ }
40
+ /**
41
+ * The hq-cli version the running daemon was started from. hqd first; then the
42
+ * version a newer daemon puts in the unit's environment; then the version an
43
+ * older daemon passed to the child bootstrap, which covers daemons from before
44
+ * this release on machines with HQ Anywhere off.
45
+ */
46
+ export async function resolveRunningDaemonVersion(deps) {
47
+ try {
48
+ return await deps.ping();
49
+ }
50
+ catch {
51
+ // fall through to the local sources
52
+ }
53
+ const fromEnv = deps.env.HQ_DAEMON_CLI_VERSION?.trim();
54
+ if (fromEnv)
55
+ return fromEnv;
56
+ try {
57
+ return daemonVersionFromBootstrapCommandLine(deps.parentCommandLine());
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
21
63
  export async function runDaemonUpdater(deps) {
22
64
  let ok = true;
23
65
  // The restart stops this process too, so it is requested only once all the
@@ -42,6 +84,13 @@ export async function runDaemonUpdater(deps) {
42
84
  deps.log(`hq CLI: ${cli.action === "current" ? "up to date" : cli.action}`);
43
85
  }
44
86
  }
87
+ if (!restart && deps.installedCliVersion && deps.runningDaemonVersion) {
88
+ const running = await deps.runningDaemonVersion().catch(() => null);
89
+ if (running && daemonIsOlderThanCli(running, deps.installedCliVersion)) {
90
+ deps.log(`hqd still runs hq-cli ${running}, older than the installed ${deps.installedCliVersion}; the daemon restarts onto it once the tools are checked`);
91
+ restart = true;
92
+ }
93
+ }
45
94
  if (deps.updateHqCloud) {
46
95
  const cloud = await deps.updateHqCloud().catch((err) => ({
47
96
  ok: false,