@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,385 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { z } from 'zod';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { ScheduleValidationError } from "./schedule-errors.js";
7
+ import { isActiveOccurrence, occurrenceValidator, scheduleValidator, SCHEDULE_RETENTION_MS, storageId, timestamp } from "./schedules.js";
8
+ function sync(directory) {
9
+ const fd = openSync(directory, 'r');
10
+ try {
11
+ fsyncSync(fd);
12
+ }
13
+ finally {
14
+ closeSync(fd);
15
+ }
16
+ }
17
+ function durableDirectory(directory) {
18
+ if (existsSync(directory))
19
+ return;
20
+ const parent = dirname(directory);
21
+ durableDirectory(parent);
22
+ mkdirSync(directory, { mode: 0o700 });
23
+ sync(parent);
24
+ }
25
+ function atomicWrite(path, value) {
26
+ const directory = dirname(path);
27
+ durableDirectory(directory);
28
+ const temporary = join(directory, `.${randomUUID()}.tmp`);
29
+ try {
30
+ const fd = openSync(temporary, 'wx', 0o600);
31
+ try {
32
+ writeFileSync(fd, JSON.stringify(value));
33
+ fsyncSync(fd);
34
+ }
35
+ finally {
36
+ closeSync(fd);
37
+ }
38
+ renameSync(temporary, path);
39
+ sync(directory);
40
+ }
41
+ finally {
42
+ rmSync(temporary, { force: true });
43
+ }
44
+ }
45
+ function ids(directory, invalid) {
46
+ if (!existsSync(directory))
47
+ return [];
48
+ return readdirSync(directory).filter(name => name.endsWith('.json')).flatMap(name => {
49
+ const id = storageId.safeParse(name.slice(0, -5));
50
+ if (id.success)
51
+ return [id.data];
52
+ invalid?.();
53
+ console.error('Workflow Schedule record has an invalid filename. File retained for manual review.');
54
+ return [];
55
+ });
56
+ }
57
+ const cleanupJournalValidator = z.object({ occurrenceId: storageId, status: z.enum(['pending', 'done']) }).strict();
58
+ function needsUnstartedCleanup(value) {
59
+ return value.executionId === undefined && ['interrupted', 'launch-failed', 'cancelled'].includes(value.status);
60
+ }
61
+ export class ScheduleRecordNotFound extends Error {
62
+ }
63
+ export class ScheduleRevisionConflict extends Error {
64
+ constructor() { super('Schedule changed; reload before editing'); }
65
+ }
66
+ /** Private, durable records independent of Agent Session lifecycle and transcript retention. */
67
+ export class WorkflowScheduleStore {
68
+ root;
69
+ schedules = new Map();
70
+ occurrences = new Map();
71
+ activeRecords = new Map();
72
+ history = [];
73
+ historyBySchedule = new Map();
74
+ active = new Set();
75
+ activeBySchedule = new Map();
76
+ projection;
77
+ pruning;
78
+ unknownOccurrences = false;
79
+ unstartedCleanup = new Map();
80
+ constructor(stateRoot) {
81
+ this.root = join(stateRoot, 'workflow-schedules');
82
+ for (const id of ids(join(this.root, 'unstarted-cleanup'))) {
83
+ try {
84
+ const value = cleanupJournalValidator.parse(JSON.parse(readFileSync(this.cleanupPath(id), 'utf8')));
85
+ if (value.occurrenceId !== id)
86
+ throw new Error('Invalid cleanup identity');
87
+ this.unstartedCleanup.set(id, value.status);
88
+ }
89
+ catch {
90
+ this.unstartedCleanup.set(id, 'unknown');
91
+ console.error('Workflow Occurrence cleanup journal is invalid. File retained for manual review.');
92
+ }
93
+ }
94
+ for (const id of ids(join(this.root, 'definitions'))) {
95
+ try {
96
+ const value = scheduleValidator.parse(JSON.parse(readFileSync(this.schedulePath(id), 'utf8')));
97
+ if (value.id !== id)
98
+ throw new Error('Invalid schedule identity');
99
+ this.schedules.set(id, value);
100
+ }
101
+ catch {
102
+ console.error('Workflow Schedule record is invalid. File retained for manual review.');
103
+ }
104
+ }
105
+ for (const id of ids(join(this.root, 'occurrences'), () => { this.unknownOccurrences = true; })) {
106
+ try {
107
+ const value = occurrenceValidator.parse(JSON.parse(readFileSync(this.occurrencePath(id), 'utf8')));
108
+ if (value.id !== id)
109
+ throw new Error('Invalid occurrence identity');
110
+ this.indexOccurrence(value);
111
+ try {
112
+ this.queueUnstartedCleanup(value);
113
+ }
114
+ catch {
115
+ this.unstartedCleanup.set(id, 'pending');
116
+ console.error('Workflow Occurrence cleanup journal could not be saved. Its record will be retained for retry.');
117
+ }
118
+ }
119
+ catch {
120
+ this.unknownOccurrences = true;
121
+ console.error('Workflow Occurrence record is invalid. File retained for manual review.');
122
+ }
123
+ }
124
+ }
125
+ cleanupPath(id) { return join(this.root, 'unstarted-cleanup', `${storageId.parse(id)}.json`); }
126
+ queueUnstartedCleanup(value) {
127
+ if (!needsUnstartedCleanup(value) || this.unstartedCleanup.has(value.id))
128
+ return;
129
+ atomicWrite(this.cleanupPath(value.id), { occurrenceId: value.id, status: 'pending' });
130
+ this.unstartedCleanup.set(value.id, 'pending');
131
+ }
132
+ pendingUnstartedCleanup() { return [...this.unstartedCleanup].filter(([, status]) => status === 'pending').map(([id]) => id); }
133
+ prepareUnstartedCleanup(id) {
134
+ atomicWrite(this.cleanupPath(id), { occurrenceId: id, status: 'pending' });
135
+ }
136
+ completeUnstartedCleanup(id) {
137
+ atomicWrite(this.cleanupPath(id), { occurrenceId: id, status: 'done' });
138
+ this.unstartedCleanup.set(id, 'done');
139
+ }
140
+ setOccurrenceProjection(project) { this.projection = project; }
141
+ project(value) {
142
+ const copy = structuredClone(value);
143
+ return isActiveOccurrence(value) && this.projection ? this.projection(copy) : copy;
144
+ }
145
+ indexOccurrence(value) {
146
+ const fresh = !this.occurrences.has(value.id);
147
+ const { id, scheduleId, scheduledAt, status, finishedAt } = value;
148
+ this.occurrences.set(id, { id, scheduleId, scheduledAt, status, ...(finishedAt === undefined ? {} : { finishedAt }) });
149
+ if (isActiveOccurrence(value))
150
+ this.activeRecords.set(id, value);
151
+ else
152
+ this.activeRecords.delete(id);
153
+ const active = this.activeBySchedule.get(value.scheduleId) ?? new Set();
154
+ this.activeBySchedule.set(value.scheduleId, active);
155
+ if (isActiveOccurrence(value)) {
156
+ this.active.add(value.id);
157
+ active.add(value.id);
158
+ }
159
+ else {
160
+ this.active.delete(value.id);
161
+ active.delete(value.id);
162
+ }
163
+ if (!fresh)
164
+ return;
165
+ const history = this.historyBySchedule.get(value.scheduleId) ?? [];
166
+ this.historyBySchedule.set(value.scheduleId, history);
167
+ for (const list of [this.history, history]) {
168
+ let low = 0, high = list.length;
169
+ while (low < high) {
170
+ const mid = (low + high) >>> 1;
171
+ const other = this.occurrences.get(list[mid]);
172
+ if (other.scheduledAt > value.scheduledAt || (other.scheduledAt === value.scheduledAt && other.id > value.id))
173
+ low = mid + 1;
174
+ else
175
+ high = mid;
176
+ }
177
+ list.splice(low, 0, value.id);
178
+ }
179
+ }
180
+ historyIds(scheduleId) {
181
+ if (scheduleId === undefined)
182
+ return this.history;
183
+ storageId.parse(scheduleId);
184
+ return this.historyBySchedule.get(scheduleId) ?? [];
185
+ }
186
+ listActiveOccurrences(scheduleId) {
187
+ if (scheduleId !== undefined)
188
+ storageId.parse(scheduleId);
189
+ const active = scheduleId === undefined ? this.active : this.activeBySchedule.get(scheduleId) ?? [];
190
+ return [...active].map(id => this.getOccurrence(id)).filter(isActiveOccurrence);
191
+ }
192
+ activeCount(scheduleId) { return this.listActiveOccurrences(scheduleId).length; }
193
+ schedulePath(id) { return join(this.root, 'definitions', `${storageId.parse(id)}.json`); }
194
+ occurrencePath(id) { return join(this.root, 'occurrences', `${storageId.parse(id)}.json`); }
195
+ getSchedule(id) {
196
+ storageId.parse(id);
197
+ const value = this.schedules.get(id);
198
+ if (!value)
199
+ throw new ScheduleRecordNotFound('Schedule not found');
200
+ return structuredClone(value);
201
+ }
202
+ listSchedules(includeDeleted = false) {
203
+ return [...this.schedules.values()].filter(value => includeDeleted || value.deletedAt === undefined).map(value => structuredClone(value));
204
+ }
205
+ saveSchedule(value, expectedRevision) {
206
+ const validated = scheduleValidator.parse(value);
207
+ const path = this.schedulePath(validated.id);
208
+ if (expectedRevision === undefined) {
209
+ if (existsSync(path))
210
+ throw new ScheduleRevisionConflict();
211
+ }
212
+ else if (this.getSchedule(validated.id).revision !== expectedRevision || validated.revision !== expectedRevision + 1)
213
+ throw new ScheduleRevisionConflict();
214
+ atomicWrite(path, validated);
215
+ this.schedules.set(validated.id, validated);
216
+ }
217
+ /** Cursor advancement is not a user edit and retains the activation/revision. */
218
+ advanceCursor(id, revision, due, nextDue) {
219
+ const saved = this.getSchedule(id);
220
+ if (!saved.enabled || saved.revision !== revision || saved.nextDue !== due)
221
+ throw new ScheduleRevisionConflict();
222
+ if (nextDue <= due)
223
+ throw new Error('Schedule cursor must advance');
224
+ const value = scheduleValidator.parse({ ...saved, nextDue });
225
+ atomicWrite(this.schedulePath(id), value);
226
+ this.schedules.set(id, value);
227
+ }
228
+ deleteSchedule(id, revision, now) {
229
+ const saved = this.getSchedule(id);
230
+ const { nextDue: _, ...rest } = saved;
231
+ this.saveSchedule({ ...rest, enabled: false, revision: saved.revision + 1, deletedAt: timestamp.parse(now), updatedAt: now }, revision);
232
+ }
233
+ readOccurrence(id) {
234
+ storageId.parse(id);
235
+ if (!this.occurrences.has(id))
236
+ throw new ScheduleRecordNotFound('Occurrence not found');
237
+ const value = this.activeRecords.get(id) ?? occurrenceValidator.parse(JSON.parse(readFileSync(this.occurrencePath(id), 'utf8')));
238
+ if (value.id !== id)
239
+ throw new Error('Invalid occurrence identity');
240
+ return value;
241
+ }
242
+ getStoredOccurrence(id) { return structuredClone(this.readOccurrence(id)); }
243
+ getOccurrence(id) { return this.project(this.readOccurrence(id)); }
244
+ listOccurrences(scheduleId) {
245
+ return this.historyIds(scheduleId).map(id => this.getOccurrence(id));
246
+ }
247
+ page(options = {}) {
248
+ const limit = options.limit ?? 50;
249
+ if (!Number.isInteger(limit) || limit < 1 || limit > 200)
250
+ throw new ScheduleValidationError('Invalid history limit');
251
+ const values = this.historyIds(options.scheduleId);
252
+ let start = 0;
253
+ if (options.before !== undefined) {
254
+ if (!storageId.safeParse(options.before).success)
255
+ throw new ScheduleValidationError('Invalid history cursor');
256
+ const cursor = /^(\d+)_([a-f0-9]{64})$/.exec(options.before);
257
+ if (cursor) {
258
+ const parsed = timestamp.safeParse(Number(cursor[1]));
259
+ if (!parsed.success)
260
+ throw new ScheduleValidationError('Invalid history cursor');
261
+ const due = parsed.data, id = cursor[2];
262
+ let high = values.length;
263
+ while (start < high) {
264
+ const mid = (start + high) >>> 1, other = this.occurrences.get(values[mid]);
265
+ if (other.scheduledAt > due || (other.scheduledAt === due && other.id >= id))
266
+ start = mid + 1;
267
+ else
268
+ high = mid;
269
+ }
270
+ }
271
+ else {
272
+ const index = values.indexOf(options.before);
273
+ if (index < 0)
274
+ throw new ScheduleValidationError('Invalid history cursor');
275
+ start = index + 1;
276
+ }
277
+ }
278
+ const last = this.occurrences.get(values[start + limit - 1]);
279
+ return { occurrences: values.slice(start, start + limit).map(id => this.getOccurrence(id)), ...(values.length > start + limit ? { next: `${last.scheduledAt}_${last.id}` } : {}) };
280
+ }
281
+ /** Durable admission claim. Call before provisioning or executable effects; never overwrite. */
282
+ claimOccurrence(value) {
283
+ const validated = occurrenceValidator.parse(value);
284
+ if (this.occurrences.has(value.id) || existsSync(this.occurrencePath(value.id)))
285
+ return false;
286
+ this.queueUnstartedCleanup(validated);
287
+ atomicWrite(this.occurrencePath(value.id), validated);
288
+ this.indexOccurrence(validated);
289
+ return true;
290
+ }
291
+ saveOccurrence(value) {
292
+ const validated = occurrenceValidator.parse(value);
293
+ const saved = this.readOccurrence(validated.id);
294
+ if (saved.scheduleId !== value.scheduleId || saved.activation !== value.activation || saved.scheduledAt !== value.scheduledAt || saved.revision !== value.revision)
295
+ throw new Error('Occurrence identity cannot change');
296
+ if (!isDeepStrictEqual(saved.settings, validated.settings))
297
+ throw new Error('Occurrence settings cannot change');
298
+ if (!isActiveOccurrence(saved) && !isDeepStrictEqual(saved, validated))
299
+ throw new Error('Terminal occurrence is immutable');
300
+ this.queueUnstartedCleanup(validated);
301
+ atomicWrite(this.occurrencePath(value.id), validated);
302
+ this.indexOccurrence(validated);
303
+ }
304
+ saveCleanupWarning(occurrence, warning) {
305
+ atomicWrite(join(this.root, 'cleanup', `${storageId.parse(occurrence.id)}.json`), { occurrenceId: occurrence.id, worktree: occurrence.worktree, warning });
306
+ }
307
+ clearCleanupWarning(id) {
308
+ const path = join(this.root, 'cleanup', `${storageId.parse(id)}.json`);
309
+ if (!existsSync(path))
310
+ return;
311
+ rmSync(path);
312
+ sync(dirname(path));
313
+ }
314
+ cleanupWarnings() {
315
+ return ids(join(this.root, 'cleanup')).flatMap(id => {
316
+ try {
317
+ return [JSON.parse(readFileSync(join(this.root, 'cleanup', `${id}.json`), 'utf8'))];
318
+ }
319
+ catch {
320
+ console.error('Workflow Occurrence cleanup warning is invalid. File retained for manual review.');
321
+ return [];
322
+ }
323
+ });
324
+ }
325
+ /** The callback owns execution cleanup; no Agent Session directories are ever removed here. */
326
+ prune(now, cleanup, canPrune = () => true) {
327
+ this.pruning ??= this.pruneExpired(now, cleanup, canPrune).finally(() => { this.pruning = undefined; });
328
+ return this.pruning;
329
+ }
330
+ async pruneExpired(now, cleanup, canPrune) {
331
+ timestamp.parse(now);
332
+ const removed = [];
333
+ for (const id of [...this.history]) {
334
+ if (!canPrune(id))
335
+ continue;
336
+ const indexed = this.occurrences.get(id);
337
+ if (!isActiveOccurrence(indexed) && (indexed.finishedAt === undefined || indexed.finishedAt > now - SCHEDULE_RETENTION_MS))
338
+ continue;
339
+ try {
340
+ const value = this.getOccurrence(id);
341
+ if (isActiveOccurrence(value) || value.finishedAt === undefined || value.finishedAt > now - SCHEDULE_RETENTION_MS)
342
+ continue;
343
+ if (this.active.has(value.id))
344
+ this.saveOccurrence(value);
345
+ await cleanup(value);
346
+ if (this.unstartedCleanup.has(id) && this.unstartedCleanup.get(id) !== 'unknown') {
347
+ rmSync(this.cleanupPath(id), { force: true });
348
+ sync(dirname(this.cleanupPath(id)));
349
+ this.unstartedCleanup.delete(id);
350
+ }
351
+ rmSync(this.occurrencePath(value.id));
352
+ sync(dirname(this.occurrencePath(value.id)));
353
+ this.occurrences.delete(value.id);
354
+ this.activeRecords.delete(value.id);
355
+ this.active.delete(value.id);
356
+ this.activeBySchedule.get(value.scheduleId)?.delete(value.id);
357
+ const history = this.historyBySchedule.get(value.scheduleId);
358
+ for (const list of [this.history, history])
359
+ list.splice(list.indexOf(value.id), 1);
360
+ if (!history.length) {
361
+ this.historyBySchedule.delete(value.scheduleId);
362
+ this.activeBySchedule.delete(value.scheduleId);
363
+ }
364
+ removed.push(value.id);
365
+ }
366
+ catch {
367
+ console.error('Workflow Occurrence retention failed. Its record and owned work will be retained for retry.');
368
+ }
369
+ }
370
+ const retained = new Set(this.historyBySchedule.keys());
371
+ for (const schedule of this.listSchedules(true)) {
372
+ if (this.unknownOccurrences || schedule.deletedAt === undefined || retained.has(schedule.id) || schedule.deletedAt > now - SCHEDULE_RETENTION_MS)
373
+ continue;
374
+ try {
375
+ rmSync(this.schedulePath(schedule.id));
376
+ sync(dirname(this.schedulePath(schedule.id)));
377
+ this.schedules.delete(schedule.id);
378
+ }
379
+ catch {
380
+ console.error('Workflow Schedule retention failed. Its record will be retained for retry.');
381
+ }
382
+ }
383
+ return removed;
384
+ }
385
+ }
@@ -1,3 +1,5 @@
1
+ import { executionOwner } from "./records.js";
2
+ import { executionAccessibleBy, executionAssociation, executionIdentity, executionOwnerKey, executionOwnerOf } from "./owner.js";
1
3
  import { randomUUID } from 'node:crypto';
