@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,25 +1,140 @@
1
- import { randomUUID } from "node:crypto";
2
- import { realpathSync, statSync } from "node:fs";
3
- import { dirname, resolve } from "node:path";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { dirname, join, resolve, sep } from "node:path";
4
5
  import { isSea } from "node:sea";
5
6
  import { fileURLToPath } from "node:url";
6
7
  import { prepareFilesystemIsolation } from "../../isolation/filesystem.js";
8
+ import { createSandbox, sandboxMounts, sandboxUnavailable } from "../../isolation/sandbox.js";
9
+ import { validateFilesystemScope } from "../../isolation/filesystem.js";
10
+ import { workflowBuilderFolder } from "../../isolation/shared-sandbox.js";
7
11
  import { nodeExecutionAssets } from "../../isolation/node-assets.js";
8
12
  import { launchWorker, workerCommand } from "./launcher.js";
9
13
  import { seaSdkExecutionAssets } from "./assets.js";
10
14
  import { WorkerRpc } from "./rpc.js";
15
+ import { SandboxMcpSession } from "./sandbox-mcp.js";
11
16
  import { mcpMetadata } from "./protocol.js";
12
17
  import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../workflow-tools.js";
13
- import { migrateLegacyClaudeState, prepareClaudeState } from "./claude-state.js";
18
+ import { migrateLegacyClaudeState, prepareClaudeState, relocateClaudeState } from "./claude-state.js";
19
+ import { relocatePiState } from "../pi/state.js";
20
+ import { recordTiming } from "../../daemon/timings.js";
14
21
  /** One owned worker per Backend Session, optionally enforcing a filesystem boundary. */
