@nathanstephenson/flow 0.1.4 → 0.1.6

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 (50) hide show
  1. package/dist/backend/claude/index.js +30 -8
  2. package/dist/backend/claude/workflow-builder.js +12 -0
  3. package/dist/backend/mcp.js +47 -7
  4. package/dist/backend/pi/index.js +30 -16
  5. package/dist/backend/pi/workflow-builder.js +11 -0
  6. package/dist/backend/worker/claude-state.js +131 -9
  7. package/dist/backend/worker/entry.js +11 -3
  8. package/dist/backend/worker/index.js +35 -10
  9. package/dist/backend/worker/launcher.js +1 -0
  10. package/dist/backend/workflow-builder.js +8 -0
  11. package/dist/build-id +1 -1
  12. package/dist/cli/bootstrap.js +1 -1
  13. package/dist/cli/main.js +13 -1
  14. package/dist/daemon/host.js +14 -0
  15. package/dist/daemon/mcp-auth.js +32 -4
  16. package/dist/daemon/runtime.js +13 -3
  17. package/dist/daemon/server.js +34 -0
  18. package/dist/daemon/workflow-authoring-scope-checks.js +134 -0
  19. package/dist/daemon/workflow-authoring-scope-reader.js +42 -0
  20. package/dist/daemon/workflow-authoring-scope.js +49 -0
  21. package/dist/daemon/workflow-builder-files.js +321 -0
  22. package/dist/daemon/workflow-builder-guidance.js +31 -0
  23. package/dist/daemon/workflow-builder-reader.js +131 -0
  24. package/dist/daemon/workflow-builder-routes.js +61 -0
  25. package/dist/daemon/workflow-builder.js +480 -0
  26. package/dist/daemon/workflow-mcp-authoring-routes.js +44 -0
  27. package/dist/daemon/workflow-mcp-authoring.js +313 -0
  28. package/dist/isolation/filesystem.js +7 -4
  29. package/dist/protocol/workflow-builder.js +1 -0
  30. package/dist/protocol/workflow-mcp-authoring.js +1 -0
  31. package/package.json +1 -1
  32. package/web/dist/assets/index-C_M0oDHN.js +38 -0
  33. package/web/dist/assets/index-D8CGXp1X.css +2 -0
  34. package/web/dist/assets/{input-NIrLDFaS.js → input-D9fbSfQF.js} +1 -1
  35. package/web/dist/assets/settings-mcp-BvSvGrcs.js +1 -0
  36. package/web/dist/assets/{settings-secrets-BtQwc-w4.js → settings-secrets-DlkU6W_Z.js} +1 -1
  37. package/web/dist/assets/settings-workflows-DNGE-b_U.js +23 -0
  38. package/web/dist/assets/switch-DEvHojwW.js +1 -0
  39. package/web/dist/assets/workflow-editors-D6XT6pcb.js +137 -0
  40. package/web/dist/assets/{workflows-9aO6cptD.css → workflows-Bb90N0XJ.css} +1 -1
  41. package/web/dist/assets/workflows-LSCnXIxN.js +7 -0
  42. package/web/dist/assets/workflows-pane-BIlp7uyg.js +1 -0
  43. package/web/dist/index.html +5 -4
  44. package/web/dist/assets/index-Bn-ECZ7w.js +0 -174
  45. package/web/dist/assets/index-DL0CGVaN.css +0 -2
  46. package/web/dist/assets/settings-mcp-B60T2XUv.js +0 -1
  47. package/web/dist/assets/settings-workflows-BZ4W0Ja8.js +0 -23
  48. package/web/dist/assets/switch-DyYU6B5T.js +0 -1
  49. package/web/dist/assets/workflows-BAdf2yKH.js +0 -7
  50. package/web/dist/assets/workflows-pane-MSSNIrgu.js +0 -1
@@ -10,13 +10,14 @@ import { seaSdkExecutionAssets } from "./assets.js";
10
10
  import { WorkerRpc } from "./rpc.js";
11
11
  import { mcpMetadata } from "./protocol.js";
12
12
  import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../workflow-tools.js";
13
- import { prepareClaudeState } from "./claude-state.js";
13
+ import { migrateLegacyClaudeState, prepareClaudeState } from "./claude-state.js";
14
14
  /** One owned worker per Backend Session, optionally enforcing a filesystem boundary. */
