@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
@@ -0,0 +1,480 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdtemp, chmod, mkdir, rm, writeFile, rename } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { validateDefinition, workflowDefinitionValidator } from "../workflows/graph.js";
8
+ import { workflowAuthoringScope } from "./workflow-authoring-scope.js";
9
+ import { WorkflowBuilderFiles } from "./workflow-builder-files.js";
10
+ import { workflowBuilderInstructions } from "./workflow-builder-guidance.js";
11
+ const MAX_DEFINITION = 256_000;
12
+ const MAX_MESSAGES = 100;
13
+ const MAX_TEXT = 32_000;
14
+ const MAX_HISTORY = 256_000;
15
+ // A cold catalogue probe and a worker startup each have their own bounded launch window.
16
+ const defaults = { startupMs: 120_000, idleMs: 30 * 60_000, lifetimeMs: 2 * 60 * 60_000, turnMs: 10 * 60_000, disposeMs: 5_000, maxBuilders: 8 };
17
+ export class WorkflowBuilderRequestError extends Error {
18
+ status;
19
+ constructor(status, message) { super(message); this.status = status; }
20
+ }
21
+ const invalid = () => new WorkflowBuilderRequestError(400, 'Invalid workflow builder request');
22
+ /** Limits nesting and collection counts before recursive schema/graph validation. */
23
+ function bounded(value) {
24
+ const pending = [{ value, depth: 0 }];
25
+ let count = 0;
26
+ while (pending.length) {
27
+ const item = pending.pop();
28
+ if (++count > 20_000 || item.depth > 40)
29
+ throw invalid();
30
+ if (item.value && typeof item.value === 'object') {
31
+ for (const child of Object.values(item.value))
32
+ pending.push({ value: child, depth: item.depth + 1 });
33
+ }
34
+ }
35
+ if (Buffer.byteLength(JSON.stringify(value) ?? '') > MAX_DEFINITION)
36
+ throw invalid();
37
+ }
38
+ const stepValidators = workflowDefinitionValidator.shape.steps.element.options;
39
+ const draftName = { name: stepValidators[0].shape.name.or(z.literal('')) };
40
+ const draftStepValidator = z.discriminatedUnion('kind', [
41
+ stepValidators[0].extend({ ...draftName, model: z.string() }),
42
+ stepValidators[1].extend(draftName), stepValidators[2].extend(draftName),
43
+ stepValidators[3].extend(draftName), stepValidators[4].extend(draftName), stepValidators[5].extend(draftName),
44
+ ]);
45
+ const draftValidator = workflowDefinitionValidator.extend({
46
+ name: z.string(), steps: z.array(draftStepValidator).max(200), edges: workflowDefinitionValidator.shape.edges.max(500),
47
+ });
48
+ function definition(value, draft = false) {
49
+ bounded(value);
50
+ // Creation is authoring input, not an executable graph: permit blank model selections and
51
+ // broken connections/mappings for the agent to repair. Writes still require full validation.
52
+ const parsed = draftValidator.parse(value);
53
+ return draft ? parsed : validateDefinition(parsed).definition;
54
+ }
55
+ function within(promise, ms) {
56
+ return new Promise((resolve, reject) => {
57
+ const timer = setTimeout(() => reject(new Error('Timed out')), ms);
58
+ promise.then(value => { clearTimeout(timer); resolve(value); }, error => { clearTimeout(timer); reject(error); });
59
+ });
60
+ }
61
+ /** Ephemeral authoring only. No WorkflowStore reference, saved-definition writes, or Agent Session. */
62
+ export class WorkflowBuilderService {
63
+ entries = new Map();
64
+ opening = new Map();
65
+ disposing = new Map();
66
+ options;
67
+ limits;
68
+ sweep;
69
+ stopped = false;
70
+ constructor(options) {
71
+ this.options = options;
72
+ this.limits = { ...defaults, ...options.limits };
73
+ this.sweep = setInterval(() => {
74
+ const now = Date.now();
75
+ for (const entry of this.entries.values()) {
76
+ if (now - entry.createdAt >= this.limits.lifetimeMs || (entry.view.status !== 'running' && now - entry.touchedAt >= this.limits.idleMs))
77
+ void this.close(entry.view.id);
78
+ }
79
+ }, Math.min(30_000, this.limits.idleMs, this.limits.lifetimeMs));
80
+ this.sweep.unref();
81
+ }
82
+ async create(input) {
83
+ if (this.stopped)
84
+ throw new WorkflowBuilderRequestError(503, 'Workflow builder unavailable');
85
+ // Timed-out adapter creates remain quarantined until their late result can be disposed.
86
+ if (new Set([...this.entries.values(), ...this.opening.keys()]).size + this.disposing.size >= this.limits.maxBuilders)
87
+ throw new WorkflowBuilderRequestError(429, 'Too many workflow builders');
88
+ let draft;
89
+ try {
90
+ if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['definition', 'modelId', 'effort'].includes(key)))
91
+ throw invalid();
92
+ if (input.modelId !== undefined && (typeof input.modelId !== 'string' || !input.modelId || input.modelId.length > 256))
93
+ throw invalid();
94
+ draft = definition(input.definition, true);
95
+ this.options.validateDefinition?.(draft);
96
+ }
97
+ catch {
98
+ throw invalid();
99
+ }
100
+ 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)] : []), catalogueMcpTools: [] };
102
+ this.entries.set(entry.view.id, entry);
103
+ try {
104
+ await within(this.trackStartup(entry, () => this.start(entry, input)), this.limits.startupMs);
105
+ this.check(entry);
106
+ entry.ready = true;
107
+ return this.view(entry.view.id);
108
+ }
109
+ catch (error) {
110
+ // Report a startup timeout promptly, but retain ownership of its eventual disposal.
111
+ await within(this.close(entry.view.id), this.limits.disposeMs).catch(() => { });
112
+ if (error instanceof WorkflowBuilderRequestError)
113
+ throw error;
114
+ throw new WorkflowBuilderRequestError(400, 'Workflow builder could not start');
115
+ }
116
+ }
117
+ trackStartup(entry, work) {
118
+ const startup = new AbortController();
119
+ entry.startup = startup;
120
+ const pending = Promise.resolve().then(() => { startup.signal.throwIfAborted(); return work(); }).finally(() => {
121
+ if (this.opening.get(entry) === pending)
122
+ this.opening.delete(entry);
123
+ if (entry.startup === startup)
124
+ delete entry.startup;
125
+ });
126
+ this.opening.set(entry, pending);
127
+ return pending;
128
+ }
129
+ check(entry, starting = false) {
130
+ if (entry.closed || this.stopped)
131
+ throw new WorkflowBuilderRequestError(404, 'Workflow builder not found');
132
+ if (starting)
133
+ entry.startup?.signal.throwIfAborted();
134
+ }
135
+ async start(entry, input) {
136
+ const { config, scope, stateRoot, host } = this.options;
137
+ let root;
138
+ try {
139
+ root = workflowAuthoringScope(config, scope, entry.view.definition.projectId);
140
+ }
141
+ catch {
142
+ throw new WorkflowBuilderRequestError(400, 'Workflow Project is not opted in or its Scope is unavailable');
143
+ }
144
+ const files = await WorkflowBuilderFiles.create(root, stateRoot);
145
+ if (entry.closed) {
146
+ await files.close();
147
+ this.check(entry);
148
+ }
149
+ entry.files = files;
150
+ entry.view.scope = files.scope;
151
+ const directory = await mkdtemp(join(tmpdir(), 'flow-workflow-builder-'));
152
+ if (entry.closed) {
153
+ await rm(directory, { recursive: true, force: true });
154
+ this.check(entry);
155
+ }
156
+ entry.directory = directory;
157
+ files.protect(directory);
158
+ await chmod(directory, 0o700);
159
+ await writeFile(join(directory, 'workflow.json'), JSON.stringify(entry.view.definition), { mode: 0o600, flag: 'wx' });
160
+ await mkdir(join(directory, 'backend'), { mode: 0o700 });
161
+ await mkdir(join(directory, 'scope'), { mode: 0o700 });
162
+ this.check(entry);
163
+ const catalogue = (await host.models(join(directory, 'scope'))).find(catalogue => catalogue.backend === entry.view.definition.backend);
164
+ this.check(entry, true);
165
+ if (!catalogue?.models.length)
166
+ throw new WorkflowBuilderRequestError(400, 'Workflow Backend models are unavailable');
167
+ entry.models = catalogue.models.slice(0, 500);
168
+ const modelId = input.modelId ?? config.defaultModel(entry.view.definition.backend) ?? entry.models[0].id;
169
+ const model = entry.models.find(model => model.id === modelId);
170
+ if (!model)
171
+ throw new WorkflowBuilderRequestError(400, 'Workflow builder model is unavailable');
172
+ const levels = model.effortLevels ?? [];
173
+ const effort = input.effort ?? (levels.length
174
+ ? config.defaultEffort(entry.view.definition.backend) ?? (levels.includes('medium') ? 'medium' : levels[0])
175
+ : 'off');
176
+ if (levels.length ? !levels.includes(effort) : effort !== 'off')
177
+ throw new WorkflowBuilderRequestError(400, 'Workflow builder Effort is unsupported');
178
+ entry.modelId = modelId;
179
+ entry.effort = effort;
180
+ await this.open(entry);
181
+ }
182
+ async open(entry) {
183
+ this.check(entry, true);
184
+ const generation = ++entry.generation;
185
+ entry.meterGeneration = generation;
186
+ delete entry.view.contextUsage;
187
+ const instructions = await workflowBuilderInstructions(entry.view.definition, entry.models);
188
+ this.check(entry, true);
189
+ const live = () => { this.check(entry); if (entry.generation !== generation || entry.view.status !== 'running')
190
+ throw new Error('Workflow builder turn is not active'); };
191
+ const options = {
192
+ scope: join(entry.directory, 'scope'), stateDir: join(entry.directory, 'backend'),
193
+ ...(entry.startup ? { signal: entry.startup.signal } : {}),
194
+ ...(entry.modelId ? { modelId: entry.modelId } : {}), ...(entry.effort ? { effort: entry.effort } : {}),
195
+ ...(entry.view.spend ? { priorSpend: structuredClone(entry.view.spend) } : {}),
196
+ workflowBuilder: {
197
+ instructions,
198
+ read: async (path) => {
199
+ live();
200
+ if (path === 'workflow.json')
201
+ return JSON.stringify(entry.view.definition);
202
+ if (path === 'mcp-tools.json') {
203
+ await entry.files.checkScope();
204
+ live();
205
+ const catalogue = await this.options.mcpCatalogue?.(entry.view.scope, entry.view.definition.projectId, entry.files.scopeIdentity)
206
+ ?? { scope: entry.view.scope, scopeIdentity: entry.files.scopeIdentity, connections: [], tools: [], errors: [] };
207
+ await entry.files.checkScope();
208
+ live();
209
+ if (catalogue.scope !== entry.view.scope || catalogue.scopeIdentity !== entry.files.scopeIdentity)
210
+ throw new Error('MCP authoring Scope changed. Close and reopen the builder.');
211
+ const content = JSON.stringify(catalogue);
212
+ if (Buffer.byteLength(content) > 192_000)
213
+ throw new Error('MCP tool catalogue is too large');
214
+ entry.catalogueMcpTools = structuredClone(catalogue.tools);
215
+ return content;
216
+ }
217
+ const content = await entry.files.read(path);
218
+ live();
219
+ return content;
220
+ },
221
+ list: async (path) => { live(); return entry.files.list(path); },
222
+ write: async (content) => {
223
+ live();
224
+ const turn = entry.turn;
225
+ if (entry.writing)
226
+ throw new Error('Workflow draft write already in progress');
227
+ entry.writing = true;
228
+ let replaced = false;
229
+ let diagnostic = 'Invalid workflow draft';
230
+ const previous = JSON.stringify(entry.view.definition);
231
+ try {
232
+ if (typeof content !== 'string' || Buffer.byteLength(content) > MAX_DEFINITION)
233
+ throw new Error();
234
+ let draft;
235
+ try {
236
+ draft = definition(JSON.parse(content));
237
+ }
238
+ catch (error) {
239
+ diagnostic = error instanceof z.ZodError
240
+ ? error.issues.slice(0, 3).map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; ').slice(0, 500)
241
+ : error instanceof SyntaxError ? 'Invalid JSON definition'
242
+ : error instanceof Error ? error.message.slice(0, 500) : diagnostic;
243
+ throw error;
244
+ }
245
+ diagnostic = 'Keep the workflow id, Backend Adapter and Project unchanged';
246
+ if (draft.id !== entry.view.definition.id || draft.projectId !== entry.view.definition.projectId || draft.backend !== entry.view.definition.backend)
247
+ throw new Error();
248
+ diagnostic = 'Agent steps must use an available model and supported Effort';
249
+ for (const step of draft.steps) {
250
+ if (step.kind !== 'agent')
251
+ continue;
252
+ const model = entry.models.find(model => model.id === step.model);
253
+ if (!model || (model.effortLevels?.length ? !model.effortLevels.includes(step.effort) : step.effort !== 'off'))
254
+ throw new Error();
255
+ }
256
+ diagnostic = 'MCP steps must use unchanged existing snapshots or exact tools from mcp-tools.json';
257
+ for (const step of draft.steps) {
258
+ if (step.kind === 'mcp' && ![...entry.originalMcpTools, ...entry.catalogueMcpTools].some(tool => isDeepStrictEqual(tool, step.tool)))
259
+ throw new Error();
260
+ }
261
+ diagnostic = 'Workflow credential or MCP snapshot validation failed';
262
+ this.options.validateDefinition?.(draft);
263
+ diagnostic = 'Workflow draft write interrupted';
264
+ live();
265
+ const temporary = join(entry.directory, 'workflow.next');
266
+ await writeFile(temporary, JSON.stringify(draft), { mode: 0o600 });
267
+ live();
268
+ if (entry.turn !== turn)
269
+ throw new Error();
270
+ await rename(temporary, join(entry.directory, 'workflow.json'));
271
+ replaced = true;
272
+ live();
273
+ if (entry.turn !== turn)
274
+ throw new Error();
275
+ entry.view.definition = draft;
276
+ return 'Private workflow.json updated. The human must Apply and Save to persist it.';
277
+ }
278
+ catch {
279
+ // Cancellation can win while the atomic rename is awaiting IO. The public draft is
280
+ // unchanged; restore its private mirror before permitting another turn.
281
+ if (replaced && !entry.closed) {
282
+ const rollback = join(entry.directory, 'workflow.rollback');
283
+ await writeFile(rollback, previous, { mode: 0o600 }).then(() => rename(rollback, join(entry.directory, 'workflow.json'))).catch(() => { });
284
+ }
285
+ throw new Error(`Invalid workflow draft; previous draft preserved. ${diagnostic}`);
286
+ }
287
+ finally {
288
+ entry.writing = false;
289
+ }
290
+ },
291
+ },
292
+ emit: event => {
293
+ if (event.type === 'context_usage') {
294
+ if (event.spend && entry.meterGeneration === generation)
295
+ entry.view.spend = structuredClone(event.spend);
296
+ if (!entry.closed && entry.generation === generation)
297
+ this.event(entry, event);
298
+ }
299
+ else if (!entry.closed && entry.generation === generation)
300
+ this.event(entry, event);
301
+ },
302
+ onFailure: () => { if (!entry.closed && entry.generation === generation)
303
+ this.fail(entry); },
304
+ };
305
+ const builder = options.workflowBuilder;
306
+ const performWrite = builder.write;
307
+ builder.write = async (content) => {
308
+ live();
309
+ if (entry.writePending)
310
+ throw new Error('Workflow draft write already in progress');
311
+ const pending = performWrite(content);
312
+ entry.writePending = pending;
313
+ void pending.finally(() => { if (entry.writePending === pending)
314
+ delete entry.writePending; }).catch(() => { });
315
+ return pending;
316
+ };
317
+ const session = await this.options.host.createWorkflowBuilderSession(entry.view.definition.backend, options);
318
+ if (entry.closed || entry.generation !== generation) {
319
+ await session.dispose().catch(() => { });
320
+ if (entry.meterGeneration === generation)
321
+ delete entry.meterGeneration;
322
+ this.check(entry);
323
+ throw new Error();
324
+ }
325
+ entry.session = session;
326
+ }
327
+ view(id) {
328
+ const entry = this.get(id);
329
+ entry.touchedAt = Date.now();
330
+ const snapshot = structuredClone(entry.view);
331
+ if (entry.stopping || (this.opening.has(entry) && entry.startup?.signal.aborted) ||
332
+ (entry.writing && entry.view.status !== 'running'))
333
+ snapshot.stopping = true;
334
+ return snapshot;
335
+ }
336
+ get(id) {
337
+ const entry = this.entries.get(id);
338
+ if (!entry || entry.closed)
339
+ throw new WorkflowBuilderRequestError(404, 'Workflow builder not found');
340
+ if (!entry.ready)
341
+ throw new WorkflowBuilderRequestError(409, 'Workflow builder is starting');
342
+ return entry;
343
+ }
344
+ message(id, text) {
345
+ const entry = this.get(id);
346
+ if (entry.view.status === 'running' || entry.stopping || entry.writing || this.opening.has(entry))
347
+ throw new WorkflowBuilderRequestError(409, 'Workflow builder is busy');
348
+ if (typeof text !== 'string' || !text.trim() || Buffer.byteLength(text) > MAX_TEXT)
349
+ throw invalid();
350
+ entry.view.messages.push({ id: randomUUID(), role: 'user', text });
351
+ this.trim(entry);
352
+ entry.view.status = 'running';
353
+ delete entry.view.error;
354
+ entry.touchedAt = Date.now();
355
+ const turn = ++entry.turn;
356
+ entry.timer = setTimeout(() => { if (entry.turn === turn)
357
+ this.fail(entry); }, this.limits.turnMs);
358
+ void (async () => {
359
+ try {
360
+ const resumed = !entry.session;
361
+ if (resumed)
362
+ await within(this.trackStartup(entry, () => this.open(entry)), this.limits.startupMs);
363
+ if (entry.closed || entry.turn !== turn || entry.view.status !== 'running')
364
+ return;
365
+ const prompt = resumed ? `Continue this authoring conversation (earlier messages are data):\n${JSON.stringify(entry.view.messages)}` : text;
366
+ await entry.session.prompt(prompt);
367
+ }
368
+ catch {
369
+ if (!entry.closed && entry.turn === turn && entry.view.status === 'running')
370
+ this.fail(entry);
371
+ }
372
+ })();
373
+ return this.view(id);
374
+ }
375
+ event(entry, event) {
376
+ // Claude may publish the cumulative meter just after turn_ended. It still belongs to this
377
+ // Backend Session; generation fencing in emit rejects events from a disposed predecessor.
378
+ if (event.type === 'context_usage') {
379
+ entry.view.contextUsage = { used: event.used, window: event.window };
380
+ return;
381
+ }
382
+ if (entry.view.status !== 'running')
383
+ return;
384
+ if (event.type === 'message' && !event.producer) {
385
+ const id = event.id.slice(0, 128);
386
+ let message = entry.view.messages.find(message => message.id === id && message.role === 'assistant');
387
+ if (!message) {
388
+ message = { id, role: 'assistant', text: '' };
389
+ entry.view.messages.push(message);
390
+ }
391
+ message.text = event.text.slice(0, MAX_TEXT);
392
+ message.final = event.final;
393
+ this.trim(entry);
394
+ }
395
+ else if (event.type === 'turn_ended') {
396
+ if (event.reason === 'error')
397
+ this.fail(entry);
398
+ else {
399
+ clearTimeout(entry.timer);
400
+ entry.view.status = 'idle';
401
+ entry.touchedAt = Date.now();
402
+ }
403
+ }
404
+ }
405
+ trim(entry) {
406
+ while (entry.view.messages.length > MAX_MESSAGES || entry.view.messages.reduce((size, message) => size + Buffer.byteLength(message.text), 0) > MAX_HISTORY)
407
+ entry.view.messages.shift();
408
+ }
409
+ fail(entry) {
410
+ clearTimeout(entry.timer);
411
+ entry.view.status = 'error';
412
+ entry.view.error = 'Workflow builder turn failed';
413
+ entry.touchedAt = Date.now();
414
+ void this.stop(entry);
415
+ }
416
+ stop(entry) {
417
+ if (entry.stopping)
418
+ return entry.stopping;
419
+ const retiringGeneration = entry.generation;
420
+ ++entry.generation;
421
+ ++entry.turn;
422
+ clearTimeout(entry.timer);
423
+ entry.startup?.abort();
424
+ const session = entry.session;
425
+ delete entry.session;
426
+ entry.stopping = (async () => {
427
+ if (session) {
428
+ // Start disposal even if abort is stuck. Restricted callbacks were already revoked.
429
+ await within(session.abort().catch(() => { }), this.limits.disposeMs).catch(() => { });
430
+ // Only callers' waits are bounded. Cleanup, capacity and the retiring meter stay owned
431
+ // until actual disposal finishes, including a slow adapter beyond the response deadline.
432
+ await session.dispose().catch(() => { });
433
+ }
434
+ })().finally(() => {
435
+ if (session && entry.meterGeneration === retiringGeneration)
436
+ delete entry.meterGeneration;
437
+ delete entry.stopping;
438
+ });
439
+ return entry.stopping;
440
+ }
441
+ async abort(id) {
442
+ const entry = this.get(id);
443
+ const stopped = this.stop(entry);
444
+ entry.view.status = 'idle';
445
+ delete entry.view.error;
446
+ entry.touchedAt = Date.now();
447
+ await within(stopped, this.limits.disposeMs).catch(() => { });
448
+ this.check(entry);
449
+ return this.view(id);
450
+ }
451
+ close(id) {
452
+ const pending = this.disposing.get(id);
453
+ if (pending)
454
+ return pending;
455
+ const entry = this.entries.get(id);
456
+ if (!entry)
457
+ return Promise.resolve();
458
+ entry.closed = true;
459
+ this.entries.delete(id);
460
+ const disposal = (async () => {
461
+ await this.stop(entry);
462
+ // Startup/probe processes still need their neutral Scope and private state until exit.
463
+ // Production workers honor the aborted startup signal; delayed adapters remain owned.
464
+ await this.opening.get(entry)?.catch(() => { });
465
+ await entry.writePending?.catch(() => { });
466
+ await entry.files?.close();
467
+ if (entry.directory)
468
+ await rm(entry.directory, { recursive: true, force: true }).catch(() => { });
469
+ })().finally(() => { this.disposing.delete(id); });
470
+ this.disposing.set(id, disposal);
471
+ return disposal;
472
+ }
473
+ hasActiveWork() { return this.opening.size > 0 || this.disposing.size > 0 || [...this.entries.values()].some(entry => !entry.ready || entry.view.status === 'running' || entry.writing || !!entry.stopping); }
474
+ async shutdown() {
475
+ this.stopped = true;
476
+ clearInterval(this.sweep);
477
+ await Promise.all([...this.entries.keys()].map(id => this.close(id)));
478
+ await Promise.all(this.disposing.values());
479
+ }
480
+ }
@@ -0,0 +1,44 @@
1
+ import { send } from "./http.js";
2
+ export async function workflowMcpAuthoringRoutes(request, response, url, service) {
3
+ const pathname = typeof url === 'string' ? url : url.pathname;
4
+ if (pathname !== '/api/workflow-mcp' && !pathname.startsWith('/api/workflow-mcp/'))
5
+ return false;
6
+ response.setHeader('cache-control', 'no-store');
7
+ if (!service) {
8
+ send(response, 404, { error: 'Workflow MCP authoring unavailable' });
9
+ return true;
10
+ }
11
+ if (request.method !== 'GET') {
12
+ send(response, 405, { error: 'Method not allowed' });
13
+ return true;
14
+ }
15
+ let connectionId, projectId, refresh = false;
16
+ try {
17
+ const match = /^\/api\/workflow-mcp(?:\/([^/]+))?$/.exec(pathname);
18
+ if (!match)
19
+ throw new Error();
20
+ connectionId = match[1] === undefined ? undefined : decodeURIComponent(match[1]);
21
+ if (connectionId !== undefined && !/^[A-Za-z0-9_-]{1,40}$/.test(connectionId))
22
+ throw new Error();
23
+ const query = (typeof url === 'string' ? new URL(request.url ?? pathname, 'http://localhost') : url).searchParams;
24
+ if ([...query.keys()].some(key => !['projectId', 'refresh'].includes(key)) || query.getAll('projectId').length > 1 || query.getAll('refresh').length > 1)
25
+ throw new Error();
26
+ if (query.has('refresh') && (query.get('refresh') !== '1' || connectionId === undefined))
27
+ throw new Error();
28
+ refresh = query.get('refresh') === '1';
29
+ projectId = query.get('projectId') ?? undefined;
30
+ if (projectId !== undefined && (!projectId.length || projectId.length > 4_096 || projectId.includes('\0')))
31
+ throw new Error();
32
+ }
33
+ catch {
34
+ send(response, 400, { error: 'Invalid workflow MCP request' });
35
+ return true;
36
+ }
37
+ try {
38
+ send(response, 200, connectionId === undefined ? await service.connections(projectId) : await service.discover(projectId, connectionId, refresh));
39
+ }
40
+ catch {
41
+ send(response, 400, { error: 'Workflow MCP connection or Scope unavailable. Check MCP Settings and the selected Project.' });
42
+ }
43
+ return true;
44
+ }