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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/assets/scaffold/core/scripts/lib/trigger-fact-text.awk +152 -41
  3. package/dist/command-catalog.generated.d.ts +28 -0
  4. package/dist/command-catalog.generated.js +34 -0
  5. package/dist/commands/bot-runtime.d.ts +21 -2
  6. package/dist/commands/bot-runtime.js +54 -9
  7. package/dist/commands/bot.d.ts +13 -0
  8. package/dist/commands/bot.js +142 -12
  9. package/dist/commands/core-derive-trigger-facts-native.d.ts +1 -0
  10. package/dist/commands/core-derive-trigger-facts-native.js +61 -11
  11. package/dist/commands/core-work-mesh-bind-trusted-native.d.ts +14 -2
  12. package/dist/commands/core-work-mesh-bind-trusted-native.js +62 -8
  13. package/dist/commands/daemon.js +3 -0
  14. package/dist/commands/integrations-connect.d.ts +16 -0
  15. package/dist/commands/integrations-connect.js +23 -4
  16. package/dist/commands/whoami.js +7 -6
  17. package/dist/lib/bot/api.d.ts +1 -1
  18. package/dist/lib/bot/config.js +2 -1
  19. package/dist/lib/bot/fleet-daemon.d.ts +4 -0
  20. package/dist/lib/bot/fleet-daemon.js +12 -1
  21. package/dist/lib/bot/fleet-download.d.ts +6 -0
  22. package/dist/lib/bot/fleet-download.js +128 -3
  23. package/dist/lib/bot/fleet-local.d.ts +38 -1
  24. package/dist/lib/bot/fleet-local.js +239 -26
  25. package/dist/lib/bot/install-progress.d.ts +28 -0
  26. package/dist/lib/bot/install-progress.js +185 -0
  27. package/dist/lib/bot/legacy-provider-login.d.ts +22 -1
  28. package/dist/lib/bot/legacy-provider-login.js +67 -9
  29. package/dist/lib/bot/prompt.d.ts +1 -0
  30. package/dist/lib/bot/prompt.js +3 -2
  31. package/dist/lib/bot/readiness.d.ts +68 -0
  32. package/dist/lib/bot/readiness.js +145 -0
  33. package/dist/lib/bot/run.d.ts +2 -0
  34. package/dist/lib/bot/run.js +6 -3
  35. package/dist/lib/bot/scaffold.d.ts +6 -3
  36. package/dist/lib/bot/scaffold.js +18 -12
  37. package/dist/lib/daemon/catalog.d.ts +9 -0
  38. package/dist/lib/daemon/catalog.js +13 -1
  39. package/dist/lib/daemon/run.d.ts +6 -3
  40. package/dist/lib/daemon/run.js +43 -6
  41. package/dist/lib/daemon/supervisor.d.ts +3 -0
  42. package/dist/lib/daemon/supervisor.js +64 -3
  43. package/dist/lib/sync-core/reconcile.js +15 -11
  44. package/package.json +7 -7
@@ -52,6 +52,7 @@ import { executiveStatus } from "../lib/bot/executive-settings.js";
52
52
  import { describeExecutiveBotSource, resolveExecutiveBot, setExecutiveBot } from "../lib/bot/executive.js";
53
53
  import { executiveHotSignalSyncCompanies } from "../lib/bot/executive-sync.js";
54
54
  import { readBotListedProcess } from "../lib/bot/listed-running.js";
55
+ import { DEFAULT_BOT_READY_TIMEOUT_SECONDS, botReadinessReport, clearBotSetupStep, createSetupStepReporter, readBotSetupStep, waitForGatewayReady, writeBotSetupStep, } from "../lib/bot/readiness.js";
55
56
  import { ensureFleetHotSignalSync, fleetCronOps, migrateLegacyJobsToFleet } from "../lib/bot/fleet-cron.js";
56
57
  import { resolvePackSetupPrompt } from "../lib/bot/pack-setup.js";
57
58
  import { detectCodingToolActivity } from "../lib/bot/coding-tool-activity.js";
@@ -80,7 +81,8 @@ import { PROBE_DEFAULT_TIMEOUT_MS, probeBotRuntime } from "../lib/bot/probe.js";
80
81
  import { BOT_LOGIN_RUNTIMES, botAuthEnv, botRuntimeAuth, capacityAccountHome, describeBotAuth, formatBotAuth, isBotLoginRuntime, restoreBotSessions, setAsideBotSessions, signInBotRuntime, signOutBotRuntime, withRuntimeAuth, } from "../lib/bot/runtime-auth.js";
81
82
  import { BotApi, BotApiError, BOT_RESTORE_DEFAULTS, buildBotLocalConfig, describeBotLocalConfig, orphanBotRunMessage, parseBotLocalConfig, removeOrphanBotDaemon, botDaemonStatus, botDir, botCredsPath, botLogPath, botsRoot, botTokenStateDir, botWorkerRelDir, buildBotDaemonPaths, createBotLogger, deleteBotCreds, installBotDaemon, repairBotDaemonIfStale, healBotDaemonNodeFromJob, introDmText, isBotMemoryMode, botLocalMemoryDir, botMemoryMode, resolveBotMemoryDir, validateBotIntro, validateBotDisplayName, validateBotKickoff, validateBotEffort, validateBotModel, effectiveBotEffort, BOT_EFFORT_LEVELS, DEFAULT_BOT_EFFORT, BOT_MEMORY_MODES, BOT_KINDS, isBotKind, effectiveBotKind, effectiveBotCompanies, normalizeBotCompanies, SETUP_BOT_WORKER_ID, isBotRuntimeId, localNameForRemoteBot, remoteBotRunnability, isPidAlive, listBotWorkerOptions, patchBotConfig, readBotConfig, readBotCredsIdentity, readBotStatus, patchBotStatus, runtimeCrashSinceStart, resolveBotWorker, runBot, runtimeFor, scaffoldBotMemory, scaffoldBotWorker, startBotDaemon, stopBotDaemon, uninstallBotDaemon, validateBotName, writeBotConfig, writeBotCreds, BOT_RUNTIMES, BOT_INTRO_MAX_CHARS, BOT_DISPLAY_NAME_MAX_CHARS, BOT_KICKOFF_MAX_CHARS, detectBotPlatform, withBotLock, localBotRole, remoteBotRole, remoteBotDisplayName, personFacingName, writeCloudDisplayName, setupSlugFor, ASSISTANT_ROLE, HQ_FLEET_RUNTIME_ENGINE_ID, HQ_FLEET_LOCAL_RELEASE, authenticateFleetLocalBot, bootstrapFleetLocalBot, buildSystemPrompt, controlFleetBot as controlFleetLocalBot, fleetBotUnitId, fleetBotsManagedByDaemon, ensureFleetPython, fleetLocalGatewayPid, fleetLocalProfileNeedsAdoption, fleetLocalServiceInstalled, fleetProviderForRuntime, importFleetLocalMachineCredential, importFleetLocalProviderLogin, fleetProviderNeedsSignIn, fleetOwnerCompanies, refreshFleetLocalInstructions, fleetLocalPromotionRuntime, installPinnedFleetLocalDistribution, installTargetFleetLocalDistribution, resolveFleetLocalPointerTarget, resolveFleetLocalTargetRelease, fleetLocalProfileDir, fleetProfileOwnerCompanies, fleetLocalChannels, readFleetLocalGatewayState, readPromptSources, removeFleetLocalBot, } from "../lib/bot/index.js";
