@indigoai-us/hq-cli 5.345.234 → 5.345.236

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 (100) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/dist/command-catalog.generated.d.ts +311 -7
  3. package/dist/command-catalog.generated.js +383 -7
  4. package/dist/command-registration-plan.d.ts +30 -0
  5. package/dist/command-registration-plan.js +5 -0
  6. package/dist/commands/bot-companies.d.ts +4 -1
  7. package/dist/commands/bot-companies.js +5 -1
  8. package/dist/commands/bot.d.ts +10 -0
  9. package/dist/commands/bot.js +165 -36
  10. package/dist/commands/capacity.js +1 -1
  11. package/dist/commands/core-handoff.js +2 -2
  12. package/dist/commands/core-ontology-native.js +5 -4
  13. package/dist/commands/core-pipeline-workflow-runner-native.js +4 -9
  14. package/dist/commands/deploy-app-db.d.ts +3 -0
  15. package/dist/commands/deploy-app-db.js +79 -0
  16. package/dist/commands/deploy-app-upload.d.ts +3 -0
  17. package/dist/commands/deploy-app-upload.js +120 -0
  18. package/dist/commands/deploy-comments.js +46 -1
  19. package/dist/commands/deploy-mutations.js +71 -5
  20. package/dist/commands/deploy-runtime-bindings.d.ts +3 -0
  21. package/dist/commands/deploy-runtime-bindings.js +135 -0
  22. package/dist/commands/deploy-ssr.d.ts +3 -0
  23. package/dist/commands/deploy-ssr.js +74 -0
  24. package/dist/commands/dm.d.ts +7 -1
  25. package/dist/commands/dm.js +39 -9
  26. package/dist/commands/doctor.js +2 -10
  27. package/dist/commands/fingerprint.js +4 -9
  28. package/dist/commands/lanes-accounts.js +5 -5
  29. package/dist/commands/lanes-hold.js +1 -1
  30. package/dist/commands/lanes-message.js +3 -3
  31. package/dist/commands/lanes-move.js +1 -1
  32. package/dist/commands/lanes-resume.js +6 -6
  33. package/dist/commands/lanes-watch.js +2 -2
  34. package/dist/commands/lanes.js +21 -21
  35. package/dist/commands/work-env.d.ts +90 -0
  36. package/dist/commands/work-env.js +304 -0
  37. package/dist/lazy-commands.js +2 -10
  38. package/dist/lib/bot/api.d.ts +27 -0
  39. package/dist/lib/bot/api.js +28 -2
  40. package/dist/lib/bot/cloud-create.d.ts +46 -0
  41. package/dist/lib/bot/cloud-create.js +128 -0
  42. package/dist/lib/bot/fleet-daemon.js +4 -1
  43. package/dist/lib/bot/fleet-local.d.ts +7 -0
  44. package/dist/lib/bot/fleet-local.js +39 -3
  45. package/dist/lib/bot/fleet-owner-companies.js +2 -2
  46. package/dist/lib/bot/promote.d.ts +81 -2
  47. package/dist/lib/bot/promote.js +425 -51
  48. package/dist/lib/bot/promotion-hold.d.ts +9 -0
  49. package/dist/lib/bot/promotion-hold.js +29 -0
  50. package/dist/lib/bot/promotion-receipt.d.ts +10 -0
  51. package/dist/lib/bot/promotion-receipt.js +41 -1
  52. package/dist/lib/bot/promotion-upload.d.ts +6 -1
  53. package/dist/lib/bot/promotion-upload.js +3 -1
  54. package/dist/lib/bot/readiness.d.ts +9 -0
  55. package/dist/lib/bot/readiness.js +16 -0
  56. package/dist/lib/capacity/route.js +4 -4
  57. package/dist/lib/capacity/sign-in.js +1 -1
  58. package/dist/lib/checkpoint-ontology/entity-file.js +15 -17
  59. package/dist/lib/daemon/catalog.d.ts +2 -0
  60. package/dist/lib/daemon/catalog.js +2 -0
  61. package/dist/lib/daemon/hook-requests.js +23 -3
  62. package/dist/lib/daemon/run.d.ts +14 -0
  63. package/dist/lib/daemon/run.js +24 -14
  64. package/dist/lib/deploy-api.d.ts +3 -1
  65. package/dist/lib/deploy-api.js +11 -1
  66. package/dist/lib/environment/work-requirements.js +1 -1
  67. package/dist/lib/hot-channels/signals-pass.d.ts +0 -76
  68. package/dist/lib/hot-channels/signals-pass.js +81 -4
  69. package/dist/lib/lanes/account-company.js +1 -1
  70. package/dist/lib/lanes/account-ownership.js +1 -1
  71. package/dist/lib/lanes/accounts.js +1 -1
  72. package/dist/lib/lanes/delivery.js +7 -7
  73. package/dist/lib/lanes/dropbox.js +1 -1
  74. package/dist/lib/lanes/grants.js +3 -3
  75. package/dist/lib/lanes/hq-root.js +1 -1
  76. package/dist/lib/lanes/keep-alive-audit.js +2 -2
  77. package/dist/lib/lanes/links.js +4 -4
  78. package/dist/lib/lanes/monitor.js +3 -3
  79. package/dist/lib/lanes/quota-notice.js +1 -1
  80. package/dist/lib/lanes/reconcile.js +22 -12
  81. package/dist/lib/lanes/signal-brief-template.js +1 -1
  82. package/dist/lib/lanes/worker-continuity.js +1 -1
  83. package/dist/lib/mesh/live/direct-drain.d.ts +1 -0
  84. package/dist/lib/mesh/live/direct-drain.js +12 -1
  85. package/dist/lib/mesh/live/emit.d.ts +1 -1
  86. package/dist/lib/mesh/live/emit.js +10 -5
  87. package/dist/lib/mesh/live/flush.js +19 -4
  88. package/dist/lib/mesh/live/reporting-privacy.d.ts +9 -3
  89. package/dist/lib/mesh/live/reporting-privacy.js +27 -7
  90. package/dist/lib/mesh/live/spool.d.ts +2 -0
  91. package/dist/lib/mesh/live/spool.js +41 -0
  92. package/dist/lib/signals/sanitize.js +5 -4
  93. package/dist/lib/signals/steps/garden.js +5 -4
  94. package/dist/utils/frontmatter.d.ts +8 -0
  95. package/dist/utils/frontmatter.js +11 -2
  96. package/dist/utils/hq-roots-core.d.ts +5 -0
  97. package/dist/utils/hq-roots-core.js +18 -9
  98. package/dist/utils/owner-session.d.ts +13 -0
  99. package/dist/utils/owner-session.js +28 -0
  100. package/package.json +7 -7
