@nathanstephenson/flow 0.1.0

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 (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,573 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { resolveMapping, validateDefinition } from "./graph.js";
4
+ import { declaredOutputSchema, parseValue, valueAt } from "./schema.js";
5
+ import { validateMcpOutput } from "./mcp.js";
6
+ import { WorkflowStore } from "./store.js";
7
+ export class WorkflowStepError extends Error {
8
+ partialOutput;
9
+ constructor(message, partialOutput) { super(message); this.partialOutput = partialOutput; }
10
+ }
11
+ export class WorkflowLoopConflict extends Error {
12
+ }
13
+ const occupied = (record) => record.status === 'running' || record.status === 'recovery-required';
14
+ export class WorkflowScheduler {
15
+ active = new Map();
16
+ slots = new Map();
17
+ store;
18
+ executors;
19
+ constructor(store, executors) {
20
+ this.store = store;
21
+ this.executors = executors;
22
+ for (const sessionId of store.listSessionIds()) {
23
+ for (const record of store.listExecutions(sessionId)) {
24
+ if (!occupied(record))
25
+ continue;
26
+ if (this.slots.has(sessionId))
27
+ 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);
41
+ }
42
+ }
43
+ }
44
+ occupied(sessionId) { return this.slots.has(sessionId); }
45
+ /** Whether the slot contains a full execution doing work, excluding tests and recovery waits. */
46
+ activeFull(sessionId) {
47
+ const executionId = this.slots.get(sessionId);
48
+ const record = executionId ? this.active.get(executionId)?.record : undefined;
49
+ return record?.status === 'running' && record.testStepId === undefined;
50
+ }
51
+ forgetSession(sessionId) {
52
+ const executions = [...this.active.values()].filter(active => active.record.sessionId === sessionId);
53
+ if (executions.some(active => active.running.size || active.record.status === 'running'))
54
+ throw new Error('Workflow work must stop before forgetting an Agent Session');
55
+ for (const active of executions)
56
+ this.active.delete(active.record.id);
57
+ this.slots.delete(sessionId);
58
+ }
59
+ start(definition, session, input, testStepId, launchId) {
60
+ if (this.occupied(session.sessionId))
61
+ throw new Error('Agent Session workflow slot is occupied');
62
+ const graph = validateDefinition(definition);
63
+ if (graph.definition.backend !== session.backend)
64
+ throw new Error('Backend Adapter mismatch');
65
+ if (graph.definition.projectId && graph.definition.projectId !== session.projectId)
66
+ throw new Error('Workflow is restricted to another Project');
67
+ const testStep = testStepId === undefined ? undefined : graph.order.find(step => step.id === testStepId);
68
+ if (testStepId !== undefined && !testStep)
69
+ throw new Error('Unknown test step');
70
+ this.check(testStep ? [testStep] : graph.order, session);
71
+ const parsed = parseValue(testStep ? graph.inputSchemas.get(testStep.id) : graph.definition.inputSchema, input);
72
+ const record = {
73
+ version: 1, id: randomUUID(), sessionId: session.sessionId, scope: session.scope,
74
+ definition: graph.definition, input: parsed, status: 'running', startedAt: Date.now(),
75
+ ...(launchId ? { launchId } : {}),
76
+ steps: Object.fromEntries(graph.order.map(step => [step.id, { status: testStep && step.id !== testStep.id ? 'skipped' : 'pending', attempts: [] }])),
77
+ ...(testStepId === undefined ? { loops: Object.fromEntries(graph.loops.map(loop => [loop.headerId, { activation: 0, try: 0, phase: 'inactive', grants: [] }])) } : { testStepId }),
78
+ };
79
+ this.store.saveExecution(record);
80
+ const active = this.install(record);
81
+ this.pump(active);
82
+ return structuredClone(record);
83
+ }
84
+ get(sessionId, executionId) {
85
+ const active = this.active.get(executionId);
86
+ if (active?.record.sessionId === sessionId)
87
+ return structuredClone(active.record);
88
+ return this.store.getExecution(sessionId, executionId);
89
+ }
90
+ wait(sessionId, executionId) {
91
+ const active = this.require(sessionId, executionId);
92
+ if (active.persistenceError)
93
+ return Promise.reject(active.persistenceError);
94
+ if (active.record.status !== 'running' && !active.running.size)
95
+ return Promise.resolve(structuredClone(active.record));
96
+ return new Promise((resolve, reject) => active.waiters.push({ resolve, reject }));
97
+ }
98
+ async cancel(sessionId, executionId) {
99
+ const active = this.require(sessionId, executionId);
100
+ if (!occupied(active.record))
101
+ return structuredClone(active.record);
102
+ active.stopped = true;
103
+ active.record.status = 'cancelled';
104
+ for (const step of Object.values(active.record.steps))
105
+ if (['pending', 'blocked', 'running', 'interrupted'].includes(step.status))
106
+ step.status = 'cancelled';
107
+ this.persist(active);
108
+ for (const running of active.running.values())
109
+ running.controller.abort();
110
+ await Promise.all([...active.running.values()].map(running => running.done));
111
+ active.record.finishedAt = Date.now();
112
+ this.persist(active);
113
+ this.settle(active);
114
+ return structuredClone(active.record);
115
+ }
116
+ async interrupt(sessionId, executionId) {
117
+ const active = this.require(sessionId, executionId);
118
+ if (!occupied(active.record))
119
+ return structuredClone(active.record);
120
+ active.stopped = true;
121
+ active.record.status = 'recovery-required';
122
+ for (const step of Object.values(active.record.steps)) {
123
+ if (step.status !== 'running')
124
+ continue;
125
+ step.status = 'interrupted';
126
+ const attempt = step.attempts.at(-1);
127
+ attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
128
+ attempt.finishedAt = Date.now();
129
+ }
130
+ this.persist(active);
131
+ for (const running of active.running.values())
132
+ running.controller.abort();
133
+ await Promise.all([...active.running.values()].map(running => running.done));
134
+ this.settle(active);
135
+ return structuredClone(active.record);
136
+ }
137
+ recover(session, executionId, action) {
138
+ const active = this.require(session.sessionId, executionId);
139
+ const record = active.record;
140
+ if (record.status !== 'recovery-required' || active.running.size)
141
+ throw new Error('Execution is not ready for recovery');
142
+ if (record.definition.backend !== session.backend || record.scope !== session.scope)
143
+ throw new Error('Recovery requires the original Scope and Backend Adapter');
144
+ 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);
145
+ const limits = Object.entries(record.loops ?? {}).filter(([, loop]) => loop.phase === 'limit');
146
+ if (action.kind === 'continue' && limits.length)
147
+ throw new WorkflowLoopConflict('Loop limit requires an extra try or cancellation');
148
+ if (action.kind === 'extend-loop') {
149
+ const loop = record.loops?.[action.headerId];
150
+ if (!loop || loop.phase !== 'limit' || loop.activation !== action.activation || loop.try !== action.try || loop.grants.some(grant => grant.activation === action.activation && grant.try === action.try + 1))
151
+ throw new WorkflowLoopConflict('Loop limit decision is no longer available');
152
+ if (action.guidance !== undefined && (typeof action.guidance !== 'string' || action.guidance.length > 100_000))
153
+ throw new Error('Invalid loop guidance');
154
+ loop.grants.push({ activation: loop.activation, try: loop.try + 1, ...(action.guidance === undefined ? {} : { guidance: action.guidance }) });
155
+ loop.phase = 'active';
156
+ }
157
+ else if (action.kind !== 'continue') {
158
+ const step = active.graph.order.find(step => step.id === action.stepId);
159
+ const state = record.steps[action.stepId];
160
+ if (!step || !state || !['interrupted', 'failed', 'timed-out'].includes(state.status))
161
+ throw new Error('Step does not require recovery');
162
+ if (state.status !== 'interrupted' && !record.testStepId && !state.recovery && active.graph.outgoing.get(step.id).some(edge => edge.outcome === state.outcome))
163
+ throw new Error('Recover the failed handling step, not the handled failure');
164
+ if (action.kind === 'supply') {
165
+ const output = this.validateOutput(active, step, action.output);
166
+ 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) } : {}) };
167
+ state.attempts.push(attempt);
168
+ state.output = output;
169
+ state.status = 'completed';
170
+ state.outcome = step.kind === 'branch' ? output ? 'true' : 'false' : 'success';
171
+ }
172
+ else {
173
+ this.check([step], session);
174
+ state.status = 'pending';
175
+ delete state.outcome;
176
+ }
177
+ if (!record.testStepId) {
178
+ const affected = new Set([step.id]);
179
+ for (const downstream of active.graph.order) {
180
+ const next = record.steps[downstream.id];
181
+ if (!['pending', 'blocked', 'skipped'].includes(next.status) || !active.graph.forwardIncoming.get(downstream.id).some(edge => affected.has(edge.from)))
182
+ continue;
183
+ const exited = active.graph.loops.filter(loop => loop.memberIds.includes(downstream.id)).map(loop => record.loops[loop.headerId]).filter(loop => loop.phase === 'exited');
184
+ if (exited.some(loop => loop.try > 0))
185
+ continue;
186
+ for (const loop of exited)
187
+ loop.phase = 'inactive';
188
+ affected.add(downstream.id);
189
+ next.status = 'pending';
190
+ }
191
+ }
192
+ }
193
+ else if (Object.values(record.steps).some(step => ['interrupted', 'failed', 'timed-out'].includes(step.status) && !step.outcome))
194
+ throw new Error('Recover interrupted steps first');
195
+ for (const step of Object.values(record.steps))
196
+ if (step.status === 'blocked' || (step.status === 'skipped' && !record.testStepId && !active.graph.loops.length))
197
+ step.status = 'pending';
198
+ record.status = 'running';
199
+ delete record.finishedAt;
200
+ active.stopped = false;
201
+ delete active.persistenceError;
202
+ this.persist(active);
203
+ this.pump(active);
204
+ return structuredClone(record);
205
+ }
206
+ check(steps, session) {
207
+ for (const step of steps) {
208
+ if (step.kind === 'branch' || step.kind === 'join')
209
+ continue;
210
+ const executor = this.executors[step.kind];
211
+ if (!executor)
212
+ throw new Error(`Executor is unavailable: ${step.kind}`);
213
+ executor.check(step, session);
214
+ }
215
+ }
216
+ install(record) {
217
+ const active = { record, graph: validateDefinition(record.definition), running: new Map(), waiters: [], stopped: record.status !== 'running' };
218
+ this.active.set(record.id, active);
219
+ this.slots.set(record.sessionId, record.id);
220
+ return active;
221
+ }
222
+ require(sessionId, executionId) {
223
+ const active = this.active.get(executionId);
224
+ if (!active || active.record.sessionId !== sessionId)
225
+ throw new Error('Unknown workflow execution');
226
+ return active;
227
+ }
228
+ edgeState(active, edge) {
229
+ if (!active.record.testStepId && active.graph.loops.some(loop => loop.exitEdgeIds.includes(edge.id) && active.record.loops?.[loop.headerId]?.phase !== 'exited'))
230
+ return 'waiting';
231
+ const state = active.record.steps[edge.from];
232
+ if (state.status === 'pending' || state.status === 'running')
233
+ return 'waiting';
234
+ if (state.status === 'skipped' || state.status === 'cancelled')
235
+ return 'skipped';
236
+ if (state.status === 'blocked' || state.status === 'interrupted')
237
+ return 'blocked';
238
+ if (state.outcome === edge.outcome && !(state.recovery && state.status !== 'completed'))
239
+ return 'selected';
240
+ if (state.status === 'completed')
241
+ return 'skipped';
242
+ const handled = !state.recovery && active.graph.outgoing.get(edge.from).some(candidate => candidate.outcome === state.outcome);
243
+ return handled || edge.outcome === 'failure' || edge.outcome === 'timeout' ? 'skipped' : 'blocked';
244
+ }
245
+ pump(active) {
246
+ if (active.stopped || active.record.status !== 'running')
247
+ return;
248
+ this.transitionLoops(active);
249
+ for (const step of active.graph.order) {
250
+ const state = active.record.steps[step.id];
251
+ if (state.status !== 'pending')
252
+ continue;
253
+ if (active.graph.loops.some(loop => loop.memberIds.includes(step.id) && active.record.loops?.[loop.headerId]?.phase === 'limit'))
254
+ continue;
255
+ const header = active.record.loops?.[step.id];
256
+ const edges = active.record.testStepId || (header && header.phase === 'active' && header.try > 1) ? [] : active.graph.forwardIncoming.get(step.id);
257
+ const statuses = edges.map(edge => this.edgeState(active, edge));
258
+ if (statuses.includes('waiting'))
259
+ continue;
260
+ if (statuses.includes('blocked')) {
261
+ state.status = 'blocked';
262
+ continue;
263
+ }
264
+ if (edges.length && !statuses.includes('selected')) {
265
+ state.status = 'skipped';
266
+ continue;
267
+ }
268
+ const selected = edges.filter((_, index) => statuses[index] === 'selected');
269
+ if (!active.record.testStepId) {
270
+ let limited = false;
271
+ for (const loop of active.graph.loops) {
272
+ const runtime = active.record.loops[loop.headerId];
273
+ if (runtime.phase === 'active' && loop.memberIds.includes(step.id) && step.id !== loop.headerId && active.record.steps[loop.headerId].status === 'completed' && this.repeatOnly(active, loop, step.id)) {
274
+ if (!this.reserveTry(active, loop))
275
+ limited = true;
276
+ }
277
+ }
278
+ if (limited)
279
+ continue;
280
+ if (header?.phase === 'inactive') {
281
+ header.activation++;
282
+ header.try = 1;
283
+ header.phase = 'active';
284
+ delete header.headerInput;
285
+ }
286
+ }
287
+ state.recovery = !!header?.headerRecovery || selected.some(edge => edge.outcome === 'failure' || edge.outcome === 'timeout' || active.record.steps[edge.from].recovery);
288
+ const controller = new AbortController();
289
+ const identities = active.graph.loops.filter(loop => !active.record.testStepId && loop.memberIds.includes(step.id)).map(loop => ({ headerId: loop.headerId, activation: active.record.loops[loop.headerId].activation, try: active.record.loops[loop.headerId].try }));
290
+ const previous = state.attempts.at(-1);
291
+ const retry = previous && isDeepStrictEqual(previous.loops ?? [], identities);
292
+ let input = null;
293
+ let inputError;
294
+ try {
295
+ input = retry ? previous.input : header?.headerInput !== undefined ? header.headerInput : this.input(active, step, selected);
296
+ }
297
+ catch (error) {
298
+ inputError = error;
299
+ }
300
+ state.attempts.push({ number: state.attempts.length + 1, action: retry ? 'retry' : 'execute', startedAt: Date.now(), input, ...(identities.length ? { loops: identities } : {}) });
301
+ const done = Promise.resolve().then(() => this.execute(active, step, controller, inputError)).finally(() => {
302
+ active.running.delete(step.id);
303
+ if (active.stopped) {
304
+ if (!active.running.size && active.persistenceError)
305
+ this.settle(active);
306
+ return;
307
+ }
308
+ this.pump(active);
309
+ }).catch(error => {
310
+ active.persistenceError = error;
311
+ active.stopped = true;
312
+ if (!active.running.size)
313
+ this.settle(active);
314
+ });
315
+ state.status = 'running';
316
+ active.running.set(step.id, { controller, done });
317
+ }
318
+ this.persist(active);
319
+ if (active.running.size)
320
+ return;
321
+ if (this.transitionLoops(active)) {
322
+ this.persist(active);
323
+ this.pump(active);
324
+ return;
325
+ }
326
+ const states = Object.entries(active.record.steps);
327
+ 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))));
328
+ if (unresolved)
329
+ active.record.status = 'recovery-required';
330
+ else {
331
+ 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')));
332
+ 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]));
333
+ 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';
334
+ active.record.finishedAt = Date.now();
335
+ }
336
+ this.persist(active);
337
+ this.settle(active);
338
+ }
339
+ repeatOnly(active, loop, id) {
340
+ const seen = new Set();
341
+ const pending = [id];
342
+ while (pending.length) {
343
+ const current = pending.pop();
344
+ if (seen.has(current))
345
+ continue;
346
+ seen.add(current);
347
+ const step = active.graph.order.find(step => step.id === current);
348
+ const edges = active.graph.outgoing.get(current);
349
+ for (const outcome of step.kind === 'branch' ? ['true', 'false'] : ['success']) {
350
+ const selected = edges.filter(edge => edge.outcome === outcome);
351
+ if (!selected.length)
352
+ return false;
353
+ for (const edge of selected) {
354
+ if (loop.backEdgeIds.includes(edge.id))
355
+ continue;
356
+ if (!loop.memberIds.includes(edge.to))
357
+ return false;
358
+ pending.push(edge.to);
359
+ }
360
+ }
361
+ }
362
+ return true;
363
+ }
364
+ reserveTry(active, loop) {
365
+ const state = active.record.loops[loop.headerId];
366
+ if (state.phase === 'repeating')
367
+ return true;
368
+ if (state.try >= loop.maxTries && !state.grants.some(grant => grant.activation === state.activation && grant.try === state.try + 1)) {
369
+ state.phase = 'limit';
370
+ return false;
371
+ }
372
+ state.try++;
373
+ state.phase = 'repeating';
374
+ return true;
375
+ }
376
+ transitionLoops(active) {
377
+ if (active.record.testStepId)
378
+ return false;
379
+ let changed = false;
380
+ for (const loop of [...active.graph.loops].reverse()) {
381
+ const runtime = active.record.loops[loop.headerId];
382
+ if (runtime.phase === 'exited' || runtime.phase === 'limit')
383
+ continue;
384
+ if (loop.memberIds.some(id => active.running.has(id) || ['pending', 'running', 'interrupted', 'blocked'].includes(active.record.steps[id].status)))
385
+ continue;
386
+ if (active.graph.loops.some(child => child.headerId !== loop.headerId && loop.memberIds.includes(child.headerId) && active.record.loops[child.headerId].phase !== 'exited'))
387
+ continue;
388
+ const failed = loop.memberIds.some(id => {
389
+ const state = active.record.steps[id];
390
+ return ['failed', 'timed-out'].includes(state.status) && (state.recovery || !active.graph.outgoing.get(id).some(edge => edge.outcome === state.outcome));
391
+ });
392
+ if (failed)
393
+ continue;
394
+ const back = active.graph.definition.edges.filter(edge => loop.backEdgeIds.includes(edge.id) && this.edgeState(active, edge) === 'selected');
395
+ if (back.length) {
396
+ if (!this.reserveTry(active, loop)) {
397
+ changed = true;
398
+ continue;
399
+ }
400
+ const header = active.graph.order.find(step => step.id === loop.headerId);
401
+ const { mapping: _, ...unmapped } = header;
402
+ const repeated = { ...unmapped, ...(header.repeatMapping ? { mapping: header.repeatMapping } : {}) };
403
+ const input = this.input(active, repeated, back);
404
+ runtime.headerInput = structuredClone(parseValue(active.graph.repeatInputSchemas.get(header.id), input));
405
+ runtime.headerRecovery = back.some(edge => edge.outcome === 'failure' || edge.outcome === 'timeout' || active.record.steps[edge.from].recovery);
406
+ runtime.phase = 'active';
407
+ for (const id of loop.memberIds) {
408
+ const state = active.record.steps[id];
409
+ state.status = 'pending';
410
+ delete state.output;
411
+ delete state.outcome;
412
+ delete state.recovery;
413
+ }
414
+ for (const child of active.graph.loops.filter(child => child.headerId !== loop.headerId && loop.memberIds.includes(child.headerId))) {
415
+ const state = active.record.loops[child.headerId];
416
+ state.phase = 'inactive';
417
+ state.try = 0;
418
+ delete state.headerInput;
419
+ delete state.headerRecovery;
420
+ }
421
+ changed = true;
422
+ }
423
+ else {
424
+ runtime.phase = 'exited';
425
+ changed = true;
426
+ }
427
+ }
428
+ return changed;
429
+ }
430
+ guidedStep(active, step, attempt) {
431
+ const copy = structuredClone(step);
432
+ if (copy.kind === 'agent') {
433
+ for (const identity of attempt.loops ?? []) {
434
+ const grant = active.record.loops[identity.headerId].grants.find(grant => grant.activation === identity.activation && grant.try === identity.try);
435
+ if (grant?.guidance)
436
+ copy.instructions += '\nExtra try guidance:\n' + grant.guidance;
437
+ }
438
+ }
439
+ return copy;
440
+ }
441
+ settle(active) {
442
+ if (!occupied(active.record))
443
+ this.slots.delete(active.record.sessionId);
444
+ for (const waiter of active.waiters.splice(0)) {
445
+ if (active.persistenceError)
446
+ waiter.reject(active.persistenceError);
447
+ else
448
+ waiter.resolve(structuredClone(active.record));
449
+ }
450
+ }
451
+ persist(active) {
452
+ try {
453
+ this.store.saveExecution(active.record);
454
+ }
455
+ catch (error) {
456
+ active.persistenceError = error;
457
+ active.stopped = true;
458
+ active.record.status = 'recovery-required';
459
+ for (const step of Object.values(active.record.steps)) {
460
+ if (step.status !== 'running')
461
+ continue;
462
+ step.status = 'interrupted';
463
+ const attempt = step.attempts.at(-1);
464
+ attempt.error = { kind: 'interrupted', message: 'Workflow storage failed; effects may already have occurred' };
465
+ attempt.finishedAt = Date.now();
466
+ }
467
+ for (const running of active.running.values())
468
+ running.controller.abort();
469
+ throw error;
470
+ }
471
+ }
472
+ input(active, step, edges) {
473
+ if (active.record.testStepId)
474
+ return active.record.input;
475
+ if (step.mapping) {
476
+ const mapped = resolveMapping(active.record, step);
477
+ if (mapped === undefined)
478
+ throw new Error('Mapped input is missing');
479
+ return mapped;
480
+ }
481
+ if (!edges.length)
482
+ return active.record.input;
483
+ const inputs = edges.map(edge => {
484
+ const source = active.record.steps[edge.from];
485
+ const attempt = source.attempts.at(-1);
486
+ const value = edge.outcome === 'failure' || edge.outcome === 'timeout' ? {
487
+ input: attempt.input, error: { ...attempt.error }, ...(attempt.partialOutput === undefined ? {} : { partialOutput: attempt.partialOutput }),
488
+ } : source.output;
489
+ return [active.graph.order.find(candidate => candidate.id === edge.from).name, value];
490
+ });
491
+ return inputs.length === 1 && step.kind !== 'join' ? inputs[0][1] : Object.fromEntries(inputs);
492
+ }
493
+ validateOutput(active, step, value) {
494
+ if (step.kind === 'mcp')
495
+ return validateMcpOutput(step.tool, value);
496
+ const output = parseValue(declaredOutputSchema(step) ?? active.graph.outputSchemas.get(step.id), value);
497
+ if (step.kind === 'shell' && !(step.acceptedExitCodes ?? [0]).includes(output.exitCode))
498
+ throw new WorkflowStepError('Shell exit code was not accepted', output);
499
+ return output;
500
+ }
501
+ async execute(active, step, controller, inputError) {
502
+ const state = active.record.steps[step.id];
503
+ if (active.stopped) {
504
+ state.attempts.at(-1).finishedAt ??= Date.now();
505
+ this.persist(active);
506
+ return;
507
+ }
508
+ const attempt = state.attempts.at(-1);
509
+ let timer;
510
+ let timedOut = false;
511
+ try {
512
+ if (inputError)
513
+ throw inputError;
514
+ if (step.inputSchema)
515
+ attempt.input = parseValue(step.inputSchema, attempt.input);
516
+ this.persist(active);
517
+ const timeout = step.timeoutMs ?? (step.kind === 'shell' || step.kind === 'typescript' || step.kind === 'mcp' ? 60_000 : undefined);
518
+ if (timeout !== undefined)
519
+ timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeout);
520
+ let value;
521
+ if (step.kind === 'join')
522
+ value = attempt.input;
523
+ else if (step.kind === 'branch') {
524
+ const actual = valueAt(attempt.input, step.condition.path);
525
+ const condition = step.condition;
526
+ switch (condition.operator) {
527
+ case 'truthy':
528
+ if (typeof actual !== 'boolean')
529
+ throw new Error('Branch condition requires a boolean');
530
+ value = actual;
531
+ break;
532
+ case 'equals':
533
+ value = isDeepStrictEqual(actual, condition.value);
534
+ break;
535
+ case 'not-equals':
536
+ value = !isDeepStrictEqual(actual, condition.value);
537
+ break;
538
+ case 'greater-than':
539
+ case 'less-than':
540
+ if (typeof actual !== 'number')
541
+ throw new Error('Branch condition requires a number');
542
+ value = condition.operator === 'greater-than' ? actual > condition.value : actual < condition.value;
543
+ break;
544
+ }
545
+ }
546
+ else
547
+ 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 });
548
+ if (active.stopped)
549
+ return;
550
+ if (timedOut)
551
+ throw new WorkflowStepError('Step timed out', value);
552
+ const output = this.validateOutput(active, step, value);
553
+ state.status = 'completed';
554
+ state.output = output;
555
+ state.outcome = step.kind === 'branch' ? output ? 'true' : 'false' : 'success';
556
+ attempt.output = output;
557
+ }
558
+ catch (error) {
559
+ if (active.stopped)
560
+ return;
561
+ state.status = timedOut ? 'timed-out' : 'failed';
562
+ state.outcome = timedOut ? 'timeout' : 'failure';
563
+ attempt.error = { kind: state.outcome, message: timedOut ? 'Step timed out' : error instanceof Error ? error.message : String(error) };
564
+ if (error instanceof WorkflowStepError && error.partialOutput !== undefined)
565
+ attempt.partialOutput = structuredClone(error.partialOutput);
566
+ }
567
+ finally {
568
+ clearTimeout(timer);
569
+ attempt.finishedAt ??= Date.now();
570
+ this.persist(active);
571
+ }
572
+ }
573
+ }