@nathanstephenson/flow 0.1.9 → 0.1.10-beta.2

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 (53) hide show
  1. package/README.md +9 -0
  2. package/build/backend-worker-chunks/chunk-LO7O6NAM.mjs +133 -0
  3. package/build/backend-worker-chunks/{claude-GTW5KHY5.mjs → claude-COCNALN2.mjs} +76 -8
  4. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-HJKTV2TH.mjs} +84 -6
  5. package/build/backend-worker.mjs +16 -5
  6. package/dist/backend/claude/index.js +54 -7
  7. package/dist/backend/claude/session-tools.js +14 -0
  8. package/dist/backend/fake/index.js +16 -1
  9. package/dist/backend/pi/agent-permissions.js +1 -1
  10. package/dist/backend/pi/index.js +41 -4
  11. package/dist/backend/pi/session-tools.js +21 -0
  12. package/dist/backend/pi/state.js +16 -1
  13. package/dist/backend/session-tools.js +27 -0
  14. package/dist/backend/worker/claude-state.js +22 -0
  15. package/dist/backend/worker/entry.js +14 -2
  16. package/dist/backend/worker/index.js +34 -6
  17. package/dist/backend/worker/protocol.js +1 -1
  18. package/dist/backend/workflow-tools.js +9 -6
  19. package/dist/build-id +1 -1
  20. package/dist/cli/bootstrap.js +1 -1
  21. package/dist/client/reduce.js +20 -0
  22. package/dist/daemon/host.js +218 -12
  23. package/dist/daemon/runtime.js +8 -0
  24. package/dist/daemon/session-tool-views.js +22 -0
  25. package/dist/daemon/workflow-builder-guidance.js +1 -1
  26. package/dist/daemon/workflow-builder.js +36 -11
  27. package/dist/daemon/workflow-execution-routes.js +14 -5
  28. package/dist/daemon/workflow-executions.js +214 -79
  29. package/dist/daemon/workflow-routes.js +39 -0
  30. package/dist/protocol/events.js +2 -0
  31. package/dist/workflows/calls.js +50 -0
  32. package/dist/workflows/graph.js +78 -4
  33. package/dist/workflows/invocations.js +20 -0
  34. package/dist/workflows/records.js +142 -8
  35. package/dist/workflows/recovery.js +87 -2
  36. package/dist/workflows/scheduler.js +348 -80
  37. package/dist/workflows/schema.js +2 -0
  38. package/package.json +1 -1
  39. package/web/dist/assets/index-CLdr6AA0.js +40 -0
  40. package/web/dist/assets/index-DHAcGIoF.css +2 -0
  41. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-sebWClE0.js} +1 -1
  42. package/web/dist/assets/settings-workflows-BvArjkes.js +23 -0
  43. package/web/dist/assets/workflow-editors-Tztq_Opa.js +139 -0
  44. package/web/dist/assets/workflows-CdDynCfW.js +7 -0
  45. package/web/dist/assets/workflows-pane-DaqHEeXu.js +1 -0
  46. package/web/dist/index.html +3 -3
  47. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  48. package/web/dist/assets/index-DRfeO6GJ.js +0 -40
  49. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  50. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  51. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  52. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  53. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
@@ -4,6 +4,9 @@ import { resolveMapping, validateDefinition } from "./graph.js";
4
4
  import { declaredOutputSchema, parseValue, valueAt } from "./schema.js";
5
5
  import { validateMcpOutput } from "./mcp.js";
6
6
  import { WorkflowStore } from "./store.js";
