@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.
Files changed (73) hide show
  1. package/README.md +18 -0
  2. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
  3. package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-6L5KCQWJ.mjs} +99 -21
  4. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-QNU2YE4G.mjs} +45 -13
  5. package/build/backend-worker.mjs +48 -7
  6. package/dist/backend/claude/background-calls.js +7 -3
  7. package/dist/backend/claude/index.js +72 -10
  8. package/dist/backend/claude/subagents.js +30 -9
  9. package/dist/backend/fake/index.js +36 -6
  10. package/dist/backend/pi/index.js +34 -2
  11. package/dist/backend/pi/state.js +16 -1
  12. package/dist/backend/pi/subagents.js +7 -3
  13. package/dist/backend/worker/claude-state.js +22 -0
  14. package/dist/backend/worker/entry.js +25 -6
  15. package/dist/backend/worker/index.js +30 -5
  16. package/dist/backend/worker/protocol.js +1 -1
  17. package/dist/backend/worker/rpc.js +13 -0
  18. package/dist/backend/worker/sandbox-mcp.js +18 -7
  19. package/dist/backend/workflow-tools.js +9 -7
  20. package/dist/build-id +1 -1
  21. package/dist/cli/bootstrap.js +1 -1
  22. package/dist/client/reduce.js +29 -3
  23. package/dist/client/subagent-tree.js +49 -0
  24. package/dist/daemon/git.js +10 -7
  25. package/dist/daemon/host.js +226 -26
  26. package/dist/daemon/runtime.js +71 -3
  27. package/dist/daemon/server.js +3 -0
  28. package/dist/daemon/store.js +2 -0
  29. package/dist/daemon/workflow-builder-guidance.js +1 -1
  30. package/dist/daemon/workflow-builder.js +36 -11
  31. package/dist/daemon/workflow-environment.js +191 -0
  32. package/dist/daemon/workflow-execution-launch.js +77 -0
  33. package/dist/daemon/workflow-execution-resources.js +76 -0
  34. package/dist/daemon/workflow-execution-routes.js +9 -6
  35. package/dist/daemon/workflow-execution-values.js +128 -0
  36. package/dist/daemon/workflow-executions.js +382 -300
  37. package/dist/daemon/workflow-routes.js +39 -0
  38. package/dist/daemon/workflow-schedule-driver.js +247 -0
  39. package/dist/daemon/workflow-schedule-routes.js +137 -0
  40. package/dist/daemon/workflow-schedules.js +341 -0
  41. package/dist/isolation/sandbox.js +30 -14
  42. package/dist/isolation/shared-sandbox.js +3 -3
  43. package/dist/protocol/events.js +2 -0
  44. package/dist/protocol/workflow-schedules.js +1 -0
  45. package/dist/tui/render.js +7 -1
  46. package/dist/workflows/calls.js +53 -0
  47. package/dist/workflows/errors.js +2 -0
  48. package/dist/workflows/executors.js +1 -1
  49. package/dist/workflows/graph.js +78 -4
  50. package/dist/workflows/invocations.js +23 -0
  51. package/dist/workflows/owner.js +45 -0
  52. package/dist/workflows/records.js +124 -8
  53. package/dist/workflows/recovery.js +37 -1
  54. package/dist/workflows/schedule-errors.js +2 -0
  55. package/dist/workflows/schedule-store.js +385 -0
  56. package/dist/workflows/scheduler.js +351 -92
  57. package/dist/workflows/schedules.js +129 -0
  58. package/dist/workflows/schema.js +2 -0
  59. package/dist/workflows/store.js +110 -11
  60. package/package.json +2 -1
  61. package/web/dist/assets/index-BGu3YSP7.css +2 -0
  62. package/web/dist/assets/index-Miy2nveb.js +40 -0
  63. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-Vf_fCXyE.js} +1 -1
  64. package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
  65. package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
  66. package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
  67. package/web/dist/index.html +4 -3
  68. package/web/dist/assets/index-DRfeO6GJ.js +0 -40
  69. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  70. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  71. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  72. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  73. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
