@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10

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 (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  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-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -0,0 +1,342 @@
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
+ async create(settings, enabled) {
258
+ await this.driver.validate(settings);
259
+ return this.serial(() => { const saved = createSchedule(settings, this.now(), enabled); this.store.saveSchedule(saved); return saved; });
260
+ }
261
+ async update(id, revision, settings, enabled) {
262
+ await this.driver.validate(settings);
263
+ return this.serial(() => {
264
+ const current = this.store.getSchedule(id);
265
+ if (current.revision !== revision)
266
+ throw new ScheduleRevisionConflict();
267
+ const saved = editSchedule(current, settings, enabled, this.now());
268
+ this.store.saveSchedule(saved, revision);
269
+ return saved;
270
+ });
271
+ }
272
+ pause(id, revision) {
273
+ return this.serial(() => {
274
+ const current = this.store.getSchedule(id);
275
+ if (current.revision !== revision)
276
+ throw new ScheduleRevisionConflict();
277
+ const saved = editSchedule(current, occurrenceSettings(current), false, this.now());
278
+ this.store.saveSchedule(saved, revision);
279
+ return saved;
280
+ });
281
+ }
282
+ delete(id, revision) { return this.serial(() => this.store.deleteSchedule(id, revision, this.now())); }
283
+ preview(settings) { return nextOccurrence(settings.timing, this.now()); }
284
+ retryAttachment(id) {
285
+ return this.forOccurrence(id, async () => {
286
+ const occurrence = this.store.getOccurrence(id);
287
+ if (occurrence.status !== 'recovery-required' || occurrence.association !== 'failed')
288
+ throw new ScheduleValidationError('Attachment is not available');
289
+ try {
290
+ await this.driver.reconcile(occurrence);
291
+ this.reconciliations.delete(id);
292
+ }
293
+ catch {
294
+ throw new Error('Workflow Occurrence attachment failed. Durable work has been retained.');
295
+ }
296
+ });
297
+ }
298
+ cancel(id) {
299
+ this.launches.get(id)?.controller.abort();
300
+ return this.forOccurrence(id, async () => {
301
+ const occurrence = this.store.getOccurrence(id);
302
+ try {
303
+ await this.driver.cancel(occurrence);
304
+ this.reconciliations.delete(id);
305
+ }
306
+ catch {
307
+ throw new Error('Workflow Occurrence cancellation failed. Durable work has been retained.');
308
+ }
309
+ }).finally(() => this.sweepUnstartedCleanup());
310
+ }
311
+ async prune() {
312
+ await this.serial(() => { this.flushPending(); });
313
+ this.sweepUnstartedCleanup();
314
+ return this.store.prune(this.now(), occurrence => this.forOccurrence(occurrence.id, () => this.driver.cleanup(occurrence)), id => !this.occurrenceQueues.has(id));
315
+ }
316
+ hasActiveWork() { return this.launches.size > 0 || this.store.activeCount() > 0; }
317
+ async stopAdmission() {
318
+ this.stopped = true;
319
+ clearTimeout(this.timer);
320
+ for (const launch of this.launches.values())
321
+ launch.controller.abort();
322
+ await this.queue;
323
+ await Promise.all([...this.launches.values()].map(launch => launch.done));
324
+ while (this.occurrenceQueues.size || this.reconciling.size || this.cleanups.size) {
325
+ await Promise.all([...this.occurrenceQueues.values(), ...this.reconciling.values(), ...this.cleanups.values()]);
326
+ }
327
+ }
328
+ result(record) {
329
+ if (!record.occurrenceId)
330
+ return;
331
+ const durable = this.store.getStoredOccurrence(record.occurrenceId);
332
+ if (!isActiveOccurrence(durable)) {
333
+ this.pendingUpdates.delete(durable.id);
334
+ return;
335
+ }
336
+ const saved = this.project(durable), projected = projectExecution(saved, this.driver.current?.(saved) ?? record, this.now());
337
+ if (this.occurrenceQueues.has(saved.id))
338
+ this.pendingUpdates.set(saved.id, projected);
339
+ else
340
+ this.persist(projected);
341
+ }
342
+ }
@@ -307,7 +307,7 @@ export async function prepareFilesystemIsolation(options) {
307
307
  const privateHome = join(scratch, "home");
308
308
  mkdirSync(join(privateHome, ".pi/agent"), { recursive: true, mode: 0o700 });
309
309
  mkdirSync(join(privateHome, ".claude"), { mode: 0o700 });
310
- args.push("--bind-fd", pinned(scope, options.expectedScopeIdentity), scope, "--dir", virtualRoot, "--bind-fd", pinned(privateHome), virtualHome, "--dir", `${virtualRoot}/run`, "--bind-fd", pinned(backend), virtualState);
310
+ args.push(options.scopeReadOnly ? "--ro-bind-fd" : "--bind-fd", pinned(scope, options.expectedScopeIdentity), scope, "--dir", virtualRoot, "--bind-fd", pinned(privateHome), virtualHome, "--dir", `${virtualRoot}/run`, "--bind-fd", pinned(backend), virtualState);
311
311
  for (const path of directoryMasks)
312
312
  args.push("--remount-ro", path);
313
313
  const stage = (source, destination) => {
@@ -333,7 +333,11 @@ export async function prepareFilesystemIsolation(options) {
333
333
  }
334
334
  };
335
335
  if (options.credentials === "pi") {
336
- for (const name of ["auth.json", "models.json", "settings.json"])
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 === "claudeAuthDir" && value[key] === undefined)
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, removing = false;
128
- let finish;
129
- const removed = new Promise((resolve) => { finish = resolve; });
130
- removed.catch(() => { });
131
- const settle = () => {
132
- if (closed && !holds && !removing) {
133
- removing = true;
134
- finish(remove().then(() => rmSync(specPath, { force: true })));
135
- }
136
- };
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
- settle();
183
+ if (!--holds)
184
+ unheld();
150
185
  } };
