@nathanstephenson/flow 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +6 -1
  2. package/dist/backend/fake/index.js +3 -1
  3. package/dist/backend/pi/effort-capabilities.js +12 -0
  4. package/dist/backend/pi/index.js +25 -36
  5. package/dist/backend/pi/workflow-subagent.js +8 -3
  6. package/dist/build-id +1 -1
  7. package/dist/cli/application.js +9 -1
  8. package/dist/cli/bootstrap.js +258 -22
  9. package/dist/cli/install-guard.js +52 -9
  10. package/dist/cli/update.js +30 -13
  11. package/dist/cli/web-update.js +357 -0
  12. package/dist/client/model-choices.js +22 -4
  13. package/dist/client/reduce.js +18 -6
  14. package/dist/client/status.js +34 -20
  15. package/dist/client/workflow-effort.js +30 -0
  16. package/dist/daemon/credential-redaction.js +97 -4
  17. package/dist/daemon/host.js +341 -74
  18. package/dist/daemon/release-checker.js +104 -0
  19. package/dist/daemon/runtime.js +12 -4
  20. package/dist/daemon/server.js +81 -14
  21. package/dist/daemon/summariser.js +81 -15
  22. package/dist/daemon/update-api.js +3 -0
  23. package/dist/daemon/workflow-executions.js +146 -15
  24. package/dist/protocol/update.js +1 -0
  25. package/dist/tui/app.js +104 -10
  26. package/dist/tui/keys.js +46 -10
  27. package/dist/tui/render.js +58 -13
  28. package/dist/workflows/records.js +3 -1
  29. package/dist/workflows/scheduler.js +15 -1
  30. package/package.json +1 -1
  31. package/web/dist/apple-touch-icon.png +0 -0
  32. package/web/dist/assets/index-CaJfF2tQ.js +170 -0
  33. package/web/dist/assets/index-DWF4-3Fh.css +2 -0
  34. package/web/dist/assets/{settings-mcp-CcT0ADJR.js → settings-mcp-COi1p_1o.js} +1 -1
  35. package/web/dist/assets/{settings-secrets-CK4uF7fd.js → settings-secrets-C599riFl.js} +1 -1
  36. package/web/dist/assets/settings-workflows-BPjeFoaT.js +23 -0
  37. package/web/dist/assets/{workflows-D4T4Gy_7.css → workflows-9aO6cptD.css} +1 -1
  38. package/web/dist/assets/workflows-Bmsrl5kE.js +7 -0
  39. package/web/dist/assets/workflows-pane-DJ3UwHjd.js +1 -0
  40. package/web/dist/favicon-16x16.png +0 -0
  41. package/web/dist/favicon-32x32.png +0 -0
  42. package/web/dist/favicon.ico +0 -0
  43. package/web/dist/favicon.svg +8 -0
  44. package/web/dist/index.html +8 -3
  45. package/web/dist/safari-pinned-tab.svg +4 -0
  46. package/web/dist/assets/index-BC0gLS53.js +0 -106
  47. package/web/dist/assets/index-CCeZYKES.css +0 -2
  48. package/web/dist/assets/settings-workflows-CrbZF-nM.js +0 -23
  49. package/web/dist/assets/workflow-editors-naPqAmYO.js +0 -65
  50. package/web/dist/assets/workflows-hh6ioeEA.js +0 -7
  51. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +0 -1
package/README.md CHANGED
@@ -60,7 +60,12 @@ do not tag a version until its license and release contents are approved.
60
60
  ## Updating Flow
61
61
 
62
62
  Run `flow update` to install `@nathanstephenson/flow@latest` with the npm selected by PATH.
63
- Its global prefix must match this exact installation. Only user-owned prefixes without group or
63
+ An authorised browser connected to a background Session Host can perform the same guarded operation
64
+ from **Settings → General → Flow update** after explicit confirmation. The browser checks only npm's
65
+ stable `latest` tag, cannot select a package/version/path or force active work to stop, and reconnects
66
+ on the same address and port to verify the running version. Updates are never automatic.
67
+
68
+ The global prefix must match this exact installation. Only user-owned prefixes without group or
64
69
  other write access are supported; their ancestor directories must also prevent replacement by other users. Source, npm-link, root/sudo, shared prefixes, and SEA self-update
65
70
  are not supported. Ordinary commands still work for these installations. Update shared or system
66
71
  installations manually with npm after stopping all Flow processes.
