@indigoai-us/hq-cli 5.345.236 → 5.345.238

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 (96) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/command-catalog.generated.d.ts +1 -1
  3. package/dist/command-catalog.generated.js +1 -1
  4. package/dist/commands/bot.d.ts +2 -0
  5. package/dist/commands/bot.js +32 -0
  6. package/dist/commands/daemon.d.ts +1 -0
  7. package/dist/commands/daemon.js +70 -6
  8. package/dist/commands/deploy-app-db.js +4 -19
  9. package/dist/commands/deploy-app-upload.js +66 -40
  10. package/dist/commands/deploy-mutations.js +24 -16
  11. package/dist/commands/deploy-runtime-bindings.js +7 -26
  12. package/dist/commands/deploy-ssr.js +5 -24
  13. package/dist/commands/mesh.js +6 -2
  14. package/dist/commands/signals-run.d.ts +43 -2
  15. package/dist/commands/signals-run.js +85 -7
  16. package/dist/commands/sync-core.d.ts +7 -0
  17. package/dist/commands/sync-core.js +52 -3
  18. package/dist/lib/agent-kit/inbox-state.d.ts +2 -1
  19. package/dist/lib/agent-kit/inbox-state.js +27 -3
  20. package/dist/lib/bot/continuity.d.ts +21 -2
  21. package/dist/lib/bot/continuity.js +48 -19
  22. package/dist/lib/bot/fleet-cron.js +6 -0
  23. package/dist/lib/bot/fleet-local.d.ts +11 -1
  24. package/dist/lib/bot/fleet-local.js +21 -1
  25. package/dist/lib/bot/fleet-state.d.ts +129 -0
  26. package/dist/lib/bot/fleet-state.js +669 -0
  27. package/dist/lib/bot/promote.d.ts +32 -3
  28. package/dist/lib/bot/promote.js +188 -16
  29. package/dist/lib/bot/promotion-hold-reconcile.d.ts +56 -0
  30. package/dist/lib/bot/promotion-hold-reconcile.js +155 -0
  31. package/dist/lib/daemon/catalog.d.ts +13 -0
  32. package/dist/lib/daemon/catalog.js +32 -6
  33. package/dist/lib/daemon/lanes-reconcile-status.d.ts +0 -4
  34. package/dist/lib/daemon/lanes-reconcile-status.js +2 -12
  35. package/dist/lib/daemon/lanes-reconcile-watcher.d.ts +1 -1
  36. package/dist/lib/daemon/lanes-reconcile-watcher.js +2 -1
  37. package/dist/lib/daemon/legacy-handover.d.ts +38 -0
  38. package/dist/lib/daemon/legacy-handover.js +117 -0
  39. package/dist/lib/daemon/mesh-owner.js +2 -1
  40. package/dist/lib/daemon/run.d.ts +35 -2
  41. package/dist/lib/daemon/run.js +108 -15
  42. package/dist/lib/daemon/selfcheck.d.ts +28 -0
  43. package/dist/lib/daemon/selfcheck.js +86 -15
  44. package/dist/lib/deploy-api.d.ts +1 -1
  45. package/dist/lib/deploy-api.js +2 -1
  46. package/dist/lib/deploy-identity.d.ts +18 -0
  47. package/dist/lib/deploy-identity.js +179 -0
  48. package/dist/lib/hot-channels/alert.js +13 -6
  49. package/dist/lib/hot-channels/fleet-complete.d.ts +89 -0
  50. package/dist/lib/hot-channels/fleet-complete.js +157 -0
  51. package/dist/lib/hot-channels/run.js +2 -1
  52. package/dist/lib/hot-channels/signals-claude-login.d.ts +3 -2
  53. package/dist/lib/hot-channels/signals-claude-login.js +6 -1
  54. package/dist/lib/hot-channels/signals-pass-failure.d.ts +29 -0
  55. package/dist/lib/hot-channels/signals-pass-failure.js +36 -0
  56. package/dist/lib/hot-channels/signals-pass.d.ts +49 -2
  57. package/dist/lib/hot-channels/signals-pass.js +188 -12
  58. package/dist/lib/hot-channels/signals-runtime.d.ts +6 -3
  59. package/dist/lib/hot-channels/signals-runtime.js +11 -2
  60. package/dist/lib/lanes/reconcile-result.d.ts +5 -0
  61. package/dist/lib/lanes/reconcile-result.js +20 -2
  62. package/dist/lib/lanes/reconcile.js +12 -3
  63. package/dist/lib/mesh/live/emit.js +25 -6
  64. package/dist/lib/mesh/live/flush.js +119 -15
  65. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -0
  66. package/dist/lib/mesh/live/reporting-privacy.js +147 -1
  67. package/dist/lib/mesh/live/spool.d.ts +16 -0
  68. package/dist/lib/mesh/live/spool.js +45 -0
  69. package/dist/lib/signals/engine.d.ts +17 -3
  70. package/dist/lib/signals/engine.js +28 -9
  71. package/dist/lib/signals/failure-alert.d.ts +33 -1
  72. package/dist/lib/signals/failure-alert.js +72 -5
  73. package/dist/lib/signals/owner-notice.d.ts +94 -0
  74. package/dist/lib/signals/owner-notice.js +233 -0
  75. package/dist/lib/signals/reply.d.ts +7 -0
  76. package/dist/lib/signals/reply.js +23 -3
  77. package/dist/lib/signals/steps/adapters.d.ts +51 -2
  78. package/dist/lib/signals/steps/adapters.js +213 -7
  79. package/dist/lib/signals/steps/extract.js +18 -4
  80. package/dist/lib/signals/steps/types.d.ts +63 -1
  81. package/dist/lib/signals/steps/types.js +32 -0
  82. package/dist/lib/sync-core/engine-auth.d.ts +35 -0
  83. package/dist/lib/sync-core/engine-auth.js +96 -0
  84. package/dist/lib/sync-core/engine-home.d.ts +6 -0
  85. package/dist/lib/sync-core/engine-home.js +12 -0
  86. package/dist/lib/sync-core/rollout-state.d.ts +1 -0
  87. package/dist/lib/sync-core/rollout-state.js +3 -0
  88. package/dist/lib/vault-sync-switches.d.ts +7 -0
  89. package/dist/lib/vault-sync-switches.js +56 -0
  90. package/dist/lib/work-context/errors.d.ts +12 -0
  91. package/dist/lib/work-context/errors.js +15 -0
  92. package/dist/lib/work-context/organize.js +6 -1
  93. package/dist/lib/work-context/reconcile.js +20 -1
  94. package/dist/utils/resident-package-preload.js +34 -4
  95. package/docs/anywhere-runtime.md +6 -0
  96. package/package.json +7 -7