151
186
  },
152
- close: () => { closed = true; settle(); return removed; },
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) {
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
2
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
- import { nodeExecutionAssets } from "./node-assets.js";
3
+ import { nodeExecutionAssets } from './node-assets.js';
4
4
  /** Discover assets only; the filesystem policy must validate and pin every returned path. */
5
5
  export function pathToolchainAssets(path, scope, hidden, protectedPath) {
6
6
  const assets = new Set();
@@ -17,4 +17,7 @@ export const HOST_OWNED_EVENT_TYPES = [
17
17
  "session_ended",
18
18
  "branch_changed",
19
19
  "workflow_spend",
20
+ "rewound",
21
+ "forked",
22
+ "diff_excerpts",
20
23
  ];
@@ -0,0 +1 @@
1
+ export {};
@@ -12,6 +12,7 @@
12
12
  * they mean on disk; this file owns only their shape.
13
13
  */
14
14
  export const DEFAULT_WORKFLOW_RUNTIME = {};
15
+ export const WHISPER_MODELS = ["tiny", "base", "small", "medium"];
15
16
  /** Explicitly configured backends never silently fall back to a different inference route. */
16
17
  export function resolveDefaultBackend(backends, configured) {
17
18
  return configured ?? (backends.includes("claude") ? "claude" : backends[0]);
@@ -0,0 +1,2 @@
1
+ export const SPEND_SOURCES = ["session", "workflow", "naming", "publish", "tour", "builder"];
2
+ export const SPEND_WINDOWS = ["day", "week", "month", "lifetime"];
@@ -1,41 +1,14 @@
1
- /** Normalize display data in the daemon. Never mutates its inputs. */
2
- export function stackDisplayGraph(status) {
3
- const { graph, view, candidate } = status;
4
- let display = graph ? { ...graph, branches: graph.branches.map(branch => ({ ...branch, ...(branch.pr ? { pr: { ...branch.pr } } : {}) })) } : undefined;
5
- if (!display && view && view.currentBranch !== view.trunk) {
6
- let parent = view.trunk;
7
- display = { trunk: view.trunk, currentBranch: view.currentBranch, explicit: true, branches: view.branches.map(member => {
8
- const branch = { name: member.name, parent, relation: "local", isCurrent: member.isCurrent, availability: "local", ...(member.pr ? { pr: { ...member.pr, state: member.isMerged ? "MERGED" : member.pr.state } } : {}) };
9
- parent = member.name;
10
- return branch;
11
- }) };
1
+ export function stackMergeBlock(view) {
2
+ const open = view.branches.filter(branch => !branch.isMerged);
3
+ if (!open.length)
4
+ return "All pull requests of this stack are merged.";
5
+ for (const { name, pr } of open) {
6
+ if (!pr)
7
+ return `${name} has no pull request. Submit the stack first.`;
8
+ if (pr.state !== "OPEN")
9
+ return `#${pr.number} is ${pr.state.toLowerCase()}.`;
10
+ if (pr.isDraft)
11
+ return `#${pr.number} is a draft. Mark it ready for review first.`;
12
12
  }
13
- if (!display && candidate)
14
- display = { trunk: candidate.trunk, currentBranch: candidate.branches.at(-1) ?? "", explicit: false, branches: [] };
15
- if (!display)
16
- return;
17
- const byName = new Map(display.branches.map(branch => [branch.name, branch]));
18
- let parent = view?.trunk;
19
- for (const member of view?.branches ?? []) {
20
- const pr = member.pr ? { ...member.pr, state: member.isMerged ? "MERGED" : member.pr.state } : undefined;
21
- const branch = byName.get(member.name) ?? { name: member.name, ...(parent ? { parent } : {}), relation: "local", isCurrent: member.isCurrent, availability: "local" };
22
- Object.assign(branch, { isCurrent: member.isCurrent, ...(pr ? { pr } : {}) });
23
- if (!byName.has(member.name)) {
24
- display.branches.push(branch);
25
- byName.set(member.name, branch);
26
- }
27
- parent = member.name;
28
- }
29
- parent = candidate?.trunk;
30
- for (const pr of candidate?.pullRequests ?? []) {
31
- const name = pr.branch;
32
- const branch = byName.get(name) ?? { name, ...(parent ? { parent } : {}), relation: "pull-request", isCurrent: name === display.currentBranch, availability: "local" };
33
- branch.pr = { ...pr };
34
- if (!byName.has(name)) {
35
- display.branches.push(branch);
36
- byName.set(name, branch);
37
- }
38
- parent = name;
39
- }
40
- return display;
13
+ return undefined;
41
14
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,53 @@
1
+ import { validateDefinition } from './graph.js';
2
+ import { WorkflowValidationError } from './errors.js';
3
+ function canonical(value) {
4
+ if (Array.isArray(value))
5
+ return value.map(canonical);
6
+ if (value !== null && typeof value === 'object')
7
+ return Object.fromEntries(Object.entries(value).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => [key, canonical(value)]));
8
+ return value;
9
+ }
10
+ export function deriveResultSchema(definition) {
11
+ return validateDefinition(definition).resultSchema;
12
+ }
13
+ export function resolveWorkflowCalls(definition, lookup, testStepId) {
14
+ const retained = new Map();
15
+ const visited = new Set();
16
+ const visit = (candidate, ancestry, selected) => {
17
+ if (ancestry.has(candidate.id))
18
+ throw new WorkflowValidationError(`Recursive Workflow call: ${candidate.id}`);
19
+ const graph = validateDefinition(candidate);
20
+ const current = graph.definition;
21
+ if (selected !== undefined && !current.steps.some(step => step.id === selected))
22
+ throw new WorkflowValidationError('Unknown test step');
23
+ retained.set(current.id, current);
24
+ const path = new Set([...ancestry, current.id]);
25
+ for (const step of current.steps) {
26
+ if (step.kind !== 'workflow' || (selected !== undefined && step.id !== selected))
27
+ continue;
28
+ if (path.has(step.workflowId))
29
+ throw new WorkflowValidationError(`Recursive Workflow call: ${step.workflowId}`);
30
+ let target = retained.get(step.workflowId);
31
+ if (!target) {
32
+ try {
33
+ target = lookup(step.workflowId);
34
+ }
35
+ catch (error) {
36
+ if (error?.code === 'ENOENT')
37
+ throw new WorkflowValidationError(`Missing Workflow call target: ${step.workflowId}`);
38
+ throw error;
39
+ }
40
+ }
41
+ if (!target || target.id !== step.workflowId)
42
+ throw new WorkflowValidationError(`Missing Workflow call target: ${step.workflowId}`);
43
+ const called = validateDefinition(target);
44
+ if (JSON.stringify(canonical(step.contract.inputSchema)) !== JSON.stringify(canonical(called.definition.inputSchema)) || JSON.stringify(canonical(step.contract.outputSchema)) !== JSON.stringify(canonical(called.resultSchema)))
45
+ throw new WorkflowValidationError(`Workflow call contract does not match target: ${step.workflowId}`);
46
+ if (!visited.has(target.id))
47
+ visit(called.definition, path);
48
+ }
49
+ visited.add(current.id);
50
+ };
51
+ visit(definition, new Set(), testStepId);
52
+ return Object.fromEntries(retained);
53
+ }
@@ -0,0 +1,2 @@
1
+ export class WorkflowValidationError extends Error {
2
+ }