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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;
@@ -1,9 +1,10 @@
1
- import { execFileSync, spawnSync } from "node:child_process";
1
+ import { execFileSync, spawn, spawnSync } from "node:child_process";
2
2
  import * as crypto from "node:crypto";
3
3
  import * as fs from "node:fs";
4
4
  import * as os from "node:os";
5
5
  import * as path from "node:path";
6
6
  import * as zlib from "node:zlib";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
8
  import { HQ_FLEET_RUNTIME_ENGINE_ID, } from "./config.js";
8
9
  import { withBotLock } from "./lock.js";
9
10
  import { downloadFleetFile, fileSha256 } from "./fleet-download.js";
@@ -81,15 +82,15 @@ export function sharedRuntimeLayout(root, id, platform) {
81
82
  }
82
83
  export const HQ_FLEET_LOCAL_RELEASE = {
83
84
  repository: "indigoai-us/hq-fleet-local",
84
- tag: "v0.4.28",
85
- version: "0.4.28",
86
- artifact: "hq-fleet-local-0.4.28.zip",
87
- artifactSha256: "7ddb302db63e771aca6b53fa7cf295446016746e7dd508ecb1568ef8bdc40bfd",
88
- runtimeArtifact: "hq-fleet-runtime-1f8e7cb662f4.tar.gz",
89
- runtimeArtifactSha256: "44e53714fcaf2ce823d05a8a91f86806e4ce88d24e9c52aba853eb389ea4d85f",
90
- manifestSha256: "a58834dd3a4abaa45a5eb180ad24de10df800ca561b80f45de5ab03d8d71e26d",
91
- signatureSha256: "b3c3f338af6964417e1630ac735248c5969aebe946d65d14617a2429a32d4a17",
92
- runtimeCommit: "1f8e7cb662f43836aa4edff167bcaf5e92998fb1",
85
+ tag: "v0.4.31",
86
+ version: "0.4.31",
87
+ artifact: "hq-fleet-local-0.4.31.zip",
88
+ artifactSha256: "cb0f224bfe4d4c091a920a59b13502864d43129191c5aaa78a0b0c006e9868df",
89
+ runtimeArtifact: "hq-fleet-runtime-398523c9ead4.tar.gz",
90
+ runtimeArtifactSha256: "074e15d560b263fc2e10b1cc1f3ca89a177a1b0e54dcfd63aff55236e414a0ff",
91
+ manifestSha256: "38c4ca7f5cc7b6b874cf65de9d70effb78c2f762d0f3b7e04b6ef78fc368302d",
92
+ signatureSha256: "ef421dcbe6bde60d0a4dc6c9b470dc114d95c85dbe163ad68b498cd7b000f00d",
93
+ runtimeCommit: "398523c9ead40e36f45adcd4489e7d8c01e283ff",
93
94
  };
94
95
  /** hq-fleet-local trust/release-public.pem (rotated 2026-10-30; signed v0.4.17). */
95
96
  export const HQ_FLEET_LOCAL_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
