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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +308 -43
  4. package/dist/command-catalog.generated.js +373 -43
  5. package/dist/command-registration-plan.d.ts +15 -0
  6. package/dist/command-registration-plan.js +20 -1
  7. package/dist/commands/agent-inbox.d.ts +11 -1
  8. package/dist/commands/agent-inbox.js +128 -38
  9. package/dist/commands/agent-kit.js +2 -2
  10. package/dist/commands/agents.js +6 -1
  11. package/dist/commands/billing.js +17 -4
  12. package/dist/commands/core-handoff.js +1 -0
  13. package/dist/commands/core-hq-session-native.js +2 -2
  14. package/dist/commands/core-pin-native.js +1 -1
  15. package/dist/commands/core-policy.js +1 -1
  16. package/dist/commands/core-resolve-company-native.js +1 -1
  17. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  18. package/dist/commands/core-sentry-report-fast.js +3 -1
  19. package/dist/commands/daemon.js +68 -6
  20. package/dist/commands/files.js +2 -2
  21. package/dist/commands/integrations-api.d.ts +11 -0
  22. package/dist/commands/integrations-connect.d.ts +9 -1
  23. package/dist/commands/integrations-connect.js +154 -18
  24. package/dist/commands/integrations-core.d.ts +1 -1
  25. package/dist/commands/integrations-core.js +18 -10
  26. package/dist/commands/integrations.js +1 -1
  27. package/dist/commands/lanes-link.js +10 -5
  28. package/dist/commands/lanes.js +34 -16
  29. package/dist/commands/rescue.js +13 -0
  30. package/dist/commands/secrets.d.ts +11 -0
  31. package/dist/commands/secrets.js +41 -7
  32. package/dist/index.js +2 -0
  33. package/dist/lazy-commands.js +6 -1
  34. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  35. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  36. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  37. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  38. package/dist/lib/agent-kit/inbox-state.js +261 -4
  39. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  40. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  41. package/dist/lib/agent-kit/run/inbox.js +4 -2
  42. package/dist/lib/agent-kit/skills.js +4 -1
  43. package/dist/lib/agent-kit/wake.d.ts +9 -1
  44. package/dist/lib/agent-kit/wake.js +10 -3
  45. package/dist/lib/billing/usage-only.d.ts +4 -1
  46. package/dist/lib/billing/usage-only.js +7 -2
  47. package/dist/lib/bot/fleet-cron.js +193 -14
  48. package/dist/lib/bot/fleet-download.d.ts +2 -0
  49. package/dist/lib/bot/fleet-download.js +23 -0
  50. package/dist/lib/bot/fleet-local.d.ts +1 -0
  51. package/dist/lib/bot/fleet-local.js +41 -8
  52. package/dist/lib/capacity/ledger.d.ts +7 -0
  53. package/dist/lib/capacity/ledger.js +31 -1
  54. package/dist/lib/capacity/project.d.ts +1 -1
  55. package/dist/lib/capacity/project.js +13 -4
  56. package/dist/lib/capacity/route.d.ts +10 -0
  57. package/dist/lib/capacity/route.js +16 -0
  58. package/dist/lib/core-utils/session-id.d.ts +1 -1
  59. package/dist/lib/core-utils/session-id.js +4 -0
  60. package/dist/lib/daemon/install.d.ts +15 -0
  61. package/dist/lib/daemon/install.js +31 -0
  62. package/dist/lib/daemon/migrate.js +29 -4
  63. package/dist/lib/daemon/run.js +9 -1
  64. package/dist/lib/daemon/updater.d.ts +34 -2
  65. package/dist/lib/daemon/updater.js +51 -2
  66. package/dist/lib/doctor/__testing__/run-doctor.js +4 -0
  67. package/dist/lib/doctor/checks/jq.d.ts +27 -0
  68. package/dist/lib/doctor/checks/jq.js +82 -0
  69. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  70. package/dist/lib/doctor/checks/release-links.js +260 -24
  71. package/dist/lib/doctor/fix/apply.js +24 -8
  72. package/dist/lib/doctor/fix/remediation.js +15 -5
  73. package/dist/lib/doctor/registry.js +4 -0
  74. package/dist/lib/flag-snapshot-file.js +36 -8
  75. package/dist/lib/install/codex-targets.d.ts +52 -1
  76. package/dist/lib/install/codex-targets.js +77 -2
  77. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  78. package/dist/lib/lanes/autopilot-registry.js +59 -7
  79. package/dist/lib/lanes/links.d.ts +14 -0
  80. package/dist/lib/lanes/links.js +320 -25
  81. package/dist/lib/lanes/monitor.d.ts +4 -1
  82. package/dist/lib/lanes/monitor.js +47 -10
  83. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  84. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  85. package/dist/lib/lanes/spawn.js +8 -1
  86. package/dist/lib/lanes/watch.js +31 -0
  87. package/dist/lib/onboarding/checkpoint.d.ts +6 -0
  88. package/dist/lib/onboarding/checkpoint.js +6 -0
  89. package/dist/lib/onboarding/orchestrator.d.ts +3 -1
  90. package/dist/lib/onboarding/orchestrator.js +62 -9
  91. package/dist/lib/onboarding/types.d.ts +8 -0
  92. package/dist/lib/work-context/organize.d.ts +23 -1
  93. package/dist/lib/work-context/organize.js +25 -3
  94. package/dist/lib/work-context/reconcile.js +3 -2
  95. package/dist/main.js +3 -1
  96. package/dist/secrets-env-action.js +7 -5
  97. package/dist/sentry-init.d.ts +2 -0
  98. package/dist/sentry-init.js +13 -2
  99. package/dist/sentry.d.ts +2 -0
  100. package/dist/sentry.js +5 -1
  101. package/dist/startup-registration.js +7 -2
  102. package/dist/utils/billing-gate.d.ts +12 -16
  103. package/dist/utils/billing-gate.js +17 -18
  104. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  105. package/dist/utils/cli-network-lifecycle.js +52 -0
  106. package/dist/utils/install-tree-torn.d.ts +22 -4
  107. package/dist/utils/install-tree-torn.js +24 -0
  108. package/dist/utils/registration-plan-error.d.ts +22 -0
  109. package/dist/utils/registration-plan-error.js +27 -0
  110. package/dist/utils/safe-link.d.ts +63 -0
  111. package/dist/utils/safe-link.js +246 -0
  112. package/dist/utils/sentry-fingerprint.js +3 -0
  113. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  114. package/dist/utils/sentry-keepalive-transport.js +70 -0
  115. package/dist/utils/unauthorized-error.d.ts +36 -0
  116. package/dist/utils/unauthorized-error.js +105 -0
  117. package/dist/utils/vault-api.js +7 -5
  118. package/package.json +7 -7
  119. package/scripts/install-hook-engine.mjs +17 -0