@@ -208,8 +208,10 @@ export class FakeSession {
208
208
  this.wantedEffort = effort;
209
209
  const levels = FAKE_CAPABILITIES.models.find((model) => model.id === this.modelId)?.effortLevels;
210
210
  const level = clampEffort(effort, levels);
211
- if (!level)
211
+ if (!level) {
212
+ this.effort = undefined;
212
213
  return;
214
+ }
213
215
  this.effort = level;
214
216
  this.emit({ type: "effort_changed", effort: level });
215
217
  }
@@ -0,0 +1,12 @@
1
+ import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
2
+ export function piEffortLevels(model) {
3
+ if (!model.reasoning)
4
+ return [];
5
+ // The SDK helper reads only the two fields retained above; registry models carry the full shape.
6
+ return getSupportedThinkingLevels(model);
7
+ }
8
+ /** Exact workflow validation, including the internal sentinel for a confirmed no-control model. */
9
+ export function piAcceptsWorkflowEffort(model, effort) {
10
+ const levels = piEffortLevels(model);
11
+ return levels.length === 0 ? effort === "off" : levels.includes(effort);
12
+ }
@@ -3,6 +3,7 @@ import { piMcpTools } from "./mcp.js";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
5
5
  import { PiWorkflowSubagent } from "./workflow-subagent.js";
6
+ import { piEffortLevels } from "./effort-capabilities.js";
6
7
  import { clampEffort } from "../effort.js";
7
8
  import { piAutoCompaction } from "./auto-compaction.js";
8
9
  import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
@@ -102,8 +103,10 @@ export class PiSession {
102
103
  // Which levels are on offer follows the model, and pi may have clamped its own thinking level
103
104
  // on the way through, so both the list and the level in force are re-read here.
104
105
  this.capabilities = capabilitiesOf(this.session, this.enquiries !== undefined, this.capabilities.subagents);
105
- this.emit({ type: "model_changed", model: describeModel(model) });
106
+ // Publish the new list first. A client that receives the model first would briefly classify its
107
+ // Effort support as unknown (or, worse, reuse the old model's list).
106
108
  this.emit({ type: "capabilities_changed", capabilities: this.capabilities });
109
+ this.emit({ type: "model_changed", model: describeModel(model) });
107
110
  this.reapplyEffort();
108
111
  }
109
112
  async setEffort(effort) {
@@ -448,10 +451,21 @@ export class PiBackend {
448
451
  const listed = piSession.capabilities.models.find((model) => model.id === described.id);
449
452
  options.emit({ type: "model_changed", model: listed ?? described });
450
453
  }
451
- // Announced after the model, because which model is in force is what decides whether an effort
452
- // level means anything at all.
453
- if (options.effort)
454
+ // Announced after the model, because which model is in force decides whether an Effort level
455
+ // means anything. A persisted/default value is configuration, not a live model switch: reject
456
+ // an invalid one for explicit correction instead of silently clamping it. Live setEffort keeps
457
+ // the normal nearest-level clamp below.
458
+ if (options.effort) {
459
+ const levels = session.model ? piEffortLevels(session.model) : [];
460
+ const accepted = levels.length === 0 ? options.effort === "off" : levels.includes(options.effort);
461
+ if (!accepted) {
462
+ await piSession.dispose();
463
+ throw new Error(levels.length > 0
464
+ ? `Unsupported saved Effort “${options.effort}” for ${describeModel(session.model).id}. Choose one of ${levels.join(", ")}.`
465
+ : `Unsupported saved Effort “${options.effort}” for a model with no Effort control. Clear it or use off.`);
466
+ }
454
467
  await piSession.setEffort(options.effort);
468
+ }
455
469
  else
456
470
  piSession.noteStartingEffort();
457
471
  return piSession;
@@ -524,17 +538,9 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
524
538
  }
525
539
  }
