@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -0
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
- package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-6L5KCQWJ.mjs} +99 -21
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-QNU2YE4G.mjs} +45 -13
- package/build/backend-worker.mjs +48 -7
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/index.js +72 -10
- package/dist/backend/claude/subagents.js +30 -9
- package/dist/backend/fake/index.js +36 -6
- package/dist/backend/pi/index.js +34 -2
- package/dist/backend/pi/state.js +16 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/worker/claude-state.js +22 -0
- package/dist/backend/worker/entry.js +25 -6
- package/dist/backend/worker/index.js +30 -5
- package/dist/backend/worker/protocol.js +1 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- 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 +29 -3
- package/dist/client/subagent-tree.js +49 -0
- package/dist/daemon/git.js +10 -7
- package/dist/daemon/host.js +226 -26
- package/dist/daemon/runtime.js +71 -3
- package/dist/daemon/server.js +3 -0
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder.js +36 -11
- package/dist/daemon/workflow-environment.js +191 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +9 -6
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +382 -300
- package/dist/daemon/workflow-routes.js +39 -0
- package/dist/daemon/workflow-schedule-driver.js +247 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +341 -0
- package/dist/isolation/sandbox.js +30 -14
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/protocol/events.js +2 -0
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/tui/render.js +7 -1
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +1 -1
- package/dist/workflows/graph.js +78 -4
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +124 -8
- package/dist/workflows/recovery.js +37 -1
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +351 -92
- package/dist/workflows/schedules.js +129 -0
- package/dist/workflows/schema.js +2 -0
- package/dist/workflows/store.js +110 -11
- package/package.json +2 -1
- package/web/dist/assets/index-BGu3YSP7.css +2 -0
- package/web/dist/assets/index-Miy2nveb.js +40 -0
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-Vf_fCXyE.js} +1 -1
- package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
- package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
- package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
- package/web/dist/index.html +4 -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
|
@@ -1,10 +1,14 @@
|
|
|
1
|
+
import { executionOwner } from "./records.js";
|
|
2
|
+
import { executionAccessibleBy, executionAssociation, executionIdentity, executionOwnerKey, executionOwnerOf } from "./owner.js";
|
|
1
3
|
import { randomUUID } from 'node:crypto';
|
|
2
4
|
import { isDeepStrictEqual } from 'node:util';
|
|
3
5
|
import { resolveMapping, validateDefinition } from "./graph.js";
|
|
4
6
|
import { declaredOutputSchema, parseValue, valueAt } from "./schema.js";
|
|
5
7
|
import { validateMcpOutput } from "./mcp.js";
|
|
6
8
|
import { WorkflowStore } from "./store.js";
|
|
7
|
-
import { savedDefinitionRevision, validateCompatibleDefinition } from "./recovery.js";
|
|
9
|
+
import { recoverySteps, savedDefinitionRevision, validateCompatibleDefinition } from "./recovery.js";
|
|
10
|
+
import { resolveWorkflowCalls } from "./calls.js";
|
|
11
|
+
import { invocationCheckpoint, invocationExecution } from "./invocations.js";
|
|
8
12
|
export class WorkflowStepError extends Error {
|
|
9
13
|
partialOutput;
|
|
10
14
|
constructor(message, partialOutput) { super(message); this.partialOutput = partialOutput; }
|
|
@@ -17,62 +21,63 @@ export class WorkflowScheduler {
|
|
|
17
21
|
slots = new Map();
|
|
18
22
|
store;
|
|
19
23
|
executors;
|
|
20
|
-
|
|
24
|
+
onResume;
|
|
25
|
+
constructor(store, executors, onResume) {
|
|
21
26
|
this.store = store;
|
|
22
27
|
this.executors = executors;
|
|
23
|
-
|
|
24
|
-
|
|
28
|
+
this.onResume = onResume;
|
|
29
|
+
for (const owner of store.listOwners()) {
|
|
30
|
+
for (const record of store.listOwnedExecutions(owner)) {
|
|
25
31
|
if (!occupied(record))
|
|
26
32
|
continue;
|
|
27
|
-
if (this.slots.has(
|
|
28
|
-
throw new Error('Multiple workflow executions occupy one
|
|
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
|
+
if (this.slots.has(executionOwnerKey(owner)))
|
|
34
|
+
throw new Error('Multiple workflow executions occupy one execution owner');
|
|
35
|
+
const active = this.install(record);
|
|
36
|
+
this.reconcile(active);
|
|
37
|
+
this.persist(active);
|
|
42
38
|
}
|
|
43
39
|
}
|
|
44
40
|
}
|
|
45
|
-
occupied(sessionId) { return this.slots.has(sessionId); }
|
|
41
|
+
occupied(sessionId) { return this.slots.has(sessionId) || [...this.active.values()].some(active => executionAssociation(active.record) === sessionId && occupied(active.record)); }
|
|
46
42
|
/** Whether the slot contains a full execution doing work, excluding tests and recovery waits. */
|
|
47
43
|
activeFull(sessionId) {
|
|
48
|
-
const executionId = this.slots.get(sessionId);
|
|
44
|
+
const executionId = this.slots.get(sessionId) ?? [...this.active.values()].find(active => executionAssociation(active.record) === sessionId && occupied(active.record))?.record.id;
|
|
49
45
|
const record = executionId ? this.active.get(executionId)?.record : undefined;
|
|
50
46
|
return record?.status === 'running' && record.testStepId === undefined;
|
|
51
47
|
}
|
|
52
48
|
forgetSession(sessionId) {
|
|
53
|
-
const executions = [...this.active.values()].filter(active => active.record
|
|
54
|
-
if (executions.some(active => active
|
|
49
|
+
const executions = [...this.active.values()].filter(active => executionOwner(active.record) === sessionId);
|
|
50
|
+
if (executions.some(active => this.hasWork(active) || active.record.status === 'running'))
|
|
55
51
|
throw new Error('Workflow work must stop before forgetting an Agent Session');
|
|
56
52
|
for (const active of executions)
|
|
57
53
|
this.active.delete(active.record.id);
|
|
58
54
|
this.slots.delete(sessionId);
|
|
59
55
|
}
|
|
60
|
-
start(definition, session, input, testStepId, launchId, namingEligible = false) {
|
|
61
|
-
if (this.occupied(session
|
|
56
|
+
start(definition, session, input, testStepId, launchId, namingEligible = false, capturedDefinitions) {
|
|
57
|
+
if (this.occupied(executionOwner(session)))
|
|
62
58
|
throw new Error('Agent Session workflow slot is occupied');
|
|
63
59
|
const graph = validateDefinition(definition);
|
|
64
60
|
if (graph.definition.backend !== session.backend)
|
|
65
61
|
throw new Error('Backend Adapter mismatch');
|
|
66
|
-
if (graph.definition.projectId && graph.definition.projectId
|
|
62
|
+
if (graph.definition.projectId && !(session.matchesProject?.(graph.definition.projectId) ?? graph.definition.projectId === session.projectId))
|
|
67
63
|
throw new Error('Workflow is restricted to another Project');
|
|
68
64
|
const testStep = testStepId === undefined ? undefined : graph.order.find(step => step.id === testStepId);
|
|
69
65
|
if (testStepId !== undefined && !testStep)
|
|
70
66
|
throw new Error('Unknown test step');
|
|
71
|
-
|
|
67
|
+
const retainedDefinitions = resolveWorkflowCalls(graph.definition, id => {
|
|
68
|
+
if (!capturedDefinitions)
|
|
69
|
+
return this.store.getDefinition(id);
|
|
70
|
+
const retained = capturedDefinitions[id];
|
|
71
|
+
if (!retained)
|
|
72
|
+
throw new Error('Missing captured Workflow Definition');
|
|
73
|
+
return retained;
|
|
74
|
+
}, testStepId);
|
|
75
|
+
this.check(testStep ? [testStep] : graph.order, session, retainedDefinitions);
|
|
72
76
|
const parsed = parseValue(testStep ? graph.inputSchemas.get(testStep.id) : graph.definition.inputSchema, input);
|
|
73
77
|
const record = {
|
|
74
|
-
|
|
78
|
+
...executionIdentity(session), ...(session.runtime ? { runtime: session.runtime } : {}), id: randomUUID(), scope: session.scope,
|
|
75
79
|
definition: graph.definition, input: parsed, status: 'running', startedAt: Date.now(),
|
|
80
|
+
...(graph.order.some(step => step.kind === 'workflow') ? { retainedDefinitions, invocations: {} } : {}),
|
|
76
81
|
...(launchId ? { launchId } : {}),
|
|
77
82
|
...(namingEligible && testStepId === undefined ? { naming: 'pending' } : {}),
|
|
78
83
|
steps: Object.fromEntries(graph.order.map(step => [step.id, { status: testStep && step.id !== testStep.id ? 'skipped' : 'pending', attempts: [] }])),
|
|
@@ -83,16 +88,25 @@ export class WorkflowScheduler {
|
|
|
83
88
|
this.pump(active);
|
|
84
89
|
return structuredClone(record);
|
|
85
90
|
}
|
|
91
|
+
associate(occurrenceId, executionId, sessionId) {
|
|
92
|
+
const active = this.require(executionOwnerKey({ kind: 'occurrence', occurrenceId }), executionId);
|
|
93
|
+
if (executionOwnerOf(active.record).kind !== 'occurrence' || (executionAssociation(active.record) && executionAssociation(active.record) !== sessionId))
|
|
94
|
+
throw new Error('Invalid execution association');
|
|
95
|
+
const visit = (node) => { node.record.sessionId = sessionId; for (const call of node.calls.values())
|
|
96
|
+
visit(call.child); };
|
|
97
|
+
visit(active);
|
|
98
|
+
this.persist(active);
|
|
99
|
+
}
|
|
86
100
|
get(sessionId, executionId) {
|
|
87
101
|
const active = this.active.get(executionId);
|
|
88
|
-
if (active
|
|
102
|
+
if (active !== undefined && executionAccessibleBy(active.record, sessionId))
|
|
89
103
|
return structuredClone(active.record);
|
|
90
104
|
return this.store.getExecution(sessionId, executionId);
|
|
91
105
|
}
|
|
92
106
|
/** Atomically consume an automatic naming request before model work starts. */
|
|
93
107
|
claimNaming(sessionId, executionId) {
|
|
94
108
|
const active = this.active.get(executionId);
|
|
95
|
-
const record = active
|
|
109
|
+
const record = active !== undefined && executionAccessibleBy(active.record, sessionId) ? active.record : this.store.getExecution(sessionId, executionId);
|
|
96
110
|
if (record.naming !== 'pending' || record.testStepId)
|
|
97
111
|
return false;
|
|
98
112
|
record.naming = 'requested';
|
|
@@ -106,25 +120,20 @@ export class WorkflowScheduler {
|
|
|
106
120
|
const active = this.require(sessionId, executionId);
|
|
107
121
|
if (active.persistenceError)
|
|
108
122
|
return Promise.reject(active.persistenceError);
|
|
109
|
-
if (active.record.status !== 'running' && !active
|
|
123
|
+
if (active.record.status !== 'running' && !this.hasWork(active))
|
|
110
124
|
return Promise.resolve(structuredClone(active.record));
|
|
111
125
|
return new Promise((resolve, reject) => active.waiters.push({ resolve, reject }));
|
|
112
126
|
}
|
|
127
|
+
hasPendingDeadline(sessionId, executionId) {
|
|
128
|
+
const pending = (active) => !active.stopped && [...active.calls.values()].some(call => call.timer !== undefined || pending(call.child));
|
|
129
|
+
const active = this.active.get(executionId);
|
|
130
|
+
return active !== undefined && executionAccessibleBy(active.record, sessionId) && pending(active);
|
|
131
|
+
}
|
|
113
132
|
async cancel(sessionId, executionId) {
|
|
114
133
|
const active = this.require(sessionId, executionId);
|
|
115
134
|
if (!occupied(active.record))
|
|
116
135
|
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);
|
|
136
|
+
await this.stopTree(active, 'cancelled');
|
|
128
137
|
this.settle(active);
|
|
129
138
|
return structuredClone(active.record);
|
|
130
139
|
}
|
|
@@ -132,28 +141,16 @@ export class WorkflowScheduler {
|
|
|
132
141
|
const active = this.require(sessionId, executionId);
|
|
133
142
|
if (!occupied(active.record))
|
|
134
143
|
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));
|
|
144
|
+
await this.stopTree(active, 'interrupted');
|
|
149
145
|
this.settle(active);
|
|
150
146
|
return structuredClone(active.record);
|
|
151
147
|
}
|
|
152
148
|
/** replacementDefinition is resolved from saved storage by the host, never from request JSON. */
|
|
153
149
|
recover(session, executionId, action, replacementDefinition) {
|
|
154
|
-
const
|
|
150
|
+
const root = this.require(executionOwner(session), executionId);
|
|
151
|
+
const active = action.invocationId ? this.findInvocation(root, action.invocationId) : root;
|
|
155
152
|
const record = active.record;
|
|
156
|
-
if (record.status !== 'recovery-required' || active
|
|
153
|
+
if (record.status !== 'recovery-required' || this.hasWork(active))
|
|
157
154
|
throw new Error('Execution is not ready for recovery');
|
|
158
155
|
if (record.definition.backend !== session.backend || record.scope !== session.scope)
|
|
159
156
|
throw new Error('Recovery requires the original Scope and Backend Adapter');
|
|
@@ -169,7 +166,7 @@ export class WorkflowScheduler {
|
|
|
169
166
|
throw new Error('Replacement definition requires retry-updated');
|
|
170
167
|
// Check the corrected configuration, not the obsolete one. No checkpoint/graph mutation
|
|
171
168
|
// happens until compatibility, authority, eligibility and all runtime checks pass.
|
|
172
|
-
this.check(
|
|
169
|
+
this.check(recoverySteps(root.record, action, replacementDefinition), session, root.record.retainedDefinitions);
|
|
173
170
|
const limits = Object.entries(record.loops ?? {}).filter(([, loop]) => loop.phase === 'limit');
|
|
174
171
|
if (action.kind === 'continue' && limits.length)
|
|
175
172
|
throw new WorkflowLoopConflict('Loop limit requires an extra try or cancellation');
|
|
@@ -191,6 +188,9 @@ export class WorkflowScheduler {
|
|
|
191
188
|
throw new Error('Recover the failed handling step, not the handled failure');
|
|
192
189
|
if (action.kind === 'supply') {
|
|
193
190
|
const output = this.validateOutput(active, step, action.output);
|
|
191
|
+
this.releaseCancelledCall(active, step.id);
|
|
192
|
+
if (active.calls.has(step.id))
|
|
193
|
+
throw new Error('Cancel the owned call subtree before replacing its output');
|
|
194
194
|
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
195
|
state.attempts.push(attempt);
|
|
196
196
|
state.output = output;
|
|
@@ -198,7 +198,8 @@ export class WorkflowScheduler {
|
|
|
198
198
|
state.outcome = step.kind === 'branch' ? output ? 'true' : 'false' : 'success';
|
|
199
199
|
}
|
|
200
200
|
else {
|
|
201
|
-
this.check([step], session);
|
|
201
|
+
this.check([step], session, root.record.retainedDefinitions);
|
|
202
|
+
this.releaseCancelledCall(active, step.id);
|
|
202
203
|
if (action.kind === 'retry-updated') {
|
|
203
204
|
const previousStep = record.definition.steps.find(previous => previous.id === step.id);
|
|
204
205
|
(record.definitionUpdates ??= []).push({ stepId: step.id, previousStep: structuredClone(previousStep), nextStep: structuredClone(step), appliedAt: Date.now(), attempt: state.attempts.length + 1 });
|
|
@@ -233,14 +234,37 @@ export class WorkflowScheduler {
|
|
|
233
234
|
delete record.finishedAt;
|
|
234
235
|
active.stopped = false;
|
|
235
236
|
delete active.persistenceError;
|
|
237
|
+
for (let parent = active.parent; parent; parent = parent.parent) {
|
|
238
|
+
parent.stopped = false;
|
|
239
|
+
parent.record.status = 'running';
|
|
240
|
+
delete parent.record.finishedAt;
|
|
241
|
+
}
|
|
236
242
|
this.persist(active);
|
|
243
|
+
delete root.persistenceError;
|
|
244
|
+
this.resumeCalls(active);
|
|
245
|
+
for (let parent = active.parent; parent; parent = parent.parent)
|
|
246
|
+
this.resumeCalls(parent);
|
|
237
247
|
this.pump(active);
|
|
238
|
-
return structuredClone(record);
|
|
248
|
+
return structuredClone(root.record);
|
|
239
249
|
}
|
|
240
|
-
check(steps, session) {
|
|
250
|
+
check(steps, session, manifest, checked = new Set()) {
|
|
241
251
|
for (const step of steps) {
|
|
242
252
|
if (step.kind === 'branch' || step.kind === 'join')
|
|
243
253
|
continue;
|
|
254
|
+
if (step.kind === 'workflow') {
|
|
255
|
+
const target = manifest?.[step.workflowId];
|
|
256
|
+
if (!target)
|
|
257
|
+
throw new Error('Missing retained called Workflow Definition');
|
|
258
|
+
if (target.backend !== session.backend)
|
|
259
|
+
throw new Error('Backend Adapter mismatch');
|
|
260
|
+
if (target.projectId && !(session.matchesProject?.(target.projectId) ?? target.projectId === session.projectId))
|
|
261
|
+
throw new Error('Workflow is restricted to another Project');
|
|
262
|
+
if (!checked.has(target.id)) {
|
|
263
|
+
checked.add(target.id);
|
|
264
|
+
this.check(target.steps, session, manifest, checked);
|
|
265
|
+
}
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
244
268
|
const executor = this.executors[step.kind];
|
|
245
269
|
if (!executor)
|
|
246
270
|
throw new Error(`Executor is unavailable: ${step.kind}`);
|
|
@@ -248,14 +272,232 @@ export class WorkflowScheduler {
|
|
|
248
272
|
}
|
|
249
273
|
}
|
|
250
274
|
install(record) {
|
|
251
|
-
const active = { record, graph: validateDefinition(record.definition), running: new Map(), waiters: [], stopped: record.status !== 'running' };
|
|
275
|
+
const active = { record, graph: validateDefinition(record.definition), running: new Map(), calls: new Map(), waiters: [], stopped: record.status !== 'running' };
|
|
252
276
|
this.active.set(record.id, active);
|
|
253
|
-
this.slots.set(record
|
|
277
|
+
this.slots.set(executionOwner(record), record.id);
|
|
278
|
+
const installed = new Map();
|
|
279
|
+
const restore = (id) => {
|
|
280
|
+
const cached = installed.get(id);
|
|
281
|
+
if (cached)
|
|
282
|
+
return cached;
|
|
283
|
+
const invocation = record.invocations[id];
|
|
284
|
+
const parent = invocation.parentInvocationId ? restore(invocation.parentInvocationId) : active;
|
|
285
|
+
const local = invocationExecution(record, id);
|
|
286
|
+
const step = parent.graph.order.find(step => step.id === invocation.callStepId);
|
|
287
|
+
const child = { record: local, graph: validateDefinition(local.definition), parent, root: active, callStepId: invocation.callStepId, callAttempt: invocation.callAttempt,
|
|
288
|
+
inheritedAsk: parent.inheritedAsk || parent.record.definition.permission === 'ask' || step.permission === 'ask', running: new Map(), calls: new Map(), waiters: [], stopped: local.status !== 'running' };
|
|
289
|
+
installed.set(id, child);
|
|
290
|
+
const state = parent.record.steps[invocation.callStepId];
|
|
291
|
+
if (state.attempts.length === invocation.callAttempt && state.status === 'running')
|
|
292
|
+
parent.calls.set(invocation.callStepId, { child });
|
|
293
|
+
return child;
|
|
294
|
+
};
|
|
295
|
+
for (const id of Object.keys(record.invocations ?? {}))
|
|
296
|
+
restore(id);
|
|
254
297
|
return active;
|
|
255
298
|
}
|
|
299
|
+
hasWork(active) {
|
|
300
|
+
return active.running.size > 0 || [...active.calls.values()].some(call => !!call.stopping || this.hasWork(call.child));
|
|
301
|
+
}
|
|
302
|
+
findInvocation(active, id) {
|
|
303
|
+
const pending = [active];
|
|
304
|
+
while (pending.length) {
|
|
305
|
+
const current = pending.pop();
|
|
306
|
+
if (current !== active && current.record.id === id)
|
|
307
|
+
return current;
|
|
308
|
+
pending.push(...[...current.calls.values()].map(call => call.child));
|
|
309
|
+
}
|
|
310
|
+
throw new Error('Invocation does not require recovery');
|
|
311
|
+
}
|
|
312
|
+
syncInvocations(active) {
|
|
313
|
+
const root = active.root ?? active;
|
|
314
|
+
for (const call of active.calls.values()) {
|
|
315
|
+
const child = call.child;
|
|
316
|
+
this.syncInvocations(child);
|
|
317
|
+
(root.record.invocations ??= {})[child.record.id] = invocationCheckpoint(child.record, {
|
|
318
|
+
...(active.parent ? { parentInvocationId: active.record.id } : {}), callStepId: child.callStepId, callAttempt: child.callAttempt, definitionId: child.record.definition.id,
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
reconcile(active) {
|
|
323
|
+
for (const call of active.calls.values())
|
|
324
|
+
this.reconcile(call.child);
|
|
325
|
+
if (!occupied(active.record))
|
|
326
|
+
return;
|
|
327
|
+
for (const [id, state] of Object.entries(active.record.steps)) {
|
|
328
|
+
if (state.status !== 'running' || active.calls.has(id))
|
|
329
|
+
continue;
|
|
330
|
+
state.status = 'interrupted';
|
|
331
|
+
const attempt = state.attempts.at(-1);
|
|
332
|
+
attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
|
|
333
|
+
attempt.finishedAt ??= Date.now();
|
|
334
|
+
}
|
|
335
|
+
active.record.status = 'recovery-required';
|
|
336
|
+
active.stopped = true;
|
|
337
|
+
}
|
|
338
|
+
releaseCancelledCall(active, stepId) {
|
|
339
|
+
const call = active.calls.get(stepId);
|
|
340
|
+
if (call?.child.record.status !== 'cancelled')
|
|
341
|
+
return;
|
|
342
|
+
clearTimeout(call.timer);
|
|
343
|
+
this.syncInvocations(active);
|
|
344
|
+
active.calls.delete(stepId);
|
|
345
|
+
}
|
|
346
|
+
failStorage(active) {
|
|
347
|
+
active.stopped = true;
|
|
348
|
+
if (!active.parent || occupied(active.record))
|
|
349
|
+
active.record.status = 'recovery-required';
|
|
350
|
+
for (const call of active.calls.values()) {
|
|
351
|
+
clearTimeout(call.timer);
|
|
352
|
+
this.failStorage(call.child);
|
|
353
|
+
}
|
|
354
|
+
for (const [id, state] of Object.entries(active.record.steps)) {
|
|
355
|
+
if (state.status !== 'running' || active.calls.has(id))
|
|
356
|
+
continue;
|
|
357
|
+
state.status = 'interrupted';
|
|
358
|
+
const attempt = state.attempts.at(-1);
|
|
359
|
+
attempt.error = { kind: 'interrupted', message: 'Workflow storage failed; effects may already have occurred' };
|
|
360
|
+
attempt.finishedAt ??= Date.now();
|
|
361
|
+
}
|
|
362
|
+
for (const running of active.running.values())
|
|
363
|
+
running.controller.abort();
|
|
364
|
+
}
|
|
365
|
+
async stopTree(active, reason) {
|
|
366
|
+
const tree = [active];
|
|
367
|
+
for (const current of tree)
|
|
368
|
+
tree.push(...[...current.calls.values()].map(call => call.child));
|
|
369
|
+
for (const current of tree) {
|
|
370
|
+
current.stopped = true;
|
|
371
|
+
if (!occupied(current.record))
|
|
372
|
+
continue;
|
|
373
|
+
current.record.status = reason === 'cancelled' ? 'cancelled' : 'recovery-required';
|
|
374
|
+
for (const [id, state] of Object.entries(current.record.steps)) {
|
|
375
|
+
if (reason === 'cancelled' && ['pending', 'blocked', 'running', 'interrupted'].includes(state.status))
|
|
376
|
+
state.status = 'cancelled';
|
|
377
|
+
else if (reason === 'interrupted' && state.status === 'running' && !current.calls.has(id)) {
|
|
378
|
+
state.status = 'interrupted';
|
|
379
|
+
const attempt = state.attempts.at(-1);
|
|
380
|
+
attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
|
|
381
|
+
attempt.finishedAt ??= Date.now();
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
const work = tree.flatMap(current => [...current.running.values()]);
|
|
386
|
+
try {
|
|
387
|
+
this.persist(active);
|
|
388
|
+
}
|
|
389
|
+
finally {
|
|
390
|
+
for (const current of tree)
|
|
391
|
+
for (const call of current.calls.values())
|
|
392
|
+
clearTimeout(call.timer);
|
|
393
|
+
for (const running of work)
|
|
394
|
+
running.controller.abort();
|
|
395
|
+
await Promise.all(work.map(running => running.done));
|
|
396
|
+
for (const current of tree)
|
|
397
|
+
if (reason === 'cancelled' && current.record.status === 'cancelled') {
|
|
398
|
+
current.record.finishedAt ??= Date.now();
|
|
399
|
+
for (const state of Object.values(current.record.steps))
|
|
400
|
+
if (state.status === 'cancelled') {
|
|
401
|
+
const attempt = state.attempts.at(-1);
|
|
402
|
+
if (attempt)
|
|
403
|
+
attempt.finishedAt ??= Date.now();
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
this.persist(active);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
startCall(active, step, attempt) {
|
|
410
|
+
const root = active.root ?? active;
|
|
411
|
+
const definition = root.record.retainedDefinitions?.[step.workflowId];
|
|
412
|
+
if (!definition)
|
|
413
|
+
throw new Error('Missing retained called Workflow Definition');
|
|
414
|
+
const graph = validateDefinition(definition);
|
|
415
|
+
const record = {
|
|
416
|
+
...executionIdentity(root.record), id: randomUUID(), scope: root.record.scope, definition: graph.definition,
|
|
417
|
+
input: structuredClone(attempt.input), status: 'running', startedAt: Date.now(),
|
|
418
|
+
steps: Object.fromEntries(graph.order.map(step => [step.id, { status: 'pending', attempts: [] }])),
|
|
419
|
+
loops: Object.fromEntries(graph.loops.map(loop => [loop.headerId, { activation: 0, try: 0, phase: 'inactive', grants: [] }])),
|
|
420
|
+
};
|
|
421
|
+
const child = { record, graph, parent: active, root, callStepId: step.id, callAttempt: attempt.number,
|
|
422
|
+
inheritedAsk: active.inheritedAsk || active.record.definition.permission === 'ask' || step.permission === 'ask',
|
|
423
|
+
running: new Map(), calls: new Map(), waiters: [], stopped: false };
|
|
424
|
+
active.calls.set(step.id, { child });
|
|
425
|
+
if (step.timeoutMs !== undefined)
|
|
426
|
+
attempt.deadlineAt = attempt.startedAt + step.timeoutMs;
|
|
427
|
+
this.persist(active);
|
|
428
|
+
this.armCall(active, step.id);
|
|
429
|
+
if (attempt.deadlineAt === undefined || attempt.deadlineAt > Date.now())
|
|
430
|
+
this.pump(child);
|
|
431
|
+
}
|
|
432
|
+
armCall(active, stepId) {
|
|
433
|
+
const call = active.calls.get(stepId);
|
|
434
|
+
clearTimeout(call.timer);
|
|
435
|
+
const deadline = active.record.steps[stepId].attempts.at(-1).deadlineAt;
|
|
436
|
+
if (deadline === undefined || call.stopping)
|
|
437
|
+
return;
|
|
438
|
+
call.timer = setTimeout(() => {
|
|
439
|
+
call.stopping = this.stopTree(call.child, 'cancelled').then(() => {
|
|
440
|
+
if (active.stopped)
|
|
441
|
+
return;
|
|
442
|
+
const state = active.record.steps[stepId];
|
|
443
|
+
const attempt = state.attempts.at(-1);
|
|
444
|
+
state.status = 'timed-out';
|
|
445
|
+
state.outcome = 'timeout';
|
|
446
|
+
attempt.error = { kind: 'timeout', message: 'Step timed out' };
|
|
447
|
+
attempt.finishedAt = Date.now();
|
|
448
|
+
this.persist(active);
|
|
449
|
+
active.calls.delete(stepId);
|
|
450
|
+
const root = active.root ?? active;
|
|
451
|
+
const resumed = root.record.status === 'recovery-required';
|
|
452
|
+
for (let current = active; current; current = current.parent) {
|
|
453
|
+
current.record.status = 'running';
|
|
454
|
+
delete current.record.finishedAt;
|
|
455
|
+
}
|
|
456
|
+
if (resumed)
|
|
457
|
+
this.onResume?.(structuredClone(root.record));
|
|
458
|
+
this.pump(active);
|
|
459
|
+
}).catch(error => { (active.root ?? active).persistenceError = error; this.failStorage(active.root ?? active); this.settle(active.root ?? active); }).finally(() => { delete call.stopping; });
|
|
460
|
+
}, Math.max(0, deadline - Date.now()));
|
|
461
|
+
}
|
|
462
|
+
resumeCalls(active) {
|
|
463
|
+
for (const [stepId, call] of active.calls) {
|
|
464
|
+
this.armCall(active, stepId);
|
|
465
|
+
if (call.child.record.status === 'completed' || call.child.record.status === 'completed-with-recovery')
|
|
466
|
+
this.completeCall(call.child);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
completeCall(child) {
|
|
470
|
+
const parent = child.parent;
|
|
471
|
+
const stepId = child.callStepId;
|
|
472
|
+
const call = parent.calls.get(stepId);
|
|
473
|
+
if (!call || call.child !== child || call.stopping || parent.stopped)
|
|
474
|
+
return;
|
|
475
|
+
if (child.record.status === 'completed' || child.record.status === 'completed-with-recovery') {
|
|
476
|
+
clearTimeout(call.timer);
|
|
477
|
+
const state = parent.record.steps[stepId];
|
|
478
|
+
const attempt = state.attempts.at(-1);
|
|
479
|
+
const step = parent.graph.order.find(step => step.id === stepId);
|
|
480
|
+
try {
|
|
481
|
+
const output = this.validateOutput(parent, step, child.record.result);
|
|
482
|
+
state.status = 'completed';
|
|
483
|
+
state.outcome = 'success';
|
|
484
|
+
state.output = output;
|
|
485
|
+
attempt.output = output;
|
|
486
|
+
}
|
|
487
|
+
catch (error) {
|
|
488
|
+
state.status = 'failed';
|
|
489
|
+
state.outcome = 'failure';
|
|
490
|
+
attempt.error = { kind: 'failure', message: error instanceof Error ? error.message : String(error) };
|
|
491
|
+
}
|
|
492
|
+
attempt.finishedAt = Date.now();
|
|
493
|
+
this.persist(child);
|
|
494
|
+
parent.calls.delete(stepId);
|
|
495
|
+
}
|
|
496
|
+
this.pump(parent);
|
|
497
|
+
}
|
|
256
498
|
require(sessionId, executionId) {
|
|
257
499
|
const active = this.active.get(executionId);
|
|
258
|
-
if (!active || active.record
|
|
500
|
+
if (!active || !executionAccessibleBy(active.record, sessionId))
|
|
259
501
|
throw new Error('Unknown workflow execution');
|
|
260
502
|
return active;
|
|
261
503
|
}
|
|
@@ -276,8 +518,17 @@ export class WorkflowScheduler {
|
|
|
276
518
|
const handled = !state.recovery && active.graph.outgoing.get(edge.from).some(candidate => candidate.outcome === state.outcome);
|
|
277
519
|
return handled || edge.outcome === 'failure' || edge.outcome === 'timeout' ? 'skipped' : 'blocked';
|
|
278
520
|
}
|
|
521
|
+
hasExpiredAncestor(active) {
|
|
522
|
+
const now = Date.now();
|
|
523
|
+
for (let child = active; child.parent; child = child.parent) {
|
|
524
|
+
const deadline = child.parent.record.steps[child.callStepId].attempts[child.callAttempt - 1].deadlineAt;
|
|
525
|
+
if (deadline !== undefined && deadline <= now)
|
|
526
|
+
return true;
|
|
527
|
+
}
|
|
528
|
+
return false;
|
|
529
|
+
}
|
|
279
530
|
pump(active) {
|
|
280
|
-
if (active.stopped || active.record.status !== 'running')
|
|
531
|
+
if (active.stopped || active.record.status !== 'running' || this.hasExpiredAncestor(active))
|
|
281
532
|
return;
|
|
282
533
|
this.transitionLoops(active);
|
|
283
534
|
for (const step of active.graph.order) {
|
|
@@ -334,23 +585,25 @@ export class WorkflowScheduler {
|
|
|
334
585
|
state.attempts.push({ number: state.attempts.length + 1, action: retry ? 'retry' : 'execute', startedAt: Date.now(), input, ...(identities.length ? { loops: identities } : {}) });
|
|
335
586
|
const done = Promise.resolve().then(() => this.execute(active, step, controller, inputError)).finally(() => {
|
|
336
587
|
active.running.delete(step.id);
|
|
588
|
+
const root = active.root ?? active;
|
|
337
589
|
if (active.stopped) {
|
|
338
|
-
if (!
|
|
339
|
-
this.settle(
|
|
590
|
+
if (!this.hasWork(root) && root.persistenceError)
|
|
591
|
+
this.settle(root);
|
|
340
592
|
return;
|
|
341
593
|
}
|
|
342
594
|
this.pump(active);
|
|
343
595
|
}).catch(error => {
|
|
344
|
-
active.
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
596
|
+
const root = active.root ?? active;
|
|
597
|
+
root.persistenceError = error;
|
|
598
|
+
this.failStorage(root);
|
|
599
|
+
if (!this.hasWork(root))
|
|
600
|
+
this.settle(root);
|
|
348
601
|
});
|
|
349
602
|
state.status = 'running';
|
|
350
603
|
active.running.set(step.id, { controller, done });
|
|
351
604
|
}
|
|
352
605
|
this.persist(active);
|
|
353
|
-
if (active
|
|
606
|
+
if (this.hasWork(active))
|
|
354
607
|
return;
|
|
355
608
|
if (this.transitionLoops(active)) {
|
|
356
609
|
this.persist(active);
|
|
@@ -358,13 +611,13 @@ export class WorkflowScheduler {
|
|
|
358
611
|
return;
|
|
359
612
|
}
|
|
360
613
|
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))));
|
|
614
|
+
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
615
|
if (unresolved)
|
|
363
616
|
active.record.status = 'recovery-required';
|
|
364
617
|
else {
|
|
365
618
|
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
619
|
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';
|
|
620
|
+
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
621
|
active.record.finishedAt = Date.now();
|
|
369
622
|
}
|
|
370
623
|
this.persist(active);
|
|
@@ -473,8 +726,13 @@ export class WorkflowScheduler {
|
|
|
473
726
|
return copy;
|
|
474
727
|
}
|
|
475
728
|
settle(active) {
|
|
729
|
+
if (active.parent) {
|
|
730
|
+
if (!active.stopped)
|
|
731
|
+
this.completeCall(active);
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
476
734
|
if (!occupied(active.record))
|
|
477
|
-
this.slots.delete(active.record
|
|
735
|
+
this.slots.delete(executionOwner(active.record));
|
|
478
736
|
for (const waiter of active.waiters.splice(0)) {
|
|
479
737
|
if (active.persistenceError)
|
|
480
738
|
waiter.reject(active.persistenceError);
|
|
@@ -483,23 +741,14 @@ export class WorkflowScheduler {
|
|
|
483
741
|
}
|
|
484
742
|
}
|
|
485
743
|
persist(active) {
|
|
744
|
+
const root = active.root ?? active;
|
|
486
745
|
try {
|
|
487
|
-
this.
|
|
746
|
+
this.syncInvocations(root);
|
|
747
|
+
this.store.saveExecution(root.record);
|
|
488
748
|
}
|
|
489
749
|
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();
|
|
750
|
+
root.persistenceError = error;
|
|
751
|
+
this.failStorage(root);
|
|
503
752
|
throw error;
|
|
504
753
|
}
|
|
505
754
|
}
|
|
@@ -539,6 +788,8 @@ export class WorkflowScheduler {
|
|
|
539
788
|
this.persist(active);
|
|
540
789
|
return;
|
|
541
790
|
}
|
|
791
|
+
if (this.hasExpiredAncestor(active))
|
|
792
|
+
return;
|
|
542
793
|
const attempt = state.attempts.at(-1);
|
|
543
794
|
let timer;
|
|
544
795
|
let timedOut = false;
|
|
@@ -547,7 +798,14 @@ export class WorkflowScheduler {
|
|
|
547
798
|
throw inputError;
|
|
548
799
|
if (step.inputSchema)
|
|
549
800
|
attempt.input = parseValue(step.inputSchema, attempt.input);
|
|
801
|
+
if (step.kind === 'workflow') {
|
|
802
|
+
attempt.input = parseValue(step.contract.inputSchema, attempt.input);
|
|
803
|
+
this.startCall(active, step, attempt);
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
550
806
|
this.persist(active);
|
|
807
|
+
if (this.hasExpiredAncestor(active))
|
|
808
|
+
return;
|
|
551
809
|
const timeout = step.timeoutMs ?? (step.kind === 'shell' || step.kind === 'typescript' || step.kind === 'mcp' ? 60_000 : undefined);
|
|
552
810
|
if (timeout !== undefined)
|
|
553
811
|
timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeout);
|
|
@@ -578,7 +836,7 @@ export class WorkflowScheduler {
|
|
|
578
836
|
}
|
|
579
837
|
}
|
|
580
838
|
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 });
|
|
839
|
+
value = await this.executors[step.kind].execute({ owner: executionOwnerOf(active.record), ownerId: executionOwner(active.record), ...(active.record.sessionId ? { sessionId: active.record.sessionId } : {}), ...(active.record.occurrenceId ? { occurrenceId: active.record.occurrenceId } : {}), 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
840
|
if (active.stopped)
|
|
583
841
|
return;
|
|
584
842
|
if (timedOut)
|
|
@@ -600,7 +858,8 @@ export class WorkflowScheduler {
|
|
|
600
858
|
}
|
|
601
859
|
finally {
|
|
602
860
|
clearTimeout(timer);
|
|
603
|
-
|
|
861
|
+
if (!active.calls.has(step.id))
|
|
862
|
+
attempt.finishedAt ??= Date.now();
|
|
604
863
|
this.persist(active);
|
|
605
864
|
}
|
|
606
865
|
}
|