82
83
  import { gatedInteractiveLogin } from "../utils/interactive-caller.js";
83
- import { fleetInstallProgressReporter, runBotRuntimeInstall, runBotRuntimeStatus } from "./bot-runtime.js";
84
+ import { fleetInstallProgressReporter, fleetRuntimeStatus, runBotAuthStatus, runBotRuntimeInstall, runBotRuntimeStatus } from "./bot-runtime.js";
85
+ import { ensureFleetRuntimeInstalled } from "../lib/bot/fleet-local.js";
84
86
  function collectRepeated(value, previous) {
85
87
  return [...previous, value];
86
88
  }
@@ -549,6 +551,13 @@ function rowFor(name, opts = {}) {
549
551
  const legacy = fleet ? null : opts.legacy ?? legacyMoveState(dir, config, legacyConvertSeams.providerLogin(dir, config));
550
552
  const pid = listed.pid;
551
553
  const processAlive = listed.running;
554
+ const readiness = botReadinessReport({
555
+ setupStep: readBotSetupStep(dir),
556
+ fleet,
557
+ processAlive,
558
+ livePid: pid,
559
+ gateway: fleet ? readFleetLocalGatewayState(config.agentUid) : null,
560
+ });
552
561
  // Turns this bot has taken and not finished: what "thinking" means.
553
562
  const inflightTurns = readInflightTurns(dir);
554
563
  let daemonInstalled = false;
@@ -576,6 +585,7 @@ function rowFor(name, opts = {}) {
576
585
  effort: effectiveBotEffort(config),
577
586
  effortIsDefault: !config.effort,
578
587
  state: processAlive ? "running" : !fleet && status?.state === "failed" ? "failed" : "stopped",
588
+ ...readiness,
579
589
  pid: processAlive ? pid : null,
580
590
  processAlive,
581
591
  hosting: hasActivePromotion(dir, config.agentUid, config.ownerUid) ? "cloud" : "local",
@@ -647,6 +657,8 @@ async function decorateOnline(rows) {
647
657
  }));
648
658
  }