@@ -14,7 +14,7 @@ import { checkClaudeLoginNow, readSignalsClaudeLogin, recordSignalsPassClaudeLog
14
14
  import { machineTimeZone } from "../lib/bot/job-run.js";
15
15
  import { runCompanyHotChannelSync } from "./sources.js";
16
16
  import { OwnerContextCache, lookupOwnerContext } from "../lib/bot/owner-context.js";
17
- import { hasActivePromotion } from "../lib/bot/promotion-receipt.js";
17
+ import { hasActivePromotion, localPromotionState } from "../lib/bot/promotion-receipt.js";
18
18
  import { botBusyState, readInflightTurns } from "../lib/bot/inflight.js";
19
19
  import { hasPromotionHold, promotionHoldSummary } from "../lib/bot/promotion-hold.js";
20
20
  /**
@@ -40,7 +40,7 @@ import { hasPromotionHold, promotionHoldSummary } from "../lib/bot/promotion-hol
40
40
  * ~/.hq/bots/<name>/; the OWNER's cached session is used only for create,
41
41
  * list (online flag), and rm. Secrets are never printed.
42
42
  */
43
- import { promoteLocalBot } from "../lib/bot/promote.js";
43
+ import { assertPromotedBotRemovable, cancelLocalBotPromotion, promoteLocalBot, promotionDetailsError, promotionFailureText, PROMOTION_CANCEL_TIMEOUT_MS } from "../lib/bot/promote.js";
44
44
  import { DecisionsClient } from "../lib/decisions/client.js";
45
45
  import { releaseCurrentPackageUseLease, releasePackageUseLeaseAfterResidentPreload } from "../utils/package-use-lease.js";
46
46
  import { preloadResidentPackageModules, reportResidentPackagePreloadFailure, runResidentCommandWithPackageLease, } from "../utils/resident-package-preload.js";
@@ -55,7 +55,7 @@ import { executiveStatus } from "../lib/bot/executive-settings.js";
55
55
  import { describeExecutiveBotSource, resolveExecutiveBot, setExecutiveBot } from "../lib/bot/executive.js";
56
56
  import { executiveHotSignalSyncCompanies } from "../lib/bot/executive-sync.js";
57
57
  import { readBotListedProcess } from "../lib/bot/listed-running.js";
58
- import { DEFAULT_BOT_READY_TIMEOUT_SECONDS, botReadinessReport, clearBotSetupStep, createSetupStepReporter, readBotSetupStep, waitForGatewayReady, fleetStatusCarriesReady, writeBotSetupStep, } from "../lib/bot/readiness.js";
58
+ import { DEFAULT_BOT_READY_TIMEOUT_SECONDS, botOnlineLabel, botReadinessReport, clearBotSetupStep, createSetupStepReporter, readBotSetupStep, waitForGatewayReady, fleetStatusCarriesReady, writeBotSetupStep, } from "../lib/bot/readiness.js";
59
59
  import { ensureFleetHotSignalSync, fleetCronOps, fleetHotSignalSyncEngineCompanies, migrateLegacyJobsToFleet } from "../lib/bot/fleet-cron.js";
60
60
  import { resolvePackSetupPrompt } from "../lib/bot/pack-setup.js";
61
61
  import { detectCodingToolActivity } from "../lib/bot/coding-tool-activity.js";
@@ -69,8 +69,11 @@ import * as os from "node:os";
69
69
  import * as path from "node:path";
70
70
  import * as readline from "node:readline";
71
71
  import { DEFAULT_COGNITO, ensureCognitoToken, resolveDefaultHqRoot, } from "../utils/cognito-session.js";
72
+ import { ensureOwnerToken } from "../utils/owner-session.js";
73
+ import { OutpostsClient } from "@indigoai-us/hq-cloud/outposts";
74
+ import { runBotCreateOnOutpost } from "../lib/bot/cloud-create.js";
72
75
  import { peekHqApiKey } from "../utils/resolve-vault-credential.js";
73
- import { getCompanyUid, resolveCallerPersonUid } from "../utils/vault-api.js";
76
+ import { getCompanyUid, resolveCallerPersonUid, vaultApiFetch } from "../utils/vault-api.js";
74
77
  import { askDaemonToStart, askDaemonToStop, daemonOwnsProcess, daemonHoldReason, daemonSupervises, daemonWillSupervise, handOffInstallHere, } from "../lib/daemon/handoff.js";
75
78
  import { daemonPaths } from "../lib/daemon/paths.js";
76
79
  import { launchdLabel } from "../lib/bot/paths.js";
@@ -100,7 +103,10 @@ function wrap(action) {
100
103
  await action();
101
104
  }
102
105
  catch (err) {
103
- fail(err instanceof Error ? err.message : String(err));
106
+ console.error(chalk.red(err instanceof Error ? err.message : String(err)));
107
+ // The CLI exits explicitly, so wait for its diagnostic before exiting.
108
+ await new Promise((resolve) => { process.stderr.write("", () => resolve()); });
109
+ process.exit(1);
104
110
  }
105
111
  };
