@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.
- package/README.md +122 -640
- package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +94 -0
- package/build/backend-worker-chunks/chunk-MLOUI3ZM.mjs +19752 -0
- package/build/backend-worker-chunks/chunk-UQDH2COY.mjs +15296 -0
- package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +30778 -0
- package/build/backend-worker-chunks/pi-M4OA2FGL.mjs +5730 -0
- package/build/backend-worker.mjs +4401 -0
- package/dist/backend/fake/index.js +2 -0
- package/dist/backend/mcp.js +34 -15
- package/dist/backend/pi/state.js +18 -0
- package/dist/backend/registry.js +2 -1
- package/dist/backend/worker/claude-state.js +24 -3
- package/dist/backend/worker/entry.js +70 -13
- package/dist/backend/worker/frames.js +34 -0
- package/dist/backend/worker/index.js +139 -16
- package/dist/backend/worker/launcher.js +22 -3
- package/dist/backend/worker/sandbox-mcp.js +86 -0
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +7 -6
- package/dist/cli/install-guard.js +1 -1
- package/dist/cli/main.js +3 -6
- package/dist/cli/update.js +3 -3
- package/dist/cli/web-update.js +9 -6
- package/dist/client/connection.js +5 -2
- package/dist/client/diff.js +6 -9
- package/dist/client/reduce.js +19 -0
- package/dist/client/tool-chains.js +12 -4
- package/dist/daemon/config-store.js +21 -14
- package/dist/daemon/config.js +48 -5
- package/dist/daemon/git.js +47 -0
- package/dist/daemon/host.js +208 -29
- package/dist/daemon/models.js +27 -24
- package/dist/daemon/release-checker.js +48 -34
- package/dist/daemon/runtime.js +10 -4
- package/dist/daemon/server.js +13 -1
- package/dist/daemon/shell.js +2 -1
- package/dist/daemon/skills.js +34 -31
- package/dist/daemon/summariser.js +33 -14
- package/dist/daemon/timings.js +14 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +5 -8
- package/dist/daemon/workflow-authoring-scope-reader.js +20 -9
- package/dist/daemon/workflow-builder-files.js +5 -5
- package/dist/daemon/workflow-builder-guidance.js +3 -3
- package/dist/daemon/workflow-builder-reader.js +21 -10
- package/dist/daemon/workflow-builder.js +66 -8
- package/dist/daemon/workflow-executions.js +10 -10
- package/dist/daemon/workflow-mcp-authoring-routes.js +18 -6
- package/dist/daemon/workflow-mcp-authoring.js +44 -20
- package/dist/isolation/filesystem.js +8 -9
- package/dist/isolation/sandbox-supervisor.js +50 -0
- package/dist/isolation/sandbox.js +165 -0
- package/dist/isolation/shared-sandbox.js +77 -0
- package/dist/workflows/executors.js +16 -4
- package/dist/workflows/json-schema.js +14 -4
- package/package.json +7 -4
- package/web/dist/assets/index-CiEgCpiO.js +40 -0
- package/web/dist/assets/index-ClwLFMZN.css +2 -0
- package/web/dist/assets/settings-mcp-CoRWT-D_.js +1 -0
- package/web/dist/assets/settings-secrets-BIO_hXZ1.js +1 -0
- package/web/dist/assets/settings-workflows-BXbj0TKs.js +23 -0
- package/web/dist/assets/switch-DIogWclb.js +1 -0
- package/web/dist/assets/workflow-api-BfExddae.js +6 -0
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +139 -0
- package/web/dist/assets/workflows-Bv0sj7d0.js +7 -0
- package/web/dist/assets/workflows-pane-C_Yg4pgr.js +1 -0
- package/web/dist/index.html +5 -5
- package/web/dist/assets/index-DxTV-TYZ.js +0 -38
- package/web/dist/assets/index-jwsr3cpu.css +0 -2
- package/web/dist/assets/input-BOuBzJVY.js +0 -6
- package/web/dist/assets/settings-mcp-D-jWezcS.js +0 -1
- package/web/dist/assets/settings-secrets-DdQ0eujd.js +0 -1
- package/web/dist/assets/settings-workflows-BCzYKkOk.js +0 -23
- package/web/dist/assets/switch-B0hMd_dH.js +0 -1
- package/web/dist/assets/workflow-editors-CDZqnDvT.js +0 -137
- package/web/dist/assets/workflows-BpPNiK-H.js +0 -7
- package/web/dist/assets/workflows-pane-N3Vf30Cb.js +0 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { mkdtemp, chmod, mkdir, rm, writeFile, rename } from 'node:fs/promises';
|
|
3
|
-
import { tmpdir } from 'node:os';
|
|
4
3
|
import { join } from 'node:path';
|
|
5
4
|
import { z } from 'zod';
|
|
6
5
|
import { isDeepStrictEqual } from 'node:util';
|
|
7
6
|
import { validateDefinition, workflowDefinitionValidator } from "../workflows/graph.js";
|
|
8
7
|
import { workflowAuthoringScope } from "./workflow-authoring-scope.js";
|
|
9
8
|
import { WorkflowBuilderFiles } from "./workflow-builder-files.js";
|
|
9
|
+
import { workflowBuilderFolder } from "../isolation/shared-sandbox.js";
|
|
10
10
|
import { workflowBuilderInstructions } from "./workflow-builder-guidance.js";
|
|
11
11
|
const MAX_DEFINITION = 256_000;
|
|
12
12
|
const MAX_MESSAGES = 100;
|
|
@@ -36,6 +36,9 @@ function bounded(value) {
|
|
|
36
36
|
throw invalid();
|
|
37
37
|
}
|
|
38
38
|
const stepValidators = workflowDefinitionValidator.shape.steps.element.options;
|
|
39
|
+
const mcpReferenceValidator = stepValidators[5].shape.tool.omit({ connectionName: true, inputSchema: true, outputSchema: true });
|
|
40
|
+
const mcpDiagnostic = (id) => `MCP step ${JSON.stringify(id)} must use unchanged existing snapshots or exact tools from mcp-tools/<connectionId>/<toolName>.json`;
|
|
41
|
+
const mcpToolPath = /^mcp-tools\/([A-Za-z0-9_-]{1,40})\/(.+)\.json$/;
|
|
39
42
|
const draftName = { name: stepValidators[0].shape.name.or(z.literal('')) };
|
|
40
43
|
const draftStepValidator = z.discriminatedUnion('kind', [
|
|
41
44
|
stepValidators[0].extend({ ...draftName, model: z.string() }),
|
|
@@ -52,6 +55,35 @@ function definition(value, draft = false) {
|
|
|
52
55
|
const parsed = draftValidator.parse(value);
|
|
53
56
|
return draft ? parsed : validateDefinition(parsed).definition;
|
|
54
57
|
}
|
|
58
|
+
async function builderDefinition(value, entry, lookup) {
|
|
59
|
+
bounded(value);
|
|
60
|
+
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
61
|
+
const draft = value;
|
|
62
|
+
if (draft.projectId === null && entry.view.definition.projectId === undefined)
|
|
63
|
+
delete draft.projectId;
|
|
64
|
+
if (Array.isArray(draft.steps)) {
|
|
65
|
+
if (draft.steps.length > 200)
|
|
66
|
+
throw invalid();
|
|
67
|
+
for (const step of draft.steps) {
|
|
68
|
+
if (!step || typeof step !== 'object' || step.kind !== 'mcp')
|
|
69
|
+
continue;
|
|
70
|
+
const reference = mcpReferenceValidator.safeParse(step.tool);
|
|
71
|
+
if (!reference.success)
|
|
72
|
+
continue;
|
|
73
|
+
let reason = '';
|
|
74
|
+
const current = await lookup(reference.data.connectionId, reference.data.toolName)
|
|
75
|
+
.catch((error) => { reason = `: ${error instanceof Error ? error.message : String(error)}`; return undefined; });
|
|
76
|
+
const tool = [...(current ? [current] : []), ...entry.originalMcpTools].find(tool => Object.entries(reference.data).every(([key, value]) => tool[key] === value));
|
|
77
|
+
if (!tool)
|
|
78
|
+
throw new Error(mcpDiagnostic(step.id) + reason);
|
|
79
|
+
step.tool = tool;
|
|
80
|
+
bounded(value);
|
|
81
|
+
step.tool = structuredClone(tool);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return definition(value);
|
|
86
|
+
}
|
|
55
87
|
function within(promise, ms) {
|
|
56
88
|
return new Promise((resolve, reject) => {
|
|
57
89
|
const timer = setTimeout(() => reject(new Error('Timed out')), ms);
|
|
@@ -98,7 +130,7 @@ export class WorkflowBuilderService {
|
|
|
98
130
|
throw invalid();
|
|
99
131
|
}
|
|
100
132
|
const now = Date.now();
|
|
101
|
-
const entry = { view: { id: randomUUID(), definition: draft, scope: '', status: 'idle', messages: [] }, createdAt: now, touchedAt: now, closed: false, ready: false, generation: 0, turn: 0, writing: false, models: [], originalMcpTools: draft.steps.flatMap(step => step.kind === 'mcp' && step.tool.connectionId !== 'unselected' ? [structuredClone(step.tool)] : [])
|
|
133
|
+
const entry = { view: { id: randomUUID(), definition: draft, scope: '', status: 'idle', messages: [] }, createdAt: now, touchedAt: now, closed: false, ready: false, generation: 0, turn: 0, writing: false, models: [], originalMcpTools: draft.steps.flatMap(step => step.kind === 'mcp' && step.tool.connectionId !== 'unselected' ? [structuredClone(step.tool)] : []) };
|
|
102
134
|
this.entries.set(entry.view.id, entry);
|
|
103
135
|
try {
|
|
104
136
|
await within(this.trackStartup(entry, () => this.start(entry, input)), this.limits.startupMs);
|
|
@@ -126,6 +158,16 @@ export class WorkflowBuilderService {
|
|
|
126
158
|
this.opening.set(entry, pending);
|
|
127
159
|
return pending;
|
|
128
160
|
}
|
|
161
|
+
async mcpTool(entry, connectionId, toolName) {
|
|
162
|
+
if (!this.options.mcpTool)
|
|
163
|
+
throw new Error('MCP discovery unavailable');
|
|
164
|
+
await entry.files.checkScope();
|
|
165
|
+
this.check(entry);
|
|
166
|
+
const tool = await this.options.mcpTool(entry.view.scope, entry.view.definition.projectId, entry.files.scopeIdentity, connectionId, toolName);
|
|
167
|
+
await entry.files.checkScope();
|
|
168
|
+
this.check(entry);
|
|
169
|
+
return tool;
|
|
170
|
+
}
|
|
129
171
|
check(entry, starting = false) {
|
|
130
172
|
if (entry.closed || this.stopped)
|
|
131
173
|
throw new WorkflowBuilderRequestError(404, 'Workflow builder not found');
|
|
@@ -148,7 +190,7 @@ export class WorkflowBuilderService {
|
|
|
148
190
|
}
|
|
149
191
|
entry.files = files;
|
|
150
192
|
entry.view.scope = files.scope;
|
|
151
|
-
const directory = await mkdtemp(join(
|
|
193
|
+
const directory = await mkdtemp(join(workflowBuilderFolder(), 'flow-workflow-builder-'));
|
|
152
194
|
if (entry.closed) {
|
|
153
195
|
await rm(directory, { recursive: true, force: true });
|
|
154
196
|
this.check(entry);
|
|
@@ -160,7 +202,7 @@ export class WorkflowBuilderService {
|
|
|
160
202
|
await mkdir(join(directory, 'backend'), { mode: 0o700 });
|
|
161
203
|
await mkdir(join(directory, 'scope'), { mode: 0o700 });
|
|
162
204
|
this.check(entry);
|
|
163
|
-
const catalogue =
|
|
205
|
+
const catalogue = await host.workflowBuilderModels(entry.view.definition.backend, join(directory, 'scope'));
|
|
164
206
|
this.check(entry, true);
|
|
165
207
|
if (!catalogue?.models.length)
|
|
166
208
|
throw new WorkflowBuilderRequestError(400, 'Workflow Backend models are unavailable');
|
|
@@ -211,9 +253,16 @@ export class WorkflowBuilderService {
|
|
|
211
253
|
const content = JSON.stringify(catalogue);
|
|
212
254
|
if (Buffer.byteLength(content) > 192_000)
|
|
213
255
|
throw new Error('MCP tool catalogue is too large');
|
|
214
|
-
entry.catalogueMcpTools = structuredClone(catalogue.tools);
|
|
215
256
|
return content;
|
|
216
257
|
}
|
|
258
|
+
if (path.startsWith('mcp-tools/')) {
|
|
259
|
+
const match = mcpToolPath.exec(path);
|
|
260
|
+
if (!match)
|
|
261
|
+
throw new Error('Unknown MCP tool file. Use mcp-tools/<connectionId>/<toolName>.json.');
|
|
262
|
+
const tool = await this.mcpTool(entry, match[1], match[2]);
|
|
263
|
+
live();
|
|
264
|
+
return JSON.stringify(tool);
|
|
265
|
+
}
|
|
217
266
|
const content = await entry.files.read(path);
|
|
218
267
|
live();
|
|
219
268
|
return content;
|
|
@@ -231,9 +280,16 @@ export class WorkflowBuilderService {
|
|
|
231
280
|
try {
|
|
232
281
|
if (typeof content !== 'string' || Buffer.byteLength(content) > MAX_DEFINITION)
|
|
233
282
|
throw new Error();
|
|
283
|
+
const lookups = new Map();
|
|
284
|
+
const lookup = (connectionId, toolName) => {
|
|
285
|
+
const key = JSON.stringify([connectionId, toolName]);
|
|
286
|
+
if (!lookups.has(key))
|
|
287
|
+
lookups.set(key, this.mcpTool(entry, connectionId, toolName));
|
|
288
|
+
return lookups.get(key);
|
|
289
|
+
};
|
|
234
290
|
let draft;
|
|
235
291
|
try {
|
|
236
|
-
draft =
|
|
292
|
+
draft = await builderDefinition(JSON.parse(content), entry, lookup);
|
|
237
293
|
}
|
|
238
294
|
catch (error) {
|
|
239
295
|
diagnostic = error instanceof z.ZodError
|
|
@@ -253,9 +309,11 @@ export class WorkflowBuilderService {
|
|
|
253
309
|
if (!model || (model.effortLevels?.length ? !model.effortLevels.includes(step.effort) : step.effort !== 'off'))
|
|
254
310
|
throw new Error();
|
|
255
311
|
}
|
|
256
|
-
diagnostic = 'MCP steps must use unchanged existing snapshots or exact tools from mcp-tools.json';
|
|
257
312
|
for (const step of draft.steps) {
|
|
258
|
-
if (step.kind
|
|
313
|
+
if (step.kind !== 'mcp' || entry.originalMcpTools.some(tool => isDeepStrictEqual(tool, step.tool)))
|
|
314
|
+
continue;
|
|
315
|
+
diagnostic = mcpDiagnostic(step.id);
|
|
316
|
+
if (!isDeepStrictEqual(await lookup(step.tool.connectionId, step.tool.toolName).catch(() => undefined), step.tool))
|
|
259
317
|
throw new Error();
|
|
260
318
|
}
|
|
261
319
|
diagnostic = 'Workflow credential or MCP snapshot validation failed';
|
|
@@ -113,7 +113,7 @@ export class WorkflowExecutionService {
|
|
|
113
113
|
}
|
|
114
114
|
refresh() {
|
|
115
115
|
const discovered = workflowRuntimeOptions(this.config.view().workflowRuntime);
|
|
116
|
-
const options = { ...(discovered.nodePath ? { nodePath: discovered.nodePath } : {}),
|
|
116
|
+
const options = { ...(discovered.nodePath ? { nodePath: discovered.nodePath } : {}), isolationMode: this.config.filesystemIsolationMode() };
|
|
117
117
|
const key = JSON.stringify(options);
|
|
118
118
|
if (key === this.runtimeKey)
|
|
119
119
|
return;
|
|
@@ -123,7 +123,7 @@ export class WorkflowExecutionService {
|
|
|
123
123
|
this.code = {};
|
|
124
124
|
this.ready = (async () => {
|
|
125
125
|
try {
|
|
126
|
-
const executors = await createCodeExecutors({ ...this.filesystemPolicy(),
|
|
126
|
+
const executors = await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: (sessionId) => this.host.workflowSandbox(sessionId), isolationMode: options.isolationMode, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) });
|
|
127
127
|
if (key !== this.runtimeKey)
|
|
128
128
|
return;
|
|
129
129
|
this.code = executors;
|
|
@@ -476,7 +476,7 @@ export class WorkflowExecutionService {
|
|
|
476
476
|
pinned.set(step.tool.connectionId, tools);
|
|
477
477
|
}
|
|
478
478
|
for (const [connectionId, tools] of pinned)
|
|
479
|
-
await this.discoverMcp(sessionId, connectionId, tools, snapshot.runtime.
|
|
479
|
+
await this.discoverMcp(sessionId, connectionId, tools, snapshot.runtime.isolationMode);
|
|
480
480
|
this.host.assertWorkflowSession(sessionId, session.session);
|
|
481
481
|
// All setup above may yield. Resolve an overlapping retry by its durable identity before
|
|
482
482
|
// treating the session as occupied, then make occupancy the final check before the synchronous
|
|
@@ -511,9 +511,9 @@ export class WorkflowExecutionService {
|
|
|
511
511
|
throw new WorkflowConflict();
|
|
512
512
|
this.privateView(sessionId, executionId);
|
|
513
513
|
// Pre-toggle records were always restricted. Missing historical policy must never downgrade them.
|
|
514
|
-
const options = this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime),
|
|
514
|
+
const options = this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime), isolationMode: 'bubblewrap' };
|
|
515
515
|
const needsCode = saved.definition.steps.some(step => ['shell', 'typescript'].includes(step.kind));
|
|
516
|
-
const code = needsCode ? await createCodeExecutors({ ...this.filesystemPolicy(),
|
|
516
|
+
const code = needsCode ? await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: (sessionId) => this.host.workflowSandbox(sessionId), isolationMode: options.isolationMode, scope: session.scope, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) }) : {};
|
|
517
517
|
if (saved.definition.projectId && !sameProject(saved.definition.projectId, session.projectId))
|
|
518
518
|
throw new Error('Workflow is restricted to another Project');
|
|
519
519
|
const values = this.referencedSecrets(saved.definition, saved.testStepId);
|
|
@@ -701,11 +701,11 @@ export class WorkflowExecutionService {
|
|
|
701
701
|
throw new Error('MCP connection removed, disabled or changed. Enable the original connection or reselect the tool in the workflow editor.');
|
|
702
702
|
validateMcpSchemas(tool);
|
|
703
703
|
}
|
|
704
|
-
async discoverMcp(sessionId, connectionId, expected,
|
|
704
|
+
async discoverMcp(sessionId, connectionId, expected, isolationMode = this.config.filesystemIsolationMode()) {
|
|
705
705
|
const pinned = expected ? (Array.isArray(expected) ? expected : [expected]) : [];
|
|
706
706
|
for (const tool of pinned)
|
|
707
707
|
this.checkMcp(sessionId, tool);
|
|
708
|
-
const session = await this.host.openWorkflowMcp(sessionId, connectionId,
|
|
708
|
+
const session = await this.host.openWorkflowMcp(sessionId, connectionId, isolationMode);
|
|
709
709
|
try {
|
|
710
710
|
await session.open();
|
|
711
711
|
if (session.status()[0]?.state !== 'connected')
|
|
@@ -792,8 +792,8 @@ export class WorkflowExecutionService {
|
|
|
792
792
|
await this.mcpPermission(context);
|
|
793
793
|
this.checkMcp(context.sessionId, expected);
|
|
794
794
|
context.signal.throwIfAborted();
|
|
795
|
-
const
|
|
796
|
-
const session = await this.host.openWorkflowMcp(context.sessionId, expected.connectionId,
|
|
795
|
+
const isolationMode = this.runtimeSnapshots.get(context.executionId)?.isolationMode ?? 'bubblewrap';
|
|
796
|
+
const session = await this.host.openWorkflowMcp(context.sessionId, expected.connectionId, isolationMode);
|
|
797
797
|
const abort = () => { void session.dispose(); };
|
|
798
798
|
context.signal.addEventListener('abort', abort, { once: true });
|
|
799
799
|
const values = () => [...(this.secretValues.get(context.executionId) ?? []), ...this.host.workflowMcpCredentials()];
|
|
@@ -1023,7 +1023,7 @@ export class WorkflowExecutionService {
|
|
|
1023
1023
|
const saved = JSON.parse(readFileSync(this.privatePath(sessionId, executionId), 'utf8'));
|
|
1024
1024
|
const { runtime, ...activity } = saved;
|
|
1025
1025
|
if (runtime && typeof runtime === 'object') {
|
|
1026
|
-
this.runtimeSnapshots.set(executionId, { nodePath: runtime.nodePath,
|
|
1026
|
+
this.runtimeSnapshots.set(executionId, { nodePath: runtime.nodePath, isolationMode: ['none', 'bubblewrap', 'sandbox'].includes(runtime.isolationMode) ? runtime.isolationMode : runtime.isolationEnabled === false ? 'none' : 'bubblewrap' });
|
|
1027
1027
|
}
|
|
1028
1028
|
view = activity;
|
|
1029
1029
|
view.enquiries = [];
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { send } from "./http.js";
|
|
2
|
+
import { UnknownMcpTool, validMcpToolName } from "./workflow-mcp-authoring.js";
|
|
2
3
|
export async function workflowMcpAuthoringRoutes(request, response, url, service) {
|
|
3
4
|
const pathname = typeof url === 'string' ? url : url.pathname;
|
|
4
5
|
if (pathname !== '/api/workflow-mcp' && !pathname.startsWith('/api/workflow-mcp/'))
|
|
@@ -12,18 +13,21 @@ export async function workflowMcpAuthoringRoutes(request, response, url, service
|
|
|
12
13
|
send(response, 405, { error: 'Method not allowed' });
|
|
13
14
|
return true;
|
|
14
15
|
}
|
|
15
|
-
let connectionId, projectId, refresh = false;
|
|
16
|
+
let connectionId, toolName, projectId, refresh = false;
|
|
16
17
|
try {
|
|
17
|
-
const match = /^\/api\/workflow-mcp(?:\/([^/]+))?$/.exec(pathname);
|
|
18
|
+
const match = /^\/api\/workflow-mcp(?:\/([^/]+)(?:\/tools\/([^/]+))?)?$/.exec(pathname);
|
|
18
19
|
if (!match)
|
|
19
20
|
throw new Error();
|
|
20
21
|
connectionId = match[1] === undefined ? undefined : decodeURIComponent(match[1]);
|
|
21
22
|
if (connectionId !== undefined && !/^[A-Za-z0-9_-]{1,40}$/.test(connectionId))
|
|
22
23
|
throw new Error();
|
|
24
|
+
toolName = match[2] === undefined ? undefined : decodeURIComponent(match[2]);
|
|
25
|
+
if (toolName !== undefined && !validMcpToolName(toolName))
|
|
26
|
+
throw new Error();
|
|
23
27
|
const query = (typeof url === 'string' ? new URL(request.url ?? pathname, 'http://localhost') : url).searchParams;
|
|
24
28
|
if ([...query.keys()].some(key => !['projectId', 'refresh'].includes(key)) || query.getAll('projectId').length > 1 || query.getAll('refresh').length > 1)
|
|
25
29
|
throw new Error();
|
|
26
|
-
if (query.has('refresh') && (query.get('refresh') !== '1' || connectionId === undefined))
|
|
30
|
+
if (query.has('refresh') && (query.get('refresh') !== '1' || connectionId === undefined || toolName !== undefined))
|
|
27
31
|
throw new Error();
|
|
28
32
|
refresh = query.get('refresh') === '1';
|
|
29
33
|
projectId = query.get('projectId') ?? undefined;
|
|
@@ -35,10 +39,18 @@ export async function workflowMcpAuthoringRoutes(request, response, url, service
|
|
|
35
39
|
return true;
|
|
36
40
|
}
|
|
37
41
|
try {
|
|
38
|
-
send(response, 200, connectionId === undefined ? await service.connections(projectId)
|
|
42
|
+
send(response, 200, connectionId === undefined ? await service.connections(projectId)
|
|
43
|
+
: toolName === undefined ? await service.discover(projectId, connectionId, refresh)
|
|
44
|
+
: await service.tool(projectId, connectionId, toolName));
|
|
39
45
|
}
|
|
40
|
-
catch {
|
|
41
|
-
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (error instanceof UnknownMcpTool) {
|
|
48
|
+
send(response, 404, { error: error.message });
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
const reason = error instanceof Error ? error.message : 'Check MCP Settings and the selected Project.';
|
|
52
|
+
console.error(`Workflow MCP authoring request failed: ${reason}`);
|
|
53
|
+
send(response, 400, { error: `Workflow MCP connection or Scope unavailable: ${reason}` });
|
|
42
54
|
}
|
|
43
55
|
return true;
|
|
44
56
|
}
|
|
@@ -10,6 +10,11 @@ const MAX_BYTES = 192_000;
|
|
|
10
10
|
const MAX_TOOLS = 256;
|
|
11
11
|
const MAX_ERRORS = 128;
|
|
12
12
|
const MAX_TOOL_BYTES = 48_000;
|
|
13
|
+
const MAX_CACHED_BYTES = 2_000_000;
|
|
14
|
+
const MAX_DESCRIPTION = 300;
|
|
15
|
+
export class UnknownMcpTool extends Error {
|
|
16
|
+
}
|
|
17
|
+
export const validMcpToolName = (name) => /^[^\x00-\x1f\x7f]{1,128}$/.test(name);
|
|
13
18
|
export class WorkflowMcpAuthoringService {
|
|
14
19
|
options;
|
|
15
20
|
scopes = new WorkflowAuthoringScopeChecks();
|
|
@@ -40,15 +45,33 @@ export class WorkflowMcpAuthoringService {
|
|
|
40
45
|
}
|
|
41
46
|
}
|
|
42
47
|
discover(projectId, connectionId, refresh = false) {
|
|
43
|
-
return this.bounded(deadline =>
|
|
48
|
+
return this.bounded(async (deadline) => {
|
|
49
|
+
const result = await this.discoverWithin(projectId, connectionId, refresh, deadline);
|
|
50
|
+
return this.redact(structuredClone({ tools: result.tools.map(tool => tool.listing), errors: result.errors }));
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
tool(projectId, connectionId, toolName, expectedScope) {
|
|
54
|
+
return this.bounded(async (deadline) => {
|
|
55
|
+
if (!validMcpToolName(toolName))
|
|
56
|
+
throw new Error('Invalid MCP tool name');
|
|
57
|
+
const result = await this.discoverWithin(projectId, connectionId, false, deadline, expectedScope, true);
|
|
58
|
+
const found = result.tools.find(tool => tool.snapshot.toolName === toolName);
|
|
59
|
+
if (!found)
|
|
60
|
+
throw new UnknownMcpTool('Unknown MCP tool');
|
|
61
|
+
return this.redact(structuredClone(found.snapshot));
|
|
62
|
+
});
|
|
44
63
|
}
|
|
45
|
-
async discoverWithin(projectId, connectionId, refresh, deadline) {
|
|
64
|
+
async discoverWithin(projectId, connectionId, refresh, deadline, expectedScope, known = false) {
|
|
46
65
|
const scope = await this.scope(projectId);
|
|
47
66
|
this.checkDeadline(deadline);
|
|
67
|
+
if (expectedScope && (scope.path !== expectedScope.scope || scope.identity !== expectedScope.scopeIdentity))
|
|
68
|
+
throw new Error('MCP authoring Scope changed. Close and reopen the builder.');
|
|
48
69
|
const generation = this.generation;
|
|
49
70
|
const connection = this.options.config.mcpConnections().find(connection => connection.id === connectionId);
|
|
50
71
|
if (!connection)
|
|
51
72
|
throw new Error('Unknown MCP connection');
|
|
73
|
+
if (known && !connection.enabledByDefault && !this.entries.has(this.key(scope, connection)))
|
|
74
|
+
throw new Error('MCP connection is not discovered; discover it in the MCP editor first');
|
|
52
75
|
const result = await this.request(scope, connection, deadline, generation, refresh);
|
|
53
76
|
this.checkDeadline(deadline);
|
|
54
77
|
await this.scopes.check(scope);
|
|
@@ -56,7 +79,7 @@ export class WorkflowMcpAuthoringService {
|
|
|
56
79
|
this.refresh();
|
|
57
80
|
if (generation !== this.generation)
|
|
58
81
|
throw new Error('MCP configuration changed; discover again');
|
|
59
|
-
return
|
|
82
|
+
return result;
|
|
60
83
|
}
|
|
61
84
|
catalogue(projectId, expectedScope) {
|
|
62
85
|
return this.bounded(deadline => this.catalogueWithin(projectId, expectedScope, deadline));
|
|
@@ -103,8 +126,8 @@ export class WorkflowMcpAuthoringService {
|
|
|
103
126
|
}
|
|
104
127
|
for (const { connection, discovery } of results) {
|
|
105
128
|
const source = { connectionId: connection.id, connectionName: connection.name };
|
|
106
|
-
for (const tool of discovery?.tools ?? []) {
|
|
107
|
-
result.tools.push(this.redact(tool));
|
|
129
|
+
for (const { listing: tool } of discovery?.tools ?? []) {
|
|
130
|
+
result.tools.push(this.redact(structuredClone(tool)));
|
|
108
131
|
if (result.tools.length > MAX_TOOLS || !fits()) {
|
|
109
132
|
result.tools.pop();
|
|
110
133
|
addError({ ...source, toolName: this.text(tool.toolName, 120), message: 'MCP catalogue limit exceeded; tool omitted' });
|
|
@@ -129,7 +152,7 @@ export class WorkflowMcpAuthoringService {
|
|
|
129
152
|
if (this.stopped)
|
|
130
153
|
throw new Error('Workflow MCP authoring stopped');
|
|
131
154
|
const config = this.options.config;
|
|
132
|
-
const fingerprint = createHash('sha256').update(JSON.stringify([config.projectRoot(), config.projectInclude(), config.mcpConnections(), config.
|
|
155
|
+
const fingerprint = createHash('sha256').update(JSON.stringify([config.projectRoot(), config.projectInclude(), config.mcpConnections(), config.filesystemIsolationMode(), this.options.host.workflowMcpCredentials()])).digest('hex');
|
|
133
156
|
if (fingerprint !== this.fingerprint) {
|
|
134
157
|
this.fingerprint = fingerprint;
|
|
135
158
|
this.invalidate(new Error('MCP configuration changed; discover again'));
|
|
@@ -166,7 +189,7 @@ export class WorkflowMcpAuthoringService {
|
|
|
166
189
|
}
|
|
167
190
|
let resolve, reject;
|
|
168
191
|
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
169
|
-
const entry = { scope: scope.path, directory: scope, connection: structuredClone(connection), isolation: this.options.config.
|
|
192
|
+
const entry = { scope: scope.path, directory: scope, connection: structuredClone(connection), isolation: this.options.config.filesystemIsolationMode(), generation: this.generation, promise, resolve, reject, controller: new AbortController(), expires: 0, timer: undefined };
|
|
170
193
|
entry.controller.signal.addEventListener('abort', () => {
|
|
171
194
|
clearTimeout(entry.timer);
|
|
172
195
|
entry.expires = Date.now() + TTL;
|
|
@@ -247,6 +270,7 @@ export class WorkflowMcpAuthoringService {
|
|
|
247
270
|
signal.removeEventListener('abort', cancel);
|
|
248
271
|
}
|
|
249
272
|
}
|
|
273
|
+
/** Keeps full snapshots for the cache. Responses carry listings; tool() serves one snapshot. */
|
|
250
274
|
snapshot(connection, session) {
|
|
251
275
|
const result = { tools: [], errors: [] };
|
|
252
276
|
let omitted = false;
|
|
@@ -256,30 +280,30 @@ export class WorkflowMcpAuthoringService {
|
|
|
256
280
|
return;
|
|
257
281
|
}
|
|
258
282
|
result.errors.push({ toolName: this.text(toolName, 120), message: this.text(message, 600) });
|
|
259
|
-
if (bytes(result) > MAX_BYTES - 1_024) {
|
|
260
|
-
result.errors.pop();
|
|
261
|
-
omitted = true;
|
|
262
|
-
}
|
|
263
283
|
};
|
|
264
|
-
const tools = session.tools();
|
|
265
|
-
|
|
284
|
+
const tools = session.tools().slice(0, MAX_TOOLS);
|
|
285
|
+
let cached = 0;
|
|
286
|
+
for (const [index, tool] of tools.entries()) {
|
|
266
287
|
try {
|
|
267
|
-
const data = { connectionId: connection.id, connectionName: connection.name, serverIdentity: tool.serverIdentity, toolName: tool.definition.name, inputSchema: tool.definition.inputSchema, outputSchema: tool.definition.outputSchema };
|
|
288
|
+
const data = { connectionId: connection.id, connectionName: connection.name, serverIdentity: tool.serverIdentity, toolName: tool.definition.name, description: tool.definition.description, inputSchema: tool.definition.inputSchema, outputSchema: tool.definition.outputSchema };
|
|
268
289
|
this.assertNoSecrets(data);
|
|
269
290
|
if (bytes(data) > MAX_TOOL_BYTES)
|
|
270
291
|
throw new Error('MCP tool exceeds the discovery size limit');
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
throw new Error('MCP discovery size limit exceeded; tool omitted');
|
|
292
|
+
cached += bytes(data);
|
|
293
|
+
if (cached > MAX_CACHED_BYTES) {
|
|
294
|
+
error('', `MCP discovery memory limit exceeded; ${tools.length - index} tools omitted`);
|
|
295
|
+
break;
|
|
276
296
|
}
|
|
297
|
+
const snapshot = snapshotTool(connection, tool);
|
|
298
|
+
const { inputSchema: _input, outputSchema: _output, ...listing } = snapshot;
|
|
299
|
+
const description = tool.definition.description?.slice(0, MAX_DESCRIPTION);
|
|
300
|
+
result.tools.push({ snapshot, listing: description === undefined ? listing : { ...listing, description } });
|
|
277
301
|
}
|
|
278
302
|
catch (failure) {
|
|
279
303
|
error(tool.definition.name, this.safeError(failure).message);
|
|
280
304
|
}
|
|
281
305
|
}
|
|
282
|
-
if (tools.length > MAX_TOOLS)
|
|
306
|
+
if (session.tools().length > MAX_TOOLS)
|
|
283
307
|
error('', 'MCP tool count limit exceeded; additional tools omitted');
|
|
284
308
|
if (omitted)
|
|
285
309
|
result.errors.push({ toolName: '', message: 'MCP diagnostic limit exceeded; additional diagnostics omitted' });
|
|
@@ -194,7 +194,7 @@ export async function prepareFilesystemIsolation(options) {
|
|
|
194
194
|
if (before.dev !== after.dev || before.ino !== after.ino || realpathSync(`/proc/self/fd/${fd}`) !== path) {
|
|
195
195
|
throw new Error(`Execution mount source changed during preparation: ${path}`);
|
|
196
196
|
}
|
|
197
|
-
return String(
|
|
197
|
+
return String(3 + sources.length - 1);
|
|
198
198
|
};
|
|
199
199
|
try {
|
|
200
200
|
const { inherited, home, credentialHome, piDir, claudeDir, claudeAuthDir, flowRoots, protectedPaths, scope } = scopeContext(options);
|
|
@@ -335,14 +335,16 @@ export async function prepareFilesystemIsolation(options) {
|
|
|
335
335
|
if (options.credentials === "pi") {
|
|
336
336
|
for (const name of ["auth.json", "models.json", "settings.json"])
|
|
337
337
|
stage(join(piDir, name), join(env.PI_CODING_AGENT_DIR, name));
|
|
338
|
-
|
|
338
|
+
if (!options.workflowBuilder)
|
|
339
|
+
resources("Pi", piDir, env.PI_CODING_AGENT_DIR, ["AGENTS.md", "skills", "prompts", "themes", "extensions", "packages", "bin", "tools"]);
|
|
339
340
|
}
|
|
340
341
|
else if (options.credentials === "claude") {
|
|
341
342
|
stage(join(claudeAuthDir, ".credentials.json"), join(env.CLAUDE_CONFIG_DIR, ".credentials.json"));
|
|
342
343
|
const config = existsSync(join(claudeDir, ".claude.json")) ? join(claudeDir, ".claude.json") : join(credentialHome, ".claude.json");
|
|
343
344
|
stage(config, join(virtualHome, ".claude.json"));
|
|
344
345
|
stage(config, join(env.CLAUDE_CONFIG_DIR, ".claude.json"));
|
|
345
|
-
|
|
346
|
+
if (!options.workflowBuilder)
|
|
347
|
+
resources("Claude", claudeDir, env.CLAUDE_CONFIG_DIR, ["CLAUDE.md", "commands", "skills", "agents", "rules", "plugins"]);
|
|
346
348
|
// The CLI owns its project transcripts. Persist only that subtree, not global credentials.
|
|
347
349
|
const projects = join(backend, "claude-projects");
|
|
348
350
|
if (!existsSync(projects))
|
|
@@ -363,18 +365,15 @@ export async function prepareFilesystemIsolation(options) {
|
|
|
363
365
|
// Probe the actual mount policy and namespaces, not merely `bwrap --version`. Never run the
|
|
364
366
|
// requested program when unavailable; no cached probe can turn a later failure into fallback.
|
|
365
367
|
try {
|
|
366
|
-
|
|
367
|
-
await probeBoundary(bwrap, [...args, "--", "/bin/true"], env, [...(options.ipc ? ["ignore"] : []), ...sources]);
|
|
368
|
+
await probeBoundary(bwrap, [...args, "--", "/bin/true"], env, sources);
|
|
368
369
|
}
|
|
369
370
|
catch (error) {
|
|
370
371
|
// execFile's default message includes every --setenv argument, including provider keys.
|
|
371
372
|
const failure = error;
|
|
372
373
|
throw new Error(`Bubblewrap namespace/mount probe failed (${failure.signal ?? failure.code ?? "unknown"}): ${(failure.stderr ?? "").trim().slice(-2048)}`);
|
|
373
374
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
if (options.ipc)
|
|
377
|
-
args.push("--setenv", "NODE_CHANNEL_FD", "3", "--setenv", "NODE_CHANNEL_SERIALIZATION_MODE", "advanced", "--setenv", "FLOW_BACKEND_WORKER", "1");
|
|
375
|
+
if (options.worker)
|
|
376
|
+
args.push("--setenv", "FLOW_BACKEND_WORKER", "1");
|
|
378
377
|
args.push("--", command, ...options.args);
|
|
379
378
|
return { command: bwrap, args, env, stdioFds: sources.slice(), scope, stateDir: virtualState, cleanup };
|
|
380
379
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Runs inside the sandbox as `node -e`. Stops every process carrying this command's marker when
|
|
2
|
+
* stdin closes or the command exits, so one command tree stops without affecting others in the VM. */
|
|
3
|
+
export function sandboxSupervisor() {
|
|
4
|
+
const { spawn } = process.getBuiltinModule("node:child_process");
|
|
5
|
+
const { readdirSync, readFileSync } = process.getBuiltinModule("node:fs");
|
|
6
|
+
const { constants } = process.getBuiltinModule("node:os");
|
|
7
|
+
const id = `${process.pid}-${Date.now()}`;
|
|
8
|
+
const marker = `FLOW_SANDBOX_COMMAND=${id}`;
|
|
9
|
+
const argv = process.argv.slice(1);
|
|
10
|
+
if (argv[0] === "--")
|
|
11
|
+
argv.shift();
|
|
12
|
+
const child = spawn(argv[0], argv.slice(1), { stdio: "pipe", env: { ...process.env, FLOW_SANDBOX_COMMAND: id } });
|
|
13
|
+
child.stdout.pipe(process.stdout);
|
|
14
|
+
child.stderr.pipe(process.stderr);
|
|
15
|
+
const drained = Promise.all([child.stdout, child.stderr].map((stream) => new Promise((resolve) => stream.once("close", resolve))));
|
|
16
|
+
const marked = () => readdirSync("/proc").filter((entry) => /^\d+$/.test(entry) && Number(entry) !== process.pid).filter((pid) => {
|
|
17
|
+
try {
|
|
18
|
+
return readFileSync(`/proc/${pid}/environ`, "latin1").split("\0").includes(marker);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}).map(Number);
|
|
24
|
+
const signalAll = (signal) => {
|
|
25
|
+
for (const pid of marked()) {
|
|
26
|
+
try {
|
|
27
|
+
process.kill(pid, signal);
|
|
28
|
+
}
|
|
29
|
+
catch { /* already gone */ }
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
let finishing = false;
|
|
33
|
+
const finish = async (code) => {
|
|
34
|
+
if (finishing)
|
|
35
|
+
return;
|
|
36
|
+
finishing = true;
|
|
37
|
+
signalAll("SIGTERM");
|
|
38
|
+
for (let wait = 0; wait < 40 && marked().length; wait++)
|
|
39
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
40
|
+
signalAll("SIGKILL");
|
|
41
|
+
await Promise.race([drained, new Promise((resolve) => setTimeout(resolve, 2000))]);
|
|
42
|
+
process.stdout.write("", () => process.exit(code));
|
|
43
|
+
};
|
|
44
|
+
child.on("error", () => void finish(127));
|
|
45
|
+
child.on("exit", (code, signal) => void finish(code ?? 128 + (signal ? constants.signals[signal] : 1)));
|
|
46
|
+
child.stdin.on("error", () => { });
|
|
47
|
+
process.stdin.pipe(child.stdin);
|
|
48
|
+
process.stdin.on("end", () => { setTimeout(() => void finish(143), 5000).unref(); });
|
|
49
|
+
}
|
|
50
|
+
export const sandboxSupervisorSource = `(${sandboxSupervisor.toString()})()`;
|