@@ -0,0 +1,341 @@
1
+ import { ScheduleValidationError } from "../workflows/schedule-errors.js";
2
+ import { WorkflowScheduleStore, ScheduleRecordNotFound, ScheduleRevisionConflict } from "../workflows/schedule-store.js";
3
+ import { advancePast, createSchedule, editSchedule, isActiveOccurrence, LIVE_DISPATCH_TOLERANCE_MS, nextOccurrence, occurrenceId, occurrenceSettings, projectExecution } from "../workflows/schedules.js";
4
+ export class ScheduledExecutionStarted extends Error {
5
+ executionId;
6
+ constructor(executionId, options) {
7
+ super('Scheduled execution requires reconciliation', options);
8
+ this.executionId = executionId;
9
+ }
10
+ }
11
+ export class WorkflowScheduleService {
12
+ store;
13
+ driver;
14
+ now;
15
+ queue = Promise.resolve();
16
+ launches = new Map();
17
+ pendingUpdates = new Map();
18
+ occurrenceQueues = new Map();
19
+ reconciliations = new Set();
20
+ startupMisses = new Map();
21
+ reconciling = new Map();
22
+ cleanups = new Map();
23
+ timer;
24
+ stopped = true;
25
+ constructor(store, driver, now = Date.now) {
26
+ this.store = store;
27
+ this.driver = driver;
28
+ this.now = now;
29
+ store.setOccurrenceProjection(occurrence => this.project(occurrence));
30
+ }
31
+ project(occurrence) {
32
+ const pending = this.pendingUpdates.get(occurrence.id);
33
+ const saved = structuredClone(pending ? { ...occurrence, status: pending.status,
34
+ ...(!occurrence.executionId && pending.executionId ? { executionId: pending.executionId } : {}),
35
+ ...(!occurrence.sessionId && pending.sessionId ? { sessionId: pending.sessionId } : {}),
36
+ ...(pending.finishedAt === undefined ? {} : { finishedAt: pending.finishedAt }),
37
+ ...(pending.outcome === undefined ? {} : { outcome: pending.outcome }) } : occurrence);
38
+ try {
39
+ const execution = this.driver.current?.(saved);
40
+ return execution ? projectExecution(saved, execution, this.now()) : saved;
41
+ }
42
+ catch {
43
+ console.error('Workflow Occurrence checkpoint is unavailable. Its durable state will be retained for reconciliation.');
44
+ return saved;
45
+ }
46
+ }
47
+ persist(occurrence) {
48
+ if (!isActiveOccurrence(this.store.getStoredOccurrence(occurrence.id))) {
49
+ this.pendingUpdates.delete(occurrence.id);
50
+ return;
51
+ }
52
+ this.pendingUpdates.set(occurrence.id, occurrence);
53
+ try {
54
+ this.store.saveOccurrence(occurrence);
55
+ }
56
+ catch (error) {
57
+ if (isActiveOccurrence(this.store.getStoredOccurrence(occurrence.id)))
58
+ throw error;
59
+ }
60
+ this.pendingUpdates.delete(occurrence.id);
61
+ }
62
+ flushPending() {
63
+ let failed = false;
64
+ for (const occurrence of this.pendingUpdates.values()) {
65
+ try {
66
+ const saved = this.store.getStoredOccurrence(occurrence.id);
67
+ if (!isActiveOccurrence(saved))
68
+ this.pendingUpdates.delete(occurrence.id);
69
+ else if (!this.occurrenceQueues.has(occurrence.id))
70
+ this.persist(this.project(saved));
71
+ }
72
+ catch (error) {
73
+ if (error instanceof ScheduleRecordNotFound) {
74
+ this.pendingUpdates.delete(occurrence.id);
75
+ continue;
76
+ }
77
+ failed = true;
78
+ console.error('Workflow Occurrence status could not be saved. Its pending update will be retained for retry.');
79
+ }
80
+ }
81
+ return failed;
82
+ }
83
+ forOccurrence(id, run) {
84
+ const next = (this.occurrenceQueues.get(id) ?? Promise.resolve()).then(run);
85
+ const tail = next.catch(() => { }).finally(() => { if (this.occurrenceQueues.get(id) === tail)
86
+ this.occurrenceQueues.delete(id); });
87
+ this.occurrenceQueues.set(id, tail);
88
+ return next;
89
+ }
90
+ reconcilePending() {
91
+ return Promise.all([...this.reconciliations].map(id => {
92
+ const existing = this.reconciling.get(id);
93
+ if (existing)
94
+ return existing;
95
+ const done = this.forOccurrence(id, async () => {
96
+ try {
97
+ const occurrence = this.store.getOccurrence(id);
98
+ if (isActiveOccurrence(occurrence))
99
+ await this.driver.reconcile(occurrence);
100
+ this.reconciliations.delete(id);
101
+ }
102
+ catch {
103
+ console.error('Workflow Occurrence reconciliation failed. Durable work will be retained for retry without replay.');
104
+ }
105
+ }).finally(() => { this.reconciling.delete(id); });
106
+ this.reconciling.set(id, done);
107
+ return done;
108
+ })).then(() => { });
109
+ }
110
+ sweepUnstartedCleanup() {
111
+ if (!this.driver.cleanupUnstarted)
112
+ return;
113
+ for (const id of this.store.pendingUnstartedCleanup()) {
114
+ if (this.cleanups.has(id))
115
+ continue;
116
+ const done = this.forOccurrence(id, async () => {
117
+ try {
118
+ const occurrence = this.store.getStoredOccurrence(id);
119
+ if (isActiveOccurrence(occurrence))
120
+ return;
121
+ this.store.prepareUnstartedCleanup(id);
122
+ await this.driver.cleanupUnstarted(occurrence);
123
+ this.store.completeUnstartedCleanup(id);
124
+ }
125
+ catch (error) {
126
+ if (!(error instanceof ScheduleRecordNotFound))
127
+ console.error('Workflow Occurrence resource cleanup failed. Its journal and owned work will be retained for retry.');
128
+ }
129
+ }).finally(() => { this.cleanups.delete(id); });
130
+ this.cleanups.set(id, done);
131
+ }
132
+ }
133
+ serial(run) {
134
+ const next = this.queue.then(run);
135
+ this.queue = next.catch(() => { });
136
+ return next;
137
+ }
138
+ async start(timers = true) {
139
+ for (const occurrence of this.store.listActiveOccurrences())
140
+ this.reconciliations.add(occurrence.id);
141
+ await this.reconcilePending();
142
+ await this.serial(() => {
143
+ this.stopped = false;
144
+ try {
145
+ this.dispatch(true);
146
+ }
147
+ catch {
148
+ console.error('Workflow Schedule startup admission failed. The Session Host will retry.');
149
+ }
150
+ });
151
+ this.sweepUnstartedCleanup();
152
+ if (timers)
153
+ this.arm();
154
+ }
155
+ arm(retryDelay) {
156
+ if (this.stopped)
157
+ return;
158
+ const due = Math.min(...this.store.listSchedules().flatMap(schedule => schedule.nextDue === undefined ? [] : [schedule.nextDue]));
159
+ const delay = retryDelay ?? Math.max(1, Math.min(30_000, due - this.now()));
160
+ this.timer = setTimeout(() => {
161
+ void this.tick().then(() => this.arm(), () => {
162
+ console.error('Workflow Schedule admission failed. The Session Host will retry.');
163
+ this.arm(1000);
164
+ });
165
+ }, delay);
166
+ this.timer.unref();
167
+ }
168
+ tick() {
169
+ return this.serial(() => { if (!this.stopped)
170
+ this.dispatch(false); }).finally(() => {
171
+ if (!this.stopped) {
172
+ void this.reconcilePending();
173
+ this.sweepUnstartedCleanup();
174
+ }
175
+ });
176
+ }
177
+ dispatch(startup) {
178
+ let failed = this.flushPending();
179
+ for (const schedule of this.store.listSchedules()) {
180
+ try {
181
+ this.admit(schedule, startup);
182
+ }
183
+ catch {
184
+ failed = true;
185
+ }
186
+ }
187
+ if (failed)
188
+ throw new Error('Workflow Schedule admission failed');
189
+ }
190
+ admit(schedule, startup) {
191
+ const now = this.now(), due = schedule.nextDue;
192
+ if (!schedule.enabled || due === undefined || due > now)
193
+ return;
194
+ const id = occurrenceId(schedule.id, schedule.activation, due);
195
+ if (startup)
196
+ this.startupMisses.set(schedule.id, id);
197
+ const missed = startup || this.startupMisses.get(schedule.id) === id || now - due > LIVE_DISPATCH_TOLERANCE_MS;
198
+ const next = advancePast(schedule.timing, due, now);
199
+ const active = this.store.activeCount(schedule.id);
200
+ const status = missed ? 'missed' : active >= schedule.concurrency ? 'capacity-skipped' : 'provisioning';
201
+ const occurrence = { version: 1, id, scheduleId: schedule.id, activation: schedule.activation, revision: schedule.revision, scheduledAt: due,
202
+ settings: occurrenceSettings(schedule), status, createdAt: now,
203
+ ...(missed ? { missedThrough: now } : {}), ...(status === 'provisioning' ? {} : { finishedAt: now }) };
204
+ const claimed = this.store.claimOccurrence(occurrence);
205
+ try {
206
+ this.store.advanceCursor(schedule.id, schedule.revision, due, next);
207
+ }
208
+ catch (error) {
209
+ if (claimed && status === 'provisioning')
210
+ this.interruptClaim(occurrence);
211
+ throw error;
212
+ }
213
+ this.startupMisses.delete(schedule.id);
214
+ if (!claimed) {
215
+ const saved = this.store.getOccurrence(occurrence.id);
216
+ if (saved.status === 'provisioning' && !this.launches.has(saved.id) && !this.reconciliations.has(saved.id) && !this.occurrenceQueues.has(saved.id) && !this.driver.current?.(saved))
217
+ this.interruptClaim(saved);
218
+ return;
219
+ }
220
+ if (status !== 'provisioning')
221
+ return;
222
+ const controller = new AbortController();
223
+ const done = this.forOccurrence(occurrence.id, () => this.launch(occurrence, controller.signal))
224
+ .catch(() => { console.error('Workflow Occurrence status could not be saved. Its durable claim or execution will be retained.'); })
225
+ .finally(() => { this.launches.delete(occurrence.id); this.sweepUnstartedCleanup(); });
226
+ this.launches.set(occurrence.id, { done, controller });
227
+ }
228
+ interruptClaim(occurrence) {
229
+ this.persist({ ...occurrence, status: 'interrupted', finishedAt: this.now(), outcome: 'Admission stopped before provisioning. This occurrence will not be replayed.' });
230
+ }
231
+ async launch(occurrence, signal) {
232
+ try {
233
+ signal.throwIfAborted();
234
+ const current = this.store.getSchedule(occurrence.scheduleId);
235
+ if (this.stopped || !current.enabled || current.revision !== occurrence.revision || current.activation !== occurrence.activation) {
236
+ this.interruptClaim(occurrence);
237
+ return;
238
+ }
239
+ await this.driver.launch(occurrence, signal);
240
+ }
241
+ catch (error) {
242
+ const saved = this.store.getOccurrence(occurrence.id);
243
+ const execution = this.driver.current?.(saved);
244
+ if (execution) {
245
+ this.result(execution);
246
+ return;
247
+ }
248
+ if (error instanceof ScheduledExecutionStarted) {
249
+ this.persist({ ...saved, executionId: error.executionId, status: 'recovery-required', outcome: 'Launch bookkeeping failed after execution started; effects may have occurred. Recovery is required.' });
250
+ }
251
+ else if (saved.status === 'provisioning') {
252
+ this.persist({ ...saved, status: signal.aborted ? (this.stopped ? 'interrupted' : 'cancelled') : 'launch-failed', finishedAt: this.now(),
253
+ outcome: signal.aborted ? 'Provisioning stopped before execution.' : 'Scheduled launch failed validation or provisioning. Check the saved workflow, Project, runtime and MCP configuration.' });
254
+ }
255
+ }
256
+ }
257
+ create(settings, enabled) {
258
+ return this.serial(async () => { await this.driver.validate(settings); const saved = createSchedule(settings, this.now(), enabled); this.store.saveSchedule(saved); return saved; });
259
+ }
260
+ update(id, revision, settings, enabled) {
261
+ return this.serial(async () => {
262
+ const current = this.store.getSchedule(id);
263
+ if (current.revision !== revision)
264
+ throw new ScheduleRevisionConflict();
265
+ await this.driver.validate(settings);
266
+ const saved = editSchedule(current, settings, enabled, this.now());
267
+ this.store.saveSchedule(saved, revision);
268
+ return saved;
269
+ });
270
+ }
271
+ pause(id, revision) {
272
+ return this.serial(() => {
273
+ const current = this.store.getSchedule(id);
274
+ if (current.revision !== revision)
275
+ throw new ScheduleRevisionConflict();
276
+ const saved = editSchedule(current, occurrenceSettings(current), false, this.now());
277
+ this.store.saveSchedule(saved, revision);
278
+ return saved;
279
+ });
280
+ }
281
+ delete(id, revision) { return this.serial(() => this.store.deleteSchedule(id, revision, this.now())); }
282
+ preview(settings) { return nextOccurrence(settings.timing, this.now()); }
283
+ retryAttachment(id) {
284
+ return this.forOccurrence(id, async () => {
285
+ const occurrence = this.store.getOccurrence(id);
286
+ if (occurrence.status !== 'recovery-required' || occurrence.association !== 'failed')
287
+ throw new ScheduleValidationError('Attachment is not available');
288
+ try {
289
+ await this.driver.reconcile(occurrence);
290
+ this.reconciliations.delete(id);
291
+ }
292
+ catch {
293
+ throw new Error('Workflow Occurrence attachment failed. Durable work has been retained.');
294
+ }
295
+ });
296
+ }
297
+ cancel(id) {
298
+ this.launches.get(id)?.controller.abort();
299
+ return this.forOccurrence(id, async () => {
300
+ const occurrence = this.store.getOccurrence(id);
301
+ try {
302
+ await this.driver.cancel(occurrence);
303
+ this.reconciliations.delete(id);
304
+ }
305
+ catch {
306
+ throw new Error('Workflow Occurrence cancellation failed. Durable work has been retained.');
307
+ }
308
+ }).finally(() => this.sweepUnstartedCleanup());
309
+ }
310
+ async prune() {
311
+ await this.serial(() => { this.flushPending(); });
312
+ this.sweepUnstartedCleanup();
313
+ return this.store.prune(this.now(), occurrence => this.forOccurrence(occurrence.id, () => this.driver.cleanup(occurrence)), id => !this.occurrenceQueues.has(id));
314
+ }
315
+ hasActiveWork() { return this.launches.size > 0 || this.store.activeCount() > 0; }
316
+ async stopAdmission() {
317
+ this.stopped = true;
318
+ clearTimeout(this.timer);
319
+ for (const launch of this.launches.values())
320
+ launch.controller.abort();
321
+ await this.queue;
322
+ await Promise.all([...this.launches.values()].map(launch => launch.done));
323
+ while (this.occurrenceQueues.size || this.reconciling.size || this.cleanups.size) {
324
+ await Promise.all([...this.occurrenceQueues.values(), ...this.reconciling.values(), ...this.cleanups.values()]);
325
+ }
326
+ }
327
+ result(record) {
328
+ if (!record.occurrenceId)
329
+ return;
330
+ const durable = this.store.getStoredOccurrence(record.occurrenceId);
331
+ if (!isActiveOccurrence(durable)) {
332
+ this.pendingUpdates.delete(durable.id);
333
+ return;
334
+ }
335
+ const saved = this.project(durable), projected = projectExecution(saved, this.driver.current?.(saved) ?? record, this.now());
336
+ if (this.occurrenceQueues.has(saved.id))
337
+ this.pendingUpdates.set(saved.id, projected);
338
+ else
339
+ this.persist(projected);
340
+ }
341
+ }
@@ -100,7 +100,19 @@ function runProvider(argv, timeoutMs, signal) {
100
100
  });