106
112
  }
@@ -488,13 +494,14 @@ async function ownerToken(interactive = ownerSignInAllowed()) {
488
494
  expected: true,
489
495
  });
490
496
  }
491
- // Bots belong to a person, so `hq bot` always acts as the signed-in person,
497
+ // Bots belong to a person, so `hq bot` always acts as the signed-in person
498
+ // (on a personal Outpost, as its owner through the box's delegated sign-in),
492
499
  // even when a bot runs it: a bot's own process exports its machine
493
500
  // credentials, and a machine identity can own no bot ("No person entity
494
501
  // found"), which left a setup bot unable to create its owner's first bot.
495
502
  // Under the desktop app (no TTY) never open a browser login; the app owns
496
503
  // sign-in and shares the same cached session file.
497
- return ensureCognitoToken({ tokenSource: "person", interactive });
504
+ return ensureOwnerToken({ interactive });
498
505
  }
499
506
  /**
500
507
  * The bot's word on its coding tool's sign-in. Only a running bot's report
@@ -753,6 +760,7 @@ function rowFor(name, opts = {}) {
753
760
  processAlive,
754
761
  hosting: hasActivePromotion(dir, config.agentUid, config.ownerUid) ? "cloud" : "local",
755
762
  promotionHold: promotionHoldSummary(dir, config.agentUid, config.ownerUid),
763
+ promotion: localPromotionState(dir, config.agentUid, config.ownerUid),
756
764
  online: null,
757
765
  lastHeartbeatAt: status?.lastHeartbeatAt ?? null,
758
766
  lastHeartbeatOk: status?.lastHeartbeatOk ?? null,
@@ -823,15 +831,16 @@ async function decorateOnline(rows) {
823
831
  }));
824
832
  }
825
833
  function humanOnline(row) {
826
- if (row.readiness === "creating" || row.readiness === "installing" || row.readiness === "starting")
827
- return chalk.yellow(row.readiness);
828
- if (row.lastHeartbeatOk === false)
829
- return chalk.red("unreachable");
830
- if (row.online === true)
831
- return chalk.green("online");
832
- if (row.online === false)
833
- return chalk.gray("offline");
834
- return chalk.gray("unknown");
834
+ const label = botOnlineLabel(row);
835
+ if (label === "cloud")
836
+ return chalk.cyan(label);
837
+ if (label === "online")
838
+ return chalk.green(label);
839
+ if (label === "unreachable")
840
+ return chalk.red(label);
841
+ if (label === "offline" || label === "unknown")
842
+ return chalk.gray(label);
843
+ return chalk.yellow(label);
835
844
  }
836
845
  /** Spawn `hq bot run <name>` detached (no launchd). */
837
846
  export function spawnDetachedRun(name, dir) {
@@ -1468,6 +1477,15 @@ function removeEmptyDir(dir) {
1468
1477
  return;
1469
1478
  }
1470
1479
  }