@@ -443,6 +444,61 @@ function noReleaseSourceError(release, reason) {
443
444
  export const FLEET_LOCAL_LATEST_TIMEOUT_MS = 5_000;
444
445
  export const FLEET_LOCAL_LATEST_CACHE_MS = 10 * 60_000;
445
446
  const FLEET_LOCAL_LATEST_CACHE_FILE = "release-pointer.json";
447
+ export const FLEET_RELEASE_POINTER_FILE_ENV = "HQ_FLEET_RELEASE_POINTER_FILE";
448
+ const LOCAL_POINTER_LINK_LIFETIME_SECONDS = 365 * 24 * 60 * 60;
449
+ export function fleetReleasePointerFileOverride(env = process.env) {
450
+ const value = env[FLEET_RELEASE_POINTER_FILE_ENV]?.trim();
451
+ return value ? path.resolve(value) : null;
452
+ }
453
+ function localAssetUrl(url, base) {
454
+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !/^[a-z]:[\\/]/i.test(url))
455
+ return url;
456
+ return pathToFileURL(path.resolve(base, url)).href;
457
+ }
458
+ export function readLocalFleetReleasePointer(file, now = Date.now()) {
459
+ let body;
460
+ try {
461
+ body = JSON.parse(fs.readFileSync(file, "utf8"));
462
+ }
463
+ catch (error) {
464
+ throw expectedError(`${FLEET_RELEASE_POINTER_FILE_ENV} names ${file}, which could not be read as JSON (${error instanceof Error ? error.message : String(error)}).`);
465
+ }
466
+ if (body && typeof body === "object" && !Array.isArray(body)) {
467
+ const record = body;
468
+ const base = path.dirname(file);
469
+ body = {
470
+ ...record,
471
+ expiresInSeconds: typeof record.expiresInSeconds === "number" && record.expiresInSeconds > 0 ? record.expiresInSeconds : LOCAL_POINTER_LINK_LIFETIME_SECONDS,
472
+ assets: Array.isArray(record.assets)
473
+ ? record.assets.map((asset) => {
474
+ const entry = asset;
475
+ return entry && typeof entry.url === "string" ? { ...entry, url: localAssetUrl(entry.url, base) } : asset;
476
+ })
477
+ : record.assets,
478
+ };
479
+ }
480
+ const pointer = parseFleetLocalReleasePointer(body, now);
481
+ if (!pointer) {
482
+ throw expectedError(`${FLEET_RELEASE_POINTER_FILE_ENV} names ${file}, which is not a valid HQ Fleet Local release pointer.`);
483
+ }
484
+ return { ...pointer, localFile: file };
485
+ }
486
+ function localPointerTarget(pointer, cliVersion) {
487
+ if (pointer.minimumHqCli) {
488
+ const required = semver.valid(semver.coerce(pointer.minimumHqCli));
489
+ const current = semver.valid(semver.coerce(cliVersion));
490
+ if (!required || !current || semver.lt(current, required)) {
491
+ throw expectedError(`The release pointer in ${pointer.localFile} needs hq-cli ${pointer.minimumHqCli} or newer; this is ${cliVersion}.`);
492
+ }
493
+ }
494
+ return {
495
+ release: pointer.release,
496
+ source: "pointer",
497
+ links: pointer.links,
498
+ linksExpireAt: pointer.linksExpireAt,
499
+ ...(pointer.localFile ? { localFile: pointer.localFile } : {}),
500
+ };
501
+ }
446
502
  const SHA256_RE = /^[0-9a-f]{64}$/;
447
503
  const COMMIT_RE = /^[0-9a-f]{40}$/;
