@nathanstephenson/flow 0.1.7 → 0.1.8

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 (76) hide show
  1. package/README.md +122 -640
  2. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +94 -0
  3. package/build/backend-worker-chunks/chunk-MLOUI3ZM.mjs +19752 -0
  4. package/build/backend-worker-chunks/chunk-UQDH2COY.mjs +15296 -0
  5. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +30778 -0
  6. package/build/backend-worker-chunks/pi-M4OA2FGL.mjs +5730 -0
  7. package/build/backend-worker.mjs +4401 -0
  8. package/dist/backend/fake/index.js +2 -0
  9. package/dist/backend/mcp.js +34 -15
  10. package/dist/backend/pi/state.js +18 -0
  11. package/dist/backend/registry.js +2 -1
  12. package/dist/backend/worker/claude-state.js +24 -3
  13. package/dist/backend/worker/entry.js +70 -13
  14. package/dist/backend/worker/frames.js +34 -0
  15. package/dist/backend/worker/index.js +139 -16
  16. package/dist/backend/worker/launcher.js +22 -3
  17. package/dist/backend/worker/sandbox-mcp.js +86 -0
  18. package/dist/build-id +1 -1
  19. package/dist/cli/bootstrap.js +7 -6
  20. package/dist/cli/install-guard.js +1 -1
  21. package/dist/cli/main.js +3 -6
  22. package/dist/cli/update.js +3 -3
  23. package/dist/cli/web-update.js +9 -6
  24. package/dist/client/connection.js +5 -2
  25. package/dist/client/diff.js +6 -9
  26. package/dist/client/reduce.js +19 -0
  27. package/dist/client/tool-chains.js +12 -4
  28. package/dist/daemon/config-store.js +21 -14
  29. package/dist/daemon/config.js +48 -5
  30. package/dist/daemon/git.js +47 -0
  31. package/dist/daemon/host.js +208 -29
  32. package/dist/daemon/models.js +27 -24
  33. package/dist/daemon/release-checker.js +48 -34
  34. package/dist/daemon/runtime.js +10 -4
  35. package/dist/daemon/server.js +13 -1
  36. package/dist/daemon/shell.js +2 -1
  37. package/dist/daemon/skills.js +34 -31
  38. package/dist/daemon/summariser.js +33 -14
  39. package/dist/daemon/timings.js +14 -0
  40. package/dist/daemon/workflow-authoring-scope-checks.js +5 -8
  41. package/dist/daemon/workflow-authoring-scope-reader.js +20 -9
  42. package/dist/daemon/workflow-builder-files.js +5 -5
  43. package/dist/daemon/workflow-builder-guidance.js +3 -3
  44. package/dist/daemon/workflow-builder-reader.js +21 -10
  45. package/dist/daemon/workflow-builder.js +66 -8
  46. package/dist/daemon/workflow-executions.js +10 -10
  47. package/dist/daemon/workflow-mcp-authoring-routes.js +18 -6
  48. package/dist/daemon/workflow-mcp-authoring.js +44 -20
  49. package/dist/isolation/filesystem.js +8 -9
  50. package/dist/isolation/sandbox-supervisor.js +50 -0
  51. package/dist/isolation/sandbox.js +165 -0
  52. package/dist/isolation/shared-sandbox.js +77 -0
  53. package/dist/workflows/executors.js +16 -4
  54. package/dist/workflows/json-schema.js +14 -4
  55. package/package.json +7 -4
  56. package/web/dist/assets/index-CiEgCpiO.js +40 -0
  57. package/web/dist/assets/index-ClwLFMZN.css +2 -0
  58. package/web/dist/assets/settings-mcp-CoRWT-D_.js +1 -0
  59. package/web/dist/assets/settings-secrets-BIO_hXZ1.js +1 -0
  60. package/web/dist/assets/settings-workflows-BXbj0TKs.js +23 -0
  61. package/web/dist/assets/switch-DIogWclb.js +1 -0
  62. package/web/dist/assets/workflow-api-BfExddae.js +6 -0
  63. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +139 -0
  64. package/web/dist/assets/workflows-Bv0sj7d0.js +7 -0
  65. package/web/dist/assets/workflows-pane-C_Yg4pgr.js +1 -0
  66. package/web/dist/index.html +5 -5
  67. package/web/dist/assets/index-DxTV-TYZ.js +0 -38
  68. package/web/dist/assets/index-jwsr3cpu.css +0 -2
  69. package/web/dist/assets/input-BOuBzJVY.js +0 -6
  70. package/web/dist/assets/settings-mcp-D-jWezcS.js +0 -1
  71. package/web/dist/assets/settings-secrets-DdQ0eujd.js +0 -1
  72. package/web/dist/assets/settings-workflows-BCzYKkOk.js +0 -23
  73. package/web/dist/assets/switch-B0hMd_dH.js +0 -1
  74. package/web/dist/assets/workflow-editors-CDZqnDvT.js +0 -137
  75. package/web/dist/assets/workflows-BpPNiK-H.js +0 -7
  76. package/web/dist/assets/workflows-pane-N3Vf30Cb.js +0 -1
