@indigoai-us/hq-cli 5.345.211 → 5.345.212

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 (90) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/command-catalog.generated.d.ts +28 -0
  3. package/dist/command-catalog.generated.js +34 -0
  4. package/dist/command-registration-plan.d.ts +15 -0
  5. package/dist/command-registration-plan.js +20 -1
  6. package/dist/commands/agents.js +6 -1
  7. package/dist/commands/billing.js +17 -4
  8. package/dist/commands/bot-runtime.d.ts +21 -2
  9. package/dist/commands/bot-runtime.js +54 -9
  10. package/dist/commands/bot.d.ts +13 -0
  11. package/dist/commands/bot.js +142 -12
  12. package/dist/commands/daemon.js +60 -5
  13. package/dist/commands/files.js +2 -2
  14. package/dist/commands/integrations-api.d.ts +11 -0
  15. package/dist/commands/integrations-connect.d.ts +2 -0
  16. package/dist/commands/integrations-connect.js +17 -5
  17. package/dist/commands/integrations-core.d.ts +1 -1
  18. package/dist/commands/integrations-core.js +18 -10
  19. package/dist/commands/integrations.js +1 -1
  20. package/dist/commands/lanes.js +34 -16
  21. package/dist/commands/whoami.js +7 -6
  22. package/dist/lazy-commands.js +4 -1
  23. package/dist/lib/billing/usage-only.d.ts +4 -1
  24. package/dist/lib/billing/usage-only.js +7 -2
  25. package/dist/lib/bot/api.d.ts +1 -1
  26. package/dist/lib/bot/config.js +2 -1
  27. package/dist/lib/bot/fleet-daemon.d.ts +4 -0
  28. package/dist/lib/bot/fleet-daemon.js +12 -1
  29. package/dist/lib/bot/fleet-download.d.ts +6 -0
  30. package/dist/lib/bot/fleet-download.js +128 -3
  31. package/dist/lib/bot/fleet-local.d.ts +38 -1
  32. package/dist/lib/bot/fleet-local.js +239 -26
  33. package/dist/lib/bot/install-progress.d.ts +28 -0
  34. package/dist/lib/bot/install-progress.js +185 -0
  35. package/dist/lib/bot/legacy-provider-login.d.ts +22 -1
  36. package/dist/lib/bot/legacy-provider-login.js +67 -9
  37. package/dist/lib/bot/prompt.d.ts +1 -0
  38. package/dist/lib/bot/prompt.js +3 -2
  39. package/dist/lib/bot/readiness.d.ts +68 -0
  40. package/dist/lib/bot/readiness.js +145 -0
  41. package/dist/lib/bot/run.d.ts +2 -0
  42. package/dist/lib/bot/run.js +6 -3
  43. package/dist/lib/bot/scaffold.d.ts +6 -3
  44. package/dist/lib/bot/scaffold.js +18 -12
  45. package/dist/lib/capacity/ledger.d.ts +7 -0
  46. package/dist/lib/capacity/ledger.js +31 -1
  47. package/dist/lib/capacity/project.d.ts +1 -1
  48. package/dist/lib/capacity/project.js +13 -4
  49. package/dist/lib/capacity/route.d.ts +10 -0
  50. package/dist/lib/capacity/route.js +16 -0
  51. package/dist/lib/daemon/install.d.ts +15 -0
  52. package/dist/lib/daemon/install.js +31 -0
  53. package/dist/lib/daemon/migrate.js +29 -4
  54. package/dist/lib/daemon/run.d.ts +1 -0
  55. package/dist/lib/daemon/run.js +6 -1
  56. package/dist/lib/daemon/supervisor.d.ts +1 -0
  57. package/dist/lib/daemon/supervisor.js +5 -3
  58. package/dist/lib/doctor/__testing__/run-doctor.js +4 -0
  59. package/dist/lib/doctor/checks/jq.d.ts +27 -0
  60. package/dist/lib/doctor/checks/jq.js +82 -0
  61. package/dist/lib/doctor/registry.js +4 -0
  62. package/dist/lib/flag-snapshot-file.js +36 -8
  63. package/dist/lib/install/codex-targets.d.ts +52 -1
  64. package/dist/lib/install/codex-targets.js +77 -2
  65. package/dist/lib/lanes/monitor.d.ts +4 -1
  66. package/dist/lib/lanes/monitor.js +47 -10
  67. package/dist/lib/lanes/spawn.js +8 -1
  68. package/dist/lib/lanes/watch.js +31 -0
  69. package/dist/lib/onboarding/checkpoint.d.ts +6 -0
  70. package/dist/lib/onboarding/checkpoint.js +6 -0
  71. package/dist/lib/onboarding/orchestrator.d.ts +3 -1
  72. package/dist/lib/onboarding/orchestrator.js +62 -9
  73. package/dist/lib/onboarding/types.d.ts +8 -0
  74. package/dist/lib/work-context/organize.d.ts +23 -1
  75. package/dist/lib/work-context/organize.js +25 -3
  76. package/dist/lib/work-context/reconcile.js +3 -2
  77. package/dist/secrets-env-action.js +7 -5
  78. package/dist/startup-registration.js +7 -2
  79. package/dist/utils/billing-gate.d.ts +12 -16
  80. package/dist/utils/billing-gate.js +17 -18
  81. package/dist/utils/install-tree-torn.d.ts +22 -4
  82. package/dist/utils/install-tree-torn.js +24 -0
  83. package/dist/utils/registration-plan-error.d.ts +22 -0
  84. package/dist/utils/registration-plan-error.js +27 -0
  85. package/dist/utils/sentry-fingerprint.js +3 -0
  86. package/dist/utils/unauthorized-error.d.ts +36 -0
  87. package/dist/utils/unauthorized-error.js +105 -0
  88. package/dist/utils/vault-api.js +7 -5
  89. package/package.json +7 -7
  90. package/scripts/install-hook-engine.mjs +17 -0