526
540
  function capabilitiesOf(session, enquiries, subagents) {
527
- const current = session.model ? describeModel(session.model).id : undefined;
528
- // The SDK populates this auth-filtered snapshot before createAgentSession resolves.
529
- const models = session.modelRuntime.getAvailableSnapshot().map((model) => {
530
- const described = describeModel(model);
531
- // pi will only answer for the model it has selected, and that answer is the authoritative one.
532
- // Every other entry is inferred from the registry and firms up if you switch to it.
533
- if (described.id !== current)
534
- return described;
535
- const available = availableEffort(session);
536
- return available.length > 0 ? { ...described, effortLevels: available } : omitEffort(described);
537
- });
541
+ // The SDK populates this auth-filtered snapshot before createAgentSession resolves. Every model is
542
+ // described directly: effort discovery is observational and must never switch the active model.
543
+ const models = session.modelRuntime.getAvailableSnapshot().map(describeModel);
538
544
  const providers = [...new Set(models.map((model) => model.provider).filter(isString))];
539
545
  return {
540
546
  providers: providers.length > 0 ? providers : ["pi"],
@@ -547,8 +553,8 @@ function capabilitiesOf(session, enquiries, subagents) {
547
553
  permissions: false,
548
554
  };
549
555
  }
550
- function describeModel(model) {
551
- const effortLevels = inferredEffort(model);
556
+ export function describeModel(model) {
557
+ const effortLevels = piEffortLevels(model);
552
558
  return {
553
559
  id: model.provider ? `${model.provider}/${model.id}` : model.id,
554
560
  ...(model.contextWindow !== undefined && Number.isFinite(model.contextWindow) && model.contextWindow > 0 ? { contextWindow: model.contextWindow } : {}),
@@ -561,26 +567,9 @@ function describeModel(model) {
561
567
  ...(model.input?.includes("image") ? { acceptsImages: true } : {}),
562
568
  };
563
569
  }
564
- /** The levels pi will accept for the model it currently has selected. */
570
+ /** The same per-model SDK answer used for non-selected catalogue entries. */
565
571
  function availableEffort(session) {
566
- return session.supportsThinking() ? session.getAvailableThinkingLevels() : [];
567
- }
568
- /**
569
- * What a model that is not currently selected probably offers. A model that cannot reason offers
570
- * nothing; otherwise its thinkingLevelMap names the levels it was configured with.
571
- */
572
- function inferredEffort(model) {
573
- if (model.reasoning === false)
574
- return [];
575
- const map = model.thinkingLevelMap;
576
- if (!map)
577
- return model.reasoning ? PI_EFFORT_LEVELS : [];
578
- return PI_EFFORT_LEVELS.filter((level) => map[level] !== undefined && map[level] !== null);
579
- }
580
- const PI_EFFORT_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
581
- function omitEffort(model) {
582
- const { effortLevels: _dropped, ...rest } = model;
583
- return rest;
572
+ return session.model ? piEffortLevels(session.model) : [];
584
573
  }
585
574
  function joinBlocks(content, kind) {
586
575
  if (typeof content === "string")
@@ -1,6 +1,7 @@
1
1
  import { piMcpTools } from "./mcp.js";
2
2
  import { createAgentSession, DefaultPackageManager, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, createReadToolDefinition, createEditToolDefinition, createWriteToolDefinition, createGrepToolDefinition, createFindToolDefinition, createLsToolDefinition, createPowerShellToolDefinition, } from "@earendil-works/pi-coding-agent";
3
3
  import { PiSession } from "./index.js";
4
+ import { piAcceptsWorkflowEffort, piEffortLevels } from "./effort-capabilities.js";
4
5
  import { piAutoCompaction } from "./auto-compaction.js";
5
6
  import { PiEnquiries } from "./enquiries.js";
6
7
  import { backgroundTools } from "./background-calls.js";
@@ -111,6 +112,13 @@ export class PiWorkflowSubagent {
111
112
  throw error;
112
113
  }
113
114
  controller.signal.throwIfAborted();
115
+ // Validate against the registry model before creating a child. This is the same SDK-backed
116
+ // rule used by the catalogue and parent capabilities, and guarantees invalid workflow input
117
+ // cannot launch agent work first and fail afterwards.
118
+ if (!piAcceptsWorkflowEffort(model, options.effort)) {
119
+ const available = model.reasoning ? ` Choose one of ${piEffortLevels(model).join(", ")}.` : " This model has no Effort control; use off.";
120
+ throw new Error(`Unsupported workflow Effort “${options.effort}” for ${options.modelId}.${available}`);
121
+ }
114
122
  let prompt = JSON.stringify(options.input);
115
123
  if (options.skill) {
116
124
  const promptTemplate = resourceLoader.getPrompts().prompts.some(candidate => candidate.name === options.skill.name);
@@ -137,9 +145,6 @@ export class PiWorkflowSubagent {
137
145
  piAutoCompaction(settingsManager, this.autoCompaction)(model);
138
146
  this.child = session;
139
147
  controller.signal.throwIfAborted();
140
- if (!session.getAvailableThinkingLevels().includes(options.effort)) {
141
- throw new Error(`Unsupported workflow Effort: ${options.effort}`);
142
- }
143
148
  session.setThinkingLevel(options.effort);
144
149
  let output = "";
145
150
  let failure;
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- 5c6019d6-3a5b-4de8-b299-042673073db0
1
+ ca236dea-ce0d-4f67-8bb5-ca21105f393d
@@ -16,6 +16,8 @@ import { answerLines } from "../client/enquiry.js";
16
16
  import { authorisationLabel } from "../client/permission.js";
17
17
  import { initialState, reduce } from "../client/reduce.js";
18
18
  import { runTui } from "../tui/app.js";
19
+ import { updateUnsupportedReason } from "./install-guard.js";
20
+ let webUpdateSupport;
19
21
  const USAGE = `usage:
20
22
  flow --version print the installed version
21
23
  flow update [--force] update a private global npm installation
@@ -159,6 +161,11 @@ const LOOPBACK = "127.0.0.1";
159
161
  async function startHost(port, address, mode = 'embedded') {
160
162
  const runtime = await startRuntime({
161
163
  root: defaultStateRoot(), version: installedVersion(), mode, assets: webClient,
164
+ ...(webUpdateSupport?.installation && webUpdateSupport.bootstrapEntry
165
+ ? { updateInstallation: { installation: webUpdateSupport.installation, bootstrapEntry: webUpdateSupport.bootstrapEntry } }
166
+ : { updateUnsupportedReason: isSea()
167
+ ? updateUnsupportedReason('sea')
168
+ : webUpdateSupport?.unsupportedReason ?? updateUnsupportedReason('source') }),
162
169
  workflowRuntime: () => isSea() ? embeddedWorkflowRuntime() : fileURLToPath(new URL('../../build/workflow-runtime.cjs', import.meta.url)),
163
170
  ...(port === undefined ? {} : { port }), ...(address === undefined ? {} : { address }),
164
171
  });
@@ -385,7 +392,8 @@ async function reachable(daemon) {
385
392
  return false;
386
393
  }
387
394
  }
388
- export function runCli() {
395
+ export function runCli(updateSupport) {
396
+ webUpdateSupport = updateSupport;
389
397
  return main()
390
398
  .then((code) => process.exit(code))
391
399
  .catch((error) => {
@@ -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 join5 } from "node:path";
5
+ import { resolve as resolve3, join as join6 } from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
7
 
8
8
  // src/cli/install-guard.ts
@@ -185,21 +185,53 @@ function registryExists(slot) {
185
185
  throw error;
186
186
  }
187
187
  }
188
- function updateEligible(slot) {
188
+ function updateIneligibility(slot, uid = process.getuid?.()) {
189
189
  slot = resolve(slot);
190
190
  const prefix = resolve(slot, "../../../..");
191
- const uid = process.getuid?.();
192
- if (slot !== join3(prefix, "lib/node_modules", packageName) || uid === 0) return false;
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() || stat.uid !== uid || (stat.mode & 18) !== 0) return false;
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() || stat.uid !== 0 && stat.uid !== uid || (stat.mode & 18) !== 0 && (stat.mode & 512) === 0) return false;
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);
@@ -403,6 +435,48 @@ async function replacePackage(npm, prefix, packageSpec) {
403
435
  if (result.code !== 0) throw new Error(`npm installation failed (${result.signal ?? result.code})`);
404
436
  }
405
437
 
438
+ // src/daemon/release-checker.ts
439
+ var STABLE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
440
+ 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-]+)*)?$/;
441
+ function parsed(version) {
442
+ const match = SEMVER.exec(version);
443
+ if (!match) return void 0;
444
+ return {
445
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
446
+ prerelease: match[4]?.split(".") ?? []
447
+ };
448
+ }
449
+ function compareIdentifiers(left, right) {
450
+ const leftNumber = /^\d+$/.test(left) ? Number(left) : void 0;
451
+ const rightNumber = /^\d+$/.test(right) ? Number(right) : void 0;
452
+ if (leftNumber !== void 0 && rightNumber !== void 0) return Math.sign(leftNumber - rightNumber);
453
+ if (leftNumber !== void 0) return -1;
454
+ if (rightNumber !== void 0) return 1;
455
+ return left.localeCompare(right);
456
+ }
457
+ function compareVersions(left, right) {
458
+ const a = parsed(left), b = parsed(right);
459
+ if (!a || !b) throw new Error("Invalid semantic version");
460
+ for (let index = 0; index < 3; index += 1) {
461
+ const difference = a.core[index] - b.core[index];
462
+ if (difference) return Math.sign(difference);
463
+ }
464
+ if (!a.prerelease.length && !b.prerelease.length) return 0;
465
+ if (!a.prerelease.length) return 1;
466
+ if (!b.prerelease.length) return -1;
467
+ for (let index = 0; index < Math.max(a.prerelease.length, b.prerelease.length); index += 1) {
468
+ const av = a.prerelease[index], bv = b.prerelease[index];
469
+ if (av === void 0) return -1;
470
+ if (bv === void 0) return 1;
471
+ const difference = compareIdentifiers(av, bv);
472
+ if (difference) return difference;
473
+ }
474
+ return 0;
475
+ }
476
+ function newerStableVersion(installed, latest) {
477
+ return STABLE.test(latest) && compareVersions(latest, installed) > 0;
478
+ }
479
+
406
480
  // src/cli/update.ts
407
481
  function npmExecutable() {
408
482
  for (const directory of (process.env.PATH ?? "").split(delimiter)) {
@@ -434,27 +508,39 @@ async function verify(install, transaction, expected) {
434
508
  await transaction.assertAuthorizationConsumed();
435
509
  return version;
436
510
  }
437
- async function restore(install, transaction, root, host, version) {
438
- const env = await transaction.authorizeRestoration(backgroundHostArgs(host.settings));
511
+ async function restore(install, transaction, root, host, version, preserveConcretePort) {
512
+ const settings = preserveConcretePort && host.settings.port === 0 ? { ...host.settings, port: Number(new URL(host.url).port) } : host.settings;
513
+ const env = await transaction.authorizeRestoration(backgroundHostArgs(settings));
439
514
  await launchBackground({
440
515
  root,
441
- settings: host.settings,
516
+ settings,
442
517
  entry: [join4(install.slot, "dist/cli/bootstrap.js")],
443
518
  env,
444
519
  validate(status) {
445
- if (status.instanceId === host.instanceId || status.version !== version || status.mode !== "background" || ["port", "address", "cwd", "oidc"].some((key) => status.settings[key] !== host.settings[key])) {
520
+ if (status.instanceId === host.instanceId || status.version !== version || status.mode !== "background" || ["port", "address", "cwd", "oidc"].some((key) => status.settings[key] !== settings[key])) {
446
521
  throw new Error("Restored Session Host settings or version differ");
447
522
  }
448
523
  }
449
524
  });
450
525
  await transaction.assertAuthorizationConsumed();
451
526
  }
452
- async function update(install, lease, args) {
453
- if (args.length > 2 || args[0] !== "update" || args.length === 2 && args[1] !== "--force") throw new Error("usage: flow update [--force]");
527
+ function inspectUpdateInstallation(install) {
454
528
  const npm = npmExecutable();
455
529
  const prefix = npmPath(npm, "prefix"), root = npmPath(npm, "root");
456
530
  if (prefix !== install.prefix || root !== join4(prefix, "lib/node_modules") || realpathSync4(join4(root, packageName)) !== install.slot) throw new Error("npm selects a different installation. Put the matching npm in PATH and select its prefix.");
457
- const previous = packageVersion(install.slot);
531
+ return { npm, version: packageVersion(install.slot) };
532
+ }
533
+ async function update(install, lease, args, options = {}) {
534
+ if (args.length > 2 || args[0] !== "update" || args.length === 2 && args[1] !== "--force") throw new Error("usage: flow update [--force]");
535
+ const inspected = inspectUpdateInstallation(install);
536
+ const npm = inspected.npm;
537
+ const prefix = install.prefix;
538
+ const previous = inspected.version;
539
+ if (options.expectedVersion !== void 0 && !newerStableVersion(previous, options.expectedVersion)) {
540
+ throw new Error(`The confirmed web update target ${options.expectedVersion} is not a newer stable release`);
541
+ }
542
+ const target = options.expectedVersion ?? "latest";
543
+ const preserveConcretePort = options.preserveConcreteHostPort === true;
458
544
  let host = readHost(lease.root);
459
545
  if (host && processAlive(host.pid)) {
460
546
  const status = await getHostStatus(host);
@@ -470,7 +556,7 @@ async function update(install, lease, args) {
470
556
  await replacePackage(npm, prefix, `${packageName}@${version}`);
471
557
  const installed = await verify(install, transaction, expected);
472
558
  if (host && needsRestoration) {
473
- await restore(install, transaction, lease.root, host, installed);
559
+ await restore(install, transaction, lease.root, host, installed, preserveConcretePort);
474
560
  needsRestoration = false;
475
561
  }
476
562
  await transaction.complete();
@@ -488,15 +574,16 @@ async function update(install, lease, args) {
488
574
  const pid = host.pid;
489
575
  await waitUntil(async () => !processAlive(pid), "Session Host process did not exit; installation was not changed");
490
576
  }
491
- const version = await replace("latest");
577
+ const version = await replace(target, options.expectedVersion);
492
578
  console.log(version === previous ? `Flow is already at ${version}.` : `Flow updated: ${previous} \u2192 ${version}`);
579
+ return { previousVersion: previous, installedVersion: version, changed: version !== previous };
493
580
  } catch (error) {
494
581
  if (error instanceof InstallationProcessUncertain) throw new Error(`${String(error)}. ${repair()}`);
495
582
  if (!replacing) {
496
583
  if (needsRestoration && host && processAlive(host.pid)) throw new Error(`${String(error)}. No package files were changed; wait for the stopping host to exit. ${repair()}`);
497
584
  if (needsRestoration && host) {
498
585
  try {
499
- await restore(install, transaction, lease.root, host, previous);
586
+ await restore(install, transaction, lease.root, host, previous, preserveConcretePort);
500
587
  } catch (failure) {
501
588
  throw new Error(`${String(error)}; restoration failed: ${String(failure)}. ${repair()}`);
502
589
  }
@@ -513,21 +600,170 @@ async function update(install, lease, args) {
513
600
  }
514
601
  }
515
602
 
603
+ // src/cli/web-update.ts
604
+ import { randomUUID as randomUUID3 } from "node:crypto";
605
+ import {
606
+ closeSync as closeSync2,
607
+ constants as constants3,
608
+ fchmodSync as fchmodSync2,
609
+ mkdirSync as mkdirSync4,
610
+ openSync as openSync2,
611
+ readFileSync as readFileSync4,
612
+ readdirSync as readdirSync3,
613
+ renameSync as renameSync3,
614
+ rmdirSync as rmdirSync3,
615
+ unlinkSync as unlinkSync3,
616
+ writeFileSync as writeFileSync3
617
+ } from "node:fs";
618
+ import { join as join5 } from "node:path";
619
+ var STATUS_FILE = "web-update.json";
620
+ var STATUS_LOCK = "web-update-lock";
621
+ var STATUS_LOCK_ATTEMPTS = 100;
622
+ var STATUS_LOCK_WAIT_MS = 25;
623
+ function statusPath(root) {
624
+ return join5(root, STATUS_FILE);
625
+ }
626
+ function readOperation(root) {
627
+ try {
628
+ const value = JSON.parse(readFileSync4(statusPath(root), "utf8"));
629
+ if (!value || typeof value.id !== "string" || !["updating", "succeeded", "failed", "unverified"].includes(value.state)) return void 0;
630
+ return value;
631
+ } catch {
632
+ return void 0;
633
+ }
634
+ }
635
+ function writeOperation(root, operation) {
636
+ const temporary = join5(root, `${STATUS_FILE}-${process.pid}-${randomUUID3()}`);
637
+ writeFileSync3(temporary, JSON.stringify(operation), { mode: 384 });
638
+ renameSync3(temporary, statusPath(root));
639
+ }
640
+ function removeLockOwner(path, filename) {
641
+ try {
642
+ unlinkSync3(join5(path, filename));
643
+ } catch (error) {
644
+ if (error.code !== "ENOENT") throw error;
645
+ }
646
+ try {
647
+ rmdirSync3(path);
648
+ } catch (error) {
649
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) throw error;
650
+ }
651
+ }
652
+ function sleep(milliseconds) {
653
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
654
+ }
655
+ function transitionOperation(root, transition) {
656
+ const ownerId = randomUUID3();
657
+ const filename = `${ownerId}.json`;
658
+ const candidate = join5(root, `${STATUS_LOCK}-${ownerId}`);
659
+ const lock = join5(root, STATUS_LOCK);
660
+ mkdirSync4(candidate, { mode: 448 });
661
+ writeFileSync3(join5(candidate, filename), JSON.stringify({ pid: process.pid, id: ownerId }), { mode: 384 });
662
+ let acquired = false;
663
+ try {
664
+ for (let attempt = 0; !acquired; attempt++) {
665
+ try {
666
+ renameSync3(candidate, lock);
667
+ acquired = true;
668
+ } catch (error) {
669
+ if (!["ENOTEMPTY", "EEXIST"].includes(error.code ?? "")) throw error;
670
+ if (attempt >= STATUS_LOCK_ATTEMPTS) throw new Error("Web update status is busy");
671
+ let entries;
672
+ try {
673
+ entries = readdirSync3(lock);
674
+ } catch (readError) {
675
+ if (readError.code === "ENOENT") continue;
676
+ throw readError;
677
+ }
678
+ if (entries.length === 0) {
679
+ sleep(STATUS_LOCK_WAIT_MS);
680
+ continue;
681
+ }
682
+ if (entries.length !== 1 || !/^[a-f0-9-]+\.json$/.test(entries[0])) throw new Error("Invalid web update status owner");
683
+ let owner2;
684
+ try {
685
+ owner2 = JSON.parse(readFileSync4(join5(lock, entries[0]), "utf8"));
686
+ } catch (readError) {
687
+ if (readError.code === "ENOENT") continue;
688
+ throw readError;
689
+ }
690
+ if (!owner2 || typeof owner2 !== "object" || !Number.isInteger(owner2.pid) || owner2.pid <= 0 || owner2.id !== entries[0].slice(0, -5)) {
691
+ throw new Error("Invalid web update status owner");
692
+ }
693
+ if (!processAlive(owner2.pid)) removeLockOwner(lock, entries[0]);
694
+ sleep(STATUS_LOCK_WAIT_MS);
695
+ }
696
+ }
697
+ const current = readOperation(root);
698
+ const next = transition(current);
699
+ if (next !== void 0 && next !== current) writeOperation(root, next);
700
+ return next;
701
+ } finally {
702
+ removeLockOwner(acquired ? lock : candidate, filename);
703
+ }
704
+ }
705
+ function publicError(error) {
706
+ const message = error instanceof Error ? error.message : String(error);
707
+ return message.replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/((?:token|secret|password)[=:]\s*)[^\s;,]+/gi, "$1[redacted]").slice(0, 2e3);
708
+ }
709
+ function finishWebUpdate(root, id, result, error) {
710
+ transitionOperation(root, (current) => {
711
+ if (!current || current.id !== id || !["updating", "unverified"].includes(current.state)) return current;
712
+ const finishedAt = (/* @__PURE__ */ new Date()).toISOString();
713
+ if (error !== void 0) return { ...current, state: "failed", finishedAt, message: publicError(error) };
714
+ if (!result?.changed) {
715
+ return {
716
+ ...current,
717
+ state: "failed",
718
+ installedVersion: result?.installedVersion ?? current.previousVersion,
719
+ finishedAt,
720
+ message: `npm completed, but Flow remains at ${result?.installedVersion ?? current.previousVersion}. No update was installed.`
721
+ };
722
+ }
723
+ return {
724
+ ...current,
725
+ state: "succeeded",
726
+ installedVersion: result.installedVersion,
727
+ finishedAt,
728
+ message: `Flow updated from ${result.previousVersion} to ${result.installedVersion}.`
729
+ };
730
+ });
731
+ }
732
+
516
733
  // src/cli/bootstrap.ts
517
734
  async function bootstrap() {
518
735
  const slot = resolve3(fileURLToPath(new URL("../..", import.meta.url)));
519
736
  const args = process.argv.slice(2);
520
- const root = canonicalRoot(process.env.FLOW_STATE_DIR ?? join5(homedir(), ".flow"));
737
+ const root = canonicalRoot(process.env.FLOW_STATE_DIR ?? join6(homedir(), ".flow"));
521
738
  const globalSlot = slot.endsWith("/lib/node_modules/@nathanstephenson/flow");
739
+ let updateSupport;
522
740
  if (globalSlot && (args[0] === "update" || updateEligible(slot) || registryExists(slot))) {
523
741
  const install = installation(slot);
524
- const lease = await install.register("5c6019d6-3a5b-4de8-b299-042673073db0", root, args, process.env.FLOW_UPDATE_CAPABILITY);
742
+ const lease = await install.register("ca236dea-ce0d-4f67-8bb5-ca21105f393d", root, args, process.env.FLOW_UPDATE_CAPABILITY);
525
743
  delete process.env.FLOW_UPDATE_CAPABILITY;
526
744
  process.on("exit", lease.release);
527
- if (args[0] === "update") return update(install, lease, args);
528
- } else if (args[0] === "update") throw new Error("Self-update requires a private global npm installation; source and npm link are unsupported");
745
+ if (args[0] === "update") {
746
+ const webId = process.env.FLOW_WEB_UPDATE_ID;
747
+ const webVersion = process.env.FLOW_WEB_UPDATE_VERSION;
748
+ delete process.env.FLOW_WEB_UPDATE_ID;
749
+ delete process.env.FLOW_WEB_UPDATE_VERSION;
750
+ try {
751
+ if (webId === void 0 !== (webVersion === void 0)) throw new Error("Web update authorization is incomplete");
752
+ const result = await update(install, lease, args, webId ? { expectedVersion: webVersion, preserveConcreteHostPort: true } : {});
753
+ if (webId) finishWebUpdate(root, webId, result);
754
+ return;
755
+ } catch (error) {
756
+ if (webId) finishWebUpdate(root, webId, void 0, error);
757
+ throw error;
758
+ }
759
+ }
760
+ updateSupport = { installation: install, bootstrapEntry: fileURLToPath(import.meta.url) };
761
+ } else {
762
+ 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");
763
+ updateSupport = { unsupportedReason: explainUnsupportedUpdate(slot) };
764
+ }
529
765
  const { runCli } = await import(new URL("./application.js", import.meta.url).href);
530
- await runCli();
766
+ await runCli(updateSupport);
531
767
  }
532
768
  bootstrap().catch((error) => {
533
769
  console.error(error instanceof Error ? error.message : error);
@@ -76,25 +76,68 @@ export function registryExists(slot) {
76
76
  throw error;
77
77
  }
78
78
  }
79
- export function updateEligible(slot) {
79
+ function updateIneligibility(slot, uid = process.getuid?.()) {
80
80
  slot = resolve(slot);
81
81
  const prefix = resolve(slot, '../../../..');
82
- const uid = process.getuid?.();
83
- if (slot !== join(prefix, 'lib/node_modules', packageName) || uid === 0)
84
- return false;
82
+ if (slot !== join(prefix, 'lib/node_modules', packageName))
83
+ return 'source';
84
+ if (uid === undefined || uid === 0)
85
+ return 'root';
85
86
  for (const path of [prefix, join(prefix, 'lib'), join(prefix, 'lib/node_modules'), join(prefix, 'lib/node_modules/@nathanstephenson'), slot]) {
86
87
  const stat = lstatSync(path);
87
- if (stat.isSymbolicLink() || stat.uid !== uid || (stat.mode & 0o022) !== 0)
88
- return false;
88
+ if (stat.isSymbolicLink())
89
+ return 'npm-link';
90
+ if (stat.uid !== uid)
91
+ return 'system';
92
+ if ((stat.mode & 0o022) !== 0)
93
+ return 'shared';
89
94
  }
90
95
  for (let path = dirname(prefix);; path = dirname(path)) {
91
96
  const stat = lstatSync(path);
92
- if (stat.isSymbolicLink() || (stat.uid !== 0 && stat.uid !== uid) || ((stat.mode & 0o022) !== 0 && (stat.mode & 0o1000) === 0))
93
- return false;
97
+ if (stat.isSymbolicLink())
98
+ return 'npm-link';
99
+ if (stat.uid !== 0 && stat.uid !== uid)
100
+ return 'system';
101
+ if ((stat.mode & 0o022) !== 0 && (stat.mode & 0o1000) === 0)
102
+ return 'shared';
94
103
  if (dirname(path) === path)
95
104
  break;
96
105
  }
97
- return realpathSync(prefix) === prefix;
106
+ return realpathSync(prefix) === prefix ? undefined : 'npm-link';
107
+ }
108
+ function pathHasSymlink(path) {
109
+ for (let current = resolve(path);; current = dirname(current)) {
110
+ try {
111
+ if (lstatSync(current).isSymbolicLink())
112
+ return true;
113
+ }
114
+ catch (error) {
115
+ if (error.code !== 'ENOENT')
116
+ throw error;
117
+ }
118
+ if (dirname(current) === current)
119
+ return false;
120
+ }
121
+ }
122
+ export function updateUnsupportedReason(kind) {
123
+ return {
124
+ source: 'A source checkout cannot update itself. Install or update Flow through a private global npm prefix.',
125
+ 'npm-link': 'An npm-linked Flow checkout cannot update itself. Remove the link and install Flow in a private global npm prefix.',
126
+ sea: 'Single-executable Flow builds cannot update themselves. Install the new binary manually.',
127
+ shared: 'A shared or group/other-writable global npm installation cannot update itself. Use a private, user-owned npm prefix without sudo.',
128
+ system: 'A system-owned or another user\'s global npm installation cannot update itself. Install Flow in your own private npm prefix without sudo.',
129
+ root: 'A root-owned or sudo-installed Flow cannot update itself. Install Flow as your normal user in a private npm prefix.',
130
+ }[kind];
131
+ }
132
+ /** Explain why this process cannot expose web self-update without mislabelling global installs as source. */
133
+ export function explainUnsupportedUpdate(slot, entry = process.argv[1], uid = process.getuid?.()) {
134
+ let kind = updateIneligibility(slot, uid) ?? 'source';
135
+ if (kind === 'source' && entry && pathHasSymlink(entry))
136
+ kind = 'npm-link';
137
+ return updateUnsupportedReason(kind);
138
+ }
139
+ export function updateEligible(slot) {
140
+ return updateIneligibility(slot) === undefined;
98
141
  }
99
142
  export function installation(slot) {
100
143
  slot = resolve(slot);