7
+ import { recoverySteps, savedDefinitionRevision, validateCompatibleDefinition } from "./recovery.js";
8
+ import { resolveWorkflowCalls } from "./calls.js";
9
+ import { invocationCheckpoint, invocationExecution } from "./invocations.js";
7
10
  export class WorkflowStepError extends Error {
8
11
  partialOutput;
9
12
  constructor(message, partialOutput) { super(message); this.partialOutput = partialOutput; }
@@ -16,28 +19,20 @@ export class WorkflowScheduler {
16
19
  slots = new Map();
17
20
  store;
18
21
  executors;
19
- constructor(store, executors) {
22
+ onResume;
23
+ constructor(store, executors, onResume) {
20
24
  this.store = store;
21
25
  this.executors = executors;
26
+ this.onResume = onResume;
22
27
  for (const sessionId of store.listSessionIds()) {
23
28
  for (const record of store.listExecutions(sessionId)) {
24
29
  if (!occupied(record))
25
30
  continue;
26
31
  if (this.slots.has(sessionId))
27
32
  throw new Error('Multiple workflow executions occupy one Agent Session');
28
- if (record.status === 'running') {
29
- for (const step of Object.values(record.steps)) {
30
- if (step.status !== 'running')
31
- continue;
32
- step.status = 'interrupted';
33
- const attempt = step.attempts.at(-1);
34
- attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
35
- attempt.finishedAt = Date.now();
36
- }
37
- record.status = 'recovery-required';
38
- store.saveExecution(record);
39
- }
40
- this.install(record);
33
+ const active = this.install(record);
34
+ this.reconcile(active);
35
+ this.persist(active);
41
36
  }
42
37
  }
43
38
  }
@@ -50,28 +45,37 @@ export class WorkflowScheduler {
50
45
  }
51
46
  forgetSession(sessionId) {
52
47
  const executions = [...this.active.values()].filter(active => active.record.sessionId === sessionId);
53
- if (executions.some(active => active.running.size || active.record.status === 'running'))
48
+ if (executions.some(active => this.hasWork(active) || active.record.status === 'running'))
54
49
  throw new Error('Workflow work must stop before forgetting an Agent Session');
55
50
  for (const active of executions)
56
51
  this.active.delete(active.record.id);
57
52
  this.slots.delete(sessionId);
58
53
  }
59
- start(definition, session, input, testStepId, launchId, namingEligible = false) {
54
+ start(definition, session, input, testStepId, launchId, namingEligible = false, capturedDefinitions) {
60
55
  if (this.occupied(session.sessionId))
61
56
  throw new Error('Agent Session workflow slot is occupied');
62
57
  const graph = validateDefinition(definition);
63
58
  if (graph.definition.backend !== session.backend)
64
59
  throw new Error('Backend Adapter mismatch');
65
- if (graph.definition.projectId && graph.definition.projectId !== session.projectId)
60
+ if (graph.definition.projectId && !(session.matchesProject?.(graph.definition.projectId) ?? graph.definition.projectId === session.projectId))
66
61
  throw new Error('Workflow is restricted to another Project');
67
62
  const testStep = testStepId === undefined ? undefined : graph.order.find(step => step.id === testStepId);
68
63
  if (testStepId !== undefined && !testStep)
69
64
  throw new Error('Unknown test step');
70
- this.check(testStep ? [testStep] : graph.order, session);
65
+ const retainedDefinitions = resolveWorkflowCalls(graph.definition, id => {
66
+ if (!capturedDefinitions)
67
+ return this.store.getDefinition(id);
68
+ const retained = capturedDefinitions[id];
69
+ if (!retained)
70
+ throw new Error('Missing captured Workflow Definition');
71
+ return retained;
72
+ }, testStepId);
73
+ this.check(testStep ? [testStep] : graph.order, session, retainedDefinitions);
71
74
  const parsed = parseValue(testStep ? graph.inputSchemas.get(testStep.id) : graph.definition.inputSchema, input);
72
75
  const record = {
73
76
  version: 1, id: randomUUID(), sessionId: session.sessionId, scope: session.scope,
74
77
  definition: graph.definition, input: parsed, status: 'running', startedAt: Date.now(),
78
+ ...(graph.order.some(step => step.kind === 'workflow') ? { retainedDefinitions, invocations: {} } : {}),
75
79
  ...(launchId ? { launchId } : {}),
76
80
  ...(namingEligible && testStepId === undefined ? { naming: 'pending' } : {}),
77
81
  steps: Object.fromEntries(graph.order.map(step => [step.id, { status: testStep && step.id !== testStep.id ? 'skipped' : 'pending', attempts: [] }])),
@@ -105,25 +109,20 @@ export class WorkflowScheduler {
105
109
  const active = this.require(sessionId, executionId);
106
110
  if (active.persistenceError)
107
111
  return Promise.reject(active.persistenceError);
108
- if (active.record.status !== 'running' && !active.running.size)
112
+ if (active.record.status !== 'running' && !this.hasWork(active))
109
113
  return Promise.resolve(structuredClone(active.record));
110
114
  return new Promise((resolve, reject) => active.waiters.push({ resolve, reject }));
111
115
  }
116
+ hasPendingDeadline(sessionId, executionId) {
117
+ const pending = (active) => !active.stopped && [...active.calls.values()].some(call => call.timer !== undefined || pending(call.child));
118
+ const active = this.active.get(executionId);
119
+ return active?.record.sessionId === sessionId && pending(active);
120
+ }
112
121
  async cancel(sessionId, executionId) {
113
122
  const active = this.require(sessionId, executionId);
114
123
  if (!occupied(active.record))
115
124
  return structuredClone(active.record);
116
- active.stopped = true;
117
- active.record.status = 'cancelled';
118
- for (const step of Object.values(active.record.steps))
119
- if (['pending', 'blocked', 'running', 'interrupted'].includes(step.status))
120
- step.status = 'cancelled';
121
- this.persist(active);
122
- for (const running of active.running.values())
123
- running.controller.abort();
124
- await Promise.all([...active.running.values()].map(running => running.done));
125
- active.record.finishedAt = Date.now();
126
- this.persist(active);
125
+ await this.stopTree(active, 'cancelled');
127
126
  this.settle(active);
128
127
  return structuredClone(active.record);
129
128
  }
@@ -131,31 +130,32 @@ export class WorkflowScheduler {
131
130
  const active = this.require(sessionId, executionId);
132
131
  if (!occupied(active.record))
133
132
  return structuredClone(active.record);
134
- active.stopped = true;
135
- active.record.status = 'recovery-required';
136
- for (const step of Object.values(active.record.steps)) {
137
- if (step.status !== 'running')
138
- continue;
139
- step.status = 'interrupted';
140
- const attempt = step.attempts.at(-1);
141
- attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
142
- attempt.finishedAt = Date.now();
143
- }
144
- this.persist(active);
145
- for (const running of active.running.values())
146
- running.controller.abort();
147
- await Promise.all([...active.running.values()].map(running => running.done));
133
+ await this.stopTree(active, 'interrupted');
148
134
  this.settle(active);
149
135
  return structuredClone(active.record);
150
136
  }
151
- recover(session, executionId, action) {
152
- const active = this.require(session.sessionId, executionId);
137
+ /** replacementDefinition is resolved from saved storage by the host, never from request JSON. */
138
+ recover(session, executionId, action, replacementDefinition) {
139
+ const root = this.require(session.sessionId, executionId);
140
+ const active = action.invocationId ? this.findInvocation(root, action.invocationId) : root;
153
141
  const record = active.record;
154
- if (record.status !== 'recovery-required' || active.running.size)
142
+ if (record.status !== 'recovery-required' || this.hasWork(active))
155
143
  throw new Error('Execution is not ready for recovery');
156
144
  if (record.definition.backend !== session.backend || record.scope !== session.scope)
157
145
  throw new Error('Recovery requires the original Scope and Backend Adapter');
158
- this.check(active.graph.order.filter(step => (!record.testStepId || step.id === record.testStepId) && record.steps[step.id].status !== 'completed' && !(action.kind === 'supply' && step.id === action.stepId)), session);
146
+ let graph = active.graph;
147
+ if (action.kind === 'retry-updated') {
148
+ if (!replacementDefinition)
149
+ throw new Error('Updated recovery requires a saved Workflow Definition');
150
+ if (savedDefinitionRevision(replacementDefinition) !== action.definitionRevision)
151
+ throw new Error('Saved Workflow Definition revision changed');
152
+ graph = validateCompatibleDefinition(record.definition, replacementDefinition, action.stepId);
153
+ }
154
+ else if (replacementDefinition !== undefined)
155
+ throw new Error('Replacement definition requires retry-updated');
156
+ // Check the corrected configuration, not the obsolete one. No checkpoint/graph mutation
157
+ // happens until compatibility, authority, eligibility and all runtime checks pass.
158
+ this.check(recoverySteps(root.record, action, replacementDefinition), session, root.record.retainedDefinitions);
159
159
  const limits = Object.entries(record.loops ?? {}).filter(([, loop]) => loop.phase === 'limit');
160
160
  if (action.kind === 'continue' && limits.length)
161
161
  throw new WorkflowLoopConflict('Loop limit requires an extra try or cancellation');
@@ -169,14 +169,17 @@ export class WorkflowScheduler {
169
169
  loop.phase = 'active';
170
170
  }
171
171
  else if (action.kind !== 'continue') {
172
- const step = active.graph.order.find(step => step.id === action.stepId);
172
+ const step = graph.order.find(step => step.id === action.stepId);
173
173
  const state = record.steps[action.stepId];
174
174
  if (!step || !state || !['interrupted', 'failed', 'timed-out'].includes(state.status))
175
175
  throw new Error('Step does not require recovery');
176
- if (state.status !== 'interrupted' && !record.testStepId && !state.recovery && active.graph.outgoing.get(step.id).some(edge => edge.outcome === state.outcome))
176
+ if (state.status !== 'interrupted' && !record.testStepId && !state.recovery && graph.outgoing.get(step.id).some(edge => edge.outcome === state.outcome))
177
177
  throw new Error('Recover the failed handling step, not the handled failure');
178
178
  if (action.kind === 'supply') {
179
179
  const output = this.validateOutput(active, step, action.output);
180
+ this.releaseCancelledCall(active, step.id);
181
+ if (active.calls.has(step.id))
182
+ throw new Error('Cancel the owned call subtree before replacing its output');
180
183
  const attempt = { number: state.attempts.length + 1, action: 'supply', startedAt: Date.now(), finishedAt: Date.now(), input: state.attempts.at(-1).input, output, ...(state.attempts.at(-1).loops ? { loops: structuredClone(state.attempts.at(-1).loops) } : {}) };
181
184
  state.attempts.push(attempt);
182
185
  state.output = output;
@@ -184,7 +187,14 @@ export class WorkflowScheduler {
184
187
  state.outcome = step.kind === 'branch' ? output ? 'true' : 'false' : 'success';
185
188
  }
186
189
  else {
187
- this.check([step], session);
190
+ this.check([step], session, root.record.retainedDefinitions);
191
+ this.releaseCancelledCall(active, step.id);
192
+ if (action.kind === 'retry-updated') {
193
+ const previousStep = record.definition.steps.find(previous => previous.id === step.id);
194
+ (record.definitionUpdates ??= []).push({ stepId: step.id, previousStep: structuredClone(previousStep), nextStep: structuredClone(step), appliedAt: Date.now(), attempt: state.attempts.length + 1 });
195
+ record.definition = graph.definition;
196
+ active.graph = graph;
197
+ }
188
198
  state.status = 'pending';
189
199
  delete state.outcome;
190
200
  }
@@ -213,14 +223,37 @@ export class WorkflowScheduler {
213
223
  delete record.finishedAt;
214
224
  active.stopped = false;
215
225
  delete active.persistenceError;
226
+ for (let parent = active.parent; parent; parent = parent.parent) {
227
+ parent.stopped = false;
228
+ parent.record.status = 'running';
229
+ delete parent.record.finishedAt;
230
+ }
216
231
  this.persist(active);
232
+ delete root.persistenceError;
233
+ this.resumeCalls(active);
234
+ for (let parent = active.parent; parent; parent = parent.parent)
235
+ this.resumeCalls(parent);
217
236
  this.pump(active);
218
- return structuredClone(record);
237
+ return structuredClone(root.record);
219
238
  }
220
- check(steps, session) {
239
+ check(steps, session, manifest, checked = new Set()) {
221
240
  for (const step of steps) {
222
241
  if (step.kind === 'branch' || step.kind === 'join')
223
242
  continue;
243
+ if (step.kind === 'workflow') {
244
+ const target = manifest?.[step.workflowId];
245
+ if (!target)
246
+ throw new Error('Missing retained called Workflow Definition');
247
+ if (target.backend !== session.backend)
248
+ throw new Error('Backend Adapter mismatch');
249
+ if (target.projectId && !(session.matchesProject?.(target.projectId) ?? target.projectId === session.projectId))
250
+ throw new Error('Workflow is restricted to another Project');
251
+ if (!checked.has(target.id)) {
252
+ checked.add(target.id);
253
+ this.check(target.steps, session, manifest, checked);
254
+ }
255
+ continue;
256
+ }
224
257
  const executor = this.executors[step.kind];
225
258
  if (!executor)
226
259
  throw new Error(`Executor is unavailable: ${step.kind}`);
@@ -228,11 +261,229 @@ export class WorkflowScheduler {
228
261
  }
229
262
  }
230
263
  install(record) {
231
- const active = { record, graph: validateDefinition(record.definition), running: new Map(), waiters: [], stopped: record.status !== 'running' };
264
+ const active = { record, graph: validateDefinition(record.definition), running: new Map(), calls: new Map(), waiters: [], stopped: record.status !== 'running' };
232
265
  this.active.set(record.id, active);
233
266
  this.slots.set(record.sessionId, record.id);
267
+ const installed = new Map();
268
+ const restore = (id) => {
269
+ const cached = installed.get(id);
270
+ if (cached)
271
+ return cached;
272
+ const invocation = record.invocations[id];
273
+ const parent = invocation.parentInvocationId ? restore(invocation.parentInvocationId) : active;
274
+ const local = invocationExecution(record, id);
275
+ const step = parent.graph.order.find(step => step.id === invocation.callStepId);
276
+ const child = { record: local, graph: validateDefinition(local.definition), parent, root: active, callStepId: invocation.callStepId, callAttempt: invocation.callAttempt,
277
+ inheritedAsk: parent.inheritedAsk || parent.record.definition.permission === 'ask' || step.permission === 'ask', running: new Map(), calls: new Map(), waiters: [], stopped: local.status !== 'running' };
278
+ installed.set(id, child);
279
+ const state = parent.record.steps[invocation.callStepId];
280
+ if (state.attempts.length === invocation.callAttempt && state.status === 'running')
281
+ parent.calls.set(invocation.callStepId, { child });
282
+ return child;
283
+ };
284
+ for (const id of Object.keys(record.invocations ?? {}))
285
+ restore(id);
234
286
  return active;
235
287
  }
288
+ hasWork(active) {
289
+ return active.running.size > 0 || [...active.calls.values()].some(call => !!call.stopping || this.hasWork(call.child));
290
+ }
291
+ findInvocation(active, id) {
292
+ const pending = [active];
293
+ while (pending.length) {
294
+ const current = pending.pop();
295
+ if (current !== active && current.record.id === id)
296
+ return current;
297
+ pending.push(...[...current.calls.values()].map(call => call.child));
298
+ }
299
+ throw new Error('Invocation does not require recovery');
300
+ }
301
+ syncInvocations(active) {
302
+ const root = active.root ?? active;
303
+ for (const call of active.calls.values()) {
304
+ const child = call.child;
305
+ this.syncInvocations(child);
306
+ (root.record.invocations ??= {})[child.record.id] = invocationCheckpoint(child.record, {
307
+ ...(active.parent ? { parentInvocationId: active.record.id } : {}), callStepId: child.callStepId, callAttempt: child.callAttempt, definitionId: child.record.definition.id,
308
+ });
309
+ }
310
+ }
311
+ reconcile(active) {
312
+ for (const call of active.calls.values())
313
+ this.reconcile(call.child);
314
+ if (!occupied(active.record))
315
+ return;
316
+ for (const [id, state] of Object.entries(active.record.steps)) {
317
+ if (state.status !== 'running' || active.calls.has(id))
318
+ continue;
319
+ state.status = 'interrupted';
320
+ const attempt = state.attempts.at(-1);
321
+ attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
322
+ attempt.finishedAt ??= Date.now();
323
+ }
324
+ active.record.status = 'recovery-required';
325
+ active.stopped = true;
326
+ }
327
+ releaseCancelledCall(active, stepId) {
328
+ const call = active.calls.get(stepId);
329
+ if (call?.child.record.status !== 'cancelled')
330
+ return;
331
+ clearTimeout(call.timer);
332
+ this.syncInvocations(active);
333
+ active.calls.delete(stepId);
334
+ }
335
+ failStorage(active) {
336
+ active.stopped = true;
337
+ if (!active.parent || occupied(active.record))
338
+ active.record.status = 'recovery-required';
339
+ for (const call of active.calls.values()) {
340
+ clearTimeout(call.timer);
341
+ this.failStorage(call.child);
342
+ }
343
+ for (const [id, state] of Object.entries(active.record.steps)) {
344
+ if (state.status !== 'running' || active.calls.has(id))
345
+ continue;
346
+ state.status = 'interrupted';
347
+ const attempt = state.attempts.at(-1);
348
+ attempt.error = { kind: 'interrupted', message: 'Workflow storage failed; effects may already have occurred' };
349
+ attempt.finishedAt ??= Date.now();
350
+ }
351
+ for (const running of active.running.values())
352
+ running.controller.abort();
353
+ }
354
+ async stopTree(active, reason) {
355
+ const tree = [active];
356
+ for (const current of tree)
357
+ tree.push(...[...current.calls.values()].map(call => call.child));
358
+ for (const current of tree) {
359
+ current.stopped = true;
360
+ if (!occupied(current.record))
361
+ continue;
362
+ current.record.status = reason === 'cancelled' ? 'cancelled' : 'recovery-required';
363
+ for (const [id, state] of Object.entries(current.record.steps)) {
364
+ if (reason === 'cancelled' && ['pending', 'blocked', 'running', 'interrupted'].includes(state.status))
365
+ state.status = 'cancelled';
366
+ else if (reason === 'interrupted' && state.status === 'running' && !current.calls.has(id)) {
367
+ state.status = 'interrupted';
368
+ const attempt = state.attempts.at(-1);
369
+ attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
370
+ attempt.finishedAt ??= Date.now();
371
+ }
372
+ }
373
+ }
374
+ const work = tree.flatMap(current => [...current.running.values()]);
375
+ try {
376
+ this.persist(active);
377
+ }
378
+ finally {
379
+ for (const current of tree)
380
+ for (const call of current.calls.values())
381
+ clearTimeout(call.timer);
382
+ for (const running of work)
383
+ running.controller.abort();
384
+ await Promise.all(work.map(running => running.done));
385
+ for (const current of tree)
386
+ if (reason === 'cancelled' && current.record.status === 'cancelled') {
387
+ current.record.finishedAt ??= Date.now();
388
+ for (const state of Object.values(current.record.steps))
389
+ if (state.status === 'cancelled') {
390
+ const attempt = state.attempts.at(-1);
391
+ if (attempt)
392
+ attempt.finishedAt ??= Date.now();
393
+ }
394
+ }
395
+ this.persist(active);
396
+ }
397
+ }
398
+ startCall(active, step, attempt) {
399
+ const root = active.root ?? active;
400
+ const definition = root.record.retainedDefinitions?.[step.workflowId];
401
+ if (!definition)
402
+ throw new Error('Missing retained called Workflow Definition');
403
+ const graph = validateDefinition(definition);
404
+ const record = {
405
+ version: 1, id: randomUUID(), sessionId: root.record.sessionId, scope: root.record.scope, definition: graph.definition,
406
+ input: structuredClone(attempt.input), status: 'running', startedAt: Date.now(),
407
+ steps: Object.fromEntries(graph.order.map(step => [step.id, { status: 'pending', attempts: [] }])),
408
+ loops: Object.fromEntries(graph.loops.map(loop => [loop.headerId, { activation: 0, try: 0, phase: 'inactive', grants: [] }])),
409
+ };
410
+ const child = { record, graph, parent: active, root, callStepId: step.id, callAttempt: attempt.number,
411
+ inheritedAsk: active.inheritedAsk || active.record.definition.permission === 'ask' || step.permission === 'ask',
412
+ running: new Map(), calls: new Map(), waiters: [], stopped: false };
413
+ active.calls.set(step.id, { child });
414
+ if (step.timeoutMs !== undefined)
415
+ attempt.deadlineAt = attempt.startedAt + step.timeoutMs;
416
+ this.persist(active);
417
+ this.armCall(active, step.id);
418
+ if (attempt.deadlineAt === undefined || attempt.deadlineAt > Date.now())
419
+ this.pump(child);
420
+ }
421
+ armCall(active, stepId) {
422
+ const call = active.calls.get(stepId);
423
+ clearTimeout(call.timer);
424
+ const deadline = active.record.steps[stepId].attempts.at(-1).deadlineAt;
425
+ if (deadline === undefined || call.stopping)
426
+ return;
427
+ call.timer = setTimeout(() => {
428
+ call.stopping = this.stopTree(call.child, 'cancelled').then(() => {
429
+ if (active.stopped)
430
+ return;
431
+ const state = active.record.steps[stepId];
432
+ const attempt = state.attempts.at(-1);
433
+ state.status = 'timed-out';
434
+ state.outcome = 'timeout';
435
+ attempt.error = { kind: 'timeout', message: 'Step timed out' };
436
+ attempt.finishedAt = Date.now();
437
+ this.persist(active);
438
+ active.calls.delete(stepId);
439
+ const root = active.root ?? active;
440
+ const resumed = root.record.status === 'recovery-required';
441
+ for (let current = active; current; current = current.parent) {
442
+ current.record.status = 'running';
443
+ delete current.record.finishedAt;
444
+ }
445
+ if (resumed)
446
+ this.onResume?.(structuredClone(root.record));
447
+ this.pump(active);
448
+ }).catch(error => { (active.root ?? active).persistenceError = error; this.failStorage(active.root ?? active); this.settle(active.root ?? active); }).finally(() => { delete call.stopping; });
449
+ }, Math.max(0, deadline - Date.now()));
450
+ }
451
+ resumeCalls(active) {
452
+ for (const [stepId, call] of active.calls) {
453
+ this.armCall(active, stepId);
454
+ if (call.child.record.status === 'completed' || call.child.record.status === 'completed-with-recovery')
455
+ this.completeCall(call.child);
456
+ }
457
+ }
458
+ completeCall(child) {
459
+ const parent = child.parent;
460
+ const stepId = child.callStepId;
461
+ const call = parent.calls.get(stepId);
462
+ if (!call || call.child !== child || call.stopping || parent.stopped)
463
+ return;
464
+ if (child.record.status === 'completed' || child.record.status === 'completed-with-recovery') {
465
+ clearTimeout(call.timer);
466
+ const state = parent.record.steps[stepId];
467
+ const attempt = state.attempts.at(-1);
468
+ const step = parent.graph.order.find(step => step.id === stepId);
469
+ try {
470
+ const output = this.validateOutput(parent, step, child.record.result);
471
+ state.status = 'completed';
472
+ state.outcome = 'success';
473
+ state.output = output;
474
+ attempt.output = output;
475
+ }
476
+ catch (error) {
477
+ state.status = 'failed';
478
+ state.outcome = 'failure';
479
+ attempt.error = { kind: 'failure', message: error instanceof Error ? error.message : String(error) };
480
+ }
481
+ attempt.finishedAt = Date.now();
482
+ this.persist(child);
483
+ parent.calls.delete(stepId);
484
+ }
485
+ this.pump(parent);
486
+ }
236
487
  require(sessionId, executionId) {
237
488
  const active = this.active.get(executionId);
238
489
  if (!active || active.record.sessionId !== sessionId)
@@ -256,8 +507,17 @@ export class WorkflowScheduler {
256
507
  const handled = !state.recovery && active.graph.outgoing.get(edge.from).some(candidate => candidate.outcome === state.outcome);
257
508
  return handled || edge.outcome === 'failure' || edge.outcome === 'timeout' ? 'skipped' : 'blocked';
258
509
  }
510
+ hasExpiredAncestor(active) {
511
+ const now = Date.now();
512
+ for (let child = active; child.parent; child = child.parent) {
513
+ const deadline = child.parent.record.steps[child.callStepId].attempts[child.callAttempt - 1].deadlineAt;
514
+ if (deadline !== undefined && deadline <= now)
515
+ return true;
516
+ }
517
+ return false;
518
+ }
259
519
  pump(active) {
260
- if (active.stopped || active.record.status !== 'running')
520
+ if (active.stopped || active.record.status !== 'running' || this.hasExpiredAncestor(active))
261
521
  return;
262
522
  this.transitionLoops(active);
263
523
  for (const step of active.graph.order) {
@@ -314,23 +574,25 @@ export class WorkflowScheduler {
314
574
  state.attempts.push({ number: state.attempts.length + 1, action: retry ? 'retry' : 'execute', startedAt: Date.now(), input, ...(identities.length ? { loops: identities } : {}) });
315
575
  const done = Promise.resolve().then(() => this.execute(active, step, controller, inputError)).finally(() => {
316
576
  active.running.delete(step.id);
577
+ const root = active.root ?? active;
317
578
  if (active.stopped) {
318
- if (!active.running.size && active.persistenceError)
319
- this.settle(active);
579
+ if (!this.hasWork(root) && root.persistenceError)
580
+ this.settle(root);
320
581
  return;
321
582
  }
322
583
  this.pump(active);
323
584
  }).catch(error => {
324
- active.persistenceError = error;
325
- active.stopped = true;
326
- if (!active.running.size)
327
- this.settle(active);
585
+ const root = active.root ?? active;
586
+ root.persistenceError = error;
587
+ this.failStorage(root);
588
+ if (!this.hasWork(root))
589
+ this.settle(root);
328
590
  });
329
591
  state.status = 'running';
330
592
  active.running.set(step.id, { controller, done });
331
593
  }
332
594
  this.persist(active);
333
- if (active.running.size)
595
+ if (this.hasWork(active))
334
596
  return;
335
597
  if (this.transitionLoops(active)) {
336
598
  this.persist(active);
@@ -338,13 +600,13 @@ export class WorkflowScheduler {
338
600
  return;
339
601
  }
340
602
  const states = Object.entries(active.record.steps);
341
- const unresolved = Object.values(active.record.loops ?? {}).some(loop => loop.phase === 'limit') || states.some(([id, state]) => ['pending', 'interrupted', 'blocked'].includes(state.status) || ((state.status === 'failed' || state.status === 'timed-out') && (active.record.testStepId || state.recovery || !active.graph.outgoing.get(id).some(edge => edge.outcome === state.outcome))));
603
+ const unresolved = active.calls.size > 0 || Object.values(active.record.loops ?? {}).some(loop => loop.phase === 'limit') || states.some(([id, state]) => ['pending', 'interrupted', 'blocked'].includes(state.status) || ((state.status === 'failed' || state.status === 'timed-out') && (active.record.testStepId || state.recovery || !active.graph.outgoing.get(id).some(edge => edge.outcome === state.outcome))));
342
604
  if (unresolved)
343
605
  active.record.status = 'recovery-required';
344
606
  else {
345
607
  const terminals = active.graph.order.filter(step => active.record.steps[step.id].status === 'completed' && (active.record.testStepId || !active.graph.outgoing.get(step.id).some(edge => this.edgeState(active, edge) === 'selected')));
346
608
  active.record.result = terminals.length === 1 ? active.record.steps[terminals[0].id].output : Object.fromEntries(terminals.map(step => [step.name, active.record.steps[step.id].output]));
347
- active.record.status = Object.values(active.record.loops ?? {}).some(loop => loop.grants.length) || states.some(([, state]) => state.attempts.some(attempt => attempt.error || attempt.action !== 'execute')) ? 'completed-with-recovery' : 'completed';
609
+ active.record.status = Object.values(active.record.loops ?? {}).some(loop => loop.grants.length) || Object.values((active.root ?? active).record.invocations ?? {}).some(invocation => invocation.status === 'completed-with-recovery') || states.some(([, state]) => state.attempts.some(attempt => attempt.error || attempt.action !== 'execute')) ? 'completed-with-recovery' : 'completed';
348
610
  active.record.finishedAt = Date.now();
349
611
  }
350
612
  this.persist(active);
@@ -453,6 +715,11 @@ export class WorkflowScheduler {
453
715
  return copy;
454
716
  }
455
717
  settle(active) {
718
+ if (active.parent) {
719
+ if (!active.stopped)
720
+ this.completeCall(active);
721
+ return;
722
+ }
456
723
  if (!occupied(active.record))
457
724
  this.slots.delete(active.record.sessionId);
458
725
  for (const waiter of active.waiters.splice(0)) {
@@ -463,23 +730,14 @@ export class WorkflowScheduler {
463
730
  }
464
731
  }
465
732
  persist(active) {
733
+ const root = active.root ?? active;
466
734
  try {
467
- this.store.saveExecution(active.record);
735
+ this.syncInvocations(root);
736
+ this.store.saveExecution(root.record);
468
737
  }
469
738
  catch (error) {
470
- active.persistenceError = error;
471
- active.stopped = true;
472
- active.record.status = 'recovery-required';
473
- for (const step of Object.values(active.record.steps)) {
474
- if (step.status !== 'running')
475
- continue;
476
- step.status = 'interrupted';
477
- const attempt = step.attempts.at(-1);
478
- attempt.error = { kind: 'interrupted', message: 'Workflow storage failed; effects may already have occurred' };
479
- attempt.finishedAt = Date.now();
480
- }
481
- for (const running of active.running.values())
482
- running.controller.abort();
739
+ root.persistenceError = error;
740
+ this.failStorage(root);
483
741
  throw error;
484
742
  }
485
743
  }
@@ -519,6 +777,8 @@ export class WorkflowScheduler {
519
777
  this.persist(active);
520
778
  return;
521
779
  }
780
+ if (this.hasExpiredAncestor(active))
781
+ return;
522
782
  const attempt = state.attempts.at(-1);
523
783
  let timer;
524
784
  let timedOut = false;
@@ -527,7 +787,14 @@ export class WorkflowScheduler {
527
787
  throw inputError;
528
788
  if (step.inputSchema)
529
789
  attempt.input = parseValue(step.inputSchema, attempt.input);
790
+ if (step.kind === 'workflow') {
791
+ attempt.input = parseValue(step.contract.inputSchema, attempt.input);
792
+ this.startCall(active, step, attempt);
793
+ return;
794
+ }
530
795
  this.persist(active);
796
+ if (this.hasExpiredAncestor(active))
797
+ return;
531
798
  const timeout = step.timeoutMs ?? (step.kind === 'shell' || step.kind === 'typescript' || step.kind === 'mcp' ? 60_000 : undefined);
532
799
  if (timeout !== undefined)
533
800
  timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeout);
@@ -558,7 +825,7 @@ export class WorkflowScheduler {
558
825
  }
559
826
  }
560
827
  else
561
- value = await this.executors[step.kind].execute({ sessionId: active.record.sessionId, scope: active.record.scope, executionId: active.record.id, step: this.guidedStep(active, step, attempt), input: structuredClone(attempt.input), inputSchema: active.graph.inputSchemas.get(step.id), permission: step.permission ?? active.record.definition.permission ?? 'auto-accept', signal: controller.signal });
828
+ value = await this.executors[step.kind].execute({ sessionId: active.record.sessionId, scope: active.record.scope, executionId: (active.root ?? active).record.id, ...(active.parent ? { invocationId: active.record.id } : {}), attempt: attempt.number, step: this.guidedStep(active, step, attempt), input: structuredClone(attempt.input), inputSchema: active.graph.inputSchemas.get(step.id), permission: active.inheritedAsk ? 'ask' : step.permission ?? active.record.definition.permission ?? 'auto-accept', signal: controller.signal });
562
829
  if (active.stopped)
563
830
  return;
564
831
  if (timedOut)
@@ -580,7 +847,8 @@ export class WorkflowScheduler {
580
847
  }
581
848
  finally {
582
849
  clearTimeout(timer);
583
- attempt.finishedAt ??= Date.now();
850
+ if (!active.calls.has(step.id))
851
+ attempt.finishedAt ??= Date.now();
584
852
  this.persist(active);
585
853
  }
586
854
  }
@@ -76,6 +76,8 @@ export const shellOutputSchema = { type: 'object', fields: {
76
76
  stderr: { schema: { type: 'string' }, required: true },
77
77
  } };
78
78
  export function declaredOutputSchema(step) {
79
+ if (step.kind === 'workflow')
80
+ return step.contract.outputSchema;
79
81
  if (step.kind === 'mcp')
80
82
  return { type: 'object', fields: { structuredContent: { required: true, schema: { type: 'json', ...(step.tool.outputSchema === undefined ? {} : { schema: step.tool.outputSchema }) } }, content: { required: true, schema: { type: 'array', items: { type: 'json' } } } } };
81
83
  if (step.kind === 'shell')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathanstephenson/flow",
3
- "version": "0.1.9",
3
+ "version": "0.1.10-beta.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",