101
101
  });
102
102
  }
103
+ /** Reclaim an occurrence-owned VM even if no execution checkpoint was written.
104
+ * Keep its ownership record on provider failure so pruning can retry safely. */
105
+ export async function removeOwnedSandbox(provider, specPath, expectedName) {
106
+ if (!existsSync(specPath))
107
+ return;
108
+ const saved = JSON.parse(readFileSync(specPath, 'utf8'));
109
+ if (saved.schemaVersion !== '1' || saved.name !== expectedName)
110
+ throw new Error('Invalid Sandbox ownership record');
111
+ await runProvider(fillTemplate(provider.remove, { name: expectedName }), 120_000);
112
+ rmSync(specPath, { force: true });
113
+ }
103
114
  export async function createSandbox(provider, spec, specPath, signal) {
115
+ signal?.throwIfAborted();
104
116
  for (const mount of spec.mounts) {
105
117
  const stat = statSync(mount.path);
106
118
  if (realpathSync(mount.path) !== mount.path || stat.dev !== mount.dev || stat.ino !== mount.ino)
@@ -117,6 +129,7 @@ export async function createSandbox(provider, spec, specPath, signal) {
117
129
  const startup = { remove: performance.now() - start, create: 0 };
118
130
  start = performance.now();
119
131
  try {
132
+ signal?.throwIfAborted();
120
133
  await runProvider(fillTemplate(provider.create, { spec: specPath, name: spec.name }), 600_000, signal);
121
134
  }
122
135
  catch (error) {
@@ -124,16 +137,10 @@ export async function createSandbox(provider, spec, specPath, signal) {
124
137
  throw error;
125
138
  }
126
139
  startup.create = performance.now() - start;
127
- let holds = 0, closed = false, removing = false;
128
- let finish;
129
- const removed = new Promise((resolve) => { finish = resolve; });
130
- removed.catch(() => { });
131
- const settle = () => {
132
- if (closed && !holds && !removing) {
133
- removing = true;
134
- finish(remove().then(() => rmSync(specPath, { force: true })));
135
- }
136
- };
140
+ let holds = 0, closed = false;
141
+ let unheld;
142
+ let drained = Promise.resolve();
143
+ let removal;
137
144
  return {
138
145
  name: spec.name,
139
146
  nodePath: provider.nodePath,
@@ -141,15 +148,24 @@ export async function createSandbox(provider, spec, specPath, signal) {
141
148
  hold: () => {
142
149
  if (closed)
143
150
  throw new Error(`Sandbox ${spec.name} is stopping`);
144
- holds++;
151
+ if (!holds++)
152
+ drained = new Promise(resolve => { unheld = resolve; });
145
153
  let released = false;
146
154
  return () => { if (!released) {
147
155
  released = true;
148
- holds--;
149
- settle();
156
+ if (!--holds)
157
+ unheld();
150
158
  } };
151
159
  },
152
- close: () => { closed = true; settle(); return removed; },
160
+ close: () => {
161
+ closed = true;
162
+ return removal ??= (async () => {
163
+ if (holds)
164
+ await drained;
165
+ await remove();
166
+ rmSync(specPath, { force: true });
167
+ })().catch(error => { removal = undefined; throw error; });
168
+ },
153
169
  command: (cwd, argv, env) => {
154
170
  const [command, ...args] = fillTemplate(provider.exec, { name: spec.name, cwd });
155
171
  return { command: command, args: [...args, provider.nodePath, "-e", sandboxSupervisorSource, "--", "env",
@@ -28,10 +28,10 @@ export class SharedSandbox {
28
28
  const projectRoot = this.projectRoot();
29
29
  if (!projectRoot)
30
30
  throw new Error(`${sandboxUnavailable().message}: a shared sandbox needs a Project Root`);
31
- const worktrees = join(this.stateRoot, "worktrees"), sessions = join(this.stateRoot, "sessions");
32
- for (const path of [worktrees, sessions])
31
+ const worktrees = join(this.stateRoot, "worktrees"), sessions = join(this.stateRoot, "sessions"), executions = join(this.stateRoot, "workflow-schedules", "executions");
32
+ for (const path of [worktrees, sessions, executions])
33
33
  mkdirSync(path, { recursive: true });
34
- return [realpathSync(projectRoot), realpathSync(worktrees), workflowBuilderFolder(), realpathSync(sessions)];
34
+ return [realpathSync(projectRoot), realpathSync(worktrees), workflowBuilderFolder(), realpathSync(sessions), realpathSync(executions)];
35
35
  }
36
36
  /** Single-flight: creates the VM when none fits the mounts and every session that holds it can be evicted. */
37
37
  acquire(provider, workspace, mounts, signal, evict) {
@@ -17,4 +17,6 @@ export const HOST_OWNED_EVENT_TYPES = [
17
17
  "session_ended",
18
18
  "branch_changed",
19
19
  "workflow_spend",
20
+ "rewound",
21
+ "forked",
20
22
  ];
@@ -0,0 +1 @@
1
+ export {};
@@ -5,6 +5,7 @@ import { authorisationLabel, permissionChoices } from "../client/permission.js";
5
5
  import { toolSummary } from "../client/tool-summary.js";
6
6
  import { relativeTime } from "../client/relative-time.js";
7
7
  import { scopeKindLabel } from "../client/scope-kind.js";
8
+ import { depthOf, producerKey, subagentKey, subagentParents } from "../client/subagent-tree.js";
8
9
  import { sessionLabel } from "../client/session-label.js";
9
10
  import { railGroup, railGroupLabel, RAIL_GROUPS } from "../client/status.js";
10
11
  export function renderFrame(ui, size) {
@@ -197,7 +198,12 @@ function status(ui, width) {
197
198
  return clip(parts.join(" · "), width);
198
199
  }
199
200
  function transcript(view, width, height) {
200
- const lines = view.entries.flatMap((entry) => entryLines(entry, width));
201
+ const subagents = new Map(view.entries.flatMap((entry) => entry.kind === "subagent" ? [[subagentKey(entry.id), entry]] : []));
202
+ const parents = subagentParents([...subagents.keys()], (key) => subagents.get(key));
203
+ const lines = view.entries.flatMap((entry) => {
204
+ const indent = " ".repeat(depthOf(parents, producerKey(entry)));
205
+ return entryLines(entry, Math.max(1, width - indent.length)).map((line) => indent + line);
206
+ });
201
207
  return padTo(lines.slice(-height), height, width);
202
208
  }
203
209
  function entryLines(entry, width) {
@@ -0,0 +1,53 @@
1
+ import { validateDefinition } from "./graph.js";
2
+ import { WorkflowValidationError } from "./errors.js";
3
+ function canonical(value) {
4
+ if (Array.isArray(value))
5
+ return value.map(canonical);
6
+ if (value !== null && typeof value === 'object')
7
+ return Object.fromEntries(Object.entries(value).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => [key, canonical(value)]));
8
+ return value;
9
+ }
10
+ export function deriveResultSchema(definition) {
11
+ return validateDefinition(definition).resultSchema;
12
+ }
13
+ export function resolveWorkflowCalls(definition, lookup, testStepId) {
14
+ const retained = new Map();
15
+ const visited = new Set();
16
+ const visit = (candidate, ancestry, selected) => {
17
+ if (ancestry.has(candidate.id))
18
+ throw new WorkflowValidationError(`Recursive Workflow call: ${candidate.id}`);
19
+ const graph = validateDefinition(candidate);
20
+ const current = graph.definition;
21
+ if (selected !== undefined && !current.steps.some(step => step.id === selected))
22
+ throw new WorkflowValidationError('Unknown test step');
23
+ retained.set(current.id, current);
24
+ const path = new Set([...ancestry, current.id]);
25
+ for (const step of current.steps) {
26
+ if (step.kind !== 'workflow' || (selected !== undefined && step.id !== selected))
27
+ continue;
28
+ if (path.has(step.workflowId))
29
+ throw new WorkflowValidationError(`Recursive Workflow call: ${step.workflowId}`);
30
+ let target = retained.get(step.workflowId);
31
+ if (!target) {
32
+ try {
33
+ target = lookup(step.workflowId);
34
+ }
35
+ catch (error) {
36
+ if (error?.code === 'ENOENT')
37
+ throw new WorkflowValidationError(`Missing Workflow call target: ${step.workflowId}`);
38
+ throw error;
39
+ }
40
+ }
41
+ if (!target || target.id !== step.workflowId)
42
+ throw new WorkflowValidationError(`Missing Workflow call target: ${step.workflowId}`);
43
+ const called = validateDefinition(target);
44
+ if (JSON.stringify(canonical(step.contract.inputSchema)) !== JSON.stringify(canonical(called.definition.inputSchema)) || JSON.stringify(canonical(step.contract.outputSchema)) !== JSON.stringify(canonical(called.resultSchema)))
45
+ throw new WorkflowValidationError(`Workflow call contract does not match target: ${step.workflowId}`);
46
+ if (!visited.has(target.id))
47
+ visit(called.definition, path);
48
+ }
49
+ visited.add(current.id);
50
+ };
51
+ visit(definition, new Set(), testStepId);
52
+ return Object.fromEntries(retained);
53
+ }
@@ -0,0 +1,2 @@
1
+ export class WorkflowValidationError extends Error {
2
+ }
@@ -99,7 +99,7 @@ export async function createCodeExecutors(options) {
99
99
  const stateRoot = options.stateRoot ? { stateRoot: options.stateRoot } : {};
100
100
  const scope = canonicalScope(context.scope);
101
101
  const runtimePath = realpathSync(options.runtimePath);
102
- const sandbox = isolationMode === 'sandbox' ? await options.sandbox(context.sessionId) : undefined;
102
+ const sandbox = isolationMode === 'sandbox' ? await options.sandbox(context.ownerId ?? context.sessionId) : undefined;
103
103
  const nodePath = sandbox ? sandbox.nodePath : realpathSync(options.nodePath);
104
104
  const args = ['--noprofile', '--norc', '-c', 'ulimit -c 0; exec "$@"', 'flow-workflow', nodePath, '--max-old-space-size=128', runtimePath];
105
105
  const timeout = Math.min(context.step.timeoutMs ?? 60_000, 2_147_000_000);
@@ -4,7 +4,7 @@ import { z } from 'zod';
4
4
  import { validSecretName } from "../protocol/secrets.js";
5
5
  import { Decisions } from "./decisions.js";
6
6
  import { analyzeLoops } from "./loops.js";
7
- import { dictionaryKey, dictionaryRecord, declaredOutputSchema, partialSchema, schemaAssignable, schemaAt, unionSchema, validateSchema, valueAt, visualSchemaValidator } from "./schema.js";
7
+ import { dictionaryKey, dictionaryRecord, declaredOutputSchema, parseValue, partialSchema, schemaAssignable, schemaAt, unionSchema, validateSchema, valueAt, visualSchemaValidator } from "./schema.js";
8
8
  const reference = z.discriminatedUnion('source', [
9
9
  z.object({ source: z.literal('input'), path: z.array(z.string()) }).strict(),
10
10
  z.object({ source: z.literal('step'), stepId: z.string(), path: z.array(z.string()) }).strict(),
@@ -37,12 +37,19 @@ export const workflowDefinitionValidator = z.object({
37
37
  z.object({ ...base, kind: z.literal('typescript'), code: z.string(), outputSchema: visualSchemaValidator }).strict(),
38
38
  z.object({ ...base, kind: z.literal('branch'), condition }).strict(),
39
39
  z.object({ ...base, kind: z.literal('join') }).strict(),
40
+ z.object({ ...base, kind: z.literal('workflow'), workflowId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/), contract: z.object({ inputSchema: visualSchemaValidator.refine(schema => schema.type === 'object'), outputSchema: visualSchemaValidator }).strict() }).strict(),
40
41
  z.object({ ...base, kind: z.literal('mcp'), tool: z.object({ connectionId: z.string().min(1), connectionName: z.string(), identity: z.string().regex(/^[a-f0-9]{64}$/), serverIdentity: z.string().regex(/^[a-f0-9]{64}$/), toolName: z.string().min(1), inputSchema: originalSchema, outputSchema: originalSchema.optional() }).strict() }).strict(),
41
42
  ])).min(1),
42
43
  loopSettings: dictionaryRecord(z.object({ maxTries: z.number().int().min(1).max(100) }).strict()).optional(),
43
44
  edges: z.array(z.object({ id: z.string().min(1), from: z.string(), to: z.string(), outcome: z.enum(['success', 'failure', 'timeout', 'true', 'false']) }).strict()),
44
45
  }).strict();
45
46
  export function validateDefinition(value) {
47
+ return buildGraph(value);
48
+ }
49
+ export function mappingSourceGraph(value) {
50
+ return buildGraph(value, true);
51
+ }
52
+ function buildGraph(value, mappingSources = false) {
46
53
  const definition = workflowDefinitionValidator.parse(value);
47
54
  const skillStep = definition.steps.find(step => step.kind === 'agent' && leadingSkillInvocation(step.instructions));
48
55
  if (skillStep && !definition.projectId) {
@@ -167,7 +174,31 @@ export function validateDefinition(value) {
167
174
  node.items.forEach(inspect);
168
175
  };
169
176
  inspect(mapping.template);
170
- input = { type: 'json' };
177
+ const infer = (node) => {
178
+ if (node.kind === 'reference')
179
+ return referenceSchema(node.reference).schema;
180
+ if (node.kind === 'object')
181
+ return { type: 'object', fields: Object.fromEntries(Object.entries(node.fields).map(([key, value]) => [key, { schema: infer(value), required: true }])) };
182
+ if (node.kind === 'array')
183
+ return { type: 'array', items: node.items.length ? unionSchema(node.items.map(infer)) : { type: 'json' } };
184
+ const literal = (value) => {
185
+ if (value === null)
186
+ return { type: 'null' };
187
+ if (typeof value === 'string')
188
+ return { type: 'enum', values: [value] };
189
+ if (typeof value === 'number')
190
+ return { type: 'number', integer: Number.isInteger(value) };
191
+ if (typeof value === 'boolean')
192
+ return { type: 'boolean' };
193
+ if (Array.isArray(value))
194
+ return { type: 'array', items: value.length ? unionSchema(value.map(literal)) : { type: 'json' } };
195
+ return { type: 'object', fields: Object.fromEntries(Object.entries(value).map(([key, value]) => [key, { schema: literal(value), required: true }])) };
196
+ };
197
+ return literal(node.value);
198
+ };
199
+ input = step.kind === 'workflow' ? infer(mapping.template) : { type: 'json' };
200
+ if (step.kind === 'workflow' && !mappingSources && mapping.template.kind === 'literal')
201
+ parseValue(step.contract.inputSchema, mapping.template.value);
171
202
  }
172
203
  else if (mapping?.kind === 'reference') {
173
204
  const field = referenceSchema(mapping.reference);
@@ -198,9 +229,16 @@ export function validateDefinition(value) {
198
229
  }
199
230
  if (step.inputSchema) {
200
231
  validateSchema(step.inputSchema);
201
- if (!schemaAssignable(input, step.inputSchema))
232
+ if (!(mappingSources && step.kind === 'workflow') && !schemaAssignable(input, step.inputSchema))
202
233
  throw new Error('Input does not match the declared input schema');
203
234
  }
235
+ if (step.kind === 'workflow') {
236
+ validateSchema(step.contract.inputSchema);
237
+ validateSchema(step.contract.outputSchema);
238
+ if (!mappingSources && (!schemaAssignable(input, step.contract.inputSchema) || (step.inputSchema && !schemaAssignable(step.inputSchema, step.contract.inputSchema))))
239
+ throw new Error('Input does not match the Workflow call input contract');
240
+ return step.contract.inputSchema;
241
+ }
204
242
  return step.inputSchema ?? input;
205
243
  };
206
244
  const inputFor = (id) => {
@@ -235,7 +273,43 @@ export function validateDefinition(value) {
235
273
  }
236
274
  outputFor(step.id);
237
275
  }
238
- return graph;
276
+ const terminalConditions = order.map(step => decisions.and(completed.get(step.id), decisions.not(any(outgoing.get(step.id).map(edge => selectedEdges.get(edge.id))))));
277
+ let finished = 1;
278
+ for (const step of order) {
279
+ const handled = any(outgoing.get(step.id).filter(edge => edge.outcome === 'failure' || edge.outcome === 'timeout').map(edge => selectedEdges.get(edge.id)));
280
+ finished = decisions.and(finished, decisions.or(decisions.not(reaches.get(step.id)), decisions.or(completed.get(step.id), handled)));
281
+ if (loops.length)
282
+ finished = decisions.and(finished, decisions.not(any(outgoing.get(step.id).filter(edge => backIds.has(edge.id)).map(edge => selectedEdges.get(edge.id)))));
283
+ }
284
+ const candidates = order.map((step, index) => ({ step, condition: terminalConditions[index] })).filter(({ condition }) => decisions.and(finished, condition) !== 0);
285
+ const variants = [];
286
+ let none = 1;
287
+ let one = 0;
288
+ let many = 0;
289
+ for (const { condition } of candidates) {
290
+ many = decisions.or(many, decisions.and(one, condition));
291
+ one = decisions.or(decisions.and(one, decisions.not(condition)), decisions.and(none, condition));
292
+ none = decisions.and(none, decisions.not(condition));
293
+ }
294
+ if (loops.length || definition.edges.some(edge => edge.outcome === 'failure' || edge.outcome === 'timeout')) {
295
+ const possible = order.filter(step => step.kind === 'branch'
296
+ ? ['true', 'false'].some(outcome => !outgoing.get(step.id).some(edge => edge.outcome === outcome))
297
+ : !outgoing.get(step.id).some(edge => edge.outcome === 'success'));
298
+ variants.push(...possible.map(step => outputFor(step.id)));
299
+ if (possible.length > 1)
300
+ variants.push({ type: 'object', fields: Object.fromEntries(possible.map(step => [step.name, { schema: outputFor(step.id) }])) });
301
+ }
302
+ else {
303
+ for (const { step, condition } of candidates)
304
+ if (decisions.and(finished, decisions.and(one, condition)) !== 0)
305
+ variants.push(outputFor(step.id));
306
+ const multiple = decisions.and(finished, many);
307
+ if (multiple !== 0)
308
+ variants.push({ type: 'object', fields: Object.fromEntries(candidates.filter(({ condition }) => decisions.and(multiple, condition) !== 0).map(({ step, condition }) => [step.name, { schema: outputFor(step.id), required: decisions.implies(multiple, condition) }])) });
309
+ if (decisions.and(finished, none) !== 0)
310
+ variants.push({ type: 'object', fields: {} });
311
+ }
312
+ return { ...graph, resultSchema: variants.length ? unionSchema(variants) : { type: 'json' } };
239
313
  }
240
314
  export function recoverySchema(input, output) {
241
315
  return { type: 'object', fields: {