15
22
  export class WorkerBackend {
16
23
  name;
17
24
  options;
18
25
  constructor(options = {}) { this.options = options; this.name = options.backend ?? "pi"; }
26
+ async opened(proxy, signal, isolation, begin, sandbox) {
27
+ const opening = performance.now();
28
+ const worker = await proxy.open(signal);
29
+ if (!this.options.stateRoot)
30
+ return;
31
+ const ms = (value = 0) => Math.round(value);
32
+ recordTiming(this.options.stateRoot, { kind: "start", backend: this.name, isolation, ...sandbox, prepare: ms(opening - begin), open: ms(performance.now() - opening),
33
+ worker: { ready: ms(worker?.ready), import: ms(worker?.import), create: ms(worker?.create) } });
34
+ }
35
+ async createSandboxed(options) {
36
+ const begin = performance.now();
37
+ const support = this.options.sandbox?.();
38
+ if (!support?.supported)
39
+ throw new Error(`${sandboxUnavailable().message}: ${support?.reason ?? "no sandbox provider"}`);
40
+ if (isSea())
41
+ throw new Error(`${sandboxUnavailable().message}: single-executable builds cannot run in a sandbox`);
42
+ const packageRoot = fileURLToPath(new URL("../../..", import.meta.url));
43
+ const bundle = this.options.entry ?? join(packageRoot, "build/backend-worker.mjs");
44
+ if (!existsSync(bundle))
45
+ throw new Error(`${sandboxUnavailable().message}: worker bundle ${bundle} is missing; run npm run build:worker`);
46
+ const scope = options.workflowBuilder ? realpathSync(options.scope) : validateFilesystemScope({ scope: options.scope, expectedScope: resolve(options.scope),
47
+ ...(this.options.stateRoot ? { stateRoot: this.options.stateRoot } : {}) });
48
+ const shared = this.options.sharedSandbox?.();
49
+ const roots = shared?.roots();
50
+ if (roots && !roots.slice(0, 3).some((root) => scope === root || scope.startsWith(root + sep))) {
51
+ throw new Error(`${sandboxUnavailable().message}: Scope ${scope} is not under the Project Root ${roots[0]}`);
52
+ }
53
+ const temp = options.stateDir ? undefined : realpathSync(mkdtempSync(join(shared ? workflowBuilderFolder() : tmpdir(), "flow-sandbox-")));
54
+ const stateDir = options.stateDir ?? temp;
55
+ const plan = workerCommand({ ...this.options, entry: bundle });
56
+ const assets = [packageRoot, bundle, ...(this.options.readablePaths ?? [])];
57
+ if (this.options.backendModule)
58
+ assets.push(fileURLToPath(this.options.backendModule));
59
+ assets.push(...nodeExecutionAssets(assets));
60
+ const env = { FLOW_BACKEND_WORKER: "1",
61
+ ...Object.fromEntries(Object.entries(this.options.env ?? {}).filter((entry) => entry[1] !== undefined)) };
62
+ const cleanups = [];
63
+ let removed = Promise.resolve();
64
+ if (this.name === "claude") {
65
+ const claude = prepareClaudeState(stateDir, { ...process.env, ...this.options.env }, scope, options.resume, { viewRoot: stateDir, secureStorage: support.provider.claudeAuthDir ?? null });
66
+ cleanups.push(claude.cleanup);
67
+ env.CLAUDE_CONFIG_DIR = claude.env.CLAUDE_CONFIG_DIR;
68
+ if (claude.env.CLAUDE_SECURESTORAGE_CONFIG_DIR)
69
+ env.CLAUDE_SECURESTORAGE_CONFIG_DIR = claude.env.CLAUDE_SECURESTORAGE_CONFIG_DIR;
70
+ env.FLOW_CLAUDE_PATH = support.provider.claudePath;
71
+ for (const entry of readdirSync(env.CLAUDE_CONFIG_DIR)) {
72
+ const link = join(env.CLAUDE_CONFIG_DIR, entry);
73
+ if (!options.workflowBuilder && lstatSync(link).isSymbolicLink() && entry !== "projects")
74
+ assets.push(realpathSync(link));
75
+ }
76
+ }
77
+ else {
78
+ const source = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi/agent");
79
+ const agent = join(stateDir, "pi-agent");
80
+ rmSync(agent, { recursive: true, force: true });
81
+ mkdirSync(agent, { recursive: true, mode: 0o700 });
82
+ cleanups.push(() => rmSync(agent, { recursive: true, force: true }));
83
+ for (const name of ["auth.json", "models.json", "settings.json"]) {
84
+ if (existsSync(join(source, name)))
85
+ copyFileSync(join(source, name), join(agent, name));
86
+ }
87
+ env.PI_CODING_AGENT_DIR = agent;
88
+ env.PI_CODING_AGENT_SESSION_DIR = join(stateDir, "sessions");
89
+ }
90
+ const cleanup = () => {
91
+ for (const step of cleanups.splice(0))
92
+ step();
93
+ if (temp)
94
+ void removed.then(() => rmSync(temp, { recursive: true, force: true }));
95
+ };
96
+ let proxy;
97
+ try {
98
+ const auth = support.provider.claudeAuthDir && (shared || this.name === "claude") ? [support.provider.claudeAuthDir] : [];
99
+ const mounts = sandboxMounts([...roots ?? [scope, stateDir], ...auth], assets);
100
+ let sandbox, startup;
101
+ if (shared) {
102
+ const acquired = await shared.acquire(support.provider, roots[0], mounts, options.signal, options.evict);
103
+ ({ sandbox, startup } = acquired);
104
+ cleanups.push(acquired.release);
105
+ }
106
+ else {
107
+ sandbox = await createSandbox(support.provider, { name: `flow-${createHash("sha256").update(stateDir).digest("hex").slice(0, 16)}`,
108
+ workspace: scope, mounts, env: {} }, join(stateDir, "sandbox.json"), options.signal);
109
+ ({ startup } = sandbox);
110
+ cleanups.push(() => { removed = sandbox.close().catch((error) => console.error(`Sandbox ${sandbox.name} removal failed: ${error.message}`)); });
111
+ }
112
+ const launch = sandbox.command(scope, [support.provider.nodePath, ...plan.args], env);
113
+ proxy = new WorkerSession({ ...options, scope, stateDir }, { ...this.options, sandboxed: sandbox, startupTimeoutMs: this.options.startupTimeoutMs ?? 300_000, command: launch.command, args: launch.args, env: {} }, cleanup);
114
+ await this.opened(proxy, options.signal, "sandbox", begin, { sharing: shared ? "shared" : "own", remove: Math.round(startup.remove), create: Math.round(startup.create) });
115
+ return proxy;
116
+ }
117
+ catch (error) {
118
+ if (proxy)
119
+ await proxy.dispose();
120
+ else
121
+ cleanup();
122
+ throw error;
123
+ }
124
+ }
125
+ relocate(stateDir, from, to) {
126
+ if (this.name === "claude")
127
+ relocateClaudeState(stateDir, from, to);
128
+ else
129
+ relocatePiState(stateDir, from, to);
130
+ }
19
131
  async create(options) {
132
+ const begin = performance.now();
20
133
  options.signal?.throwIfAborted();
21
- const isolationEnabled = this.options.isolationEnabled?.() ?? true;
22
- if (!isolationEnabled) {
134
+ const isolationMode = this.options.isolationMode?.() ?? "bubblewrap";
135
+ if (isolationMode === "sandbox")
136
+ return this.createSandboxed(options);
137
+ if (isolationMode === "none") {
23
138
  const scope = realpathSync(options.scope);
24
139
  if (!statSync(scope).isDirectory())
25
140
  throw new Error("Scope must be a directory");
@@ -29,7 +144,7 @@ export class WorkerBackend {
29
144
  let proxy;
30
145
  try {
31
146
  proxy = new WorkerSession({ ...options, scope }, claude ? { ...this.options, env: claude.env } : this.options, claude?.cleanup ?? (() => { }));
32
- await proxy.open(options.signal);
147
+ await this.opened(proxy, options.signal, "none", begin);
33
148
  return proxy;
34
149
  }
35
150
  catch (error) {
@@ -58,14 +173,14 @@ export class WorkerBackend {
58
173
  const isolation = await prepareFilesystemIsolation({ ...plan, scope: options.scope, expectedScope: resolve(options.scope),
59
174
  ...(options.stateDir ? { stateDir: options.stateDir } : {}),
60
175
  ...(this.options.stateRoot ? { stateRoot: this.options.stateRoot } : {}),
61
- env: this.options.env ?? {}, credentials: this.name, ipc: true, readablePaths: assets });
176
+ env: this.options.env ?? {}, credentials: this.name, workflowBuilder: !!options.workflowBuilder, worker: true, readablePaths: assets });
62
177
  let proxy;
63
178
  try {
64
179
  options.signal?.throwIfAborted();
65
180
  if (this.name === "claude")
66
181
  migrateLegacyClaudeState(options.stateDir, { ...process.env, ...this.options.env }, isolation.scope, options.resume);
67
182
  proxy = new WorkerSession({ ...options, scope: isolation.scope, stateDir: isolation.stateDir }, { ...this.options, command: isolation.command, args: isolation.args, env: isolation.env, stdioFds: isolation.stdioFds }, isolation.cleanup);
68
- await proxy.open(options.signal);
183
+ await this.opened(proxy, options.signal, "bubblewrap", begin);
69
184
  return proxy;
70
185
  }
71
186
  catch (error) {
@@ -79,6 +194,7 @@ export class WorkerBackend {
79
194
  }
80
195
  class WorkerSession {
81
196
  capabilities;
197
+ get sandbox() { return this.launchOptions.sandboxed; }
82
198
  resume;
83
199
  worker;
84
200
  rpc;
@@ -103,9 +219,7 @@ class WorkerSession {
103
219
  this.worker = launchWorker(launchOptions);
104
220
  const child = this.worker.child;
105
221
  this.rpc = new WorkerRpc((message) => {
106
- if (!child.connected)
107
- throw new Error("Backend worker disconnected");
108
- child.send(message, (error) => { if (error)
222
+ this.worker.send(message, (error) => { if (error)
109
223
  this.fail(error); });
110
224
  }, async (method, args, signal) => {
111
225
  if (this.disposing || this.failed)
@@ -116,6 +230,11 @@ class WorkerSession {
116
230
  }
117
231
  // Never look up host functions by a worker-supplied property name.
118
232
  switch (method) {
233
+ case "mcp.token": {
234
+ if (!(this.options.mcp instanceof SandboxMcpSession) || typeof args[0] !== "string")
235
+ throw new Error("Host capability is not enabled");
236
+ return this.options.mcp.token(args[0], args[1] === true);
237
+ }
119
238
  case "workflowBuilder.read": return this.requireWorkflowBuilder(args[0]).read(args[0]);
120
239
  case "workflowBuilder.list": return this.requireWorkflowBuilder(args[0]).list(args[0]);
121
240
  case "workflowBuilder.write": return this.requireWorkflowBuilder(args[0]).write(args[0]);
@@ -138,9 +257,9 @@ class WorkerSession {
138
257
  default: throw new Error(`Unknown host method: ${method}`);
139
258
  }
140
259
  }, (name, value) => this.notify(name, value));
141
- child.on("message", (message) => this.rpc.receive(message));
260
+ this.worker.onMessage((message) => this.rpc.receive(message), (error) => this.fail(error));
142
261
  child.once("error", (error) => this.fail(error));
143
- child.once("disconnect", () => this.fail(new Error("Backend worker disconnected")));
262
+ child.stdout?.once("close", () => this.fail(new Error("Backend worker disconnected")));
144
263
  child.once("exit", (code, signal) => this.fail(new Error(`Backend worker exited (${signal ?? code ?? "unknown"})${this.worker.diagnostics() ? `: ${this.worker.diagnostics()}` : ""}`)));
145
264
  }
146
265
  requireWorkflowBuilder(input) {
@@ -156,7 +275,7 @@ class WorkerSession {
156
275
  return this.options.workflow;
157
276
  }
158
277
  async open(signal) {
159
- const { emit: _emit, onFailure: _onFailure, signal: _signal, mcp, workflow, workflowBuilder, ...options } = this.options;
278
+ const { emit: _emit, onFailure: _onFailure, signal: _signal, evict: _evict, mcp, workflow, workflowBuilder, ...options } = this.options;
160
279
  const controller = new AbortController();
161
280
  const cancel = () => controller.abort(signal?.reason);
162
281
  if (signal?.aborted)
@@ -168,10 +287,13 @@ class WorkerSession {
168
287
  const state = await this.rpc.call("create", [{ ...options, backend: this.launchOptions.backend ?? "pi",
169
288
  workflowEnabled: !workflowBuilder && !!workflow,
170
289
  ...(workflowBuilder ? { workflowBuilderInstructions: workflowBuilder.instructions }
171
- : mcp ? { mcpTools: mcpMetadata(mcp), mcpConnectionIds: (mcp.connections ?? []).map((connection) => connection.id) } : {}),
290
+ : mcp instanceof SandboxMcpSession ? { mcpSandbox: mcp.definitions() }
291
+ : mcp ? { mcpTools: mcpMetadata(mcp), mcpConnectionIds: (mcp.connections ?? []).map((connection) => connection.id) } : {}),
172
292
  ...(this.launchOptions.backendModule ? { backendModule: this.launchOptions.backendModule } : {}),
173
293
  }], controller.signal);
174
294
  this.updateSnapshot(state);
295
+ if (mcp instanceof SandboxMcpSession)
296
+ mcp.attach((method, args, signal) => this.rpc.call(method, args, signal));
175
297
  const methods = new Set(state.methods);
176
298
  if (!workflowBuilder && methods.has("refreshMcp"))
177
299
  this.refreshMcp = () => this.rpc.call("refreshMcp", [mcpMetadata(this.options.mcp)]);
@@ -187,6 +309,7 @@ class WorkerSession {
187
309
  this.setPermissionMode = (mode) => this.rpc.call("setPermissionMode", [mode]);
188
310
  if (!workflowBuilder && methods.has("startWorkflowSubagent"))
189
311
  this.startWorkflowSubagent = (options) => this.startWorkflow(options);
312
+ return state.startup;
190
313
  }
191
314
  finally {
192
315
  clearTimeout(timer);
@@ -1,4 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { encodeFrame, frameDecoder } from "./frames.js";
2
3
  import { isSea } from "node:sea";
3
4
  import { fileURLToPath } from "node:url";
4
5
  export function workerCommand(options = {}) {
@@ -15,9 +16,9 @@ export function launchWorker(options = {}) {
15
16
  env: { ...process.env, ...options.env, FLOW_BACKEND_WORKER: "1" },
16
17
  ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
17
18
  detached: process.platform !== "win32",
18
- stdio: ["ignore", "ignore", "pipe", "ipc", ...(options.stdioFds ?? [])],
19
- serialization: "advanced",
19
+ stdio: ["pipe", "pipe", "pipe", ...(options.stdioFds ?? [])],
20
20
  });
21
+ child.stdin?.on("error", () => { });
21
22
  // Drain diagnostics so a chatty SDK cannot block on stderr. Keep only a bounded failure tail.
22
23
  let diagnostics = "";
23
24
  child.stderr?.on("data", (chunk) => { diagnostics = (diagnostics + chunk.toString()).slice(-8192); });
@@ -28,6 +29,22 @@ export function launchWorker(options = {}) {
28
29
  return {
29
30
  child,
30
31
  exited,
32
+ send: (message, callback) => {
33
+ if (!child.stdin?.writable)
34
+ throw new Error("Backend worker disconnected");
35
+ child.stdin.write(encodeFrame(message), callback);
36
+ },
37
+ onMessage: (listener, onError) => {
38
+ const decode = frameDecoder(listener);
39
+ child.stdout?.on("data", (chunk) => {
40
+ try {
41
+ decode(chunk);
42
+ }
43
+ catch (error) {
44
+ onError(error);
45
+ }
46
+ });
47
+ },
31
48
  diagnostics: () => diagnostics.trim(),
32
49
  /** Await the process, then kill its entire process group if cooperative disposal stalled. */
33
50
  stop: (graceful) => stopping ??= (async () => {
@@ -61,7 +78,9 @@ export async function killWorkerTree(child) {
61
78
  process.kill(-child.pid, "SIGKILL");
62
79
  }
63
80
  catch (error) {
64
- if (error.code !== "ESRCH")
81
+ const code = error.code;
82
+ const exited = child.exitCode !== null || child.signalCode !== null;
83
+ if (code !== "ESRCH" && !(code === "EPERM" && exited))
65
84
  throw error;
66
85
  }
67
86
  }
@@ -0,0 +1,86 @@
1
+ import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
2
+ import { McpSession } from "../mcp.js";
3
+ /** Host stand-in for MCP clients that run in a sandbox worker (ADR 0033). The host keeps
4
+ * definitions, OAuth and status; the worker owns the clients and their tool calls. */
5
+ export class SandboxMcpSession extends McpSession {
6
+ worker;
7
+ attached;
8
+ resolveAttached;
9
+ cached;
10
+ oauth;
11
+ secret;
12
+ root;
13
+ constructor(connections, scope, oauth, resolveSecret) {
14
+ super(connections, scope);
15
+ this.oauth = oauth;
16
+ this.root = scope;
17
+ this.secret = resolveSecret;
18
+ this.cached = connections.map((connection) => ({ id: connection.id, state: "connecting", tools: 0 }));
19
+ this.attached = new Promise((resolve) => { this.resolveAttached = resolve; });
20
+ }
21
+ attach(worker) {
22
+ this.worker = worker;
23
+ this.resolveAttached();
24
+ }
25
+ /** Definitions for the worker: Secret-backed header values are resolved here and enter the VM. */
26
+ definitions() {
27
+ return this.connections.map((connection) => connection.transport !== "http" ? connection : {
28
+ ...connection,
29
+ headers: Object.fromEntries(Object.entries(connection.headers).map(([name, value]) => [name, "secret" in value ? { value: this.secret(value.secret) } : value])),
30
+ });
31
+ }
32
+ async token(connectionId, refresh) {
33
+ const connection = this.connections.find((entry) => entry.id === connectionId);
34
+ if (connection?.transport !== "http" || !connection.oauth || !this.oauth)
35
+ throw new Error("Unknown MCP connection");
36
+ const provider = this.oauth(connection);
37
+ if (refresh && await auth(provider, { serverUrl: connection.url }) !== "AUTHORIZED")
38
+ throw new Error("MCP sign-in required");
39
+ const token = (await provider.tokens())?.access_token;
40
+ if (!token)
41
+ throw new Error("MCP sign-in required");
42
+ return token;
43
+ }
44
+ async open() {
45
+ await this.attached;
46
+ this.cached = await this.worker("mcp.open", []);
47
+ }
48
+ async retry(id) {
49
+ await this.attached;
50
+ this.cached = await this.worker("mcp.retry", [id]);
51
+ }
52
+ async directView(connectionId) {
53
+ const connection = this.connections.find((entry) => entry.id === connectionId);
54
+ if (!connection)
55
+ throw new Error("MCP connection is not selected for this Agent Session");
56
+ await this.attached;
57
+ return new SandboxDirectMcpSession(connection, this.root, this.worker);
58
+ }
59
+ status() { return this.cached.map((state) => ({ ...state })); }
60
+ tools() { return []; }
61
+ registrationFailed() { this.cached = this.cached.map((state) => ({ ...state, state: "failed", tools: 0 })); }
62
+ async dispose() { }
63
+ }
64
+ /** A direct MCP Workflow Step's view of one connection in the sandbox worker (ADR 0033). */
65
+ class SandboxDirectMcpSession extends McpSession {
66
+ worker;
67
+ connectionId;
68
+ state;
69
+ listed = [];
70
+ constructor(connection, scope, worker) {
71
+ super([connection], scope);
72
+ this.worker = worker;
73
+ this.connectionId = connection.id;
74
+ this.state = { id: connection.id, state: "connecting", tools: 0 };
75
+ }
76
+ async open() {
77
+ const result = await this.worker("mcp.direct", [this.connectionId]);
78
+ this.state = result.status;
79
+ this.listed = result.tools.map((tool) => ({ ...tool,
80
+ call: (input, signal, timeoutMs) => this.worker("mcp.callTool", [tool.name, input, timeoutMs], signal) }));
81
+ }
82
+ async retry() { await this.open(); }
83
+ status() { return [{ ...this.state }]; }
84
+ tools() { return this.listed; }
85
+ async dispose() { }
86
+ }
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- e95e7068-765f-495c-9ba0-420a165b3c5f
1
+ c2ebc7bf-24c1-4862-ad7d-59cd06ba08f1
@@ -317,7 +317,7 @@ function installation(slot) {
317
317
  const barrier = readBarrier(barrierPath);
318
318
  if (barrier) {
319
319
  const allowed = barrier.capability;
320
- if (!processAlive(barrier.pid) || !allowed || !capability || allowed.token !== capability || allowed.root !== root || JSON.stringify(allowed.args) !== JSON.stringify(args)) throw new Error(`Flow startup blocked by ${barrierPath}. An update is active or needs manual repair; see README, Updating Flow.`);
320
+ if (!processAlive(barrier.pid) || !allowed || !capability || allowed.token !== capability || allowed.root !== root || JSON.stringify(allowed.args) !== JSON.stringify(args)) throw new Error(`Flow startup blocked by ${barrierPath}. An update is active or needs manual repair; see docs/updating.md, Manual repair.`);
321
321
  delete barrier.capability;
322
322
  save(barrier);
323
323
  }
@@ -546,6 +546,7 @@ async function restoreSystemd(root, c, transaction, old, version) {
546
546
 
547
547
  // src/daemon/release-checker.ts
548
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 BETA = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)-beta\.(0|[1-9]\d*)$/;
549
550
  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
551
  function parsed(version) {
551
552
  const match = SEMVER.exec(version);
@@ -582,8 +583,8 @@ function compareVersions(left, right) {
582
583
  }
583
584
  return 0;
584
585
  }
585
- function newerStableVersion(installed, latest) {
586
- return STABLE.test(latest) && compareVersions(latest, installed) > 0;
586
+ function newerReleaseVersion(installed, candidate) {
587
+ return (STABLE.test(candidate) || BETA.test(candidate)) && compareVersions(candidate, installed) > 0;
587
588
  }
588
589
 
589
590
  // src/cli/update.ts
@@ -645,8 +646,8 @@ async function update(install, lease, args, options = {}) {
645
646
  const npm = inspected.npm;
646
647
  const prefix = install.prefix;
647
648
  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`);
649
+ if (options.expectedVersion !== void 0 && !newerReleaseVersion(previous, options.expectedVersion)) {
650
+ throw new Error(`The confirmed web update target ${options.expectedVersion} is not a newer stable or beta release`);
650
651
  }
651
652
  const target = options.expectedVersion ?? "latest";
652
653
  const preserveConcretePort = options.preserveConcreteHostPort === true;
@@ -883,7 +884,7 @@ async function bootstrap() {
883
884
  if (!managed) throw new Error("Missing systemd update configuration");
884
885
  await assertSystemdOwner(managed, managed.updater, process.pid);
885
886
  }
886
- const lease = await install.register("e95e7068-765f-495c-9ba0-420a165b3c5f", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
887
+ const lease = await install.register("c2ebc7bf-24c1-4862-ad7d-59cd06ba08f1", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
887
888
  delete process.env.FLOW_UPDATE_CAPABILITY;
888
889
  process.on("exit", lease.release);
889
890
  if (args[0] === "update") {
@@ -242,7 +242,7 @@ export function installation(slot) {
242
242
  if (barrier) {
243
243
  const allowed = barrier.capability;
244
244
  if (!processAlive(barrier.pid) || !allowed || !capability || allowed.token !== capability || allowed.root !== root || JSON.stringify(allowed.args) !== JSON.stringify(args))
245
- throw new Error(`Flow startup blocked by ${barrierPath}. An update is active or needs manual repair; see README, Updating Flow.`);
245
+ throw new Error(`Flow startup blocked by ${barrierPath}. An update is active or needs manual repair; see docs/updating.md, Manual repair.`);
246
246
  delete barrier.capability;
247
247
  save(barrier);
248
248
  }
package/dist/cli/main.js CHANGED
@@ -1,23 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  import { isSea } from 'node:sea';
3
- if (process.argv[2] === '--flow-workflow-authoring-scope-reader' && process.send && process.env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER === '1') {
3
+ if (process.argv[2] === '--flow-workflow-authoring-scope-reader' && process.env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER === '1') {
4
4
  void import("../daemon/workflow-authoring-scope-reader.js").then(({ runWorkflowAuthoringScopeReader }) => runWorkflowAuthoringScopeReader()).catch(() => {
5
5
  process.exitCode = 1;
6
- process.disconnect?.();
7
6
  });
8
7
  }
9
- else if (process.argv[2] === '--flow-workflow-builder-reader' && process.send && process.env.FLOW_WORKFLOW_BUILDER_READER === '1') {
8
+ else if (process.argv[2] === '--flow-workflow-builder-reader' && process.env.FLOW_WORKFLOW_BUILDER_READER === '1') {
10
9
  void import("../daemon/workflow-builder-reader.js").then(({ runWorkflowBuilderReader }) => runWorkflowBuilderReader()).catch(() => {
11
10
  process.exitCode = 1;
12
- process.disconnect?.();
13
11
  });
14
12
  }
15
13
  else if (process.argv[2] === '--flow-isolation-launch' ||
16
- (process.argv[2] === '--flow-backend-worker' && process.send && process.env.FLOW_BACKEND_WORKER === '1')) {
14
+ (process.argv[2] === '--flow-backend-worker' && process.env.FLOW_BACKEND_WORKER === '1')) {
17
15
  void import("../backend/worker/entry.js").catch(error => {
18
16
  console.error(error instanceof Error ? error.message : error);
19
17
  process.exitCode = 1;
20
- process.disconnect?.();
21
18
  });
22
19
  }
23
20
  else if (!isSea() && import.meta.url.endsWith('.js')) {
@@ -6,7 +6,7 @@ import { readHost } from "../daemon/ownership.js";
6
6
  import { backgroundHostArgs, getHostStatus, HostRefusal, launchBackground, processAlive, requestHostStop, requireRestartable, waitUntil } from "./host-control.js";
7
7
  import { InstallationProcessUncertain, replacePackage } from "./install-process.js";
8
8
  import { assertSystemdOwner, restoreSystemd, resumeSystemdAdmission, systemctl, SystemdCommandFailed } from "./systemd-update.js";
9
- import { newerStableVersion } from "../daemon/release-checker.js";
9
+ import { newerReleaseVersion } from "../daemon/release-checker.js";
10
10
  export function npmExecutable() {
11
11
  for (const directory of (process.env.PATH ?? '').split(delimiter)) {
12
12
  const path = resolve(directory, 'npm');
@@ -72,8 +72,8 @@ export async function update(install, lease, args, options = {}) {
72
72
  const npm = inspected.npm;
73
73
  const prefix = install.prefix;
74
74
  const previous = inspected.version;
75
- if (options.expectedVersion !== undefined && !newerStableVersion(previous, options.expectedVersion)) {
76
- throw new Error(`The confirmed web update target ${options.expectedVersion} is not a newer stable release`);
75
+ if (options.expectedVersion !== undefined && !newerReleaseVersion(previous, options.expectedVersion)) {
76
+ throw new Error(`The confirmed web update target ${options.expectedVersion} is not a newer stable or beta release`);
77
77
  }
78
78
  const target = options.expectedVersion ?? 'latest';
79
79
  const preserveConcretePort = options.preserveConcreteHostPort === true;
@@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto';
3
3
  import { closeSync, constants, fchmodSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync, } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { spawn } from 'node:child_process';
6
- import { newerStableVersion, ReleaseChecker } from "../daemon/release-checker.js";
6
+ import { newerReleaseVersion, ReleaseChecker } from "../daemon/release-checker.js";
7
7
  import { UpdateRefusal } from "../daemon/update-api.js";
8
8
  export { UpdateRefusal } from "../daemon/update-api.js";
9
9
  import { processAlive } from "./host-control.js";
@@ -160,13 +160,16 @@ export class WebUpdateController {
160
160
  const registryUrl = process.env.FLOW_UPDATE_REGISTRY_URL;
161
161
  this.checker = options.checker ?? new ReleaseChecker(registryUrl ? { registryUrl } : {});
162
162
  }
163
+ channel() { return this.options.channel?.() ?? 'stable'; }
163
164
  async status(refresh = false) {
164
165
  const installedVersion = this.installedVersion();
165
- const check = await this.checker.check(refresh);
166
+ const channel = this.channel();
167
+ const check = await this.checker.check(refresh, channel);
166
168
  const operation = this.operation(installedVersion);
167
169
  return {
168
170
  installedVersion,
169
- updateAvailable: 'latestVersion' in check && newerStableVersion(installedVersion, check.latestVersion),
171
+ channel,
172
+ updateAvailable: 'latestVersion' in check && newerReleaseVersion(installedVersion, check.latestVersion),
170
173
  ...('latestVersion' in check ? { latestVersion: check.latestVersion } : { checkError: check.error }),
171
174
  checkedAt: check.checkedAt,
172
175
  eligibility: this.eligibility(),
@@ -187,11 +190,11 @@ export class WebUpdateController {
187
190
  throw new UpdateRefusal(eligibility.reason);
188
191
  const installedVersion = this.installedVersion();
189
192
  // Mutation never trusts the up-to-fifteen-minute discovery cache. The confirmed version must
190
- // still be npm's stable latest tag, and the detached helper installs that exact version.
191
- const release = await this.checker.check(true);
193
+ // still be npm's release for the active channel, and the detached helper installs that exact version.
194
+ const release = await this.checker.check(true, this.channel());
192
195
  if ('error' in release)
193
196
  throw new UpdateRefusal(`${release.error} Check again before updating.`);
194
- if (!newerStableVersion(installedVersion, release.latestVersion)) {
197
+ if (!newerReleaseVersion(installedVersion, release.latestVersion)) {
195
198
  throw new UpdateRefusal(`Flow ${installedVersion} is already up to date.`);
196
199
  }
197
200
  if (release.latestVersion !== confirmedVersion) {
@@ -3,7 +3,7 @@ const BACKOFF_MIN_MS = 500;
3
3
  const BACKOFF_MAX_MS = 8_000;
4
4
  /**
5
5
  * The Session Host sends no heartbeat, so at this layer a stream that has gone quiet is
6
- * indistinguishable from an Agent Session with nothing to say. README documents `--address 0.0.0.0`
6
+ * indistinguishable from an Agent Session with nothing to say. docs/remote-access.md documents `--address 0.0.0.0`
7
7
  * for containers, where a proxy's idle timeout drops a quiet stream without telling either end.
8
8
  * Treating silence as death costs one resumed reconnect when the stream was merely idle, and is the
9
9
  * only thing that recovers the case where it was real.
@@ -249,10 +249,13 @@ async function requireOk(response, token, authenticationRequired) {
249
249
  if (!response.ok)
250
250
  throw await responseError(response, token, authenticationRequired);
251
251
  }
252
+ /** A refusal's `code`, when the host sent one, is kept on the Error so a client can act on it. */
252
253
  async function responseError(response, token, authenticationRequired) {
253
254
  if (!token)
254
255
  authenticationRequired?.(response);
255
- return new Error(await describe(response));
256
+ const code = await response.clone().json().then((body) => body?.code, () => undefined);
257
+ const error = new Error(await describe(response));
258
+ return typeof code === "string" ? Object.assign(error, { code }) : error;
256
259
  }
257
260
  async function describe(response) {
258
261
  const body = await response.text().catch(() => "");
@@ -27,16 +27,13 @@ export function editDiff(input) {
27
27
  };
28
28
  }
29
29
  /**
30
- * Explicit diff/patch fences may contain just +/- fragments. Without that hint, require a unified
31
- * file header and hunk, so ordinary code and tool output are not mistaken for changes. Keep every
32
- * byte, including newlines, for copying and search highlighting.
30
+ * Labelled fences may contain just +/- fragments. Without a label, require a unified file header
31
+ * and hunk, so ordinary tool output is not mistaken for changes. Keep every byte, including
32
+ * newlines, for copying and search highlighting.
33
33
  */
34
34
  export function textDiff(text, lang) {
35
- const language = lang?.trim().split(/\s+/, 1)[0]?.toLowerCase();
36
- const explicit = language === "diff" || language === "patch";
37
- if (language && !explicit)
38
- return undefined;
39
- if (!explicit) {
35
+ const labelled = Boolean(lang?.trim());
36
+ if (!labelled) {
40
37
  const fileHeader = /^--- [^\n]*\n\+\+\+ [^\n]*\n/m.test(text);
41
38
  const hunkHeader = /^@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@/m.test(text);
42
39
  if (!fileHeader || !hunkHeader)
@@ -53,7 +50,7 @@ export function textDiff(text, lang) {
53
50
  }
54
51
  const inHunk = remainingOld > 0 || remainingNew > 0;
55
52
  let kind = "context";
56
- if (inHunk || explicit) {
53
+ if (inHunk || labelled) {
57
54
  // ---/+++ are file headers outside a hunk, but valid removed/added content inside one.
58
55
  if (line.startsWith("-") && (inHunk || !line.startsWith("--- ")))
59
56
  kind = "removed";
@@ -41,6 +41,22 @@ export function reduceAll(entries, from = initialState()) {
41
41
  state = reduce(state, entry);
42
42
  return state;
43
43
  }
44
+ /** The parent's last message since the last user message gets the turn's end time. */
45
+ function stampTurnEnd(entries, at) {
46
+ for (let index = entries.length - 1; index >= 0; index--) {
47
+ const entry = entries[index];
48
+ if (entry.kind === "user")
49
+ return entries;
50
+ if (entry.kind === "assistant" && entry.producer === undefined) {
51
+ if (entry.endedAt === at)
52
+ return entries;
53
+ const next = entries.slice();
54
+ next[index] = { ...entry, endedAt: at };
55
+ return next;
56
+ }
57
+ }
58
+ return entries;
59
+ }
44
60
  export function reduce(state, entry) {
45
61
  /*
46
62
  * The cast is deliberate. `applyEvent`'s switch is exhaustive over `AgentEvent` and has no
@@ -100,6 +116,7 @@ function applyEvent(state, event, at) {
100
116
  id: event.id,
101
117
  text: event.text,
102
118
  ...(event.attachments === undefined ? {} : { attachments: event.attachments }),
119
+ at,
103
120
  }),
104
121
  };
105
122
  case "turn_started":
@@ -270,6 +287,7 @@ function applyEvent(state, event, at) {
270
287
  case "turn_ended":
271
288
  return {
272
289
  ...state,
290
+ entries: stampTurnEnd(state.entries, at),
273
291
  turnInFlight: false,
274
292
  asking: state.asking?.producer === undefined ? undefined : state.asking,
275
293
  authorising: state.authorising?.producer === undefined ? undefined : state.authorising,
@@ -369,6 +387,7 @@ function applyEvent(state, event, at) {
369
387
  case "revived":
370
388
  return {
371
389
  ...state,
390
+ ...(event.scope === undefined ? {} : { scope: event.scope }),
372
391
  lifecycle: "live",
373
392
  turnInFlight: false,
374
393
  entries: [