@nathanstephenson/flow 0.1.5 → 0.1.7

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 (49) hide show
  1. package/dist/backend/claude/index.js +28 -6
  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/entry.js +11 -3
  7. package/dist/backend/worker/index.js +31 -8
  8. package/dist/backend/worker/launcher.js +1 -0
  9. package/dist/backend/workflow-builder.js +8 -0
  10. package/dist/build-id +1 -1
  11. package/dist/cli/bootstrap.js +1 -1
  12. package/dist/cli/main.js +13 -1
  13. package/dist/daemon/host.js +14 -0
  14. package/dist/daemon/mcp-auth.js +32 -4
  15. package/dist/daemon/runtime.js +13 -3
  16. package/dist/daemon/server.js +34 -0
  17. package/dist/daemon/workflow-authoring-scope-checks.js +116 -0
  18. package/dist/daemon/workflow-authoring-scope-reader.js +42 -0
  19. package/dist/daemon/workflow-authoring-scope.js +49 -0
  20. package/dist/daemon/workflow-builder-files.js +321 -0
  21. package/dist/daemon/workflow-builder-guidance.js +31 -0
  22. package/dist/daemon/workflow-builder-reader.js +131 -0
  23. package/dist/daemon/workflow-builder-routes.js +61 -0
  24. package/dist/daemon/workflow-builder.js +480 -0
  25. package/dist/daemon/workflow-mcp-authoring-routes.js +44 -0
  26. package/dist/daemon/workflow-mcp-authoring.js +316 -0
  27. package/dist/isolation/filesystem.js +7 -4
  28. package/dist/protocol/workflow-builder.js +1 -0
  29. package/dist/protocol/workflow-mcp-authoring.js +1 -0
  30. package/package.json +1 -1
  31. package/web/dist/assets/index-DxTV-TYZ.js +38 -0
  32. package/web/dist/assets/index-jwsr3cpu.css +2 -0
  33. package/web/dist/assets/{input-CqyJUgIE.js → input-BOuBzJVY.js} +1 -1
  34. package/web/dist/assets/settings-mcp-D-jWezcS.js +1 -0
  35. package/web/dist/assets/{settings-secrets-D3zCO2H1.js → settings-secrets-DdQ0eujd.js} +1 -1
  36. package/web/dist/assets/settings-workflows-BCzYKkOk.js +23 -0
  37. package/web/dist/assets/switch-B0hMd_dH.js +1 -0
  38. package/web/dist/assets/workflow-editors-CDZqnDvT.js +137 -0
  39. package/web/dist/assets/{workflows-9aO6cptD.css → workflows-Bb90N0XJ.css} +1 -1
  40. package/web/dist/assets/workflows-BpPNiK-H.js +7 -0
  41. package/web/dist/assets/workflows-pane-N3Vf30Cb.js +1 -0
  42. package/web/dist/index.html +5 -4
  43. package/web/dist/assets/index-2oJWC9JF.css +0 -2
  44. package/web/dist/assets/index-6BD3ul5N.js +0 -174
  45. package/web/dist/assets/settings-mcp-DOQOULdG.js +0 -1
  46. package/web/dist/assets/settings-workflows-BSVIqm4R.js +0 -23
  47. package/web/dist/assets/switch-ehZe7Kr5.js +0 -1
  48. package/web/dist/assets/workflows-DC1k1O8g.js +0 -7
  49. package/web/dist/assets/workflows-pane-B0hL69SD.js +0 -1