1480
+ function cloudCreateDeps() {
1481
+ const client = new OutpostsClient({ transport: vaultApiFetch, token: () => ownerToken() });
1482
+ return {
1483
+ list: () => client.list(),
1484
+ submitExec: (command, outpostId, timeoutSeconds) => client.submitExec(command, outpostId, timeoutSeconds),
1485
+ waitForExecResult: (commandId, outpostId, maxWaitMs) => client.waitForExecResult(commandId, outpostId, { maxWaitMs }),
1486
+ print: (line) => console.log(line),
1487
+ };
1488
+ }
1471
1489
  /**
1472
1490
  * `hq bot create`. Runs under the bot's lock, so a create racing an adopt,
1473
1491
  * restore, rm or set of the same bot waits for it instead of tripping over
@@ -1476,6 +1494,10 @@ function removeEmptyDir(dir) {
1476
1494
  export async function runBotCreate(nameArg, opts) {
1477
1495
  try {
1478
1496
  const name = validateBotName(nameArg);
1497
+ if (opts.cloud === true) {
1498
+ await runBotCreateOnOutpost(name, opts, cloudCreateDeps());
1499
+ return;
1500
+ }
1479
1501
  const dir = botDir(name);
1480
1502
  const dirExisted = fs.existsSync(dir);
1481
1503
  try {
@@ -2787,10 +2809,17 @@ async function runBotRmLocked(validated, opts) {
2787
2809
  return;
2788
2810
  }
2789
2811
  const { name, dir, config } = requireBot(nameArg);
2790
- if (hasPromotionHold(dir))
2791
- throw new Error("This bot is held for cloud promotion. Continue its promotion before changing local settings or lifecycle.");
2812
+ // Only HQ's word that a promoted bot's cloud agent is gone frees its local state.
2813
+ const promoted = localPromotionState(dir, config.agentUid, config.ownerUid) !== null || fs.existsSync(path.join(dir, "promotion-active.json"));
2814
+ let movedTo = null;
2815
+ if (promoted) {
2816
+ const ownerTok = await ownerToken();
2817
+ movedTo = (await assertPromotedBotRemovable({ dir, config, api: new BotApi({ token: async () => ownerTok }), signedInPerson: () => resolveCallerPersonUid(ownerTok, undefined, { command: "hq bot rm" }) })).companyUid;
2818
+ }
2792
2819
  if (!opts.yes) {
2793
- const ok = await confirm(`Remove bot "${name}" (${config.agentUid}), its identity, and its local state? [y/N] `);
2820
+ const ok = await confirm(promoted
2821
+ ? `The cloud copy of "${name}" was deleted in HQ. Remove what is left of it on this computer (${config.agentUid})? [y/N] `
2822
+ : `Remove bot "${name}" (${config.agentUid}), its identity, and its local state? [y/N] `);
2794
2823
  if (!ok) {
2795
2824
  console.log(chalk.dim("Cancelled."));
2796
2825
  return;
@@ -2806,14 +2835,18 @@ async function runBotRmLocked(validated, opts) {
2806
2835
  const token = await ownerToken();
2807
2836
  const api = new BotApi({ token: async () => token });
2808
2837
  let identity;
2809
- try {
2810
- identity = await api.deleteLocalBot(config.agentUid);
2811
- }
2812
- catch (err) {
2813
- if (err instanceof BotApiError && err.status === 404)
2814
- identity = { alreadyGone: true };
2815
- else
2816
- throw err;
2838
+ if (promoted)
2839
+ identity = { alreadyGone: true };
2840
+ else {
2841
+ try {
2842
+ identity = await api.deleteLocalBot(config.agentUid);
2843
+ }
2844
+ catch (err) {
2845
+ if (err instanceof BotApiError && err.status === 404)
2846
+ identity = { alreadyGone: true };
2847
+ else
2848
+ throw err;
2849
+ }
2817
2850
  }
2818
2851
  const terminal = "alreadyGone" in identity ? true : identity.terminal;
2819
2852
  // A teardown HQ could only half-finish. Classified here so neither branch
@@ -2822,8 +2855,9 @@ async function runBotRmLocked(validated, opts) {
2822
2855
  const incomplete = terminal ? null : botRemovalIncomplete("failures" in identity ? identity.failures : undefined);
2823
2856
  // A company bot is a member of its companies: leave them too. Best effort —
2824
2857
  // a stale membership row must not keep the bot's local state around.
2858
+ // Deleting a promoted bot's cloud agent revoked only its seat in the company it moved to.
2825
2859
  const memberships = effectiveBotCompanies(config);
2826
- const left = memberships.length > 0 ? await removeBotFromCompanies({ agentUid: config.agentUid, companies: memberships, token }) : { done: [], failed: [] };
2860
+ const left = memberships.length > 0 ? await removeBotFromCompanies({ agentUid: config.agentUid, companies: memberships, token, skipCompanyUid: movedTo }) : { done: [], failed: [] };
2827
2861
  deleteBotCreds(dir);
2828
2862
  // The local-state decision. A refusal, or a step whose target was already
2829
2863
  // gone, answers the same way forever — and by then the steps that did
@@ -2858,8 +2892,8 @@ async function runBotRmLocked(validated, opts) {
2858
2892
  companiesLeft: left.done,
2859
2893
  companiesNotLeft: left.failed,
2860
2894
  localStateRemoved,
2861
- remoteRemoved: terminal,
2862
- remoteDetail: incomplete ? incomplete.detail : "alreadyGone" in identity ? "it was already gone from HQ" : "removed from HQ",
2895
+ remoteRemoved: promoted ? false : terminal,
2896
+ remoteDetail: promoted ? "its cloud copy was already deleted in HQ; only what was left on this computer was removed" : incomplete ? incomplete.detail : "alreadyGone" in identity ? "it was already gone from HQ" : "removed from HQ",
2863
2897
  remoteStepsUnfinished: incomplete?.steps ?? [],
2864
2898
  workerKept: path.join(config.hqRoot, config.workerDir),
2865
2899
  }, null, 2));
@@ -2871,6 +2905,8 @@ async function runBotRmLocked(validated, opts) {
2871
2905
  console.log(chalk.yellow(` could not remove ${name} from ${f.slug}: ${f.reason}`) + chalk.dim(` — remove it by hand: hq members --company ${f.slug} revoke ${config.agentUid}`));
2872
2906
  }
2873
2907
  if (terminal) {
2908
+ if (promoted)
2909
+ console.log(chalk.dim(`Its cloud copy was already deleted in HQ, so only what was left on this computer was removed.`));
2874
2910
  console.log(chalk.green(`Removed bot ${name}`) + chalk.dim(` (${config.agentUid}${left.done.length ? `; left ${left.done.join(", ")}` : ""}); worker folder kept at ${path.join(config.hqRoot, config.workerDir)}`));
2875
2911
  return;
2876
2912
  }
@@ -4187,6 +4223,78 @@ async function runBotListRemote(opts) {
4187
4223
  if (rows.some((r) => !r.here && r.runnable))
4188
4224
  console.log(chalk.dim(`\nBring them all back with: hq bot restore`));
4189
4225
  }
4226
+ /** The bot's lifecycle seams for `hq bot promote`; tests replace them. */
4227
+ export const botPromoteSeams = {
4228
+ start: (name, dir, config) => startBot(name, dir, config, "silent"),
4229
+ };
4230
+ /** `hq bot promote <name> --company <uid> --cancel`. */
4231
+ async function runBotPromoteCancel(name, dir, config, api, opts) {
4232
+ const result = await cancelLocalBotPromotion({
4233
+ dir,
4234
+ config,
4235
+ companyUid: opts.company,
4236
+ api,
4237
+ ...(opts.signedInPerson ? { signedInPerson: opts.signedInPerson } : {}),
4238
+ onWaiting: () => {
4239
+ if (!opts.json)
4240
+ console.log(chalk.dim(`${name}: waiting for the cloud copy to shut down (up to ${Math.round(PROMOTION_CANCEL_TIMEOUT_MS / 60_000)} minutes)...`));
4241
+ },
4242
+ });
4243
+ // An hq that wrote the hold before this record existed leaves none: restart then.
4244
+ const restart = result.localHoldReleased && result.wasRunning !== false;
4245
+ let started = null;
4246
+ let startError = null;
4247
+ if (restart) {
4248
+ try {
4249
+ started = (await botPromoteSeams.start(name, dir, config)).running;
4250
+ }
4251
+ catch (err) {
4252
+ started = false;
4253
+ startError = err instanceof Error ? err.message : String(err);
4254
+ }
4255
+ }
4256
+ const identityLost = result.outcome === "canceled" && result.identityRestored === false;
4257
+ if (result.outcome === "pending" || result.outcome === "active")
4258
+ process.exitCode = 1;
4259
+ if (opts.json) {
4260
+ console.log(JSON.stringify({
4261
+ promotion: result.promotion,
4262
+ pending: result.pending,
4263
+ outcome: result.outcome,
4264
+ localHoldReleased: result.localHoldReleased,
4265
+ started,
4266
+ ...(startError ? { startError } : {}),
4267
+ identityRestored: result.identityRestored,
4268
+ ...(identityLost ? { repairCommand: "hq bot restore --all" } : {}),
4269
+ }));
4270
+ return;
4271
+ }
4272
+ const local = !result.localHoldReleased
4273
+ ? ""
4274
+ : !restart
4275
+ ? ` It was not running when the move began, so it stays stopped. Start it with: hq bot start ${name}`
4276
+ : started
4277
+ ? " It is running on this computer again."
4278
+ : ` It is free to run on this computer again but has not come up yet${startError ? ` (${startError})` : ""}. Check with: hq bot status ${name}, or start it with: hq bot start ${name}`;
4279
+ if (result.outcome === "canceled") {
4280
+ console.log(chalk.green(`${name}: the move to the cloud is canceled and the cloud copy is shut down.`) + local);
4281
+ if (identityLost) {
4282
+ console.log(chalk.yellow(`${name}: HQ could not restore the bot's own sign-in, so it may fail to connect. Issue it a new machine credential with: hq bot restore --all`));
4283
+ }
4284
+ }
4285
+ else if (result.outcome === "pending") {
4286
+ console.log(chalk.yellow(`${name}: the cloud copy is still shutting down. The bot stays held on this computer until it has. Run the same command again to continue.`));
4287
+ }
4288
+ else if (result.outcome === "active") {
4289
+ console.log(chalk.yellow(`${name}: this bot is already live in the cloud, so the move can no longer be canceled. To remove the cloud bot, run: hq agents rm`));
4290
+ }
4291
+ else if (result.localHoldReleased) {
4292
+ console.log(chalk.green(`${name}: HQ has no move to the cloud for this bot, so the hold left on this computer was removed.`) + local);
4293
+ }
4294
+ else {
4295
+ console.log(`${name}: there is no move to the cloud to cancel.`);
4296
+ }
4297
+ }
4190
4298
  // ── registration ─────────────────────────────────────────────────────────────