@@ -1,6 +1,7 @@
1
1
  import { type BotApi, type BotPromotionBrain, type BotPromotionState } from "./api.js";
2
- import type { BotConfig, BotRuntimeId } from "./config.js";
2
+ import { type BotConfig, type BotRuntimeId } from "./config.js";
3
3
  import type { BotMachineCreds } from "./creds.js";
4
+ import { type FleetStateManifest } from "./fleet-state.js";
4
5
  /** HQ's note on why a move is stuck, as the person should read it; HQ's own text goes to the bot log. */
5
6
  export declare function promotionFailureText(dir: string, config: BotConfig, companyUid: string, failure: string, failureCode?: string): string;
6
7
  /** Any error from reading a move's details, as a short reason; the raw text goes to the bot log. */
@@ -45,7 +46,7 @@ export interface LocalBotPromotionRuntime {
45
46
  model?: string;
46
47
  } | null;
47
48
  }
48
- /** The bot's brain as sent at prepare: a known runtime profile provider wins over bot.json. */
49
+ /** The bot's brain as sent at prepare: a known runtime profile provider, and its model, win over bot.json. */
49
50
  export declare function promotionBrain(config: BotConfig, runtime?: LocalBotPromotionRuntime): BotPromotionBrain;
50
51
  /** Cloud bots run on Codex only for now. A bot already held names the cancel. */
51
52
  export declare function promotionBrainRefusal(config: BotConfig, brain: BotPromotionBrain, dir: string): Error | null;
@@ -63,10 +64,36 @@ export declare function promoteLocalBot(input: {
63
64
  runtime?: LocalBotPromotionRuntime;
64
65
  isRunning?: () => boolean;
65
66
  restart?: () => Promise<unknown>;
67
+ fleetHome?: string;
68
+ onSnapshot?: (fleetState: FleetStateManifest | null) => void;
66
69
  }): Promise<{
67
70
  promotion: BotPromotionState;
68
71
  pending: boolean;
72
+ fleetState?: FleetStateManifest | null;
69
73
  }>;
74
+ export type PromotionHoldReconcile = {
75
+ outcome: "none";
76
+ } | {
77
+ outcome: "kept";
78
+ reason: string;
79
+ } | {
80
+ outcome: "released";
81
+ reason: "cancelled" | "not-found";
82
+ companyUid: string;
83
+ wasRunning: boolean | null;
84
+ };
85
+ /** A held bot whose move HQ has since dropped frees itself, by the proof rules
86
+ * of cancelLocalBotPromotion: HQ shows this hold's own operation cancelled, or
87
+ * HQ has no move for the bot and its owner is the one signed in. A bot with an
88
+ * active-promotion receipt, a damaged hold, an in-flight or different move, or
89
+ * any failed read stays held. Never cancels anything on the server.
90
+ */
91
+ export declare function reconcilePromotionHold(input: {
92
+ dir: string;
93
+ config: BotConfig;
94
+ api: BotApi;
95
+ signedInPerson?: SignedInPerson;
96
+ }): Promise<PromotionHoldReconcile>;
70
97
  export type PromotionCancelOutcome = "canceled" | "pending" | "active" | "not-found";