@@ -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);
@@ -170,6 +170,11 @@ export interface NowAccount {
170
170
  * been able to refresh them since.
171
171
  */
172
172
  usageStale?: boolean;
173
+ /**
174
+ * Newest failure for this account that is not a sign-in problem (parse
175
+ * drift, HTTP error), absent once a later reading from the account lands.
176
+ */
177
+ lastError?: string;
173
178
  limits: NowLimit[];
174
179
  }
175
180
  export interface NowProvider {
@@ -402,4 +407,6 @@ export declare function readLedgerEvents(options?: LedgerOptions): LedgerEvent[]
402
407
  export declare function readCollectorMark(options?: LedgerOptions): CollectorMark | null;
403
408
  export declare function setCollectorEnabled(enabled: boolean, options?: LedgerOptions): CollectorMark;
404
409
  export declare function rebuildNow(options?: LedgerOptions): NowView;
410
+ /** Newest uncleared parse or HTTP error among these accounts. */
411
+ export declare function newestAccountError(accounts: readonly NowAccount[]): string | null;
405
412
  //# sourceMappingURL=ledger.d.ts.map
@@ -881,7 +881,10 @@ function materialize(events, ctx) {
881
881
  }
882
882
  if (failed)
883
883
  state = "unknown";
884
- if (limits.length === 0 && failed)
884
+ // No mapped limit is never "ok". A labelled account's parse drift or HTTP
885
+ // error is account-scoped, so `failed` misses it; without this the
886
+ // provider read "ok" with an empty table (feedback_601a961f).
887
+ if (limits.length === 0)
885
888
  state = "unknown";
886
889
  const unknownLimit = limits.find((limit) => limit.state === "unknown" && limit.lastError);
887
890
  const lastError = failed
@@ -894,6 +897,10 @@ function materialize(events, ctx) {
894
897
  }
895
898
  const unscopedFailure = bucket.failure !== null && bucket.failure.at >= bucket.latestReadingAt;
896
899
  attachAccounts(entry, events, unscopedFailure);
900
+ // With no limits, show the newest account error (parse drift, HTTP error)
901
+ // that no later reading from that account has cleared.
902
+ if (limits.length === 0 && entry.lastError === null)
903
+ entry.lastError = newestAccountError(entry.accounts ?? []);
897
904
  if (provider === "codex" && !failed && entry.accounts?.length) {
898
905
  for (const account of entry.accounts) {
899
906
  if (account.authState === "ok" && account.state === "exhausted"
@@ -972,6 +979,7 @@ function clusterAccounts(provider, events) {
972
979
  organization: cleanOrganization(event.organization),
973
980
  at,
974
981
  problem: problemFor(event.error),
982
+ failure: problemFor(event.error) ? null : event.error,
975
983
  });
976
984
  continue;
977
985
  }
@@ -985,6 +993,7 @@ function clusterAccounts(provider, events) {
985
993
  organization: cleanOrganization(reading.organization),
986
994
  at,
987
995
  problem: null,
996
+ failure: null,
988
997
  });
989
998
  }
