@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.
- package/CHANGELOG.md +20 -0
- package/dist/command-catalog.generated.d.ts +28 -0
- package/dist/command-catalog.generated.js +34 -0
- package/dist/commands/bot-runtime.d.ts +21 -2
- package/dist/commands/bot-runtime.js +54 -9
- package/dist/commands/bot.d.ts +13 -0
- package/dist/commands/bot.js +142 -12
- package/dist/commands/daemon.js +3 -0
- package/dist/commands/whoami.js +7 -6
- package/dist/lib/bot/api.d.ts +1 -1
- package/dist/lib/bot/config.js +2 -1
- package/dist/lib/bot/fleet-daemon.d.ts +4 -0
- package/dist/lib/bot/fleet-daemon.js +12 -1
- package/dist/lib/bot/fleet-download.d.ts +6 -0
- package/dist/lib/bot/fleet-download.js +128 -3
- package/dist/lib/bot/fleet-local.d.ts +38 -1
- package/dist/lib/bot/fleet-local.js +239 -26
- package/dist/lib/bot/install-progress.d.ts +28 -0
- package/dist/lib/bot/install-progress.js +185 -0
- package/dist/lib/bot/legacy-provider-login.d.ts +22 -1
- package/dist/lib/bot/legacy-provider-login.js +67 -9
- package/dist/lib/bot/prompt.d.ts +1 -0
- package/dist/lib/bot/prompt.js +3 -2
- package/dist/lib/bot/readiness.d.ts +68 -0
- package/dist/lib/bot/readiness.js +145 -0
- package/dist/lib/bot/run.d.ts +2 -0
- package/dist/lib/bot/run.js +6 -3
- package/dist/lib/bot/scaffold.d.ts +6 -3
- package/dist/lib/bot/scaffold.js +18 -12
- package/dist/lib/daemon/run.d.ts +1 -0
- package/dist/lib/daemon/run.js +6 -1
- package/dist/lib/daemon/supervisor.d.ts +1 -0
- package/dist/lib/daemon/supervisor.js +5 -3
- package/package.json +7 -7
package/dist/commands/bot.js
CHANGED
|
@@ -52,6 +52,7 @@ import { executiveStatus } from "../lib/bot/executive-settings.js";
|
|
|
52
52
|
import { describeExecutiveBotSource, resolveExecutiveBot, setExecutiveBot } from "../lib/bot/executive.js";
|
|
53
53
|
import { executiveHotSignalSyncCompanies } from "../lib/bot/executive-sync.js";
|
|
54
54
|
import { readBotListedProcess } from "../lib/bot/listed-running.js";
|
|
55
|
+
import { DEFAULT_BOT_READY_TIMEOUT_SECONDS, botReadinessReport, clearBotSetupStep, createSetupStepReporter, readBotSetupStep, waitForGatewayReady, writeBotSetupStep, } from "../lib/bot/readiness.js";
|
|
55
56
|
import { ensureFleetHotSignalSync, fleetCronOps, migrateLegacyJobsToFleet } from "../lib/bot/fleet-cron.js";
|
|
56
57
|
import { resolvePackSetupPrompt } from "../lib/bot/pack-setup.js";
|
|
57
58
|
import { detectCodingToolActivity } from "../lib/bot/coding-tool-activity.js";
|
|
@@ -80,7 +81,8 @@ import { PROBE_DEFAULT_TIMEOUT_MS, probeBotRuntime } from "../lib/bot/probe.js";
|
|
|
80
81
|
import { BOT_LOGIN_RUNTIMES, botAuthEnv, botRuntimeAuth, capacityAccountHome, describeBotAuth, formatBotAuth, isBotLoginRuntime, restoreBotSessions, setAsideBotSessions, signInBotRuntime, signOutBotRuntime, withRuntimeAuth, } from "../lib/bot/runtime-auth.js";
|
|
81
82
|
import { BotApi, BotApiError, BOT_RESTORE_DEFAULTS, buildBotLocalConfig, describeBotLocalConfig, orphanBotRunMessage, parseBotLocalConfig, removeOrphanBotDaemon, botDaemonStatus, botDir, botCredsPath, botLogPath, botsRoot, botTokenStateDir, botWorkerRelDir, buildBotDaemonPaths, createBotLogger, deleteBotCreds, installBotDaemon, repairBotDaemonIfStale, healBotDaemonNodeFromJob, introDmText, isBotMemoryMode, botLocalMemoryDir, botMemoryMode, resolveBotMemoryDir, validateBotIntro, validateBotDisplayName, validateBotKickoff, validateBotEffort, validateBotModel, effectiveBotEffort, BOT_EFFORT_LEVELS, DEFAULT_BOT_EFFORT, BOT_MEMORY_MODES, BOT_KINDS, isBotKind, effectiveBotKind, effectiveBotCompanies, normalizeBotCompanies, SETUP_BOT_WORKER_ID, isBotRuntimeId, localNameForRemoteBot, remoteBotRunnability, isPidAlive, listBotWorkerOptions, patchBotConfig, readBotConfig, readBotCredsIdentity, readBotStatus, patchBotStatus, runtimeCrashSinceStart, resolveBotWorker, runBot, runtimeFor, scaffoldBotMemory, scaffoldBotWorker, startBotDaemon, stopBotDaemon, uninstallBotDaemon, validateBotName, writeBotConfig, writeBotCreds, BOT_RUNTIMES, BOT_INTRO_MAX_CHARS, BOT_DISPLAY_NAME_MAX_CHARS, BOT_KICKOFF_MAX_CHARS, detectBotPlatform, withBotLock, localBotRole, remoteBotRole, remoteBotDisplayName, personFacingName, writeCloudDisplayName, setupSlugFor, ASSISTANT_ROLE, HQ_FLEET_RUNTIME_ENGINE_ID, HQ_FLEET_LOCAL_RELEASE, authenticateFleetLocalBot, bootstrapFleetLocalBot, buildSystemPrompt, controlFleetBot as controlFleetLocalBot, fleetBotUnitId, fleetBotsManagedByDaemon, ensureFleetPython, fleetLocalGatewayPid, fleetLocalProfileNeedsAdoption, fleetLocalServiceInstalled, fleetProviderForRuntime, importFleetLocalMachineCredential, importFleetLocalProviderLogin, fleetProviderNeedsSignIn, fleetOwnerCompanies, refreshFleetLocalInstructions, fleetLocalPromotionRuntime, installPinnedFleetLocalDistribution, installTargetFleetLocalDistribution, resolveFleetLocalPointerTarget, resolveFleetLocalTargetRelease, fleetLocalProfileDir, fleetProfileOwnerCompanies, fleetLocalChannels, readFleetLocalGatewayState, readPromptSources, removeFleetLocalBot, } from "../lib/bot/index.js";
|
|
82
83
|
import { gatedInteractiveLogin } from "../utils/interactive-caller.js";
|
|
83
|
-
import { fleetInstallProgressReporter, runBotRuntimeInstall, runBotRuntimeStatus } from "./bot-runtime.js";
|
|
84
|
+
import { fleetInstallProgressReporter, fleetRuntimeStatus, runBotAuthStatus, runBotRuntimeInstall, runBotRuntimeStatus } from "./bot-runtime.js";
|
|
85
|
+
import { ensureFleetRuntimeInstalled } from "../lib/bot/fleet-local.js";
|
|
84
86
|
function collectRepeated(value, previous) {
|
|
85
87
|
return [...previous, value];
|
|
86
88
|
}
|
|
@@ -549,6 +551,13 @@ function rowFor(name, opts = {}) {
|
|
|
549
551
|
const legacy = fleet ? null : opts.legacy ?? legacyMoveState(dir, config, legacyConvertSeams.providerLogin(dir, config));
|
|
550
552
|
const pid = listed.pid;
|
|
551
553
|
const processAlive = listed.running;
|
|
554
|
+
const readiness = botReadinessReport({
|
|
555
|
+
setupStep: readBotSetupStep(dir),
|
|
556
|
+
fleet,
|
|
557
|
+
processAlive,
|
|
558
|
+
livePid: pid,
|
|
559
|
+
gateway: fleet ? readFleetLocalGatewayState(config.agentUid) : null,
|
|
560
|
+
});
|
|
552
561
|
// Turns this bot has taken and not finished: what "thinking" means.
|
|
553
562
|
const inflightTurns = readInflightTurns(dir);
|
|
554
563
|
let daemonInstalled = false;
|
|
@@ -576,6 +585,7 @@ function rowFor(name, opts = {}) {
|
|
|
576
585
|
effort: effectiveBotEffort(config),
|
|
577
586
|
effortIsDefault: !config.effort,
|
|
578
587
|
state: processAlive ? "running" : !fleet && status?.state === "failed" ? "failed" : "stopped",
|
|
588
|
+
...readiness,
|
|
579
589
|
pid: processAlive ? pid : null,
|
|
580
590
|
processAlive,
|
|
581
591
|
hosting: hasActivePromotion(dir, config.agentUid, config.ownerUid) ? "cloud" : "local",
|
|
@@ -647,6 +657,8 @@ async function decorateOnline(rows) {
|
|
|
647
657
|
}));
|
|
648
658
|
}
|
|
649
659
|
function humanOnline(row) {
|
|
660
|
+
if (row.readiness === "creating" || row.readiness === "installing" || row.readiness === "starting")
|
|
661
|
+
return chalk.yellow(row.readiness);
|
|
650
662
|
if (row.lastHeartbeatOk === false)
|
|
651
663
|
return chalk.red("unreachable");
|
|
652
664
|
if (row.online === true)
|
|
@@ -848,6 +860,9 @@ async function convertLegacyBotToFleet(name, dir, config, from) {
|
|
|
848
860
|
};
|
|
849
861
|
if (from === "start")
|
|
850
862
|
await stopBot(name, dir, config, "silent");
|
|
863
|
+
const daemonRunsIt = fleetBotsManagedByDaemon();
|
|
864
|
+
if (daemonRunsIt)
|
|
865
|
+
writeBotConfig(dir, fleet);
|
|
851
866
|
let failure = null;
|
|
852
867
|
try {
|
|
853
868
|
refreshFleetLocalInstructions(config.agentUid, fleetBotSystemPrompt(name, fleet));
|
|
@@ -865,6 +880,8 @@ async function convertLegacyBotToFleet(name, dir, config, from) {
|
|
|
865
880
|
catch {
|
|
866
881
|
/* nothing was running */
|
|
867
882
|
}
|
|
883
|
+
if (daemonRunsIt)
|
|
884
|
+
writeBotConfig(dir, current);
|
|
868
885
|
keepLegacy("start", failure);
|
|
869
886
|
return ready();
|
|
870
887
|
}
|
|
@@ -1027,7 +1044,7 @@ async function installFleetRuntimeProfile(name, dir, config, opts = {}) {
|
|
|
1027
1044
|
installation = await installTargetFleetLocalDistribution({ target, onProgress: progress });
|
|
1028
1045
|
}
|
|
1029
1046
|
catch (err) {
|
|
1030
|
-
if (target.source !== "pointer")
|
|
1047
|
+
if (target.source !== "pointer" || target.localFile)
|
|
1031
1048
|
throw err;
|
|
1032
1049
|
if (opts.pointerOnly) {
|
|
1033
1050
|
createBotLogger(dir)("warn", `could not install HQ Fleet Local ${target.release.version} (${err instanceof Error ? err.message : String(err)}); the bot stays on its current release`);
|
|
@@ -1069,6 +1086,9 @@ async function installFleetRuntimeProfile(name, dir, config, opts = {}) {
|
|
|
1069
1086
|
export const botCreateSeams = {
|
|
1070
1087
|
/** The Claude Code login read the way the HQ Fleet Runtime reads it. */
|
|
1071
1088
|
claudeLogin: () => checkClaudeCodeLogin(),
|
|
1089
|
+
runtimeStatus: fleetRuntimeStatus,
|
|
1090
|
+
installRuntime: ensureFleetRuntimeInstalled,
|
|
1091
|
+
waitForReady: waitForGatewayReady,
|
|
1072
1092
|
};
|
|
1073
1093
|
/**
|
|
1074
1094
|
* A Claude bot on the HQ Fleet Runtime answers with the owner's Claude Code
|
|
@@ -1232,6 +1252,15 @@ export function resolveCreateKind(opts, worker) {
|
|
|
1232
1252
|
}
|
|
1233
1253
|
return { kind, companies };
|
|
1234
1254
|
}
|
|
1255
|
+
function removeEmptyDir(dir) {
|
|
1256
|
+
try {
|
|
1257
|
+
if (fs.readdirSync(dir).length === 0)
|
|
1258
|
+
fs.rmdirSync(dir);
|
|
1259
|
+
}
|
|
1260
|
+
catch {
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1235
1264
|
/**
|
|
1236
1265
|
* `hq bot create`. Runs under the bot's lock, so a create racing an adopt,
|
|
1237
1266
|
* restore, rm or set of the same bot waits for it instead of tripping over
|
|
@@ -1240,7 +1269,16 @@ export function resolveCreateKind(opts, worker) {
|
|
|
1240
1269
|
export async function runBotCreate(nameArg, opts) {
|
|
1241
1270
|
try {
|
|
1242
1271
|
const name = validateBotName(nameArg);
|
|
1243
|
-
|
|
1272
|
+
const dir = botDir(name);
|
|
1273
|
+
const dirExisted = fs.existsSync(dir);
|
|
1274
|
+
try {
|
|
1275
|
+
await withBotLock(name, () => runBotCreateLocked(name, opts), { command: "hq bot create" });
|
|
1276
|
+
}
|
|
1277
|
+
finally {
|
|
1278
|
+
clearBotSetupStep(dir);
|
|
1279
|
+
if (!dirExisted)
|
|
1280
|
+
removeEmptyDir(dir);
|
|
1281
|
+
}
|
|
1244
1282
|
}
|
|
1245
1283
|
catch (err) {
|
|
1246
1284
|
// Under --json the desktop app reads stdout: a failure, including one in
|
|
@@ -1362,6 +1400,31 @@ async function finishExistingSetupBot(name, dir, config, displayName, opts) {
|
|
|
1362
1400
|
else if (opts.start !== false)
|
|
1363
1401
|
console.log(chalk.yellow(`${name} did not report running within 15s`) + chalk.dim(` logs: hq bot logs ${name}`));
|
|
1364
1402
|
}
|
|
1403
|
+
export function parseReadyTimeoutSeconds(value) {
|
|
1404
|
+
if (value === undefined)
|
|
1405
|
+
return DEFAULT_BOT_READY_TIMEOUT_SECONDS;
|
|
1406
|
+
const seconds = typeof value === "number" ? value : Number(String(value).trim());
|
|
1407
|
+
if (!Number.isInteger(seconds) || seconds < 1 || seconds > 3600) {
|
|
1408
|
+
throw Object.assign(new Error("--ready-timeout must be a whole number of seconds from 1 to 3600."), { expected: true });
|
|
1409
|
+
}
|
|
1410
|
+
return seconds;
|
|
1411
|
+
}
|
|
1412
|
+
export function createReadyMessage(name, readiness, wait, timeoutMs) {
|
|
1413
|
+
if (readiness === "ready")
|
|
1414
|
+
return `${name} is ready to chat.`;
|
|
1415
|
+
if (wait?.failed)
|
|
1416
|
+
return `${name} could not start: ${wait.failed}. See its logs with hq bot logs ${name}, then run hq bot restart ${name}.`;
|
|
1417
|
+
if (wait?.timedOut) {
|
|
1418
|
+
return `${name} is still getting ready after ${Math.round(timeoutMs / 1000)} seconds. It finishes on its own; check with hq bot status ${name}.`;
|
|
1419
|
+
}
|
|
1420
|
+
return null;
|
|
1421
|
+
}
|
|
1422
|
+
function createReadyLine(name, readiness, wait, timeoutMs) {
|
|
1423
|
+
const message = createReadyMessage(name, readiness, wait, timeoutMs);
|
|
1424
|
+
if (!message)
|
|
1425
|
+
return null;
|
|
1426
|
+
return readiness === "ready" ? chalk.green(message) : chalk.yellow(message);
|
|
1427
|
+
}
|
|
1365
1428
|
async function runBotCreateLocked(name, opts) {
|
|
1366
1429
|
if (opts.legacyRuntime) {
|
|
1367
1430
|
throw Object.assign(new Error("--legacy-runtime is no longer supported: new bots run on the HQ Fleet Runtime. Drop --legacy-runtime."), { expected: true });
|
|
@@ -1521,10 +1584,20 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1521
1584
|
// of sending another create that the entity store will reject.
|
|
1522
1585
|
if (isSetupBot && (await adoptOwnedSetupBot(true)))
|
|
1523
1586
|
return;
|
|
1524
|
-
const
|
|
1525
|
-
const
|
|
1587
|
+
const readyTimeoutMs = parseReadyTimeoutSeconds(opts.readyTimeout) * 1000;
|
|
1588
|
+
const progress = fleetInstallProgressReporter(opts.json ? (opts.progress ? "json" : "silent") : "text");
|
|
1589
|
+
const steps = createSetupStepReporter(opts.json ? (opts.progress ? "json" : "silent") : "text");
|
|
1590
|
+
const fleetTarget = await resolveFleetLocalTargetRelease();
|
|
1591
|
+
const runtimeStatus = await botCreateSeams.runtimeStatus({ target: fleetTarget });
|
|
1592
|
+
if (!opts.json)
|
|
1593
|
+
console.log(chalk.dim(`Setting up ${name} takes ${runtimeStatus.estimate}.`));
|
|
1594
|
+
steps.begin("install");
|
|
1595
|
+
const fleetInstallation = await installTargetFleetLocalDistribution({ target: fleetTarget, onProgress: progress });
|
|
1526
1596
|
progress({ phase: "python" });
|
|
1527
1597
|
const fleetPython = await ensureFleetPython();
|
|
1598
|
+
await botCreateSeams.installRuntime(fleetInstallation, { python: fleetPython, onProgress: progress });
|
|
1599
|
+
steps.finish("install", runtimeStatus.installed ? "skipped" : "done");
|
|
1600
|
+
steps.begin("identity");
|
|
1528
1601
|
const ownerCompanies = kind === "personal" ? await fleetOwnerCompanies() : companies;
|
|
1529
1602
|
// A company bot's companies are resolved first (a typo must not cost an
|
|
1530
1603
|
// identity) and sent with the create: the server makes the bot a member of
|
|
@@ -1595,6 +1668,7 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1595
1668
|
throw err;
|
|
1596
1669
|
}
|
|
1597
1670
|
const agentUid = created.agent.uid;
|
|
1671
|
+
steps.identify(agentUid);
|
|
1598
1672
|
writeBotCreds(dir, {
|
|
1599
1673
|
username: created.identity.cognitoUsername,
|
|
1600
1674
|
secret: created.identity.secret,
|
|
@@ -1603,6 +1677,7 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1603
1677
|
clientId: DEFAULT_COGNITO.clientId,
|
|
1604
1678
|
region: DEFAULT_COGNITO.region,
|
|
1605
1679
|
});
|
|
1680
|
+
const daemonRunsFleetBots = fleetBotsManagedByDaemon();
|
|
1606
1681
|
const config = {
|
|
1607
1682
|
v: 1,
|
|
1608
1683
|
name,
|
|
@@ -1639,8 +1714,10 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1639
1714
|
createdAt: new Date().toISOString(),
|
|
1640
1715
|
enabled: !fleetAuthPending,
|
|
1641
1716
|
...(fleetAuthPending ? { fleetAuthPending: true } : {}),
|
|
1717
|
+
...(daemonRunsFleetBots ? { fleetServiceInstallPending: true } : {}),
|
|
1642
1718
|
};
|
|
1643
1719
|
writeBotConfig(dir, config);
|
|
1720
|
+
writeBotSetupStep(dir, "identity");
|
|
1644
1721
|
// A company bot acts as itself, so it must be a member of each of its
|
|
1645
1722
|
// companies. Only the companies it actually joined are recorded, so after a failed invite the identity
|
|
1646
1723
|
// and bot.json stay on disk and `hq bot companies <name> --add <slug>`
|
|
@@ -1662,15 +1739,19 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1662
1739
|
}
|
|
1663
1740
|
// A worker-sourced bot never writes into the company tree: only its own
|
|
1664
1741
|
// memory folder is scaffolded.
|
|
1665
|
-
const scaffoldOpts = { memoryDir: config.memoryDir };
|
|
1742
|
+
const scaffoldOpts = { memoryDir: config.memoryDir, ...(config.displayName ? { displayName: config.displayName } : {}) };
|
|
1666
1743
|
const scaffold = worker
|
|
1667
1744
|
? scaffoldBotMemory(hqRoot, name, undefined, scaffoldOpts)
|
|
1668
1745
|
: scaffoldBotWorker(hqRoot, name, agentUid, HQ_FLEET_RUNTIME_ENGINE_ID, undefined, scaffoldOpts);
|
|
1669
1746
|
fs.rmSync(path.join(dir, "status.json"), { force: true });
|
|
1670
|
-
const introText = introDmText(name, runtime, intro, { kind, companies });
|
|
1747
|
+
const introText = introDmText(name, runtime, intro, { kind, companies, ...(config.displayName ? { displayName: config.displayName } : {}) });
|
|
1671
1748
|
const toolOffer = isSetupBot && kickoff ? fleetSetupToolOffer(dir, config) : null;
|
|
1672
1749
|
const startNow = opts.start !== false && !fleetAuthPending;
|
|
1673
|
-
|
|
1750
|
+
steps.finish("identity", "done");
|
|
1751
|
+
if (startNow) {
|
|
1752
|
+
steps.begin("starting");
|
|
1753
|
+
writeBotSetupStep(dir, "starting");
|
|
1754
|
+
}
|
|
1674
1755
|
const fleetBootstrap = await bootstrapFleetLocalBot({
|
|
1675
1756
|
agentUid,
|
|
1676
1757
|
ownerUid: config.ownerUid,
|
|
@@ -1692,6 +1773,22 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1692
1773
|
syncFleetRuntimeJobs(name, dir, config);
|
|
1693
1774
|
const startedByDaemon = startNow && daemonRunsFleetBots && controlFleetLocalBot(agentUid, "install").ok === true;
|
|
1694
1775
|
const running = fleetBootstrap.running || startedByDaemon;
|
|
1776
|
+
let readyWait = null;
|
|
1777
|
+
if (!startNow) {
|
|
1778
|
+
steps.finish("starting", "skipped");
|
|
1779
|
+
steps.finish("ready", "skipped");
|
|
1780
|
+
}
|
|
1781
|
+
else if (!running) {
|
|
1782
|
+
steps.finish("starting", "failed");
|
|
1783
|
+
steps.finish("ready", "skipped");
|
|
1784
|
+
}
|
|
1785
|
+
else {
|
|
1786
|
+
steps.finish("starting", "done");
|
|
1787
|
+
steps.begin("ready");
|
|
1788
|
+
readyWait = await botCreateSeams.waitForReady(agentUid, { timeoutMs: readyTimeoutMs });
|
|
1789
|
+
steps.finish("ready", readyWait.ready ? "done" : readyWait.failed ? "failed" : "timeout");
|
|
1790
|
+
}
|
|
1791
|
+
const readiness = !startNow || !running || readyWait?.failed ? "offline" : readyWait?.ready ? "ready" : "starting";
|
|
1695
1792
|
const fleetProfile = fleetBootstrap.profile;
|
|
1696
1793
|
const runtimeLabel = HQ_FLEET_RUNTIME_ENGINE_ID;
|
|
1697
1794
|
createBotLogger(dir)("info", `created ${name} (${agentUid}) kind=${kind}${companies.length ? ` companies=${companies.join(",")}` : ""} runtime=${runtimeLabel}${worker ? ` worker=${worker.id} company=${worker.company ?? "-"}` : ""} memory=${memoryMode}`);
|
|
@@ -1734,6 +1831,9 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1734
1831
|
if (fleetAuthPending) {
|
|
1735
1832
|
console.log(chalk.yellow(` sign it in before it can answer: hq bot auth ${name} --provider ${runtime === "grok" ? "grok" : "chatgpt"}`));
|
|
1736
1833
|
}
|
|
1834
|
+
const readyLine = createReadyLine(name, readiness, readyWait, readyTimeoutMs);
|
|
1835
|
+
if (readyLine)
|
|
1836
|
+
console.log(readyLine);
|
|
1737
1837
|
}
|
|
1738
1838
|
if (opts.json) {
|
|
1739
1839
|
const status = readBotStatus(dir);
|
|
@@ -1744,6 +1844,14 @@ async function runBotCreateLocked(name, opts) {
|
|
|
1744
1844
|
daemon: null,
|
|
1745
1845
|
running,
|
|
1746
1846
|
how: startedByDaemon ? "started by hq daemon" : fleetBootstrap.running ? "started by the HQ Fleet Runtime" : null,
|
|
1847
|
+
steps: steps.steps(),
|
|
1848
|
+
readiness,
|
|
1849
|
+
ready: readiness === "ready",
|
|
1850
|
+
readyAt: readyWait?.readyAt ?? null,
|
|
1851
|
+
readyWait: readyWait
|
|
1852
|
+
? { timedOut: readyWait.timedOut, failed: readyWait.failed, waitedMs: readyWait.waitedMs, timeoutMs: readyTimeoutMs }
|
|
1853
|
+
: null,
|
|
1854
|
+
message: createReadyMessage(name, readiness, readyWait, readyTimeoutMs),
|
|
1747
1855
|
state: status?.state ?? "unknown",
|
|
1748
1856
|
pid: status?.pid ?? null,
|
|
1749
1857
|
lastError: status?.lastError ?? null,
|
|
@@ -2112,6 +2220,7 @@ async function runBotStatus(nameArg, opts) {
|
|
|
2112
2220
|
console.log(` worker: ${row.workerId}${row.companySlug ? ` (company ${row.companySlug})` : ""} ${chalk.dim(row.workerDir)}`);
|
|
2113
2221
|
console.log(` memory: ${row.memory} ${chalk.dim(row.memoryDir)}`);
|
|
2114
2222
|
console.log(` process: ${row.processAlive ? chalk.green(`running (pid ${row.pid})`) : chalk.gray(row.state)}`);
|
|
2223
|
+
console.log(` readiness: ${row.readiness === "ready" ? chalk.green(`ready${row.readyAt ? ` since ${row.readyAt}` : ""}`) : row.readiness === "offline" ? chalk.gray("offline") : chalk.yellow(row.readiness)}`);
|
|
2115
2224
|
if (row.needsSignIn)
|
|
2116
2225
|
console.log(` sign-in: required (${row.authCommand})`);
|
|
2117
2226
|
if (row.brainUsage.state === "exhausted") {
|
|
@@ -2947,7 +3056,7 @@ export async function runBotIntro(nameArg) {
|
|
|
2947
3056
|
if (hasPromotionHold(dir))
|
|
2948
3057
|
throw new Error("This bot is held for cloud promotion. Continue its promotion before changing local settings or lifecycle.");
|
|
2949
3058
|
const api = new BotApi({ token: botTokenSupplier(dir) });
|
|
2950
|
-
await api.sendDm({ toPersonUid: config.ownerUid, body: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config) }) });
|
|
3059
|
+
await api.sendDm({ toPersonUid: config.ownerUid, body: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config), ...(config.displayName ? { displayName: config.displayName } : {}) }) });
|
|
2951
3060
|
patchBotConfig(dir, { introSentAt: new Date().toISOString() });
|
|
2952
3061
|
console.log(chalk.green(`${name} introduced itself to you.`));
|
|
2953
3062
|
}
|
|
@@ -3034,8 +3143,9 @@ export async function runBotAuth(nameArg, opts) {
|
|
|
3034
3143
|
process.on("SIGINT", keepAliveOnInterrupt);
|
|
3035
3144
|
let result;
|
|
3036
3145
|
try {
|
|
3037
|
-
result = authenticateFleetLocalBot({
|
|
3146
|
+
result = await authenticateFleetLocalBot({
|
|
3038
3147
|
agentUid: b.config.agentUid,
|
|
3148
|
+
...(opts.json ? { onAuthEvent: (event) => { console.log(JSON.stringify(event)); } } : {}),
|
|
3039
3149
|
provider: opts.provider,
|
|
3040
3150
|
...(adopted || legacy || b.config.fleetAuthPending === true ? { installService: true } : {}),
|
|
3041
3151
|
...(opts.model ? { model: opts.model } : {}),
|
|
@@ -3043,6 +3153,16 @@ export async function runBotAuth(nameArg, opts) {
|
|
|
3043
3153
|
...(opts.baseUrl ? { baseUrl: opts.baseUrl } : {}),
|
|
3044
3154
|
...(opts.transport ? { transport: opts.transport } : {}),
|
|
3045
3155
|
openBrowser: opts.browser !== false,
|
|
3156
|
+
}, {
|
|
3157
|
+
control: (agentUid, action) => {
|
|
3158
|
+
if (fleetBotsManagedByDaemon()) {
|
|
3159
|
+
if (legacy && engine)
|
|
3160
|
+
writeBotConfig(b.dir, { ...(readBotConfig(b.dir) ?? legacy), engine });
|
|
3161
|
+
else if (b.config.fleetAuthPending === true)
|
|
3162
|
+
patchBotConfig(b.dir, { fleetAuthPending: false });
|
|
3163
|
+
}
|
|
3164
|
+
return controlFleetLocalBot(agentUid, action);
|
|
3165
|
+
},
|
|
3046
3166
|
});
|
|
3047
3167
|
if (result.authenticated !== true)
|
|
3048
3168
|
throw Object.assign(new Error("The provider has not completed sign-in."), { expected: true });
|
|
@@ -3058,6 +3178,8 @@ export async function runBotAuth(nameArg, opts) {
|
|
|
3058
3178
|
catch {
|
|
3059
3179
|
/* nothing was running */
|
|
3060
3180
|
}
|
|
3181
|
+
if (fleetBotsManagedByDaemon())
|
|
3182
|
+
writeBotConfig(b.dir, legacy);
|
|
3061
3183
|
await startBot(b.name, b.dir, legacy, "silent", {}, { keepLegacy: true }).catch(() => undefined);
|
|
3062
3184
|
}
|
|
3063
3185
|
throw err;
|
|
@@ -3369,7 +3491,7 @@ async function adoptRemoteBotLocked(input) {
|
|
|
3369
3491
|
if (fleetInstallation)
|
|
3370
3492
|
config.engine = fleetInstallation.engine;
|
|
3371
3493
|
writeBotConfig(dir, config);
|
|
3372
|
-
const scaffoldOpts = { memoryDir: config.memoryDir };
|
|
3494
|
+
const scaffoldOpts = { memoryDir: config.memoryDir, ...(config.displayName ? { displayName: config.displayName } : {}) };
|
|
3373
3495
|
const scaffold = config.workerSource === "worker"
|
|
3374
3496
|
? scaffoldBotMemory(input.hqRoot, name, undefined, scaffoldOpts)
|
|
3375
3497
|
: scaffoldBotWorker(input.hqRoot, name, bot.agentUid, config.runtime, undefined, scaffoldOpts);
|
|
@@ -3388,7 +3510,7 @@ async function adoptRemoteBotLocked(input) {
|
|
|
3388
3510
|
...(input.preserveFirstStart
|
|
3389
3511
|
? {
|
|
3390
3512
|
firstStart: {
|
|
3391
|
-
intro: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config) }),
|
|
3513
|
+
intro: introDmText(name, config.runtime, config.intro, { kind: effectiveBotKind(config), companies: effectiveBotCompanies(config), ...(config.displayName ? { displayName: config.displayName } : {}) }),
|
|
3392
3514
|
...(config.kickoff ? { kickoff: config.kickoff } : {}),
|
|
3393
3515
|
},
|
|
3394
3516
|
}
|
|
@@ -3716,6 +3838,8 @@ export function registerBotCommand(program) {
|
|
|
3716
3838
|
.option("--memory <where>", "Where the bot keeps its memory: synced (personal/workers/<name>/memory in HQ) or local (~/.hq/bots/<name>/memory, this computer only)", "synced")
|
|
3717
3839
|
.option("--no-daemon", "Accepted for compatibility; HQ Fleet bots run under their own background service")
|
|
3718
3840
|
.option("--no-start", "Create without starting")
|
|
3841
|
+
.option("--ready-timeout <seconds>", `How long to wait for the bot to be ready to chat before returning (default ${DEFAULT_BOT_READY_TIMEOUT_SECONDS})`)
|
|
3842
|
+
.option("--progress", "With --json: print each setup step and download progress as one JSON line before the final document")
|
|
3719
3843
|
.option("--json", "Print machine-readable JSON")
|
|
3720
3844
|
.action((name, opts) => wrap(() => runBotCreate(name, opts))());
|
|
3721
3845
|
bot
|
|
@@ -3802,6 +3926,12 @@ export function registerBotCommand(program) {
|
|
|
3802
3926
|
.option("--no-browser", "Do not open a browser during device authorization")
|
|
3803
3927
|
.option("--json", "Print machine-readable JSON")
|
|
3804
3928
|
.action((name, opts) => wrap(async () => { await runBotAuth(name, opts); })());
|
|
3929
|
+
bot
|
|
3930
|
+
.command("auth-status")
|
|
3931
|
+
.description("Say whether a Fleet bot created now would need its own ChatGPT or Grok sign-in, or reuse a login already on this computer")
|
|
3932
|
+
.requiredOption("--provider <provider>", "Provider: chatgpt or grok")
|
|
3933
|
+
.option("--json", "Print machine-readable JSON: { signedIn }")
|
|
3934
|
+
.action((opts) => wrap(async () => { await runBotAuthStatus(opts); })());
|
|
3805
3935
|
bot
|
|
3806
3936
|
.command("logs <name>")
|
|
3807
3937
|
.description("Show the bot's log")
|
package/dist/commands/daemon.js
CHANGED
|
@@ -194,6 +194,9 @@ function hostFor(d, paths, pathEnv) {
|
|
|
194
194
|
env.PATH = d.env.PATH;
|
|
195
195
|
if (d.env.HQ_DAEMON_DIR)
|
|
196
196
|
env.HQ_DAEMON_DIR = d.env.HQ_DAEMON_DIR;
|
|
197
|
+
const pointerFile = d.env.HQ_FLEET_RELEASE_POINTER_FILE?.trim();
|
|
198
|
+
if (pointerFile)
|
|
199
|
+
env.HQ_FLEET_RELEASE_POINTER_FILE = path.resolve(pointerFile);
|
|
197
200
|
return {
|
|
198
201
|
platform: d.platform,
|
|
199
202
|
home: d.home,
|
package/dist/commands/whoami.js
CHANGED
|
@@ -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
|
-
|
|
103
|
-
|
|
104
|
-
|
|
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
|
|
143
|
-
|
|
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;
|
package/dist/lib/bot/api.d.ts
CHANGED
|
@@ -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;
|
package/dist/lib/bot/config.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
65
|
-
|
|
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);
|