4191
4299
  export function registerBotCommand(program) {
4192
4300
  const bot = program
@@ -4198,23 +4306,43 @@ export function registerBotCommand(program) {
4198
4306
  bot.command("promote <name>")
4199
4307
  .description("Move this local bot to cloud compute, preserving its identity and private context")
4200
4308
  .requiredOption("--company <uid>", "Destination company identity")
4309
+ .option("--cancel", "Cancel the move: shut down the cloud copy and run the bot on this computer again")
4201
4310
  .option("--json", "Print promotion progress as JSON")
4202
4311
  .action((name, opts) => wrap(async () => {
4203
4312
  const { dir, config } = requireBot(name);
4204
4313
  const token = await ownerToken(false);
4205
4314
  const api = new BotApi({ token: async () => token });
4206
- const result = await promoteLocalBot({
4315
+ if (opts.cancel) {
4316
+ const signedInPerson = () => resolveCallerPersonUid(token, undefined, { command: "hq bot promote --cancel" });
4317
+ await withBotLock(name, () => runBotPromoteCancel(name, dir, config, api, { company: opts.company, json: opts.json, signedInPerson }), { command: "hq bot promote --cancel" });
4318
+ return;
4319
+ }
4320
+ const result = await withBotLock(name, () => promoteLocalBot({
4207
4321
  dir,
4208
4322
  config,
4209
4323
  companyUid: opts.company,
4210
4324
  api,
4325
+ isRunning: () => readBotListedProcess(dir, config).running,
4326
+ restart: () => botPromoteSeams.start(name, dir, config),
4211
4327
  ...(isFleetRuntimeBot(config) ? { runtime: fleetLocalPromotionRuntime(config.agentUid) } : {}),
4212
- });
4213
- const details = result.pending ? await api.promotionDetails(config.agentUid, opts.company) : null;
4328
+ }), { command: "hq bot promote" });
4329
+ let details = null;
4330
+ let detailsError = null;
4331
+ if (result.pending) {
4332
+ try {
4333
+ details = await api.promotionDetails(config.agentUid, opts.company);
4334
+ }
4335
+ catch (err) {
4336
+ detailsError = `${promotionDetailsError(dir, err)}, so the details of the move could not be read`;
4337
+ }
4338
+ }
4339
+ const failure = details?.failure ? promotionFailureText(dir, config, opts.company, details.failure, details.failureCode) : null;
4214
4340
  if (opts.json)
4215
- console.log(JSON.stringify({ ...result, pairing: details?.pairing ?? null, ...(details?.failure ? { failure: details.failure } : {}) }));
4216
- else if (details?.failure)
4217
- console.log(`${name}: ${details.failure}`);
4341
+ console.log(JSON.stringify({ ...result, pairing: details?.pairing ?? null, ...(failure ? { failure } : {}), ...(detailsError ? { detailsError } : {}) }));
4342
+ else if (failure)
4343
+ console.log(`${name}: ${failure}`);
4344
+ else if (detailsError)
4345
+ console.log(`${name}: ${result.promotion.phase}. ${detailsError}. Run the same command to continue promotion.`);
4218
4346
  else if (details?.pairing)
4219
4347
  console.log(`${name}: connect the cloud bot to your ChatGPT subscription at ${details.pairing.url}, using code ${details.pairing.code}. Then run the same command to continue.`);
4220
4348
  else
@@ -4236,6 +4364,7 @@ export function registerBotCommand(program) {
4236
4364
  .option("--intro <text>", `The hello the bot DMs you when it first comes online (verbatim, up to ${BOT_INTRO_MAX_CHARS} chars)`)
4237
4365
  .option("--kickoff <prompt>", `A first task the bot starts on by itself right after its hello: one model turn run as if you had sent it, answered in your DM, once (up to ${BOT_KICKOFF_MAX_CHARS} chars)`)
4238
4366
  .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")
4367
+ .option("--cloud", "Create a personal bot that runs on your personal Outpost instead of this computer; it acts as you in every company you belong to")
4239
4368
  .option("--no-daemon", "Accepted for compatibility; HQ Fleet bots run under their own background service")
4240
4369
  .option("--no-start", "Create without starting")
4241
4370
  .option("--ready-timeout <seconds>", `How long to wait for the bot to be ready to chat before returning (default ${DEFAULT_BOT_READY_TIMEOUT_SECONDS})`)
@@ -535,7 +535,7 @@ export function registerCapacityCommand(program, deps = {}) {
535
535
  });
536
536
  capacity
537
537
  .command("login")
538
- .description("Show signed-in accounts, or sign into a provider through hq lanes accounts login")
538
+ .description("Show signed-in accounts, or sign into a provider through hq runners accounts login")
539
539
  .argument("[provider]", "claude, codex, or grok")
540
540
  .option("--account <name>", "Registry account id. Omit to name it from the organization after the first read")
541
541
  .option("--repair", "Sign in again for signed-out accounts. Expired accounts are listed, not logged in again")
@@ -1880,10 +1880,10 @@ export function runHandoffArchiveDecision(args, context) {
1880
1880
  env: { HQ_NO_UPDATE_CHECK: "1" },
1881
1881
  });
1882
1882
  if (lanes.code !== 0)
1883
- return archiveNo("could not verify background work: hq lanes list failed");
1883
+ return archiveNo("could not verify background work: hq runners list failed");
1884
1884
  const lanesActive = laneCount(lanes.stdout ?? "");
1885
1885
  if (lanesActive === undefined)
1886
- return archiveNo("could not verify background work: hq lanes list failed");
1886
+ return archiveNo("could not verify background work: hq runners list failed");
1887
1887
  if (lanesActive > 0)
1888
1888
  return archiveNo(`background work running: ${lanesActive} active lane(s)`);
1889
1889
  const monitors = subprocess("hq", ["monitor", "list", "--json"], cwd, {
@@ -1,4 +1,5 @@
1
1
  /** Native TypeScript implementation of the local ontology scaffold scripts. */
2
+ import { splitFrontmatterBody } from "../utils/frontmatter.js";
2
3
  import { createHash } from "node:crypto";
3
4
  import { spawnSync } from "node:child_process";
4
5
  import * as fs from "node:fs";
@@ -257,10 +258,10 @@ function fileNamedExists(directory, name) {
257
258
  }
258
259
  function frontmatter(file) {
259
260
  const text = fs.readFileSync(file, "utf8");
260
- const match = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
261
- const output = { _body: (match ? match[2] : text).trim() };
262
- if (match) {
263
- for (const line of match[1].split("\n")) {
261
+ const block = splitFrontmatterBody(text, "lf");
262
+ const output = { _body: (block?.body ?? text).trim() };
263
+ if (block) {
264
+ for (const line of block.yaml.split("\n")) {
264
265
  const item = line.match(/^([A-Za-z_]+):\s*(.*)$/);
265
266
  if (item)
266
267
  output[item[1]] = item[2].trim().replace(/^"(.*)"$/, "$1");
@@ -150,6 +150,7 @@
150
150
  *
151
151
  * The script's top-level return value prints to stdout as JSON.
152
152
  */
153
+ import { findHqRootAncestor } from "../utils/hq-roots-core.js";
153
154
  import { spawn, spawnSync } from 'node:child_process';
154
155
  import crypto from 'node:crypto';
155
156
  import fs from 'node:fs';
@@ -171,15 +172,9 @@ function findHqRoot() {
171
172
  if (process.env.HQ_ROOT)
172
173
  return path.resolve(process.env.HQ_ROOT);
173
174
  for (const start of [__dirname, process.cwd()]) {
174
- let dir = path.resolve(start);
175
- for (;;) {
176
- if (looksLikeHqRoot(dir))
177
- return dir;
178
- const parent = path.dirname(dir);
179
- if (parent === dir)
180
- break;
181
- dir = parent;
182
- }
175
+ const dir = findHqRootAncestor(path.resolve(start), looksLikeHqRoot);
176
+ if (dir !== null)
177
+ return dir;
183
178
  }
184
179
  process.stderr.write('workflow-runner: cannot locate the HQ root — set HQ_ROOT\n');
185
180
  process.exit(2);
@@ -0,0 +1,3 @@
1
+ import type { Command } from "commander";
2
+ export declare function registerDeployAppDatabaseCommand(deploy: Command): void;
3
+ //# sourceMappingURL=deploy-app-db.d.ts.map
@@ -0,0 +1,79 @@
1
+ import { deployApiRequest } from "../lib/deploy-api.js";
2
+ import { ensureCognitoToken, resolveCognitoTokenSource } from "../utils/cognito-session.js";
3
+ class EnableDatabaseError extends Error {
4
+ }
5
+ const VERIFY_SETTING = "Check the app's database setting before trying again.";
6
+ function responseError(status) {
7
+ switch (status) {
8
+ case 400:
9
+ return new EnableDatabaseError("The deploy service refused the request. Check the app ID and billing acknowledgement.");
10
+ case 401:
11
+ return new EnableDatabaseError("Your deploy sign-in expired. Run hq login and try again.");
12
+ case 403:
13
+ case 404:
14
+ return new EnableDatabaseError("Could not access this app. To continue, check your scope and app ID or ask the app owner.");
15
+ case 429:
16
+ return new EnableDatabaseError("The deploy service is rate-limiting requests. Wait a moment before trying again.");
17
+ default:
18
+ return new EnableDatabaseError(`Could not confirm database enablement (HTTP ${status}). ${VERIFY_SETTING}`);
19
+ }
20
+ }
21
+ async function enableDatabase(appId, options) {
22
+ const { company, personal, acknowledgeDatabaseBilling, json } = options;
23
+ if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
24
+ throw new EnableDatabaseError("Use the app ID shown by hq deploy list.");
25
+ }
26
+ if ((company !== undefined) === (personal === true)) {
27
+ throw new EnableDatabaseError("Choose exactly one of --company <slug> or --personal.");
28
+ }
29
+ if (company !== undefined && !/^[a-z0-9][a-z0-9-]{0,62}$/.test(company)) {
30
+ throw new EnableDatabaseError("Use a valid company slug.");
31
+ }
32
+ if (acknowledgeDatabaseBilling !== true) {
33
+ throw new EnableDatabaseError("Obtain explicit database billing approval before passing --acknowledge-database-billing.");
34
+ }
35
+ if (resolveCognitoTokenSource() === "machine") {
36
+ throw new EnableDatabaseError("Database enablement requires a person identity. Sign in as the authorized operator.");
37
+ }
38
+ const token = await ensureCognitoToken({ tokenSource: "person", interactive: false }).catch(() => {
39
+ throw new EnableDatabaseError("Could not get an HQ person sign-in. Run hq login and try again.");
40
+ });
41
+ const headers = company === undefined
42
+ ? { "X-HQ-Deploy-Scope": "personal" }
43
+ : { "X-Org-Slug": company };
44
+ const response = await deployApiRequest(token, `/api/apps/${encodeURIComponent(appId)}`, "PATCH", {
45
+ database: true,
46
+ databaseBillingAcknowledged: true,
47
+ }, headers).catch(() => {
48
+ throw new EnableDatabaseError(`Could not confirm database enablement. ${VERIFY_SETTING}`);
49
+ });
50
+ if (response.status !== 200)
51
+ throw responseError(response.status);
52
+ const receipt = await response.json().catch(() => null);
53
+ if (receipt?.id !== appId || receipt.database !== true) {
54
+ throw new EnableDatabaseError(`The deploy service returned an invalid database setting receipt. ${VERIFY_SETTING}`);
55
+ }
56
+ console.log(json
57
+ ? JSON.stringify({ appId, database: true })
58
+ : `Database setting saved for the next app deploy of ${appId}.`);
59
+ }
60
+ export function registerDeployAppDatabaseCommand(deploy) {
61
+ deploy.command("enable-database <app-id>")
62
+ .description("Enable database attachment for the next app deploy")
63
+ .option("--company <slug>", "company owning the app")
64
+ .option("--personal", "use personal scope")
65
+ .option("--acknowledge-database-billing", "confirm explicit database billing approval")
66
+ .option("--json", "print the saved database setting as JSON")
67
+ .action(async (appId, options) => {
68
+ try {
69
+ await enableDatabase(appId, options);
70
+ }
71
+ catch (error) {
72
+ console.error(error instanceof EnableDatabaseError
73
+ ? error.message
74
+ : `Could not confirm database enablement. ${VERIFY_SETTING}`);
75
+ process.exitCode = 1;
76
+ }
77
+ });
78
+ }
79
+ //# sourceMappingURL=deploy-app-db.js.map
@@ -0,0 +1,3 @@
1
+ import type { Command } from "commander";
2
+ export declare function registerDeployAppUploadCommand(deploy: Command): void;
3
+ //# sourceMappingURL=deploy-app-upload.d.ts.map
@@ -0,0 +1,120 @@
1
+ import { openAsBlob } from "node:fs";
2
+ import { stat } from "node:fs/promises";
3
+ import { deployApiFormRequest } from "../lib/deploy-api.js";
4
+ import { ensureCognitoToken, resolveCognitoTokenSource } from "../utils/cognito-session.js";
5
+ const MAX_ARCHIVE_BYTES = 100 * 1024 * 1024;
6
+ class AppUploadError extends Error {
7
+ }
8
+ function scopeHeaders(options) {
9
+ if (Boolean(options.company) === Boolean(options.personal)) {
10
+ throw new AppUploadError("Choose exactly one of --company <slug> or --personal.");
11
+ }
12
+ if (options.company) {
13
+ if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(options.company)) {
14
+ throw new AppUploadError("Use a valid company slug.");
15
+ }
16
+ return { "X-Org-Slug": options.company };
17
+ }
18
+ if (resolveCognitoTokenSource() === "machine") {
19
+ throw new AppUploadError("A machine identity needs an explicit company scope. Choose an authorized company.");
20
+ }
21
+ return { "X-HQ-Deploy-Scope": "personal" };
22
+ }
23
+ async function loadArchive(path) {
24
+ try {
25
+ const file = await stat(path);
26
+ if (!file.isFile())
27
+ throw new AppUploadError("Choose a regular gzip archive file.");
28
+ if (file.size > MAX_ARCHIVE_BYTES)
29
+ throw new AppUploadError("The archive exceeds 100 MiB. Rebuild a smaller archive.");
30
+ const blob = await openAsBlob(path, { type: "application/gzip" });
31
+ if (blob.size > MAX_ARCHIVE_BYTES)
32
+ throw new AppUploadError("The archive exceeds 100 MiB. Rebuild a smaller archive.");
33
+ const magic = new Uint8Array(await blob.slice(0, 2).arrayBuffer());
34
+ if (magic[0] !== 0x1f || magic[1] !== 0x8b) {
35
+ throw new AppUploadError("Choose a gzip archive produced by the app build.");
36
+ }
37
+ return blob;
38
+ }
39
+ catch (error) {
40
+ if (error instanceof AppUploadError)
41
+ throw error;
42
+ throw new AppUploadError("Could not read the archive. Check the file path and permissions.");
43
+ }
44
+ }
45
+ async function failureMessage(response) {
46
+ if (response.status === 401)
47
+ return "Your deploy sign-in expired. Run hq login and try again.";
48
+ if (response.status === 403 || response.status === 404) {
49
+ return "Could not access this app. To continue, check your scope and app ID or ask the app owner.";
50
+ }
51
+ if (response.status === 413 || response.status === 415 || response.status === 422) {
52
+ return "The deploy service refused the archive. Rebuild it as gzip within 100 MiB and try again.";
53
+ }
54
+ if (response.status === 409 || response.status === 503) {
55
+ const body = await response.json().catch(() => null);
56
+ const code = body?.code ?? body?.error?.code;
57
+ if (response.status === 409 && code === "DATABASE_BILLING_ACK_REQUIRED") {
58
+ return "This deployment needs database billing approval. Obtain approval before acknowledging billing.";
59
+ }
60
+ if (response.status === 409 && code === "PUBLIC_SECRET_BACKED_DEPLOY_BLOCKED") {
61
+ return "This public app has bound secrets. Add an access gate or obtain explicit approval before acknowledging the risk.";
62
+ }
63
+ if (response.status === 503 && code === "DATABASE_PROVISIONING") {
64
+ const hint = body?.retryAfterSeconds;
65
+ const delay = typeof hint === "number" && Number.isFinite(hint) ? Math.max(2, Math.min(30, Math.floor(hint))) : 5;
66
+ return `DATABASE_PROVISIONING: the app database is being created. Wait and retry in ${delay} seconds.`;
67
+ }
68
+ }
69
+ return "Could not confirm the app upload. Check deployment history before trying again.";
70
+ }
71
+ async function uploadApp(appId, archive, options) {
72
+ if (!/^(?:[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}|app_[A-Za-z0-9_-]+)$/i.test(appId)) {
73
+ throw new AppUploadError("Use the app ID shown by hq deploy list.");
74
+ }
75
+ const headers = scopeHeaders(options);
76
+ const form = new FormData();
77
+ form.set("type", "app");
78
+ form.set("file", await loadArchive(archive), "upload.tar.gz");
79
+ if (options.acknowledgeDatabaseBilling)
80
+ form.set("database_billing_acknowledged", "true");
81
+ if (options.acknowledgePublicSecretRisk)
82
+ form.set("acknowledge_public_secret_risk", "true");
83
+ const token = await ensureCognitoToken({ interactive: false, ...(options.personal ? { tokenSource: "person" } : {}) })
84
+ .catch(() => { throw new AppUploadError("Could not get an HQ sign-in. Run hq login or check the configured machine identity."); });
85
+ const appRoute = `/api/apps/${encodeURIComponent(appId)}`;
86
+ const response = await deployApiFormRequest(token, `${appRoute}/deploy`, form, headers)
87
+ .catch(() => { throw new AppUploadError("Could not confirm the app upload. Check deployment history before trying again."); });
88
+ if (response.status !== 200)
89
+ throw new AppUploadError(await failureMessage(response));
90
+ const receipt = await response.json().catch(() => null);
91
+ const { appId: returnedApp, deployId, version, status, statusUrl } = receipt ?? {};
92
+ if (returnedApp !== appId || typeof deployId !== "string" || !/^[A-Za-z0-9_-]+$/.test(deployId)
93
+ || typeof version !== "number" || !Number.isSafeInteger(version) || version < 1
94
+ || typeof status !== "string" || !/^[a-z][a-z0-9_-]*$/.test(status)
95
+ || statusUrl !== `${appRoute}/deploys/${deployId}/status`) {
96
+ throw new AppUploadError("The deploy service returned an invalid receipt. Check deployment history before trying again.");
97
+ }
98
+ console.log(options.json
99
+ ? JSON.stringify({ appId, deployId, version, status, statusUrl })
100
+ : `App upload received for ${appId} (deployment ${deployId}, status ${status}).`);
101
+ }
102
+ export function registerDeployAppUploadCommand(deploy) {
103
+ deploy.command("upload-app <app-id> <archive>")
104
+ .description("Upload an app archive with frontend and backend code")
105
+ .option("--company <slug>", "company owning the app")
106
+ .option("--personal", "use personal scope")
107
+ .option("--acknowledge-database-billing", "confirm explicit database billing approval")
108
+ .option("--acknowledge-public-secret-risk", "confirm explicit approval for the public app's secret-binding risk")
109
+ .option("--json", "print the deployment receipt as JSON")
110
+ .action(async (appId, archive, options) => {
111
+ try {
112
+ await uploadApp(appId, archive, options);
113
+ }
114
+ catch (error) {
115
+ console.error(error instanceof AppUploadError ? error.message : "Could not confirm the app upload. Check deployment history before trying again.");
116
+ process.exitCode = 1;
117
+ }
118
+ });
119
+ }
120
+ //# sourceMappingURL=deploy-app-upload.js.map