15
15
  export class WorkerBackend {
16
16
  name;
17
17
  options;
18
18
  constructor(options = {}) { this.options = options; this.name = options.backend ?? "pi"; }
19
19
  async create(options) {
20
+ options.signal?.throwIfAborted();
20
21
  const isolationEnabled = this.options.isolationEnabled?.() ?? true;
21
22
  if (!isolationEnabled) {
22
23
  const scope = realpathSync(options.scope);
@@ -24,11 +25,11 @@ export class WorkerBackend {
24
25
  throw new Error("Scope must be a directory");
25
26
  // Pi retains its ordinary full environment. Claude needs an owned projects tree in both
26
27
  // modes; prepare its private config view on the host so Workflow children inherit it too.
27
- const claude = this.name === "claude" ? prepareClaudeState(options.stateDir, { ...process.env, ...this.options.env }, scope) : undefined;
28
+ const claude = this.name === "claude" ? prepareClaudeState(options.stateDir, { ...process.env, ...this.options.env }, scope, options.resume) : undefined;
28
29
  let proxy;
29
30
  try {
30
31
  proxy = new WorkerSession({ ...options, scope }, claude ? { ...this.options, env: claude.env } : this.options, claude?.cleanup ?? (() => { }));
31
- await proxy.open();
32
+ await proxy.open(options.signal);
32
33
  return proxy;
33
34
  }
34
35
  catch (error) {
@@ -60,8 +61,11 @@ export class WorkerBackend {
60
61
  env: this.options.env ?? {}, credentials: this.name, ipc: true, readablePaths: assets });
61
62
  let proxy;
62
63
  try {
64
+ options.signal?.throwIfAborted();
65
+ if (this.name === "claude")
66
+ migrateLegacyClaudeState(options.stateDir, { ...process.env, ...this.options.env }, isolation.scope, options.resume);
63
67
  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);
64
- await proxy.open();
68
+ await proxy.open(options.signal);
65
69
  return proxy;
66
70
  }
67
71
  catch (error) {
@@ -106,8 +110,15 @@ class WorkerSession {
106
110
  }, async (method, args, signal) => {
107
111
  if (this.disposing || this.failed)
108
112
  throw new Error("Backend Session stopped");
113
+ // Builders never inherit other host capabilities, even if the worker asks directly.
114
+ if (this.options.workflowBuilder && !["workflowBuilder.read", "workflowBuilder.list", "workflowBuilder.write"].includes(method)) {
115
+ throw new Error("Host capability is not enabled for workflow builder");
116
+ }
109
117
  // Never look up host functions by a worker-supplied property name.
110
118
  switch (method) {
119
+ case "workflowBuilder.read": return this.requireWorkflowBuilder(args[0]).read(args[0]);
120
+ case "workflowBuilder.list": return this.requireWorkflowBuilder(args[0]).list(args[0]);
121
+ case "workflowBuilder.write": return this.requireWorkflowBuilder(args[0]).write(args[0]);
111
122
  case "mcp.call": {
112
123
  const tool = this.options.mcp?.tools().find((tool) => tool.name === args[0]);
113
124
  if (!tool)
@@ -132,24 +143,37 @@ class WorkerSession {
132
143
  child.once("disconnect", () => this.fail(new Error("Backend worker disconnected")));
133
144
  child.once("exit", (code, signal) => this.fail(new Error(`Backend worker exited (${signal ?? code ?? "unknown"})${this.worker.diagnostics() ? `: ${this.worker.diagnostics()}` : ""}`)));
134
145
  }
146
+ requireWorkflowBuilder(input) {
147
+ if (!this.options.workflowBuilder)
148
+ throw new Error("Workflow builder tools are not enabled");
149
+ if (typeof input !== "string")
150
+ throw new Error("Invalid workflow builder input: expected a string");
151
+ return this.options.workflowBuilder;
152
+ }
135
153
  requireWorkflow() {
136
154
  if (!this.options.workflow)
137
155
  throw new Error("Workflow tools are not enabled");
138
156
  return this.options.workflow;
139
157
  }
140
- async open() {
141
- const { emit: _emit, onFailure: _onFailure, mcp, workflow, ...options } = this.options;
158
+ async open(signal) {
159
+ const { emit: _emit, onFailure: _onFailure, signal: _signal, mcp, workflow, workflowBuilder, ...options } = this.options;
142
160
  const controller = new AbortController();
161
+ const cancel = () => controller.abort(signal?.reason);
162
+ if (signal?.aborted)
163
+ cancel();
164
+ else
165
+ signal?.addEventListener('abort', cancel, { once: true });
143
166
  const timer = setTimeout(() => controller.abort(), this.launchOptions.startupTimeoutMs ?? 60_000);
144
167
  try {
145
168
  const state = await this.rpc.call("create", [{ ...options, backend: this.launchOptions.backend ?? "pi",
146
- workflowEnabled: !!workflow,
147
- ...(mcp ? { mcpTools: mcpMetadata(mcp) } : {}),
169
+ workflowEnabled: !workflowBuilder && !!workflow,
170
+ ...(workflowBuilder ? { workflowBuilderInstructions: workflowBuilder.instructions }
171
+ : mcp ? { mcpTools: mcpMetadata(mcp) } : {}),
148
172
  ...(this.launchOptions.backendModule ? { backendModule: this.launchOptions.backendModule } : {}),
149
173
  }], controller.signal);
150
174
  this.updateSnapshot(state);
151
175
  const methods = new Set(state.methods);
152
- if (methods.has("refreshMcp"))
176
+ if (!workflowBuilder && methods.has("refreshMcp"))
153
177
  this.refreshMcp = () => this.rpc.call("refreshMcp", [mcpMetadata(this.options.mcp)]);
154
178
  if (methods.has("compact"))
155
179
  this.compact = (instructions) => this.rpc.call("compact", [instructions]);
@@ -161,11 +185,12 @@ class WorkerSession {
161
185
  this.answerPermission = (id, decision) => this.rpc.call("answerPermission", [id, decision]);
162
186
  if (methods.has("setPermissionMode"))
163
187
  this.setPermissionMode = (mode) => this.rpc.call("setPermissionMode", [mode]);
164
- if (methods.has("startWorkflowSubagent"))
188
+ if (!workflowBuilder && methods.has("startWorkflowSubagent"))
165
189
  this.startWorkflowSubagent = (options) => this.startWorkflow(options);
166
190
  }
167
191
  finally {
168
192
  clearTimeout(timer);
193
+ signal?.removeEventListener('abort', cancel);
169
194
  }
170
195
  }
171
196
  updateSnapshot(state) {
@@ -13,6 +13,7 @@ export function launchWorker(options = {}) {
13
13
  const { command, args } = workerCommand(options);
14
14
  const child = spawn(command, args, {
15
15
  env: { ...process.env, ...options.env, FLOW_BACKEND_WORKER: "1" },
16
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
16
17
  detached: process.platform !== "win32",
17
18
  stdio: ["ignore", "ignore", "pipe", "ipc", ...(options.stdioFds ?? [])],
18
19
  serialization: "advanced",
@@ -0,0 +1,8 @@
1
+ export const workflowBuilderTools = [
2
+ { name: "workflow_builder_read", label: "Read workflow reference", field: "path", method: "read",
3
+ description: "Read a reference at a host-approved path. This is not an arbitrary filesystem reader." },
4
+ { name: "workflow_builder_list", label: "List workflow references", field: "path", method: "list",
5
+ description: "List references at a host-approved path. This is not an arbitrary directory listing." },
6
+ { name: "workflow_builder_write", label: "Save workflow definition", field: "content", method: "write",
7
+ description: "Validate and save Workflow Definition content through the host. The host chooses the destination; no file path is accepted." },
8
+ ];
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- e5b65913-9f67-4248-8f84-d7d8187c41ee
1
+ dd94e5bf-c6e7-43c8-9b45-5cd67ff6c921
@@ -883,7 +883,7 @@ async function bootstrap() {
883
883
  if (!managed) throw new Error("Missing systemd update configuration");
884
884
  await assertSystemdOwner(managed, managed.updater, process.pid);
885
885
  }
886
- const lease = await install.register("e5b65913-9f67-4248-8f84-d7d8187c41ee", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
886
+ const lease = await install.register("dd94e5bf-c6e7-43c8-9b45-5cd67ff6c921", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
887
887
  delete process.env.FLOW_UPDATE_CAPABILITY;
888
888
  process.on("exit", lease.release);
889
889
  if (args[0] === "update") {
package/dist/cli/main.js CHANGED
@@ -1,6 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { isSea } from 'node:sea';
3
- if (process.argv[2] === '--flow-isolation-launch' ||
3
+ if (process.argv[2] === '--flow-workflow-authoring-scope-reader' && process.send && process.env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER === '1') {
4
+ void import("../daemon/workflow-authoring-scope-reader.js").then(({ runWorkflowAuthoringScopeReader }) => runWorkflowAuthoringScopeReader()).catch(() => {
5
+ process.exitCode = 1;
6
+ process.disconnect?.();
7
+ });
8
+ }
9
+ else if (process.argv[2] === '--flow-workflow-builder-reader' && process.send && process.env.FLOW_WORKFLOW_BUILDER_READER === '1') {
10
+ void import("../daemon/workflow-builder-reader.js").then(({ runWorkflowBuilderReader }) => runWorkflowBuilderReader()).catch(() => {
11
+ process.exitCode = 1;
12
+ process.disconnect?.();
13
+ });
14
+ }
15
+ else if (process.argv[2] === '--flow-isolation-launch' ||
4
16
  (process.argv[2] === '--flow-backend-worker' && process.send && process.env.FLOW_BACKEND_WORKER === '1')) {
5
17
  void import("../backend/worker/entry.js").catch(error => {
6
18
  console.error(error instanceof Error ? error.message : error);
@@ -1964,6 +1964,14 @@ export class SessionHost {
1964
1964
  const scope = this.workflowSession(id).scope;
1965
1965
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationEnabled);
1966
1966
  }
1967
+ /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
1968
+ async openWorkflowMcpAuthoring(scope, connectionId, isolationEnabled = this.filesystemIsolationEnabled(), expectedScopeIdentity) {
1969
+ const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
1970
+ if (!connection)
1971
+ throw new Error('MCP connection removed. Refresh the workflow editor.');
1972
+ 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);
1974
+ }
1967
1975
  mcpStatus(id) {
1968
1976
  const record = this.sessions.get(id);
1969
1977
  if (!record)
@@ -2587,6 +2595,12 @@ export class SessionHost {
2587
2595
  ...(store ? { sink: (entry) => store.append(entry) } : {}),
2588
2596
  });
2589
2597
  }
2598
+ /** Independent, host-mediated authoring; never inherits Agent Session tools or MCP. */
2599
+ createWorkflowBuilderSession(backend, options) {
2600
+ if (!options.workflowBuilder)
2601
+ throw new Error('Workflow builder capabilities are required');
2602
+ return this.backendFor(backend).create(options);
2603
+ }
2590
2604
  backendFor(name) {
2591
2605
  const backend = this.backends.get(name);
2592
2606
  if (!backend)
@@ -6,6 +6,7 @@ import { auth, } from "@modelcontextprotocol/sdk/client/auth.js";
6
6
  export class McpAuth {
7
7
  path;
8
8
  values;
9
+ revisions = new Map();
9
10
  pending = new Map();
10
11
  dispose() {
11
12
  for (const entry of this.pending.values())
@@ -30,6 +31,30 @@ export class McpAuth {
30
31
  ]))
31
32
  .digest("hex");
32
33
  }
34
+ persist() {
35
+ const scratch = `${this.path}.tmp`;
36
+ writeFileSync(scratch, JSON.stringify(this.values), { mode: 0o600 });
37
+ renameSync(scratch, this.path);
38
+ }
39
+ signedIn(connections) {
40
+ return connections
41
+ .filter((connection) => connection.transport === "http" && connection.oauth && this.values[this.key(connection)]?.tokens?.access_token)
42
+ .map((connection) => connection.id);
43
+ }
44
+ logout(connection) {
45
+ if (connection.transport !== "http" || !connection.oauth)
46
+ throw new Error("OAuth is not enabled");
47
+ for (const [state, entry] of this.pending) {
48
+ if (entry.connectionId !== connection.id)
49
+ continue;
50
+ clearTimeout(entry.timer);
51
+ this.pending.delete(state);
52
+ }
53
+ const key = this.key(connection);
54
+ this.revisions.set(key, (this.revisions.get(key) ?? 0) + 1);
55
+ delete this.values[key];
56
+ this.persist();
57
+ }
33
58
  credentialValues() {
34
59
  const values = [];
35
60
  const visit = (value) => {
@@ -47,12 +72,13 @@ export class McpAuth {
47
72
  }
48
73
  provider(connection, redirectUrl = "http://127.0.0.1/", redirect, state) {
49
74
  const key = this.key(connection);
75
+ const revision = this.revisions.get(key) ?? 0;
50
76
  let verifier = "";
51
77
  const save = (patch) => {
78
+ if ((this.revisions.get(key) ?? 0) !== revision || (state && !this.pending.has(state)))
79
+ throw new Error("Sign-in cancelled or expired");
52
80
  this.values[key] = { ...this.values[key], ...patch };
53
- const scratch = `${this.path}.tmp`;
54
- writeFileSync(scratch, JSON.stringify(this.values), { mode: 0o600 });
55
- renameSync(scratch, this.path);
81
+ this.persist();
56
82
  };
57
83
  return {
58
84
  redirectUrl,
@@ -119,6 +145,8 @@ export class McpAuth {
119
145
  timer,
120
146
  });
121
147
  await auth(provider, { serverUrl: connection.url, fetchFn: timedFetch });
148
+ if (!this.pending.has(state))
149
+ throw new Error("Sign-in cancelled or expired");
122
150
  if (!authorizationUrl)
123
151
  throw new Error("No authorization URL");
124
152
  return authorizationUrl;
@@ -146,7 +174,7 @@ export class McpAuth {
146
174
  authorizationCode: code,
147
175
  fetchFn: timedFetch,
148
176
  });
149
- if (status === "AUTHORIZED")
177
+ if (status === "AUTHORIZED" && this.pending.get(state) === entry)
150
178
  result = "signed-in";
151
179
  }
152
180
  catch { }
@@ -4,6 +4,8 @@ import { ConfigStore } from "./config-store.js";
4
4
  import { SecretStore } from "./secret-store.js";
5
5
  import { WorkflowStore } from "../workflows/store.js";
6
6
  import { WorkflowExecutionService } from "./workflow-executions.js";
7
+ import { WorkflowBuilderService } from "./workflow-builder.js";
8
+ import { WorkflowMcpAuthoringService } from "./workflow-mcp-authoring.js";
7
9
  import { SessionHost } from "./host.js";
8
10
  import { McpAuth } from "./mcp-auth.js";
9
11
  import { serve } from "./server.js";
@@ -47,6 +49,8 @@ export async function startRuntime(options) {
47
49
  defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel,
48
50
  });
49
51
  const shells = new ShellRegistry();
52
+ let workflowBuilders;
53
+ let workflowMcpAuthoring;
50
54
  let running;
51
55
  let oidc;
52
56
  let sweep;
@@ -54,7 +58,7 @@ export async function startRuntime(options) {
54
58
  let stopping;
55
59
  const stop = () => stopping ??= (async () => {
56
60
  clearInterval(sweep);
57
- const interrupt = async () => { await Promise.all([host.shutdown(), shells.killAll(), reaping]); };
61
+ const interrupt = async () => { await Promise.all([host.shutdown(), workflowBuilders?.shutdown(), workflowMcpAuthoring?.shutdown(), shells.killAll(), reaping]); };
58
62
  if (running)
59
63
  await running.stopAdmission(interrupt);
60
64
  else
@@ -76,6 +80,12 @@ export async function startRuntime(options) {
76
80
  registerBackends(host);
77
81
  const workflows = new WorkflowStore(root);
78
82
  const workflowExecutions = new WorkflowExecutionService(host, workflows, secrets, config, options.workflowRuntime());
83
+ workflowMcpAuthoring = new WorkflowMcpAuthoringService({ host, config, scope: process.cwd() });
84
+ workflowBuilders = new WorkflowBuilderService({
85
+ host, config, scope: process.cwd(), stateRoot: root,
86
+ validateDefinition: definition => workflowExecutions.validateDefinitionCredentials(definition),
87
+ mcpCatalogue: (scope, projectId, scopeIdentity) => workflowMcpAuthoring.catalogue(projectId, { scope, scopeIdentity }),
88
+ });
79
89
  await host.load();
80
90
  workflowExecutions.reconcile();
81
91
  sweep = setInterval(() => { reaping = reaping.then(async () => { await host.reap(); }); }, 60 * 60 * 1000);
@@ -87,7 +97,7 @@ export async function startRuntime(options) {
87
97
  instanceId: ownership.instanceId, pid: process.pid, version: options.version, url: '', token, mode: options.mode,
88
98
  settings: { port: options.port ?? 0, address: options.address ?? '127.0.0.1', cwd: process.cwd(), oidc: oidcFingerprint() },
89
99
  };
90
- const hasActiveWork = () => host.hasActiveWork() || shells.hasLiveShells() || host.list().some(session => workflowExecutions.list(session.id).occupied);
100
+ const hasActiveWork = () => host.hasActiveWork() || workflowBuilders.hasActiveWork() || workflowMcpAuthoring.hasActiveWork() || shells.hasLiveShells() || host.list().some(session => workflowExecutions.list(session.id).occupied);
91
101
  const updates = new WebUpdateController({
92
102
  root,
93
103
  installedVersion: options.version,
@@ -99,7 +109,7 @@ export async function startRuntime(options) {
99
109
  running = await serve({
100
110
  control: { identity, stop, hasActiveWork },
101
111
  updates,
102
- host, token, shells, config, mcpAuth, store, workflows, secrets, workflowExecutions,
112
+ host, token, shells, config, mcpAuth, store, workflows, secrets, workflowExecutions, workflowBuilders, workflowMcpAuthoring,
103
113
  assets: options.assets(), scope: process.cwd(),
104
114
  ...(oidc === undefined ? {} : { oidc }),
105
115
  ...(options.port === undefined ? {} : { port: options.port }),
@@ -2,6 +2,8 @@ import { createServer } from "node:http";
2
2
  import { mediaTypeOf } from "../protocol/attachments.js";
3
3
  import { ConfigError } from "./config.js";
4
4
  import { workflowRoutes } from "./workflow-routes.js";
5
+ import { workflowBuilderRoutes } from "./workflow-builder-routes.js";
6
+ import { workflowMcpAuthoringRoutes } from "./workflow-mcp-authoring-routes.js";
5
7
  import { hostControlRoute } from "./host-control-routes.js";
6
8
  import { readBody, send } from "./http.js";
7
9
  import { workflowExecutionRoutes } from "./workflow-execution-routes.js";
@@ -287,6 +289,10 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
287
289
  response.end();
288
290
  return;
289
291
  }
292
+ if (await workflowMcpAuthoringRoutes(request, response, url.pathname, options.workflowMcpAuthoring))
293
+ return;
294
+ if (await workflowBuilderRoutes(request, response, url.pathname, options.workflowBuilders))
295
+ return;
290
296
  if (await workflowExecutionRoutes(request, response, url.pathname, options.workflowExecutions, options.workflows))
291
297
  return;
292
298
  if (await workflowRoutes(request, response, url.pathname, options.workflows, options.secrets, options.workflowExecutions))
@@ -308,6 +314,34 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
308
314
  }
309
315
  return;
310
316
  }
317
+ if (url.pathname === "/api/mcp/auth") {
318
+ response.setHeader("cache-control", "no-store");
319
+ if (request.method === "GET") {
320
+ send(response, 200, { signedIn: options.mcpAuth?.signedIn(options.config?.mcpConnections() ?? []) ?? [] });
321
+ }
322
+ else
323
+ send(response, 405, { error: "Method not allowed" });
324
+ return;
325
+ }
326
+ const mcpLogout = /^\/api\/mcp\/([^/]+)\/logout$/.exec(url.pathname);
327
+ if (mcpLogout) {
328
+ response.setHeader("cache-control", "no-store");
329
+ if (request.method !== "POST") {
330
+ send(response, 405, { error: "Method not allowed" });
331
+ return;
332
+ }
333
+ try {
334
+ const connection = options.config?.mcpConnections().find((entry) => entry.id === mcpLogout[1]);
335
+ if (!connection || !options.mcpAuth)
336
+ throw new Error("Unknown connection");
337
+ options.mcpAuth.logout(connection);
338
+ send(response, 200, {});
339
+ }
340
+ catch {
341
+ send(response, 400, { error: "MCP sign-out failed" });
342
+ }
343
+ return;
344
+ }
311
345
  const mcpLogin = /^\/api\/mcp\/([^/]+)\/login$/.exec(url.pathname);
312
346
  if (request.method === "POST" && mcpLogin) {
313
347
  const connection = options.config?.mcpConnections().find((entry) => entry.id === mcpLogin[1]);
@@ -0,0 +1,134 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ import { isSea } from 'node:sea';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { launchWorker } from "../backend/worker/launcher.js";
6
+ import { checkWorkflowAuthoringDirectory, workflowAuthoringDirectory } from "./workflow-authoring-scope.js";
7
+ const unavailable = () => new Error('Workflow authoring Scope unavailable');
8
+ const changed = () => new Error('Workflow authoring Scope changed; discover again');
9
+ const validPath = (path) => typeof path === 'string' && path.length > 0 && path.length <= 4096 && !path.includes('\0');
10
+ const validDirectory = (value) => {
11
+ const directory = value;
12
+ return !!directory && validPath(directory.path) && isAbsolute(directory.path) && resolve(directory.path) === directory.path &&
13
+ typeof directory.identity === 'string' && /^\d{1,40}:\d{1,40}$/.test(directory.identity);
14
+ };
15
+ export class WorkflowAuthoringScopeChecks {
16
+ readers = new Set();
17
+ pending = new Map();
18
+ closed = false;
19
+ closing;
20
+ options;
21
+ constructor(options = {}) { this.options = options; }
22
+ async read(path) {
23
+ if (this.closed || !validPath(path))
24
+ throw unavailable();
25
+ if (process.platform === 'linux' && this.options.linuxSync !== false) {
26
+ try {
27
+ return workflowAuthoringDirectory(realpathSync(path));
28
+ }
29
+ catch {
30
+ throw unavailable();
31
+ }
32
+ }
33
+ return this.inspect({ operation: 'read', path: resolve(path) });
34
+ }
35
+ async check(directory) {
36
+ if (this.closed || !validDirectory(directory))
37
+ throw changed();
38
+ const pinned = { path: directory.path, identity: directory.identity };
39
+ if (process.platform === 'linux' && this.options.linuxSync !== false) {
40
+ try {
41
+ return checkWorkflowAuthoringDirectory(pinned);
42
+ }
43
+ catch {
44
+ throw changed();
45
+ }
46
+ }
47
+ const actual = await this.inspect({ operation: 'check', ...pinned });
48
+ if (actual.path !== pinned.path || actual.identity !== pinned.identity)
49
+ throw changed();
50
+ }
51
+ hasActiveWork() { return this.readers.size > 0; }
52
+ shutdown() {
53
+ this.closed = true;
54
+ return this.closing ??= (async () => {
55
+ const readers = [...this.readers];
56
+ for (const reader of readers)
57
+ reader.cancel();
58
+ await Promise.all(readers.map(reader => reader.cleanup));
59
+ })();
60
+ }
61
+ inspect(request) {
62
+ if (this.closed)
63
+ return Promise.reject(unavailable());
64
+ const key = JSON.stringify(request);
65
+ const existing = this.pending.get(key);
66
+ if (existing)
67
+ return existing;
68
+ const pending = this.inspectOwned(request);
69
+ this.pending.set(key, pending);
70
+ const settled = () => { if (this.pending.get(key) === pending)
71
+ this.pending.delete(key); };
72
+ void pending.then(settled, settled);
73
+ return pending;
74
+ }
75
+ inspectOwned(request) {
76
+ if (this.closed || this.readers.size >= 4 || !validPath(request.path))
77
+ return Promise.reject(unavailable());
78
+ return new Promise((accept, reject) => {
79
+ let settled = false;
80
+ let reader;
81
+ let helper;
82
+ let finishCleanup;
83
+ let failCleanup;
84
+ const cleanup = new Promise((resolve, reject) => { finishCleanup = resolve; failCleanup = reject; });
85
+ void cleanup.catch(() => { });
86
+ const finish = (error, result) => {
87
+ if (settled)
88
+ return;
89
+ settled = true;
90
+ clearTimeout(timer);
91
+ if (error)
92
+ reject(error);
93
+ else
94
+ accept(result);
95
+ if (!helper) {
96
+ finishCleanup();
97
+ return;
98
+ }
99
+ void helper.stop(async () => { }).then(() => {
100
+ this.readers.delete(reader);
101
+ finishCleanup();
102
+ }, failCleanup);
103
+ };
104
+ const timer = setTimeout(() => finish(unavailable()), 5000);
105
+ const source = import.meta.url.endsWith('.ts');
106
+ const entry = fileURLToPath(new URL(source ? './workflow-authoring-scope-reader.ts' : './workflow-authoring-scope-reader.js', import.meta.url));
107
+ const env = Object.fromEntries(Object.keys(process.env).map(key => [key, undefined]));
108
+ env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER = '1';
109
+ try {
110
+ helper = (this.options.launch ?? launchWorker)({
111
+ ...(isSea() ? { args: ['--flow-workflow-authoring-scope-reader'] } : { entry, execArgv: source ? ['--experimental-strip-types'] : [] }),
112
+ cwd: '/', env, shutdownTimeoutMs: 0,
113
+ });
114
+ reader = { cancel: () => finish(unavailable()), cleanup };
115
+ this.readers.add(reader);
116
+ helper.child.once('error', () => finish(unavailable()));
117
+ helper.child.once('disconnect', () => finish(unavailable()));
118
+ void helper.exited.then(() => finish(unavailable()));
119
+ helper.child.once('message', (message) => {
120
+ const response = message;
121
+ if (!response || response.ok !== true || !validDirectory(response.result))
122
+ finish(request.operation === 'check' ? changed() : unavailable());
123
+ else
124
+ finish(undefined, response.result);
125
+ });
126
+ helper.child.send(request, error => { if (error)
127
+ finish(unavailable()); });
128
+ }
129
+ catch {
130
+ finish(unavailable());
131
+ }
132
+ });
133
+ }
134
+ }
@@ -0,0 +1,42 @@
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, resolve } from 'node:path';
3
+ import { isSea } from 'node:sea';
4
+ import { fileURLToPath } from 'node:url';
5
+ async function inspect(request) {
6
+ const value = request;
7
+ if (!value || !['read', 'check'].includes(value.operation) || typeof value.path !== 'string' ||
8
+ !value.path || value.path.length > 4096 || value.path.includes('\0') || !isAbsolute(value.path) ||
9
+ (value.operation === 'check' && (resolve(value.path) !== value.path || typeof value.identity !== 'string' ||
10
+ !/^\d{1,40}:\d{1,40}$/.test(value.identity))))
11
+ throw new Error();
12
+ const path = await realpath(value.path);
13
+ if (value.operation === 'check' && path !== value.path)
14
+ throw new Error();
15
+ const stat = await lstat(path, { bigint: true });
16
+ if (!stat.isDirectory() || await realpath(path) !== path)
17
+ throw new Error();
18
+ const identity = `${stat.dev}:${stat.ino}`;
19
+ if (value.operation === 'check' && identity !== value.identity)
20
+ throw new Error();
21
+ return { path, identity };
22
+ }
23
+ export function runWorkflowAuthoringScopeReader() {
24
+ if (!process.send || process.env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER !== '1')
25
+ throw new Error();
26
+ const timer = setTimeout(() => process.exit(1), 4500);
27
+ process.once('disconnect', () => process.exit(1));
28
+ process.once('message', (request) => {
29
+ void inspect(request).then(result => ({ ok: true, result }), () => ({ ok: false })).then(response => {
30
+ process.send(response, () => { clearTimeout(timer); process.exit(0); });
31
+ });
32
+ });
33
+ }
34
+ if (!isSea() && process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1])) {
35
+ try {
36
+ runWorkflowAuthoringScopeReader();
37
+ }
38
+ catch {
39
+ process.exitCode = 1;
40
+ process.disconnect?.();
41
+ }
42
+ }
@@ -0,0 +1,49 @@
1
+ import { lstatSync, realpathSync, statSync } from 'node:fs';
2
+ import { isAbsolute, join } from 'node:path';
3
+ import { expandHome } from "./projects.js";
4
+ export function workflowAuthoringScopePath(config, fallback, projectId) {
5
+ const root = config.projectRoot();
6
+ if (projectId === undefined)
7
+ return expandHome(root ?? fallback);
8
+ const base = root === undefined ? undefined : expandHome(root);
9
+ for (const entry of config.projectInclude()) {
10
+ const trimmed = entry.trim();
11
+ if (!trimmed)
12
+ continue;
13
+ const expanded = expandHome(trimmed);
14
+ if (!isAbsolute(expanded) && base === undefined)
15
+ continue;
16
+ const path = (isAbsolute(expanded) ? expanded : join(base, expanded))
17
+ .replace(/\/+$/, '').replace(/\/\.(?=\/|$)/g, '') || '/';
18
+ if (path === projectId)
19
+ return path;
20
+ }
21
+ throw new Error('Workflow Project is not opted in');
22
+ }
23
+ export function workflowAuthoringScope(config, fallback, projectId) {
24
+ const scope = workflowAuthoringScopePath(config, fallback, projectId);
25
+ if (projectId !== undefined) {
26
+ let directory = false;
27
+ try {
28
+ directory = statSync(scope).isDirectory();
29
+ }
30
+ catch { }
31
+ if (!directory)
32
+ throw new Error('Workflow Project is not opted in');
33
+ }
34
+ const canonical = realpathSync(scope);
35
+ if (!statSync(canonical).isDirectory())
36
+ throw new Error('Workflow Scope must be a directory');
37
+ return canonical;
38
+ }
39
+ /** Pin directory identity as well as its canonical path; replacements must not reuse tools. */
40
+ export function workflowAuthoringDirectory(path) {
41
+ const stat = lstatSync(path, { bigint: true });
42
+ if (!stat.isDirectory() || realpathSync(path) !== path)
43
+ throw new Error('Workflow authoring Scope changed; discover again');
44
+ return { path, identity: `${stat.dev}:${stat.ino}` };
45
+ }
46
+ export function checkWorkflowAuthoringDirectory(directory) {
47
+ if (workflowAuthoringDirectory(directory.path).identity !== directory.identity)
48
+ throw new Error('Workflow authoring Scope changed; discover again');
49
+ }