@@ -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,116 @@
1
+ import { isAbsolute, resolve } from 'node:path';
2
+ import { isSea } from 'node:sea';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { launchWorker } from "../backend/worker/launcher.js";
5
+ const unavailable = () => new Error('Workflow authoring Scope unavailable');
6
+ const changed = () => new Error('Workflow authoring Scope changed; discover again');
7
+ const validPath = (path) => typeof path === 'string' && path.length > 0 && path.length <= 4096 && !path.includes('\0');
8
+ const validDirectory = (value) => {
9
+ const directory = value;
10
+ return !!directory && validPath(directory.path) && isAbsolute(directory.path) && resolve(directory.path) === directory.path &&
11
+ typeof directory.identity === 'string' && /^\d{1,40}:\d{1,40}$/.test(directory.identity);
12
+ };
13
+ export class WorkflowAuthoringScopeChecks {
14
+ readers = new Set();
15
+ pending = new Map();
16
+ closed = false;
17
+ closing;
18
+ options;
19
+ constructor(options = {}) { this.options = options; }
20
+ async read(path) {
21
+ if (this.closed || !validPath(path))
22
+ throw unavailable();
23
+ return this.inspect({ operation: 'read', path: resolve(path) });
24
+ }
25
+ async check(directory) {
26
+ if (this.closed || !validDirectory(directory))
27
+ throw changed();
28
+ const pinned = { path: directory.path, identity: directory.identity };
29
+ const actual = await this.inspect({ operation: 'check', ...pinned });
30
+ if (actual.path !== pinned.path || actual.identity !== pinned.identity)
31
+ throw changed();
32
+ }
33
+ hasActiveWork() { return this.readers.size > 0; }
34
+ shutdown() {
35
+ this.closed = true;
36
+ return this.closing ??= (async () => {
37
+ const readers = [...this.readers];
38
+ for (const reader of readers)
39
+ reader.cancel();
40
+ await Promise.all(readers.map(reader => reader.cleanup));
41
+ })();
42
+ }
43
+ inspect(request) {
44
+ if (this.closed)
45
+ return Promise.reject(unavailable());
46
+ const key = JSON.stringify(request);
47
+ const existing = this.pending.get(key);
48
+ if (existing)
49
+ return existing;
50
+ const pending = this.inspectOwned(request);
51
+ this.pending.set(key, pending);
52
+ const settled = () => { if (this.pending.get(key) === pending)
53
+ this.pending.delete(key); };
54
+ void pending.then(settled, settled);
55
+ return pending;
56
+ }
57
+ inspectOwned(request) {
58
+ if (this.closed || this.readers.size >= 4 || !validPath(request.path))
59
+ return Promise.reject(unavailable());
60
+ return new Promise((accept, reject) => {
61
+ let settled = false;
62
+ let reader;
63
+ let helper;
64
+ let finishCleanup;
65
+ let failCleanup;
66
+ const cleanup = new Promise((resolve, reject) => { finishCleanup = resolve; failCleanup = reject; });
67
+ void cleanup.catch(() => { });
68
+ const finish = (error, result) => {
69
+ if (settled)
70
+ return;
71
+ settled = true;
72
+ clearTimeout(timer);
73
+ if (error)
74
+ reject(error);
75
+ else
76
+ accept(result);
77
+ if (!helper) {
78
+ finishCleanup();
79
+ return;
80
+ }
81
+ void helper.stop(async () => { }).then(() => {
82
+ this.readers.delete(reader);
83
+ finishCleanup();
84
+ }, failCleanup);
85
+ };
86
+ const timer = setTimeout(() => finish(unavailable()), 5000);
87
+ const source = import.meta.url.endsWith('.ts');
88
+ const entry = fileURLToPath(new URL(source ? './workflow-authoring-scope-reader.ts' : './workflow-authoring-scope-reader.js', import.meta.url));
89
+ const env = Object.fromEntries(Object.keys(process.env).map(key => [key, undefined]));
90
+ env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER = '1';
91
+ try {
92
+ helper = (this.options.launch ?? launchWorker)({
93
+ ...(isSea() ? { args: ['--flow-workflow-authoring-scope-reader'] } : { entry, execArgv: source ? ['--experimental-strip-types'] : [] }),
94
+ cwd: '/', env, shutdownTimeoutMs: 0,
95
+ });
96
+ reader = { cancel: () => finish(unavailable()), cleanup };
97
+ this.readers.add(reader);
98
+ helper.child.once('error', () => finish(unavailable()));
99
+ helper.child.once('disconnect', () => finish(unavailable()));
100
+ void helper.exited.then(() => finish(unavailable()));
101
+ helper.child.once('message', (message) => {
102
+ const response = message;
103
+ if (!response || response.ok !== true || !validDirectory(response.result))
104
+ finish(request.operation === 'check' ? changed() : unavailable());
105
+ else
106
+ finish(undefined, response.result);
107
+ });
108
+ helper.child.send(request, error => { if (error)
109
+ finish(unavailable()); });
110
+ }
111
+ catch {
112
+ finish(unavailable());
113
+ }
114
+ });
115
+ }
116
+ }
@@ -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
+ }