448
504
  export function parseFleetLocalReleasePin(value) {
@@ -592,6 +648,9 @@ function pointerFromCache(body) {
592
648
  async function loadFleetLocalReleasePointer(deps) {
593
649
  const root = deps.fleetHome ?? fleetHome();
594
650
  const now = (deps.now ?? Date.now)();
651
+ const localFile = fleetReleasePointerFileOverride(deps.env ?? process.env);
652
+ if (localFile)
653
+ return readLocalFleetReleasePointer(localFile, now);
595
654
  const cached = readPointerCache(root, now);
596
655
  if (cached)
597
656
  return pointerFromCache(cached.body);
@@ -606,12 +665,24 @@ async function loadFleetLocalReleasePointer(deps) {
606
665
  }
607
666
  export async function resolveFleetLocalTargetRelease(deps = {}) {
608
667
  const pointer = await loadFleetLocalReleasePointer(deps);
668
+ if (pointer?.localFile)
669
+ return localPointerTarget(pointer, deps.cliVersion ?? CLI_VERSION);
609
670
  return chooseFleetLocalTargetRelease(pointer, deps.compiled ?? HQ_FLEET_LOCAL_RELEASE, deps.cliVersion ?? CLI_VERSION);
610
671
  }
672
+ export function cachedFleetLocalTargetRelease(deps = {}) {
673
+ const now = (deps.now ?? Date.now)();
674
+ const localFile = fleetReleasePointerFileOverride(deps.env ?? process.env);
675
+ if (localFile)
676
+ return localPointerTarget(readLocalFleetReleasePointer(localFile, now), deps.cliVersion ?? CLI_VERSION);
677
+ const cached = readPointerCache(deps.fleetHome ?? fleetHome(), now);
678
+ return chooseFleetLocalTargetRelease(cached ? pointerFromCache(cached.body) : null, deps.compiled ?? HQ_FLEET_LOCAL_RELEASE, deps.cliVersion ?? CLI_VERSION);
679
+ }
611
680
  export async function resolveFleetLocalPointerTarget(deps = {}) {
612
681
  const pointer = await loadFleetLocalReleasePointer(deps);
613
682
  if (!pointer)
614
683
  return null;
684
+ if (pointer.localFile)
685
+ return localPointerTarget(pointer, deps.cliVersion ?? CLI_VERSION);
615
686
  if (pointer.minimumHqCli) {
616
687
  const required = semver.valid(semver.coerce(pointer.minimumHqCli));
617
688
  const current = semver.valid(semver.coerce(deps.cliVersion ?? CLI_VERSION));
@@ -629,6 +700,7 @@ export async function installTargetFleetLocalDistribution(deps = {}) {
629
700
  ...installDeps,
630
701
  release: target.release,
631
702
  ...(freshLinks && !installDeps.hqReleaseLinks ? { hqReleaseLinks: async () => freshLinks } : {}),
703
+ ...(target.localFile ? { allowFileLinks: true } : {}),
632
704
  });
633
705
  }
634
706
  function trustedReleaseLink(url) {
@@ -666,12 +738,24 @@ function discardDownloads(target) {
666
738
  async function downloadReleaseFiles(release, fetcher, resolve, cachedRuntime, target, onProgress, stallMs) {
667
739
  fs.mkdirSync(target, { recursive: true, mode: 0o700 });
668
740
  const downloaded = new Map();
669
- for (const name of RELEASE_FILE_NAMES(release)) {
741
+ const wanted = RELEASE_FILE_NAMES(release).filter((name) => {
670
742
  if (name === release.runtimeArtifact && cachedRuntime) {
671
743
  downloaded.set(name, cachedRuntime);
672
- continue;
744
+ return false;
745
+ }
746
+ return true;
747
+ });
748
+ const sources = wanted.map((name) => ({ name, ...resolve(name) }));
749
+ onProgress?.({ phase: "download-start", files: wanted.length });
750
+ await Promise.all(sources.map(async ({ name, url, headers }) => {
751
+ if (url.startsWith("file:")) {
752
+ const destination = path.join(target, name);
753
+ fs.copyFileSync(fileURLToPath(url), destination);
754
+ const size = fs.statSync(destination).size;
755
+ onProgress?.({ phase: "download", file: name, received: size, total: size });
756
+ downloaded.set(name, destination);
757
+ return;
673
758
  }
674
- const { url, headers } = resolve(name);
675
759
  const file = await downloadFleetFile(url, path.join(target, name), {
676
760
  fetch: fetcher,
677
761
  ...(headers ? { headers } : {}),
@@ -679,7 +763,7 @@ async function downloadReleaseFiles(release, fetcher, resolve, cachedRuntime, ta
679
763
  onProgress: (progress) => onProgress?.({ phase: "download", file: name, received: progress.received, total: progress.total }),
680
764
  });
681
765
  downloaded.set(name, file);
682
- }
766
+ }));
683
767
  return {
684
768
  archive: fs.readFileSync(downloaded.get(release.artifact)),
685
769
  runtimeArchive: fs.readFileSync(downloaded.get(release.runtimeArtifact)),
@@ -687,14 +771,14 @@ async function downloadReleaseFiles(release, fetcher, resolve, cachedRuntime, ta
687
771
  signature: fs.readFileSync(downloaded.get("release-manifest.sig")),
688
772
  };
689
773
  }
690
- async function downloadFleetLocalReleaseFromHq(release, fetcher, links, cachedRuntime, target, onProgress, stallMs) {
774
+ async function downloadFleetLocalReleaseFromHq(release, fetcher, links, cachedRuntime, target, onProgress, stallMs, allowFileLinks = false) {
691
775
  for (const name of RELEASE_FILE_NAMES(release)) {
692
776
  if (name === release.runtimeArtifact && cachedRuntime)
693
777
  continue;
694
778
  const url = links.get(name);
695
779
  if (!url)
696
780
  throw expectedError(`HQ Fleet Local ${release.tag} is missing release asset ${name}.`);
697
- if (!trustedReleaseLink(url)) {
781
+ if (!trustedReleaseLink(url) && !(allowFileLinks && url.startsWith("file:"))) {
698
782
  throw expectedError(`HQ Fleet Local ${release.tag} returned an untrusted download link for ${name}.`);
699
783
  }
700
784
  }
@@ -801,9 +885,18 @@ function cachedRuntimeArchive(root, release) {
801
885
  }
802
886
  return null;
803
887
  }
888
+ function filesMatchPin(files, release) {
889
+ if (!files)
890
+ return null;
891
+ const matches = digest(files.archive) === release.artifactSha256 &&
892
+ digest(files.runtimeArchive) === release.runtimeArtifactSha256 &&
893
+ digest(files.manifest) === release.manifestSha256 &&
894
+ digest(files.signature) === release.signatureSha256;
895
+ return matches ? files : null;
896
+ }
804
897
  /** Whether the pinned release is installed on this machine (no download needed). */
805
898
  export function fleetLocalDistributionInstalled(release = HQ_FLEET_LOCAL_RELEASE, root = fleetHome()) {
806
- return installedFiles(path.join(root, "distributions", "hq-fleet-local", release.version), release) !== null;
899
+ return filesMatchPin(installedFiles(path.join(root, "distributions", "hq-fleet-local", release.version), release), release) !== null;
807
900
  }
808
901
  export async function installPinnedFleetLocalDistribution(deps = {}) {
809
902
  const release = deps.release ?? HQ_FLEET_LOCAL_RELEASE;
@@ -825,7 +918,7 @@ export async function installPinnedFleetLocalDistribution(deps = {}) {
825
918
  signature: path.join(dir, "release-manifest.sig"),
826
919
  engine: engineMetadata(release),
827
920
  });
828
- const current = installedFiles(dir, release);
921
+ const current = filesMatchPin(installedFiles(dir, release), release);
829
922
  if (current) {
830
923
  verifyFleetLocalRelease(current, release, publicKey);
831
924
  warnCompatibility(current.manifest);
@@ -833,7 +926,7 @@ export async function installPinnedFleetLocalDistribution(deps = {}) {
833
926
  return installation();
834
927
  }
835
928
  return withBotLock(FLEET_LOCAL_DISTRIBUTION_LOCK_NAME, async () => {
836
- const again = installedFiles(dir, release);
929
+ const again = filesMatchPin(installedFiles(dir, release), release);
837
930
  if (again) {
838
931
  verifyFleetLocalRelease(again, release, publicKey);
839
932
  warnCompatibility(again.manifest);
@@ -849,7 +942,7 @@ export async function installPinnedFleetLocalDistribution(deps = {}) {
849
942
  const target = downloadsDir(root, release);
850
943
  let files;
851
944
  if (links) {
852
- files = await downloadFleetLocalReleaseFromHq(release, fetcher, links, cachedRuntime, target, onProgress, deps.downloadStallMs);
945
+ files = await downloadFleetLocalReleaseFromHq(release, fetcher, links, cachedRuntime, target, onProgress, deps.downloadStallMs, deps.allowFileLinks === true);
853
946
  }
854
947
  else {
855
948
  let githubToken;
@@ -1296,7 +1389,86 @@ export function removeFleetLocalBot(agentUid, deps = {}) {
1296
1389
  fs.rmSync(files.profileDir, { recursive: true, force: true });
1297
1390
  return { removed: true, credentialsRemoved: providers.length + 1 };
1298
1391
  }
1299
- export function authenticateFleetLocalBot(input, deps = {}) {
1392
+ export const spawnFleetAuth = (executable, args, onStderrLine) => new Promise((resolve, reject) => {
1393
+ const child = spawn(executable, args, { stdio: ["inherit", "pipe", "pipe"], windowsHide: true });
1394
+ let stdout = "";
1395
+ let pending = "";
1396
+ child.stdout.setEncoding("utf8");
1397
+ child.stdout.on("data", (chunk) => {
1398
+ stdout += chunk;
1399
+ });
1400
+ child.stderr.setEncoding("utf8");
1401
+ child.stderr.on("data", (chunk) => {
1402
+ pending += chunk;
1403
+ for (let at = pending.indexOf("\n"); at >= 0; at = pending.indexOf("\n")) {
1404
+ onStderrLine(pending.slice(0, at));
1405
+ pending = pending.slice(at + 1);
1406
+ }
1407
+ });
1408
+ child.on("error", reject);
1409
+ child.on("close", (code) => {
1410
+ if (pending)
1411
+ onStderrLine(pending);
1412
+ resolve({ code, stdout });
1413
+ });
1414
+ });
1415
+ export const FLEET_GROK_CLI_IMPORT_MIN_VERSION = "0.4.31-local.13";
1416
+ export function fleetReleaseImportsGrokCli(version) {
1417
+ const valid = typeof version === "string" ? semver.valid(version) : null;
1418
+ return valid !== null && semver.gte(valid, FLEET_GROK_CLI_IMPORT_MIN_VERSION);
1419
+ }
1420
+ export function fleetLocalProfileEngineVersion(agentUid, deps = {}) {
1421
+ if (!/^agt_[A-Za-z0-9_-]+$/.test(agentUid))
1422
+ return null;
1423
+ try {
1424
+ const marker = JSON.parse(fs.readFileSync(path.join(profileRoot(agentUid, deps.fleetHome ?? fleetHome()), "bootstrap.json"), "utf8"));
1425
+ return typeof marker.engine?.version === "string" ? marker.engine.version : null;
1426
+ }
1427
+ catch {
1428
+ return null;
1429
+ }
1430
+ }
1431
+ function authEventLine(line) {
1432
+ if (!line.startsWith("{"))
1433
+ return null;
1434
+ try {
1435
+ const value = JSON.parse(line);
1436
+ return value && typeof value === "object" && !Array.isArray(value) && value.event === "auth"
1437
+ ? value
1438
+ : null;
1439
+ }
1440
+ catch {
1441
+ return null;
1442
+ }
1443
+ }
1444
+ async function runAuthWithEvents(spawnAuth, executable, args, onAuthEvent, writeStderr, label) {
1445
+ let result;
1446
+ try {
1447
+ result = await spawnAuth(executable, [...args, "--json-events"], (line) => {
1448
+ const event = authEventLine(line);
1449
+ if (event)
1450
+ onAuthEvent(event);
1451
+ else
1452
+ writeStderr(`${line}\n`);
1453
+ });
1454
+ }
1455
+ catch {
1456
+ throw expectedError(`HQ Fleet Local ${label} failed.`);
1457
+ }
1458
+ if (result.code !== 0)
1459
+ throw expectedError(`HQ Fleet Local ${label} failed.`);
1460
+ try {
1461
+ const value = JSON.parse(result.stdout);
1462
+ if (!value || typeof value !== "object" || Array.isArray(value))
1463
+ throw new Error("not an object");
1464
+ return value;
1465
+ }
1466
+ catch {
1467
+ throw expectedError(`HQ Fleet Local ${label} returned an invalid result.`);
1468
+ }
1469
+ }
1470
+ export async function authenticateFleetLocalBot(input, deps = {}) {
1471
+ const control = deps.control ?? ((agentUid, action) => controlFleetLocalBot(agentUid, action, deps));
1300
1472
  const requested = input.provider.trim().toLowerCase();
1301
1473
  if (!/^[a-z0-9][a-z0-9._:-]*$/.test(requested)) {
1302
1474
  throw expectedError("HQ Fleet provider identifier is invalid.");
@@ -1308,7 +1480,7 @@ export function authenticateFleetLocalBot(input, deps = {}) {
1308
1480
  replaceProfileProvider(files.profile, input.agentUid, native);
1309
1481
  runJson(run, files.helper, ["render-profile", "--spec", files.profile, "--mode", "update"], { stdio: ["ignore", "pipe", "pipe"] }, "profile update");
1310
1482
  runJson(run, files.helper, ["doctor-profile", "--profile", files.profileDir, "--runtime", files.runtime], { stdio: ["ignore", "pipe", "pipe"] }, "profile validation");
1311
- const restarted = controlFleetLocalBot(input.agentUid, input.installService ? "install" : "restart", deps).ok === true;
1483
+ const restarted = control(input.agentUid, input.installService ? "install" : "restart").ok === true;
1312
1484
  return { provider: requested, runtimeProvider: "anthropic", model: native.model, authenticated: true, restarted };
1313
1485
  }
1314
1486
  const known = providerProfiles[requested];
@@ -1356,9 +1528,14 @@ export function authenticateFleetLocalBot(input, deps = {}) {
1356
1528
  "--base-url",
1357
1529
  baseUrl,
1358
1530
  ];
1359
- const auth = runJson(run, files.helper, authArgs, input.apiKey
1360
- ? { input: input.apiKey, stdio: ["pipe", "pipe", "pipe"] }
1361
- : { stdio: ["inherit", "pipe", "inherit"] }, `${provider.runtimeProvider} authentication`);
1531
+ const label = `${provider.runtimeProvider} authentication`;
1532
+ const streamEvents = provider.oauth && !input.apiKey && provider.runtimeProvider === "xai-oauth" && input.onAuthEvent !== undefined
1533
+ && fleetReleaseImportsGrokCli(fleetLocalProfileEngineVersion(input.agentUid, deps));
1534
+ const auth = streamEvents
1535
+ ? await runAuthWithEvents(deps.spawnAuth ?? spawnFleetAuth, files.helper, authArgs, input.onAuthEvent, deps.writeStderr ?? ((text) => { process.stderr.write(text); }), label)
1536
+ : runJson(run, files.helper, authArgs, input.apiKey
1537
+ ? { input: input.apiKey, stdio: ["pipe", "pipe", "pipe"] }
1538
+ : { stdio: ["inherit", "pipe", "inherit"] }, label);
1362
1539
  if (auth.authenticated !== true) {
1363
1540
  throw expectedError(`HQ Fleet Local could not authenticate ${provider.runtimeProvider}.`);
1364
1541
  }
@@ -1371,7 +1548,7 @@ export function authenticateFleetLocalBot(input, deps = {}) {
1371
1548
  });
1372
1549
  runJson(run, files.helper, ["render-profile", "--spec", files.profile, "--mode", "update"], { stdio: ["ignore", "pipe", "pipe"] }, "profile update");
1373
1550
  runJson(run, files.helper, ["doctor-profile", "--profile", files.profileDir, "--runtime", files.runtime], { stdio: ["ignore", "pipe", "pipe"] }, "profile validation");
1374
- const restarted = controlFleetLocalBot(input.agentUid, input.installService ? "install" : "restart", deps).ok === true;
1551
+ const restarted = control(input.agentUid, input.installService ? "install" : "restart").ok === true;
1375
1552
  return {
1376
1553
  provider: requested,
1377
1554
  runtimeProvider: provider.runtimeProvider,
@@ -1527,6 +1704,41 @@ export function fleetLocalProfileDir(agentUid, deps = {}) {
1527
1704
  }
1528
1705
  return profileRoot(agentUid, deps.fleetHome ?? fleetHome());
1529
1706
  }
1707
+ export function parseGatewayReady(value) {
1708
+ if (!value || typeof value !== "object" || Array.isArray(value))
1709
+ return { ready: false, readyAt: null };
1710
+ const at = value.at;
1711
+ return { ready: true, readyAt: typeof at === "string" && Number.isFinite(Date.parse(at)) ? at : null };
1712
+ }
1713
+ export function clearStaleFleetGatewayReady(profileDir, alive = (pid) => {
1714
+ try {
1715
+ process.kill(pid, 0);
1716
+ return true;
1717
+ }
1718
+ catch {
1719
+ return false;
1720
+ }
1721
+ }) {
1722
+ const file = path.join(profileDir, "gateway_state.json");
1723
+ let raw;
1724
+ let mode;
1725
+ try {
1726
+ raw = JSON.parse(fs.readFileSync(file, "utf8"));
1727
+ mode = fs.statSync(file).mode & 0o777;
1728
+ }
1729
+ catch {
1730
+ return false;
1731
+ }
1732
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || !parseGatewayReady(raw.ready).ready)
1733
+ return false;
1734
+ const pid = raw.pid;
1735
+ if (typeof pid === "number" && Number.isInteger(pid) && pid > 0 && alive(pid))
1736
+ return false;
1737
+ const temporary = `${file}.${process.pid}.tmp`;
1738
+ fs.writeFileSync(temporary, `${JSON.stringify({ ...raw, ready: null })}\n`, { mode });
1739
+ fs.renameSync(temporary, file);
1740
+ return true;
1741
+ }
1530
1742
  export function readFleetLocalGatewayState(agentUid, deps = {}) {
1531
1743
  let raw;
1532
1744
  try {
@@ -1551,6 +1763,7 @@ export function readFleetLocalGatewayState(agentUid, deps = {}) {
1551
1763
  gatewayState: typeof raw.gateway_state === "string" ? raw.gateway_state : null,
1552
1764
  activeAgents: Number.isFinite(active) && active > 0 ? Math.floor(active) : 0,
1553
1765
  platforms,
1766
+ ...parseGatewayReady(raw.ready),
1554
1767
  };
1555
1768
  }
1556
1769
  export function fleetLocalChannels(state, gatewayAlive) {
@@ -0,0 +1,28 @@
1
+ import type { FleetInstallProgress } from "./fleet-local.js";
2
+ export type InstallProgressPhase = "download" | "verify" | "prepare" | "unpack" | "environment" | "done";
3
+ export interface InstallProgressLine {
4
+ event: "install";
5
+ phase: InstallProgressPhase;
6
+ bytesDone: number | null;
7
+ bytesTotal: number | null;
8
+ fraction: number;
9
+ message: string;
10
+ cached?: true;
11
+ }
12
+ export declare const INSTALL_PROGRESS_INTERVAL_MS = 250;
13
+ export declare const INSTALL_PHASE_SPANS: Record<Exclude<InstallProgressPhase, "done">, readonly [number, number]>;
14
+ export declare const PREPARE_EXPECTED_MS = 15000;
15
+ export declare const PACKAGES_EXPECTED_MS = 30000;
16
+ type Timer = unknown;
17
+ export interface InstallProgressTrackerDeps {
18
+ now?: () => number;
19
+ setTimer?: (fn: () => void, ms: number) => Timer;
20
+ clearTimer?: (timer: Timer) => void;
21
+ }
22
+ export interface InstallProgressTracker {
23
+ (event: FleetInstallProgress): void;
24
+ stop(): void;
25
+ }
26
+ export declare function createInstallProgressTracker(emit: (line: InstallProgressLine) => void, deps?: InstallProgressTrackerDeps): InstallProgressTracker;
27
+ export {};
28
+ //# sourceMappingURL=install-progress.d.ts.map