@@ -1,7 +1,8 @@
1
1
  import { credentialKey } from "./credential-redaction.js";
2
2
  import { randomUUID } from "node:crypto";
3
- import { realpathSync } from "node:fs";
4
- import { resolve } from "node:path";
3
+ import { existsSync, realpathSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { validateFilesystemScope } from "../isolation/filesystem.js";
5
6
  import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest } from "./pull-request.js";
6
7
  import { stackStatus, actionStackStatus, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
7
8
  import { gitStatus, snapshot, target, branchChanges, canNameBranch, publish } from "./publish.js";
@@ -10,10 +11,12 @@ import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_AT
10
11
  import { deriveStatus, railGroupRank } from "../client/status.js";
11
12
  // `switchBranch` is aliased because this class has a method of that name: the method is the
12
13
  // Session Host's refusal-and-record wrapper, and the import is the git invocation it wraps.
13
- import { createWorktree, head, isClean, isRepository, removeWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
14
+ import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
14
15
  import { SessionLog } from "./log.js";
15
16
  import { probeModels } from "./models.js";
16
17
  import { probeSkills } from "./skills.js";
18
+ import { recordTiming } from "./timings.js";
19
+ import { SharedSandbox } from "../isolation/shared-sandbox.js";
17
20
  import { nameInput, summarisePublish, suggestedBranch, SummaryModelSpare } from "./summariser.js";
18
21
  /**
19
22
  * A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
@@ -21,9 +24,15 @@ import { nameInput, summarisePublish, suggestedBranch, SummaryModelSpare } from
21
24
  *
22
25
  * Named for its subject the way `ConfigError` is, and its message written to be read by whoever
23
26
  * sent the command. That is the whole distinction it exists to draw: a refusal is the caller's to
24
- * fix and is safe to pass back, while anything else is ours and becomes a 500.
27
+ * fix and is safe to pass back, while anything else is ours and becomes a 500. `code` lets a client
28
+ * act on one refusal without reading its message.
25
29
  */
26
30
  export class CommandRefused extends Error {
31
+ code;
32
+ constructor(message, code) {
33
+ super(message);
34
+ this.code = code;
35
+ }
27
36
  }
28
37
  /** Owns every Agent Session, and the Steering Queue that sits above all backends (ADR 0002). */
29
38
  export class SessionHost {
@@ -31,6 +40,8 @@ export class SessionHost {
31
40
  backends = new Map();
32
41
  /** Model probes by backend name, held in flight rather than resolved — see `models`. */
33
42
  modelProbes = new Map();
43
+ /** One warm Skills session per Backend Adapter, for the last Scope asked — see `skillsFor` (ADR 0035). */
44
+ skillSessions = new Map();
34
45
  /**
35
46
  * Skill probes by Backend Adapter and Scope, held *only* while in flight — see `skillsFor`.
36
47
  *
@@ -210,11 +221,17 @@ export class SessionHost {
210
221
  backendFailures = new Set();
211
222
  keptListeners = new Set();
212
223
  filesystemIsolation;
224
+ sandbox;
225
+ sandboxSharing;
226
+ shared;
213
227
  mcpConnections;
214
228
  mcpAuth;
215
229
  resolveSecret;
216
230
  constructor(options = {}) {
217
- this.filesystemIsolation = options.filesystemIsolationEnabled;
231
+ this.filesystemIsolation = options.filesystemIsolationMode;
232
+ this.sandbox = options.sandboxSupport;
233
+ this.sandboxSharing = options.sandboxSharing;
234
+ this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
218
235
  this.mcpConnections = options.mcpConnections;
219
236
  this.mcpAuth = options.mcpAuth;
220
237
  this.resolveSecret = options.resolveSecret;
@@ -249,7 +266,7 @@ export class SessionHost {
249
266
  /**
250
267
  * Notified when a reap left a worktree on disk rather than removing it.
251
268
  *
252
- * Only a clean worktree is removed: a branch ref always survives a reap, so no commit is ever
269
+ * Only a clean worktree is removed: unmerged branch refs survive a reap, so no commit is ever
253
270
  * lost, but uncommitted and untracked work would be — and deleting that on a retention timer,
254
271
  * from a sweep nobody is watching, is a second destructive act ADR 0006 does not license.
255
272
  *
@@ -286,7 +303,7 @@ export class SessionHost {
286
303
  const held = this.modelProbes.get(backend.name);
287
304
  if (held)
288
305
  return held;
289
- const probe = probeModels(backend, scope);
306
+ const probe = this.timed("models", backend, false, (timed) => probeModels(timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false)));
290
307
  this.modelProbes.set(backend.name, probe);
291
308
  return probe;
292
309
  });
@@ -300,13 +317,12 @@ export class SessionHost {
300
317
  * it is here and not folded into that: they share a word and nothing else, and a shared helper
301
318
  * would be one `try` bought by dragging one of two return shapes onto the other.
302
319
  *
303
- * **Held in flight and never after.** The entry is deleted as the probe settles, so two clients
304
- * asking at once spawn one backend between them, and the next ask after that spawns another. That
305
- * is deliberately unlike `models` directly above: a model list changes when an account's
306
- * entitlements do, while a Skill directory changes when somebody saves a file, and ADR 0020
307
- * already drew that line between `/api/models` and `/api/branches`. Skills are on the
308
- * `/api/branches` side. What makes the spawn affordable is the client asking early — when its
309
- * Scope field settles rather than when the menu opens — not the host holding a stale answer.
320
+ * **The answer is held in flight; the session is kept warm (ADR 0035).** Two clients asking at
321
+ * once share one probe. After it settles, its Backend Session stays in `skillSessions` for that
322
+ * backend and Scope, and the next ask calls `skills()` on it again, which reads the disk again. A
323
+ * new Scope replaces the warm session. A warm session that reported an error, or whose `skills()`
324
+ * throws, is dropped and the ask falls back to one cold probe. The startup model probe fills an
325
+ * empty slot, so the first ask after host start is warm too.
310
326
  *
311
327
  * Never throws, so the route never falls through to `serve`'s blanket 500: an unknown Backend
312
328
  * Adapter is reported as a `problem` like any other reason a list might be empty.
@@ -320,12 +336,58 @@ export class SessionHost {
320
336
  const held = this.skillProbes.get(key);
321
337
  if (held)
322
338
  return await held;
323
- const probe = probeSkills(backend, scope).finally(() => {
339
+ const probe = this.askSkills(backend, scope).finally(() => {
324
340
  this.skillProbes.delete(key);
325
341
  });
326
342
  this.skillProbes.set(key, probe);
327
343
  return await probe;
328
344
  }
345
+ async askSkills(backend, scope) {
346
+ const warm = this.skillSessions.get(backend.name);
347
+ if (warm?.scope === scope && !warm.dead && warm.session.skills) {
348
+ try {
349
+ return await this.timed("skills", backend, true, async () => ({ backend: backend.name, scope, skills: await warm.session.skills() }));
350
+ }
351
+ catch {
352
+ this.skillSessions.delete(backend.name);
353
+ void warm.session.dispose().catch(() => { });
354
+ }
355
+ }
356
+ return await this.timed("skills", backend, false, (timed) => probeSkills(timed, scope, (held) => this.holdSkillSession(backend.name, held, true)));
357
+ }
358
+ /** `replace` is false for the model probe: it fills an empty or dead slot and never replaces a live one. */
359
+ holdSkillSession(name, held, replace) {
360
+ const old = this.skillSessions.get(name);
361
+ if (this.workflowShutdown || (old && !old.dead && !replace)) {
362
+ void held.session.dispose().catch(() => { });
363
+ return;
364
+ }
365
+ this.skillSessions.set(name, held);
366
+ if (old)
367
+ void old.session.dispose().catch(() => { });
368
+ }
369
+ /** Records `create` (time in `backend.create`), `answer` and `total` to the timings file. */
370
+ async timed(kind, backend, warm, probe) {
371
+ const begin = performance.now();
372
+ let create = 0;
373
+ const timed = { name: backend.name, create: async (options) => {
374
+ const start = performance.now();
375
+ try {
376
+ return await backend.create(options);
377
+ }
378
+ finally {
379
+ create = performance.now() - start;
380
+ }
381
+ } };
382
+ try {
383
+ return await probe(timed);
384
+ }
385
+ finally {
386
+ const total = performance.now() - begin;
387
+ if (this.store)
388
+ recordTiming(this.store.root, { kind, backend: backend.name, warm, create: Math.round(create), answer: Math.round(total - create), total: Math.round(total) });
389
+ }
390
+ }
329
391
  logFor(sessionId) {
330
392
  return this.record(sessionId).log;
331
393
  }
@@ -429,6 +491,10 @@ export class SessionHost {
429
491
  ...(record.capabilities ? { capabilities: record.capabilities } : {}),
430
492
  ...(record.branch ? { branch: record.branch } : {}),
431
493
  ...(record.worktree ? { worktree: true } : {}),
494
+ ...(record.session || existsSync(record.scope) ? {} : {
495
+ scopeMissing: true,
496
+ ...this.suggestion(record.scope),
497
+ }),
432
498
  };
433
499
  })
434
500
  /* Attention groups are newest qualifying event first. Ordinary groups retain Resting/filed
@@ -703,6 +769,9 @@ export class SessionHost {
703
769
  /** Attach a fresh Backend Session to a Dormant Agent Session, continuing the same transcript. */
704
770
  async revive(sessionId) {
705
771
  const record = this.record(sessionId);
772
+ if (!record.session && !existsSync(record.scope)) {
773
+ throw new CommandRefused(`Scope ${record.scope} no longer exists. Relocate this Agent Session to revive it.`, "scope_missing");
774
+ }
706
775
  this.refuseGitOperation(record.scope);
707
776
  if (record.session)
708
777
  return;
@@ -725,6 +794,67 @@ export class SessionHost {
725
794
  record.reviving = undefined;
726
795
  }
727
796
  }
797
+ /**
798
+ * Bind a Dormant Agent Session to a new Scope, only because its old Scope is gone (ADR 0036).
799
+ *
800
+ * The backend record moves first and the meta is written last, so a failure leaves the old
801
+ * binding whole.
802
+ */
803
+ async relocate(sessionId, scope, repo) {
804
+ const record = this.record(sessionId);
805
+ const from = record.scope;
806
+ if (record.session || record.reviving)
807
+ throw new CommandRefused("This Agent Session is running. Only a stopped Agent Session can relocate.");
808
+ if (existsSync(from))
809
+ throw new CommandRefused(`Scope ${from} still exists. An Agent Session keeps its Scope while it exists.`);
810
+ const to = this.relocationFolder(scope);
811
+ let worktree = record.worktree;
812
+ if (worktree) {
813
+ if (!repo)
814
+ throw new CommandRefused("Choose the repository of this Worktree.");
815
+ const repository = this.relocationFolder(repo);
816
+ if (!isRepository(repository))
817
+ throw new CommandRefused(`${repository} is not a git repository`);
818
+ const repaired = await repairWorktree(repository, to);
819
+ if (!repaired.ok)
820
+ throw new CommandRefused(repaired.failure.message);
821
+ if (record.scope !== from || record.session || record.reviving)
822
+ throw new CommandRefused("This Agent Session changed during the relocation. Try again.");
823
+ worktree = { ...worktree, path: to, repo: repository };
824
+ }
825
+ const backend = this.backendFor(record.backendName);
826
+ const stateDir = this.store?.backendDir(record.id);
827
+ if (stateDir)
828
+ backend.relocate?.(stateDir, from, to);
829
+ const previous = record.worktree;
830
+ record.scope = to;
831
+ record.worktree = worktree;
832
+ try {
833
+ this.persist(record);
834
+ }
835
+ catch (error) {
836
+ record.scope = from;
837
+ record.worktree = previous;
838
+ if (stateDir)
839
+ backend.relocate?.(stateDir, to, from);
840
+ throw error;
841
+ }
842
+ }
843
+ /** A folder the user chose for a relocation, resolved and checked as a Scope is before a restricted launch. */
844
+ relocationFolder(folder) {
845
+ if (!existsSync(folder))
846
+ throw new CommandRefused(`${folder} does not exist`);
847
+ try {
848
+ return validateFilesystemScope({ scope: folder, expectedScope: resolve(folder), ...(this.store ? { stateRoot: this.store.root } : {}) });
849
+ }
850
+ catch (error) {
851
+ throw new CommandRefused(error instanceof Error ? error.message : String(error));
852
+ }
853
+ }
854
+ suggestion(scope) {
855
+ const suggested = this.store && suggestedScope(scope, this.store.worktreesRoot());
856
+ return suggested ? { suggestedScope: suggested } : {};
857
+ }
728
858
  async reviveOnce(record) {
729
859
  const fromSeq = record.log.lastSeq;
730
860
  record.buffered = [];
@@ -741,7 +871,7 @@ export class SessionHost {
741
871
  // one this Revive just undid.
742
872
  record.settledAt = undefined;
743
873
  record.restingAt = new Date().toISOString();
744
- record.log.append({ type: "revived", fromSeq });
874
+ record.log.append({ type: "revived", fromSeq, scope: record.scope });
745
875
  this.flushBuffered(record);
746
876
  // A Dormant Agent Session may have sat for a week while its Scope was moved by hand.
747
877
  await this.refreshBranch(record);
@@ -1698,10 +1828,8 @@ export class SessionHost {
1698
1828
  /**
1699
1829
  * Remove a reaped session's worktree, but only while it is clean.
1700
1830
  *
1701
- * `git worktree remove` never deletes the branch ref or the commits on it, so committed work
1702
- * survives a reap and is reachable by name afterwards. The only thing at risk is what was never
1703
- * committed, which is why one `status --porcelain` is the whole safety rule — and why a dirty
1704
- * worktree is left where it is and announced instead.
1831
+ * Unmerged branch refs survive a reap. Local branches merged into the source repository's branch
1832
+ * are removed after the worktree, unless Git refuses. Uncommitted work stays in a dirty worktree.
1705
1833
  */
1706
1834
  async releaseWorktree(record) {
1707
1835
  const worktree = record.worktree;
@@ -1721,9 +1849,17 @@ export class SessionHost {
1721
1849
  kept("it has uncommitted changes");
1722
1850
  return;
1723
1851
  }
1852
+ const current = await head(worktree.path);
1724
1853
  const removed = await removeWorktree({ repo: worktree.repo, path: worktree.path });
1725
- if (!removed.ok)
1854
+ if (!removed.ok) {
1726
1855
  kept(removed.failure.message);
1856
+ return;
1857
+ }
1858
+ const branches = new Set([worktree.branch]);
1859
+ if (current.ok && !current.value.detached)
1860
+ branches.add(current.value.name);
1861
+ for (const branch of branches)
1862
+ await removeMergedBranch(worktree.repo, branch);
1727
1863
  }
1728
1864
  /**
1729
1865
  * Name this Agent Session again, from its Presentation Transcript, with the Summary Model.
@@ -1756,9 +1892,10 @@ export class SessionHost {
1756
1892
  throw new CommandRefused(`No backend named ${summary.backend} — check the Summary Model in Settings`);
1757
1893
  }
1758
1894
  const generation = (record.titleGeneration += 1);
1759
- const name = await this.summarySpare.name(backend, summary, nameInput(entries));
1895
+ let reason;
1896
+ const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; });
1760
1897
  if (name === undefined)
1761
- throw new CommandRefused("Could not name this Agent Session");
1898
+ throw new CommandRefused(`Could not name this Agent Session${reason ? `: ${reason}` : ""}`);
1762
1899
  // Refused rather than applied when something newer has already been asked for. A human who
1763
1900
  // clicked twice wants the second answer, and the first arriving afterwards must not undo it.
1764
1901
  if (record.titleGeneration !== generation)
@@ -1817,6 +1954,9 @@ export class SessionHost {
1817
1954
  // that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
1818
1955
  // `SummaryModelSpare.dispose`.
1819
1956
  this.summarySpare.dispose();
1957
+ const warm = [...this.skillSessions.values()];
1958
+ this.skillSessions.clear();
1959
+ await Promise.all(warm.map((held) => held.session.dispose().catch(() => { })));
1820
1960
  await Promise.all(this.backendFailures);
1821
1961
  for (const record of this.sessions.values()) {
1822
1962
  if (!record.session)
@@ -1835,6 +1975,7 @@ export class SessionHost {
1835
1975
  record.log.append({ type: "session_dormant", reason: "host shutdown" });
1836
1976
  this.persist(record);
1837
1977
  }
1978
+ await this.shared?.close().catch((error) => console.error(`Shared sandbox removal failed: ${error.message}`));
1838
1979
  }
1839
1980
  async execute(command) {
1840
1981
  switch (command.type) {
@@ -1858,6 +1999,8 @@ export class SessionHost {
1858
1999
  return await this.abort(command.sessionId);
1859
2000
  case "revive":
1860
2001
  return await this.revive(command.sessionId);
2002
+ case "relocate":
2003
+ return await this.relocate(command.sessionId, command.scope, command.repo);
1861
2004
  case "dispose":
1862
2005
  return await this.dispose(command.sessionId);
1863
2006
  case "settle":
@@ -1946,6 +2089,13 @@ export class SessionHost {
1946
2089
  }
1947
2090
  return values;
1948
2091
  }
2092
+ /** Sandbox mode: the Agent Session's VM, reviving the session when needed. */
2093
+ async workflowSandbox(sessionId) {
2094
+ const { session } = await this.openWorkflowSession(sessionId);
2095
+ if (!session?.sandbox)
2096
+ throw new Error("Sandbox isolation is unavailable; unrestricted launch refused: the Agent Session has no sandbox");
2097
+ return session.sandbox;
2098
+ }
1949
2099
  workflowMcpConnections(id) {
1950
2100
  const record = this.sessions.get(id);
1951
2101
  if (!record)
@@ -1955,22 +2105,33 @@ export class SessionHost {
1955
2105
  /** Include an SDK-supplied owning root in every local execution's filesystem policy. */
1956
2106
  filesystemStateRoot() { return this.store?.root; }
1957
2107
  /** A host without configured Settings keeps the safe, restricted library default. */
1958
- filesystemIsolationEnabled() { return this.filesystemIsolation?.() ?? true; }
1959
- async openWorkflowMcp(id, connectionId, isolationEnabled = this.filesystemIsolationEnabled()) {
2108
+ filesystemIsolationMode() { return this.filesystemIsolation?.() ?? "bubblewrap"; }
2109
+ sandboxSupport() { return this.sandbox?.(); }
2110
+ /** The Shared Sandbox, when the Settings choose one VM for all sandbox sessions. */
2111
+ sharedSandbox() { return this.sandboxSharing?.() === "shared" ? this.shared : undefined; }
2112
+ async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode()) {
2113
+ if (isolationMode === "sandbox") {
2114
+ await this.openWorkflowSession(id);
2115
+ const { SandboxMcpSession } = await import("../backend/worker/sandbox-mcp.js");
2116
+ const mcp = this.record(id).mcp;
2117
+ if (!(mcp instanceof SandboxMcpSession))
2118
+ throw new Error("Sandbox isolation is unavailable; unrestricted launch refused: the Agent Session has no sandbox");
2119
+ return mcp.directView(connectionId);
2120
+ }
1960
2121
  const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
1961
2122
  if (!connection)
1962
2123
  throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
1963
2124
  const { McpSession } = await import("../backend/mcp.js");
1964
2125
  const scope = this.workflowSession(id).scope;
1965
- return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationEnabled);
2126
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
1966
2127
  }
1967
2128
  /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
1968
- async openWorkflowMcpAuthoring(scope, connectionId, isolationEnabled = this.filesystemIsolationEnabled(), expectedScopeIdentity) {
2129
+ async openWorkflowMcpAuthoring(scope, connectionId, isolationMode = this.filesystemIsolationMode(), expectedScopeIdentity) {
1969
2130
  const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
1970
2131
  if (!connection)
1971
2132
  throw new Error('MCP connection removed. Refresh the workflow editor.');
1972
2133
  const { McpSession } = await import("../backend/mcp.js");
1973
- return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationEnabled, expectedScopeIdentity);
2134
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity);
1974
2135
  }
1975
2136
  mcpStatus(id) {
1976
2137
  const record = this.sessions.get(id);
@@ -2049,7 +2210,13 @@ export class SessionHost {
2049
2210
  record.endedTurnIds = new Set();
2050
2211
  const backend = this.backendFor(record.backendName);
2051
2212
  const { McpSession } = await import("../backend/mcp.js");
2052
- const mcp = new McpSession((this.mcpConnections?.() ?? []).filter((connection) => record.mcpConnectionIds?.includes(connection.id)), record.scope, this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined, false, this.resolveSecret, undefined, this.filesystemStateRoot(), this.filesystemIsolationEnabled());
2213
+ const { SandboxMcpSession } = await import("../backend/worker/sandbox-mcp.js");
2214
+ const selected = (this.mcpConnections?.() ?? []).filter((connection) => record.mcpConnectionIds?.includes(connection.id));
2215
+ const oauth = this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined;
2216
+ const isolationMode = this.filesystemIsolationMode();
2217
+ const mcp = isolationMode === "sandbox"
2218
+ ? new SandboxMcpSession(selected, record.scope, oauth, this.resolveSecret)
2219
+ : new McpSession(selected, record.scope, oauth, false, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
2053
2220
  record.mcp = mcp;
2054
2221
  const openingMcp = mcp.open();
2055
2222
  const autoCompaction = this.autoCompaction?.(backend.name);
@@ -2595,6 +2762,9 @@ export class SessionHost {
2595
2762
  ...(store ? { sink: (entry) => store.append(entry) } : {}),
2596
2763
  });
2597
2764
  }
2765
+ workflowBuilderModels(backend, scope) {
2766
+ return probeModels(this.backendFor(backend), scope, true);
2767
+ }
2598
2768
  /** Independent, host-mediated authoring; never inherits Agent Session tools or MCP. */
2599
2769
  createWorkflowBuilderSession(backend, options) {
2600
2770
  if (!options.workflowBuilder)
@@ -2650,6 +2820,15 @@ export class SessionHost {
2650
2820
  this.store.writeMeta(meta);
2651
2821
  }
2652
2822
  }
2823
+ /** The same Worktree under this host's state root, when a Scope was a Worktree of another state root and it is here now. */
2824
+ export function suggestedScope(scope, worktreesRoot) {
2825
+ const marker = "/.flow/worktrees/";
2826
+ const at = scope.indexOf(marker);
2827
+ if (at < 0)
2828
+ return undefined;
2829
+ const candidate = join(worktreesRoot, scope.slice(at + marker.length));
2830
+ return candidate !== scope && existsSync(candidate) ? candidate : undefined;
2831
+ }
2653
2832
  /** The turn still open at the end of these entries, if any. */
2654
2833
  function openTurnId(entries) {
2655
2834
  let openTurn;
@@ -1,3 +1,4 @@
1
+ import { probeSession, release } from "./skills.js";
1
2
  /**
2
3
  * Which models a Backend Adapter can actually reach, asked without an Agent Session.
3
4
  *
@@ -8,8 +9,8 @@
8
9
  * all until this existed.
9
10
  *
10
11
  * A machine-wide Default Model and Summary Model cannot wait for a session that does not exist yet.
11
- * So this opens a throwaway one — the same device the Summary Model uses (ADR 0020), tools and all
12
- * off — reads its Capabilities, and disposes of it.
12
+ * So this opens one — the same device the Summary Model uses (ADR 0020), tools and all off — reads
13
+ * its Capabilities, and gives it to `keep` or disposes of it.
13
14
  */
14
15
  /**
15
16
  * A backend that has not answered in this long is not going to.
@@ -28,7 +29,7 @@ const PROBE_TIMEOUT_MS = 45_000;
28
29
  * Never throws: a backend that cannot answer reports a `problem`, and its section of the Settings
29
30
  * offers a text field instead of a list. A refusal here must not make the whole page unreachable.
30
31
  */
31
- export async function probeModels(backend, scope) {
32
+ export async function probeModels(backend, scope, workflowBuilder = false, keep) {
32
33
  let models = [];
33
34
  let settle;
34
35
  // Claude reports a provisional Capabilities at create and the real list moments later, over
@@ -37,38 +38,40 @@ export async function probeModels(backend, scope) {
37
38
  const listed = new Promise((resolve) => {
38
39
  settle = resolve;
39
40
  });
40
- const emit = (event) => {
41
+ const { held, options } = probeSession(scope, (event) => {
41
42
  if (event.type !== "capabilities_changed")
42
43
  return;
43
44
  models = [...event.capabilities.models];
44
45
  settle?.();
45
- };
46
+ });
46
47
  let session;
47
48
  try {
48
- session = await backend.create({ scope, tools: "none", emit });
49
+ const refuseTool = async () => { throw new Error("Model discovery cannot use workflow builder tools"); };
50
+ session = await backend.create({ ...options, ...(workflowBuilder ? { workflowBuilder: {
51
+ instructions: "List available models only.", read: refuseTool, list: refuseTool, write: refuseTool,
52
+ } } : {}) });
49
53
  }
50
54
  catch (error) {
51
55
  return { backend: backend.name, models: [], problem: message(error) };
52
56
  }
53
- try {
54
- /*
55
- * A backend that already knows is not waited on.
56
- *
57
- * pi and the fake build their whole list before `create` resolves and never emit
58
- * `capabilities_changed` again, so waiting for one costs the entire timeout and answers with
59
- * exactly what was on the session all along. Only Claude, which fetches over its control
60
- * channel after the session is up, has anything to wait for.
61
- */
62
- if (session.capabilities.models.length > 0)
63
- return { backend: backend.name, models: [...session.capabilities.models], ...(session.capabilities.autoCompaction ? { autoCompaction: session.capabilities.autoCompaction } : {}) };
57
+ held.session = session;
58
+ /*
59
+ * A backend that already knows is not waited on.
60
+ *
61
+ * pi and the fake build their whole list before `create` resolves and never emit
62
+ * `capabilities_changed` again, so waiting for one costs the entire timeout and answers with
63
+ * exactly what was on the session all along. Only Claude, which fetches over its control
64
+ * channel after the session is up, has anything to wait for.
65
+ */
66
+ if (session.capabilities.models.length > 0)
67
+ models = [...session.capabilities.models];
68
+ else
64
69
  await within(listed, PROBE_TIMEOUT_MS);
65
- return models.length > 0
66
- ? { backend: backend.name, models, ...(session.capabilities.autoCompaction ? { autoCompaction: session.capabilities.autoCompaction } : {}) }
67
- : { backend: backend.name, models: [], problem: `${backend.name} listed no models` };
68
- }
69
- finally {
70
- await session.dispose().catch(() => { });
71
- }
70
+ const answer = models.length > 0
71
+ ? { backend: backend.name, models, ...(session.capabilities.autoCompaction ? { autoCompaction: session.capabilities.autoCompaction } : {}) }
72
+ : { backend: backend.name, models: [], problem: `${backend.name} listed no models` };
73
+ await release(held, models.length > 0 ? keep : undefined);
74
+ return answer;
72
75
  }
73
76
  function message(error) {
74
77
  return error instanceof Error ? error.message : String(error);
@@ -1,5 +1,6 @@
1
1
  const packageName = '@nathanstephenson/flow';
2
2
  const STABLE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
3
+ const BETA = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)-beta\.(0|[1-9]\d*)$/;
3
4
  const 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-]+)*)?$/;
4
5
  function parsed(version) {
5
6
  const match = SEMVER.exec(version);
@@ -48,51 +49,45 @@ export function compareVersions(left, right) {
48
49
  }
49
50
  return 0;
50
51
  }
51
- /** `latest` must itself be stable, and must advance rather than select a channel or downgrade. */
52
- export function newerStableVersion(installed, latest) {
53
- return STABLE.test(latest) && compareVersions(latest, installed) > 0;
52
+ /** A release must be stable or `X.Y.Z-beta.N`, and must advance rather than downgrade. */
53
+ export function newerReleaseVersion(installed, candidate) {
54
+ return (STABLE.test(candidate) || BETA.test(candidate)) && compareVersions(candidate, installed) > 0;
54
55
  }
55
56
  export class ReleaseChecker {
56
- cached;
57
- inFlight;
57
+ cached = new Map();
58
+ inFlight = new Map();
58
59
  options;
59
60
  constructor(options = {}) { this.options = options; }
60
- check(refresh = false) {
61
+ check(refresh = false, channel = 'stable') {
61
62
  const now = (this.options.now ?? Date.now)();
62
63
  const cacheMs = this.options.cacheMs ?? 15 * 60 * 1000;
63
- if (!refresh && this.cached && now - this.cached.at < cacheMs)
64
- return Promise.resolve(this.cached.result);
65
- if (this.inFlight)
66
- return this.inFlight;
67
- this.inFlight = this.fetchLatest().then(result => {
68
- this.cached = { at: (this.options.now ?? Date.now)(), result };
64
+ const cached = this.cached.get(channel);
65
+ if (!refresh && cached && now - cached.at < cacheMs)
66
+ return Promise.resolve(cached.result);
67
+ const running = this.inFlight.get(channel);
68
+ if (running)
69
+ return running;
70
+ const pending = this.fetchChannel(channel).then(result => {
71
+ this.cached.set(channel, { at: (this.options.now ?? Date.now)(), result });
69
72
  return result;
70
- }).finally(() => { this.inFlight = undefined; });
71
- return this.inFlight;
73
+ }).finally(() => { this.inFlight.delete(channel); });
74
+ this.inFlight.set(channel, pending);
75
+ return pending;
72
76
  }
73
- async fetchLatest() {
77
+ async fetchChannel(channel) {
74
78
  const checkedAt = new Date((this.options.now ?? Date.now)()).toISOString();
75
79
  try {
76
- const response = await (this.options.fetch ?? fetch)(this.options.registryUrl ?? `https://registry.npmjs.org/${packageName.replace('/', '%2F')}/latest`, {
77
- headers: { accept: 'application/json' },
78
- signal: AbortSignal.timeout(this.options.timeoutMs ?? 5000),
79
- });
80
- if (!response.ok)
81
- throw new Error(`npm registry answered ${response.status}`);
82
- const length = Number(response.headers.get('content-length'));
83
- if (Number.isFinite(length) && length > 64 * 1024)
84
- throw new Error('npm registry response was too large');
85
- const text = await response.text();
86
- if (Buffer.byteLength(text) > 64 * 1024)
87
- throw new Error('npm registry response was too large');
88
- const body = JSON.parse(text);
89
- const latestVersion = body && typeof body === 'object' && 'version' in body
90
- ? body.version
91
- : undefined;
92
- if (typeof latestVersion !== 'string' || !STABLE.test(latestVersion)) {
80
+ const latest = await this.fetchTag('latest') ?? '';
81
+ if (!STABLE.test(latest))
93
82
  throw new Error('npm latest tag is not a stable semantic version');
94
- }
95
- return { checkedAt, latestVersion };
83
+ if (channel === 'stable')
84
+ return { checkedAt, latestVersion: latest };
85
+ const beta = await this.fetchTag('beta');
86
+ if (beta === undefined)
87
+ return { checkedAt, latestVersion: latest };
88
+ if (!BETA.test(beta))
89
+ throw new Error('npm beta tag is not an X.Y.Z-beta.N version');
90
+ return { checkedAt, latestVersion: compareVersions(beta, latest) > 0 ? beta : latest };
96
91
  }
97
92
  catch (error) {
98
93
  const message = error instanceof Error && error.name === 'TimeoutError'
@@ -101,4 +96,23 @@ export class ReleaseChecker {
101
96
  return { checkedAt, error: message };
102
97
  }
103
98
  }
99
+ async fetchTag(tag) {
100
+ const response = await (this.options.fetch ?? fetch)(`${this.options.registryUrl ?? `https://registry.npmjs.org/${packageName.replace('/', '%2F')}`}/${tag}`, {
101
+ headers: { accept: 'application/json' },
102
+ signal: AbortSignal.timeout(this.options.timeoutMs ?? 5000),
103
+ });
104
+ if (tag === 'beta' && response.status === 404)
105
+ return undefined;
106
+ if (!response.ok)
107
+ throw new Error(`npm registry answered ${response.status}`);
108
+ const length = Number(response.headers.get('content-length'));
109
+ if (Number.isFinite(length) && length > 64 * 1024)
110
+ throw new Error('npm registry response was too large');
111
+ const text = await response.text();
112
+ if (Buffer.byteLength(text) > 64 * 1024)
113
+ throw new Error('npm registry response was too large');
114
+ const body = JSON.parse(text);
115
+ const version = body && typeof body === 'object' && 'version' in body ? body.version : undefined;
116
+ return typeof version === 'string' ? version : '';
117
+ }
104
118
  }