@nathanstephenson/flow 0.1.10-beta.2 → 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 (60) hide show
  1. package/README.md +18 -0
  2. package/build/backend-worker-chunks/{claude-COCNALN2.mjs → claude-6L5KCQWJ.mjs} +63 -15
  3. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-QNU2YE4G.mjs} +10 -10
  4. package/build/backend-worker.mjs +42 -5
  5. package/dist/backend/claude/background-calls.js +7 -3
  6. package/dist/backend/claude/index.js +37 -5
  7. package/dist/backend/claude/subagents.js +30 -9
  8. package/dist/backend/fake/index.js +20 -5
  9. package/dist/backend/pi/index.js +1 -0
  10. package/dist/backend/pi/subagents.js +7 -3
  11. package/dist/backend/worker/entry.js +19 -5
  12. package/dist/backend/worker/index.js +21 -2
  13. package/dist/backend/worker/rpc.js +13 -0
  14. package/dist/backend/worker/sandbox-mcp.js +18 -7
  15. package/dist/build-id +1 -1
  16. package/dist/cli/bootstrap.js +1 -1
  17. package/dist/client/reduce.js +9 -3
  18. package/dist/client/subagent-tree.js +49 -0
  19. package/dist/daemon/git.js +10 -7
  20. package/dist/daemon/host.js +88 -21
  21. package/dist/daemon/runtime.js +63 -3
  22. package/dist/daemon/server.js +3 -0
  23. package/dist/daemon/store.js +2 -0
  24. package/dist/daemon/workflow-environment.js +191 -0
  25. package/dist/daemon/workflow-execution-launch.js +77 -0
  26. package/dist/daemon/workflow-execution-resources.js +76 -0
  27. package/dist/daemon/workflow-execution-values.js +128 -0
  28. package/dist/daemon/workflow-executions.js +272 -285
  29. package/dist/daemon/workflow-schedule-driver.js +247 -0
  30. package/dist/daemon/workflow-schedule-routes.js +137 -0
  31. package/dist/daemon/workflow-schedules.js +341 -0
  32. package/dist/isolation/sandbox.js +30 -14
  33. package/dist/isolation/shared-sandbox.js +3 -3
  34. package/dist/protocol/workflow-schedules.js +1 -0
  35. package/dist/tui/render.js +7 -1
  36. package/dist/workflows/calls.js +10 -7
  37. package/dist/workflows/errors.js +2 -0
  38. package/dist/workflows/executors.js +1 -1
  39. package/dist/workflows/invocations.js +8 -5
  40. package/dist/workflows/owner.js +45 -0
  41. package/dist/workflows/records.js +8 -2
  42. package/dist/workflows/schedule-errors.js +2 -0
  43. package/dist/workflows/schedule-store.js +385 -0
  44. package/dist/workflows/scheduler.js +29 -18
  45. package/dist/workflows/schedules.js +129 -0
  46. package/dist/workflows/store.js +110 -11
  47. package/package.json +2 -1
  48. package/web/dist/assets/index-BGu3YSP7.css +2 -0
  49. package/web/dist/assets/index-Miy2nveb.js +40 -0
  50. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-Vf_fCXyE.js} +1 -1
  51. package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
  52. package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
  53. package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
  54. package/web/dist/index.html +4 -3
  55. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  56. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  57. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  58. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  59. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  60. package/web/dist/assets/workflows-pane-DaqHEeXu.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) {
@@ -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) {
@@ -1,4 +1,5 @@
1
1
  import { validateDefinition } from "./graph.js";
2
+ import { WorkflowValidationError } from "./errors.js";
2
3
  function canonical(value) {
3
4
  if (Array.isArray(value))
4
5
  return value.map(canonical);
@@ -14,32 +15,34 @@ export function resolveWorkflowCalls(definition, lookup, testStepId) {
14
15
  const visited = new Set();
15
16
  const visit = (candidate, ancestry, selected) => {
16
17
  if (ancestry.has(candidate.id))
17
- throw new Error(`Recursive Workflow call: ${candidate.id}`);
18
+ throw new WorkflowValidationError(`Recursive Workflow call: ${candidate.id}`);
18
19
  const graph = validateDefinition(candidate);
19
20
  const current = graph.definition;
20
21
  if (selected !== undefined && !current.steps.some(step => step.id === selected))
21
- throw new Error('Unknown test step');
22
+ throw new WorkflowValidationError('Unknown test step');
22
23
  retained.set(current.id, current);
23
24
  const path = new Set([...ancestry, current.id]);
24
25
  for (const step of current.steps) {
25
26
  if (step.kind !== 'workflow' || (selected !== undefined && step.id !== selected))
26
27
  continue;
27
28
  if (path.has(step.workflowId))
28
- throw new Error(`Recursive Workflow call: ${step.workflowId}`);
29
+ throw new WorkflowValidationError(`Recursive Workflow call: ${step.workflowId}`);
29
30
  let target = retained.get(step.workflowId);
30
31
  if (!target) {
31
32
  try {
32
33
  target = lookup(step.workflowId);
33
34
  }
34
- catch {
35
- throw new Error(`Missing Workflow call target: ${step.workflowId}`);
35
+ catch (error) {
36
+ if (error?.code === 'ENOENT')
37
+ throw new WorkflowValidationError(`Missing Workflow call target: ${step.workflowId}`);
38
+ throw error;
36
39
  }
37
40
  }
38
41
  if (!target || target.id !== step.workflowId)
39
- throw new Error(`Missing Workflow call target: ${step.workflowId}`);
42
+ throw new WorkflowValidationError(`Missing Workflow call target: ${step.workflowId}`);
40
43
  const called = validateDefinition(target);
41
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)))
42
- throw new Error(`Workflow call contract does not match target: ${step.workflowId}`);
45
+ throw new WorkflowValidationError(`Workflow call contract does not match target: ${step.workflowId}`);
43
46
  if (!visited.has(target.id))
44
47
  visit(called.definition, path);
45
48
  }
@@ -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);
@@ -1,7 +1,10 @@
1
+ import { executionIdentity } from "./owner.js";
2
+ export class WorkflowInvocationNotFound extends Error {
3
+ }
1
4
  export function invocationExecution(root, invocationId) {
2
- const invocation = root.invocations?.[invocationId];
3
- if (!invocation)
4
- throw new Error('Unknown workflow invocation');
5
+ if (!root.invocations || !Object.hasOwn(root.invocations, invocationId))
6
+ throw new WorkflowInvocationNotFound('Unknown workflow invocation');
7
+ const invocation = root.invocations[invocationId];
5
8
  const retained = root.retainedDefinitions?.[invocation.definitionId];
6
9
  if (!retained)
7
10
  throw new Error('Missing retained Workflow Definition');
@@ -12,9 +15,9 @@ export function invocationExecution(root, invocationId) {
12
15
  throw new Error('Invalid invocation correction');
13
16
  definition.steps[index] = structuredClone(correction.nextStep);
14
17
  }
15
- return { ...structuredClone(invocation), version: 1, sessionId: root.sessionId, scope: root.scope, definition };
18
+ return { ...structuredClone(invocation), ...executionIdentity(root), scope: root.scope, definition };
16
19
  }
17
20
  export function invocationCheckpoint(record, ownership) {
18
- const { version: _, sessionId: __, scope: ___, definition: ____, ...state } = record;
21
+ const { version: _, occurrenceId: _occurrence, runtime: _runtime, sessionId: __, scope: ___, definition: ____, ...state } = record;
19
22
  return { ...state, ...ownership };
20
23
  }
@@ -0,0 +1,45 @@
1
+ import { join } from 'node:path';
2
+ function storageId(value) {
3
+ if (!/^[a-zA-Z0-9_-]+$/.test(value))
4
+ throw new Error('Invalid storage ID');
5
+ return value;
6
+ }
7
+ export function executionOwnerOf(value) {
8
+ if (value.version === 1 && (value.occurrenceId !== undefined || !value.sessionId))
9
+ throw new Error('Invalid execution owner');
10
+ if (value.version === 2 && !value.occurrenceId)
11
+ throw new Error('Invalid execution owner');
12
+ if (value.occurrenceId !== undefined)
13
+ return { kind: 'occurrence', occurrenceId: storageId(value.occurrenceId) };
14
+ if (value.sessionId)
15
+ return { kind: 'session', sessionId: storageId(value.sessionId) };
16
+ throw new Error('Missing execution owner');
17
+ }
18
+ export function executionOwnerKey(owner) {
19
+ return owner.kind === 'occurrence' ? `occurrence-${storageId(owner.occurrenceId)}` : storageId(owner.sessionId);
20
+ }
21
+ export function parseExecutionOwnerKey(key) {
22
+ storageId(key);
23
+ return key.startsWith('occurrence-') ? { kind: 'occurrence', occurrenceId: storageId(key.slice(11)) } : { kind: 'session', sessionId: key };
24
+ }
25
+ export function executionOwnerPath(stateRoot, owner) {
26
+ return owner.kind === 'occurrence'
27
+ ? join(stateRoot, 'workflow-schedules', 'executions', storageId(owner.occurrenceId))
28
+ : join(stateRoot, 'sessions', storageId(owner.sessionId));
29
+ }
30
+ export function executionIdentity(value) {
31
+ const owner = executionOwnerOf(value);
32
+ return owner.kind === 'session'
33
+ ? { version: 1, sessionId: owner.sessionId }
34
+ : { version: 2, occurrenceId: owner.occurrenceId, ...(value.sessionId === undefined ? {} : { sessionId: storageId(value.sessionId) }) };
35
+ }
36
+ export function executionAssociation(value) {
37
+ return executionOwnerOf(value).kind === 'occurrence' ? value.sessionId : undefined;
38
+ }
39
+ export function executionAccessibleBy(value, owner) {
40
+ const requested = typeof owner === 'string' ? parseExecutionOwnerKey(owner) : owner;
41
+ const actual = executionOwnerOf(value);
42
+ if (requested.kind === 'occurrence')
43
+ return actual.kind === 'occurrence' && actual.occurrenceId === requested.occurrenceId;
44
+ return actual.kind === 'session' ? actual.sessionId === requested.sessionId : executionAssociation(value) === requested.sessionId;
45
+ }
@@ -5,6 +5,7 @@ import { resolveWorkflowCalls } from "./calls.js";
5
5
  import { dictionaryRecord } from "./schema.js";
6
6
  import { validateDefinition, workflowDefinitionValidator } from "./graph.js";
7
7
  import { validateCompatibleDefinition } from "./recovery.js";
8
+ import { executionIdentity, executionOwnerKey, executionOwnerOf } from "./owner.js";
8
9
  const errorValidator = z.object({ message: z.string(), kind: z.enum(['failure', 'timeout', 'interrupted']) }).strict();
9
10
  const identityValidator = z.object({ headerId: z.string().min(1), activation: z.number().int().positive(), try: z.number().int().positive() }).strict();
10
11
  const loopValidator = z.object({
@@ -35,7 +36,7 @@ const invocationValidator = z.object({
35
36
  callStepId: z.string().min(1), callAttempt: z.number().int().positive(), definitionId: z.string().min(1),
36
37
  }).strict();
37
38
  export const workflowExecutionValidator = z.object({
38
- ...checkpointFields, version: z.literal(1), id: z.string().min(1), sessionId: z.string().min(1), scope: z.string(), definition: workflowDefinitionValidator,
39
+ ...checkpointFields, version: z.union([z.literal(1), z.literal(2)]), occurrenceId: z.string().regex(/^[a-zA-Z0-9_-]+$/).optional(), runtime: z.object({ nodePath: z.string().optional(), isolationMode: z.enum(['none', 'bubblewrap', 'sandbox']) }).strict().optional(), id: z.string().min(1), sessionId: z.string().min(1).optional(), scope: z.string(), definition: workflowDefinitionValidator,
39
40
  retainedDefinitions: z.preprocess(value => value && typeof value === 'object' && !Array.isArray(value) ? new Map(Object.entries(value)) : value, z.map(workflowDefinitionValidator.shape.id, workflowDefinitionValidator)).transform(entries => Object.fromEntries(entries)).optional(),
40
41
  invocations: dictionaryRecord(invocationValidator).optional(),
41
42
  launchId: z.string().min(1).optional(), naming: z.enum(['pending', 'requested']).optional(), testStepId: z.string().optional(),
@@ -160,6 +161,7 @@ function stepConfiguration(record, original, stepId, attempt) {
160
161
  }
161
162
  export function parseExecution(value) {
162
163
  const record = workflowExecutionValidator.parse(value);
164
+ executionIdentity(record);
163
165
  const original = validateCheckpoint(record);
164
166
  const manifest = record.retainedDefinitions;
165
167
  if (!manifest) {
@@ -194,7 +196,7 @@ export function parseExecution(value) {
194
196
  throw new Error('Unknown invocation correction step');
195
197
  definition.steps[index] = structuredClone(update.nextStep);
196
198
  }
197
- const local = { ...invocation, version: 1, sessionId: record.sessionId, scope: record.scope, definition };
199
+ const local = { ...invocation, ...executionIdentity(record), scope: record.scope, definition };
198
200
  if (!isDeepStrictEqual(validateCheckpoint(local), retained))
199
201
  throw new Error('Invocation corrections do not match the retained definition');
200
202
  locals.set(id, local);
@@ -245,3 +247,7 @@ export function parseExecution(value) {
245
247
  }
246
248
  return record;
247
249
  }
250
+ /** Stable checkpoint owner, independent of optional Agent Session association. */
251
+ export function executionOwner(record) {
252
+ return executionOwnerKey(executionOwnerOf(record));
253
+ }
@@ -0,0 +1,2 @@
1
+ export class ScheduleValidationError extends Error {
2
+ }