71
98
  export interface PromotionCancelResult {
72
99
  outcome: PromotionCancelOutcome;
@@ -89,7 +116,8 @@ export declare const PROMOTION_CANCEL_IDENTITY_RETRIES = 3;
89
116
  * promotion at all. Anything else keeps the hold. A damaged hold may name
90
117
  * another company, so only a confirmed cancel releases it. When HQ will not
91
118
  * show the move (403, or 404 without a code), a readable hold for this company
92
- * still asks HQ to cancel its operation: cancel is authorized on the bot alone.
119
+ * still asks HQ to cancel its operation: cancel is authorized on the bot alone,
120
+ * and a PROMOTION_NOT_FOUND answer then keeps the hold, since HQ proved nothing.
93
121
  */
94
122
  export declare function cancelLocalBotPromotion(input: {
95
123
  dir: string;
@@ -99,6 +127,7 @@ export declare function cancelLocalBotPromotion(input: {
99
127
  pollMs?: number;
100
128
  timeoutMs?: number;
101
129
  sleep?: (ms: number) => Promise<void>;
130
+ now?: () => number;
102
131
  onWaiting?: () => void;
103
132
  signedInPerson?: SignedInPerson;
104
133
  }): Promise<PromotionCancelResult>;
@@ -3,8 +3,10 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { BotApiError } from "./api.js";
6
+ import { HQ_FLEET_RUNTIME_ENGINE_ID } from "./config.js";
6
7
  import { botCredsPath } from "./paths.js";
7
- import { snapshotBotContinuity, validateBotContinuity } from "./continuity.js";
8
+ import { FLEET_STATE_DIR, planFleetContinuity, snapshotBotContinuity, validateBotContinuity } from "./continuity.js";
9
+ import { collectFleetState, FleetStateLimitError, fleetStateManifestOf } from "./fleet-state.js";
8
10
  import { attestPromotionDrain, hasPromotionHold, holdForPromotion, localBotProcessAlive, promotionHoldSummary, readPromotionHoldOrigin, recordPromotionHoldOrigin, waitForPromotionDrain, } from "./promotion-hold.js";
9
11
  import { uploadLocalBotPromotion } from "./promotion-upload.js";
10
12
  import { appendBotLog, botLogLine } from "./log.js";
@@ -80,12 +82,14 @@ function otherCompanyError(config, held, asked, cancel) {
80
82
  (cancel ? "" : `Continue that move with: hq bot promote ${config.name} --company ${held}, or `) +
81
83
  `${cancel ? "Cancel" : "cancel"} it with: hq bot promote ${config.name} --company ${held} --cancel`);
82
84
  }
85
+ /** Every file a release removes, for a person freeing the bot by hand. */
86
+ const manualRelease = (holdFile) => `delete ${holdFile} and the promotion-hold-origin.json, promotion-active.json and promotion-snapshot-*.json files beside it`;
83
87
  function damagedHoldError(dir, config, reason, companyUid) {
84
88
  const file = path.join(dir, "promotion-hold.json");
85
89
  return new Error(`The promotion hold for ${config.name} on this computer (${file}) is damaged: ${reason}. ` +
86
90
  `HQ has no move to the cloud for ${config.name} in company ${companyUid}, but a damaged hold may belong to a move in another company, so it was not removed. ` +
87
91
  `Nothing was released: ${config.name} stays held on this computer. If it is moving to another company, cancel there with: hq bot promote ${config.name} --company <uid> --cancel. ` +
88
- `If you are sure it is not moving to the cloud anywhere, delete ${file} and the promotion-snapshot-*.json files beside it, then start it with: hq bot start ${config.name}`);
92
+ `If you are sure it is not moving to the cloud anywhere, ${manualRelease(file)}, then start it with: hq bot start ${config.name}`);
89
93
  }
90
94
  /** HQ's raw answer goes to the bot's own log only, never to the person. */
91
95
  function logRaw(dir, error) {
@@ -233,10 +237,10 @@ function withCancelHint(error, config, companyUid, dir) {
233
237
  return new Error(`${reason(error, dir)}. ${config.name} stays stopped on this computer while it is held for the move. ` +
234
238
  `Run the same command to continue, or cancel the move with: hq bot promote ${config.name} --company ${companyUid} --cancel`, { cause: error });
235
239
  }
236
- /** The bot's brain as sent at prepare: a known runtime profile provider wins over bot.json. */
240
+ /** The bot's brain as sent at prepare: a known runtime profile provider, and its model, win over bot.json. */
237
241
  export function promotionBrain(config, runtime) {
238
242
  const profile = runtime?.brain?.() ?? null;
239
- const model = config.model?.trim() || profile?.model?.trim();
243
+ const model = profile?.runtime ? profile.model?.trim() || config.model?.trim() : config.model?.trim() || profile?.model?.trim();
240
244
  const effort = config.effort?.trim();
241
245
  return { runtime: profile?.runtime ?? config.runtime, ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
242
246
  }
@@ -256,6 +260,42 @@ export function promotionBrainRefusal(config, brain, dir) {
256
260
  : `Moving a Grok bot to the cloud is not supported yet. Switch ${name} to Codex first with: hq bot switch-account ${name} --runtime codex, or keep it on this computer. Nothing was changed.`;
257
261
  return Object.assign(new Error(text), { expected: true });
258
262
  }
263
+ /** Where the cloud computer keeps HQ; the released importer plans against it. */
264
+ const CLOUD_HQ_ROOT = "/home/ec2-user/hq-agent";
265
+ /** Run the cloud importer's own checks here, so a snapshot it would refuse is
266
+ * never frozen, uploaded or announced to the server.
267
+ */
268
+ function assertCloudImportable(bundle, config) {
269
+ try {
270
+ validateBotContinuity(bundle, { agentUid: config.agentUid, ownerUid: config.ownerUid });
271
+ planFleetContinuity(bundle, { agentUid: config.agentUid, ownerUid: config.ownerUid, hqRoot: CLOUD_HQ_ROOT, ...(config.companySlug ? { companySlug: config.companySlug } : {}) });
272
+ }
273
+ catch (error) {
274
+ const reason = error instanceof Error ? error.message : String(error);
275
+ if (!reason.includes("SOUL transfer budget"))
276
+ throw error;
277
+ const skillFiles = bundle.files.filter((file) => file.area === "memory" && file.path.startsWith(`${FLEET_STATE_DIR}/skills/`)).length;
278
+ throw new Error(`the cloud bot's identity file lists every moved file and is limited to 32 KiB, which ${bundle.files.length} files (${skillFiles} of them from learned skills) exceed; nothing was truncated`);
279
+ }
280
+ }
281
+ const SKILL_LIMIT = /32 KiB|-file transfer limit|MiB transfer limit/;
282
+ /** Learned skills to name in a pre-flight failure: the ones the error points
283
+ * at, or for a size limit every carried skill, largest first.
284
+ */
285
+ function skillsToRemove(reason, state) {
286
+ const skills = state?.manifest.skills ?? [];
287
+ const named = skills.filter((skill) => reason.includes(`skills/${skill}/`));
288
+ if (named.length || !SKILL_LIMIT.test(reason))
289
+ return named;
290
+ const byBytes = reason.includes("MiB");
291
+ const weight = new Map();
292
+ for (const file of state?.files ?? []) {
293
+ const owner = skills.filter((skill) => file.path.startsWith(`${FLEET_STATE_DIR}/skills/${skill}/`)).sort((a, b) => b.length - a.length)[0];
294
+ if (owner)
295
+ weight.set(owner, (weight.get(owner) ?? 0) + (byBytes ? file.bytes.length : 1));
296
+ }
297
+ return [...weight].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([skill]) => skill);
298
+ }
259
299
  /** One recoverable local-to-cloud step, used by CLI and desktop. Never kills the
260
300
  * local runtime, recopies provider login files, or changes another bot.
261
301
  * When this call creates the hold and fails before the server records the
@@ -267,6 +307,28 @@ export async function promoteLocalBot(input) {
267
307
  const refusal = promotionBrainRefusal(config, brain, dir);
268
308
  if (refusal)
269
309
  throw refusal;
310
+ const fleetBot = config.engine?.id === HQ_FLEET_RUNTIME_ENGINE_ID;
311
+ const stillHeld = `${config.name} is held for this move and stays stopped until it finishes; fix the problem, then rerun hq bot promote ${config.name} --company ${companyUid}, or cancel the move with: hq bot promote ${config.name} --company ${companyUid} --cancel`;
312
+ // The pre-flight and the frozen snapshot scan each unchanged skill file once between them.
313
+ const scanCache = new Map();
314
+ const buildSnapshot = (held) => {
315
+ let state = null;
316
+ try {
317
+ if (!fleetBot)
318
+ return snapshotBotContinuity(config, dir);
319
+ state = collectFleetState(config, dir, { brain, scanCache, ...(input.fleetHome ? { fleetHome: input.fleetHome } : {}) });
320
+ const snapshot = snapshotBotContinuity(config, dir, state?.files);
321
+ assertCloudImportable(snapshot, config);
322
+ return snapshot;
323
+ }
324
+ catch (error) {
325
+ if (!fleetBot)
326
+ throw error;
327
+ const reason = sentence(error).replace(/^Bot continuity: /, "");
328
+ const skills = error instanceof FleetStateLimitError ? error.skills : skillsToRemove(reason, state);
329
+ throw new Error(`This bot cannot be moved to the cloud yet: ${reason}.${skills.length ? ` Remove or shrink ${skills.length === 1 ? "this learned skill" : "these learned skills"} in the bot's skills folder, then retry: ${skills.join(", ")}.` : ""} Nothing was uploaded.${held ? ` ${stillHeld}.` : ""}`, { cause: error });
330
+ }
331
+ };
270
332
  if (config.kind === "personal")
271
333
  throw personalBotError(config);
272
334
  const read = readLocalHold(dir, config);
@@ -277,10 +339,11 @@ export async function promoteLocalBot(input) {
277
339
  throw otherCompanyError(config, localHold.companyUid, companyUid, false);
278
340
  let existing = await readPromotionStatus(api, config, companyUid, dir);
279
341
  let priorOrigin = null;
342
+ let canceledHere = false;
280
343
  if (existing?.phase === "cancelled") {
281
344
  // A canceled operation is finished: no hold, id or frozen snapshot from before is used again.
282
345
  priorOrigin = readPromotionHoldOrigin(dir);
283
- releaseLocalPromotion(dir);
346
+ canceledHere = releaseLocalPromotion(dir);
284
347
  localHold = null;
285
348
  existing = null;
286
349
  }
@@ -289,6 +352,29 @@ export async function promoteLocalBot(input) {
289
352
  throw new Error("Invalid saved promotion operation");
290
353
  const hold = { agentUid: config.agentUid, ownerUid: config.ownerUid, companyUid, operationId };
291
354
  const fresh = !existing && !localHold;
355
+ const file = path.join(dir, `promotion-snapshot-${operationId}.json`);
356
+ // A first attempt that cannot succeed fails here, before the bot is held or stopped.
357
+ if (fleetBot && !existing && !fs.existsSync(file)) {
358
+ try {
359
+ buildSnapshot(localHold !== null);
360
+ }
361
+ catch (error) {
362
+ if (!canceledHere)
363
+ throw error;
364
+ // The canceled move's hold is gone, so put the bot back the way it was before that move.
365
+ const freed = `${sentence(error)}. The earlier move was canceled, so ${config.name} is no longer held on this computer`;
366
+ if (!priorOrigin || !input.restart) {
367
+ throw new Error(`${freed}${priorOrigin === false ? "" : `; start it with: hq bot start ${config.name}`}.`, { cause: error });
368
+ }
369
+ try {
370
+ await input.restart();
371
+ }
372
+ catch (restartError) {
373
+ throw new Error(`${freed}, but it did not start again: ${sentence(restartError)}. Start it with: hq bot start ${config.name}`, { cause: error });
374
+ }
375
+ throw new Error(`${freed} and was started again, since it was running before that move.`, { cause: error });
376
+ }
377
+ }
292
378
  const wasRunning = fresh ? priorOrigin ?? (input.isRunning ?? (() => localBotProcessAlive(dir)))() : null;
293
379
  holdForPromotion(dir, hold);
294
380
  let prepared = !fresh;
@@ -302,11 +388,10 @@ export async function promoteLocalBot(input) {
302
388
  }
303
389
  runtime?.stop();
304
390
  await waitForPromotionDrain(dir, input.drainTimeoutMs ?? 60_000);
305
- const file = path.join(dir, `promotion-snapshot-${operationId}.json`);
306
391
  if (!fs.existsSync(file)) {
307
392
  if (existing)
308
393
  throw new Error("The original frozen snapshot is missing. Restore it before retrying.");
309
- const snapshot = snapshotBotContinuity(config, dir);
394
+ const snapshot = buildSnapshot(false);
310
395
  const temp = `${file}.${randomUUID()}.tmp`;
311
396
  fs.writeFileSync(temp, JSON.stringify(snapshot), { mode: 0o600, flag: "wx" });
312
397
  try {
@@ -324,6 +409,10 @@ export async function promoteLocalBot(input) {
324
409
  validateBotContinuity(bundle, { agentUid: config.agentUid, ownerUid: config.ownerUid });
325
410
  if (existing && existing.snapshotSha256 !== bundle.digest)
326
411
  throw new Error("Frozen snapshot does not match the cloud operation");
412
+ const fleetState = fleetBot ? fleetStateManifestOf(bundle) : null;
413
+ if (fleetBot)
414
+ input.onSnapshot?.(fleetState);
415
+ const carried = fleetBot ? { fleetState } : {};
327
416
  let state = existing;
328
417
  if (!state || state.phase === "preparing") {
329
418
  const machine = runtime ? runtime.machineCredential() : readPrivateJson(botCredsPath(dir), 8192);
@@ -342,15 +431,15 @@ export async function promoteLocalBot(input) {
342
431
  const result = await api.resumePromotion(config.agentUid, { companyUid, operationId });
343
432
  if (result.promotion.phase === "active")
344
433
  recordActivePromotion(dir, hold, result.promotion);
345
- return result;
434
+ return { ...result, ...carried };
346
435
  }
347
- return { promotion: state, pending: state.phase !== "active" };
436
+ return { promotion: state, pending: state.phase !== "active", ...carried };
348
437
  }
349
438
  catch (error) {
350
439
  if (prepared)
351
440
  throw withCancelHint(error, config, companyUid, dir);
352
441
  // A prepare whose answer was lost may still have been recorded: ask before releasing.
353
- if (prepareSent && !(error instanceof BotApiError) && await serverMayKnow(api, config, companyUid, operationId))
442
+ if (prepareSent && (!(error instanceof BotApiError) || error.status >= 500) && await serverMayKnow(api, config, companyUid, operationId))
354
443
  throw withCancelHint(error, config, companyUid, dir);
355
444
  const refused = serverRefusal(error, config);
356
445
  releaseLocalPromotion(dir);
@@ -374,6 +463,79 @@ async function serverMayKnow(api, config, companyUid, operationId) {
374
463
  return true;
375
464
  }
376
465
  }
466
+ function hasReceiptFile(dir) {
467
+ try {
468
+ fs.lstatSync(path.join(dir, "promotion-active.json"));
469
+ return true;
470
+ }
471
+ catch {
472
+ return false;
473
+ }
474
+ }
475
+ /** A held bot whose move HQ has since dropped frees itself, by the proof rules
476
+ * of cancelLocalBotPromotion: HQ shows this hold's own operation cancelled, or
477
+ * HQ has no move for the bot and its owner is the one signed in. A bot with an
478
+ * active-promotion receipt, a damaged hold, an in-flight or different move, or
479
+ * any failed read stays held. Never cancels anything on the server.
480
+ */
481
+ export async function reconcilePromotionHold(input) {
482
+ const { dir, config, api } = input;
483
+ if (!hasPromotionHold(dir))
484
+ return { outcome: "none" };
485
+ if (hasReceiptFile(dir))
486
+ return { outcome: "kept", reason: "the bot moved to the cloud" };
487
+ const read = readLocalHold(dir, config);
488
+ if (!read.hold)
489
+ return { outcome: "kept", reason: `the hold cannot be used: ${read.unreadable ?? "it is missing"}` };
490
+ const companyUid = read.hold.companyUid;
491
+ const operationId = read.hold.operationId;
492
+ let state;
493
+ try {
494
+ state = await readPromotionStatusRaw(api, config, companyUid);
495
+ }
496
+ catch (error) {
497
+ if (error instanceof BotApiError)
498
+ logRaw(dir, error);
499
+ else
500
+ appendBotLog(dir, botLogLine("warn", `promotion: status check failed: ${sentence(error)}`));
501
+ if (!(error instanceof BotApiError && error.status === 404 && error.code === "PROMOTION_NOT_FOUND"))
502
+ return { outcome: "kept", reason: "HQ did not show the move" };
503
+ state = null;
504
+ }
505
+ let why;
506
+ if (state === null) {
507
+ if (!await signedInAsOwner(input))
508
+ return { outcome: "kept", reason: "only the bot's owner can confirm HQ has no move" };
509
+ why = "not-found";
510
+ }
511
+ else if (state.operationId !== operationId) {
512
+ return { outcome: "kept", reason: "HQ shows a different move" };
513
+ }
514
+ else if (state.phase === "active") {
515
+ // The bot is live in the cloud; record it so nothing asks HQ about this hold again.
516
+ try {
517
+ recordActivePromotion(dir, { agentUid: config.agentUid, ownerUid: config.ownerUid, companyUid, operationId }, state);
518
+ }
519
+ catch (error) {
520
+ appendBotLog(dir, botLogLine("warn", `promotion: could not record the cloud move: ${sentence(error)}`));
521
+ }
522
+ return { outcome: "kept", reason: "the bot moved to the cloud" };
523
+ }
524
+ else if (state.phase !== "cancelled") {
525
+ return { outcome: "kept", reason: `the move is ${state.phase}` };
526
+ }
527
+ else
528
+ why = "cancelled";
529
+ const again = readLocalHold(dir, config);
530
+ if (again.hold?.operationId !== operationId || again.hold.companyUid !== companyUid || hasReceiptFile(dir))
531
+ return { outcome: "kept", reason: "the hold changed" };
532
+ const wasRunning = readPromotionHoldOrigin(dir, operationId);
533
+ releaseLocalPromotion(dir);
534
+ appendBotLog(dir, botLogLine("info", why === "cancelled"
535
+ ? `promotion: HQ shows the move ${operationId} to company ${companyUid} cancelled; released the hold on this computer`
536
+ : `promotion: HQ has no move to company ${companyUid} for this bot; released the hold on this computer`));
537
+ return { outcome: "released", reason: why, companyUid, wasRunning };
538
+ }
377
539
  export const PROMOTION_CANCEL_POLL_MS = 5_000;
378
540
  /** Below the bot lock's stale age, so no other command can take the lock mid-cancel. */
379
541
  export const PROMOTION_CANCEL_TIMEOUT_MS = 8 * 60_000;
@@ -384,7 +546,8 @@ export const PROMOTION_CANCEL_IDENTITY_RETRIES = 3;
384
546
  * promotion at all. Anything else keeps the hold. A damaged hold may name
385
547
  * another company, so only a confirmed cancel releases it. When HQ will not
386
548
  * show the move (403, or 404 without a code), a readable hold for this company
387
- * still asks HQ to cancel its operation: cancel is authorized on the bot alone.
549
+ * still asks HQ to cancel its operation: cancel is authorized on the bot alone,
550
+ * and a PROMOTION_NOT_FOUND answer then keeps the hold, since HQ proved nothing.
388
551
  */
389
552
  export async function cancelLocalBotPromotion(input) {
390
553
  const { dir, config, companyUid, api } = input;
@@ -418,20 +581,23 @@ export async function cancelLocalBotPromotion(input) {
418
581
  const pollMs = input.pollMs ?? PROMOTION_CANCEL_POLL_MS;
419
582
  const timeoutMs = input.timeoutMs ?? PROMOTION_CANCEL_TIMEOUT_MS;
420
583
  const sleep = input.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
584
+ const now = input.now ?? Date.now;
421
585
  const kept = `Nothing was released: ${config.name} stays held on this computer.`;
422
586
  let result;
423
587
  try {
588
+ const deadline = now() + timeoutMs;
424
589
  result = await api.cancelPromotion(config.agentUid, { companyUid, operationId });
425
- let waited = 0;
590
+ let announced = false;
426
591
  let identityRetries = 0;
427
592
  for (;;) {
428
593
  if (result.pending) {
429
- if (waited >= timeoutMs)
594
+ if (now() >= deadline)
430
595
  break;
431
- if (waited === 0)
596
+ if (!announced) {
597
+ announced = true;
432
598
  input.onWaiting?.();
599
+ }
433
600
  await sleep(pollMs);
434
- waited += pollMs;
435
601
  }
436
602
  else if (result.identityRestored === false && identityRetries < PROMOTION_CANCEL_IDENTITY_RETRIES) {
437
603
  identityRetries += 1;
@@ -449,7 +615,13 @@ export async function cancelLocalBotPromotion(input) {
449
615
  if (error instanceof BotApiError && error.status === 409 && error.code === "PROMOTION_INSTANCE_NOT_OWNED") {
450
616
  throw new Error(`HQ says the cloud copy of ${config.name} does not belong to this move, so it cannot be canceled from here. ${kept}`, { cause: error });
451
617
  }
452
- if (unseen && !(error instanceof BotApiError && error.status === 404 && error.code === "PROMOTION_NOT_FOUND")) {
618
+ if (unseen && error instanceof BotApiError && error.status === 404 && error.code === "PROMOTION_NOT_FOUND") {
619
+ logRaw(dir, unseen);
620
+ const file = path.join(dir, "promotion-hold.json");
621
+ throw new Error(`${unseen.status === 403 ? "HQ refused to show" : "HQ could not find"} the move of ${config.name} to company ${companyUid} and says it has no move to cancel, so it could not prove the bot is free. ${kept} ` +
622
+ `Sign in as the bot's owner (hq whoami) and run the same command again. If you are sure ${config.name} is not moving to the cloud anywhere, ${manualRelease(file)}, then start it with: hq bot start ${config.name}`, { cause: error });
623
+ }
624
+ if (unseen) {
453
625
  logRaw(dir, unseen);
454
626
  const bothMissing = unseen.status === 404 && error instanceof BotApiError && error.status === 404 && !error.code;
455
627
  if (bothMissing && await cloudAgentPresence(input) === "gone")
@@ -0,0 +1,56 @@
1
+ import { BotApi } from "./api.js";
2
+ import { type BotConfig } from "./config.js";
3
+ import { type PromotionHoldReconcile, type SignedInPerson } from "./promote.js";
4
+ export interface PromotionAccess {
5
+ api: BotApi;
6
+ signedInPerson: SignedInPerson;
7
+ }
8
+ /** The signed-in owner's HQ access, without ever opening a browser sign-in. */
9
+ export declare function ownerPromotionAccess(command: string): PromotionAccess;
10
+ /** How often the daemon and `hq bot run` ask HQ about one held bot. */
11
+ export declare const HELD_BOT_RECONCILE_INTERVAL_MS: number;
12
+ /** Per-bot record of the last HQ check, shared by every process on this
13
+ * computer (a restarting daemon, each `hq bot run`). Written before the check
14
+ * starts, so a check in flight counts as a recent one.
15
+ */
16
+ /** Where the per-bot check records live, under the daemon's own folder. */
17
+ export declare const heldBotThrottleDir: (daemonRoot: string) => string;
18
+ export interface ReconcileThrottle {
19
+ dir: string;
20
+ intervalMs?: number;
21
+ now?: () => number;
22
+ }
23
+ /** Claims this bot's next HQ check: false while a check is in flight or ran within the interval. */
24
+ export declare function claimHeldBotCheck(throttle: ReconcileThrottle, name: string): boolean;
25
+ /** reconcilePromotionHold under the bot's lock. A busy lock, a signed-out owner
26
+ * or any other failure keeps the hold. With a throttle, a bot checked recently
27
+ * (or being checked now) is skipped without asking HQ.
28
+ */
29
+ export declare function reconcileHeldBot(name: string, dir: string, config: BotConfig, opts: {
30
+ command: string;
31
+ access?: PromotionAccess;
32
+ lockWaitMs?: number;
33
+ root?: string;
34
+ throttle?: ReconcileThrottle;
35
+ onWait?: () => void;
36
+ }): Promise<PromotionHoldReconcile>;
37
+ export interface HeldBot {
38
+ name: string;
39
+ dir: string;
40
+ config: BotConfig;
41
+ }
42
+ /** The daemon's self-heal for held bots: one pass at a time, and at most one
43
+ * HQ check per bot per interval across daemon restarts. A released bot's
44
+ * daemon unit is asked to start.
45
+ */
46
+ export declare function createHeldBotReconciler(deps: {
47
+ root?: string;
48
+ platform?: NodeJS.Platform;
49
+ throttle: ReconcileThrottle;
50
+ reconcile?: (bot: HeldBot) => Promise<PromotionHoldReconcile>;
51
+ requestStart: (unitId: string) => void;
52
+ log: (level: "info" | "warn", message: string) => void;
53
+ }): {
54
+ kick(): Promise<void>;
55
+ };
56
+ //# sourceMappingURL=promotion-hold-reconcile.d.ts.map
@@ -0,0 +1,155 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { ensureOwnerToken } from "../../utils/owner-session.js";
5
+ import { resolveCallerPersonUid } from "../../utils/vault-api.js";
6
+ import { BotApi } from "./api.js";
7
+ import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "./config.js";
8
+ import { withBotLock } from "./lock.js";
9
+ import { botsRoot } from "./paths.js";
10
+ import { reconcilePromotionHold } from "./promote.js";
11
+ import { hasPromotionHold } from "./promotion-hold.js";
12
+ /** The signed-in owner's HQ access, without ever opening a browser sign-in. */
13
+ export function ownerPromotionAccess(command) {
14
+ const token = () => ensureOwnerToken({ interactive: false });
15
+ return { api: new BotApi({ token }), signedInPerson: async () => resolveCallerPersonUid(await token(), undefined, { command }) };
16
+ }
17
+ /** How often the daemon and `hq bot run` ask HQ about one held bot. */
18
+ export const HELD_BOT_RECONCILE_INTERVAL_MS = 15 * 60_000;
19
+ /** Per-bot record of the last HQ check, shared by every process on this
20
+ * computer (a restarting daemon, each `hq bot run`). Written before the check
21
+ * starts, so a check in flight counts as a recent one.
22
+ */
23
+ /** Where the per-bot check records live, under the daemon's own folder. */
24
+ export const heldBotThrottleDir = (daemonRoot) => path.join(daemonRoot, "promotion-reconcile");
25
+ const throttleFile = (throttle, name) => path.join(throttle.dir, `${name}.json`);
26
+ /** Claims this bot's next HQ check: false while a check is in flight or ran within the interval. */
27
+ export function claimHeldBotCheck(throttle, name) {
28
+ const now = (throttle.now ?? Date.now)();
29
+ const file = throttleFile(throttle, name);
30
+ try {
31
+ const last = JSON.parse(fs.readFileSync(file, "utf8"));
32
+ if (typeof last.startedAt === "number" && last.startedAt <= now && now - last.startedAt < (throttle.intervalMs ?? HELD_BOT_RECONCILE_INTERVAL_MS))
33
+ return false;
34
+ }
35
+ catch { /* none yet, or unreadable: check now */ }
36
+ writeThrottle(file, { startedAt: now, inFlight: true, pid: process.pid });
37
+ return true;
38
+ }
39
+ function finishHeldBotCheck(throttle, name, result) {
40
+ const file = throttleFile(throttle, name);
41
+ if (result.outcome === "released" || result.outcome === "none") {
42
+ fs.rmSync(file, { force: true });
43
+ return;
44
+ }
45
+ try {
46
+ const last = JSON.parse(fs.readFileSync(file, "utf8"));
47
+ writeThrottle(file, { ...last, inFlight: false, finishedAt: (throttle.now ?? Date.now)() });
48
+ }
49
+ catch { /* the claim stays as written */ }
50
+ }
51
+ function writeThrottle(file, value) {
52
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
53
+ const temp = `${file}.${randomUUID()}.tmp`;
54
+ fs.writeFileSync(temp, JSON.stringify(value), { mode: 0o600 });
55
+ fs.renameSync(temp, file);
56
+ }
57
+ /** reconcilePromotionHold under the bot's lock. A busy lock, a signed-out owner
58
+ * or any other failure keeps the hold. With a throttle, a bot checked recently
59
+ * (or being checked now) is skipped without asking HQ.
60
+ */
61
+ export async function reconcileHeldBot(name, dir, config, opts) {
62
+ let claimed = false;
63
+ let result;
64
+ try {
65
+ if (!hasPromotionHold(dir))
66
+ return { outcome: "none" };
67
+ if (opts.throttle) {
68
+ if (!claimHeldBotCheck(opts.throttle, name))
69
+ return { outcome: "kept", reason: "HQ was asked recently" };
70
+ claimed = true;
71
+ }
72
+ const access = opts.access ?? ownerPromotionAccess(opts.command);
73
+ result = await withBotLock(name, () => reconcilePromotionHold({ dir, config, ...access }), {
74
+ command: opts.command,
75
+ ...(opts.lockWaitMs !== undefined ? { waitMs: opts.lockWaitMs } : {}),
76
+ ...(opts.root ? { root: opts.root } : {}),
77
+ ...(opts.onWait ? { onWait: opts.onWait } : {}),
78
+ });
79
+ }
80
+ catch (error) {
81
+ result = { outcome: "kept", reason: error instanceof Error ? error.message : String(error) };
82
+ }
83
+ if (claimed) {
84
+ try {
85
+ finishHeldBotCheck(opts.throttle, name, result);
86
+ }
87
+ catch { /* the claim stays as written */ }
88
+ }
89
+ return result;
90
+ }
91
+ /** The daemon's self-heal for held bots: one pass at a time, and at most one
92
+ * HQ check per bot per interval across daemon restarts. A released bot's
93
+ * daemon unit is asked to start.
94
+ */
95
+ export function createHeldBotReconciler(deps) {
96
+ const root = deps.root ?? botsRoot();
97
+ const platform = deps.platform ?? process.platform;
98
+ const reconcile = deps.reconcile ?? ((bot) => reconcileHeldBot(bot.name, bot.dir, bot.config, { command: "hq daemon", lockWaitMs: 0, root }));
99
+ let running = null;
100
+ const held = () => {
101
+ let names;
102
+ try {
103
+ names = fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
104
+ }
105
+ catch {
106
+ return [];
107
+ }
108
+ const bots = [];
109
+ for (const name of names) {
110
+ const dir = path.join(root, name);
111
+ try {
112
+ if (!hasPromotionHold(dir) || fs.existsSync(path.join(dir, "promotion-active.json")))
113
+ continue;
114
+ const config = readBotConfig(dir);
115
+ if (config)
116
+ bots.push({ name, dir, config });
117
+ }
118
+ catch { /* unreadable: stays held */ }
119
+ }
120
+ return bots;
121
+ };
122
+ const pass = async () => {
123
+ for (const bot of held()) {
124
+ if (!claimHeldBotCheck(deps.throttle, bot.name))
125
+ continue;
126
+ const result = await reconcile(bot).catch((error) => ({ outcome: "kept", reason: error instanceof Error ? error.message : String(error) }));
127
+ try {
128
+ finishHeldBotCheck(deps.throttle, bot.name, result);
129
+ }
130
+ catch { /* the claim stays as written */ }
131
+ if (result.outcome !== "released")
132
+ continue;
133
+ const fleet = bot.config.engine?.id === HQ_FLEET_RUNTIME_ENGINE_ID;
134
+ const unit = fleet ? (platform === "darwin" ? `fleet-bots:${bot.name}` : null) : `bots:${bot.name}`;
135
+ const start = unit !== null && (fleet || result.wasRunning !== false);
136
+ const why = result.reason === "cancelled" ? "HQ shows its move to the cloud was cancelled" : "HQ has no move to the cloud for it";
137
+ deps.log("info", `${bot.name}: ${why}; released its hold${start ? " and starting it" : `; start it with: hq bot start ${bot.name}`}`);
138
+ if (start) {
139
+ try {
140
+ deps.requestStart(unit);
141
+ }
142
+ catch (error) {
143
+ deps.log("warn", `${bot.name}: could not ask the daemon to start it: ${error instanceof Error ? error.message : String(error)}`);
144
+ }
145
+ }
146
+ }
147
+ };
148
+ return {
149
+ kick() {
150
+ running ??= pass().catch(() => undefined).finally(() => { running = null; });
151
+ return running;
152
+ },
153
+ };
154
+ }
155
+ //# sourceMappingURL=promotion-hold-reconcile.js.map
@@ -23,10 +23,14 @@ export declare const SERVICE_DESCRIPTIONS: Record<ServiceName, string>;
23
23
  export declare const DEFAULT_SERVICES: Record<MachineType, readonly ServiceName[]>;
24
24
  /** Services another enabled service turns on; only an explicit disable keeps them off. */
25
25
  export declare const IMPLIED_SERVICES: Partial<Record<ServiceName, ServiceName>>;
26
+ /** Services that run whenever a vault is on the new sync engine here, whatever the config says. */
27
+ export declare const ENGINE_REQUIRED_SERVICES: readonly ServiceName[];
26
28
  /** Defaults plus this host's overrides, in catalog order. Unknown names are ignored. */
27
29
  export declare function enabledServices(machineType: MachineType, overrides: {
28
30
  enable: readonly string[];
29
31
  disable: readonly string[];
32
+ }, opts?: {
33
+ engineVaults?: number;
30
34
  }): ServiceName[];
31
35
  type UnitCommand = {
32
36
  type: "hq";
@@ -141,9 +145,14 @@ export declare const SYNC_CORE_SELFCHECK_UNIT = "sync-core-selfcheck";
141
145
  export declare const SYNC_CORE_SELFCHECK_INTERVAL_SEC = 3600;
142
146
  export declare const SYNC_CORE_MANIFEST_INTERVAL_SEC: number;
143
147
  export declare const SYNC_CORE_LEGACY_SETTLE_MS: number;
148
+ /** How long an engine may wait for the old sync to restart before status and the self-check call it stuck. */
149
+ export declare const LEGACY_HANDOVER_STUCK_AFTER_MS: number;
150
+ export declare const LEGACY_HANDOVER_STUCK_PREFIX = "stuck: waiting over 10 minutes for the running sync";
144
151
  export type LegacySyncHolder = {
145
152
  status: "started";
146
153
  startedAt: number;
154
+ pid?: number;
155
+ owner?: string;
147
156
  } | {
148
157
  status: "missing";
149
158
  } | {
@@ -181,6 +190,8 @@ export interface PlanContext {
181
190
  syncCoreRunning?: SyncCoreRunning;
182
191
  legacySyncReadyForCore?: boolean;
183
192
  legacySyncHolder?: LegacySyncHolder;
193
+ /** When the daemon last asked the old sync runner to stop so it restarts with the new skip list. */
194
+ legacyHandoverStopRequestedAt?: number;
184
195
  now?: number;
185
196
  /** A legacy desktop app or sync unit is still managing sync. */
186
197
  desktopAppManagesSync: boolean;
@@ -247,6 +258,8 @@ export declare const CODEX_RUNNER_SCRIPT = "/usr/local/bin/outpost-codex-runner.
247
258
  /** The outpost's Claude runner script, read for the session name it uses. */
248
259
  export declare const CLAUDE_RUNNER_SCRIPT = "/usr/local/bin/outpost-runner.sh";
249
260
  export declare const NOT_SIGNED_IN = "not signed in (run `hq login`)";
261
+ /** True only when an engine unit's one remaining block is an old runner that has to restart. */
262
+ export declare function isLegacyRestartWait(block: UnitPlan["blocked"]): boolean;
250
263
  export declare function daemonAloneRunsLegacySync(ctx: PlanContext): boolean;
251
264
  /** Turn enabled services into concrete units for this host. */
252
265
  export declare function planUnits(services: readonly ServiceName[], ctx: PlanContext): UnitPlan[];