649
659
  function humanOnline(row) {
660
+ if (row.readiness === "creating" || row.readiness === "installing" || row.readiness === "starting")
661
+ return chalk.yellow(row.readiness);
650
662
  if (row.lastHeartbeatOk === false)
651
663
  return chalk.red("unreachable");
652
664
  if (row.online === true)
@@ -848,6 +860,9 @@ async function convertLegacyBotToFleet(name, dir, config, from) {
848
860
  };
849
861
  if (from === "start")
850
862
  await stopBot(name, dir, config, "silent");
863
+ const daemonRunsIt = fleetBotsManagedByDaemon();
864
+ if (daemonRunsIt)
865
+ writeBotConfig(dir, fleet);
851
866
  let failure = null;
852
867
  try {
853
868
  refreshFleetLocalInstructions(config.agentUid, fleetBotSystemPrompt(name, fleet));
@@ -865,6 +880,8 @@ async function convertLegacyBotToFleet(name, dir, config, from) {
865
880
  catch {
866
881
  /* nothing was running */
867
882
  }
883
+ if (daemonRunsIt)
884
+ writeBotConfig(dir, current);
868
885
  keepLegacy("start", failure);
869
886
  return ready();
870
887
  }
@@ -1027,7 +1044,7 @@ async function installFleetRuntimeProfile(name, dir, config, opts = {}) {
1027
1044
  installation = await installTargetFleetLocalDistribution({ target, onProgress: progress });
1028
1045
  }
1029
1046
  catch (err) {
1030
- if (target.source !== "pointer")
1047
+ if (target.source !== "pointer" || target.localFile)
1031
1048
  throw err;
1032
1049
  if (opts.pointerOnly) {
1033
1050
  createBotLogger(dir)("warn", `could not install HQ Fleet Local ${target.release.version} (${err instanceof Error ? err.message : String(err)}); the bot stays on its current release`);
@@ -1069,6 +1086,9 @@ async function installFleetRuntimeProfile(name, dir, config, opts = {}) {
1069
1086
  export const botCreateSeams = {
1070
1087
  /** The Claude Code login read the way the HQ Fleet Runtime reads it. */
1071
1088
  claudeLogin: () => checkClaudeCodeLogin(),
1089
+ runtimeStatus: fleetRuntimeStatus,
1090
+ installRuntime: ensureFleetRuntimeInstalled,
1091
+ waitForReady: waitForGatewayReady,
1072
1092
  };
1073
1093
  /**
1074
1094
  * A Claude bot on the HQ Fleet Runtime answers with the owner's Claude Code
@@ -1232,6 +1252,15 @@ export function resolveCreateKind(opts, worker) {
1232
1252
  }
1233
1253
  return { kind, companies };
1234
1254
  }
1255
+ function removeEmptyDir(dir) {
1256
+ try {
1257
+ if (fs.readdirSync(dir).length === 0)
1258
+ fs.rmdirSync(dir);
1259
+ }
1260
+ catch {
1261
+ return;
1262
+ }
1263
+ }
1235
1264
  /**
1236
1265
  * `hq bot create`. Runs under the bot's lock, so a create racing an adopt,
1237
1266
  * restore, rm or set of the same bot waits for it instead of tripping over
@@ -1240,7 +1269,16 @@ export function resolveCreateKind(opts, worker) {
1240
1269
  export async function runBotCreate(nameArg, opts) {
1241
1270
  try {
1242
1271
  const name = validateBotName(nameArg);
1243
- await withBotLock(name, () => runBotCreateLocked(name, opts), { command: "hq bot create" });
1272
+ const dir = botDir(name);
1273
+ const dirExisted = fs.existsSync(dir);
1274
+ try {
1275
+ await withBotLock(name, () => runBotCreateLocked(name, opts), { command: "hq bot create" });
1276
+ }
1277
+ finally {
1278
+ clearBotSetupStep(dir);
1279
+ if (!dirExisted)
1280
+ removeEmptyDir(dir);
1281
+ }
1244
1282
  }
1245
1283
  catch (err) {
1246
1284
  // Under --json the desktop app reads stdout: a failure, including one in
@@ -1362,6 +1400,31 @@ async function finishExistingSetupBot(name, dir, config, displayName, opts) {
1362
1400
  else if (opts.start !== false)
1363
1401
  console.log(chalk.yellow(`${name} did not report running within 15s`) + chalk.dim(` logs: hq bot logs ${name}`));
1364
1402
  }
1403
+ export function parseReadyTimeoutSeconds(value) {
1404
+ if (value === undefined)
1405
+ return DEFAULT_BOT_READY_TIMEOUT_SECONDS;
1406
+ const seconds = typeof value === "number" ? value : Number(String(value).trim());
1407
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) {
1408
+ throw Object.assign(new Error("--ready-timeout must be a whole number of seconds from 1 to 3600."), { expected: true });
1409
+ }
1410
+ return seconds;
1411
+ }
1412
+ export function createReadyMessage(name, readiness, wait, timeoutMs) {
1413
+ if (readiness === "ready")
1414
+ return `${name} is ready to chat.`;
1415
+ if (wait?.failed)
1416
+ return `${name} could not start: ${wait.failed}. See its logs with hq bot logs ${name}, then run hq bot restart ${name}.`;
1417
+ if (wait?.timedOut) {
1418
+ return `${name} is still getting ready after ${Math.round(timeoutMs / 1000)} seconds. It finishes on its own; check with hq bot status ${name}.`;
1419
+ }
1420
+ return null;
1421
+ }
1422
+ function createReadyLine(name, readiness, wait, timeoutMs) {
1423
+ const message = createReadyMessage(name, readiness, wait, timeoutMs);
1424
+ if (!message)
1425
+ return null;
1426
+ return readiness === "ready" ? chalk.green(message) : chalk.yellow(message);
1427
+ }
1365
1428
  async function runBotCreateLocked(name, opts) {
1366
1429
  if (opts.legacyRuntime) {
1367
1430
  throw Object.assign(new Error("--legacy-runtime is no longer supported: new bots run on the HQ Fleet Runtime. Drop --legacy-runtime."), { expected: true });
@@ -1521,10 +1584,20 @@ async function runBotCreateLocked(name, opts) {
1521
1584
  // of sending another create that the entity store will reject.
1522
1585
  if (isSetupBot && (await adoptOwnedSetupBot(true)))
1523
1586
  return;
1524
- const progress = fleetInstallProgressReporter(opts.json ? "silent" : "text");
1525
- const fleetInstallation = await installTargetFleetLocalDistribution({ onProgress: progress });
1587
+ const readyTimeoutMs = parseReadyTimeoutSeconds(opts.readyTimeout) * 1000;
1588
+ const progress = fleetInstallProgressReporter(opts.json ? (opts.progress ? "json" : "silent") : "text");
1589
+ const steps = createSetupStepReporter(opts.json ? (opts.progress ? "json" : "silent") : "text");
1590
+ const fleetTarget = await resolveFleetLocalTargetRelease();
1591
+ const runtimeStatus = await botCreateSeams.runtimeStatus({ target: fleetTarget });
1592
+ if (!opts.json)
1593
+ console.log(chalk.dim(`Setting up ${name} takes ${runtimeStatus.estimate}.`));
1594
+ steps.begin("install");
1595
+ const fleetInstallation = await installTargetFleetLocalDistribution({ target: fleetTarget, onProgress: progress });
1526
1596
  progress({ phase: "python" });
1527
1597
  const fleetPython = await ensureFleetPython();
1598
+ await botCreateSeams.installRuntime(fleetInstallation, { python: fleetPython, onProgress: progress });
1599
+ steps.finish("install", runtimeStatus.installed ? "skipped" : "done");
1600
+ steps.begin("identity");
1528
1601
  const ownerCompanies = kind === "personal" ? await fleetOwnerCompanies() : companies;
1529
1602
  // A company bot's companies are resolved first (a typo must not cost an
1530
1603
  // identity) and sent with the create: the server makes the bot a member of
@@ -1595,6 +1668,7 @@ async function runBotCreateLocked(name, opts) {
1595
1668
  throw err;
1596
1669
  }
1597
1670
  const agentUid = created.agent.uid;
1671
+ steps.identify(agentUid);
1598
1672
  writeBotCreds(dir, {
1599
1673
  username: created.identity.cognitoUsername,
1600
1674
  secret: created.identity.secret,
@@ -1603,6 +1677,7 @@ async function runBotCreateLocked(name, opts) {
1603
1677
  clientId: DEFAULT_COGNITO.clientId,
1604
1678
  region: DEFAULT_COGNITO.region,
1605
1679
  });
1680
+ const daemonRunsFleetBots = fleetBotsManagedByDaemon();
1606
1681
  const config = {
1607
1682
  v: 1,
1608
1683
  name,
@@ -1639,8 +1714,10 @@ async function runBotCreateLocked(name, opts) {
1639
1714
  createdAt: new Date().toISOString(),
1640
1715
  enabled: !fleetAuthPending,
1641
1716
  ...(fleetAuthPending ? { fleetAuthPending: true } : {}),
1717
+ ...(daemonRunsFleetBots ? { fleetServiceInstallPending: true } : {}),
1642
1718
  };
1643
1719
  writeBotConfig(dir, config);
1720
+ writeBotSetupStep(dir, "identity");
1644
1721
  // A company bot acts as itself, so it must be a member of each of its
1645
1722
  // companies. Only the companies it actually joined are recorded, so after a failed invite the identity
1646
1723
  // and bot.json stay on disk and `hq bot companies <name> --add <slug>`
@@ -1662,15 +1739,19 @@ async function runBotCreateLocked(name, opts) {
1662
1739
  }
1663
1740
  // A worker-sourced bot never writes into the company tree: only its own
1664
1741
  // memory folder is scaffolded.
1665
- const scaffoldOpts = { memoryDir: config.memoryDir };
1742
+ const scaffoldOpts = { memoryDir: config.memoryDir, ...(config.displayName ? { displayName: config.displayName } : {}) };
1666
1743
  const scaffold = worker
1667
1744
  ? scaffoldBotMemory(hqRoot, name, undefined, scaffoldOpts)
1668
1745
  : scaffoldBotWorker(hqRoot, name, agentUid, HQ_FLEET_RUNTIME_ENGINE_ID, undefined, scaffoldOpts);
1669
1746
  fs.rmSync(path.join(dir, "status.json"), { force: true });
1670
- const introText = introDmText(name, runtime, intro, { kind, companies });
1747
+ const introText = introDmText(name, runtime, intro, { kind, companies, ...(config.displayName ? { displayName: config.displayName } : {}) });
1671
1748
  const toolOffer = isSetupBot && kickoff ? fleetSetupToolOffer(dir, config) : null;
1672
1749
  const startNow = opts.start !== false && !fleetAuthPending;
1673
- const daemonRunsFleetBots = fleetBotsManagedByDaemon();
1750
+ steps.finish("identity", "done");
1751
+ if (startNow) {
1752
+ steps.begin("starting");
1753
+ writeBotSetupStep(dir, "starting");
1754
+ }
1674
1755
  const fleetBootstrap = await bootstrapFleetLocalBot({
1675
1756
  agentUid,
1676
1757
  ownerUid: config.ownerUid,
@@ -1692,6 +1773,22 @@ async function runBotCreateLocked(name, opts) {
1692
1773
  syncFleetRuntimeJobs(name, dir, config);
1693
1774
  const startedByDaemon = startNow && daemonRunsFleetBots && controlFleetLocalBot(agentUid, "install").ok === true;
1694
1775
  const running = fleetBootstrap.running || startedByDaemon;
1776
+ let readyWait = null;
1777
+ if (!startNow) {
1778
+ steps.finish("starting", "skipped");
1779
+ steps.finish("ready", "skipped");
1780
+ }
1781
+ else if (!running) {
1782
+ steps.finish("starting", "failed");
1783
+ steps.finish("ready", "skipped");
1784
+ }
1785
+ else {
1786
+ steps.finish("starting", "done");
1787
+ steps.begin("ready");
1788
+ readyWait = await botCreateSeams.waitForReady(agentUid, { timeoutMs: readyTimeoutMs });
1789
+ steps.finish("ready", readyWait.ready ? "done" : readyWait.failed ? "failed" : "timeout");
1790
+ }
1791
+ const readiness = !startNow || !running || readyWait?.failed ? "offline" : readyWait?.ready ? "ready" : "starting";
1695
1792
  const fleetProfile = fleetBootstrap.profile;
1696
1793
  const runtimeLabel = HQ_FLEET_RUNTIME_ENGINE_ID;
1697
1794
  createBotLogger(dir)("info", `created ${name} (${agentUid}) kind=${kind}${companies.length ? ` companies=${companies.join(",")}` : ""} runtime=${runtimeLabel}${worker ? ` worker=${worker.id} company=${worker.company ?? "-"}` : ""} memory=${memoryMode}`);
@@ -1734,6 +1831,9 @@ async function runBotCreateLocked(name, opts) {
1734
1831
  if (fleetAuthPending) {
1735
1832
  console.log(chalk.yellow(` sign it in before it can answer: hq bot auth ${name} --provider ${runtime === "grok" ? "grok" : "chatgpt"}`));
1736
1833
  }
1834
+ const readyLine = createReadyLine(name, readiness, readyWait, readyTimeoutMs);
1835
+ if (readyLine)
1836
+ console.log(readyLine);
1737
1837
  }
1738
1838
  if (opts.json) {
1739
1839
  const status = readBotStatus(dir);
@@ -1744,6 +1844,14 @@ async function runBotCreateLocked(name, opts) {
1744
1844
  daemon: null,
1745
1845
  running,
1746
1846
  how: startedByDaemon ? "started by hq daemon" : fleetBootstrap.running ? "started by the HQ Fleet Runtime" : null,
1847
+ steps: steps.steps(),
1848
+ readiness,
1849
+ ready: readiness === "ready",
1850
+ readyAt: readyWait?.readyAt ?? null,
1851
+ readyWait: readyWait
1852
+ ? { timedOut: readyWait.timedOut, failed: readyWait.failed, waitedMs: readyWait.waitedMs, timeoutMs: readyTimeoutMs }
1853
+ : null,
1854
+ message: createReadyMessage(name, readiness, readyWait, readyTimeoutMs),
1747
1855
  state: status?.state ?? "unknown",
1748
1856
  pid: status?.pid ?? null,
1749
1857
  lastError: status?.lastError ?? null,
@@ -2112,6 +2220,7 @@ async function runBotStatus(nameArg, opts) {
2112
2220
  console.log(` worker: ${row.workerId}${row.companySlug ? ` (company ${row.companySlug})` : ""} ${chalk.dim(row.workerDir)}`);
2113
2221
  console.log(` memory: ${row.memory} ${chalk.dim(row.memoryDir)}`);
2114
2222
  console.log(` process: ${row.processAlive ? chalk.green(`running (pid ${row.pid})`) : chalk.gray(row.state)}`);
2223
+ console.log(` readiness: ${row.readiness === "ready" ? chalk.green(`ready${row.readyAt ? ` since ${row.readyAt}` : ""}`) : row.readiness === "offline" ? chalk.gray("offline") : chalk.yellow(row.readiness)}`);
2115
2224
  if (row.needsSignIn)
2116
2225
  console.log(` sign-in: required (${row.authCommand})`);
2117
2226
  if (row.brainUsage.state === "exhausted") {
@@ -2947,7 +3056,7 @@ export async function runBotIntro(nameArg) {
2947
3056
  if (hasPromotionHold(dir))
2948
3057
  throw new Error("This bot is held for cloud promotion. Continue its promotion before changing local settings or lifecycle.");
2949
3058
  const api = new BotApi({ token: botTokenSupplier(dir) });
2950
- await api.sendDm({ toPersonUid: config.ownerUid, body: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config) }) });
3059
+ await api.sendDm({ toPersonUid: config.ownerUid, body: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config), ...(config.displayName ? { displayName: config.displayName } : {}) }) });
2951
3060
  patchBotConfig(dir, { introSentAt: new Date().toISOString() });
2952
3061
  console.log(chalk.green(`${name} introduced itself to you.`));
2953
3062
  }
@@ -3034,8 +3143,9 @@ export async function runBotAuth(nameArg, opts) {
3034
3143
  process.on("SIGINT", keepAliveOnInterrupt);
3035
3144
  let result;
3036
3145
  try {
3037
- result = authenticateFleetLocalBot({
3146
+ result = await authenticateFleetLocalBot({
3038
3147
  agentUid: b.config.agentUid,
3148
+ ...(opts.json ? { onAuthEvent: (event) => { console.log(JSON.stringify(event)); } } : {}),
3039
3149
  provider: opts.provider,
3040
3150
  ...(adopted || legacy || b.config.fleetAuthPending === true ? { installService: true } : {}),
3041
3151
  ...(opts.model ? { model: opts.model } : {}),
@@ -3043,6 +3153,16 @@ export async function runBotAuth(nameArg, opts) {
3043
3153
  ...(opts.baseUrl ? { baseUrl: opts.baseUrl } : {}),
3044
3154
  ...(opts.transport ? { transport: opts.transport } : {}),
3045
3155
  openBrowser: opts.browser !== false,
3156
+ }, {
3157
+ control: (agentUid, action) => {
3158
+ if (fleetBotsManagedByDaemon()) {
3159
+ if (legacy && engine)
3160
+ writeBotConfig(b.dir, { ...(readBotConfig(b.dir) ?? legacy), engine });
3161
+ else if (b.config.fleetAuthPending === true)
3162
+ patchBotConfig(b.dir, { fleetAuthPending: false });
3163
+ }
3164
+ return controlFleetLocalBot(agentUid, action);
3165
+ },
3046
3166
  });
3047
3167
  if (result.authenticated !== true)
3048
3168
  throw Object.assign(new Error("The provider has not completed sign-in."), { expected: true });
@@ -3058,6 +3178,8 @@ export async function runBotAuth(nameArg, opts) {
3058
3178
  catch {
3059
3179
  /* nothing was running */
3060
3180
  }
3181
+ if (fleetBotsManagedByDaemon())
3182
+ writeBotConfig(b.dir, legacy);
3061
3183
  await startBot(b.name, b.dir, legacy, "silent", {}, { keepLegacy: true }).catch(() => undefined);
3062
3184
  }
3063
3185
  throw err;
@@ -3369,7 +3491,7 @@ async function adoptRemoteBotLocked(input) {
3369
3491
  if (fleetInstallation)
3370
3492
  config.engine = fleetInstallation.engine;
3371
3493
  writeBotConfig(dir, config);
3372
- const scaffoldOpts = { memoryDir: config.memoryDir };
3494
+ const scaffoldOpts = { memoryDir: config.memoryDir, ...(config.displayName ? { displayName: config.displayName } : {}) };
3373
3495
  const scaffold = config.workerSource === "worker"
3374
3496
  ? scaffoldBotMemory(input.hqRoot, name, undefined, scaffoldOpts)
3375
3497
  : scaffoldBotWorker(input.hqRoot, name, bot.agentUid, config.runtime, undefined, scaffoldOpts);
@@ -3388,7 +3510,7 @@ async function adoptRemoteBotLocked(input) {
3388
3510
  ...(input.preserveFirstStart
3389
3511
  ? {
3390
3512
  firstStart: {
3391
- intro: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config) }),
3513
+ intro: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config), ...(config.displayName ? { displayName: config.displayName } : {}) }),
3392
3514
  ...(config.kickoff ? { kickoff: config.kickoff } : {}),
3393
3515
  },
3394
3516
  }
