@nathanstephenson/flow 0.1.10-beta.2 → 0.1.10-beta.4

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 (79) hide show
  1. package/README.md +27 -1
  2. package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
  7. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-JV6MWPW7.mjs} +1901 -45
  8. package/build/backend-worker.mjs +52 -116
  9. package/dist/backend/claude/background-calls.js +7 -3
  10. package/dist/backend/claude/index.js +106 -16
  11. package/dist/backend/claude/subagents.js +41 -9
  12. package/dist/backend/fake/index.js +26 -5
  13. package/dist/backend/pi/cache-warming.js +8 -0
  14. package/dist/backend/pi/canonical-json.js +120 -0
  15. package/dist/backend/pi/compaction-model.js +3 -2
  16. package/dist/backend/pi/host-auth.js +258 -0
  17. package/dist/backend/pi/index.js +38 -12
  18. package/dist/backend/pi/model-auth.js +159 -0
  19. package/dist/backend/pi/model-catalog.js +120 -0
  20. package/dist/backend/pi/model-config.js +5 -0
  21. package/dist/backend/pi/model-selection.js +32 -0
  22. package/dist/backend/pi/subagents.js +7 -3
  23. package/dist/backend/pi/work.js +9 -1
  24. package/dist/backend/pi/workflow-subagent.js +4 -3
  25. package/dist/backend/worker/entry.js +32 -6
  26. package/dist/backend/worker/index.js +87 -7
  27. package/dist/backend/worker/rpc.js +13 -0
  28. package/dist/backend/worker/sandbox-mcp.js +18 -7
  29. package/dist/build-id +1 -1
  30. package/dist/cli/bootstrap.js +1 -1
  31. package/dist/client/reduce.js +11 -3
  32. package/dist/client/subagent-tree.js +49 -0
  33. package/dist/client/tool-summary.js +26 -15
  34. package/dist/daemon/git.js +10 -7
  35. package/dist/daemon/host.js +100 -22
  36. package/dist/daemon/models.js +2 -2
  37. package/dist/daemon/pi-model-cache.js +44 -0
  38. package/dist/daemon/runtime.js +63 -3
  39. package/dist/daemon/server.js +3 -0
  40. package/dist/daemon/store.js +2 -0
  41. package/dist/daemon/workflow-environment.js +191 -0
  42. package/dist/daemon/workflow-execution-launch.js +77 -0
  43. package/dist/daemon/workflow-execution-resources.js +76 -0
  44. package/dist/daemon/workflow-execution-values.js +128 -0
  45. package/dist/daemon/workflow-executions.js +272 -285
  46. package/dist/daemon/workflow-schedule-driver.js +247 -0
  47. package/dist/daemon/workflow-schedule-routes.js +137 -0
  48. package/dist/daemon/workflow-schedules.js +341 -0
  49. package/dist/isolation/filesystem.js +5 -1
  50. package/dist/isolation/sandbox.js +61 -18
  51. package/dist/isolation/shared-sandbox.js +3 -3
  52. package/dist/protocol/workflow-schedules.js +1 -0
  53. package/dist/tui/render.js +7 -1
  54. package/dist/workflows/calls.js +10 -7
  55. package/dist/workflows/errors.js +2 -0
  56. package/dist/workflows/executors.js +1 -1
  57. package/dist/workflows/invocations.js +8 -5
  58. package/dist/workflows/owner.js +45 -0
  59. package/dist/workflows/records.js +8 -2
  60. package/dist/workflows/schedule-errors.js +2 -0
  61. package/dist/workflows/schedule-store.js +385 -0
  62. package/dist/workflows/scheduler.js +29 -18
  63. package/dist/workflows/schedules.js +129 -0
  64. package/dist/workflows/store.js +110 -11
  65. package/package.json +8 -5
  66. package/web/dist/assets/index-BWKZK5HD.css +2 -0
  67. package/web/dist/assets/index-nIc09tKZ.js +40 -0
  68. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-bcNKV147.js} +1 -1
  69. package/web/dist/assets/settings-workflows-C_TKOhVa.js +23 -0
  70. package/web/dist/assets/workflows-DHG-CIo3.js +146 -0
  71. package/web/dist/assets/workflows-pane-9u_hJvgQ.js +1 -0
  72. package/web/dist/index.html +4 -3
  73. package/build/backend-worker-chunks/claude-COCNALN2.mjs +0 -30846
  74. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  75. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  76. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  77. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  78. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  79. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
@@ -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
+ }
@@ -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)