@@ -13,7 +13,7 @@ import { delegatedMachineSessionFilePath, loadDelegatedMachineSession, getValidM
13
13
  import { DEFAULT_COGNITO, ensureCognitoIdToken } from "../utils/cognito-session.js";
14
14
  import chalk from "chalk";
15
15
  import { vaultApiFetch } from "../utils/vault-api.js";
16
- import { AuthError } from "../utils/auth-error.js";
16
+ import { unauthorizedError } from "../utils/unauthorized-error.js";
17
17
  import { planGateErrorFromPayload } from "../utils/plan-gate-error.js";
18
18
  import { redactErrorText } from "../utils/redact-error-text.js";
19
19
  import { redactSensitiveUrls, redactUrlsInText } from "../utils/redact-url.js";
@@ -286,16 +286,21 @@ function gatewayErrorDetails(error) {
286
286
  return { message, ...(rpcCode === undefined ? {} : { rpcCode }), shape };
287
287
  }
288
288
  // A 401 from ANY integration-gateway vault call means the caller's HQ session
289
- // is expired or missing — an expected auth state fixed by `hq login`, not an
290
- // hq-cli defect. Raise the same typed AuthError the vault company-resolution
291
- // paths use (HQ-CLI-8) so the top-level handler prints one actionable message
292
- // and skips Sentry, instead of surfacing the opaque, unactionable
289
+ // is expired, missing or rejected — an expected auth state, not an hq-cli
290
+ // defect. Raise the same typed AuthError the vault company-resolution paths
291
+ // use (HQ-CLI-8) so the top-level handler prints one actionable message and
292
+ // skips Sentry, instead of surfacing the opaque, unactionable
293
293
  // "Integration gateway request failed (HTTP 401)" that shipped as a fatal from
294
294
  // `callGateway` (HQ-CLI-9). Non-401 statuses keep their existing behavior:
295
295
  // other 4xx stay expected client errors, 5xx still report.
296
- export function raiseIfUnauthorized(res) {
296
+ //
297
+ // The message fits the caller (feedback_dfc0bb49): a person runs `hq login`,
298
+ // but a company Outpost job has no login to run, so it is told the server
299
+ // rejected the Outpost identity, with the server's code from `body` when the
300
+ // response carried one (OUTPOST_PRINCIPAL_INVALID), and the Outpost recovery.
301
+ export function raiseIfUnauthorized(res, body) {
297
302
  if (res.status === 401)
298
- throw new AuthError();
303
+ throw unauthorizedError({ body });
299
304
  }
300
305
  /**
301
306
  * A member connected, reinstalled, or signed in to an app that someone else
@@ -322,7 +327,10 @@ const CLI_ERROR_MESSAGES = new Map([
322
327
  * one route cannot quietly drift into reporting its 4xx as crashes.
323
328
  */
324
329
  export async function raiseForResponse(res, fallback) {
325
- raiseIfUnauthorized(res);
330
+ // Read the 401 body for its server code (feedback_dfc0bb49); no other
331
+ // status reads the body before the guards below.
332
+ if (res.status === 401)
333
+ raiseIfUnauthorized(res, await res.json().catch(() => undefined));
326
334
  raiseIfUpstreamUnavailable(res);
327
335
  const body = (await res.json().catch(() => ({})));
328
336
  // A plan-limit 402 is normally decoded by vaultApiFetch before it gets here.
@@ -704,7 +712,7 @@ export async function callGateway(token, params, idempotencyKey, method = "tools
704
712
  terminalStatus = terminal.status;
705
713
  }
706
714
  if (res.status !== 202 && (!res.ok || !terminalMessage)) {
707
- raiseIfUnauthorized(res);
715
+ raiseIfUnauthorized(res, message);
708
716
  if (method === "tools/call" &&
709
717
  params.acceptAsync === true &&
710
718
  isInlineTimeoutStatus(res.status)) {
@@ -787,7 +795,7 @@ async function pollAsyncGatewayJob(token, companyUid, jobId, idempotencyKey, dea
787
795
  clearTimeout(requestTimeout);
788
796
  }
789
797
  if (!res.ok) {
790
- raiseIfUnauthorized(res);
798
+ raiseIfUnauthorized(res, poll);
791
799
  raiseIfUpstreamUnavailable(res);
792
800
  if (res.status === 404) {
793
801
  throw new IntegrationsCliError(`Integration job ${jobId} was not found or is no longer available.`, { expected: true, status: 404 });
@@ -616,7 +616,7 @@ export function registerIntegrationsCommand(program) {
616
616
  });
617
617
  const body = (await res.json().catch(() => ({})));
618
618
  if (!res.ok) {
619
- raiseIfUnauthorized(res);
619
+ raiseIfUnauthorized(res, body);
620
620
  raiseIfUpstreamUnavailable(res);
621
621
  throw new IntegrationsCliError(body.error ?? `${decision} failed (HTTP ${res.status})`, { expected: isClientError(res.status) });
622
622
  }
@@ -94,8 +94,8 @@ import { writeQuestionBody } from "../lib/lanes/questions.js";
94
94
  import { compactionAfterUsage, } from "../lib/lanes/compaction.js";
95
95
  import { parseCliEffort, resolveLaneEffort, } from "../lib/lanes/effort.js";
96
96
  import { LanesError } from "../lib/lanes/errors.js";
97
- import { LedgerCorrupt, capacityOptionsFromEnv, readCollectorMark, readNow, rebuildNow, } from "../lib/capacity/ledger.js";
98
- import { pickAccount, refusalHasStaleReading, staleReadingTargets, } from "../lib/capacity/route.js";
97
+ import { LedgerCorrupt, LedgerMissing, capacityOptionsFromEnv, readCollectorMark, readNow, rebuildNow, } from "../lib/capacity/ledger.js";
98
+ import { pickAccount, refusalHasNoReadings, refusalHasStaleReading, staleReadingTargets, UNKNOWN_USAGE_SCORE, } from "../lib/capacity/route.js";
99
99
  import { capacityViewAge } from "../lib/capacity/freshness.js";
100
100
  import { applyTerminalToLane, classifyLaneExit, readLatestEnvelopeRecord } from "../lib/lanes/watcher.js";
101
101
  import { isSubagentLane, parseLaneEnvelope, parseLaneRunner } from "../lib/lanes/types.js";
@@ -3596,7 +3596,20 @@ async function runCreate(ctx, opts) {
3596
3596
  let autoChosenAccount;
3597
3597
  if (opts.account !== undefined && opts.account.trim() === "auto") {
3598
3598
  const ledgerOptions = capacityOptionsFromEnv(ctx.env);
3599
- let view;
3599
+ // feedback_9e444a9f / feedback_86552798: with no ledger yet (capacity was
3600
+ // never enabled), or a ledger with no reading for any lane account, there
3601
+ // is no evidence any account is full. Route as if the flag were omitted
3602
+ // (balanced admission over the enabled lane accounts) instead of refusing
3603
+ // with capacity_unavailable or no_account_with_room.
3604
+ const noReadingsFallback = () => {
3605
+ autoAccountPick = {
3606
+ why: "no capacity reading for any lane account yet, so the account is chosen as if --account were omitted",
3607
+ headroom: 0,
3608
+ score: UNKNOWN_USAGE_SCORE,
3609
+ };
3610
+ opts = { ...opts, account: undefined };
3611
+ };
3612
+ let view = null;
3600
3613
  try {
3601
3614
  view = readNow(ledgerOptions);
3602
3615
  }
@@ -3604,7 +3617,7 @@ async function runCreate(ctx, opts) {
3604
3617
  if (err instanceof LedgerCorrupt) {
3605
3618
  view = rebuildNow(ledgerOptions);
3606
3619
  }
3607
- else {
3620
+ else if (!(err instanceof LedgerMissing)) {
3608
3621
  throw new LanesError("capacity_unavailable", `Cannot route --account auto: ${err instanceof Error ? err.message : String(err)}`, {});
3609
3622
  }
3610
3623
  }
@@ -3629,11 +3642,11 @@ async function runCreate(ctx, opts) {
3629
3642
  lanesError: routeLanesError,
3630
3643
  allowExtraUsage: opts.allowExtraUsage === true,
3631
3644
  });
3632
- let result = routeOn(view);
3645
+ let result = view === null ? null : routeOn(view);
3633
3646
  // feedback_94446741: a refusal that rests on a missing or day-old reading
3634
3647
  // is not evidence that the account is full. Take one fresh reading and
3635
3648
  // route again; refuse only if there is still no room.
3636
- if (refusalHasStaleReading(result) && ctx.refreshCapacity) {
3649
+ if (result !== null && refusalHasStaleReading(result) && ctx.refreshCapacity) {
3637
3650
  try {
3638
3651
  const refreshed = await ctx.refreshCapacity({
3639
3652
  env: ctx.env,
@@ -3649,7 +3662,10 @@ async function runCreate(ctx, opts) {
3649
3662
  // A failed refresh leaves the original refusal in place.
3650
3663
  }
3651
3664
  }
3652
- if (!result.ok || !result.pick) {
3665
+ if (result === null || refusalHasNoReadings(result)) {
3666
+ noReadingsFallback();
3667
+ }
3668
+ else if (!result.ok || !result.pick) {
3653
3669
  const resetSuffix = result.next_reset ? `; next reset ${result.next_reset}` : "";
3654
3670
  throw new LanesError("no_account_with_room", `No account has room${resetSuffix}`, {
3655
3671
  next_reset: result.next_reset,
@@ -3657,15 +3673,17 @@ async function runCreate(ctx, opts) {
3657
3673
  skipped: result.skipped,
3658
3674
  });
3659
3675
  }
3660
- autoChosenProvider = parseLaneProvider(result.pick.provider);
3661
- autoChosenAccount = result.pick.account;
3662
- autoAccountPick = {
3663
- why: result.pick.why,
3664
- headroom: result.pick.headroom,
3665
- score: result.pick.score,
3666
- };
3667
- opts = { ...opts, account: autoChosenAccount, provider: autoChosenProvider };
3668
- explicitProvider = autoChosenProvider;
3676
+ else {
3677
+ autoChosenProvider = parseLaneProvider(result.pick.provider);
3678
+ autoChosenAccount = result.pick.account;
3679
+ autoAccountPick = {
3680
+ why: result.pick.why,
3681
+ headroom: result.pick.headroom,
3682
+ score: result.pick.score,
3683
+ };
3684
+ opts = { ...opts, account: autoChosenAccount, provider: autoChosenProvider };
3685
+ explicitProvider = autoChosenProvider;
3686
+ }
3669
3687
  }
3670
3688
  if (opts.outpost !== undefined && opts.outpost !== "") {
3671
3689
  const requested = opts.outpost.trim();
@@ -99,10 +99,9 @@ async function readPlanLimits(company) {
99
99
  const status = await fetchPlanLimitStatus(token, slug);
100
100
  if (!status)
101
101
  return null;
102
- return {
103
- status,
104
- idToken: loadCachedTokens()?.idToken,
105
- };
102
+ // The result is printed verbatim by `--json`. It must never carry a
103
+ // token: hooks and agents capture that stdout into transcripts and logs.
104
+ return { status };
106
105
  }
107
106
  catch {
108
107
  return null;
@@ -139,8 +138,10 @@ async function printPlanBlock(company) {
139
138
  const planLimits = await readPlanLimits(company);
140
139
  if (!planLimits)
141
140
  return;
142
- const { status, idToken } = planLimits;
143
- const inviteTeammateEnabled = await inviteTeammateSuggestionEnabled(status, idToken);
141
+ const { status } = planLimits;
142
+ // The flag gate needs a bearer; read it here so it never travels in the
143
+ // plan-limit result that `--json` prints.
144
+ const inviteTeammateEnabled = await inviteTeammateSuggestionEnabled(status, loadCachedTokens()?.idToken);
144
145
  const block = renderWhoamiPlanBlock(status, { inviteTeammateEnabled });
145
146
  if (!block)
146
147
  return;
@@ -4,6 +4,7 @@ import { homedir } from "node:os";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { COMMAND_CATALOG } from "./command-catalog.generated.js";
6
6
  import { installUnknownCommandSuggestions } from "./unknown-command.js";
7
+ import { MissingRegistrationPlanError } from "./utils/registration-plan-error.js";
7
8
  const commandCatalog = COMMAND_CATALOG;
8
9
  /**
9
10
  * One entry for every root, including groups that are assembled by several
@@ -14,8 +15,10 @@ const LAZY_COMMANDS = commandCatalog.map((command) => ({
14
15
  name: command.name,
15
16
  register: async (program) => {
16
17
  const registered = await registerCommandRoot(program, command.name);
18
+ // A missing plan means the catalog and the plan came from different installs
19
+ // (an update landed mid-start); the typed error routes it to torn-install recovery.
17
20
  if (!registered)
18
- throw new Error(`No registration plan for '${command.name}'`);
21
+ throw new MissingRegistrationPlanError(command.name);
19
22
  },
20
23
  }));
21
24
  /**
@@ -127,7 +127,10 @@ export declare function usageIncludedSentence(card?: UsageCard): string;
127
127
  export declare function usageOnlyUpgradeLines(card?: UsageCard): string[];
128
128
  /** The `Plan:` orientation line (`hq whoami --plan`) for a usage-only company. */
129
129
  export declare function usageOnlyPlanLine(card?: UsageCard): string;
130
- /** Agent boxes on usage pricing, priced by size from the card. */
130
+ /**
131
+ * Agent boxes on usage pricing, priced by size from the card, plus the
132
+ * agent-run meter when the card lists one.
133
+ */
131
134
  export declare function usageOnlyBoxSentence(card?: UsageCard): string;
132
135
  /**
133
136
  * A refusal that a legacy account answers by upgrading its plan. On usage
@@ -331,9 +331,14 @@ export function usageOnlyPlanLine(card = BUNDLED_USAGE_CARD) {
331
331
  return (`Plan: usage pricing — ${formatCardUsd(card.includedUsd)} of usage included each month. ` +
332
332
  "See `hq billing usage`.");
333
333
  }
334
- /** Agent boxes on usage pricing, priced by size from the card. */
334
+ /**
335
+ * Agent boxes on usage pricing, priced by size from the card, plus the
336
+ * agent-run meter when the card lists one.
337
+ */
335
338
  export function usageOnlyBoxSentence(card = BUNDLED_USAGE_CARD) {
336
- return `Agent boxes on usage pricing are billed by size: ${formatBoxQuotes(card)}.`;
339
+ const run = card.meters.find((m) => m.id === "agent-run");
340
+ const perRun = run ? `, plus ${formatCardUsd(run.unitUsd)} per agent run` : "";
341
+ return `Agent boxes on usage pricing are billed by size: ${formatBoxQuotes(card)}${perRun}.`;
337
342
  }
338
343
  /**
339
344
  * A refusal that a legacy account answers by upgrading its plan. On usage
@@ -199,7 +199,7 @@ export declare class BotApi {
199
199
  /** GET /v1/agents/{uid} — owner-only local bot record (403/404 for others). */
200
200
  getAgent(agentUid: string): Promise<AgentRecord>;
201
201
  /** POST /v1/agents/{uid}/heartbeat — agent-JWT only. */
202
- heartbeat(agentUid: string, components: Record<string, "ok" | "degraded" | "failed" | "unknown">): Promise<{
202
+ heartbeat(agentUid: string, components: Record<string, "ok" | "degraded" | "failed" | "unknown" | boolean | string | null>): Promise<{
203
203
  ok: boolean;
204
204
  at?: string;
205
205
  local?: boolean;
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import * as fs from "node:fs";
5
5
  import * as path from "node:path";
6
+ import semver from "semver";
6
7
  import { botConfigPath } from "./paths.js";
7
8
  export const BOT_RUNTIMES = ["claude", "codex", "grok"];
8
9
  export const HQ_FLEET_RUNTIME_ENGINE_ID = "hq-fleet-runtime";
@@ -13,7 +14,7 @@ export function isBotEngineMetadata(value) {
13
14
  return (engine.id === HQ_FLEET_RUNTIME_ENGINE_ID &&
14
15
  engine.distribution === "hq-fleet-local" &&
15
16
  typeof engine.version === "string" &&
16
- /^\d+\.\d+\.\d+$/.test(engine.version) &&
17
+ semver.valid(engine.version) === engine.version &&
17
18
  typeof engine.artifactSha256 === "string" &&
18
19
  /^[a-f0-9]{64}$/.test(engine.artifactSha256) &&
19
20
  typeof engine.runtimeCommit === "string" &&
@@ -85,6 +85,10 @@ export declare function gatewayOutsideDaemon(agentUid: string, deps: {
85
85
  * unit waiting.
86
86
  */
87
87
  export declare function planFleetBots(deps?: PlanFleetBotsDeps): FleetBotPlan[];
88
+ export declare function clearStaleReadyBeforeGatewayStart(unit: {
89
+ id: string;
90
+ env: Record<string, string>;
91
+ }, alive?: (pid: number) => boolean): boolean;
88
92
  export interface ControlFleetBotDeps extends FleetLocalControlDeps, FleetDaemonHost {
89
93
  root?: string;
90
94
  uid?: number;
@@ -17,7 +17,7 @@ import * as os from "node:os";
17
17
  import * as path from "node:path";
18
18
  import { HQ_FLEET_RUNTIME_ENGINE_ID, patchBotConfig, readBotConfig } from "./config.js";
19
19
  import { defaultPathEntries } from "./daemon.js";
20
- import { controlFleetLocalBot, fleetLocalGatewayPid, fleetLocalGatewayProcess, fleetLocalLaunchAgentLabel, fleetLocalLaunchAgentPlist, removeFleetLocalEmbeddedRuntime, } from "./fleet-local.js";
20
+ import { clearStaleFleetGatewayReady, controlFleetLocalBot, fleetLocalGatewayPid, fleetLocalGatewayProcess, fleetLocalLaunchAgentLabel, fleetLocalLaunchAgentPlist, removeFleetLocalEmbeddedRuntime, } from "./fleet-local.js";
21
21
  import { botsRoot } from "./paths.js";
22
22
  import { isPidAlive } from "./status.js";
23
23
  import { askDaemonToStart, askDaemonToStop, daemonUnitInstalled, hostedDaemonRunning } from "../daemon/handoff.js";
@@ -158,6 +158,17 @@ export function planFleetBots(deps = {}) {
158
158
  };
159
159
  });
160
160
  }
161
+ export function clearStaleReadyBeforeGatewayStart(unit, alive) {
162
+ const profileDir = unit.env.HQ_FLEET_HOME;
163
+ if (!unit.id.startsWith(FLEET_BOT_UNIT_PREFIX) || !profileDir)
164
+ return false;
165
+ try {
166
+ return clearStaleFleetGatewayReady(profileDir, alive);
167
+ }
168
+ catch {
169
+ return false;
170
+ }
171
+ }
161
172
  function unitState(paths, unitId, alive) {
162
173
  try {
163
174
  const state = JSON.parse(fs.readFileSync(paths.statePath, "utf8"));
@@ -2,6 +2,10 @@
2
2
  export declare const FLEET_DOWNLOAD_STALL_MS = 90000;
3
3
  /** How many times a stalled or broken download is resumed before giving up. */
4
4
  export declare const FLEET_DOWNLOAD_MAX_RESUMES = 5;
5
+ /** A file at least this large is fetched as parallel byte ranges when the server accepts them. */
6
+ export declare const FLEET_DOWNLOAD_SEGMENT_MIN_BYTES: number;
7
+ /** How many byte ranges a large file is fetched in at the same time. */
8
+ export declare const FLEET_DOWNLOAD_SEGMENTS = 8;
5
9
  export interface FleetDownloadProgress {
6
10
  name: string;
7
11
  received: number;
@@ -12,6 +16,8 @@ export interface FleetDownloadOptions {
12
16
  headers?: Record<string, string>;
13
17
  stallMs?: number;
14
18
  maxResumes?: number;
19
+ segments?: number;
20
+ segmentMinBytes?: number;
15
21
  onProgress?: (progress: FleetDownloadProgress) => void;
16
22
  }
17
23
  /**
@@ -5,6 +5,10 @@ import * as path from "node:path";
5
5
  export const FLEET_DOWNLOAD_STALL_MS = 90_000;
6
6
  /** How many times a stalled or broken download is resumed before giving up. */
7
7
  export const FLEET_DOWNLOAD_MAX_RESUMES = 5;
8
+ /** A file at least this large is fetched as parallel byte ranges when the server accepts them. */
9
+ export const FLEET_DOWNLOAD_SEGMENT_MIN_BYTES = 8 * 1_048_576;
10
+ /** How many byte ranges a large file is fetched in at the same time. */
11
+ export const FLEET_DOWNLOAD_SEGMENTS = 8;
8
12
  function expectedError(message) {
9
13
  return Object.assign(new Error(message), { expected: true });
10
14
  }
@@ -31,7 +35,7 @@ function contentRangeTotal(response) {
31
35
  const value = Number.parseInt(match[1], 10);
32
36
  return Number.isFinite(value) ? value : null;
33
37
  }
34
- async function pumpBody(response, fd, offset, name, total, stallMs, onProgress) {
38
+ async function pumpBody(response, fd, offset, name, total, stallMs, onProgress, until = null) {
35
39
  if (!response.body) {
36
40
  const bytes = Buffer.from(await response.arrayBuffer());
37
41
  fs.writeSync(fd, bytes, 0, bytes.length, offset);
@@ -61,8 +65,13 @@ async function pumpBody(response, fd, offset, name, total, stallMs, onProgress)
61
65
  }
62
66
  if (chunk.done)
63
67
  break;
64
- fs.writeSync(fd, chunk.value, 0, chunk.value.length, received);
65
- received += chunk.value.length;
68
+ const length = until === null ? chunk.value.length : Math.min(chunk.value.length, until - received);
69
+ fs.writeSync(fd, chunk.value, 0, length, received);
70
+ received += length;
71
+ if (until !== null && received >= until) {
72
+ void reader.cancel().catch(() => undefined);
73
+ break;
74
+ }
66
75
  const now = Date.now();
67
76
  if (now - lastReport >= 250 || (total !== null && received >= total)) {
68
77
  lastReport = now;
@@ -72,6 +81,108 @@ async function pumpBody(response, fd, offset, name, total, stallMs, onProgress)
72
81
  onProgress?.({ name, received, total });
73
82
  return received;
74
83
  }
84
+ function segmentBounds(total, count) {
85
+ const size = Math.ceil(total / count);
86
+ const bounds = [];
87
+ for (let start = 0; start < total; start += size)
88
+ bounds.push([start, Math.min(total, start + size)]);
89
+ return bounds;
90
+ }
91
+ function readSegmentState(file, segmentFile) {
92
+ try {
93
+ const state = JSON.parse(fs.readFileSync(file, "utf8"));
94
+ if (typeof state.total !== "number" || !Array.isArray(state.done) || !state.done.every((n) => typeof n === "number" && n >= 0))
95
+ return null;
96
+ if (partFileSize(segmentFile) !== state.total)
97
+ return null;
98
+ return { total: state.total, done: state.done };
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
104
+ async function downloadSegments(url, destination, state, first, fetcher, options, stallMs, maxResumes) {
105
+ const name = path.basename(destination);
106
+ const segmentFile = `${destination}.seg`;
107
+ const stateFile = `${segmentFile}.json`;
108
+ const bounds = segmentBounds(state.total, state.done.length);
109
+ let lastSaved = 0;
110
+ const save = (force = false) => {
111
+ const now = Date.now();
112
+ if (!force && now - lastSaved < 1_000)
113
+ return;
114
+ lastSaved = now;
115
+ fs.writeFileSync(stateFile, JSON.stringify(state), { mode: 0o600 });
116
+ };
117
+ let lastReport = 0;
118
+ const report = () => {
119
+ const received = state.done.reduce((sum, n) => sum + n, 0);
120
+ const now = Date.now();
121
+ if (now - lastReport >= 250 || received >= state.total) {
122
+ lastReport = now;
123
+ options.onProgress?.({ name, received, total: state.total });
124
+ }
125
+ save();
126
+ };
127
+ save(true);
128
+ const fd = fs.openSync(segmentFile, "r+");
129
+ try {
130
+ const results = await Promise.allSettled(bounds.map(async ([start, end], index) => {
131
+ let response = index === 0 ? first : null;
132
+ let failure = null;
133
+ for (let attempt = 0; attempt <= maxResumes; attempt += 1) {
134
+ const from = start + state.done[index];
135
+ if (from >= end)
136
+ return;
137
+ if (!response || attempt > 0) {
138
+ try {
139
+ response = await fetcher(url, { headers: { ...options.headers, Range: `bytes=${from}-${end - 1}` } });
140
+ }
141
+ catch (error) {
142
+ failure = error;
143
+ response = null;
144
+ continue;
145
+ }
146
+ if (response.status !== 206) {
147
+ void response.body?.cancel().catch(() => undefined);
148
+ throw expectedError(`Could not download ${name}: HQ storage returned HTTP ${response.status} for part of the file.`);
149
+ }
150
+ }
151
+ try {
152
+ await pumpBody(response, fd, from, name, state.total, stallMs, (progress) => {
153
+ state.done[index] = progress.received - start;
154
+ report();
155
+ }, end);
156
+ }
157
+ catch (error) {
158
+ failure = error;
159
+ continue;
160
+ }
161
+ finally {
162
+ response = null;
163
+ }
164
+ if (start + state.done[index] >= end)
165
+ return;
166
+ failure = expectedError(`ended early at ${start + state.done[index]} of ${end} bytes`);
167
+ }
168
+ throw failure;
169
+ }));
170
+ const failed = results.find((result) => result.status === "rejected");
171
+ if (failed)
172
+ throw failed.reason;
173
+ }
174
+ catch (error) {
175
+ save(true);
176
+ const cause = error instanceof Error ? error.message : String(error);
177
+ throw expectedError(`Could not download ${name} after ${maxResumes + 1} attempts (${cause}). Check your internet connection and retry; the download continues where it stopped.`);
178
+ }
179
+ finally {
180
+ fs.closeSync(fd);
181
+ }
182
+ fs.renameSync(segmentFile, destination);
183
+ fs.rmSync(stateFile, { force: true });
184
+ return destination;
185
+ }
75
186
  /**
76
187
  * Download `url` into `destination`, writing through `<destination>.part` and
77
188
  * resuming from the bytes already there. Every attempt that receives nothing
@@ -85,7 +196,13 @@ export async function downloadFleetFile(url, destination, options = {}) {
85
196
  const maxResumes = options.maxResumes ?? FLEET_DOWNLOAD_MAX_RESUMES;
86
197
  const name = path.basename(destination);
87
198
  const part = `${destination}.part`;
199
+ const segments = Math.max(1, options.segments ?? FLEET_DOWNLOAD_SEGMENTS);
200
+ const segmentMinBytes = options.segmentMinBytes ?? FLEET_DOWNLOAD_SEGMENT_MIN_BYTES;
201
+ const segmentFile = `${destination}.seg`;
88
202
  fs.mkdirSync(path.dirname(destination), { recursive: true, mode: 0o700 });
203
+ const resumable = readSegmentState(`${segmentFile}.json`, segmentFile);
204
+ if (resumable)
205
+ return downloadSegments(url, destination, resumable, null, fetcher, options, stallMs, maxResumes);
89
206
  let lastFailure = null;
90
207
  for (let attempt = 0; attempt <= maxResumes; attempt += 1) {
91
208
  const have = partFileSize(part);
@@ -113,6 +230,14 @@ export async function downloadFleetFile(url, destination, options = {}) {
113
230
  else if (response.ok) {
114
231
  offset = 0;
115
232
  total = contentLength(response);
233
+ const ranges = (response.headers.get("accept-ranges") ?? "").toLowerCase().includes("bytes");
234
+ if (response.status === 200 && segments > 1 && ranges && total !== null && total >= segmentMinBytes) {
235
+ const created = fs.openSync(segmentFile, "w", 0o600);
236
+ fs.ftruncateSync(created, total);
237
+ fs.closeSync(created);
238
+ fs.rmSync(part, { force: true });
239
+ return downloadSegments(url, destination, { total, done: new Array(segments).fill(0) }, response, fetcher, options, stallMs, maxResumes);
240
+ }
116
241
  }
117
242
  else {
118
243
  void response.body?.cancel().catch(() => undefined);
@@ -68,6 +68,7 @@ export interface FleetLocalInstallDeps {
68
68
  onProgress?: FleetInstallProgressListener;
69
69
  /** How long a download may go without bytes before it is resumed (tests). */
70
70
  downloadStallMs?: number;
71
+ allowFileLinks?: boolean;
71
72
  }
72
73
  export interface FleetLocalProfileInput {
73
74
  agentUid: string;
@@ -161,6 +162,7 @@ export interface FleetLocalControlDeps {
161
162
  }
162
163
  export interface FleetLocalAuthInput {
163
164
  installService?: boolean;
165
+ onAuthEvent?: (event: Record<string, unknown>) => void;
164
166
  agentUid: string;
165
167
  provider: string;
166
168
  model?: string;
@@ -229,13 +231,18 @@ export interface FleetLocalReleasePointer {
229
231
  minimumHqCli: string | null;
230
232
  links: Map<string, string> | null;
231
233
  linksExpireAt: number | null;
234
+ localFile?: string;
232
235
  }
233
236
  export interface FleetLocalTargetRelease {
234
237
  release: FleetLocalReleasePin;
235
238
  source: "pointer" | "compiled";
236
239
  links: Map<string, string> | null;
237
240
  linksExpireAt: number | null;
241
+ localFile?: string;
238
242
  }
243
+ export declare const FLEET_RELEASE_POINTER_FILE_ENV = "HQ_FLEET_RELEASE_POINTER_FILE";
244
+ export declare function fleetReleasePointerFileOverride(env?: NodeJS.ProcessEnv): string | null;
245
+ export declare function readLocalFleetReleasePointer(file: string, now?: number): FleetLocalReleasePointer;
239
246
  export declare function parseFleetLocalReleasePin(value: unknown): FleetLocalReleasePin | null;
240
247
  export declare function parseFleetLocalReleasePointer(body: unknown, now?: number): FleetLocalReleasePointer | null;
241
248
  export declare function chooseFleetLocalTargetRelease(pointer: FleetLocalReleasePointer | null, compiled?: FleetLocalReleasePin, cliVersion?: string): FleetLocalTargetRelease;
@@ -249,11 +256,16 @@ interface FleetLocalPointerDeps {
249
256
  fleetHome?: string;
250
257
  now?: () => number;
251
258
  fetchPointer?: () => Promise<FleetLocalReleasePointer | null>;
259
+ env?: NodeJS.ProcessEnv;
252
260
  }
253
261
  export declare function resolveFleetLocalTargetRelease(deps?: FleetLocalPointerDeps & {
254
262
  compiled?: FleetLocalReleasePin;
255
263
  cliVersion?: string;
256
264
  }): Promise<FleetLocalTargetRelease>;
265
+ export declare function cachedFleetLocalTargetRelease(deps?: FleetLocalPointerDeps & {
266
+ compiled?: FleetLocalReleasePin;
267
+ cliVersion?: string;
268
+ }): FleetLocalTargetRelease;
257
269
  export declare function resolveFleetLocalPointerTarget(deps?: FleetLocalPointerDeps & {
258
270
  cliVersion?: string;
259
271
  }): Promise<FleetLocalTargetRelease | null>;
@@ -263,6 +275,9 @@ export declare function installTargetFleetLocalDistribution(deps?: Omit<FleetLoc
263
275
  }): Promise<FleetLocalInstallation>;
264
276
  /** What an install is doing right now, for a progress bar or a log line. */
265
277
  export type FleetInstallProgress = {
278
+ phase: "download-start";
279
+ files: number;
280
+ } | {
266
281
  phase: "download";
267
282
  file: string;
268
283
  received: number;
@@ -335,7 +350,22 @@ export declare function controlFleetLocalBot(agentUid: string, action: FleetLoca
335
350
  export declare function exportFleetLocalMachineCredential(agentUid: string, deps?: FleetLocalControlDeps): BotMachineCreds;
336
351
  export declare function fleetLocalPromotionRuntime(agentUid: string, deps?: FleetLocalControlDeps): LocalBotPromotionRuntime;
337
352
  export declare function removeFleetLocalBot(agentUid: string, deps?: FleetLocalControlDeps): FleetLocalRemovalResult;
338
- export declare function authenticateFleetLocalBot(input: FleetLocalAuthInput, deps?: FleetLocalControlDeps): FleetLocalAuthResult;
353
+ export type FleetLocalStartControl = (agentUid: string, action: "install" | "restart") => {
354
+ ok?: unknown;
355
+ };
356
+ export type FleetAuthSpawn = (executable: string, args: string[], onStderrLine: (line: string) => void) => Promise<{
357
+ code: number | null;
358
+ stdout: string;
359
+ }>;
360
+ export declare const spawnFleetAuth: FleetAuthSpawn;
361
+ export declare const FLEET_GROK_CLI_IMPORT_MIN_VERSION = "0.4.31-local.13";
362
+ export declare function fleetReleaseImportsGrokCli(version: string | null | undefined): boolean;
363
+ export declare function fleetLocalProfileEngineVersion(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): string | null;
364
+ export declare function authenticateFleetLocalBot(input: FleetLocalAuthInput, deps?: FleetLocalControlDeps & {
365
+ control?: FleetLocalStartControl;
366
+ spawnAuth?: FleetAuthSpawn;
367
+ writeStderr?: (text: string) => void;
368
+ }): Promise<FleetLocalAuthResult>;
339
369
  export declare function writeFleetLocalProfile(input: FleetLocalProfileInput, deps?: FleetLocalProfileDeps): string;
340
370
  /** The runtime's inbox plugin sends the intro and runs the kickoff once, then stamps this file. */
341
371
  export declare function writeFleetLocalFirstStart(profileDir: string, firstStart: {
@@ -361,7 +391,14 @@ export interface FleetLocalGatewayState {
361
391
  gatewayState: string | null;
362
392
  activeAgents: number;
363
393
  platforms: Record<string, string>;
394
+ ready: boolean;
395
+ readyAt: string | null;
364
396
  }
397
+ export declare function parseGatewayReady(value: unknown): {
398
+ ready: boolean;
399
+ readyAt: string | null;
400
+ };
401
+ export declare function clearStaleFleetGatewayReady(profileDir: string, alive?: (pid: number) => boolean): boolean;
365
402
  export declare function readFleetLocalGatewayState(agentUid: string, deps?: Pick<FleetLocalControlDeps, "fleetHome">): FleetLocalGatewayState | null;
366
403
  export declare function fleetLocalChannels(state: FleetLocalGatewayState | null, gatewayAlive: boolean): {
367
404
  slack: string;