@@ -3716,6 +3838,8 @@ export function registerBotCommand(program) {
3716
3838
  .option("--memory <where>", "Where the bot keeps its memory: synced (personal/workers/<name>/memory in HQ) or local (~/.hq/bots/<name>/memory, this computer only)", "synced")
3717
3839
  .option("--no-daemon", "Accepted for compatibility; HQ Fleet bots run under their own background service")
3718
3840
  .option("--no-start", "Create without starting")
3841
+ .option("--ready-timeout <seconds>", `How long to wait for the bot to be ready to chat before returning (default ${DEFAULT_BOT_READY_TIMEOUT_SECONDS})`)
3842
+ .option("--progress", "With --json: print each setup step and download progress as one JSON line before the final document")
3719
3843
  .option("--json", "Print machine-readable JSON")
3720
3844
  .action((name, opts) => wrap(() => runBotCreate(name, opts))());
3721
3845
  bot
@@ -3802,6 +3926,12 @@ export function registerBotCommand(program) {
3802
3926
  .option("--no-browser", "Do not open a browser during device authorization")
3803
3927
  .option("--json", "Print machine-readable JSON")
3804
3928
  .action((name, opts) => wrap(async () => { await runBotAuth(name, opts); })());
3929
+ bot
3930
+ .command("auth-status")
3931
+ .description("Say whether a Fleet bot created now would need its own ChatGPT or Grok sign-in, or reuse a login already on this computer")
3932
+ .requiredOption("--provider <provider>", "Provider: chatgpt or grok")
3933
+ .option("--json", "Print machine-readable JSON: { signedIn }")
3934
+ .action((opts) => wrap(async () => { await runBotAuthStatus(opts); })());
3805
3935
  bot
3806
3936
  .command("logs <name>")
3807
3937
  .description("Show the bot's log")
@@ -17,6 +17,7 @@ export type DeriveTriggerRunResult = {
17
17
  };
18
18
  export declare function resolveWindowsFilesystemPath(candidate: string, cwd: string, resolveRealpath?: (value: string) => string, isDirectory?: (value: string) => boolean): string | undefined;
19
19
  export declare function commandOnPath(command: string, env: Record<string, string | undefined>, platform?: NodeJS.Platform): boolean;
20
+ export declare function matchTextFacts(rawText: string, env: Record<string, string | undefined>): string[];
20
21
  /** Run the native handler contract, retaining exact bytes for differential tests. */
21
22
  export declare function runDeriveTriggerFacts(options: DeriveTriggerRunOptions): DeriveTriggerRunResult;
22
23
  export declare function runDeriveTriggerFactsFast(argv: readonly string[], stdin: string, cwd: string, hqRoot: string | undefined): number;
@@ -271,7 +271,52 @@ function emptyPayload() {
271
271
  cwd: "", sessionId: "", transcriptPath: "",
272
272
  };
273
273
  }
274
- function matchTextFacts(rawText, env) {
274
+ // `pull request #?[0-9]+ [\s\S]* merged`, without the backtracking regex: V8
275
+ // retries `[\s\S]*` to the end of the text from every "pull request <n> ", so
276
+ // an output with many of them cost size times count. The earliest prefix
277
+ // leaves the most text for " merged", so it alone decides the match.
278
+ function pullRequestMerged(text) {
279
+ const prefix = /pull request #?[0-9]+ /.exec(text);
280
+ return prefix !== null && text.includes(" merged", prefix.index + prefix[0].length);
281
+ }
282
+ // `-----begin[a-z -]*private key`, without the backtracking regex: V8 rescans
283
+ // the [a-z -] run after every "-----begin" in it. Every "-----begin" in one
284
+ // run can reach the same bytes, so only the first in each run is checked.
285
+ function pemPrivateKeyHeader(text) {
286
+ const outsideRun = /[^a-z -]/g;
287
+ let from = 0;
288
+ for (;;) {
289
+ const start = text.indexOf("-----begin", from);
290
+ if (start < 0)
291
+ return false;
292
+ const body = start + "-----begin".length;
293
+ outsideRun.lastIndex = body;
294
+ const end = outsideRun.exec(text)?.index ?? text.length;
295
+ if (text.slice(body, end).includes("private key"))
296
+ return true;
297
+ from = end;
298
+ }
299
+ }
300
+ // File references, as `text.matchAll(/\.?[a-z0-9_][a-z0-9_./-]*\.[a-z][a-z0-9]+/g)`
301
+ // would find them. A reference holds only [a-z0-9_./-] bytes, so each run of
302
+ // those bytes is scanned on its own, and only up to the end of its last
303
+ // `.<letter><alnum>` extension: no match can end later. Without that cut, V8
304
+ // retries the pattern from every start in a long run with no extension (a hex
305
+ // blob, say) to the end of the run, which is quadratic in the run's length.
306
+ function fileReferences(text) {
307
+ const references = [];
308
+ for (const run of text.matchAll(/[a-z0-9_./-]+/g)) {
309
+ let end = 0;
310
+ for (const extension of run[0].matchAll(/\.[a-z][a-z0-9]+/g))
311
+ end = extension.index + extension[0].length;
312
+ if (end === 0)
313
+ continue;
314
+ for (const match of run[0].slice(0, end).matchAll(/\.?[a-z0-9_][a-z0-9_./-]*\.[a-z][a-z0-9]+/g))
315
+ references.push(match[0]);
316
+ }
317
+ return references;
318
+ }
319
+ export function matchTextFacts(rawText, env) {
275
320
  const text = localeLower(rawText, env);
276
321
  const facts = [];
277
322
  const words = /[a-z][a-z0-9_-]+/g;
@@ -288,19 +333,18 @@ function matchTextFacts(rawText, env) {
288
333
  /(^|[^a-z0-9])akia[a-z0-9][a-z0-9]/.test(text) ||
289
334
  /(^|[^a-z0-9])xox[bpsa]-[a-z0-9]/.test(text) ||
290
335
  /(^|[^a-z0-9])glpat-[a-z0-9]/.test(text) ||
291
- /-----begin[a-z -]*private key/.test(text) ||
336
+ pemPrivateKeyHeader(text) ||
292
337
  /(^|[^a-z0-9])bearer [a-z0-9._-][a-z0-9._-][a-z0-9._-]/.test(text)) {
293
338
  facts.push("apikey", "secret");
294
339
  }
295
340
  if (/successfully (merged|deployed|pushed|published|created)/.test(text) ||
296
341
  /(deployment|deploy|build|release) (complete|completed|succeeded|ready)/.test(text) ||
297
342
  /merged pull request/.test(text) ||
298
- /pull request #?[0-9]+ [\s\S]* merged/.test(text)) {
343
+ pullRequestMerged(text)) {
299
344
  facts.push("completed");
300
345
  }
301
- const filenames = /\.?[a-z0-9_][a-z0-9_./-]*\.[a-z][a-z0-9]+/g;
302
- for (const match of text.matchAll(filenames)) {
303
- const filename = match[0].slice(match[0].lastIndexOf("/") + 1);
346
+ for (const reference of fileReferences(text)) {
347
+ const filename = reference.slice(reference.lastIndexOf("/") + 1);
304
348
  const dot = filename.lastIndexOf(".");
305
349
  facts.push(`.${filename.slice(dot + 1)}`, filename);
306
350
  }
@@ -310,6 +354,12 @@ function matchTextFacts(rawText, env) {
310
354
  }
311
355
  return facts;
312
356
  }
357
+ // Appends one by one: `facts.push(...list)` passes every fact as an argument
358
+ // and overflows the call stack once a large text yields ~100k facts.
359
+ function pushTextFacts(facts, text, env) {
360
+ for (const fact of matchTextFacts(text, env))
361
+ facts.push(fact);
362
+ }
313
363
  function isSharedBranch(branch, env) {
314
364
  const value = localeLower(branch, env);
315
365
  return /(^|[^a-z0-9_])(main|master|staging|production)([^a-z0-9_]|$)/.test(value) || /release\//.test(value);
@@ -481,22 +531,22 @@ function computeOutput(options) {
481
531
  if (kind === "PreToolUse" || kind === "PostToolUse") {
482
532
  if (payload.tool === "Bash") {
483
533
  if (kind === "PreToolUse") {
484
- facts.push(...matchTextFacts(payload.command, env));
534
+ pushTextFacts(facts, payload.command, env);
485
535
  if (payload.runInBackground === "true")
486
536
  facts.push("run_in_background");
487
537
  }
488
538
  else
489
- facts.push(...matchTextFacts(payload.toolResponse, env));
539
+ pushTextFacts(facts, payload.toolResponse, env);
490
540
  }
491
541
  else if (payload.tool !== "") {
492
542
  if (kind === "PreToolUse")
493
543
  facts.push(localeLower(payload.tool, env));
494
544
  else
495
- facts.push(...matchTextFacts(payload.toolResponse, env));
545
+ pushTextFacts(facts, payload.toolResponse, env);
496
546
  }
497
547
  }
498
548
  else if (kind === "UserPromptSubmit") {
499
- facts.push(...matchTextFacts(payload.prompt, env));
549
+ pushTextFacts(facts, payload.prompt, env);
500
550
  }
501
551
  if (company)
502
552
  facts.push("company");
@@ -506,7 +556,7 @@ function computeOutput(options) {
506
556
  if (fs.statSync(payload.transcriptPath).isFile()) {
507
557
  const lookback = transcriptAssistantText(payload.transcriptPath);
508
558
  if (lookback)
509
- facts.push(...matchTextFacts(lookback, env));
559
+ pushTextFacts(facts, lookback, env);
510
560
  }
511
561
  }
512
562
  catch (error) {
@@ -21,9 +21,9 @@ export type WorkMeshBindDeps = {
21
21
  stdout: string;
22
22
  stderr: string;
23
23
  };
24
- spawnHq: (args: string[], env: NodeJS.ProcessEnv) => void;
24
+ /** Starts `hq <args>` detached; removes `removeAfterExit` once that process exits. */
25
+ spawnHq: (args: string[], env: NodeJS.ProcessEnv, removeAfterExit?: string) => void;
25
26
  pid: number;
26
- tmpDir: string;
27
27
  ulid: (now: Date) => string;
28
28
  };
29
29
  export declare const createWorkMeshBindDeps: (root: string, cwd: string, env: NodeJS.ProcessEnv, now: () => Date, daemonWarningEnabled?: boolean) => WorkMeshBindDeps;
@@ -33,6 +33,10 @@ type DetachedSpawnOptions = {
33
33
  env: NodeJS.ProcessEnv;
34
34
  platform?: NodeJS.Platform;
35
35
  existsSync?: (candidate: string) => boolean;
36
+ /** File to delete after the hq process exits (the observation it reads). */
37
+ removeAfterExit?: string;
38
+ /** Node binary for the wait-then-remove wrapper; defaults to process.execPath. */
39
+ execPath?: string;
36
40
  spawnProcess?: (command: string, args: string[], options: {
37
41
  cwd: string;
38
42
  env: NodeJS.ProcessEnv;
@@ -40,10 +44,18 @@ type DetachedSpawnOptions = {
40
44
  stdio: "ignore";
41
45
  shell: boolean;
42
46
  windowsVerbatimArguments?: boolean;
47
+ windowsHide?: boolean;
43
48
  }) => {
44
49
  unref: () => void;
50
+ on?: (event: "error", listener: () => void) => unknown;
45
51
  };
46
52
  };
53
+ /**
54
+ * Detached wrapper: runs the planned hq command, waits for it to exit, then
55
+ * removes the observation file it read. Mirrors the shell script's
56
+ * `nohup bash -c '"$1" mesh context reconcile ...; rm -f -- "$2"'`.
57
+ */
58
+ export declare const WORK_MESH_RECONCILE_REMOVE_WRAPPER: string;
47
59
  export declare function spawnWorkMeshHqDetached(args: string[], options: DetachedSpawnOptions): void;
48
60
  /**
49
61
  * Resolve the bind session. Only a session id the caller owns (the process env)
@@ -19,7 +19,7 @@ ROOT="\${HQ_ROOT:-\${CLAUDE_PROJECT_DIR:-}}"
19
19
  if [ -z "$ROOT" ]; then
20
20
  `;
21
21
  export const createWorkMeshBindDeps = (root, cwd, env, now, daemonWarningEnabled = false) => ({
22
- root, cwd, env, now, fs, pid: process.pid, tmpDir: env.TMPDIR || "/tmp", ulid: (date) => generateUlid(date.getTime()),
22
+ root, cwd, env, now, fs, pid: process.pid, ulid: (date) => generateUlid(date.getTime()),
23
23
  daemonWarningEnabled: daemonWarningEnabled
24
24
  && Boolean(env.HQ_FLAGS_API_URL?.trim())
25
25
  && /^cmp_[A-Za-z0-9]{3,128}$/.test(env.HQ_COMPANY_UID?.trim() ?? ""),
@@ -50,12 +50,26 @@ export const createWorkMeshBindDeps = (root, cwd, env, now, daemonWarningEnabled
50
50
  const result = spawnSync("bash", [path.join(scriptRoot, "core/scripts/hq-session.sh"), ...args], { cwd, env: childEnv, encoding: "utf8" });
51
51
  return { code: result.status ?? 127, stdout: result.stdout ?? "", stderr: result.stderr ?? (result.error ? `${result.error.message}\n` : "") };
52
52
  },
53
- spawnHq: (args, childEnv) => spawnWorkMeshHqDetached(args, {
53
+ spawnHq: (args, childEnv, removeAfterExit) => spawnWorkMeshHqDetached(args, {
54
54
  cwd,
55
55
  root,
56
56
  env: childEnv,
57
+ ...(removeAfterExit ? { removeAfterExit } : {}),
57
58
  }),
58
59
  });
60
+ /**
61
+ * Detached wrapper: runs the planned hq command, waits for it to exit, then
62
+ * removes the observation file it read. Mirrors the shell script's
63
+ * `nohup bash -c '"$1" mesh context reconcile ...; rm -f -- "$2"'`.
64
+ */
65
+ export const WORK_MESH_RECONCILE_REMOVE_WRAPPER = [
66
+ "const cp=require('node:child_process'),fs=require('node:fs');",
67
+ "const [spec,file]=process.argv.slice(1);",
68
+ "let done=false;const remove=()=>{if(done)return;done=true;try{fs.rmSync(file,{force:true})}catch{}};",
69
+ "try{const p=JSON.parse(spec);",
70
+ "const child=cp.spawn(p.cmd,p.args,{cwd:p.cwd,env:process.env,stdio:'ignore',shell:p.shell,windowsHide:true,windowsVerbatimArguments:p.windowsVerbatimArguments===true});",
71
+ "child.on('error',remove);child.on('exit',remove)}catch{remove()}",
72
+ ].join("");
59
73
  export function spawnWorkMeshHqDetached(args, options) {
60
74
  const platform = options.platform ?? process.platform;
61
75
  const childEnv = { ...options.env, HQ_ROOT: options.root };
@@ -63,6 +77,28 @@ export function spawnWorkMeshHqDetached(args, options) {
63
77
  ? resolveWindowsExecutable("hq", childEnv, options.existsSync ?? fs.existsSync, options.cwd) ?? "hq"
64
78
  : "hq";
65
79
  const plan = planResolvedCommandSpawn(executable, args, childEnv, platform);
80
+ if (options.removeAfterExit) {
81
+ const spec = JSON.stringify({
82
+ cmd: plan.cmd,
83
+ args: plan.args,
84
+ cwd: options.cwd,
85
+ shell: plan.shell,
86
+ windowsVerbatimArguments: plan.windowsVerbatimArguments === true,
87
+ });
88
+ const wrapper = (options.spawnProcess ?? spawn)(options.execPath ?? process.execPath, ["--input-type=commonjs", "-e", WORK_MESH_RECONCILE_REMOVE_WRAPPER, spec, options.removeAfterExit], {
89
+ cwd: options.cwd,
90
+ env: childEnv,
91
+ detached: true,
92
+ stdio: "ignore",
93
+ shell: false,
94
+ windowsHide: true,
95
+ });
96
+ // A failed wrapper start must not throw in this process; the SessionStart
97
+ // hook's age sweep removes the observation it leaves.
98
+ wrapper.on?.("error", () => { });
99
+ wrapper.unref();
100
+ return;
101
+ }
66
102
  const child = (options.spawnProcess ?? spawn)(plan.cmd, plan.args, {
67
103
  cwd: options.cwd,
68
104
  env: childEnv,
@@ -216,12 +252,21 @@ export function runWorkMeshBindTrusted(args, deps) {
216
252
  trusted.authority = "trusted";
217
253
  observation.trustedContext = trusted;
218
254
  }
219
- const directory = path.join(deps.tmpDir, "hq-work-mesh-obs");
255
+ // Observations live under the HQ root's workspace/, not the system temp
256
+ // folder (on Windows that is the user's Temp, which nothing cleans). The
257
+ // SessionStart hook's age sweep removes any that a crashed run leaves.
258
+ const scratchRoot = path.join(root, "workspace", "tmp", "work-mesh");
259
+ const directory = path.join(scratchRoot, "obs");
220
260
  try {
221
- deps.fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
222
- deps.fs.chmodSync(directory, 0o700);
261
+ deps.fs.mkdirSync(directory, { recursive: true });
262
+ }
263
+ catch { /* legacy mkdir -p is best effort */ }
264
+ for (const folder of [scratchRoot, directory]) {
265
+ try {
266
+ deps.fs.chmodSync(folder, 0o700);
267
+ }
268
+ catch { /* legacy chmod is best effort */ }
223
269
  }
224
- catch { /* legacy mkdir/chmod are best effort */ }
225
270
  const observationFile = path.join(directory, `${sid}.bind.${deps.pid}.json`);
226
271
  try {
227
272
  deps.fs.writeFileSync(observationFile, `${workMeshObservationJson(observation)}\n`);
@@ -250,8 +295,17 @@ export function runWorkMeshBindTrusted(args, deps) {
250
295
  catch { /* the shell's jq test fails quiet on invalid status JSON */ }
251
296
  }
252
297
  }
253
- if (hasExecutable(deps, "hq") && deps.fs.existsSync(observationFile)) {
254
- deps.spawnHq(["mesh", "context", "reconcile", "--observation-file", observationFile, "--machine"], childEnv);
298
+ if (!hasExecutable(deps, "hq")) {
299
+ // No reader: the observation would never be consumed.
300
+ try {
301
+ deps.fs.rmSync(observationFile, { force: true });
302
+ }
303
+ catch { /* legacy rm -f is best effort */ }
304
+ stderr += "Work Mesh reconcile skipped: hq CLI not found on PATH.\n";
305
+ return { code: 0, stdout: output.join(""), stderr };
306
+ }
307
+ if (deps.fs.existsSync(observationFile)) {
308
+ deps.spawnHq(["mesh", "context", "reconcile", "--observation-file", observationFile, "--machine"], childEnv, observationFile);
255
309
  }
256
310
  return { code: 0, stdout: output.join(""), stderr };
257
311
  }