990
999
  if (seeds.length === 0)
@@ -1035,6 +1044,8 @@ function clusterAccounts(provider, events) {
1035
1044
  let problem = null;
1036
1045
  let latestReadingAt = Number.NEGATIVE_INFINITY;
1037
1046
  let latestAt = Number.NEGATIVE_INFINITY;
1047
+ let latestDataAt = Number.NEGATIVE_INFINITY;
1048
+ let failure = null;
1038
1049
  for (const seed of members) {
1039
1050
  for (const label of seed.labels) {
1040
1051
  if (!labels.includes(label))
@@ -1051,7 +1062,13 @@ function clusterAccounts(provider, events) {
1051
1062
  latestReadingAt = seed.at;
1052
1063
  if (seed.at > latestAt)
1053
1064
  latestAt = seed.at;
1065
+ if (seed.failure !== null && (!failure || seed.at >= failure.at))
1066
+ failure = { error: seed.failure, at: seed.at };
1067
+ if (seed.problem === null && seed.failure === null && seed.at > latestDataAt)
1068
+ latestDataAt = seed.at;
1054
1069
  }
1070
+ // The account's newest parse or HTTP error, until a later reading clears it.
1071
+ const accountError = failure && failure.at >= latestDataAt ? failure.error : null;
1055
1072
  const ordered = orderLabels(labels);
1056
1073
  const primary = ordered.find((label) => label !== "default") ?? ordered[0] ?? "default";
1057
1074
  const limitedIds = ids.filter((id) => provider.limits.some((limit) => limit.accountId === id));
@@ -1099,12 +1116,25 @@ function clusterAccounts(provider, events) {
1099
1116
  : capacityLoginCommand(provider.provider, primary))
1100
1117
  : null,
1101
1118
  usageStale: usageStale ? true : undefined,
1119
+ lastError: accountError ?? undefined,
1102
1120
  limits,
1103
1121
  });
1104
1122
  }
1105
1123
  accounts.sort((a, b) => (a.labels[0] ?? "").localeCompare(b.labels[0] ?? ""));
1106
1124
  return accounts;
1107
1125
  }
