@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.
- package/README.md +27 -1
- package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
- package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-JV6MWPW7.mjs} +1901 -45
- package/build/backend-worker.mjs +52 -116
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/index.js +106 -16
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/fake/index.js +26 -5
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/index.js +38 -12
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/worker/entry.js +32 -6
- package/dist/backend/worker/index.js +87 -7
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/client/reduce.js +11 -3
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-summary.js +26 -15
- package/dist/daemon/git.js +10 -7
- package/dist/daemon/host.js +100 -22
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/runtime.js +63 -3
- package/dist/daemon/server.js +3 -0
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/workflow-environment.js +191 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +272 -285
- package/dist/daemon/workflow-schedule-driver.js +247 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +341 -0
- package/dist/isolation/filesystem.js +5 -1
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/tui/render.js +7 -1
- package/dist/workflows/calls.js +10 -7
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +1 -1
- package/dist/workflows/invocations.js +8 -5
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +8 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +29 -18
- package/dist/workflows/schedules.js +129 -0
- package/dist/workflows/store.js +110 -11
- package/package.json +8 -5
- package/web/dist/assets/index-BWKZK5HD.css +2 -0
- package/web/dist/assets/index-nIc09tKZ.js +40 -0
- package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-bcNKV147.js} +1 -1
- package/web/dist/assets/settings-workflows-C_TKOhVa.js +23 -0
- package/web/dist/assets/workflows-DHG-CIo3.js +146 -0
- package/web/dist/assets/workflows-pane-9u_hJvgQ.js +1 -0
- package/web/dist/index.html +4 -3
- package/build/backend-worker-chunks/claude-COCNALN2.mjs +0 -30846
- package/web/dist/assets/index-CLdr6AA0.js +0 -40
- package/web/dist/assets/index-DHAcGIoF.css +0 -2
- package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
- package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
- package/web/dist/assets/workflows-CdDynCfW.js +0 -7
- 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
|
+
}
|
|
@@ -333,7 +333,11 @@ export async function prepareFilesystemIsolation(options) {
|
|
|
333
333
|
}
|
|
334
334
|
};
|
|
335
335
|
if (options.credentials === "pi") {
|
|
336
|
-
|
|
336
|
+
const auth = join(piDir, 'auth.json');
|
|
337
|
+
if (existsSync(auth) && (!statSync(auth).isFile() || realpathSync(auth) !== resolve(auth))) {
|
|
338
|
+
throw new Error(`Credential must be a regular, non-symlink file: ${auth}`);
|
|
339
|
+
}
|
|
340
|
+
for (const name of ["models.json", "settings.json"])
|
|
337
341
|
stage(join(piDir, name), join(env.PI_CODING_AGENT_DIR, name));
|
|
338
342
|
if (!options.workflowBuilder)
|
|
339
343
|
resources("Pi", piDir, env.PI_CODING_AGENT_DIR, ["AGENTS.md", "skills", "prompts", "themes", "extensions", "packages", "bin", "tools"]);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { existsSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
-
import { isAbsolute, join, sep } from "node:path";
|
|
2
|
+
import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, isAbsolute, join, sep } from "node:path";
|
|
4
4
|
import { sandboxSupervisorSource } from "./sandbox-supervisor.js";
|
|
5
5
|
const placeholders = {
|
|
6
6
|
probe: { allowed: [], required: [] },
|
|
@@ -19,12 +19,14 @@ export function parseSandboxProvider(text) {
|
|
|
19
19
|
const value = JSON.parse(text);
|
|
20
20
|
if (!value || typeof value !== "object" || value.version !== 1)
|
|
21
21
|
throw new Error("version must be 1");
|
|
22
|
-
for (const key of ["nodePath", "claudePath", "claudeAuthDir"]) {
|
|
23
|
-
if (key
|
|
22
|
+
for (const key of ["nodePath", "claudePath", "hostClaudePath", "claudeAuthDir"]) {
|
|
23
|
+
if (key !== "nodePath" && value[key] === undefined)
|
|
24
24
|
continue;
|
|
25
25
|
if (typeof value[key] !== "string" || !isAbsolute(value[key]))
|
|
26
26
|
throw new Error(`${key} must be an absolute path`);
|
|
27
27
|
}
|
|
28
|
+
if (value.claudePath !== undefined && value.hostClaudePath !== undefined)
|
|
29
|
+
throw new Error("set claudePath or hostClaudePath, not both");
|
|
28
30
|
for (const [command, { allowed, required }] of Object.entries(placeholders)) {
|
|
29
31
|
const template = value[command];
|
|
30
32
|
if (command === "shell" && template === undefined)
|
|
@@ -42,6 +44,31 @@ export function parseSandboxProvider(text) {
|
|
|
42
44
|
}
|
|
43
45
|
return value;
|
|
44
46
|
}
|
|
47
|
+
const elfMachines = { x64: 62, arm64: 183 };
|
|
48
|
+
/** Resolves a host-installed native Claude and the dedicated directory that holds its versions. */
|
|
49
|
+
export function hostClaude(path) {
|
|
50
|
+
const executable = realpathSync(path);
|
|
51
|
+
if (!statSync(executable).isFile())
|
|
52
|
+
throw new Error(`host Claude ${executable} is not a file`);
|
|
53
|
+
const header = Buffer.alloc(20);
|
|
54
|
+
const fd = openSync(executable, "r");
|
|
55
|
+
try {
|
|
56
|
+
readSync(fd, header, 0, header.length, 0);
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
closeSync(fd);
|
|
60
|
+
}
|
|
61
|
+
if (header.readUInt32BE(0) !== 0x7f454c46)
|
|
62
|
+
throw new Error(`host Claude ${executable} is not a Linux native executable; the sandbox cannot run it`);
|
|
63
|
+
const machine = header[5] === 1 ? header.readUInt16LE(18) : header.readUInt16BE(18);
|
|
64
|
+
if (header[4] !== 2 || machine !== elfMachines[process.arch])
|
|
65
|
+
throw new Error(`host Claude ${executable} is not a 64-bit ${process.arch} executable`);
|
|
66
|
+
const directory = dirname(executable);
|
|
67
|
+
const other = readdirSync(directory, { withFileTypes: true }).find((entry) => !entry.isFile());
|
|
68
|
+
if (other)
|
|
69
|
+
throw new Error(`host Claude directory ${directory} holds ${other.name}, which is not a regular file; only a dedicated versions directory is mounted`);
|
|
70
|
+
return { executable, directory };
|
|
71
|
+
}
|
|
45
72
|
export function fillTemplate(template, values) {
|
|
46
73
|
return template.map((part) => {
|
|
47
74
|
const key = /^\{(.+)\}$/.exec(part)?.[1];
|
|
@@ -100,7 +127,19 @@ function runProvider(argv, timeoutMs, signal) {
|
|
|
100
127
|
});
|
|
101
128
|
});
|
|
102
129
|
}
|
|
130
|
+
/** Reclaim an occurrence-owned VM even if no execution checkpoint was written.
|
|
131
|
+
* Keep its ownership record on provider failure so pruning can retry safely. */
|
|
132
|
+
export async function removeOwnedSandbox(provider, specPath, expectedName) {
|
|
133
|
+
if (!existsSync(specPath))
|
|
134
|
+
return;
|
|
135
|
+
const saved = JSON.parse(readFileSync(specPath, 'utf8'));
|
|
136
|
+
if (saved.schemaVersion !== '1' || saved.name !== expectedName)
|
|
137
|
+
throw new Error('Invalid Sandbox ownership record');
|
|
138
|
+
await runProvider(fillTemplate(provider.remove, { name: expectedName }), 120_000);
|
|
139
|
+
rmSync(specPath, { force: true });
|
|
140
|
+
}
|
|
103
141
|
export async function createSandbox(provider, spec, specPath, signal) {
|
|
142
|
+
signal?.throwIfAborted();
|
|
104
143
|
for (const mount of spec.mounts) {
|
|
105
144
|
const stat = statSync(mount.path);
|
|
106
145
|
if (realpathSync(mount.path) !== mount.path || stat.dev !== mount.dev || stat.ino !== mount.ino)
|
|
@@ -117,6 +156,7 @@ export async function createSandbox(provider, spec, specPath, signal) {
|
|
|
117
156
|
const startup = { remove: performance.now() - start, create: 0 };
|
|
118
157
|
start = performance.now();
|
|
119
158
|
try {
|
|
159
|
+
signal?.throwIfAborted();
|
|
120
160
|
await runProvider(fillTemplate(provider.create, { spec: specPath, name: spec.name }), 600_000, signal);
|
|
121
161
|
}
|
|
122
162
|
catch (error) {
|
|
@@ -124,16 +164,10 @@ export async function createSandbox(provider, spec, specPath, signal) {
|
|
|
124
164
|
throw error;
|
|
125
165
|
}
|
|
126
166
|
startup.create = performance.now() - start;
|
|
127
|
-
let holds = 0, closed = false
|
|
128
|
-
let
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const settle = () => {
|
|
132
|
-
if (closed && !holds && !removing) {
|
|
133
|
-
removing = true;
|
|
134
|
-
finish(remove().then(() => rmSync(specPath, { force: true })));
|
|
135
|
-
}
|
|
136
|
-
};
|
|
167
|
+
let holds = 0, closed = false;
|
|
168
|
+
let unheld;
|
|
169
|
+
let drained = Promise.resolve();
|
|
170
|
+
let removal;
|
|
137
171
|
return {
|
|
138
172
|
name: spec.name,
|
|
139
173
|
nodePath: provider.nodePath,
|
|
@@ -141,15 +175,24 @@ export async function createSandbox(provider, spec, specPath, signal) {
|
|
|
141
175
|
hold: () => {
|
|
142
176
|
if (closed)
|
|
143
177
|
throw new Error(`Sandbox ${spec.name} is stopping`);
|
|
144
|
-
holds
|
|
178
|
+
if (!holds++)
|
|
179
|
+
drained = new Promise(resolve => { unheld = resolve; });
|
|
145
180
|
let released = false;
|
|
146
181
|
return () => { if (!released) {
|
|
147
182
|
released = true;
|
|
148
|
-
holds
|
|
149
|
-
|
|
183
|
+
if (!--holds)
|
|
184
|
+
unheld();
|
|
150
185
|
} };
|
|
151
186
|
},
|
|
152
|
-
close: () => {
|
|
187
|
+
close: () => {
|
|
188
|
+
closed = true;
|
|
189
|
+
return removal ??= (async () => {
|
|
190
|
+
if (holds)
|
|
191
|
+
await drained;
|
|
192
|
+
await remove();
|
|
193
|
+
rmSync(specPath, { force: true });
|
|
194
|
+
})().catch(error => { removal = undefined; throw error; });
|
|
195
|
+
},
|
|
153
196
|
command: (cwd, argv, env) => {
|
|
154
197
|
const [command, ...args] = fillTemplate(provider.exec, { name: spec.name, cwd });
|
|
155
198
|
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 {};
|
package/dist/tui/render.js
CHANGED
|
@@ -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
|
|
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) {
|
package/dist/workflows/calls.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
}
|
|
@@ -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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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),
|
|
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
|
+
}
|