@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
@@ -0,0 +1,304 @@
1
+ /**
2
+ * hq work-env: a thin launcher for the company-scoped work-env skill script
3
+ * at companies/<company>/skills/work-env/scripts/work-env.sh.
4
+ *
5
+ * The script owns every security rule (company lock, per-run key, teardown,
6
+ * leak scan). This command finds the script and runs it with `bash` from PATH
7
+ * (the script needs bash 4+), passing argv exactly as given, with no shell.
8
+ *
9
+ * Before choosing a script it checks the company against the session's locked
10
+ * company set, the same set the script checks, so no company's script runs
11
+ * from a session that is not locked to that company.
12
+ *
13
+ * Signals: the child shares the terminal's foreground process group, so a
14
+ * terminal Ctrl-C (SIGINT) or Ctrl-\ (SIGQUIT) already reaches it. The wrapper
15
+ * ignores those and does not forward them; forwarding would deliver a second
16
+ * signal that can cut the script's teardown short. SIGTERM and SIGHUP, which
17
+ * the terminal does not send to the child, are forwarded once each. The
18
+ * wrapper always waits for the child to exit and returns its exit code.
19
+ *
20
+ * Environment: nothing is added. WORK_ENV_* test seams are removed, and so
21
+ * are BASH_ENV, ENV and exported bash functions (BASH_FUNC_*), which bash
22
+ * would otherwise run before the script's first line.
23
+ */
24
+ import { spawn as nodeSpawn } from "node:child_process";
25
+ import * as fs from "node:fs";
26
+ import os from "node:os";
27
+ import path from "node:path";
28
+ import { readSessionCompanyLock } from "../lib/session-company-lock.js";
29
+ import { resolveDefaultHqRoot } from "../utils/hq-root-resolver.js";
30
+ import { STILL_USE_FLAG } from "../utils/command-usage.js";
31
+ export const WORK_ENV_COMMAND = "work-env";
32
+ export const WORK_ENV_SCRIPT_RELATIVE = path.join("skills", "work-env", "scripts", "work-env.sh");
33
+ /** The script's own slug rule (check_company in work-env.sh). */
34
+ const COMPANY_SLUG = /^[a-z0-9][a-z0-9-]*$/;
35
+ /** Signals the terminal already delivers to the child's process group. */
36
+ const TERMINAL_SIGNALS = ["SIGINT", "SIGQUIT"];
37
+ /** Signals only the wrapper receives; forwarded to the child once each. */
38
+ const FORWARDED_SIGNALS = ["SIGTERM", "SIGHUP"];
39
+ function realpathOrUndefined(target) {
40
+ try {
41
+ return fs.realpathSync(target);
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ }
47
+ /**
48
+ * The script path for `company` under `hqRoot`, and whether it is installed.
49
+ * The script must be a regular file reached without symlinks below the HQ
50
+ * root, because the script derives its HQ root from its own resolved path.
51
+ */
52
+ export function resolveWorkEnvScript(hqRoot, company) {
53
+ const scriptPath = path.join(hqRoot, "companies", company, WORK_ENV_SCRIPT_RELATIVE);
54
+ let isFile;
55
+ try {
56
+ isFile = fs.statSync(scriptPath).isFile();
57
+ }
58
+ catch {
59
+ isFile = false;
60
+ }
61
+ if (!isFile) {
62
+ return {
63
+ ok: false,
64
+ path: scriptPath,
65
+ message: `The work-env skill is not installed for company '${company}'. Expected ${scriptPath}.`,
66
+ };
67
+ }
68
+ const realRoot = realpathOrUndefined(hqRoot);
69
+ const realScript = realpathOrUndefined(scriptPath);
70
+ if (!realRoot || realScript !== path.join(realRoot, "companies", company, WORK_ENV_SCRIPT_RELATIVE)) {
71
+ return {
72
+ ok: false,
73
+ path: scriptPath,
74
+ message: `The work-env script for company '${company}' resolves outside companies/${company}/ (a symlink). Refusing to run it.`,
75
+ };
76
+ }
77
+ return { ok: true, path: scriptPath };
78
+ }
79
+ /**
80
+ * The company named on the command line. Only tokens before the first `--`
81
+ * count (after it is the user's own command), and the last `--company` wins,
82
+ * as in the script's own option loop. `--company=<slug>` is reported so the
83
+ * caller can refuse it: the script does not accept that spelling.
84
+ */
85
+ export function workEnvCompanyFromArgs(args) {
86
+ let company;
87
+ let equalsForm = false;
88
+ for (let index = 0; index < args.length; index += 1) {
89
+ const token = args[index];
90
+ if (token === "--")
91
+ break;
92
+ if (token === "--company") {
93
+ company = args[index + 1] ?? "";
94
+ index += 1;
95
+ }
96
+ else if (token.startsWith("--company=")) {
97
+ equalsForm = true;
98
+ }
99
+ }
100
+ return { company, equalsForm };
101
+ }
102
+ /**
103
+ * The parent environment minus WORK_ENV_* test seams, BASH_ENV, ENV and
104
+ * exported bash functions. Nothing is added.
105
+ */
106
+ export function workEnvChildEnv(env, { allowTestSeams = false } = {}) {
107
+ const child = {};
108
+ for (const [key, value] of Object.entries(env)) {
109
+ if (!allowTestSeams && key.startsWith("WORK_ENV_"))
110
+ continue;
111
+ if (key === "BASH_ENV" || key === "ENV" || key.startsWith("BASH_FUNC_"))
112
+ continue;
113
+ child[key] = value;
114
+ }
115
+ return child;
116
+ }
117
+ function exitCodeFor(code, signal) {
118
+ if (typeof code === "number")
119
+ return code;
120
+ if (signal) {
121
+ const number = os.constants.signals[signal];
122
+ if (typeof number === "number")
123
+ return 128 + number;
124
+ }
125
+ return 1;
126
+ }
127
+ /** Find the script, check the lock, run it, and resolve with the exit code to use. */
128
+ export async function runWorkEnv(args, deps = {}) {
129
+ const env = deps.env ?? process.env;
130
+ const writeError = deps.writeError ?? ((text) => process.stderr.write(text));
131
+ const refuse = (message, code = 2) => {
132
+ writeError(`hq work-env: ${message}\n`);
133
+ return code;
134
+ };
135
+ let hqRoot;
136
+ try {
137
+ hqRoot = resolveDefaultHqRoot({ env, cwd: deps.cwd, onMissing: "throw" });
138
+ }
139
+ catch (error) {
140
+ return refuse(error instanceof Error ? error.message : String(error));
141
+ }
142
+ const named = workEnvCompanyFromArgs(args);
143
+ if (named.equalsForm) {
144
+ return refuse("pass the company as two arguments, --company <slug>; the work-env script does not accept --company=<slug>.");
145
+ }
146
+ let locked;
147
+ try {
148
+ locked = readSessionCompanyLock({ ...env, HQ_ROOT: hqRoot })?.companies ?? [];
149
+ }
150
+ catch (error) {
151
+ return refuse(error instanceof Error ? error.message : String(error));
152
+ }
153
+ const company = named.company ?? locked[0];
154
+ if (!company) {
155
+ return refuse("no active company. Run it from an HQ session locked to the company (core/scripts/hq-session.sh add company <slug>), and pass --company <slug> to start.");
156
+ }
157
+ if (!COMPANY_SLUG.test(company))
158
+ return refuse(`'${company}' is not a valid company slug.`);
159
+ if (company === "personal")
160
+ return refuse("personal is not a company.");
161
+ if (!locked.includes(company)) {
162
+ return refuse(`company '${company}' is not in this session's locked company set (${locked.join(",") || "none"}). ` +
163
+ `Add it with core/scripts/hq-session.sh add company ${company} if this is intended.`);
164
+ }
165
+ const script = resolveWorkEnvScript(hqRoot, company);
166
+ if (!script.ok)
167
+ return refuse(script.message, 1);
168
+ const spawn = deps.spawn ?? ((file, spawnArgs, options) => nodeSpawn(file, [...spawnArgs], options));
169
+ const signals = deps.signals ?? process;
170
+ const onSpawn = deps.onSpawn ?? releaseLeaseAfterStart;
171
+ return new Promise((resolve) => {
172
+ let child;
173
+ const listeners = new Map();
174
+ const cleanup = () => {
175
+ for (const [signal, listener] of listeners)
176
+ signals.removeListener(signal, listener);
177
+ listeners.clear();
178
+ };
179
+ try {
180
+ child = spawn("bash", [script.path, ...args], {
181
+ stdio: "inherit",
182
+ env: workEnvChildEnv(env, { allowTestSeams: deps.allowTestSeams === true }),
183
+ shell: false,
184
+ });
185
+ }
186
+ catch (error) {
187
+ resolve(refuse(`could not start bash: ${error instanceof Error ? error.message : String(error)}`, 1));
188
+ return;
189
+ }
190
+ for (const signal of TERMINAL_SIGNALS) {
191
+ // Listening keeps Node from exiting on the signal. The child got its
192
+ // own copy from the terminal; keep waiting for it to finish teardown.
193
+ const listener = () => { };
194
+ listeners.set(signal, listener);
195
+ signals.on(signal, listener);
196
+ }
197
+ const forwarded = new Set();
198
+ for (const signal of FORWARDED_SIGNALS) {
199
+ const listener = () => {
200
+ if (forwarded.has(signal))
201
+ return;
202
+ forwarded.add(signal);
203
+ try {
204
+ child.kill(signal);
205
+ }
206
+ catch {
207
+ // The child already exited; its close event settles the run.
208
+ }
209
+ };
210
+ listeners.set(signal, listener);
211
+ signals.on(signal, listener);
212
+ }
213
+ child.once("spawn", () => onSpawn());
214
+ child.once("error", (error) => {
215
+ cleanup();
216
+ resolve(refuse(`could not start bash: ${error.message}`, 1));
217
+ });
218
+ child.once("close", (code, signal) => {
219
+ cleanup();
220
+ resolve(exitCodeFor(code, signal));
221
+ });
222
+ });
223
+ }
224
+ function releaseLeaseAfterStart() {
225
+ // The script calls hq itself; each nested hq takes its own lease, so this
226
+ // wrapper does not hold one for the whole run (a run can outlast the lease's
227
+ // maximum hold and would block CLI updates for hours).
228
+ void import("../utils/child-wrapper-lease.js").then(({ releaseChildWrapperPackageUseLeaseAfterStart }) => releaseChildWrapperPackageUseLeaseAfterStart("childWrapper"));
229
+ }
230
+ /**
231
+ * The tokens after `work-env` exactly as typed. Commander can take a root
232
+ * option (`--verbose`) out of a child's arguments and drops a `--` that
233
+ * follows a plain argument, so the action reads the root's raw argv instead.
234
+ * Returns undefined when the raw argv does not line up; the caller refuses
235
+ * rather than fall back to Commander's parsed (lossy) arguments.
236
+ */
237
+ export function rawWorkEnvArgs(rawArgs) {
238
+ if (!rawArgs)
239
+ return undefined;
240
+ let index = 2;
241
+ while (rawArgs[index] === "--verbose" || rawArgs[index] === STILL_USE_FLAG)
242
+ index += 1;
243
+ if (rawArgs[index] !== WORK_ENV_COMMAND)
244
+ return undefined;
245
+ return rawArgs.slice(index + 1);
246
+ }
247
+ const HELP_AFTER = `
248
+ Subcommands (handled by the company's work-env.sh):
249
+ start --company <slug> --secrets NAME1,NAME2 --workdir <abs path> --hours <n>
250
+ [--cpus 2] [--memory 4] [--backend local|microvm] -- <command...>
251
+ status <id>
252
+ logs <id>
253
+ stop <id>
254
+ build [--context <agent-image dir>]
255
+
256
+ Runs only in an HQ session locked to the company. The company is --company
257
+ (start) or, for the other subcommands, the session's primary company. It must
258
+ be in the session's locked company set; it selects
259
+ companies/<company>/skills/work-env/scripts/work-env.sh under the HQ root.
260
+ Every argument reaches the script unchanged, and the script enforces the lock
261
+ again, mints and revokes the per-run key, and runs teardown and the leak scan.
262
+
263
+ Runs the script with bash from PATH and no shell. A terminal Ctrl-C reaches
264
+ the script directly; SIGTERM and SIGHUP sent to hq are forwarded once. hq
265
+ waits for teardown and exits with the script's exit code (2 refused, 3
266
+ teardown failed, 4 key mint failed, 5 docker run failed, 124 timeout, 130/143
267
+ interrupted).
268
+
269
+ Examples:
270
+ hq work-env start --company indigo --secrets NPM_TOKEN --workdir "$PWD" --hours 1 -- pnpm test
271
+ hq work-env status we-20261118t210000z-a1b2c3
272
+ hq work-env stop we-20261118t210000z-a1b2c3
273
+ `;
274
+ export function registerWorkEnvCommand(program, deps = {}) {
275
+ return program
276
+ .command(WORK_ENV_COMMAND)
277
+ .description("Start, inspect and stop a company-scoped work environment (runs the work-env skill script)")
278
+ .usage("<start|status|logs|stop|build> [args...]")
279
+ .helpOption(false)
280
+ .allowUnknownOption()
281
+ .allowExcessArguments()
282
+ .argument("[args...]", "Arguments passed unchanged to work-env.sh")
283
+ .addHelpText("after", HELP_AFTER)
284
+ .action(async (_parsedArgs, _options, command) => {
285
+ const exit = deps.exit ?? ((code) => process.exit(code));
286
+ let root = command;
287
+ while (root.parent)
288
+ root = root.parent;
289
+ const args = rawWorkEnvArgs(root.rawArgs);
290
+ if (!args) {
291
+ (deps.writeError ?? ((text) => process.stderr.write(text)))("hq work-env: could not read the command line exactly as typed; nothing was run.\n");
292
+ exit(2);
293
+ return;
294
+ }
295
+ const first = args[0];
296
+ if (first === undefined || first === "--help" || first === "-h" || first === "help") {
297
+ command.outputHelp();
298
+ exit(0);
299
+ return;
300
+ }
301
+ exit(await runWorkEnv(args, deps));
302
+ });
303
+ }
304
+ //# sourceMappingURL=work-env.js.map
@@ -5,7 +5,7 @@ import { COMMAND_CATALOG } from "./command-catalog.generated.js";
5
5
  import { installUnknownCommandSuggestions } from "./unknown-command.js";
6
6
  import { restoreRuntimeText } from "./utils/catalog-runtime-paths.js";
7
7
  import { STILL_USE_FLAG } from "./utils/command-usage.js";
8
- import { isHqRoot } from "./utils/hq-roots-core.js";
8
+ import { findHqRootAncestor, isHqRoot } from "./utils/hq-roots-core.js";
9
9
  import { MissingRegistrationPlanError } from "./utils/registration-plan-error.js";
10
10
  const commandCatalog = COMMAND_CATALOG;
11
11
  /**
@@ -92,15 +92,7 @@ function runtimeHqRoot() {
92
92
  return findRuntimeHqRoot(resolve(process.cwd()));
93
93
  }
94
94
  export function findRuntimeHqRoot(start, parentOf = dirname, isRoot = isHqRoot) {
95
- let directory = start;
96
- for (;;) {
97
- if (isRoot(directory))
98
- return directory;
99
- const parent = parentOf(directory);
100
- if (parent === directory)
101
- return start;
102
- directory = parent;
103
- }
95
+ return findHqRootAncestor(start, isRoot, parentOf) ?? start;
104
96
  }
105
97
  /**
106
98
  * Register only generated root metadata. This is enough for root help and
@@ -125,6 +125,9 @@ export interface AgentRecord {
125
125
  };
126
126
  /** "assistant" on HQ's setup assistant, null on other local bots; absent on older servers. */
127
127
  agentRole?: string | null;
128
+ /** Cloud agents: "archived" once `hq agents rm` has torn the agent down. */
129
+ entityStatus?: string;
130
+ agentStatus?: string;
128
131
  }