1126
+ /** Newest uncleared parse or HTTP error among these accounts. */
1127
+ export function newestAccountError(accounts) {
1128
+ let best = null;
1129
+ for (const account of accounts) {
1130
+ if (!account.lastError)
1131
+ continue;
1132
+ const at = account.observedAt ?? "";
1133
+ if (!best || at > best.at)
1134
+ best = { error: account.lastError, at };
1135
+ }
1136
+ return best?.error ?? null;
1137
+ }
1108
1138
  function problemFor(error) {
1109
1139
  if (isExpiredReason(error))
1110
1140
  return { kind: "expired", reason: EXPIRED_REASON };
@@ -1,5 +1,5 @@
1
1
  import type { CapacityAccount } from "./accounts.js";
2
- import type { NowView } from "./ledger.js";
2
+ import { type NowView } from "./ledger.js";
3
3
  export interface ProjectCapacityOptions {
4
4
  accounts: readonly CapacityAccount[];
5
5
  /**
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
+ import { newestAccountError } from "./ledger.js";
13
14
  const STATE_RANK = {
14
15
  ok: 0,
15
16
  "reset-pending": 1,
@@ -131,9 +132,8 @@ function recomputeFromAccounts(provider, accounts) {
131
132
  }
132
133
  let state = "ok";
133
134
  if (limits.length === 0) {
134
- state = accounts.some((account) => account.authState === "expired" || account.authState === "signed_out" || account.signedOut)
135
- ? "unknown"
136
- : "ok";
135
+ // No limit rows is never "ok", signed in or not (feedback_601a961f).
136
+ state = "unknown";
137
137
  }
138
138
  else {
139
139
  for (const limit of limits) {
@@ -141,12 +141,20 @@ function recomputeFromAccounts(provider, accounts) {
141
141
  state = limit.state;
142
142
  }
143
143
  }
144
+ // The ledger fills an empty provider's lastError from an account's error. Show
145
+ // such an error only when its account is still in this projection; an account
146
+ // whose home left the registry is hidden, and so is its error.
147
+ const fromAccount = provider.lastError !== null
148
+ && (provider.accounts ?? []).some((account) => account.lastError === provider.lastError);
149
+ const providerError = fromAccount ? null : provider.lastError;
144
150
  return {
145
151
  ...provider,
146
152
  accounts,
147
153
  limits,
148
154
  state,
149
- lastError: state === "unknown" ? accounts.find((account) => account.reason)?.reason ?? provider.lastError : null,
155
+ lastError: state === "unknown"
156
+ ? accounts.find((account) => account.reason)?.reason ?? newestAccountError(accounts) ?? providerError
157
+ : null,
150
158
  };
151
159
  }
152
160
  function withoutAccounts(provider) {
@@ -223,6 +231,7 @@ function mergeGroup(group, homes, labels, provider) {
223
231
  reason: problem?.reason ?? null,
224
232
  fixCommand: problem?.fixCommand ?? null,
225
233
  usageStale: usageStale ? true : undefined,
234
+ lastError: newestAccountError(group.map((piece) => piece.account)) ?? undefined,
226
235
  limits,
227
236
  };
228
237
  }
@@ -168,6 +168,16 @@ export interface StaleReadingTarget {
168
168
  * reading cannot help.
169
169
  */
170
170
  export declare function staleReadingTargets(result: RouteResult): StaleReadingTarget[];
171
+ /**
172
+ * True when a refusal rests on no usage reading at all: nothing was ranked,
173
+ * and every skipped lane account was skipped only because the ledger has no
174
+ * reading for it yet (feedback_9e444a9f, feedback_86552798). On a fresh
175
+ * ledger that is the normal state until the first reading lands, so it says
176
+ * nothing about room. A skip for a used-up, signed-out, usage-only or
177
+ * day-old account is evidence and keeps the refusal. Skips with no lane
178
+ * account (a sign-in no lane uses) do not count either way.
179
+ */
180
+ export declare function refusalHasNoReadings(result: RouteResult): boolean;
171
181
  export declare class RouteUsageError extends Error {
172
182
  readonly code = "route_usage";
173
183
  constructor(message: string);
@@ -153,6 +153,22 @@ export function staleReadingTargets(result) {
153
153
  }
154
154
  return targets;
155
155
  }
156
+ /**
157
+ * True when a refusal rests on no usage reading at all: nothing was ranked,
158
+ * and every skipped lane account was skipped only because the ledger has no
159
+ * reading for it yet (feedback_9e444a9f, feedback_86552798). On a fresh
160
+ * ledger that is the normal state until the first reading lands, so it says
161
+ * nothing about room. A skip for a used-up, signed-out, usage-only or
162
+ * day-old account is evidence and keeps the refusal. Skips with no lane
163
+ * account (a sign-in no lane uses) do not count either way.
164
+ */
165
+ export function refusalHasNoReadings(result) {
166
+ if (result.ok && result.pick)
167
+ return false;
168
+ if (result.ranked.length > 0)
169
+ return false;
170
+ return result.skipped.every((entry) => !entry.account || entry.reason === SKIP_NO_READING);
171
+ }
156
172
  export class RouteUsageError extends Error {
157
173
  code = "route_usage";
158
174
  constructor(message) {
@@ -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);