@nathanstephenson/flow 0.1.0 → 0.1.2
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/README.md +10 -2
- package/dist/backend/fake/index.js +3 -1
- package/dist/backend/pi/effort-capabilities.js +12 -0
- package/dist/backend/pi/index.js +25 -36
- package/dist/backend/pi/workflow-subagent.js +8 -3
- package/dist/build-id +1 -1
- package/dist/cli/application.js +9 -1
- package/dist/cli/bootstrap.js +424 -37
- package/dist/cli/host-control.js +2 -2
- package/dist/cli/install-guard.js +57 -11
- package/dist/cli/systemd-update.js +129 -0
- package/dist/cli/update.js +64 -17
- package/dist/cli/web-update.js +376 -0
- package/dist/client/model-choices.js +22 -4
- package/dist/client/reduce.js +18 -6
- package/dist/client/status.js +34 -20
- package/dist/client/workflow-effort.js +30 -0
- package/dist/daemon/credential-redaction.js +97 -4
- package/dist/daemon/host-control-routes.js +18 -2
- package/dist/daemon/host.js +341 -74
- package/dist/daemon/release-checker.js +104 -0
- package/dist/daemon/runtime.js +12 -4
- package/dist/daemon/server.js +98 -15
- package/dist/daemon/summariser.js +81 -15
- package/dist/daemon/update-api.js +3 -0
- package/dist/daemon/workflow-executions.js +146 -15
- package/dist/protocol/update.js +1 -0
- package/dist/tui/app.js +104 -10
- package/dist/tui/keys.js +46 -10
- package/dist/tui/render.js +58 -13
- package/dist/workflows/records.js +3 -1
- package/dist/workflows/scheduler.js +15 -1
- package/package.json +1 -1
- package/web/dist/apple-touch-icon.png +0 -0
- package/web/dist/assets/index-BlZBshi8.js +170 -0
- package/web/dist/assets/index-DWF4-3Fh.css +2 -0
- package/web/dist/assets/{settings-mcp-CcT0ADJR.js → settings-mcp-ZMIfuuZU.js} +1 -1
- package/web/dist/assets/{settings-secrets-CK4uF7fd.js → settings-secrets-CgTrBpi2.js} +1 -1
- package/web/dist/assets/settings-workflows-1DMYfZtn.js +23 -0
- package/web/dist/assets/{workflows-D4T4Gy_7.css → workflows-9aO6cptD.css} +1 -1
- package/web/dist/assets/workflows-CBuB_bva.js +7 -0
- package/web/dist/assets/workflows-pane-DPXGg0na.js +1 -0
- package/web/dist/favicon-16x16.png +0 -0
- package/web/dist/favicon-32x32.png +0 -0
- package/web/dist/favicon.ico +0 -0
- package/web/dist/favicon.svg +8 -0
- package/web/dist/index.html +8 -3
- package/web/dist/safari-pinned-tab.svg +4 -0
- package/web/dist/assets/index-BC0gLS53.js +0 -106
- package/web/dist/assets/index-CCeZYKES.css +0 -2
- package/web/dist/assets/settings-workflows-CrbZF-nM.js +0 -23
- package/web/dist/assets/workflow-editors-naPqAmYO.js +0 -65
- package/web/dist/assets/workflows-hh6ioeEA.js +0 -7
- package/web/dist/assets/workflows-pane-Db-MHf7Z.js +0 -1
package/dist/cli/bootstrap.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli/bootstrap.ts
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
|
-
import { resolve as resolve3, join as
|
|
5
|
+
import { resolve as resolve3, join as join7 } from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
|
|
8
8
|
// src/cli/install-guard.ts
|
|
@@ -55,11 +55,11 @@ async function getHostStatus(host) {
|
|
|
55
55
|
if (status.instanceId !== host.instanceId || status.pid !== host.pid) throw new Error("Session Host identity changed");
|
|
56
56
|
return status;
|
|
57
57
|
}
|
|
58
|
-
async function requestHostStop(host, force) {
|
|
58
|
+
async function requestHostStop(host, force, quiesce = false) {
|
|
59
59
|
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
60
60
|
method: "POST",
|
|
61
61
|
headers: { authorization: `Bearer ${host.token}`, "content-type": "application/json" },
|
|
62
|
-
body: JSON.stringify({ instanceId: host.instanceId, force }),
|
|
62
|
+
body: JSON.stringify({ instanceId: host.instanceId, force, quiesce }),
|
|
63
63
|
signal: AbortSignal.timeout(5e3)
|
|
64
64
|
});
|
|
65
65
|
if (!response.ok) throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|
|
@@ -185,21 +185,53 @@ function registryExists(slot) {
|
|
|
185
185
|
throw error;
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
|
-
function
|
|
188
|
+
function updateIneligibility(slot, uid = process.getuid?.()) {
|
|
189
189
|
slot = resolve(slot);
|
|
190
190
|
const prefix = resolve(slot, "../../../..");
|
|
191
|
-
|
|
192
|
-
if (
|
|
191
|
+
if (slot !== join3(prefix, "lib/node_modules", packageName)) return "source";
|
|
192
|
+
if (uid === void 0 || uid === 0) return "root";
|
|
193
193
|
for (const path of [prefix, join3(prefix, "lib"), join3(prefix, "lib/node_modules"), join3(prefix, "lib/node_modules/@nathanstephenson"), slot]) {
|
|
194
194
|
const stat = lstatSync(path);
|
|
195
|
-
if (stat.isSymbolicLink()
|
|
195
|
+
if (stat.isSymbolicLink()) return "npm-link";
|
|
196
|
+
if (stat.uid !== uid) return "system";
|
|
197
|
+
if ((stat.mode & 18) !== 0) return "shared";
|
|
196
198
|
}
|
|
197
199
|
for (let path = dirname(prefix); ; path = dirname(path)) {
|
|
198
200
|
const stat = lstatSync(path);
|
|
199
|
-
if (stat.isSymbolicLink()
|
|
201
|
+
if (stat.isSymbolicLink()) return "npm-link";
|
|
202
|
+
if (stat.uid !== 0 && stat.uid !== uid) return "system";
|
|
203
|
+
if ((stat.mode & 18) !== 0 && (stat.mode & 512) === 0) return "shared";
|
|
200
204
|
if (dirname(path) === path) break;
|
|
201
205
|
}
|
|
202
|
-
return realpathSync3(prefix) === prefix;
|
|
206
|
+
return realpathSync3(prefix) === prefix ? void 0 : "npm-link";
|
|
207
|
+
}
|
|
208
|
+
function pathHasSymlink(path) {
|
|
209
|
+
for (let current = resolve(path); ; current = dirname(current)) {
|
|
210
|
+
try {
|
|
211
|
+
if (lstatSync(current).isSymbolicLink()) return true;
|
|
212
|
+
} catch (error) {
|
|
213
|
+
if (error.code !== "ENOENT") throw error;
|
|
214
|
+
}
|
|
215
|
+
if (dirname(current) === current) return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
function updateUnsupportedReason(kind) {
|
|
219
|
+
return {
|
|
220
|
+
source: "A source checkout cannot update itself. Install or update Flow through a private global npm prefix.",
|
|
221
|
+
"npm-link": "An npm-linked Flow checkout cannot update itself. Remove the link and install Flow in a private global npm prefix.",
|
|
222
|
+
sea: "Single-executable Flow builds cannot update themselves. Install the new binary manually.",
|
|
223
|
+
shared: "A shared or group/other-writable global npm installation cannot update itself. Use a private, user-owned npm prefix without sudo.",
|
|
224
|
+
system: "A system-owned or another user's global npm installation cannot update itself. Install Flow in your own private npm prefix without sudo.",
|
|
225
|
+
root: "A root-owned or sudo-installed Flow cannot update itself. Install Flow as your normal user in a private npm prefix."
|
|
226
|
+
}[kind];
|
|
227
|
+
}
|
|
228
|
+
function explainUnsupportedUpdate(slot, entry = process.argv[1], uid = process.getuid?.()) {
|
|
229
|
+
let kind = updateIneligibility(slot, uid) ?? "source";
|
|
230
|
+
if (kind === "source" && entry && pathHasSymlink(entry)) kind = "npm-link";
|
|
231
|
+
return updateUnsupportedReason(kind);
|
|
232
|
+
}
|
|
233
|
+
function updateEligible(slot) {
|
|
234
|
+
return updateIneligibility(slot) === void 0;
|
|
203
235
|
}
|
|
204
236
|
function installation(slot) {
|
|
205
237
|
slot = resolve(slot);
|
|
@@ -302,13 +334,15 @@ function installation(slot) {
|
|
|
302
334
|
} };
|
|
303
335
|
});
|
|
304
336
|
}
|
|
305
|
-
async function beginUpdate(lease, previous, host) {
|
|
337
|
+
async function beginUpdate(lease, previous, host, systemdArgs) {
|
|
306
338
|
const barrier = { pid: process.pid, id: randomUUID2(), phase: "preparing", previous };
|
|
307
339
|
await locked(() => {
|
|
308
340
|
if (readBarrier(barrierPath)) throw new Error(`Update already blocked: ${barrierPath}`);
|
|
309
341
|
const active = leases();
|
|
310
342
|
if (!active.some((other) => other.id === lease.id && other.pid === process.pid && other.root === lease.root)) throw new Error("Update process has no installation lease");
|
|
311
|
-
|
|
343
|
+
const selected = host && active.find((other) => other.pid === host.pid && other.root === lease.root);
|
|
344
|
+
if (systemdArgs && selected && JSON.stringify(selected.args) !== JSON.stringify(systemdArgs)) throw new Error("Configured systemd hostArgs do not match the running Session Host; correct systemd-update.json before updating");
|
|
345
|
+
if (active.some((other) => other.id !== lease.id && !(host && other.pid === host.pid && other.root === lease.root && (systemdArgs ? JSON.stringify(other.args) === JSON.stringify(systemdArgs) : other.args.includes("--background-host"))))) throw new Error("Stop all other Flow hosts and CLI/TUI clients using this installation first");
|
|
312
346
|
if (host && !active.some((other) => other.pid === host.pid && other.root === lease.root)) throw new Error("Stop all pre-guard Flow processes before updating");
|
|
313
347
|
save(barrier);
|
|
314
348
|
});
|
|
@@ -357,8 +391,8 @@ function installation(slot) {
|
|
|
357
391
|
|
|
358
392
|
// src/cli/update.ts
|
|
359
393
|
import { execFileSync } from "node:child_process";
|
|
360
|
-
import { accessSync, constants as constants2, readFileSync as
|
|
361
|
-
import { delimiter, join as
|
|
394
|
+
import { accessSync, constants as constants2, readFileSync as readFileSync4, realpathSync as realpathSync4 } from "node:fs";
|
|
395
|
+
import { delimiter, join as join5, resolve as resolve2 } from "node:path";
|
|
362
396
|
|
|
363
397
|
// src/cli/install-process.ts
|
|
364
398
|
import { spawn as spawn2 } from "node:child_process";
|
|
@@ -403,6 +437,155 @@ async function replacePackage(npm, prefix, packageSpec) {
|
|
|
403
437
|
if (result.code !== 0) throw new Error(`npm installation failed (${result.signal ?? result.code})`);
|
|
404
438
|
}
|
|
405
439
|
|
|
440
|
+
// src/cli/systemd-update.ts
|
|
441
|
+
import { execFile } from "node:child_process";
|
|
442
|
+
import { promisify } from "node:util";
|
|
443
|
+
import { readFileSync as readFileSync3, writeFileSync as writeFileSync3, unlinkSync as unlinkSync3 } from "node:fs";
|
|
444
|
+
import { join as join4 } from "node:path";
|
|
445
|
+
var exec = promisify(execFile);
|
|
446
|
+
function parseSystemdUpdate(value) {
|
|
447
|
+
const c = value;
|
|
448
|
+
const unit = (v) => typeof v === "string" && /^[A-Za-z0-9][A-Za-z0-9_.-]*\.service$/.test(v);
|
|
449
|
+
if (!c || !["system", "user"].includes(c.scope) || !unit(c.service) || !unit(c.updater) || c.service === c.updater || !Array.isArray(c.hostArgs) || c.hostArgs[0] !== "serve" || c.hostArgs.some((a) => typeof a !== "string") || c.hostArgs.includes("--background-host") || c.hostArgs.includes("start")) {
|
|
450
|
+
throw new Error("Invalid systemd-update.json: use distinct fixed service units and foreground serve arguments");
|
|
451
|
+
}
|
|
452
|
+
return c;
|
|
453
|
+
}
|
|
454
|
+
function systemdUpdate(root) {
|
|
455
|
+
try {
|
|
456
|
+
return parseSystemdUpdate(JSON.parse(readFileSync3(join4(root, "systemd-update.json"), "utf8")));
|
|
457
|
+
} catch (error) {
|
|
458
|
+
if (error.code === "ENOENT") return void 0;
|
|
459
|
+
throw error;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
var SystemdCommandFailed = class extends Error {
|
|
463
|
+
completed;
|
|
464
|
+
constructor(error) {
|
|
465
|
+
super(String(error), { cause: error });
|
|
466
|
+
const command = error;
|
|
467
|
+
this.completed = typeof command.code === "number" && !command.killed && !command.signal;
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
async function systemctl(c, action, unit, extra = []) {
|
|
471
|
+
try {
|
|
472
|
+
const { stdout } = await exec("/usr/bin/systemctl", [`--${c.scope}`, "--no-ask-password", action, unit, ...extra], { timeout: 6e4 });
|
|
473
|
+
return stdout.trim();
|
|
474
|
+
} catch (error) {
|
|
475
|
+
throw new SystemdCommandFailed(error);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
async function resumeSystemdAdmission(c, host) {
|
|
479
|
+
await assertSystemdOwner(c, c.service, host.pid);
|
|
480
|
+
if (await systemctl(c, "show", c.service, ["--property=ActiveState", "--value"]) !== "active" || await systemctl(c, "show", c.service, ["--property=Job", "--value"]) !== "") {
|
|
481
|
+
throw new Error("The original systemd service is not active and job-free; admission cannot safely resume");
|
|
482
|
+
}
|
|
483
|
+
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
484
|
+
method: "POST",
|
|
485
|
+
headers: { authorization: `Bearer ${host.token}`, "content-type": "application/json" },
|
|
486
|
+
body: JSON.stringify({ instanceId: host.instanceId, resume: true }),
|
|
487
|
+
signal: AbortSignal.timeout(5e3)
|
|
488
|
+
});
|
|
489
|
+
if (!response.ok) throw new Error(`Cannot resume Session Host admission: ${await response.text()}`);
|
|
490
|
+
}
|
|
491
|
+
async function assertSystemdOwner(c, unit, pid) {
|
|
492
|
+
if (await systemctl(c, "show", unit, ["--property=MainPID", "--value"]) !== String(pid)) throw new Error(`systemd ${unit} does not own the expected process`);
|
|
493
|
+
}
|
|
494
|
+
var SystemdLaunchUncertain = class extends Error {
|
|
495
|
+
};
|
|
496
|
+
var requestPath = (root) => join4(root, "systemd-update-request.json");
|
|
497
|
+
async function launchSystemdUpdate(root, c, request) {
|
|
498
|
+
const state = await systemctl(c, "show", c.updater, ["--property=ActiveState", "--value"]);
|
|
499
|
+
if (!["inactive", "failed"].includes(state)) throw new Error(`Systemd updater ${c.updater} is ${state || "unknown"}; wait for it to stop before updating`);
|
|
500
|
+
writeFileSync3(requestPath(root), JSON.stringify(request), { flag: "wx", mode: 384 });
|
|
501
|
+
try {
|
|
502
|
+
await systemctl(c, "start", c.updater, ["--no-block"]);
|
|
503
|
+
} catch (error) {
|
|
504
|
+
throw new SystemdLaunchUncertain(`Could not confirm systemd update submission: ${String(error)}. Inspect ${c.updater} and ${requestPath(root)} before retrying; the request has been retained.`);
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
function readSystemdRequest(root) {
|
|
508
|
+
const r = JSON.parse(readFileSync3(requestPath(root), "utf8"));
|
|
509
|
+
if (!r || typeof r.force !== "boolean" || r.id !== void 0 && !/^[a-f0-9-]{36}$/.test(r.id) || r.version !== void 0 && (typeof r.version !== "string" || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(r.version)) || r.id === void 0 !== (r.version === void 0)) throw new Error("Invalid systemd update request");
|
|
510
|
+
return r;
|
|
511
|
+
}
|
|
512
|
+
function clearSystemdRequest(root) {
|
|
513
|
+
unlinkSync3(requestPath(root));
|
|
514
|
+
}
|
|
515
|
+
function systemdCapability(root) {
|
|
516
|
+
if (process.env.FLOW_SYSTEMD_HOST !== "1") return void 0;
|
|
517
|
+
try {
|
|
518
|
+
return readFileSync3(join4(root, "systemd-update-capability"), "utf8");
|
|
519
|
+
} catch (error) {
|
|
520
|
+
if (error.code === "ENOENT") return void 0;
|
|
521
|
+
throw error;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
async function restoreSystemd(root, c, transaction, old, version) {
|
|
525
|
+
const env = await transaction.authorizeRestoration(c.hostArgs);
|
|
526
|
+
const path = join4(root, "systemd-update-capability");
|
|
527
|
+
writeFileSync3(path, env.FLOW_UPDATE_CAPABILITY, { flag: "wx", mode: 384 });
|
|
528
|
+
try {
|
|
529
|
+
await systemctl(c, "start", c.service);
|
|
530
|
+
await waitUntil(async () => {
|
|
531
|
+
const host = readHost(root);
|
|
532
|
+
if (!host || host.instanceId === old.instanceId) return false;
|
|
533
|
+
await assertSystemdOwner(c, c.service, host.pid);
|
|
534
|
+
const status = await getHostStatus(host);
|
|
535
|
+
if (status.version !== version || status.mode !== "foreground" || ["port", "address", "cwd", "oidc"].some((k) => status.settings[k] !== old.settings[k])) throw new Error("Restored systemd Session Host settings or version differ");
|
|
536
|
+
return true;
|
|
537
|
+
}, "systemd Session Host startup timed out");
|
|
538
|
+
await transaction.assertAuthorizationConsumed();
|
|
539
|
+
} catch (error) {
|
|
540
|
+
await systemctl(c, "stop", c.service);
|
|
541
|
+
throw error;
|
|
542
|
+
} finally {
|
|
543
|
+
unlinkSync3(path);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// src/daemon/release-checker.ts
|
|
548
|
+
var STABLE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
549
|
+
var SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
550
|
+
function parsed(version) {
|
|
551
|
+
const match = SEMVER.exec(version);
|
|
552
|
+
if (!match) return void 0;
|
|
553
|
+
return {
|
|
554
|
+
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
555
|
+
prerelease: match[4]?.split(".") ?? []
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
function compareIdentifiers(left, right) {
|
|
559
|
+
const leftNumber = /^\d+$/.test(left) ? Number(left) : void 0;
|
|
560
|
+
const rightNumber = /^\d+$/.test(right) ? Number(right) : void 0;
|
|
561
|
+
if (leftNumber !== void 0 && rightNumber !== void 0) return Math.sign(leftNumber - rightNumber);
|
|
562
|
+
if (leftNumber !== void 0) return -1;
|
|
563
|
+
if (rightNumber !== void 0) return 1;
|
|
564
|
+
return left.localeCompare(right);
|
|
565
|
+
}
|
|
566
|
+
function compareVersions(left, right) {
|
|
567
|
+
const a = parsed(left), b = parsed(right);
|
|
568
|
+
if (!a || !b) throw new Error("Invalid semantic version");
|
|
569
|
+
for (let index = 0; index < 3; index += 1) {
|
|
570
|
+
const difference = a.core[index] - b.core[index];
|
|
571
|
+
if (difference) return Math.sign(difference);
|
|
572
|
+
}
|
|
573
|
+
if (!a.prerelease.length && !b.prerelease.length) return 0;
|
|
574
|
+
if (!a.prerelease.length) return 1;
|
|
575
|
+
if (!b.prerelease.length) return -1;
|
|
576
|
+
for (let index = 0; index < Math.max(a.prerelease.length, b.prerelease.length); index += 1) {
|
|
577
|
+
const av = a.prerelease[index], bv = b.prerelease[index];
|
|
578
|
+
if (av === void 0) return -1;
|
|
579
|
+
if (bv === void 0) return 1;
|
|
580
|
+
const difference = compareIdentifiers(av, bv);
|
|
581
|
+
if (difference) return difference;
|
|
582
|
+
}
|
|
583
|
+
return 0;
|
|
584
|
+
}
|
|
585
|
+
function newerStableVersion(installed, latest) {
|
|
586
|
+
return STABLE.test(latest) && compareVersions(latest, installed) > 0;
|
|
587
|
+
}
|
|
588
|
+
|
|
406
589
|
// src/cli/update.ts
|
|
407
590
|
function npmExecutable() {
|
|
408
591
|
for (const directory of (process.env.PATH ?? "").split(delimiter)) {
|
|
@@ -420,48 +603,68 @@ function npmPath(npm, command) {
|
|
|
420
603
|
}
|
|
421
604
|
function packageVersion(slot) {
|
|
422
605
|
privatePath(slot);
|
|
423
|
-
const metadata = JSON.parse(
|
|
606
|
+
const metadata = JSON.parse(readFileSync4(join5(slot, "package.json"), "utf8"));
|
|
424
607
|
if (metadata?.name !== packageName || typeof metadata.version !== "string" || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(metadata.version)) throw new Error("Installed package identity is invalid");
|
|
425
608
|
return metadata.version;
|
|
426
609
|
}
|
|
427
610
|
async function verify(install, transaction, expected) {
|
|
428
611
|
const version = packageVersion(install.slot);
|
|
429
612
|
if (expected && version !== expected) throw new Error("Installed package verification failed");
|
|
430
|
-
if (!
|
|
613
|
+
if (!readFileSync4(join5(install.slot, "dist/build-id"), "utf8").trim()) throw new Error("Installed build identity is missing");
|
|
431
614
|
const env = await transaction.authorizeVerification();
|
|
432
|
-
const reported = execFileSync(process.execPath, [
|
|
615
|
+
const reported = execFileSync(process.execPath, [join5(install.slot, "dist/cli/bootstrap.js"), "--version"], { env, encoding: "utf8", timeout: 15e3 }).trim();
|
|
433
616
|
if (reported !== version) throw new Error("Fresh Flow process reports the wrong version");
|
|
434
617
|
await transaction.assertAuthorizationConsumed();
|
|
435
618
|
return version;
|
|
436
619
|
}
|
|
437
|
-
async function restore(install, transaction, root, host, version) {
|
|
438
|
-
const
|
|
620
|
+
async function restore(install, transaction, root, host, version, preserveConcretePort) {
|
|
621
|
+
const settings = preserveConcretePort && host.settings.port === 0 ? { ...host.settings, port: Number(new URL(host.url).port) } : host.settings;
|
|
622
|
+
const env = await transaction.authorizeRestoration(backgroundHostArgs(settings));
|
|
439
623
|
await launchBackground({
|
|
440
624
|
root,
|
|
441
|
-
settings
|
|
442
|
-
entry: [
|
|
625
|
+
settings,
|
|
626
|
+
entry: [join5(install.slot, "dist/cli/bootstrap.js")],
|
|
443
627
|
env,
|
|
444
628
|
validate(status) {
|
|
445
|
-
if (status.instanceId === host.instanceId || status.version !== version || status.mode !== "background" || ["port", "address", "cwd", "oidc"].some((key) => status.settings[key] !==
|
|
629
|
+
if (status.instanceId === host.instanceId || status.version !== version || status.mode !== "background" || ["port", "address", "cwd", "oidc"].some((key) => status.settings[key] !== settings[key])) {
|
|
446
630
|
throw new Error("Restored Session Host settings or version differ");
|
|
447
631
|
}
|
|
448
632
|
}
|
|
449
633
|
});
|
|
450
634
|
await transaction.assertAuthorizationConsumed();
|
|
451
635
|
}
|
|
452
|
-
|
|
453
|
-
if (args.length > 2 || args[0] !== "update" || args.length === 2 && args[1] !== "--force") throw new Error("usage: flow update [--force]");
|
|
636
|
+
function inspectUpdateInstallation(install) {
|
|
454
637
|
const npm = npmExecutable();
|
|
455
638
|
const prefix = npmPath(npm, "prefix"), root = npmPath(npm, "root");
|
|
456
|
-
if (prefix !== install.prefix || root !==
|
|
457
|
-
|
|
639
|
+
if (prefix !== install.prefix || root !== join5(prefix, "lib/node_modules") || realpathSync4(join5(root, packageName)) !== install.slot) throw new Error("npm selects a different installation. Put the matching npm in PATH and select its prefix.");
|
|
640
|
+
return { npm, version: packageVersion(install.slot) };
|
|
641
|
+
}
|
|
642
|
+
async function update(install, lease, args, options = {}) {
|
|
643
|
+
if (args.length > 2 || args[0] !== "update" || args.length === 2 && args[1] !== "--force") throw new Error("usage: flow update [--force]");
|
|
644
|
+
const inspected = inspectUpdateInstallation(install);
|
|
645
|
+
const npm = inspected.npm;
|
|
646
|
+
const prefix = install.prefix;
|
|
647
|
+
const previous = inspected.version;
|
|
648
|
+
if (options.expectedVersion !== void 0 && !newerStableVersion(previous, options.expectedVersion)) {
|
|
649
|
+
throw new Error(`The confirmed web update target ${options.expectedVersion} is not a newer stable release`);
|
|
650
|
+
}
|
|
651
|
+
const target = options.expectedVersion ?? "latest";
|
|
652
|
+
const preserveConcretePort = options.preserveConcreteHostPort === true;
|
|
653
|
+
const managed = options.systemd;
|
|
654
|
+
if (managed) await assertSystemdOwner(managed, managed.updater, process.pid);
|
|
458
655
|
let host = readHost(lease.root);
|
|
459
656
|
if (host && processAlive(host.pid)) {
|
|
460
657
|
const status = await getHostStatus(host);
|
|
461
|
-
|
|
658
|
+
if (managed) {
|
|
659
|
+
if (status.mode !== "foreground") throw new Error("systemd updates require a foreground Session Host");
|
|
660
|
+
if (preserveConcretePort && status.settings.port === 0) throw new Error("Systemd web updates require a fixed service port for browser reconnection");
|
|
661
|
+
await assertSystemdOwner(managed, managed.service, host.pid);
|
|
662
|
+
} else requireRestartable(status);
|
|
462
663
|
host = { ...host, ...status };
|
|
463
664
|
} else host = void 0;
|
|
464
|
-
|
|
665
|
+
if (managed && !host) throw new Error("Start the configured systemd Session Host before updating");
|
|
666
|
+
const transaction = await install.beginUpdate(lease, previous, host, managed?.hostArgs);
|
|
667
|
+
const restoreHost = (host2, version) => managed ? restoreSystemd(lease.root, managed, transaction, host2, version) : restore(install, transaction, lease.root, host2, version, preserveConcretePort);
|
|
465
668
|
let needsRestoration = false, replacing = false;
|
|
466
669
|
const repair = () => `Flow startup remains blocked by ${install.barrierPath}. Stop all Flow and npm processes for this prefix. Reinstall ${packageName}@${previous} with the matching npm and prefix ${JSON.stringify(prefix)}. Verify the package files manually, then remove ${install.barrierPath} and start the Session Host again.`;
|
|
467
670
|
async function replace(version, expected) {
|
|
@@ -470,7 +673,7 @@ async function update(install, lease, args) {
|
|
|
470
673
|
await replacePackage(npm, prefix, `${packageName}@${version}`);
|
|
471
674
|
const installed = await verify(install, transaction, expected);
|
|
472
675
|
if (host && needsRestoration) {
|
|
473
|
-
await
|
|
676
|
+
await restoreHost(host, installed);
|
|
474
677
|
needsRestoration = false;
|
|
475
678
|
}
|
|
476
679
|
await transaction.complete();
|
|
@@ -480,7 +683,8 @@ async function update(install, lease, args) {
|
|
|
480
683
|
if (host) {
|
|
481
684
|
needsRestoration = true;
|
|
482
685
|
try {
|
|
483
|
-
await requestHostStop(host, args.includes("--force"));
|
|
686
|
+
await requestHostStop(host, args.includes("--force"), !!managed);
|
|
687
|
+
if (managed) await systemctl(managed, "stop", managed.service);
|
|
484
688
|
} catch (error) {
|
|
485
689
|
if (error instanceof HostRefusal) needsRestoration = false;
|
|
486
690
|
throw error;
|
|
@@ -488,15 +692,27 @@ async function update(install, lease, args) {
|
|
|
488
692
|
const pid = host.pid;
|
|
489
693
|
await waitUntil(async () => !processAlive(pid), "Session Host process did not exit; installation was not changed");
|
|
490
694
|
}
|
|
491
|
-
const version = await replace(
|
|
695
|
+
const version = await replace(target, options.expectedVersion);
|
|
492
696
|
console.log(version === previous ? `Flow is already at ${version}.` : `Flow updated: ${previous} \u2192 ${version}`);
|
|
697
|
+
return { previousVersion: previous, installedVersion: version, changed: version !== previous };
|
|
493
698
|
} catch (error) {
|
|
494
699
|
if (error instanceof InstallationProcessUncertain) throw new Error(`${String(error)}. ${repair()}`);
|
|
495
700
|
if (!replacing) {
|
|
496
|
-
if (needsRestoration && host && processAlive(host.pid))
|
|
701
|
+
if (needsRestoration && host && processAlive(host.pid)) {
|
|
702
|
+
if (managed && error instanceof SystemdCommandFailed && error.completed) {
|
|
703
|
+
try {
|
|
704
|
+
await resumeSystemdAdmission(managed, host);
|
|
705
|
+
} catch (failure) {
|
|
706
|
+
throw new Error(`${String(error)}; could not resume admission: ${String(failure)}. No package files were changed. ${repair()}`);
|
|
707
|
+
}
|
|
708
|
+
await transaction.complete();
|
|
709
|
+
throw new Error(`${String(error)}. No package files were changed; the original Session Host is accepting requests again.`);
|
|
710
|
+
}
|
|
711
|
+
throw new Error(`${String(error)}. No package files were changed; wait for the stopping host to exit. ${repair()}`);
|
|
712
|
+
}
|
|
497
713
|
if (needsRestoration && host) {
|
|
498
714
|
try {
|
|
499
|
-
await
|
|
715
|
+
await restoreHost(host, previous);
|
|
500
716
|
} catch (failure) {
|
|
501
717
|
throw new Error(`${String(error)}; restoration failed: ${String(failure)}. ${repair()}`);
|
|
502
718
|
}
|
|
@@ -513,21 +729,192 @@ async function update(install, lease, args) {
|
|
|
513
729
|
}
|
|
514
730
|
}
|
|
515
731
|
|
|
732
|
+
// src/cli/web-update.ts
|
|
733
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
734
|
+
import {
|
|
735
|
+
closeSync as closeSync2,
|
|
736
|
+
constants as constants3,
|
|
737
|
+
fchmodSync as fchmodSync2,
|
|
738
|
+
mkdirSync as mkdirSync4,
|
|
739
|
+
openSync as openSync2,
|
|
740
|
+
readFileSync as readFileSync5,
|
|
741
|
+
readdirSync as readdirSync3,
|
|
742
|
+
renameSync as renameSync3,
|
|
743
|
+
rmdirSync as rmdirSync3,
|
|
744
|
+
unlinkSync as unlinkSync4,
|
|
745
|
+
writeFileSync as writeFileSync4
|
|
746
|
+
} from "node:fs";
|
|
747
|
+
import { join as join6 } from "node:path";
|
|
748
|
+
var STATUS_FILE = "web-update.json";
|
|
749
|
+
var STATUS_LOCK = "web-update-lock";
|
|
750
|
+
var STATUS_LOCK_ATTEMPTS = 100;
|
|
751
|
+
var STATUS_LOCK_WAIT_MS = 25;
|
|
752
|
+
function statusPath(root) {
|
|
753
|
+
return join6(root, STATUS_FILE);
|
|
754
|
+
}
|
|
755
|
+
function readOperation(root) {
|
|
756
|
+
try {
|
|
757
|
+
const value = JSON.parse(readFileSync5(statusPath(root), "utf8"));
|
|
758
|
+
if (!value || typeof value.id !== "string" || !["updating", "succeeded", "failed", "unverified"].includes(value.state)) return void 0;
|
|
759
|
+
return value;
|
|
760
|
+
} catch {
|
|
761
|
+
return void 0;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
function writeOperation(root, operation) {
|
|
765
|
+
const temporary = join6(root, `${STATUS_FILE}-${process.pid}-${randomUUID3()}`);
|
|
766
|
+
writeFileSync4(temporary, JSON.stringify(operation), { mode: 384 });
|
|
767
|
+
renameSync3(temporary, statusPath(root));
|
|
768
|
+
}
|
|
769
|
+
function removeLockOwner(path, filename) {
|
|
770
|
+
try {
|
|
771
|
+
unlinkSync4(join6(path, filename));
|
|
772
|
+
} catch (error) {
|
|
773
|
+
if (error.code !== "ENOENT") throw error;
|
|
774
|
+
}
|
|
775
|
+
try {
|
|
776
|
+
rmdirSync3(path);
|
|
777
|
+
} catch (error) {
|
|
778
|
+
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) throw error;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
function sleep(milliseconds) {
|
|
782
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
|
|
783
|
+
}
|
|
784
|
+
function transitionOperation(root, transition) {
|
|
785
|
+
const ownerId = randomUUID3();
|
|
786
|
+
const filename = `${ownerId}.json`;
|
|
787
|
+
const candidate = join6(root, `${STATUS_LOCK}-${ownerId}`);
|
|
788
|
+
const lock = join6(root, STATUS_LOCK);
|
|
789
|
+
mkdirSync4(candidate, { mode: 448 });
|
|
790
|
+
writeFileSync4(join6(candidate, filename), JSON.stringify({ pid: process.pid, id: ownerId }), { mode: 384 });
|
|
791
|
+
let acquired = false;
|
|
792
|
+
try {
|
|
793
|
+
for (let attempt = 0; !acquired; attempt++) {
|
|
794
|
+
try {
|
|
795
|
+
renameSync3(candidate, lock);
|
|
796
|
+
acquired = true;
|
|
797
|
+
} catch (error) {
|
|
798
|
+
if (!["ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) throw error;
|
|
799
|
+
if (attempt >= STATUS_LOCK_ATTEMPTS) throw new Error("Web update status is busy");
|
|
800
|
+
let entries;
|
|
801
|
+
try {
|
|
802
|
+
entries = readdirSync3(lock);
|
|
803
|
+
} catch (readError) {
|
|
804
|
+
if (readError.code === "ENOENT") continue;
|
|
805
|
+
throw readError;
|
|
806
|
+
}
|
|
807
|
+
if (entries.length === 0) {
|
|
808
|
+
sleep(STATUS_LOCK_WAIT_MS);
|
|
809
|
+
continue;
|
|
810
|
+
}
|
|
811
|
+
if (entries.length !== 1 || !/^[a-f0-9-]+\.json$/.test(entries[0])) throw new Error("Invalid web update status owner");
|
|
812
|
+
let owner2;
|
|
813
|
+
try {
|
|
814
|
+
owner2 = JSON.parse(readFileSync5(join6(lock, entries[0]), "utf8"));
|
|
815
|
+
} catch (readError) {
|
|
816
|
+
if (readError.code === "ENOENT") continue;
|
|
817
|
+
throw readError;
|
|
818
|
+
}
|
|
819
|
+
if (!owner2 || typeof owner2 !== "object" || !Number.isInteger(owner2.pid) || owner2.pid <= 0 || owner2.id !== entries[0].slice(0, -5)) {
|
|
820
|
+
throw new Error("Invalid web update status owner");
|
|
821
|
+
}
|
|
822
|
+
if (!processAlive(owner2.pid)) removeLockOwner(lock, entries[0]);
|
|
823
|
+
sleep(STATUS_LOCK_WAIT_MS);
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
const current = readOperation(root);
|
|
827
|
+
const next = transition(current);
|
|
828
|
+
if (next !== void 0 && next !== current) writeOperation(root, next);
|
|
829
|
+
return next;
|
|
830
|
+
} finally {
|
|
831
|
+
removeLockOwner(acquired ? lock : candidate, filename);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
function publicError(error) {
|
|
835
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
836
|
+
return message.replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/((?:token|secret|password)[=:]\s*)[^\s;,]+/gi, "$1[redacted]").slice(0, 2e3);
|
|
837
|
+
}
|
|
838
|
+
function claimWebUpdate(root, id) {
|
|
839
|
+
transitionOperation(root, (current) => current?.id === id && ["updating", "unverified"].includes(current.state) ? { ...current, state: "updating", pid: process.pid } : current);
|
|
840
|
+
}
|
|
841
|
+
function finishWebUpdate(root, id, result, error) {
|
|
842
|
+
transitionOperation(root, (current) => {
|
|
843
|
+
if (!current || current.id !== id || !["updating", "unverified"].includes(current.state)) return current;
|
|
844
|
+
const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
845
|
+
if (error !== void 0) return { ...current, state: "failed", finishedAt, message: publicError(error) };
|
|
846
|
+
if (!result?.changed) {
|
|
847
|
+
return {
|
|
848
|
+
...current,
|
|
849
|
+
state: "failed",
|
|
850
|
+
installedVersion: result?.installedVersion ?? current.previousVersion,
|
|
851
|
+
finishedAt,
|
|
852
|
+
message: `npm completed, but Flow remains at ${result?.installedVersion ?? current.previousVersion}. No update was installed.`
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
return {
|
|
856
|
+
...current,
|
|
857
|
+
state: "succeeded",
|
|
858
|
+
installedVersion: result.installedVersion,
|
|
859
|
+
finishedAt,
|
|
860
|
+
message: `Flow updated from ${result.previousVersion} to ${result.installedVersion}.`
|
|
861
|
+
};
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
|
|
516
865
|
// src/cli/bootstrap.ts
|
|
517
866
|
async function bootstrap() {
|
|
518
867
|
const slot = resolve3(fileURLToPath(new URL("../..", import.meta.url)));
|
|
519
868
|
const args = process.argv.slice(2);
|
|
520
|
-
const root = canonicalRoot(process.env.FLOW_STATE_DIR ??
|
|
869
|
+
const root = canonicalRoot(process.env.FLOW_STATE_DIR ?? join7(homedir(), ".flow"));
|
|
521
870
|
const globalSlot = slot.endsWith("/lib/node_modules/@nathanstephenson/flow");
|
|
871
|
+
let updateSupport;
|
|
522
872
|
if (globalSlot && (args[0] === "update" || updateEligible(slot) || registryExists(slot))) {
|
|
523
873
|
const install = installation(slot);
|
|
524
|
-
const
|
|
874
|
+
const managed = systemdUpdate(root);
|
|
875
|
+
const worker = args[0] === "update" && process.env.FLOW_SYSTEMD_WORKER === "1";
|
|
876
|
+
if (args[0] === "update" && managed && !worker) {
|
|
877
|
+
if (args.length > 2 || args[1] !== void 0 && args[1] !== "--force") throw new Error("usage: flow update [--force]");
|
|
878
|
+
await launchSystemdUpdate(root, managed, { force: args.includes("--force") });
|
|
879
|
+
console.log("Systemd update queued. See the updater unit journal for the result.");
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
if (worker) {
|
|
883
|
+
if (!managed) throw new Error("Missing systemd update configuration");
|
|
884
|
+
await assertSystemdOwner(managed, managed.updater, process.pid);
|
|
885
|
+
}
|
|
886
|
+
const lease = await install.register("a05670ad-d8b7-4859-afde-7cc8ad2f6548", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
|
|
525
887
|
delete process.env.FLOW_UPDATE_CAPABILITY;
|
|
526
888
|
process.on("exit", lease.release);
|
|
527
|
-
if (args[0] === "update")
|
|
528
|
-
|
|
889
|
+
if (args[0] === "update") {
|
|
890
|
+
const request = worker ? readSystemdRequest(root) : void 0;
|
|
891
|
+
const webId = request?.id ?? process.env.FLOW_WEB_UPDATE_ID;
|
|
892
|
+
const webVersion = request?.version ?? process.env.FLOW_WEB_UPDATE_VERSION;
|
|
893
|
+
if (webId) claimWebUpdate(root, webId);
|
|
894
|
+
delete process.env.FLOW_WEB_UPDATE_ID;
|
|
895
|
+
delete process.env.FLOW_WEB_UPDATE_VERSION;
|
|
896
|
+
try {
|
|
897
|
+
if (webId === void 0 !== (webVersion === void 0)) throw new Error("Web update authorization is incomplete");
|
|
898
|
+
const result = await update(install, lease, request ? ["update", ...request.force ? ["--force"] : []] : args, {
|
|
899
|
+
...webId ? { expectedVersion: webVersion, preserveConcreteHostPort: true } : {},
|
|
900
|
+
...worker ? { systemd: managed } : {}
|
|
901
|
+
});
|
|
902
|
+
if (webId) finishWebUpdate(root, webId, result);
|
|
903
|
+
return;
|
|
904
|
+
} catch (error) {
|
|
905
|
+
if (webId) finishWebUpdate(root, webId, void 0, error);
|
|
906
|
+
throw error;
|
|
907
|
+
} finally {
|
|
908
|
+
if (worker) clearSystemdRequest(root);
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
updateSupport = { installation: install, bootstrapEntry: fileURLToPath(import.meta.url) };
|
|
912
|
+
} else {
|
|
913
|
+
if (args[0] === "update") throw new Error("Self-update requires a private global npm installation; source, npm link, root, shared, and system installations are unsupported");
|
|
914
|
+
updateSupport = { unsupportedReason: explainUnsupportedUpdate(slot) };
|
|
915
|
+
}
|
|
529
916
|
const { runCli } = await import(new URL("./application.js", import.meta.url).href);
|
|
530
|
-
await runCli();
|
|
917
|
+
await runCli(updateSupport);
|
|
531
918
|
}
|
|
532
919
|
bootstrap().catch((error) => {
|
|
533
920
|
console.error(error instanceof Error ? error.message : error);
|
package/dist/cli/host-control.js
CHANGED
|
@@ -29,10 +29,10 @@ export async function getHostStatus(host) {
|
|
|
29
29
|
throw new Error('Session Host identity changed');
|
|
30
30
|
return status;
|
|
31
31
|
}
|
|
32
|
-
export async function requestHostStop(host, force) {
|
|
32
|
+
export async function requestHostStop(host, force, quiesce = false) {
|
|
33
33
|
const response = await fetch(`${host.url}/api/host/stop`, {
|
|
34
34
|
method: 'POST', headers: { authorization: `Bearer ${host.token}`, 'content-type': 'application/json' },
|
|
35
|
-
body: JSON.stringify({ instanceId: host.instanceId, force }), signal: AbortSignal.timeout(5000),
|
|
35
|
+
body: JSON.stringify({ instanceId: host.instanceId, force, quiesce }), signal: AbortSignal.timeout(5000),
|
|
36
36
|
});
|
|
37
37
|
if (!response.ok)
|
|
38
38
|
throw new HostRefusal(`Session Host refused: ${await response.text()}`);
|