129
132
  /**
130
133
  * One of the caller's own local bots, as `GET /v1/agents/mine?local=1` lists
@@ -173,6 +176,14 @@ export interface BotApiOptions {
173
176
  baseUrl?: string;
174
177
  fetchImpl?: typeof vaultApiFetch;
175
178
  }
179
+ /** The promotion protocol this client speaks; HQ refuses new moves from older ones. */
180
+ export declare const PROMOTION_CLIENT_VERSION = 2;
181
+ /** The local bot's model brain, sent at prepare so HQ can refuse what cloud bots cannot run. */
182
+ export interface BotPromotionBrain {
183
+ runtime: "codex" | "claude" | "grok";
184
+ model?: string;
185
+ effort?: string;
186
+ }
176
187
  export interface BotPromotionState {
177
188
  version: number;
178
189
  operationId: string;
@@ -181,6 +192,8 @@ export interface BotPromotionState {
181
192
  companyUid: string;
182
193
  snapshotSha256: string;
183
194
  phase: "preparing" | "local-stopped" | "imported" | "cloud-ready" | "active" | "cancelled";
195
+ /** True on a status read while a cancel is in progress. */
196
+ cancelRequested?: boolean;
184
197
  updatedAt: string;
185
198
  }
186
199
  export interface BotPromotionUpload {
@@ -311,16 +324,19 @@ export declare class BotApi {
311
324
  companyUid: string;
312
325
  operationId: string;
313
326
  snapshotSha256: string;
327
+ brain: BotPromotionBrain;
314
328
  }): Promise<BotPromotionState>;
315
329
  promotionDetails(agentUid: string, companyUid: string): Promise<{
316
330
  promotion: BotPromotionState | null;
317
331
  failure?: string;
332
+ failureCode?: string;
318
333
  pairing: {
319
334
  url: string;
320
335
  code: string;
321
336
  capturedAt?: string;
322
337
  } | null;
323
338
  }>;
339
+ /** Null only for an explicit `promotion: null`; any other body that is not a promotion throws. */
324
340
  promotionStatus(agentUid: string, companyUid: string): Promise<BotPromotionState | null>;
325
341
  resumePromotion(agentUid: string, input: {
326
342
  companyUid: string;
@@ -329,6 +345,17 @@ export declare class BotApi {
329
345
  promotion: BotPromotionState;
330
346
  pending: boolean;
331
347
  }>;
348
+ /** 200 once cancelled (idempotent); 202 while the cloud box is still shutting down or a cancel is in progress.
349
+ * `identityRestored: false` on a 200 means the bot's own sign-in could not be put back yet.
350
+ */
351
+ cancelPromotion(agentUid: string, input: {
352
+ companyUid: string;
353
+ operationId: string;
354
+ }): Promise<{
355
+ promotion: BotPromotionState | null;
356
+ pending: boolean;
357
+ identityRestored?: boolean;
358
+ }>;
332
359
  confirmPromotionStopped(agentUid: string, input: {
333
360
  companyUid: string;
334
361
  operationId: string;
@@ -67,6 +67,8 @@ async function readError(res) {
67
67
  return {};
68
68
  }
69
69
  }
70
+ /** The promotion protocol this client speaks; HQ refuses new moves from older ones. */
71
+ export const PROMOTION_CLIENT_VERSION = 2;
70
72
  export class BotApi {
71
73
  opts;
72
74
  fetchImpl;
@@ -281,14 +283,38 @@ export class BotApi {
281
283
  return (await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote/prepare`, { method: "POST", body: input })).body.promotion;
282
284
  }
283
285
  async promotionDetails(agentUid, companyUid) {
284
- return (await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote?companyUid=${encodeURIComponent(companyUid)}`, { method: "GET" })).body;
286
+ return (await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote?companyUid=${encodeURIComponent(companyUid)}&clientVersion=${PROMOTION_CLIENT_VERSION}`, { method: "GET" })).body;
285
287
  }
288
+ /** Null only for an explicit `promotion: null`; any other body that is not a promotion throws. */
286
289
  async promotionStatus(agentUid, companyUid) {
287
- return (await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote?companyUid=${encodeURIComponent(companyUid)}`, { method: "GET" })).body.promotion;
290
+ const body = (await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote?companyUid=${encodeURIComponent(companyUid)}&clientVersion=${PROMOTION_CLIENT_VERSION}`, { method: "GET" })).body;
291
+ if (body && typeof body === "object" && "promotion" in body) {
292
+ const promotion = body.promotion;
293
+ if (promotion === null)
294
+ return null;
295
+ if (promotion && typeof promotion === "object") {
296
+ const state = promotion;
297
+ if (typeof state.operationId === "string" && typeof state.phase === "string" && typeof state.agentUid === "string")
298
+ return promotion;
299
+ }
300
+ }
301
+ throw new Error("HQ answered the promotion status without a readable promotion. Nothing was changed; try again.");
288
302
  }
289
303
  async resumePromotion(agentUid, input) {
290
304
  return (await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote/resume`, { method: "POST", body: input })).body;
291
305
  }
306
+ /** 200 once cancelled (idempotent); 202 while the cloud box is still shutting down or a cancel is in progress.
307
+ * `identityRestored: false` on a 200 means the bot's own sign-in could not be put back yet.
308
+ */
309
+ async cancelPromotion(agentUid, input) {
310
+ const res = await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote/cancel`, { method: "POST", body: input }, [200, 202]);
311
+ const body = res.body && typeof res.body === "object" ? res.body : {};
312
+ return {
313
+ promotion: body.promotion && typeof body.promotion === "object" ? body.promotion : null,
314
+ pending: res.status === 202 || body.pending === true,
315
+ ...(typeof body.identityRestored === "boolean" ? { identityRestored: body.identityRestored } : {}),
316
+ };
317
+ }
292
318
  async confirmPromotionStopped(agentUid, input) {
293
319
  return (await this.call(`/v1/agents/${encodeURIComponent(agentUid)}/promote/local-stopped`, { method: "POST", body: input })).body.promotion;
294
320
  }
@@ -0,0 +1,46 @@
1
+ export interface CloudCreateOptions {
2
+ legacyRuntime?: boolean;
3
+ kind?: string;
4
+ company?: string[];
5
+ runtime?: string;
6
+ provider?: string;
7
+ model?: string;
8
+ autoApprove?: boolean;
9
+ worker?: string;
10
+ displayName?: string;
11
+ intro?: string;
12
+ kickoff?: string;
13
+ memory?: string;
14
+ start?: boolean;
15
+ readyTimeout?: string;
16
+ json?: boolean;
17
+ }
18
+ export interface CloudOutpost {
19
+ outpostId: string;
20
+ state: string;
21
+ createdAt?: string;
22
+ }
23
+ export interface CloudExecResult {
24
+ status: string;
25
+ done: boolean;
26
+ exitCode?: number | null;
27
+ stdout?: string;
28
+ stderr?: string;
29
+ truncated?: boolean;
30
+ }
31
+ export interface CloudCreateDeps {
32
+ list: () => Promise<CloudOutpost[]>;
33
+ submitExec: (command: string, outpostId: string, timeoutSeconds: number) => Promise<{
34
+ commandId: string;
35
+ }>;
36
+ waitForExecResult: (commandId: string, outpostId: string, maxWaitMs: number) => Promise<CloudExecResult>;
37
+ print: (line: string) => void;
38
+ }
39
+ export declare const CLOUD_CREATE_SETUP_SECONDS = 900;
40
+ export declare function assertCloudCreateOptions(opts: CloudCreateOptions, name?: string): void;
41
+ export declare function cloudCreateRemoteArgs(name: string, opts: CloudCreateOptions): string[];
42
+ export declare function cloudCreateRemoteCommand(name: string, opts: CloudCreateOptions): string;
43
+ export declare function pickPersonalOutpost(outposts: readonly CloudOutpost[]): CloudOutpost;
44
+ export declare function parseRemoteCreateResult(stdout: string): Record<string, unknown> | null;
45
+ export declare function runBotCreateOnOutpost(name: string, opts: CloudCreateOptions, deps: CloudCreateDeps): Promise<void>;
46
+ //# sourceMappingURL=cloud-create.d.ts.map
@@ -0,0 +1,128 @@
1
+ import { withRemoteHqDir } from "@indigoai-us/hq-cloud/outposts";
2
+ import { DEFAULT_BOT_READY_TIMEOUT_SECONDS } from "./readiness.js";
3
+ export const CLOUD_CREATE_SETUP_SECONDS = 900;
4
+ const GONE_STATES = new Set(["destroyed", "destroying"]);
5
+ const RESERVED_ASSISTANT_NAME = "setup";
6
+ function expected(message) {
7
+ return Object.assign(new Error(message), { expected: true });
8
+ }
9
+ function shellQuote(value) {
10
+ return `'${value.replace(/'/g, `'\\''`)}'`;
11
+ }
12
+ export function assertCloudCreateOptions(opts, name) {
13
+ if (name === RESERVED_ASSISTANT_NAME) {
14
+ throw expected(`The name ${RESERVED_ASSISTANT_NAME} is reserved for HQ's assistant on your own computer. Choose another name for a cloud bot.`);
15
+ }
16
+ const kind = opts.kind?.trim().toLowerCase();
17
+ if ((kind !== undefined && kind !== "" && kind !== "personal") || (opts.company?.length ?? 0) > 0) {
18
+ throw expected("--cloud creates a personal bot that acts as you in every company you belong to. Drop --kind company and --company; to move a company bot to the cloud use hq bot promote <name>.");
19
+ }
20
+ if (opts.memory !== undefined && opts.memory !== "synced") {
21
+ throw expected("--cloud keeps the bot's memory in your HQ so you can read it from any computer. Drop --memory, or use --memory synced.");
22
+ }
23
+ if (opts.legacyRuntime === true) {
24
+ throw expected("--legacy-runtime is no longer supported: new bots run on the HQ Fleet Runtime. Drop --legacy-runtime.");
25
+ }
26
+ }
27
+ export function cloudCreateRemoteArgs(name, opts) {
28
+ const args = ["bot", "create", name, "--kind", "personal", "--json"];
29
+ const valued = [
30
+ ["--runtime", opts.runtime],
31
+ ["--provider", opts.provider],
32
+ ["--model", opts.model],
33
+ ["--worker", opts.worker],
34
+ ["--display-name", opts.displayName],
35
+ ["--intro", opts.intro],
36
+ ["--kickoff", opts.kickoff],
37
+ ["--ready-timeout", opts.readyTimeout],
38
+ ];
39
+ for (const [flag, value] of valued)
40
+ if (value !== undefined)
41
+ args.push(`${flag}=${value}`);
42
+ if (opts.autoApprove === true)
43
+ args.push("--auto-approve");
44
+ if (opts.start === false)
45
+ args.push("--no-start");
46
+ return args;
47
+ }
48
+ export function cloudCreateRemoteCommand(name, opts) {
49
+ const inner = ["hq", ...cloudCreateRemoteArgs(name, opts)].map(shellQuote).join(" ");
50
+ return withRemoteHqDir(`bash -lc ${shellQuote(inner)}`);
51
+ }
52
+ export function pickPersonalOutpost(outposts) {
53
+ const live = outposts
54
+ .filter((outpost) => !GONE_STATES.has(outpost.state))
55
+ .sort((a, b) => (a.createdAt ?? "").localeCompare(b.createdAt ?? ""));
56
+ const ready = live.find((outpost) => outpost.state === "ready");
57
+ if (ready)
58
+ return ready;
59
+ if (live.length === 0) {
60
+ throw expected("A cloud bot runs on your personal Outpost, and you do not have one yet. Create it with: hq outposts create --personal (it shows the monthly price first). Then run this command again.");
61
+ }
62
+ throw expected(`Your personal Outpost is not ready yet (${live[0].state}). Check it with hq outposts status, then run this command again.`);
63
+ }
64
+ export function parseRemoteCreateResult(stdout) {
65
+ const lines = stdout.trim().split("\n");
66
+ for (let i = lines.length - 1; i >= 0; i--) {
67
+ if (!lines[i].startsWith("{"))
68
+ continue;
69
+ try {
70
+ const parsed = JSON.parse(lines.slice(i).join("\n"));
71
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
72
+ return parsed;
73
+ }
74
+ catch {
75
+ continue;
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+ function readySeconds(value) {
81
+ if (value === undefined)
82
+ return DEFAULT_BOT_READY_TIMEOUT_SECONDS;
83
+ const seconds = Number(value.trim());
84
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) {
85
+ throw expected("--ready-timeout must be a whole number of seconds from 1 to 3600.");
86
+ }
87
+ return seconds;
88
+ }
89
+ export async function runBotCreateOnOutpost(name, opts, deps) {
90
+ assertCloudCreateOptions(opts, name);
91
+ const budgetSeconds = CLOUD_CREATE_SETUP_SECONDS + readySeconds(opts.readyTimeout);
92
+ const outpost = pickPersonalOutpost(await deps.list());
93
+ if (!opts.json)
94
+ deps.print(`Creating ${name} on your personal Outpost (${outpost.outpostId}). This can take a few minutes.`);
95
+ const { commandId } = await deps.submitExec(cloudCreateRemoteCommand(name, opts), outpost.outpostId, budgetSeconds);
96
+ const checkLater = `It may still finish on your Outpost. Check with: hq outposts exec --id ${outpost.outpostId} -- hq bot status ${name}`;
97
+ let result;
98
+ try {
99
+ result = await deps.waitForExecResult(commandId, outpost.outpostId, (budgetSeconds + 60) * 1000);
100
+ }
101
+ catch {
102
+ const message = `Stopped waiting for ${name} to be created. ${checkLater}`;
103
+ if (opts.json) {
104
+ deps.print(JSON.stringify({ ok: false, name, hosting: "cloud", outpostId: outpost.outpostId, commandId, reason: "cloud-create-pending", message }, null, 2));
105
+ }
106
+ throw Object.assign(expected(message), { jsonReported: opts.json === true });
107
+ }
108
+ const remote = parseRemoteCreateResult(result.stdout ?? "");
109
+ const ok = result.done && result.exitCode === 0 && remote?.ok === true;
110
+ if (!ok) {
111
+ const reason = (typeof remote?.message === "string" && remote.message) ||
112
+ (remote === null && result.done && result.exitCode === 0 && `the Outpost finished the command but its result could not be read. ${checkLater}`) ||
113
+ (result.stderr ?? "").trim().split("\n").filter(Boolean).pop() ||
114
+ `the Outpost command ended with status ${result.status}`;
115
+ if (opts.json) {
116
+ deps.print(JSON.stringify({ ok: false, name, hosting: "cloud", outpostId: outpost.outpostId, reason: "cloud-create-failed", message: reason }, null, 2));
117
+ }
118
+ throw Object.assign(expected(`Could not create ${name} on your Outpost: ${reason}`), { jsonReported: opts.json === true });
119
+ }
120
+ if (opts.json) {
121
+ deps.print(JSON.stringify({ ...remote, hosting: "cloud", outpostId: outpost.outpostId }, null, 2));
122
+ return;
123
+ }
124
+ const agentUid = typeof remote.agentUid === "string" ? ` (${remote.agentUid})` : "";
125
+ deps.print(`Created cloud bot ${name}${agentUid}. It runs on your Outpost and acts as you in every company you belong to.`);
126
+ deps.print(remote.running === true ? `${name} is running. Message it from HQ.` : `${name} is set up but has not reported running yet. Check it with: hq outposts exec --id ${outpost.outpostId} -- hq bot status ${name}`);
127
+ }
128
+ //# sourceMappingURL=cloud-create.js.map
@@ -19,6 +19,7 @@ import { HQ_FLEET_RUNTIME_ENGINE_ID, patchBotConfig, readBotConfig } from "./con
19
19
  import { defaultPathEntries } from "./daemon.js";
20
20
  import { clearStaleFleetGatewayReady, controlFleetLocalBot, fleetLocalGatewayPid, fleetLocalGatewayProcess, fleetLocalLaunchAgentLabel, fleetLocalLaunchAgentPlist, removeFleetLocalEmbeddedRuntime, } from "./fleet-local.js";
21
21
  import { botsRoot } from "./paths.js";
22
+ import { localPromotionState } from "./promotion-receipt.js";
22
23
  import { isPidAlive } from "./status.js";
23
24
  import { askDaemonToStart, askDaemonToStop, daemonUnitInstalled, hostedDaemonRunning } from "../daemon/handoff.js";
24
25
  import { daemonPaths } from "../daemon/paths.js";
@@ -211,7 +212,8 @@ export function planFleetBots(deps = {}) {
211
212
  const platform = deps.platform ?? process.platform;
212
213
  const home = deps.home ?? os.homedir();
213
214
  const env = deps.env ?? process.env;
214
- return listFleetBots(deps.root ?? botsRoot(home, env)).map(({ name, config }) => {
215
+ return listFleetBots(deps.root ?? botsRoot(home, env)).map(({ name, dir, config }) => {
216
+ const promotion = localPromotionState(dir, config.agentUid, config.ownerUid);
215
217
  let legacyAgent;
216
218
  let outsideGateway;
217
219
  if (platform === "darwin") {
@@ -246,6 +248,7 @@ export function planFleetBots(deps = {}) {
246
248
  gateway,
247
249
  authPending: config.fleetAuthPending === true,
248
250
  installPending: config.fleetServiceInstallPending === true,
251
+ ...(promotion ? { promotion } : {}),
249
252
  ...(legacyAgent ? { legacyAgent } : {}),
250
253
  ...(outsideGateway !== undefined ? { outsideGateway } : {}),
251
254
  };
@@ -365,6 +365,13 @@ export declare function fleetLocalProfileNeedsAdoption(agentUid: string, deps?:
365
365
  export declare function controlFleetLocalBot(agentUid: string, action: FleetLocalServiceAction, deps?: FleetLocalControlDeps): Record<string, unknown>;
366
366
  export declare function exportFleetLocalMachineCredential(agentUid: string, deps?: FleetLocalControlDeps): BotMachineCreds;
367
367
  export declare function fleetLocalPromotionRuntime(agentUid: string, deps?: FleetLocalControlDeps): LocalBotPromotionRuntime;
368
+ /** The model provider the bot's HQ Fleet profile names, or null when it cannot be read. */
369
+ export declare function fleetLocalProfileProvider(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): Partial<FleetLocalProfile["provider"]> | null;
370
+ /**
371
+ * The model brain a Fleet profile provider runs, or null when it names none
372
+ * this hq knows. Any Anthropic sign of the provider means Claude.
373
+ */
374
+ export declare function fleetProviderBrainRuntime(provider: Partial<FleetLocalProfile["provider"]>): BotRuntimeId | null;
368
375
  export declare function removeFleetLocalBot(agentUid: string, deps?: FleetLocalControlDeps): FleetLocalRemovalResult;
369
376
  export type FleetLocalStartControl = (agentUid: string, action: "install" | "restart") => {
370
377
  ok?: unknown;