2
4
  import { isDeepStrictEqual } from 'node:util';
3
5
  import { resolveMapping, validateDefinition } from "./graph.js";
@@ -24,27 +26,27 @@ export class WorkflowScheduler {
24
26
  this.store = store;
25
27
  this.executors = executors;
26
28
  this.onResume = onResume;
27
- for (const sessionId of store.listSessionIds()) {
28
- for (const record of store.listExecutions(sessionId)) {
29
+ for (const owner of store.listOwners()) {
30
+ for (const record of store.listOwnedExecutions(owner)) {
29
31
  if (!occupied(record))
30
32
  continue;
31
- if (this.slots.has(sessionId))
32
- throw new Error('Multiple workflow executions occupy one Agent Session');
33
+ if (this.slots.has(executionOwnerKey(owner)))
34
+ throw new Error('Multiple workflow executions occupy one execution owner');
33
35
  const active = this.install(record);
34
36
  this.reconcile(active);
35
37
  this.persist(active);
36
38
  }
37
39
  }
38
40
  }
39
- occupied(sessionId) { return this.slots.has(sessionId); }
41
+ occupied(sessionId) { return this.slots.has(sessionId) || [...this.active.values()].some(active => executionAssociation(active.record) === sessionId && occupied(active.record)); }
40
42
  /** Whether the slot contains a full execution doing work, excluding tests and recovery waits. */
41
43
  activeFull(sessionId) {
42
- const executionId = this.slots.get(sessionId);
44
+ const executionId = this.slots.get(sessionId) ?? [...this.active.values()].find(active => executionAssociation(active.record) === sessionId && occupied(active.record))?.record.id;
43
45
  const record = executionId ? this.active.get(executionId)?.record : undefined;
44
46
  return record?.status === 'running' && record.testStepId === undefined;
45
47
  }
46
48
  forgetSession(sessionId) {
47
- const executions = [...this.active.values()].filter(active => active.record.sessionId === sessionId);
49
+ const executions = [...this.active.values()].filter(active => executionOwner(active.record) === sessionId);
48
50
  if (executions.some(active => this.hasWork(active) || active.record.status === 'running'))
49
51
  throw new Error('Workflow work must stop before forgetting an Agent Session');
50
52
  for (const active of executions)
@@ -52,7 +54,7 @@ export class WorkflowScheduler {
52
54
  this.slots.delete(sessionId);
53
55
  }
54
56
  start(definition, session, input, testStepId, launchId, namingEligible = false, capturedDefinitions) {
55
- if (this.occupied(session.sessionId))
57
+ if (this.occupied(executionOwner(session)))
56
58
  throw new Error('Agent Session workflow slot is occupied');
57
59
  const graph = validateDefinition(definition);
58
60
  if (graph.definition.backend !== session.backend)
@@ -73,7 +75,7 @@ export class WorkflowScheduler {
73
75
  this.check(testStep ? [testStep] : graph.order, session, retainedDefinitions);
74
76
  const parsed = parseValue(testStep ? graph.inputSchemas.get(testStep.id) : graph.definition.inputSchema, input);
75
77
  const record = {
76
- version: 1, id: randomUUID(), sessionId: session.sessionId, scope: session.scope,
78
+ ...executionIdentity(session), ...(session.runtime ? { runtime: session.runtime } : {}), id: randomUUID(), scope: session.scope,
77
79
  definition: graph.definition, input: parsed, status: 'running', startedAt: Date.now(),
78
80
  ...(graph.order.some(step => step.kind === 'workflow') ? { retainedDefinitions, invocations: {} } : {}),
79
81
  ...(launchId ? { launchId } : {}),
@@ -86,16 +88,25 @@ export class WorkflowScheduler {
86
88
  this.pump(active);
87
89
  return structuredClone(record);
88
90
  }
91
+ associate(occurrenceId, executionId, sessionId) {
92
+ const active = this.require(executionOwnerKey({ kind: 'occurrence', occurrenceId }), executionId);
93
+ if (executionOwnerOf(active.record).kind !== 'occurrence' || (executionAssociation(active.record) && executionAssociation(active.record) !== sessionId))
94
+ throw new Error('Invalid execution association');
95
+ const visit = (node) => { node.record.sessionId = sessionId; for (const call of node.calls.values())
96
+ visit(call.child); };
97
+ visit(active);
98
+ this.persist(active);
99
+ }
89
100
  get(sessionId, executionId) {
90
101
  const active = this.active.get(executionId);
91
- if (active?.record.sessionId === sessionId)
102
+ if (active !== undefined && executionAccessibleBy(active.record, sessionId))
92
103
  return structuredClone(active.record);
93
104
  return this.store.getExecution(sessionId, executionId);
94
105
  }
95
106
  /** Atomically consume an automatic naming request before model work starts. */
96
107
  claimNaming(sessionId, executionId) {
97
108
  const active = this.active.get(executionId);
98
- const record = active?.record.sessionId === sessionId ? active.record : this.store.getExecution(sessionId, executionId);
109
+ const record = active !== undefined && executionAccessibleBy(active.record, sessionId) ? active.record : this.store.getExecution(sessionId, executionId);
99
110
  if (record.naming !== 'pending' || record.testStepId)
100
111
  return false;
101
112
  record.naming = 'requested';
@@ -116,7 +127,7 @@ export class WorkflowScheduler {
116
127
  hasPendingDeadline(sessionId, executionId) {
117
128
  const pending = (active) => !active.stopped && [...active.calls.values()].some(call => call.timer !== undefined || pending(call.child));
118
129
  const active = this.active.get(executionId);
119
- return active?.record.sessionId === sessionId && pending(active);
130
+ return active !== undefined && executionAccessibleBy(active.record, sessionId) && pending(active);
120
131
  }
121
132
  async cancel(sessionId, executionId) {
122
133
  const active = this.require(sessionId, executionId);
@@ -136,7 +147,7 @@ export class WorkflowScheduler {
136
147
  }
137
148
  /** replacementDefinition is resolved from saved storage by the host, never from request JSON. */
138
149
  recover(session, executionId, action, replacementDefinition) {
139
- const root = this.require(session.sessionId, executionId);
150
+ const root = this.require(executionOwner(session), executionId);
140
151
  const active = action.invocationId ? this.findInvocation(root, action.invocationId) : root;
141
152
  const record = active.record;
142
153
  if (record.status !== 'recovery-required' || this.hasWork(active))
@@ -263,7 +274,7 @@ export class WorkflowScheduler {
263
274
  install(record) {
264
275
  const active = { record, graph: validateDefinition(record.definition), running: new Map(), calls: new Map(), waiters: [], stopped: record.status !== 'running' };
265
276
  this.active.set(record.id, active);
266
- this.slots.set(record.sessionId, record.id);
277
+ this.slots.set(executionOwner(record), record.id);
267
278
  const installed = new Map();
268
279
  const restore = (id) => {
269
280
  const cached = installed.get(id);
@@ -402,7 +413,7 @@ export class WorkflowScheduler {
402
413
  throw new Error('Missing retained called Workflow Definition');
403
414
  const graph = validateDefinition(definition);
404
415
  const record = {
405
- version: 1, id: randomUUID(), sessionId: root.record.sessionId, scope: root.record.scope, definition: graph.definition,
416
+ ...executionIdentity(root.record), id: randomUUID(), scope: root.record.scope, definition: graph.definition,
406
417
  input: structuredClone(attempt.input), status: 'running', startedAt: Date.now(),
407
418
  steps: Object.fromEntries(graph.order.map(step => [step.id, { status: 'pending', attempts: [] }])),
408
419
  loops: Object.fromEntries(graph.loops.map(loop => [loop.headerId, { activation: 0, try: 0, phase: 'inactive', grants: [] }])),
@@ -486,7 +497,7 @@ export class WorkflowScheduler {
486
497
  }
487
498
  require(sessionId, executionId) {
488
499
  const active = this.active.get(executionId);
489
- if (!active || active.record.sessionId !== sessionId)
500
+ if (!active || !executionAccessibleBy(active.record, sessionId))
490
501
  throw new Error('Unknown workflow execution');
491
502
  return active;
492
503
  }
@@ -721,7 +732,7 @@ export class WorkflowScheduler {
721
732
  return;
722
733
  }
723
734
  if (!occupied(active.record))
724
- this.slots.delete(active.record.sessionId);
735
+ this.slots.delete(executionOwner(active.record));
725
736
  for (const waiter of active.waiters.splice(0)) {
726
737
  if (active.persistenceError)
727
738
  waiter.reject(active.persistenceError);
@@ -825,7 +836,7 @@ export class WorkflowScheduler {
825
836
  }
826
837
  }
827
838
  else
828
- value = await this.executors[step.kind].execute({ sessionId: active.record.sessionId, scope: active.record.scope, executionId: (active.root ?? active).record.id, ...(active.parent ? { invocationId: active.record.id } : {}), attempt: attempt.number, step: this.guidedStep(active, step, attempt), input: structuredClone(attempt.input), inputSchema: active.graph.inputSchemas.get(step.id), permission: active.inheritedAsk ? 'ask' : step.permission ?? active.record.definition.permission ?? 'auto-accept', signal: controller.signal });
839
+ value = await this.executors[step.kind].execute({ owner: executionOwnerOf(active.record), ownerId: executionOwner(active.record), ...(active.record.sessionId ? { sessionId: active.record.sessionId } : {}), ...(active.record.occurrenceId ? { occurrenceId: active.record.occurrenceId } : {}), scope: active.record.scope, executionId: (active.root ?? active).record.id, ...(active.parent ? { invocationId: active.record.id } : {}), attempt: attempt.number, step: this.guidedStep(active, step, attempt), input: structuredClone(attempt.input), inputSchema: active.graph.inputSchemas.get(step.id), permission: active.inheritedAsk ? 'ask' : step.permission ?? active.record.definition.permission ?? 'auto-accept', signal: controller.signal });
829
840
  if (active.stopped)
830
841
  return;
831
842
  if (timedOut)
@@ -0,0 +1,129 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { Temporal } from '@js-temporal/polyfill';
4
+ import { z } from 'zod';
5
+ export const SCHEDULE_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
6
+ export const LIVE_DISPATCH_TOLERANCE_MS = 30_000;
7
+ export const storageId = z.string().regex(/^[a-zA-Z0-9_-]+$/).max(200);
8
+ export const timestamp = z.number().int().nonnegative().max(8_640_000_000_000_000);
9
+ const timezone = z.string().max(200).refine(value => {
10
+ try {
11
+ // Temporal also accepts numeric offsets; schedules deliberately require named zones.
12
+ return !/^[+\-\u2212]/.test(value) && Temporal.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(value).timeZoneId.length > 0;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }, 'Invalid IANA timezone');
18
+ export const timingValidator = z.discriminatedUnion('kind', [
19
+ z.object({ kind: z.literal('interval'), value: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), unit: z.enum(['minutes', 'hours', 'days']) }).strict().refine(value => Number.isSafeInteger(value.value * intervalUnit(value.unit)) && value.value * intervalUnit(value.unit) <= 8_640_000_000_000_000, 'Interval is too large'),
20
+ z.object({ kind: z.literal('daily'), time: z.string().regex(/^(?:[01]\d|2[0-3]):[0-5]\d$/), timezone }).strict(),
21
+ ]);
22
+ export const scheduleSettingsValidator = z.object({
23
+ name: z.string().trim().min(1).max(200), workflowId: storageId,
24
+ input: z.json(), projectId: z.string().min(1).max(4096),
25
+ mcpConnectionIds: z.array(storageId).max(100).refine(ids => new Set(ids).size === ids.length, 'Duplicate MCP selection'),
26
+ worktree: z.object({ from: z.string().min(1).max(1024) }).strict().optional(),
27
+ timing: timingValidator, concurrency: z.number().int().min(1).max(100).default(3),
28
+ }).strict();
29
+ export const scheduleValidator = scheduleSettingsValidator.extend({
30
+ version: z.literal(1), id: storageId, revision: z.number().int().positive(), activation: z.number().int().nonnegative(),
31
+ enabled: z.boolean(), createdAt: timestamp, updatedAt: timestamp,
32
+ nextDue: timestamp.optional(), deletedAt: timestamp.optional(),
33
+ }).strict().superRefine((value, context) => {
34
+ if (value.enabled !== (value.nextDue !== undefined) || (value.deletedAt !== undefined && value.enabled))
35
+ context.addIssue({ code: 'custom', message: 'Invalid schedule cursor' });
36
+ if (value.enabled && value.activation < 1)
37
+ context.addIssue({ code: 'custom', message: 'Missing activation' });
38
+ });
39
+ export const occurrenceValidator = z.object({
40
+ version: z.literal(1), id: storageId, scheduleId: storageId,
41
+ activation: z.number().int().positive(), revision: z.number().int().positive(), scheduledAt: timestamp,
42
+ missedThrough: timestamp.optional(), settings: scheduleSettingsValidator,
43
+ status: z.enum(['provisioning', 'running', 'recovery-required', 'completed', 'completed-with-recovery', 'cancelled', 'launch-failed', 'interrupted', 'capacity-skipped', 'missed']),
44
+ createdAt: timestamp, finishedAt: timestamp.optional(), sessionId: storageId.optional(), association: z.enum(['pending', 'attached', 'failed']).optional(), executionId: storageId.optional(),
45
+ scope: z.string().min(1).optional(), worktree: z.object({ path: z.string(), repo: z.string(), branch: z.string() }).strict().optional(),
46
+ outcome: z.string().max(2000).optional(),
47
+ }).strict().superRefine((value, context) => {
48
+ if (value.id !== occurrenceId(value.scheduleId, value.activation, value.scheduledAt))
49
+ context.addIssue({ code: 'custom', message: 'Invalid occurrence identity' });
50
+ if (isActiveOccurrence(value) === (value.finishedAt !== undefined))
51
+ context.addIssue({ code: 'custom', message: 'Invalid occurrence completion' });
52
+ if (value.missedThrough !== undefined && (value.status !== 'missed' || value.missedThrough < value.scheduledAt))
53
+ context.addIssue({ code: 'custom', message: 'Invalid missed range' });
54
+ });
55
+ function intervalUnit(unit) { return { minutes: 60_000, hours: 3_600_000, days: 86_400_000 }[unit]; }
56
+ export function intervalMilliseconds(timing) {
57
+ timingValidator.parse(timing);
58
+ return timing.value * intervalUnit(timing.unit);
59
+ }
60
+ export function occurrenceId(scheduleId, activation, due) {
61
+ storageId.parse(scheduleId);
62
+ z.number().int().positive().parse(activation);
63
+ timestamp.parse(due);
64
+ return createHash('sha256').update(JSON.stringify([scheduleId, activation, due])).digest('hex');
65
+ }
66
+ /** Strictly future civil-time match. Gaps are skipped; folds use only their earlier instant. */
67
+ export function nextOccurrence(timing, after) {
68
+ timingValidator.parse(timing);
69
+ timestamp.parse(after);
70
+ if (timing.kind === 'interval')
71
+ return timestamp.parse(after + intervalMilliseconds(timing));
72
+ const instant = Temporal.Instant.fromEpochMilliseconds(after);
73
+ let date = instant.toZonedDateTimeISO(timing.timezone).toPlainDate();
74
+ const time = Temporal.PlainTime.from(timing.time);
75
+ // IANA transitions can skip a date, but cannot exhaust a week of daily candidates.
76
+ for (let day = 0; day < 8; day++, date = date.add({ days: 1 })) {
77
+ const civil = date.toPlainDateTime(time);
78
+ const candidate = civil.toZonedDateTime(timing.timezone, { disambiguation: 'earlier' });
79
+ if (!candidate.toPlainDateTime().equals(civil))
80
+ continue;
81
+ const due = candidate.epochMilliseconds;
82
+ if (due > after)
83
+ return timestamp.parse(due);
84
+ }
85
+ throw new Error('No representable future occurrence');
86
+ }
87
+ /** Advance an interval in constant time; daily timing is resolved directly at the target date. */
88
+ export function advancePast(timing, due, through) {
89
+ timestamp.parse(due);
90
+ timestamp.parse(through);
91
+ if (due > through)
92
+ return due;
93
+ if (timing.kind === 'interval') {
94
+ const interval = intervalMilliseconds(timing);
95
+ return timestamp.parse(due + (Math.floor((through - due) / interval) + 1) * interval);
96
+ }
97
+ return nextOccurrence(timing, through);
98
+ }
99
+ export function isActiveOccurrence(value) {
100
+ return ['provisioning', 'running', 'recovery-required'].includes(value.status);
101
+ }
102
+ export function projectExecution(occurrence, execution, now) {
103
+ if (execution.occurrenceId !== occurrence.id)
104
+ throw new Error('Execution occurrence mismatch');
105
+ const { finishedAt: _, ...saved } = occurrence;
106
+ return { ...saved, executionId: execution.id, ...(execution.sessionId ? { sessionId: execution.sessionId } : {}), status: execution.status,
107
+ ...(isActiveOccurrence(execution) ? {} : { finishedAt: execution.finishedAt ?? now }) };
108
+ }
109
+ export function createSchedule(settings, now, enabled = false) {
110
+ const validated = scheduleSettingsValidator.parse(settings);
111
+ timestamp.parse(now);
112
+ return scheduleValidator.parse({ ...validated, version: 1, id: randomUUID(), revision: 1, activation: enabled ? 1 : 0, enabled, createdAt: now, updatedAt: now, ...(enabled ? { nextDue: nextOccurrence(validated.timing, now) } : {}) });
113
+ }
114
+ /** Timing edits and false→true activation reset the anchor; unrelated edits preserve it. */
115
+ export function editSchedule(saved, settings, enabled, now) {
116
+ scheduleValidator.parse(saved);
117
+ timestamp.parse(now);
118
+ if (saved.deletedAt !== undefined)
119
+ throw new Error('Schedule was deleted');
120
+ const validated = scheduleSettingsValidator.parse(settings);
121
+ const activate = enabled && (!saved.enabled || !isDeepStrictEqual(saved.timing, validated.timing));
122
+ const { nextDue: previousDue, ...rest } = saved;
123
+ return scheduleValidator.parse({ ...rest, ...validated, revision: saved.revision + 1, activation: saved.activation + Number(activate), enabled, updatedAt: now,
124
+ ...(enabled ? { nextDue: activate ? nextOccurrence(validated.timing, now) : previousDue } : {}) });
125
+ }
126
+ export function occurrenceSettings(schedule) {
127
+ const { name, workflowId, input, projectId, mcpConnectionIds, timing, concurrency, worktree } = schedule;
128
+ return structuredClone({ name, workflowId, input, projectId, mcpConnectionIds, timing, concurrency, ...(worktree ? { worktree } : {}) });
129
+ }