@nathanstephenson/flow 0.1.10-beta.1 → 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.
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
- package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-COCNALN2.mjs} +36 -6
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-HJKTV2TH.mjs} +35 -3
- package/build/backend-worker.mjs +7 -3
- package/dist/backend/claude/index.js +35 -5
- package/dist/backend/fake/index.js +16 -1
- package/dist/backend/pi/index.js +33 -2
- package/dist/backend/pi/state.js +16 -1
- package/dist/backend/worker/claude-state.js +22 -0
- package/dist/backend/worker/entry.js +6 -1
- package/dist/backend/worker/index.js +9 -3
- package/dist/backend/worker/protocol.js +1 -1
- package/dist/backend/workflow-tools.js +9 -7
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/client/reduce.js +20 -0
- package/dist/daemon/host.js +138 -5
- package/dist/daemon/runtime.js +8 -0
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder.js +36 -11
- package/dist/daemon/workflow-execution-routes.js +9 -6
- package/dist/daemon/workflow-executions.js +179 -84
- package/dist/daemon/workflow-routes.js +39 -0
- package/dist/protocol/events.js +2 -0
- package/dist/workflows/calls.js +50 -0
- package/dist/workflows/graph.js +78 -4
- package/dist/workflows/invocations.js +20 -0
- package/dist/workflows/records.js +118 -8
- package/dist/workflows/recovery.js +37 -1
- package/dist/workflows/scheduler.js +326 -78
- package/dist/workflows/schema.js +2 -0
- package/package.json +1 -1
- package/web/dist/assets/index-CLdr6AA0.js +40 -0
- package/web/dist/assets/index-DHAcGIoF.css +2 -0
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-sebWClE0.js} +1 -1
- package/web/dist/assets/settings-workflows-BvArjkes.js +23 -0
- package/web/dist/assets/workflow-editors-Tztq_Opa.js +139 -0
- package/web/dist/assets/workflows-CdDynCfW.js +7 -0
- package/web/dist/assets/workflows-pane-DaqHEeXu.js +1 -0
- package/web/dist/index.html +3 -3
- package/web/dist/assets/index-DRfeO6GJ.js +0 -40
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
|
@@ -4,7 +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 { savedDefinitionRevision, validateCompatibleDefinition } from "./recovery.js";
|
|
7
|
+
import { recoverySteps, savedDefinitionRevision, validateCompatibleDefinition } from "./recovery.js";
|
|
8
|
+
import { resolveWorkflowCalls } from "./calls.js";
|
|
9
|
+
import { invocationCheckpoint, invocationExecution } from "./invocations.js";
|
|
8
10
|
export class WorkflowStepError extends Error {
|
|
9
11
|
partialOutput;
|
|
10
12
|
constructor(message, partialOutput) { super(message); this.partialOutput = partialOutput; }
|
|
@@ -17,28 +19,20 @@ export class WorkflowScheduler {
|
|
|
17
19
|
slots = new Map();
|
|
18
20
|
store;
|
|
19
21
|
executors;
|
|
20
|
-
|
|
22
|
+
onResume;
|
|
23
|
+
constructor(store, executors, onResume) {
|
|
21
24
|
this.store = store;
|
|
22
25
|
this.executors = executors;
|
|
26
|
+
this.onResume = onResume;
|
|
23
27
|
for (const sessionId of store.listSessionIds()) {
|
|
24
28
|
for (const record of store.listExecutions(sessionId)) {
|
|
25
29
|
if (!occupied(record))
|
|
26
30
|
continue;
|
|
27
31
|
if (this.slots.has(sessionId))
|
|
28
32
|
throw new Error('Multiple workflow executions occupy one Agent Session');
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
continue;
|
|
33
|
-
step.status = 'interrupted';
|
|
34
|
-
const attempt = step.attempts.at(-1);
|
|
35
|
-
attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
|
|
36
|
-
attempt.finishedAt = Date.now();
|
|
37
|
-
}
|
|
38
|
-
record.status = 'recovery-required';
|
|
39
|
-
store.saveExecution(record);
|
|
40
|
-
}
|
|
41
|
-
this.install(record);
|
|
33
|
+
const active = this.install(record);
|
|
34
|
+
this.reconcile(active);
|
|
35
|
+
this.persist(active);
|
|
42
36
|
}
|
|
43
37
|
}
|
|
44
38
|
}
|
|
@@ -51,28 +45,37 @@ export class WorkflowScheduler {
|
|
|
51
45
|
}
|
|
52
46
|
forgetSession(sessionId) {
|
|
53
47
|
const executions = [...this.active.values()].filter(active => active.record.sessionId === sessionId);
|
|
54
|
-
if (executions.some(active => active
|
|
48
|
+
if (executions.some(active => this.hasWork(active) || active.record.status === 'running'))
|
|
55
49
|
throw new Error('Workflow work must stop before forgetting an Agent Session');
|
|
56
50
|
for (const active of executions)
|
|
57
51
|
this.active.delete(active.record.id);
|
|
58
52
|
this.slots.delete(sessionId);
|
|
59
53
|
}
|
|
60
|
-
start(definition, session, input, testStepId, launchId, namingEligible = false) {
|
|
54
|
+
start(definition, session, input, testStepId, launchId, namingEligible = false, capturedDefinitions) {
|
|
61
55
|
if (this.occupied(session.sessionId))
|
|
62
56
|
throw new Error('Agent Session workflow slot is occupied');
|
|
63
57
|
const graph = validateDefinition(definition);
|
|
64
58
|
if (graph.definition.backend !== session.backend)
|
|
65
59
|
throw new Error('Backend Adapter mismatch');
|
|
66
|
-
if (graph.definition.projectId && graph.definition.projectId
|
|
60
|
+
if (graph.definition.projectId && !(session.matchesProject?.(graph.definition.projectId) ?? graph.definition.projectId === session.projectId))
|
|
67
61
|
throw new Error('Workflow is restricted to another Project');
|
|
68
62
|
const testStep = testStepId === undefined ? undefined : graph.order.find(step => step.id === testStepId);
|
|
69
63
|
if (testStepId !== undefined && !testStep)
|
|
70
64
|
throw new Error('Unknown test step');
|
|
71
|
-
|
|
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);
|
|
72
74
|
const parsed = parseValue(testStep ? graph.inputSchemas.get(testStep.id) : graph.definition.inputSchema, input);
|
|
73
75
|
const record = {
|
|
74
76
|
version: 1, id: randomUUID(), sessionId: session.sessionId, scope: session.scope,
|
|
75
77
|
definition: graph.definition, input: parsed, status: 'running', startedAt: Date.now(),
|
|
78
|
+
...(graph.order.some(step => step.kind === 'workflow') ? { retainedDefinitions, invocations: {} } : {}),
|
|
76
79
|
...(launchId ? { launchId } : {}),
|
|
77
80
|
...(namingEligible && testStepId === undefined ? { naming: 'pending' } : {}),
|
|
78
81
|
steps: Object.fromEntries(graph.order.map(step => [step.id, { status: testStep && step.id !== testStep.id ? 'skipped' : 'pending', attempts: [] }])),
|
|
@@ -106,25 +109,20 @@ export class WorkflowScheduler {
|
|
|
106
109
|
const active = this.require(sessionId, executionId);
|
|
107
110
|
if (active.persistenceError)
|
|
108
111
|
return Promise.reject(active.persistenceError);
|
|
109
|
-
if (active.record.status !== 'running' && !active
|
|
112
|
+
if (active.record.status !== 'running' && !this.hasWork(active))
|
|
110
113
|
return Promise.resolve(structuredClone(active.record));
|
|
111
114
|
return new Promise((resolve, reject) => active.waiters.push({ resolve, reject }));
|
|
112
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
|
+
}
|
|
113
121
|
async cancel(sessionId, executionId) {
|
|
114
122
|
const active = this.require(sessionId, executionId);
|
|
115
123
|
if (!occupied(active.record))
|
|
116
124
|
return structuredClone(active.record);
|
|
117
|
-
active
|
|
118
|
-
active.record.status = 'cancelled';
|
|
119
|
-
for (const step of Object.values(active.record.steps))
|
|
120
|
-
if (['pending', 'blocked', 'running', 'interrupted'].includes(step.status))
|
|
121
|
-
step.status = 'cancelled';
|
|
122
|
-
this.persist(active);
|
|
123
|
-
for (const running of active.running.values())
|
|
124
|
-
running.controller.abort();
|
|
125
|
-
await Promise.all([...active.running.values()].map(running => running.done));
|
|
126
|
-
active.record.finishedAt = Date.now();
|
|
127
|
-
this.persist(active);
|
|
125
|
+
await this.stopTree(active, 'cancelled');
|
|
128
126
|
this.settle(active);
|
|
129
127
|
return structuredClone(active.record);
|
|
130
128
|
}
|
|
@@ -132,28 +130,16 @@ export class WorkflowScheduler {
|
|
|
132
130
|
const active = this.require(sessionId, executionId);
|
|
133
131
|
if (!occupied(active.record))
|
|
134
132
|
return structuredClone(active.record);
|
|
135
|
-
active
|
|
136
|
-
active.record.status = 'recovery-required';
|
|
137
|
-
for (const step of Object.values(active.record.steps)) {
|
|
138
|
-
if (step.status !== 'running')
|
|
139
|
-
continue;
|
|
140
|
-
step.status = 'interrupted';
|
|
141
|
-
const attempt = step.attempts.at(-1);
|
|
142
|
-
attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
|
|
143
|
-
attempt.finishedAt = Date.now();
|
|
144
|
-
}
|
|
145
|
-
this.persist(active);
|
|
146
|
-
for (const running of active.running.values())
|
|
147
|
-
running.controller.abort();
|
|
148
|
-
await Promise.all([...active.running.values()].map(running => running.done));
|
|
133
|
+
await this.stopTree(active, 'interrupted');
|
|
149
134
|
this.settle(active);
|
|
150
135
|
return structuredClone(active.record);
|
|
151
136
|
}
|
|
152
137
|
/** replacementDefinition is resolved from saved storage by the host, never from request JSON. */
|
|
153
138
|
recover(session, executionId, action, replacementDefinition) {
|
|
154
|
-
const
|
|
139
|
+
const root = this.require(session.sessionId, executionId);
|
|
140
|
+
const active = action.invocationId ? this.findInvocation(root, action.invocationId) : root;
|
|
155
141
|
const record = active.record;
|
|
156
|
-
if (record.status !== 'recovery-required' || active
|
|
142
|
+
if (record.status !== 'recovery-required' || this.hasWork(active))
|
|
157
143
|
throw new Error('Execution is not ready for recovery');
|
|
158
144
|
if (record.definition.backend !== session.backend || record.scope !== session.scope)
|
|
159
145
|
throw new Error('Recovery requires the original Scope and Backend Adapter');
|
|
@@ -169,7 +155,7 @@ export class WorkflowScheduler {
|
|
|
169
155
|
throw new Error('Replacement definition requires retry-updated');
|
|
170
156
|
// Check the corrected configuration, not the obsolete one. No checkpoint/graph mutation
|
|
171
157
|
// happens until compatibility, authority, eligibility and all runtime checks pass.
|
|
172
|
-
this.check(
|
|
158
|
+
this.check(recoverySteps(root.record, action, replacementDefinition), session, root.record.retainedDefinitions);
|
|
173
159
|
const limits = Object.entries(record.loops ?? {}).filter(([, loop]) => loop.phase === 'limit');
|
|
174
160
|
if (action.kind === 'continue' && limits.length)
|
|
175
161
|
throw new WorkflowLoopConflict('Loop limit requires an extra try or cancellation');
|
|
@@ -191,6 +177,9 @@ export class WorkflowScheduler {
|
|
|
191
177
|
throw new Error('Recover the failed handling step, not the handled failure');
|
|
192
178
|
if (action.kind === 'supply') {
|
|
193
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');
|
|
194
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) } : {}) };
|
|
195
184
|
state.attempts.push(attempt);
|
|
196
185
|
state.output = output;
|
|
@@ -198,7 +187,8 @@ export class WorkflowScheduler {
|
|
|
198
187
|
state.outcome = step.kind === 'branch' ? output ? 'true' : 'false' : 'success';
|
|
199
188
|
}
|
|
200
189
|
else {
|
|
201
|
-
this.check([step], session);
|
|
190
|
+
this.check([step], session, root.record.retainedDefinitions);
|
|
191
|
+
this.releaseCancelledCall(active, step.id);
|
|
202
192
|
if (action.kind === 'retry-updated') {
|
|
203
193
|
const previousStep = record.definition.steps.find(previous => previous.id === step.id);
|
|
204
194
|
(record.definitionUpdates ??= []).push({ stepId: step.id, previousStep: structuredClone(previousStep), nextStep: structuredClone(step), appliedAt: Date.now(), attempt: state.attempts.length + 1 });
|
|
@@ -233,14 +223,37 @@ export class WorkflowScheduler {
|
|
|
233
223
|
delete record.finishedAt;
|
|
234
224
|
active.stopped = false;
|
|
235
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
|
+
}
|
|
236
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);
|
|
237
236
|
this.pump(active);
|
|
238
|
-
return structuredClone(record);
|
|
237
|
+
return structuredClone(root.record);
|
|
239
238
|
}
|
|
240
|
-
check(steps, session) {
|
|
239
|
+
check(steps, session, manifest, checked = new Set()) {
|
|
241
240
|
for (const step of steps) {
|
|
242
241
|
if (step.kind === 'branch' || step.kind === 'join')
|
|
243
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
|
+
}
|
|
244
257
|
const executor = this.executors[step.kind];
|
|
245
258
|
if (!executor)
|
|
246
259
|
throw new Error(`Executor is unavailable: ${step.kind}`);
|
|
@@ -248,11 +261,229 @@ export class WorkflowScheduler {
|
|
|
248
261
|
}
|
|
249
262
|
}
|
|
250
263
|
install(record) {
|
|
251
|
-
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' };
|
|
252
265
|
this.active.set(record.id, active);
|
|
253
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);
|
|
254
286
|
return active;
|
|
255
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
|
+
}
|
|
256
487
|
require(sessionId, executionId) {
|
|
257
488
|
const active = this.active.get(executionId);
|
|
258
489
|
if (!active || active.record.sessionId !== sessionId)
|
|
@@ -276,8 +507,17 @@ export class WorkflowScheduler {
|
|
|
276
507
|
const handled = !state.recovery && active.graph.outgoing.get(edge.from).some(candidate => candidate.outcome === state.outcome);
|
|
277
508
|
return handled || edge.outcome === 'failure' || edge.outcome === 'timeout' ? 'skipped' : 'blocked';
|
|
278
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
|
+
}
|
|
279
519
|
pump(active) {
|
|
280
|
-
if (active.stopped || active.record.status !== 'running')
|
|
520
|
+
if (active.stopped || active.record.status !== 'running' || this.hasExpiredAncestor(active))
|
|
281
521
|
return;
|
|
282
522
|
this.transitionLoops(active);
|
|
283
523
|
for (const step of active.graph.order) {
|
|
@@ -334,23 +574,25 @@ export class WorkflowScheduler {
|
|
|
334
574
|
state.attempts.push({ number: state.attempts.length + 1, action: retry ? 'retry' : 'execute', startedAt: Date.now(), input, ...(identities.length ? { loops: identities } : {}) });
|
|
335
575
|
const done = Promise.resolve().then(() => this.execute(active, step, controller, inputError)).finally(() => {
|
|
336
576
|
active.running.delete(step.id);
|
|
577
|
+
const root = active.root ?? active;
|
|
337
578
|
if (active.stopped) {
|
|
338
|
-
if (!
|
|
339
|
-
this.settle(
|
|
579
|
+
if (!this.hasWork(root) && root.persistenceError)
|
|
580
|
+
this.settle(root);
|
|
340
581
|
return;
|
|
341
582
|
}
|
|
342
583
|
this.pump(active);
|
|
343
584
|
}).catch(error => {
|
|
344
|
-
active.
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
585
|
+
const root = active.root ?? active;
|
|
586
|
+
root.persistenceError = error;
|
|
587
|
+
this.failStorage(root);
|
|
588
|
+
if (!this.hasWork(root))
|
|
589
|
+
this.settle(root);
|
|
348
590
|
});
|
|
349
591
|
state.status = 'running';
|
|
350
592
|
active.running.set(step.id, { controller, done });
|
|
351
593
|
}
|
|
352
594
|
this.persist(active);
|
|
353
|
-
if (active
|
|
595
|
+
if (this.hasWork(active))
|
|
354
596
|
return;
|
|
355
597
|
if (this.transitionLoops(active)) {
|
|
356
598
|
this.persist(active);
|
|
@@ -358,13 +600,13 @@ export class WorkflowScheduler {
|
|
|
358
600
|
return;
|
|
359
601
|
}
|
|
360
602
|
const states = Object.entries(active.record.steps);
|
|
361
|
-
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))));
|
|
362
604
|
if (unresolved)
|
|
363
605
|
active.record.status = 'recovery-required';
|
|
364
606
|
else {
|
|
365
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')));
|
|
366
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]));
|
|
367
|
-
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';
|
|
368
610
|
active.record.finishedAt = Date.now();
|
|
369
611
|
}
|
|
370
612
|
this.persist(active);
|
|
@@ -473,6 +715,11 @@ export class WorkflowScheduler {
|
|
|
473
715
|
return copy;
|
|
474
716
|
}
|
|
475
717
|
settle(active) {
|
|
718
|
+
if (active.parent) {
|
|
719
|
+
if (!active.stopped)
|
|
720
|
+
this.completeCall(active);
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
476
723
|
if (!occupied(active.record))
|
|
477
724
|
this.slots.delete(active.record.sessionId);
|
|
478
725
|
for (const waiter of active.waiters.splice(0)) {
|
|
@@ -483,23 +730,14 @@ export class WorkflowScheduler {
|
|
|
483
730
|
}
|
|
484
731
|
}
|
|
485
732
|
persist(active) {
|
|
733
|
+
const root = active.root ?? active;
|
|
486
734
|
try {
|
|
487
|
-
this.
|
|
735
|
+
this.syncInvocations(root);
|
|
736
|
+
this.store.saveExecution(root.record);
|
|
488
737
|
}
|
|
489
738
|
catch (error) {
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
active.record.status = 'recovery-required';
|
|
493
|
-
for (const step of Object.values(active.record.steps)) {
|
|
494
|
-
if (step.status !== 'running')
|
|
495
|
-
continue;
|
|
496
|
-
step.status = 'interrupted';
|
|
497
|
-
const attempt = step.attempts.at(-1);
|
|
498
|
-
attempt.error = { kind: 'interrupted', message: 'Workflow storage failed; effects may already have occurred' };
|
|
499
|
-
attempt.finishedAt = Date.now();
|
|
500
|
-
}
|
|
501
|
-
for (const running of active.running.values())
|
|
502
|
-
running.controller.abort();
|
|
739
|
+
root.persistenceError = error;
|
|
740
|
+
this.failStorage(root);
|
|
503
741
|
throw error;
|
|
504
742
|
}
|
|
505
743
|
}
|
|
@@ -539,6 +777,8 @@ export class WorkflowScheduler {
|
|
|
539
777
|
this.persist(active);
|
|
540
778
|
return;
|
|
541
779
|
}
|
|
780
|
+
if (this.hasExpiredAncestor(active))
|
|
781
|
+
return;
|
|
542
782
|
const attempt = state.attempts.at(-1);
|
|
543
783
|
let timer;
|
|
544
784
|
let timedOut = false;
|
|
@@ -547,7 +787,14 @@ export class WorkflowScheduler {
|
|
|
547
787
|
throw inputError;
|
|
548
788
|
if (step.inputSchema)
|
|
549
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
|
+
}
|
|
550
795
|
this.persist(active);
|
|
796
|
+
if (this.hasExpiredAncestor(active))
|
|
797
|
+
return;
|
|
551
798
|
const timeout = step.timeoutMs ?? (step.kind === 'shell' || step.kind === 'typescript' || step.kind === 'mcp' ? 60_000 : undefined);
|
|
552
799
|
if (timeout !== undefined)
|
|
553
800
|
timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeout);
|
|
@@ -578,7 +825,7 @@ export class WorkflowScheduler {
|
|
|
578
825
|
}
|
|
579
826
|
}
|
|
580
827
|
else
|
|
581
|
-
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 });
|
|
582
829
|
if (active.stopped)
|
|
583
830
|
return;
|
|
584
831
|
if (timedOut)
|
|
@@ -600,7 +847,8 @@ export class WorkflowScheduler {
|
|
|
600
847
|
}
|
|
601
848
|
finally {
|
|
602
849
|
clearTimeout(timer);
|
|
603
|
-
|
|
850
|
+
if (!active.calls.has(step.id))
|
|
851
|
+
attempt.finishedAt ??= Date.now();
|
|
604
852
|
this.persist(active);
|
|
605
853
|
}
|
|
606
854
|
}
|
package/dist/workflows/schema.js
CHANGED
|
@@ -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')
|