@1agents/acp-service 0.3.0 → 0.4.0

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 (72) hide show
  1. package/README.md +57 -33
  2. package/dist/bin/acp-service.js +2 -2
  3. package/dist/src/bridge.d.ts +2 -2
  4. package/dist/src/bridge.js +1 -1
  5. package/dist/src/catalog.js +20 -3
  6. package/dist/src/manifest.js +1 -1
  7. package/package.json +27 -8
  8. package/vendor/runtime/LICENSE +21 -0
  9. package/vendor/runtime/README.md +115 -0
  10. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js +806 -0
  11. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +1 -0
  12. package/vendor/runtime/dist/agent-registry.d.ts +70 -0
  13. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -0
  14. package/vendor/runtime/dist/agent-registry.js +2 -0
  15. package/vendor/runtime/dist/cli-DUHyAADv.js +182 -0
  16. package/vendor/runtime/dist/cli-DUHyAADv.js.map +1 -0
  17. package/vendor/runtime/dist/cli.d.ts +12 -0
  18. package/vendor/runtime/dist/cli.d.ts.map +1 -0
  19. package/vendor/runtime/dist/cli.js +2632 -0
  20. package/vendor/runtime/dist/cli.js.map +1 -0
  21. package/vendor/runtime/dist/client-DjkWknf7.d.ts +262 -0
  22. package/vendor/runtime/dist/client-DjkWknf7.d.ts.map +1 -0
  23. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  24. package/vendor/runtime/dist/docs-site/CLI.html +832 -0
  25. package/vendor/runtime/dist/docs-site/CNAME +1 -0
  26. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  27. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  28. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  29. package/vendor/runtime/dist/docs-site/config.html +450 -0
  30. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  31. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  32. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  33. package/vendor/runtime/dist/docs-site/flows.html +497 -0
  34. package/vendor/runtime/dist/docs-site/index.html +367 -0
  35. package/vendor/runtime/dist/docs-site/install.html +386 -0
  36. package/vendor/runtime/dist/docs-site/llms.txt +35 -0
  37. package/vendor/runtime/dist/docs-site/output-formats.html +403 -0
  38. package/vendor/runtime/dist/docs-site/permissions.html +413 -0
  39. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  40. package/vendor/runtime/dist/docs-site/proof-2026-07-18-grok-ext-methods/index.html +336 -0
  41. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  42. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  43. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  44. package/vendor/runtime/dist/docs-site/session-control.html +406 -0
  45. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  46. package/vendor/runtime/dist/docs-site/sessions.html +486 -0
  47. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  48. package/vendor/runtime/dist/flows-CiJSCy4D.js +2474 -0
  49. package/vendor/runtime/dist/flows-CiJSCy4D.js.map +1 -0
  50. package/vendor/runtime/dist/flows.d.ts +334 -0
  51. package/vendor/runtime/dist/flows.d.ts.map +1 -0
  52. package/vendor/runtime/dist/flows.js +2 -0
  53. package/vendor/runtime/dist/invocation-options-BlIySxIw.js +345 -0
  54. package/vendor/runtime/dist/invocation-options-BlIySxIw.js.map +1 -0
  55. package/vendor/runtime/dist/ipc-BlljKR2b.js +5336 -0
  56. package/vendor/runtime/dist/ipc-BlljKR2b.js.map +1 -0
  57. package/vendor/runtime/dist/output-BzXQKArM.js +1012 -0
  58. package/vendor/runtime/dist/output-BzXQKArM.js.map +1 -0
  59. package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js +8867 -0
  60. package/vendor/runtime/dist/queue-owner-runtime-DSFdsS_y.js.map +1 -0
  61. package/vendor/runtime/dist/runtime.d.ts +1156 -0
  62. package/vendor/runtime/dist/runtime.d.ts.map +1 -0
  63. package/vendor/runtime/dist/runtime.js +3675 -0
  64. package/vendor/runtime/dist/runtime.js.map +1 -0
  65. package/vendor/runtime/dist/session-options-ORCchZGk.d.ts +426 -0
  66. package/vendor/runtime/dist/session-options-ORCchZGk.d.ts.map +1 -0
  67. package/vendor/runtime/dist/session-watch-BiBTBMz4.js +76 -0
  68. package/vendor/runtime/dist/session-watch-BiBTBMz4.js.map +1 -0
  69. package/vendor/runtime/dist/watch-iYiP-lOo.js +85 -0
  70. package/vendor/runtime/dist/watch-iYiP-lOo.js.map +1 -0
  71. package/vendor/runtime/package.json +46 -0
  72. package/vendor/runtime/skills/acpx/SKILL.md +688 -0
@@ -0,0 +1,2474 @@
1
+ import { a as MAX_TIMER_DELAY_MS, t as createOutputFormatter } from "./output-BzXQKArM.js";
2
+ import { At as PERMISSION_MODES, C as textPrompt, Mt as SESSION_RECORD_SCHEMA, R as resolveSessionRecord, S as promptToDisplayText, gt as writePrivateJsonFile, ht as writePrivateFile, ut as defaultSessionEventLog } from "./ipc-BlljKR2b.js";
3
+ import { P as runTimedExecFile } from "./agent-registry-CMg8LHKY.js";
4
+ import { G as recordSessionUpdate, H as createSessionConversation, U as recordClientOperation, W as recordPromptSubmission, dt as TimeoutError, i as runOnce, m as createSessionWithClient, mt as withTimeout, o as sendSessionDirect, pt as withInterrupt, q as cloneSessionAcpxState, ut as InterruptedError } from "./queue-owner-runtime-DSFdsS_y.js";
5
+ import path from "node:path";
6
+ import { spawn } from "node:child_process";
7
+ import fs from "node:fs/promises";
8
+ import os from "node:os";
9
+ import { appendRegularFile } from "@openclaw/fs-safe/advanced";
10
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
11
+ import { ZodError, z } from "zod";
12
+ import { createHash, randomUUID } from "node:crypto";
13
+ import { performance } from "node:perf_hooks";
14
+ //#region src/flows/timeout.ts
15
+ function resolveFlowTimeoutMs(timeoutMs) {
16
+ if (timeoutMs === void 0) return;
17
+ if (!Number.isFinite(timeoutMs) || timeoutMs > 2147483647) throw new TypeError(`timeoutMs must be a finite number no greater than ${MAX_TIMER_DELAY_MS}`);
18
+ return timeoutMs > 0 ? timeoutMs : void 0;
19
+ }
20
+ //#endregion
21
+ //#region src/flows/attempt.ts
22
+ /** One node attempt owns admission and completion of its managed operations. */
23
+ var FlowAttempt = class {
24
+ signal;
25
+ nodeId;
26
+ attemptId;
27
+ startedAt;
28
+ terminationSignal = "SIGTERM";
29
+ controller = new AbortController();
30
+ pending = /* @__PURE__ */ new Set();
31
+ cancellations = /* @__PURE__ */ new Set();
32
+ cleanupFailures = [];
33
+ deadlineAt;
34
+ timeoutMs;
35
+ timer;
36
+ accepting = true;
37
+ finished = false;
38
+ constructor(options) {
39
+ this.nodeId = options.nodeId;
40
+ this.attemptId = options.attemptId;
41
+ this.startedAt = options.startedAt;
42
+ this.signal = this.controller.signal;
43
+ const timeoutMs = resolveFlowTimeoutMs(options.timeoutMs);
44
+ if (timeoutMs !== void 0) {
45
+ this.timeoutMs = timeoutMs;
46
+ this.deadlineAt = performance.now() + timeoutMs;
47
+ this.timer = setTimeout(() => this.cancel(new TimeoutError(timeoutMs)), timeoutMs);
48
+ }
49
+ }
50
+ get active() {
51
+ return this.accepting && !this.signal.aborted;
52
+ }
53
+ assertActive() {
54
+ this.checkDeadline();
55
+ this.signal.throwIfAborted();
56
+ if (!this.accepting) throw new Error("Flow attempt has finished accepting work");
57
+ }
58
+ remainingTimeoutMs() {
59
+ this.assertActive();
60
+ return this.deadlineAt === void 0 ? void 0 : Math.max(1, Math.ceil(this.deadlineAt - performance.now()));
61
+ }
62
+ cancel(reason, signal = "SIGTERM") {
63
+ if (this.finished || this.signal.aborted) return;
64
+ this.accepting = false;
65
+ this.terminationSignal = signal;
66
+ this.controller.abort(reason);
67
+ for (const cancel of this.cancellations) this.trackCancellation(cancel);
68
+ }
69
+ registerCancellation(cancel) {
70
+ if (!this.active) {
71
+ this.trackCancellation(cancel);
72
+ return () => {};
73
+ }
74
+ this.cancellations.add(cancel);
75
+ return () => {
76
+ this.cancellations.delete(cancel);
77
+ };
78
+ }
79
+ /** Track runtime work, never an arbitrary user callback that may ignore cancellation. */
80
+ own(run, options = {}) {
81
+ this.assertActive();
82
+ const operation = run().then((value) => {
83
+ this.checkDeadline();
84
+ if (this.signal.aborted) this.signal.throwIfAborted();
85
+ return value;
86
+ });
87
+ const outcome = operation.then(() => ({ ok: true }), (error) => options.bestEffort ? { ok: true } : {
88
+ ok: false,
89
+ error
90
+ });
91
+ this.pending.add(outcome);
92
+ outcome.then(() => this.pending.delete(outcome));
93
+ return operation;
94
+ }
95
+ async run(run) {
96
+ let rejectAbort = () => {};
97
+ const aborted = new Promise((_resolve, reject) => {
98
+ rejectAbort = reject;
99
+ });
100
+ const onAbort = () => rejectAbort(this.signal.reason);
101
+ this.signal.addEventListener("abort", onAbort, { once: true });
102
+ try {
103
+ this.assertActive();
104
+ const value = await Promise.race([run(), aborted]);
105
+ this.accepting = false;
106
+ const errors = await this.drain();
107
+ if (errors.length > 0) throw this.cleanupError(errors);
108
+ this.checkDeadline();
109
+ this.signal.throwIfAborted();
110
+ return value;
111
+ } catch (error) {
112
+ this.cancel(error);
113
+ const errors = await this.drain();
114
+ if (errors.length > 0) throw this.cleanupError([error, ...errors]);
115
+ throw error;
116
+ } finally {
117
+ this.accepting = false;
118
+ this.finished = true;
119
+ clearTimeout(this.timer);
120
+ this.signal.removeEventListener("abort", onAbort);
121
+ }
122
+ }
123
+ checkDeadline() {
124
+ if (this.deadlineAt !== void 0 && performance.now() >= this.deadlineAt) this.cancel(new TimeoutError(this.timeoutMs));
125
+ }
126
+ async drain() {
127
+ const errors = [];
128
+ while (this.pending.size > 0) for (const outcome of await Promise.all(this.pending)) if (!outcome.ok && outcome.error !== this.signal.reason) errors.push(outcome.error);
129
+ return [.../* @__PURE__ */ new Set([...errors, ...this.cleanupFailures.splice(0)])];
130
+ }
131
+ trackCancellation(cancel) {
132
+ const outcome = Promise.resolve().then(() => cancel(this.terminationSignal)).then(() => ({ ok: true }), (error) => {
133
+ this.cleanupFailures.push(error);
134
+ return { ok: true };
135
+ });
136
+ this.pending.add(outcome);
137
+ outcome.then(() => this.pending.delete(outcome));
138
+ }
139
+ cleanupError(errors) {
140
+ const reason = this.signal.reason;
141
+ const failures = [.../* @__PURE__ */ new Set([...this.signal.aborted ? [reason] : [], ...errors])];
142
+ return new AggregateError(failures, "Flow attempt cleanup failed", { cause: failures[0] });
143
+ }
144
+ };
145
+ //#endregion
146
+ //#region src/flows/authoring.ts
147
+ const FLOW_DEFINITION_BRAND = Symbol.for("acpx.flow.definition");
148
+ function markDefinedFlow(definition) {
149
+ if (isDefinedFlow(definition)) return definition;
150
+ Object.defineProperty(definition, FLOW_DEFINITION_BRAND, {
151
+ value: true,
152
+ enumerable: false,
153
+ configurable: false,
154
+ writable: false
155
+ });
156
+ return definition;
157
+ }
158
+ function isDefinedFlow(value) {
159
+ return value != null && typeof value === "object" && value[FLOW_DEFINITION_BRAND] === true;
160
+ }
161
+ //#endregion
162
+ //#region src/flows/schema.ts
163
+ const FLOW_NODE_TYPES = [
164
+ "acp",
165
+ "compute",
166
+ "action",
167
+ "checkpoint"
168
+ ];
169
+ const finiteNonNegativeNumberSchema = z.number().finite().nonnegative();
170
+ const nonEmptyTrimmedStringSchema = z.string().refine((value) => value.trim().length > 0, { message: "must not be empty" });
171
+ function extensibleObject(shape) {
172
+ return z.object(shape).passthrough();
173
+ }
174
+ function functionSchema(label) {
175
+ return z.custom((value) => typeof value === "function", { message: `${label} must be a function` });
176
+ }
177
+ const flowNodeCommonShape = {
178
+ timeoutMs: finiteNonNegativeNumberSchema.max(MAX_TIMER_DELAY_MS).optional(),
179
+ heartbeatMs: finiteNonNegativeNumberSchema.optional(),
180
+ statusDetail: z.string().optional()
181
+ };
182
+ const flowPermissionRequirementsSchema = extensibleObject({
183
+ requiredMode: z.enum(PERMISSION_MODES),
184
+ requireExplicitGrant: z.boolean().optional(),
185
+ reason: nonEmptyTrimmedStringSchema.optional()
186
+ });
187
+ const flowRunDefinitionSchema = extensibleObject({ title: z.union([z.string(), functionSchema("run.title")]).optional() });
188
+ const acpSessionSchema = extensibleObject({
189
+ handle: z.string().optional(),
190
+ isolated: z.boolean().optional()
191
+ });
192
+ const acpNodeSchema = extensibleObject({
193
+ ...flowNodeCommonShape,
194
+ nodeType: z.literal("acp"),
195
+ profile: z.string().optional(),
196
+ cwd: z.union([z.string(), functionSchema("cwd")]).optional(),
197
+ session: acpSessionSchema.optional(),
198
+ prompt: functionSchema("prompt"),
199
+ parse: functionSchema("parse").optional()
200
+ });
201
+ const computeNodeSchema = extensibleObject({
202
+ ...flowNodeCommonShape,
203
+ nodeType: z.literal("compute"),
204
+ run: functionSchema("run")
205
+ });
206
+ const functionActionNodeSchema = extensibleObject({
207
+ ...flowNodeCommonShape,
208
+ nodeType: z.literal("action"),
209
+ run: functionSchema("run")
210
+ });
211
+ const shellActionNodeSchema = extensibleObject({
212
+ ...flowNodeCommonShape,
213
+ nodeType: z.literal("action"),
214
+ exec: functionSchema("exec"),
215
+ parse: functionSchema("parse").optional()
216
+ }).refine((node) => !hasOwn(node, "run"), { message: "shell action nodes must not define run" });
217
+ const checkpointNodeSchema = extensibleObject({
218
+ ...flowNodeCommonShape,
219
+ nodeType: z.literal("checkpoint"),
220
+ summary: z.string().optional(),
221
+ run: functionSchema("run").optional()
222
+ });
223
+ const directFlowEdgeSchema = extensibleObject({
224
+ from: z.string(),
225
+ to: z.string()
226
+ });
227
+ const switchFlowEdgeSchema = extensibleObject({
228
+ from: z.string(),
229
+ switch: extensibleObject({
230
+ on: z.string(),
231
+ cases: z.record(z.string(), z.string())
232
+ })
233
+ });
234
+ const flowDefinitionSchema = extensibleObject({
235
+ name: nonEmptyTrimmedStringSchema,
236
+ run: flowRunDefinitionSchema.optional(),
237
+ permissions: flowPermissionRequirementsSchema.optional(),
238
+ startAt: z.string(),
239
+ nodes: z.record(z.string(), z.unknown()),
240
+ edges: z.array(z.unknown())
241
+ });
242
+ const flowNodeTypeSchema = z.object({ nodeType: z.enum(FLOW_NODE_TYPES) });
243
+ function assertValidFlowDefinitionShape(flow) {
244
+ const parsed = parseWithSchema("flow definition", flowDefinitionSchema, flow);
245
+ for (const [nodeId, node] of Object.entries(flow.nodes)) assertValidFlowNodeDefinitionShape(node, `flow node "${nodeId}"`);
246
+ parsed.edges.forEach((edge, index) => {
247
+ assertValidFlowEdgeShape(edge, `flow definition: edges.${index}`);
248
+ });
249
+ }
250
+ function assertValidAcpNodeDefinition(node) {
251
+ parseWithSchema("acp node definition", acpNodeSchema, node);
252
+ }
253
+ function assertValidComputeNodeDefinition(node) {
254
+ parseWithSchema("compute node definition", computeNodeSchema, node);
255
+ }
256
+ function assertValidActionNodeDefinition(node) {
257
+ assertValidActionNodeDefinitionShape(node, "action node definition");
258
+ }
259
+ function assertValidShellActionNodeDefinition(node) {
260
+ parseWithSchema("shell action node definition", shellActionNodeSchema, node);
261
+ }
262
+ function assertValidCheckpointNodeDefinition(node) {
263
+ parseWithSchema("checkpoint node definition", checkpointNodeSchema, node);
264
+ }
265
+ function assertValidFlowNodeDefinitionShape(node, label) {
266
+ const { nodeType } = parseWithSchema(label, flowNodeTypeSchema, node);
267
+ switch (nodeType) {
268
+ case "acp":
269
+ parseWithSchema(label, acpNodeSchema, node);
270
+ return;
271
+ case "compute":
272
+ parseWithSchema(label, computeNodeSchema, node);
273
+ return;
274
+ case "action":
275
+ assertValidActionNodeDefinitionShape(node, label);
276
+ return;
277
+ case "checkpoint":
278
+ parseWithSchema(label, checkpointNodeSchema, node);
279
+ return;
280
+ }
281
+ }
282
+ function assertValidActionNodeDefinitionShape(node, label) {
283
+ const hasRun = hasOwn(node, "run");
284
+ const hasExec = hasOwn(node, "exec");
285
+ if (hasRun === hasExec) throw new Error(`Invalid ${label}: action nodes must define exactly one of run or exec`);
286
+ if (hasExec) {
287
+ parseWithSchema(label, shellActionNodeSchema, node);
288
+ return;
289
+ }
290
+ parseWithSchema(label, functionActionNodeSchema, node);
291
+ }
292
+ function assertValidFlowEdgeShape(edge, label) {
293
+ const hasTo = hasOwn(edge, "to");
294
+ if (hasTo === hasOwn(edge, "switch")) throw new Error(`Invalid ${label}: edge must define exactly one of to or switch`);
295
+ if (hasTo) {
296
+ parseWithSchema(label, directFlowEdgeSchema, edge);
297
+ return;
298
+ }
299
+ parseWithSchema(label, switchFlowEdgeSchema, edge);
300
+ const cases = edge.switch.cases;
301
+ for (const [key, target] of Object.entries(cases)) parseWithSchema(`${label}: switch.cases.${key}`, z.string(), target);
302
+ }
303
+ function parseWithSchema(label, schema, value) {
304
+ try {
305
+ return schema.parse(value);
306
+ } catch (error) {
307
+ if (error instanceof ZodError) throw new Error(formatValidationError(label, error), { cause: error });
308
+ throw error;
309
+ }
310
+ }
311
+ function formatValidationError(label, error) {
312
+ return `Invalid ${label}: ${Array.from(new Set(error.issues.flatMap((issue) => formatIssue(issue)))).join("; ")}`;
313
+ }
314
+ function formatIssue(issue, parentPath = []) {
315
+ const path = [...parentPath, ...issue.path.map(String)];
316
+ if (issue.code === "invalid_union") return issue.errors.flatMap((branch) => branch.flatMap((nestedIssue) => formatIssue(nestedIssue, path)));
317
+ const renderedPath = path.join(".");
318
+ return [renderedPath ? `${renderedPath}: ${issue.message}` : issue.message];
319
+ }
320
+ function hasOwn(value, key) {
321
+ return value != null && typeof value === "object" && Object.prototype.hasOwnProperty.call(value, key);
322
+ }
323
+ //#endregion
324
+ //#region src/flows/definition.ts
325
+ function defineFlow(definition) {
326
+ assertValidFlowDefinitionShape(definition);
327
+ return markDefinedFlow(definition);
328
+ }
329
+ function acp(definition) {
330
+ const node = {
331
+ nodeType: "acp",
332
+ ...definition
333
+ };
334
+ assertValidAcpNodeDefinition(node);
335
+ return node;
336
+ }
337
+ function compute(definition) {
338
+ const node = {
339
+ nodeType: "compute",
340
+ ...definition
341
+ };
342
+ assertValidComputeNodeDefinition(node);
343
+ return node;
344
+ }
345
+ function action(definition) {
346
+ const node = {
347
+ nodeType: "action",
348
+ ...definition
349
+ };
350
+ assertValidActionNodeDefinition(node);
351
+ return node;
352
+ }
353
+ function shell(definition) {
354
+ const node = {
355
+ nodeType: "action",
356
+ ...definition
357
+ };
358
+ assertValidShellActionNodeDefinition(node);
359
+ return node;
360
+ }
361
+ function checkpoint(definition = {}) {
362
+ const node = {
363
+ nodeType: "checkpoint",
364
+ ...definition
365
+ };
366
+ assertValidCheckpointNodeDefinition(node);
367
+ return node;
368
+ }
369
+ //#endregion
370
+ //#region src/flows/executors/shell-output.ts
371
+ function validateShellActionMaxBufferBytes(value) {
372
+ if (value === void 0) return;
373
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("Shell action maxBufferBytes must be a non-negative safe integer");
374
+ }
375
+ function createShellOutputCapture(maxBufferBytes, inactive, overflow) {
376
+ const output = {
377
+ stdout: "",
378
+ stderr: ""
379
+ };
380
+ const bytes = {
381
+ stdout: 0,
382
+ stderr: 0
383
+ };
384
+ return {
385
+ output,
386
+ append(stream, chunk) {
387
+ if (inactive()) return;
388
+ if (maxBufferBytes !== void 0) {
389
+ bytes[stream] += Buffer.byteLength(chunk, "utf8");
390
+ if (bytes[stream] > maxBufferBytes) {
391
+ overflow(/* @__PURE__ */ new Error(`Shell action exceeded maxBuffer (${maxBufferBytes} bytes) on ${stream}`));
392
+ return;
393
+ }
394
+ }
395
+ output[stream] += chunk;
396
+ }
397
+ };
398
+ }
399
+ //#endregion
400
+ //#region src/flows/executors/shell-process.ts
401
+ const KILL_GRACE_MS = 1e3;
402
+ async function readPosixProcesses() {
403
+ return (await runTimedExecFile("ps", ["-eo", "pid=,ppid=,pgid=,stat="])).trim().split("\n").map((line) => {
404
+ const [pid, parent, group, state = ""] = line.trim().split(/\s+/u);
405
+ return {
406
+ pid: Number(pid),
407
+ parent: Number(parent),
408
+ group: Number(group),
409
+ state
410
+ };
411
+ }).filter((entry) => Number.isInteger(entry.pid) && entry.pid > 0);
412
+ }
413
+ function isLive(entry) {
414
+ return entry.state.length > 0 && !entry.state.startsWith("Z");
415
+ }
416
+ function rememberOwnedProcesses(rows, root, owned) {
417
+ for (const entry of rows) if (entry.group === root) owned.add(entry.pid);
418
+ for (const parent of owned) for (const entry of rows) if (entry.parent === parent) owned.add(entry.pid);
419
+ }
420
+ function signalPid(pid, signal) {
421
+ try {
422
+ process.kill(pid, signal);
423
+ } catch (error) {
424
+ if (error.code !== "ESRCH") throw error;
425
+ }
426
+ }
427
+ async function signalGroup(root, signal) {
428
+ try {
429
+ process.kill(-root, signal);
430
+ } catch (error) {
431
+ const code = error.code;
432
+ if (code === "ESRCH") return;
433
+ if (code === "EPERM" && !(await readPosixProcesses()).some((entry) => entry.group === root && isLive(entry))) return;
434
+ throw error;
435
+ }
436
+ }
437
+ async function signalOwned(root, owned, signal) {
438
+ const rows = await readPosixProcesses();
439
+ rememberOwnedProcesses(rows, root, owned);
440
+ await signalGroup(root, signal);
441
+ for (const entry of rows) if (owned.has(entry.pid) && entry.group !== root && isLive(entry)) signalPid(entry.pid, signal);
442
+ }
443
+ async function waitForOwned(root, owned) {
444
+ const deadline = Date.now() + KILL_GRACE_MS;
445
+ do {
446
+ const rows = await readPosixProcesses();
447
+ rememberOwnedProcesses(rows, root, owned);
448
+ if (!rows.some((entry) => owned.has(entry.pid) && isLive(entry))) return true;
449
+ await setTimeout$1(25);
450
+ } while (Date.now() < deadline);
451
+ return false;
452
+ }
453
+ async function forceKnownProcesses(root, owned) {
454
+ const results = await Promise.allSettled([signalGroup(root, "SIGKILL"), ...[...owned].map(async (pid) => signalPid(pid, "SIGKILL"))]);
455
+ const errors = [];
456
+ for (const result of results) if (result.status === "rejected") errors.push(result.reason);
457
+ if (errors.length > 0) throw new AggregateError(errors, "Known shell processes could not be stopped", { cause: errors[0] });
458
+ }
459
+ async function stopPosixTree(pid, signal) {
460
+ const owned = /* @__PURE__ */ new Set([pid]);
461
+ try {
462
+ await signalOwned(pid, owned, signal);
463
+ if (await waitForOwned(pid, owned)) return;
464
+ await signalOwned(pid, owned, "SIGKILL");
465
+ if (!await waitForOwned(pid, owned)) throw new Error("Shell process tree did not terminate after SIGKILL");
466
+ } catch (error) {
467
+ try {
468
+ await forceKnownProcesses(pid, owned);
469
+ } catch (cleanupError) {
470
+ throw new AggregateError([error, cleanupError], "Shell process cleanup failed", { cause: cleanupError });
471
+ }
472
+ throw error;
473
+ }
474
+ }
475
+ async function stopWindowsTree(child) {
476
+ if (child.pid == null || child.exitCode != null || child.signalCode != null) return;
477
+ try {
478
+ await runTimedExecFile("taskkill", [
479
+ "/pid",
480
+ String(child.pid),
481
+ "/t",
482
+ "/f"
483
+ ], { windowsHide: true });
484
+ } catch (error) {
485
+ child.kill("SIGKILL");
486
+ throw error;
487
+ }
488
+ }
489
+ async function waitForShellClose(closed) {
490
+ try {
491
+ await withTimeout(closed, KILL_GRACE_MS);
492
+ } catch (cause) {
493
+ throw new Error("Shell process streams did not close after termination", { cause });
494
+ }
495
+ }
496
+ async function stopShellProcess(child, closed, signal) {
497
+ try {
498
+ if (child.pid != null) {
499
+ if (process.platform === "win32") await stopWindowsTree(child);
500
+ else await stopPosixTree(child.pid, signal);
501
+ }
502
+ } catch (error) {
503
+ try {
504
+ await waitForShellClose(closed);
505
+ } catch (closeError) {
506
+ throw new AggregateError([error, closeError], "Shell process cleanup failed", { cause: closeError });
507
+ }
508
+ throw error;
509
+ }
510
+ await waitForShellClose(closed);
511
+ }
512
+ function hasShellProcesses(child) {
513
+ if (child.pid == null) return false;
514
+ if (process.platform === "win32") return child.exitCode == null && child.signalCode == null;
515
+ try {
516
+ process.kill(-child.pid, 0);
517
+ return true;
518
+ } catch (error) {
519
+ return error.code !== "ESRCH";
520
+ }
521
+ }
522
+ //#endregion
523
+ //#region src/flows/executors/shell.ts
524
+ function writeShellStdin(child, stdin) {
525
+ const stream = child.stdin;
526
+ if (!stream) return;
527
+ stream.on("error", () => {});
528
+ if (stdin != null && stream.writable && !stream.writableEnded) stream.write(stdin);
529
+ if (stream.writable && !stream.writableEnded) stream.end();
530
+ }
531
+ function formatShellActionSummary(spec) {
532
+ return `shell: ${renderShellCommand(spec.command, spec.args ?? [])}`;
533
+ }
534
+ function renderShellCommand(command, args) {
535
+ const renderedArgs = args.map((arg) => JSON.stringify(arg)).join(" ");
536
+ return renderedArgs.length > 0 ? `${command} ${renderedArgs}` : command;
537
+ }
538
+ function createShellFailureError(spec, args, exitCode, signal, stderr) {
539
+ const status = signal ? `signal ${signal}` : `exit ${String(exitCode)}`;
540
+ const details = stderr.length > 0 ? `\n${stderr.trim()}` : "";
541
+ return /* @__PURE__ */ new Error(`Shell action failed (${renderShellCommand(spec.command, args)}): ${status}${details}`);
542
+ }
543
+ /**
544
+ * Resolve a shell-action timeout.
545
+ * Non-positive values match withTimeout: no deadline (undefined).
546
+ * Positive values arm SIGTERM/SIGKILL after that many ms.
547
+ */
548
+ function resolveShellActionTimeoutMs(timeoutMs) {
549
+ return resolveFlowTimeoutMs(timeoutMs);
550
+ }
551
+ function rejectIfShellFailed(spec, args, result, timedOut, timeoutMs) {
552
+ if (timedOut) return new TimeoutError(timeoutMs ?? spec.timeoutMs ?? 0);
553
+ if (((result.exitCode ?? 0) !== 0 || result.signal != null) && spec.allowNonZeroExit !== true) return createShellFailureError(spec, args, result.exitCode, result.signal, result.stderr);
554
+ }
555
+ function waitForShellResult(child, spec, args, cwd, startMs, termination, mode) {
556
+ const stdoutStream = child.stdout;
557
+ const stderrStream = child.stderr;
558
+ if (!stdoutStream || !stderrStream) throw new Error("Shell action child is missing stdio pipes");
559
+ return new Promise((resolve, reject) => {
560
+ let settled = false;
561
+ let drainDeadline;
562
+ const fail = (error) => {
563
+ clearTimeout(drainDeadline);
564
+ settled = true;
565
+ reject(error);
566
+ };
567
+ const capture = createShellOutputCapture(spec.maxBufferBytes, () => settled || mode === "node" && termination.cancelled(), (error) => {
568
+ if (termination.cancelled()) return;
569
+ fail(error);
570
+ termination.cancel("SIGTERM").catch(fail);
571
+ });
572
+ stdoutStream.setEncoding("utf8");
573
+ stderrStream.setEncoding("utf8");
574
+ stdoutStream.on("data", (chunk) => {
575
+ capture.append("stdout", chunk);
576
+ });
577
+ stderrStream.on("data", (chunk) => {
578
+ capture.append("stderr", chunk);
579
+ });
580
+ child.once("error", fail);
581
+ const finish = (exitCode, signal) => {
582
+ clearTimeout(drainDeadline);
583
+ if (settled) return;
584
+ settled = true;
585
+ if (mode === "node" && !termination.cancelled()) {
586
+ stdoutStream.unref();
587
+ stderrStream.unref();
588
+ }
589
+ const { stdout, stderr } = capture.output;
590
+ resolve({
591
+ command: spec.command,
592
+ args,
593
+ cwd,
594
+ stdout,
595
+ stderr,
596
+ combinedOutput: `${stdout}${stderr}`,
597
+ exitCode,
598
+ signal,
599
+ durationMs: Date.now() - startMs,
600
+ timedOut: mode === "node" ? termination.cancelled() : termination.timedOut()
601
+ });
602
+ };
603
+ child.once("close", finish);
604
+ if (mode === "node") child.once("exit", (exitCode, signal) => {
605
+ if (settled) return;
606
+ drainDeadline = setTimeout(() => finish(exitCode, signal), 100);
607
+ });
608
+ });
609
+ }
610
+ function createShellTermination(child, timeoutMs, options) {
611
+ const closed = new Promise((resolve) => child.once("close", () => resolve()));
612
+ let rejectCleanup = () => {};
613
+ const cleanupFailure = new Promise((_resolve, reject) => {
614
+ rejectCleanup = reject;
615
+ });
616
+ let termination;
617
+ let timedOut = false;
618
+ let cancelled = false;
619
+ let released = false;
620
+ let deadline;
621
+ let monitor;
622
+ let unregister;
623
+ const clearDeadline = () => {
624
+ if (deadline) clearTimeout(deadline);
625
+ };
626
+ const release = () => {
627
+ if (released) return;
628
+ released = true;
629
+ clearDeadline();
630
+ if (monitor) clearInterval(monitor);
631
+ options.signal?.removeEventListener("abort", onAbort);
632
+ unregister?.();
633
+ };
634
+ const cancel = (signal) => {
635
+ if (termination) return termination;
636
+ if (released) return Promise.resolve();
637
+ clearDeadline();
638
+ cancelled = true;
639
+ termination = stopShellProcess(child, closed, signal).finally(release);
640
+ termination.catch(rejectCleanup);
641
+ return termination;
642
+ };
643
+ const onAbort = () => {
644
+ cancel(options.terminationSignal ?? "SIGTERM");
645
+ };
646
+ options.signal?.addEventListener("abort", onAbort, { once: true });
647
+ if (timeoutMs != null) deadline = setTimeout(() => {
648
+ timedOut = true;
649
+ cancel("SIGTERM");
650
+ }, timeoutMs);
651
+ unregister = options.registerOwner?.({
652
+ cancel,
653
+ release
654
+ });
655
+ if (unregister) child.once("close", () => {
656
+ if (released || termination) return;
657
+ const prune = () => {
658
+ if (!termination && !hasShellProcesses(child)) release();
659
+ };
660
+ monitor = setInterval(prune, 100);
661
+ monitor.unref();
662
+ prune();
663
+ });
664
+ return {
665
+ cancel,
666
+ timedOut: () => timedOut,
667
+ cancelled: () => cancelled,
668
+ cleanupFailure,
669
+ async dispose() {
670
+ clearDeadline();
671
+ try {
672
+ await termination;
673
+ } finally {
674
+ if (!unregister) release();
675
+ }
676
+ }
677
+ };
678
+ }
679
+ async function runShellAction(spec, options = {}) {
680
+ const { timedOut, ...result } = await runShellProcess(spec, options, "node");
681
+ const failure = rejectIfShellFailed(spec, result.args, result, timedOut, resolveShellActionTimeoutMs(spec.timeoutMs));
682
+ if (failure) throw failure;
683
+ return result;
684
+ }
685
+ async function runShellCommand(spec, options) {
686
+ return await runShellProcess(spec, options, "command");
687
+ }
688
+ async function runShellProcess(spec, options, mode) {
689
+ options.signal?.throwIfAborted();
690
+ const cwd = spec.cwd ?? process.cwd();
691
+ const args = spec.args ?? [];
692
+ const startMs = Date.now();
693
+ const timeoutMs = resolveShellActionTimeoutMs(spec.timeoutMs);
694
+ validateShellActionMaxBufferBytes(spec.maxBufferBytes);
695
+ if (spec.stdin !== void 0 && typeof spec.stdin !== "string") throw new TypeError("stdin must be a string");
696
+ const child = spawn(spec.command, args, {
697
+ cwd,
698
+ env: {
699
+ ...process.env,
700
+ ...spec.env
701
+ },
702
+ shell: spec.shell,
703
+ stdio: [
704
+ "pipe",
705
+ "pipe",
706
+ "pipe"
707
+ ],
708
+ windowsHide: true,
709
+ detached: process.platform !== "win32"
710
+ });
711
+ const termination = createShellTermination(child, timeoutMs, options);
712
+ const finish = waitForShellResult(child, spec, args, cwd, startMs, termination, mode);
713
+ try {
714
+ writeShellStdin(child, spec.stdin);
715
+ const result = await Promise.race([finish, termination.cleanupFailure]);
716
+ throwIfShellCancelled(options.signal, mode);
717
+ return result;
718
+ } catch (error) {
719
+ await termination.cancel("SIGTERM");
720
+ throw error;
721
+ } finally {
722
+ await termination.dispose();
723
+ }
724
+ }
725
+ function throwIfShellCancelled(signal, mode) {
726
+ if (!signal?.aborted) return;
727
+ const reason = signal.reason;
728
+ if (mode === "command" || reason instanceof TimeoutError || reason instanceof InterruptedError) throw reason;
729
+ }
730
+ //#endregion
731
+ //#region src/flows/graph.ts
732
+ function validateFlowDefinition(flow) {
733
+ assertValidFlowDefinitionShape(flow);
734
+ assertKnownFlowNode(flow, flow.startAt, "Flow start node is missing");
735
+ const outgoingEdges = /* @__PURE__ */ new Set();
736
+ for (const edge of flow.edges) validateFlowEdge(flow, edge, outgoingEdges);
737
+ }
738
+ function assertKnownFlowNode(flow, nodeId, description) {
739
+ if (!Object.hasOwn(flow.nodes, nodeId)) throw new Error(`${description}: ${nodeId}`);
740
+ }
741
+ function isDirectEdge(edge) {
742
+ return Object.hasOwn(edge, "to");
743
+ }
744
+ function validateFlowEdge(flow, edge, outgoingEdges) {
745
+ assertKnownFlowNode(flow, edge.from, "Flow edge references unknown from-node");
746
+ if (outgoingEdges.has(edge.from)) throw new Error(`Flow node must not declare multiple outgoing edges: ${edge.from}`);
747
+ outgoingEdges.add(edge.from);
748
+ if (isDirectEdge(edge)) {
749
+ assertKnownFlowNode(flow, edge.to, "Flow edge references unknown to-node");
750
+ return;
751
+ }
752
+ for (const target of Object.values(edge.switch.cases)) assertKnownFlowNode(flow, target, "Flow switch references unknown to-node");
753
+ }
754
+ function canFollowEdge(edge, result) {
755
+ return !result || result.outcome === "ok" || !isDirectEdge(edge) && edge.switch.on.startsWith("$result.");
756
+ }
757
+ function resolveNext(edges, from, output, result) {
758
+ const edge = edges.find((candidate) => candidate.from === from);
759
+ if (!edge || !canFollowEdge(edge, result)) return null;
760
+ if (isDirectEdge(edge)) return edge.to;
761
+ const value = getBySwitchPath(output, result, edge.switch.on);
762
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new Error(`Flow switch value must be scalar for ${edge.switch.on}`);
763
+ const key = String(value);
764
+ if (!Object.hasOwn(edge.switch.cases, key)) throw new Error(`No flow switch case for ${edge.switch.on}=${JSON.stringify(value)}`);
765
+ return edge.switch.cases[key];
766
+ }
767
+ function getBySwitchPath(output, result, jsonPath) {
768
+ if (jsonPath.startsWith("$result.")) return getByPath(result, `$.${jsonPath.slice(8)}`);
769
+ if (jsonPath.startsWith("$output.")) return getByPath(output, `$.${jsonPath.slice(8)}`);
770
+ return getByPath(output, jsonPath);
771
+ }
772
+ function getByPath(value, jsonPath) {
773
+ if (!jsonPath.startsWith("$.")) throw new Error(`Unsupported JSON path: ${jsonPath}`);
774
+ return jsonPath.slice(2).split(".").reduce((current, key) => {
775
+ if (current == null || typeof current !== "object") return;
776
+ return current[key];
777
+ }, value);
778
+ }
779
+ //#endregion
780
+ //#region src/flows/runtime-support.ts
781
+ function isoNow$1() {
782
+ return (/* @__PURE__ */ new Date()).toISOString();
783
+ }
784
+ function persistRunFailure(store, runDir, state, error) {
785
+ if (state.finishedAt !== void 0 && (state.status === "failed" || state.status === "timed_out")) return Promise.resolve();
786
+ state.status = error instanceof TimeoutError ? "timed_out" : "failed";
787
+ state.updatedAt = isoNow$1();
788
+ state.finishedAt = state.updatedAt;
789
+ state.error = error instanceof Error ? error.message : String(error);
790
+ state.statusDetail = state.currentNode ? `Failed in ${state.currentNode}: ${state.error}` : state.error;
791
+ return store.writeSnapshot(runDir, state, {
792
+ scope: "run",
793
+ type: "run_failed",
794
+ payload: {
795
+ status: state.status,
796
+ error: state.error
797
+ }
798
+ });
799
+ }
800
+ function makeFlowNodeContext(state, input, services) {
801
+ return {
802
+ input,
803
+ outputs: state.outputs,
804
+ results: state.results,
805
+ state,
806
+ services
807
+ };
808
+ }
809
+ function markNodeStarted(state, nodeId, attemptId, nodeType, startedAt, detail) {
810
+ state.status = "running";
811
+ state.waitingOn = void 0;
812
+ state.currentNode = nodeId;
813
+ state.currentAttemptId = attemptId;
814
+ state.currentNodeType = nodeType;
815
+ state.currentNodeStartedAt = startedAt;
816
+ state.lastHeartbeatAt = startedAt;
817
+ state.statusDetail = detail ?? `Running ${nodeType} node ${nodeId}`;
818
+ }
819
+ function clearActiveNode(state, detail) {
820
+ state.currentNode = void 0;
821
+ state.currentAttemptId = void 0;
822
+ state.currentNodeType = void 0;
823
+ state.currentNodeStartedAt = void 0;
824
+ state.lastHeartbeatAt = void 0;
825
+ state.statusDetail = detail;
826
+ }
827
+ function updateStatusDetail(state, detail) {
828
+ if (!detail) return;
829
+ state.statusDetail = detail;
830
+ }
831
+ async function finalizeStepTrace(store, runDir, state, nodeId, attemptId, output, baseTrace) {
832
+ const trace = baseTrace ? structuredClone(baseTrace) : {};
833
+ if (output !== void 0) {
834
+ const inlineOutput = toInlineOutput(output);
835
+ if (inlineOutput !== void 0) trace.outputInline = inlineOutput;
836
+ else trace.outputArtifact = await store.writeArtifact(runDir, state, output, {
837
+ mediaType: outputArtifactMediaType(output),
838
+ extension: outputArtifactExtension(output),
839
+ nodeId,
840
+ attemptId
841
+ });
842
+ }
843
+ return Object.keys(trace).length > 0 ? trace : null;
844
+ }
845
+ function normalizePromptInput(prompt) {
846
+ return typeof prompt === "string" ? textPrompt(prompt) : prompt;
847
+ }
848
+ async function resolveNodeCwd(defaultCwd, cwd, context) {
849
+ if (typeof cwd === "function") {
850
+ const resolved = await cwd(context) ?? defaultCwd;
851
+ return path.resolve(defaultCwd, resolved);
852
+ }
853
+ return path.resolve(defaultCwd, cwd ?? defaultCwd);
854
+ }
855
+ function resolveShellActionCwd(defaultCwd, cwd) {
856
+ return path.resolve(defaultCwd, cwd ?? defaultCwd);
857
+ }
858
+ function summarizePrompt(promptText, explicitDetail) {
859
+ if (explicitDetail) return explicitDetail;
860
+ const line = promptText.split("\n").map((candidate) => candidate.trim()).find((candidate) => candidate.length > 0);
861
+ if (!line) return "Running ACP prompt";
862
+ return `ACP: ${line.length > 120 ? `${line.slice(0, 117)}...` : line}`;
863
+ }
864
+ function createQuietCaptureOutput() {
865
+ const chunks = [];
866
+ let sessionId;
867
+ const formatter = createOutputFormatter("quiet", { stdout: { write(chunk) {
868
+ chunks.push(chunk);
869
+ } } });
870
+ const setContext = formatter.setContext.bind(formatter);
871
+ formatter.setContext = (context) => {
872
+ sessionId = context.sessionId ?? sessionId;
873
+ setContext(context);
874
+ };
875
+ return {
876
+ formatter,
877
+ read: () => chunks.join("").trim(),
878
+ sessionId: () => sessionId
879
+ };
880
+ }
881
+ async function resolveFlowRunTitle(flow, input, flowPath) {
882
+ const titleDefinition = flow.run?.title;
883
+ if (titleDefinition === void 0) return;
884
+ return normalizeFlowRunTitle(typeof titleDefinition === "function" ? await Promise.resolve(titleDefinition({
885
+ input,
886
+ flowName: flow.name,
887
+ flowPath
888
+ })) : titleDefinition);
889
+ }
890
+ function normalizeFlowRunTitle(value) {
891
+ const trimmed = value?.trim();
892
+ return trimmed ? trimmed : void 0;
893
+ }
894
+ function createRunId(flowName) {
895
+ return `${isoNow$1().replaceAll(":", "").replaceAll(".", "")}-${slugifyAsciiIdPart(flowName)}-${randomUUID().slice(0, 8)}`;
896
+ }
897
+ function createSessionBindingKey(agentCommand, cwd, handle, agentArgv) {
898
+ return JSON.stringify([
899
+ agentCommand,
900
+ agentArgv ?? null,
901
+ cwd,
902
+ handle
903
+ ]);
904
+ }
905
+ function createSessionName(flowName, handle, cwd, runId) {
906
+ return `${flowName}-${handle}-${stableShortHash(cwd)}-${runId.slice(-8)}`;
907
+ }
908
+ function createSessionBundleId(handle, key) {
909
+ return `${slugifyAsciiIdPart(handle) || "session"}-${stableShortHash(key)}`;
910
+ }
911
+ function slugifyAsciiIdPart(value) {
912
+ let slug = "";
913
+ let lastWasSeparator = false;
914
+ for (const char of value) {
915
+ const safeChar = toLowerAsciiAlphaNumeric(char);
916
+ if (safeChar) {
917
+ slug += safeChar;
918
+ lastWasSeparator = false;
919
+ continue;
920
+ }
921
+ if (slug.length > 0 && !lastWasSeparator) {
922
+ slug += "-";
923
+ lastWasSeparator = true;
924
+ }
925
+ }
926
+ return lastWasSeparator ? slug.slice(0, -1) : slug;
927
+ }
928
+ function toLowerAsciiAlphaNumeric(char) {
929
+ const code = char.charCodeAt(0);
930
+ if (code >= 48 && code <= 57) return char;
931
+ if (code >= 65 && code <= 90) return String.fromCharCode(code + 32);
932
+ if (code >= 97 && code <= 122) return char;
933
+ return null;
934
+ }
935
+ function createIsolatedSessionBinding(flowName, runId, attemptId, profile, agent) {
936
+ const key = `isolated::${attemptId}`;
937
+ const handle = "isolated";
938
+ return {
939
+ key,
940
+ handle,
941
+ bundleId: createSessionBundleId(`${handle}-${attemptId}`, `${key}::${agent.cwd}`),
942
+ name: `${flowName}-${attemptId}-${runId.slice(-8)}`,
943
+ profile,
944
+ agentName: agent.agentName,
945
+ agentCommand: agent.agentCommand,
946
+ agentArgv: agent.agentArgv,
947
+ cwd: agent.cwd,
948
+ acpxRecordId: key,
949
+ acpSessionId: key
950
+ };
951
+ }
952
+ function createSyntheticSessionRecord(options) {
953
+ return {
954
+ schema: SESSION_RECORD_SCHEMA,
955
+ acpxRecordId: options.binding.acpxRecordId,
956
+ acpSessionId: options.binding.acpSessionId,
957
+ agentSessionId: options.binding.agentSessionId,
958
+ agentCommand: options.binding.agentCommand,
959
+ agentArgv: options.binding.agentArgv,
960
+ cwd: options.binding.cwd,
961
+ name: options.binding.name,
962
+ createdAt: options.createdAt,
963
+ lastUsedAt: options.updatedAt,
964
+ lastSeq: options.lastSeq,
965
+ lastRequestId: void 0,
966
+ eventLog: defaultSessionEventLog(options.binding.acpxRecordId),
967
+ closed: true,
968
+ closedAt: options.updatedAt,
969
+ title: options.conversation.title,
970
+ messages: options.conversation.messages,
971
+ updated_at: options.conversation.updated_at,
972
+ cumulative_token_usage: options.conversation.cumulative_token_usage,
973
+ cumulative_cost: options.conversation.cumulative_cost,
974
+ request_token_usage: options.conversation.request_token_usage,
975
+ acpx: options.acpxState
976
+ };
977
+ }
978
+ function createNodeResult(options) {
979
+ return {
980
+ attemptId: options.attemptId,
981
+ nodeId: options.nodeId,
982
+ nodeType: options.nodeType,
983
+ outcome: options.outcome,
984
+ startedAt: options.startedAt,
985
+ finishedAt: options.finishedAt,
986
+ durationMs: new Date(options.finishedAt).getTime() - new Date(options.startedAt).getTime(),
987
+ output: options.output,
988
+ error: options.error
989
+ };
990
+ }
991
+ function outcomeForError(error) {
992
+ if (error instanceof TimeoutError) return "timed_out";
993
+ if (error instanceof InterruptedError) return "cancelled";
994
+ return "failed";
995
+ }
996
+ function stableShortHash(value) {
997
+ return createHash("sha1").update(value).digest("hex").slice(0, 8);
998
+ }
999
+ function nextAttemptId(attemptCounts, nodeId) {
1000
+ const next = (attemptCounts.get(nodeId) ?? 0) + 1;
1001
+ attemptCounts.set(nodeId, next);
1002
+ return `${nodeId}#${next}`;
1003
+ }
1004
+ function createNodeOutcomePayload(result, trace) {
1005
+ return {
1006
+ nodeType: result.nodeType,
1007
+ outcome: result.outcome,
1008
+ durationMs: result.durationMs,
1009
+ error: result.error ?? null,
1010
+ ...trace
1011
+ };
1012
+ }
1013
+ function attachStepTrace(error, trace) {
1014
+ const attached = error instanceof Error ? error : new Error(typeof error === "string" ? error : String(error));
1015
+ attached.flowStepTrace = trace;
1016
+ return attached;
1017
+ }
1018
+ function extractAttachedStepTrace(error) {
1019
+ if (!(error instanceof Error)) return;
1020
+ return error.flowStepTrace;
1021
+ }
1022
+ function toInlineOutput(value) {
1023
+ if (value == null || typeof value === "number" || typeof value === "boolean") return value;
1024
+ if (typeof value === "string") return isInlineSerializableText(value) ? value : void 0;
1025
+ try {
1026
+ if (isInlineSerializableText(JSON.stringify(value))) return value;
1027
+ } catch {
1028
+ return;
1029
+ }
1030
+ }
1031
+ function isInlineSerializableText(value) {
1032
+ return value.length <= 200 && !value.includes("\n");
1033
+ }
1034
+ function outputArtifactMediaType(value) {
1035
+ return typeof value === "string" ? "text/plain" : "application/json";
1036
+ }
1037
+ function outputArtifactExtension(value) {
1038
+ return typeof value === "string" ? "txt" : "json";
1039
+ }
1040
+ function findConversationDeltaStart(before, after) {
1041
+ const maxOverlap = Math.min(before.length, after.length);
1042
+ for (let overlap = maxOverlap; overlap >= 0; overlap -= 1) {
1043
+ let matches = true;
1044
+ for (let index = 0; index < overlap; index += 1) {
1045
+ const beforeMessage = before[before.length - overlap + index];
1046
+ const afterMessage = after[index];
1047
+ if (!deepEqualJson(beforeMessage, afterMessage)) {
1048
+ matches = false;
1049
+ break;
1050
+ }
1051
+ }
1052
+ if (matches) return overlap;
1053
+ }
1054
+ return 0;
1055
+ }
1056
+ function deepEqualJson(left, right) {
1057
+ return JSON.stringify(left) === JSON.stringify(right);
1058
+ }
1059
+ //#endregion
1060
+ //#region src/flows/store.ts
1061
+ const FLOW_BUNDLE_SCHEMA = "acpx.flow-run-bundle.v1";
1062
+ const FLOW_TRACE_SCHEMA = "acpx.flow-trace-event.v1";
1063
+ const FLOW_SNAPSHOT_SCHEMA = "acpx.flow-definition-snapshot.v1";
1064
+ const MANIFEST_PATH = "manifest.json";
1065
+ const FLOW_SNAPSHOT_PATH = "flow.json";
1066
+ const TRACE_PATH = "trace.ndjson";
1067
+ const PROJECTIONS_DIR = "projections";
1068
+ const RUN_PROJECTION_PATH = "projections/run.json";
1069
+ const LIVE_PROJECTION_PATH = "projections/live.json";
1070
+ const STEPS_PROJECTION_PATH = "projections/steps.json";
1071
+ const SESSIONS_DIR = "sessions";
1072
+ const ARTIFACTS_DIR = "artifacts";
1073
+ function flowRunsBaseDir(homeDir = os.homedir()) {
1074
+ return path.join(homeDir, ".acpx", "flows", "runs");
1075
+ }
1076
+ var FlowRunStore = class {
1077
+ outputRoot;
1078
+ traceSeqByRun = /* @__PURE__ */ new Map();
1079
+ sessionSeqByBundle = /* @__PURE__ */ new Map();
1080
+ manifestByRun = /* @__PURE__ */ new Map();
1081
+ writeChainByPath = /* @__PURE__ */ new Map();
1082
+ constructor(outputRoot = flowRunsBaseDir()) {
1083
+ this.outputRoot = outputRoot;
1084
+ }
1085
+ releaseRun(runDir) {
1086
+ this.traceSeqByRun.delete(runDir);
1087
+ this.manifestByRun.delete(runDir);
1088
+ for (const key of this.sessionSeqByBundle.keys()) if (key.startsWith(`${runDir}::`)) this.sessionSeqByBundle.delete(key);
1089
+ }
1090
+ async createRunDir(runId) {
1091
+ const runDir = path.join(this.outputRoot, runId);
1092
+ await fs.mkdir(path.join(runDir, PROJECTIONS_DIR), {
1093
+ recursive: true,
1094
+ mode: 448
1095
+ });
1096
+ await fs.mkdir(path.join(runDir, SESSIONS_DIR), {
1097
+ recursive: true,
1098
+ mode: 448
1099
+ });
1100
+ await fs.mkdir(path.join(runDir, ARTIFACTS_DIR), {
1101
+ recursive: true,
1102
+ mode: 448
1103
+ });
1104
+ this.traceSeqByRun.set(runDir, 0);
1105
+ return runDir;
1106
+ }
1107
+ async initializeRunBundle(runDir, options) {
1108
+ const snapshot = createFlowDefinitionSnapshot(options.flow);
1109
+ const manifest = createRunManifest(options.state);
1110
+ this.manifestByRun.set(runDir, manifest);
1111
+ await writePrivateJsonFile(this.resolveRunPath(runDir, FLOW_SNAPSHOT_PATH), snapshot);
1112
+ await writePrivateJsonFile(this.resolveRunPath(runDir, MANIFEST_PATH), manifest);
1113
+ await writePrivateJsonFile(this.resolveRunPath(runDir, RUN_PROJECTION_PATH), options.state);
1114
+ await writePrivateJsonFile(this.resolveRunPath(runDir, LIVE_PROJECTION_PATH), createLiveState(options.state));
1115
+ await writePrivateJsonFile(this.resolveRunPath(runDir, STEPS_PROJECTION_PATH), options.state.steps);
1116
+ await ensureFile(this.resolveRunPath(runDir, TRACE_PATH));
1117
+ await this.appendTrace(runDir, options.state, {
1118
+ scope: "run",
1119
+ type: "run_started",
1120
+ payload: {
1121
+ flowName: options.state.flowName,
1122
+ ...options.state.runTitle ? { runTitle: options.state.runTitle } : {},
1123
+ ...options.state.flowPath ? { flowPath: options.state.flowPath } : {},
1124
+ ...options.inputArtifact ? { inputArtifact: options.inputArtifact } : {}
1125
+ }
1126
+ });
1127
+ }
1128
+ async writeSnapshot(runDir, state, event) {
1129
+ state.updatedAt = isoNow();
1130
+ await writePrivateJsonFile(this.resolveRunPath(runDir, RUN_PROJECTION_PATH), state);
1131
+ await writePrivateJsonFile(this.resolveRunPath(runDir, LIVE_PROJECTION_PATH), createLiveState(state));
1132
+ await writePrivateJsonFile(this.resolveRunPath(runDir, STEPS_PROJECTION_PATH), state.steps);
1133
+ await this.writeManifest(runDir, state);
1134
+ await this.appendTrace(runDir, state, event);
1135
+ }
1136
+ async writeLive(runDir, state, event) {
1137
+ state.updatedAt = isoNow();
1138
+ await writePrivateJsonFile(this.resolveRunPath(runDir, LIVE_PROJECTION_PATH), createLiveState(state));
1139
+ await this.writeManifest(runDir, state);
1140
+ await this.appendTrace(runDir, state, event);
1141
+ }
1142
+ async appendTrace(runDir, state, event) {
1143
+ const traceEvent = {
1144
+ seq: this.nextTraceSeq(runDir),
1145
+ at: isoNow(),
1146
+ runId: state.runId,
1147
+ ...event
1148
+ };
1149
+ await this.appendJsonLine(this.resolveRunPath(runDir, TRACE_PATH), traceEvent);
1150
+ return traceEvent;
1151
+ }
1152
+ async writeArtifact(runDir, state, content, options) {
1153
+ const buffer = toArtifactBuffer(content, options.mediaType);
1154
+ const sha256 = createHash("sha256").update(buffer).digest("hex");
1155
+ const relativePath = path.posix.join(ARTIFACTS_DIR, `sha256-${sha256}${normalizeArtifactExtension(options.extension)}`);
1156
+ const filePath = this.resolveRunPath(runDir, relativePath);
1157
+ try {
1158
+ await fs.access(filePath);
1159
+ } catch {
1160
+ await writePrivateFile(filePath, buffer);
1161
+ }
1162
+ const artifact = {
1163
+ path: relativePath,
1164
+ mediaType: options.mediaType,
1165
+ bytes: buffer.byteLength,
1166
+ sha256
1167
+ };
1168
+ if (options.emitTrace !== false) await this.appendTrace(runDir, state, {
1169
+ scope: "artifact",
1170
+ type: "artifact_written",
1171
+ nodeId: options.nodeId,
1172
+ attemptId: options.attemptId,
1173
+ sessionId: options.sessionId,
1174
+ artifact,
1175
+ payload: { artifact }
1176
+ });
1177
+ return artifact;
1178
+ }
1179
+ async ensureSessionBundle(runDir, state, inputBinding, record) {
1180
+ const binding = structuredClone(inputBinding);
1181
+ const sessionDir = this.resolveRunPath(runDir, sessionDirPath(binding.bundleId));
1182
+ await this.serializeWrite(path.join(sessionDir, "binding.json"), async () => {
1183
+ await fs.mkdir(sessionDir, {
1184
+ recursive: true,
1185
+ mode: 448
1186
+ });
1187
+ await writePrivateJsonFile(path.join(sessionDir, "binding.json"), binding);
1188
+ await ensureFile(path.join(sessionDir, "events.ndjson"));
1189
+ if (record) await this.writeSessionRecord(runDir, state, binding, record);
1190
+ const manifest = this.getManifest(runDir, state);
1191
+ if (!manifest.sessions.find((entry) => entry.id === binding.bundleId)) {
1192
+ const bindingArtifact = await this.writeArtifact(runDir, state, binding, {
1193
+ mediaType: "application/json",
1194
+ extension: "json",
1195
+ emitTrace: false
1196
+ });
1197
+ const entry = {
1198
+ id: binding.bundleId,
1199
+ handle: binding.handle,
1200
+ bindingPath: path.posix.join(sessionDirPath(binding.bundleId), "binding.json"),
1201
+ recordPath: path.posix.join(sessionDirPath(binding.bundleId), "record.json"),
1202
+ eventsPath: path.posix.join(sessionDirPath(binding.bundleId), "events.ndjson")
1203
+ };
1204
+ manifest.sessions.push(entry);
1205
+ await writePrivateJsonFile(this.resolveRunPath(runDir, MANIFEST_PATH), manifest);
1206
+ await this.appendTrace(runDir, state, {
1207
+ scope: "session",
1208
+ type: "session_bound",
1209
+ sessionId: binding.bundleId,
1210
+ payload: {
1211
+ sessionId: binding.bundleId,
1212
+ handle: binding.handle,
1213
+ bindingArtifact
1214
+ }
1215
+ });
1216
+ }
1217
+ });
1218
+ }
1219
+ async writeSessionRecord(runDir, _state, binding, record) {
1220
+ const bundledRecord = createBundledSessionRecord(binding, record, this.sessionSeqByBundle.get(`${runDir}::${binding.bundleId}`)?.persisted ?? 0);
1221
+ await writePrivateJsonFile(this.resolveRunPath(runDir, path.posix.join(sessionDirPath(binding.bundleId), "record.json")), bundledRecord);
1222
+ }
1223
+ async appendSessionEvent(runDir, binding, direction, message) {
1224
+ const sessionKey = `${runDir}::${binding.bundleId}`;
1225
+ const sequence = this.sessionSeqByBundle.get(sessionKey) ?? {
1226
+ allocated: 0,
1227
+ persisted: 0
1228
+ };
1229
+ this.sessionSeqByBundle.set(sessionKey, sequence);
1230
+ const seq = ++sequence.allocated;
1231
+ await this.appendJsonLine(this.resolveRunPath(runDir, path.posix.join(sessionDirPath(binding.bundleId), "events.ndjson")), {
1232
+ seq,
1233
+ at: isoNow(),
1234
+ direction,
1235
+ message
1236
+ });
1237
+ sequence.persisted = Math.max(sequence.persisted, seq);
1238
+ return seq;
1239
+ }
1240
+ getManifest(runDir, state) {
1241
+ const existing = this.manifestByRun.get(runDir);
1242
+ if (existing) {
1243
+ existing.startedAt = state.startedAt;
1244
+ existing.finishedAt = state.finishedAt;
1245
+ existing.status = state.status;
1246
+ existing.flowPath = state.flowPath;
1247
+ existing.flowName = state.flowName;
1248
+ existing.runTitle = state.runTitle;
1249
+ return existing;
1250
+ }
1251
+ const created = createRunManifest(state);
1252
+ this.manifestByRun.set(runDir, created);
1253
+ return created;
1254
+ }
1255
+ async writeManifest(runDir, state) {
1256
+ const manifest = this.getManifest(runDir, state);
1257
+ await writePrivateJsonFile(this.resolveRunPath(runDir, MANIFEST_PATH), manifest);
1258
+ }
1259
+ nextTraceSeq(runDir) {
1260
+ const next = (this.traceSeqByRun.get(runDir) ?? 0) + 1;
1261
+ this.traceSeqByRun.set(runDir, next);
1262
+ return next;
1263
+ }
1264
+ resolveRunPath(runDir, relativePath) {
1265
+ return path.join(runDir, ...relativePath.split("/"));
1266
+ }
1267
+ async appendJsonLine(filePath, value) {
1268
+ await this.serializeWrite(filePath, async () => {
1269
+ await fs.mkdir(path.dirname(filePath), {
1270
+ recursive: true,
1271
+ mode: 448
1272
+ });
1273
+ await appendRegularFile({
1274
+ filePath,
1275
+ content: `${JSON.stringify(value)}\n`,
1276
+ mode: 384
1277
+ });
1278
+ });
1279
+ }
1280
+ async serializeWrite(filePath, write) {
1281
+ const tracked = (this.writeChainByPath.get(filePath) ?? Promise.resolve()).then(write).finally(() => {
1282
+ if (this.writeChainByPath.get(filePath) === tracked) this.writeChainByPath.delete(filePath);
1283
+ });
1284
+ this.writeChainByPath.set(filePath, tracked);
1285
+ await tracked;
1286
+ }
1287
+ };
1288
+ function createRunManifest(state) {
1289
+ return {
1290
+ schema: FLOW_BUNDLE_SCHEMA,
1291
+ runId: state.runId,
1292
+ flowName: state.flowName,
1293
+ runTitle: state.runTitle,
1294
+ flowPath: state.flowPath,
1295
+ startedAt: state.startedAt,
1296
+ finishedAt: state.finishedAt,
1297
+ status: state.status,
1298
+ traceSchema: FLOW_TRACE_SCHEMA,
1299
+ paths: {
1300
+ flow: FLOW_SNAPSHOT_PATH,
1301
+ trace: TRACE_PATH,
1302
+ runProjection: RUN_PROJECTION_PATH,
1303
+ liveProjection: LIVE_PROJECTION_PATH,
1304
+ stepsProjection: STEPS_PROJECTION_PATH,
1305
+ sessionsDir: SESSIONS_DIR,
1306
+ artifactsDir: ARTIFACTS_DIR
1307
+ },
1308
+ sessions: []
1309
+ };
1310
+ }
1311
+ function createLiveState(state) {
1312
+ return {
1313
+ runId: state.runId,
1314
+ flowName: state.flowName,
1315
+ runTitle: state.runTitle,
1316
+ flowPath: state.flowPath,
1317
+ startedAt: state.startedAt,
1318
+ finishedAt: state.finishedAt,
1319
+ updatedAt: state.updatedAt,
1320
+ status: state.status,
1321
+ currentNode: state.currentNode,
1322
+ currentAttemptId: state.currentAttemptId,
1323
+ currentNodeType: state.currentNodeType,
1324
+ currentNodeStartedAt: state.currentNodeStartedAt,
1325
+ lastHeartbeatAt: state.lastHeartbeatAt,
1326
+ statusDetail: state.statusDetail,
1327
+ waitingOn: state.waitingOn,
1328
+ error: state.error,
1329
+ sessionBindings: state.sessionBindings
1330
+ };
1331
+ }
1332
+ function createFlowDefinitionSnapshot(flow) {
1333
+ return {
1334
+ schema: FLOW_SNAPSHOT_SCHEMA,
1335
+ name: flow.name,
1336
+ ...flow.run?.title !== void 0 ? { run: { hasTitle: true } } : {},
1337
+ ...flow.permissions ? { permissions: structuredClone(flow.permissions) } : {},
1338
+ startAt: flow.startAt,
1339
+ nodes: Object.fromEntries(Object.entries(flow.nodes).map(([nodeId, node]) => [nodeId, snapshotNode(node)])),
1340
+ edges: structuredClone(flow.edges)
1341
+ };
1342
+ }
1343
+ function snapshotNode(node) {
1344
+ const common = snapshotCommonNodeFields(node);
1345
+ switch (node.nodeType) {
1346
+ case "acp": return snapshotAcpNode(node, common);
1347
+ case "compute": return {
1348
+ ...common,
1349
+ hasRun: true
1350
+ };
1351
+ case "action": {
1352
+ const actionExecution = "exec" in node ? "shell" : "function";
1353
+ return {
1354
+ ...common,
1355
+ actionExecution,
1356
+ hasRun: "run" in node,
1357
+ hasExec: "exec" in node,
1358
+ hasParse: "parse" in node && typeof node.parse === "function"
1359
+ };
1360
+ }
1361
+ case "checkpoint": return {
1362
+ ...common,
1363
+ ...node.summary ? { summary: node.summary } : {},
1364
+ hasRun: typeof node.run === "function"
1365
+ };
1366
+ }
1367
+ throw new Error(`Unsupported flow node type: ${String(node)}`);
1368
+ }
1369
+ function snapshotCommonNodeFields(node) {
1370
+ return {
1371
+ nodeType: node.nodeType,
1372
+ ...node.timeoutMs !== void 0 ? { timeoutMs: node.timeoutMs } : {},
1373
+ ...node.heartbeatMs !== void 0 ? { heartbeatMs: node.heartbeatMs } : {},
1374
+ ...node.statusDetail ? { statusDetail: node.statusDetail } : {}
1375
+ };
1376
+ }
1377
+ function snapshotAcpNode(node, common) {
1378
+ return {
1379
+ ...common,
1380
+ ...node.profile ? { profile: node.profile } : {},
1381
+ session: {
1382
+ ...node.session?.handle ? { handle: node.session.handle } : {},
1383
+ ...node.session?.isolated ? { isolated: true } : {}
1384
+ },
1385
+ cwd: snapshotCwd(node.cwd),
1386
+ hasPrompt: true,
1387
+ hasParse: typeof node.parse === "function"
1388
+ };
1389
+ }
1390
+ function snapshotCwd(cwd) {
1391
+ if (typeof cwd === "function") return { mode: "dynamic" };
1392
+ if (typeof cwd === "string") return {
1393
+ mode: "static",
1394
+ value: cwd
1395
+ };
1396
+ return { mode: "default" };
1397
+ }
1398
+ function createBundledSessionRecord(binding, record, bundleLastSeq) {
1399
+ return {
1400
+ ...structuredClone(record),
1401
+ lastSeq: bundleLastSeq,
1402
+ eventLog: {
1403
+ ...structuredClone(record.eventLog),
1404
+ active_path: path.posix.join(sessionDirPath(binding.bundleId), "events.ndjson"),
1405
+ segment_count: 1,
1406
+ max_segments: 1
1407
+ }
1408
+ };
1409
+ }
1410
+ async function ensureFile(filePath) {
1411
+ await appendRegularFile({
1412
+ filePath,
1413
+ content: "",
1414
+ mode: 384
1415
+ });
1416
+ }
1417
+ function toArtifactBuffer(content, mediaType) {
1418
+ if (typeof content === "string") return Buffer.from(content, "utf8");
1419
+ if (Buffer.isBuffer(content)) return content;
1420
+ if (content instanceof Uint8Array) return Buffer.from(content);
1421
+ if (mediaType === "application/json") return Buffer.from(`${JSON.stringify(content, null, 2)}\n`, "utf8");
1422
+ return Buffer.from(String(content), "utf8");
1423
+ }
1424
+ function normalizeArtifactExtension(extension) {
1425
+ if (!extension) return "";
1426
+ return extension.startsWith(".") ? extension : `.${extension}`;
1427
+ }
1428
+ function sessionDirPath(bundleId) {
1429
+ return path.posix.join(SESSIONS_DIR, bundleId);
1430
+ }
1431
+ function isoNow() {
1432
+ return (/* @__PURE__ */ new Date()).toISOString();
1433
+ }
1434
+ //#endregion
1435
+ //#region src/flows/runtime.ts
1436
+ const DEFAULT_FLOW_HEARTBEAT_MS = 5e3;
1437
+ const DEFAULT_FLOW_STEP_TIMEOUT_MS = 9e5;
1438
+ function setNodeValue(values, nodeId, value) {
1439
+ Object.defineProperty(values, nodeId, {
1440
+ value,
1441
+ enumerable: true,
1442
+ configurable: true,
1443
+ writable: true
1444
+ });
1445
+ }
1446
+ var FlowRunner = class {
1447
+ resolveAgent;
1448
+ defaultCwd;
1449
+ connectionOptions;
1450
+ defaultNodeTimeoutMs;
1451
+ suppressSdkConsoleErrors;
1452
+ sessionOptions;
1453
+ services;
1454
+ store;
1455
+ pendingPersistentSessionClients = /* @__PURE__ */ new Map();
1456
+ attempts = /* @__PURE__ */ new Map();
1457
+ pendingClientReleases = /* @__PURE__ */ new WeakMap();
1458
+ runInterruptions = /* @__PURE__ */ new Map();
1459
+ shellOwners = /* @__PURE__ */ new Map();
1460
+ constructor(options) {
1461
+ this.resolveAgent = options.resolveAgent;
1462
+ this.defaultCwd = options.resolveAgent(void 0).cwd;
1463
+ this.connectionOptions = {
1464
+ permissionMode: options.permissionMode,
1465
+ mcpServers: options.mcpServers,
1466
+ nonInteractivePermissions: options.nonInteractivePermissions,
1467
+ permissionPolicy: options.permissionPolicy,
1468
+ authCredentials: options.authCredentials,
1469
+ authPolicy: options.authPolicy,
1470
+ fs: options.fs,
1471
+ verbose: options.verbose
1472
+ };
1473
+ this.defaultNodeTimeoutMs = options.defaultNodeTimeoutMs ?? options.timeoutMs ?? DEFAULT_FLOW_STEP_TIMEOUT_MS;
1474
+ this.suppressSdkConsoleErrors = options.suppressSdkConsoleErrors;
1475
+ this.sessionOptions = options.sessionOptions;
1476
+ this.services = options.services ?? {};
1477
+ this.store = new FlowRunStore(options.outputRoot);
1478
+ }
1479
+ async run(flow, input, options = {}) {
1480
+ validateFlowDefinition(flow);
1481
+ const runId = createRunId(flow.name);
1482
+ const runTitle = await resolveFlowRunTitle(flow, input, options.flowPath);
1483
+ const runDir = await this.store.createRunDir(runId);
1484
+ const state = {
1485
+ runId,
1486
+ flowName: flow.name,
1487
+ runTitle,
1488
+ flowPath: options.flowPath,
1489
+ startedAt: isoNow$1(),
1490
+ updatedAt: isoNow$1(),
1491
+ status: "running",
1492
+ input,
1493
+ outputs: {},
1494
+ results: {},
1495
+ steps: [],
1496
+ sessionBindings: {}
1497
+ };
1498
+ try {
1499
+ const inputArtifact = await this.store.writeArtifact(runDir, state, input, {
1500
+ mediaType: "application/json",
1501
+ extension: "json",
1502
+ emitTrace: false
1503
+ });
1504
+ await this.store.initializeRunBundle(runDir, {
1505
+ flow,
1506
+ state,
1507
+ inputArtifact
1508
+ });
1509
+ return await this.runWithOwnership(flow, input, runDir, state);
1510
+ } finally {
1511
+ try {
1512
+ await this.closePendingPersistentSessionClients(runDir);
1513
+ } finally {
1514
+ this.store.releaseRun(runDir);
1515
+ }
1516
+ }
1517
+ }
1518
+ async runWithOwnership(flow, input, runDir, state) {
1519
+ let execution;
1520
+ let cancellation;
1521
+ let interruption;
1522
+ const result = await withInterrupt(() => {
1523
+ execution = this.executeFlowRun(flow, input, runDir, state);
1524
+ return execution;
1525
+ }, async (signal) => {
1526
+ const reason = interruption ?? new InterruptedError();
1527
+ interruption = reason;
1528
+ this.runInterruptions.set(runDir, reason);
1529
+ cancellation ??= this.cancelShellOwners(runDir, signal);
1530
+ cancellation.catch(() => {});
1531
+ this.attempts.get(runDir)?.cancel(reason, signal);
1532
+ await execution?.catch(() => {});
1533
+ }).then((value) => ({
1534
+ ok: true,
1535
+ value
1536
+ }), (error) => ({
1537
+ ok: false,
1538
+ error
1539
+ }));
1540
+ try {
1541
+ try {
1542
+ await cancellation;
1543
+ } catch (cleanupError) {
1544
+ const failure = result.ok || result.error === cleanupError ? cleanupError : new AggregateError([result.error, cleanupError], "Shell cleanup failed during interruption", { cause: cleanupError });
1545
+ await persistRunFailure(this.store, runDir, state, failure);
1546
+ throw failure;
1547
+ }
1548
+ if (result.ok && !interruption) return result.value;
1549
+ const failure = result.ok ? interruption : result.error;
1550
+ if (interruption) await persistRunFailure(this.store, runDir, state, failure);
1551
+ throw failure;
1552
+ } finally {
1553
+ this.releaseShellOwners(runDir);
1554
+ }
1555
+ }
1556
+ registerShellOwner(runDir, owner) {
1557
+ let owners = this.shellOwners.get(runDir);
1558
+ if (!owners) {
1559
+ owners = /* @__PURE__ */ new Set();
1560
+ this.shellOwners.set(runDir, owners);
1561
+ }
1562
+ owners.add(owner);
1563
+ const registered = owners;
1564
+ return () => {
1565
+ registered.delete(owner);
1566
+ if (registered.size === 0) this.shellOwners.delete(runDir);
1567
+ };
1568
+ }
1569
+ async cancelShellOwners(runDir, signal) {
1570
+ const owners = [...this.shellOwners.get(runDir) ?? []];
1571
+ const results = await Promise.allSettled(owners.map((owner) => owner.cancel(signal)));
1572
+ const errors = [];
1573
+ for (const result of results) if (result.status === "rejected") errors.push(result.reason);
1574
+ if (errors.length > 0) throw new AggregateError(errors, "Shell process cleanup failed", { cause: errors[0] });
1575
+ }
1576
+ releaseShellOwners(runDir) {
1577
+ for (const owner of this.shellOwners.get(runDir) ?? []) owner.release();
1578
+ this.shellOwners.delete(runDir);
1579
+ }
1580
+ async executeFlowRun(flow, input, runDir, state) {
1581
+ let current = flow.startAt;
1582
+ const attemptCounts = /* @__PURE__ */ new Map();
1583
+ try {
1584
+ while (current !== null) {
1585
+ this.throwIfRunInterrupted(runDir);
1586
+ const step = await this.executeFlowStep(flow, input, runDir, state, current, attemptCounts);
1587
+ this.throwIfRunInterrupted(runDir, step.executionError);
1588
+ const waiting = await this.maybeCompleteCheckpointStep(runDir, state, step);
1589
+ if (waiting) return waiting;
1590
+ await this.recordFlowStepOutcome(runDir, state, step);
1591
+ current = this.resolveNextNode(flow, step);
1592
+ }
1593
+ return await this.completeFlowRun(runDir, state);
1594
+ } catch (error) {
1595
+ if (!this.runInterruptions.has(runDir)) await persistRunFailure(this.store, runDir, state, error);
1596
+ throw error;
1597
+ } finally {
1598
+ this.runInterruptions.delete(runDir);
1599
+ }
1600
+ }
1601
+ throwIfRunInterrupted(runDir, error) {
1602
+ const interrupted = this.runInterruptions.get(runDir);
1603
+ if (interrupted) throw error ?? interrupted;
1604
+ }
1605
+ async executeFlowStep(flow, input, runDir, state, nodeId, attemptCounts) {
1606
+ if (!Object.hasOwn(flow.nodes, nodeId)) throw new Error(`Unknown flow node: ${nodeId}`);
1607
+ const node = flow.nodes[nodeId];
1608
+ const attemptId = nextAttemptId(attemptCounts, nodeId);
1609
+ const startedAt = isoNow$1();
1610
+ markNodeStarted(state, nodeId, attemptId, node.nodeType, startedAt, node.statusDetail);
1611
+ const attempt = new FlowAttempt({
1612
+ nodeId,
1613
+ attemptId,
1614
+ startedAt,
1615
+ timeoutMs: node.timeoutMs ?? this.defaultNodeTimeoutMs
1616
+ });
1617
+ this.attempts.set(runDir, attempt);
1618
+ const context = this.makeAttemptContext(runDir, state, input, node, attempt);
1619
+ let stopHeartbeat = () => {};
1620
+ let executed;
1621
+ let outcome = "ok";
1622
+ let executionError;
1623
+ try {
1624
+ this.throwIfRunInterrupted(runDir);
1625
+ executed = await attempt.run(async () => {
1626
+ await attempt.own(() => this.writeNodeStartedSnapshot(runDir, state, nodeId, attemptId, node));
1627
+ stopHeartbeat = this.startHeartbeat(runDir, state, node, attempt);
1628
+ const result = await this.executeNode(runDir, state, flow, nodeId, node, context);
1629
+ result.trace = await attempt.own(() => finalizeStepTrace(this.store, runDir, state, nodeId, attemptId, result.output, result.trace));
1630
+ return result;
1631
+ });
1632
+ this.throwIfRunInterrupted(runDir);
1633
+ } catch (error) {
1634
+ outcome = outcomeForError(error);
1635
+ executionError = error;
1636
+ executed = {
1637
+ output: void 0,
1638
+ promptText: null,
1639
+ rawText: null,
1640
+ sessionInfo: null,
1641
+ agentInfo: null,
1642
+ ...context.acpResult,
1643
+ trace: await finalizeStepTrace(this.store, runDir, state, nodeId, attemptId, void 0, context.acpResult ? context.acpResult.trace : extractAttachedStepTrace(error) ?? null)
1644
+ };
1645
+ } finally {
1646
+ stopHeartbeat();
1647
+ this.attempts.delete(runDir);
1648
+ }
1649
+ const nodeResult = createNodeResult({
1650
+ attemptId,
1651
+ nodeId,
1652
+ nodeType: node.nodeType,
1653
+ outcome,
1654
+ startedAt,
1655
+ finishedAt: isoNow$1(),
1656
+ ...outcome === "ok" ? { output: executed.output } : { error: executionError instanceof Error ? executionError.message : String(executionError) }
1657
+ });
1658
+ setNodeValue(state.results, nodeId, nodeResult);
1659
+ return {
1660
+ ...executed,
1661
+ nodeResult,
1662
+ executionError,
1663
+ attemptId,
1664
+ nodeId,
1665
+ node,
1666
+ startedAt,
1667
+ state
1668
+ };
1669
+ }
1670
+ makeAttemptContext(runDir, state, input, node, attempt) {
1671
+ const context = {
1672
+ nodeContext: {
1673
+ ...makeFlowNodeContext(state, input, this.services),
1674
+ signal: attempt.signal
1675
+ },
1676
+ attempt
1677
+ };
1678
+ if (node.nodeType === "action" && "run" in node) context.nodeContext.runShell = (execution) => this.runCallbackShell(runDir, attempt, execution);
1679
+ return context;
1680
+ }
1681
+ async writeNodeStartedSnapshot(runDir, state, nodeId, attemptId, node) {
1682
+ await this.store.writeSnapshot(runDir, state, {
1683
+ scope: "node",
1684
+ type: "node_started",
1685
+ nodeId,
1686
+ attemptId,
1687
+ payload: {
1688
+ nodeType: node.nodeType,
1689
+ timeoutMs: node.timeoutMs ?? this.defaultNodeTimeoutMs,
1690
+ ...state.statusDetail ? { statusDetail: state.statusDetail } : {}
1691
+ }
1692
+ });
1693
+ }
1694
+ async maybeCompleteCheckpointStep(runDir, state, step) {
1695
+ if (step.nodeResult.outcome !== "ok" || step.node.nodeType !== "checkpoint") return;
1696
+ setNodeValue(state.outputs, step.nodeId, step.output);
1697
+ state.waitingOn = step.nodeId;
1698
+ state.updatedAt = isoNow$1();
1699
+ state.status = "waiting";
1700
+ await this.recordFlowStepOutcome(runDir, state, step, { statusDetail: step.output?.summary ?? step.nodeId });
1701
+ return {
1702
+ runDir,
1703
+ state
1704
+ };
1705
+ }
1706
+ resolveNextNode(flow, step) {
1707
+ if (step.nodeResult.outcome === "ok") {
1708
+ setNodeValue(step.state.outputs, step.nodeId, step.output);
1709
+ return resolveNext(flow.edges, step.nodeId, step.output, step.nodeResult);
1710
+ }
1711
+ const next = resolveNext(flow.edges, step.nodeId, void 0, step.nodeResult);
1712
+ if (next !== null) return next;
1713
+ throw step.executionError;
1714
+ }
1715
+ async completeFlowRun(runDir, state) {
1716
+ state.status = "completed";
1717
+ state.finishedAt = isoNow$1();
1718
+ state.updatedAt = state.finishedAt;
1719
+ clearActiveNode(state);
1720
+ await this.store.writeSnapshot(runDir, state, {
1721
+ scope: "run",
1722
+ type: "run_completed",
1723
+ payload: { status: state.status }
1724
+ });
1725
+ return {
1726
+ runDir,
1727
+ state
1728
+ };
1729
+ }
1730
+ async recordFlowStepOutcome(runDir, state, step, overrides = {}) {
1731
+ state.updatedAt = isoNow$1();
1732
+ clearActiveNode(state, overrides.statusDetail);
1733
+ state.steps.push({
1734
+ attemptId: step.attemptId,
1735
+ nodeId: step.nodeId,
1736
+ nodeType: step.node.nodeType,
1737
+ outcome: step.nodeResult.outcome,
1738
+ startedAt: step.startedAt,
1739
+ finishedAt: step.nodeResult.finishedAt,
1740
+ promptText: step.promptText,
1741
+ rawText: step.rawText,
1742
+ output: step.output,
1743
+ error: step.nodeResult.error,
1744
+ session: step.sessionInfo,
1745
+ agent: step.agentInfo,
1746
+ ...step.trace ? { trace: step.trace } : {}
1747
+ });
1748
+ await this.store.writeSnapshot(runDir, state, {
1749
+ scope: "node",
1750
+ type: "node_outcome",
1751
+ nodeId: step.nodeId,
1752
+ attemptId: step.attemptId,
1753
+ payload: createNodeOutcomePayload(step.nodeResult, step.trace)
1754
+ });
1755
+ }
1756
+ async executeNode(runDir, state, flow, nodeId, node, context) {
1757
+ switch (node.nodeType) {
1758
+ case "compute": return await this.executeCallbackNode(nodeId, node, context);
1759
+ case "action": return "run" in node ? await this.executeCallbackNode(nodeId, node, context) : await this.executeShellNode(runDir, state, node, context);
1760
+ case "checkpoint": return await this.executeCallbackNode(nodeId, node, context);
1761
+ case "acp": return await this.executeAcpNode(runDir, state, flow, node, context);
1762
+ default: throw new Error(`Unsupported flow node: ${String(node)}`);
1763
+ }
1764
+ }
1765
+ async executeCallbackNode(nodeId, node, context) {
1766
+ context.attempt.assertActive();
1767
+ const output = node.nodeType === "checkpoint" && typeof node.run !== "function" ? {
1768
+ checkpoint: nodeId,
1769
+ summary: node.summary ?? nodeId
1770
+ } : await node.run?.(context.nodeContext);
1771
+ context.attempt.assertActive();
1772
+ return {
1773
+ output,
1774
+ promptText: null,
1775
+ rawText: null,
1776
+ sessionInfo: null,
1777
+ agentInfo: null,
1778
+ trace: node.nodeType === "action" ? { action: { actionType: "function" } } : null
1779
+ };
1780
+ }
1781
+ async executeShellNode(runDir, state, node, context) {
1782
+ const attempt = context.attempt;
1783
+ const execution = await node.exec(context.nodeContext);
1784
+ attempt.assertActive();
1785
+ const effectiveExecution = {
1786
+ ...execution,
1787
+ cwd: resolveShellActionCwd(this.defaultCwd, execution.cwd),
1788
+ timeoutMs: resolveShellActionTimeoutMs(execution.timeoutMs ?? attempt.remainingTimeoutMs())
1789
+ };
1790
+ updateStatusDetail(state, formatShellActionSummary(effectiveExecution));
1791
+ await attempt.own(() => this.store.writeLive(runDir, state, {
1792
+ scope: "node",
1793
+ type: "node_heartbeat",
1794
+ nodeId: attempt.nodeId,
1795
+ attemptId: attempt.attemptId,
1796
+ payload: { statusDetail: state.statusDetail }
1797
+ }));
1798
+ await attempt.own(() => this.store.appendTrace(runDir, state, {
1799
+ scope: "action",
1800
+ type: "action_prepared",
1801
+ nodeId: attempt.nodeId,
1802
+ attemptId: attempt.attemptId,
1803
+ payload: { action: {
1804
+ actionType: "shell",
1805
+ command: effectiveExecution.command,
1806
+ args: effectiveExecution.args ?? [],
1807
+ cwd: effectiveExecution.cwd
1808
+ } }
1809
+ }));
1810
+ const result = await attempt.own(() => runShellAction(effectiveExecution, this.shellControl(runDir, attempt)));
1811
+ const stdoutArtifact = await attempt.own(() => this.store.writeArtifact(runDir, state, result.stdout, {
1812
+ mediaType: "text/plain",
1813
+ extension: "txt",
1814
+ nodeId: attempt.nodeId,
1815
+ attemptId: attempt.attemptId
1816
+ }));
1817
+ const stderrArtifact = await attempt.own(() => this.store.writeArtifact(runDir, state, result.stderr, {
1818
+ mediaType: "text/plain",
1819
+ extension: "txt",
1820
+ nodeId: attempt.nodeId,
1821
+ attemptId: attempt.attemptId
1822
+ }));
1823
+ const actionTrace = {
1824
+ actionType: "shell",
1825
+ command: result.command,
1826
+ args: result.args,
1827
+ cwd: result.cwd,
1828
+ exitCode: result.exitCode,
1829
+ signal: result.signal,
1830
+ durationMs: result.durationMs
1831
+ };
1832
+ await attempt.own(() => this.store.appendTrace(runDir, state, {
1833
+ scope: "action",
1834
+ type: "action_completed",
1835
+ nodeId: attempt.nodeId,
1836
+ attemptId: attempt.attemptId,
1837
+ payload: {
1838
+ action: actionTrace,
1839
+ stdoutArtifact,
1840
+ stderrArtifact
1841
+ }
1842
+ }));
1843
+ const trace = {
1844
+ action: actionTrace,
1845
+ stdoutArtifact,
1846
+ stderrArtifact
1847
+ };
1848
+ let output;
1849
+ try {
1850
+ output = node.parse ? await node.parse(result, context.nodeContext) : result;
1851
+ attempt.assertActive();
1852
+ } catch (error) {
1853
+ throw attachStepTrace(error, trace);
1854
+ }
1855
+ return {
1856
+ output,
1857
+ promptText: null,
1858
+ rawText: result.combinedOutput,
1859
+ sessionInfo: null,
1860
+ agentInfo: null,
1861
+ trace
1862
+ };
1863
+ }
1864
+ shellControl(runDir, attempt) {
1865
+ return {
1866
+ signal: attempt.signal,
1867
+ get terminationSignal() {
1868
+ return attempt.terminationSignal;
1869
+ },
1870
+ registerOwner: (owner) => {
1871
+ const releaseAttempt = attempt.registerCancellation((signal) => owner.cancel(signal));
1872
+ const releaseRun = this.registerShellOwner(runDir, owner);
1873
+ return () => {
1874
+ releaseAttempt();
1875
+ releaseRun();
1876
+ };
1877
+ }
1878
+ };
1879
+ }
1880
+ runCallbackShell(runDir, attempt, execution) {
1881
+ return attempt.own(() => runShellCommand({
1882
+ ...execution,
1883
+ cwd: resolveShellActionCwd(this.defaultCwd, execution.cwd)
1884
+ }, this.shellControl(runDir, attempt)));
1885
+ }
1886
+ async executeAcpNode(runDir, state, flow, node, context) {
1887
+ const attempt = context.attempt;
1888
+ const prepared = await this.prepareAcpPrompt(runDir, state, node, context);
1889
+ if (node.session?.isolated) return await this.executeIsolatedAcpPrompt(runDir, state, flow, node, context, prepared);
1890
+ const boundSession = await this.ensureSessionBinding(runDir, state, flow, node, prepared.agentInfo, attempt);
1891
+ return await this.executePersistentAcpPrompt(runDir, state, node, context, prepared, boundSession);
1892
+ }
1893
+ async prepareAcpPrompt(runDir, state, node, context) {
1894
+ const resolvedAgent = this.resolveAgent(node.profile);
1895
+ const agentInfo = {
1896
+ ...resolvedAgent,
1897
+ agentArgv: resolvedAgent.agentArgv?.slice(),
1898
+ cwd: await resolveNodeCwd(resolvedAgent.cwd, node.cwd, context.nodeContext)
1899
+ };
1900
+ context.attempt.assertActive();
1901
+ const prompt = normalizePromptInput(await Promise.resolve(node.prompt(context.nodeContext)));
1902
+ context.attempt.assertActive();
1903
+ const promptText = promptToDisplayText(prompt);
1904
+ const result = {
1905
+ output: void 0,
1906
+ promptText,
1907
+ rawText: null,
1908
+ sessionInfo: null,
1909
+ agentInfo,
1910
+ trace: null
1911
+ };
1912
+ context.acpResult = result;
1913
+ updateStatusDetail(state, summarizePrompt(promptText, node.statusDetail));
1914
+ await context.attempt.own(() => this.writeAcpPromptHeartbeat(runDir, state, context.attempt));
1915
+ const promptArtifact = await context.attempt.own(() => this.store.writeArtifact(runDir, state, promptText, {
1916
+ mediaType: "text/plain",
1917
+ extension: "txt",
1918
+ nodeId: context.attempt.nodeId,
1919
+ attemptId: context.attempt.attemptId
1920
+ }));
1921
+ result.trace = { promptArtifact };
1922
+ return {
1923
+ agentInfo,
1924
+ prompt,
1925
+ promptArtifact,
1926
+ attempt: context.attempt,
1927
+ result
1928
+ };
1929
+ }
1930
+ async writeAcpPromptHeartbeat(runDir, state, attempt) {
1931
+ await this.store.writeLive(runDir, state, {
1932
+ scope: "node",
1933
+ type: "node_heartbeat",
1934
+ nodeId: attempt.nodeId,
1935
+ attemptId: attempt.attemptId,
1936
+ payload: { statusDetail: state.statusDetail }
1937
+ });
1938
+ }
1939
+ async executeIsolatedAcpPrompt(runDir, state, flow, node, context, prepared) {
1940
+ const binding = createIsolatedSessionBinding(flow.name, state.runId, prepared.attempt.attemptId, node.profile, prepared.agentInfo);
1941
+ prepared.result.sessionInfo = binding;
1942
+ await prepared.attempt.own(() => this.initializeIsolatedSessionBundle(runDir, state, binding, prepared.attempt));
1943
+ await prepared.attempt.own(() => this.appendAcpPromptPreparedTrace(runDir, state, binding, prepared.promptArtifact, prepared.attempt));
1944
+ const prompt = await prepared.attempt.own(() => this.runIsolatedPrompt(runDir, state, binding, prepared));
1945
+ return await this.finishAcpPrompt(runDir, state, node, context, prepared, prompt);
1946
+ }
1947
+ async initializeIsolatedSessionBundle(runDir, state, binding, attempt) {
1948
+ const timestamp = attempt.startedAt;
1949
+ const initialRecord = createSyntheticSessionRecord({
1950
+ binding,
1951
+ createdAt: timestamp,
1952
+ updatedAt: timestamp,
1953
+ conversation: createSessionConversation(timestamp),
1954
+ acpxState: void 0,
1955
+ lastSeq: 0
1956
+ });
1957
+ await this.store.ensureSessionBundle(runDir, state, binding, initialRecord);
1958
+ }
1959
+ async executePersistentAcpPrompt(runDir, state, node, context, prepared, binding) {
1960
+ prepared.result.sessionInfo = binding;
1961
+ await prepared.attempt.own(() => this.appendAcpPromptPreparedTrace(runDir, state, binding, prepared.promptArtifact, prepared.attempt));
1962
+ const prompt = await prepared.attempt.own(() => this.runPersistentPrompt(runDir, state, binding, prepared));
1963
+ return await this.finishAcpPrompt(runDir, state, node, context, prepared, prompt);
1964
+ }
1965
+ async appendAcpPromptPreparedTrace(runDir, state, binding, promptArtifact, attempt) {
1966
+ await this.store.appendTrace(runDir, state, {
1967
+ scope: "acp",
1968
+ type: "acp_prompt_prepared",
1969
+ nodeId: attempt.nodeId,
1970
+ attemptId: attempt.attemptId,
1971
+ sessionId: binding.bundleId,
1972
+ payload: {
1973
+ sessionId: binding.bundleId,
1974
+ promptArtifact
1975
+ }
1976
+ });
1977
+ }
1978
+ async finishAcpPrompt(runDir, state, node, context, prepared, prompt) {
1979
+ await prepared.attempt.own(() => this.appendAcpResponseParsedTrace(runDir, state, prompt, prepared.attempt));
1980
+ const output = await this.parseAcpOutput(node, context, prompt.rawText);
1981
+ return {
1982
+ ...prepared.result,
1983
+ output
1984
+ };
1985
+ }
1986
+ async publishAcpCapture(runDir, state, prepared, sessionInfo, record, messageStart, rawText, events) {
1987
+ const result = prepared.result;
1988
+ result.sessionInfo = sessionInfo;
1989
+ const trace = {
1990
+ sessionId: sessionInfo.bundleId,
1991
+ promptArtifact: prepared.promptArtifact
1992
+ };
1993
+ result.trace = trace;
1994
+ await this.store.ensureSessionBundle(runDir, state, sessionInfo);
1995
+ await this.store.writeSessionRecord(runDir, state, sessionInfo, record);
1996
+ if (events) trace.conversation = {
1997
+ sessionId: sessionInfo.bundleId,
1998
+ messageStart,
1999
+ messageEnd: Math.max(messageStart, record.messages.length - 1),
2000
+ ...events
2001
+ };
2002
+ const rawResponseArtifact = await this.store.writeArtifact(runDir, state, rawText, {
2003
+ mediaType: "text/plain",
2004
+ extension: "txt",
2005
+ nodeId: prepared.attempt.nodeId,
2006
+ attemptId: prepared.attempt.attemptId,
2007
+ sessionId: sessionInfo.bundleId
2008
+ });
2009
+ trace.rawResponseArtifact = rawResponseArtifact;
2010
+ return {
2011
+ rawText,
2012
+ sessionInfo,
2013
+ conversation: trace.conversation,
2014
+ rawResponseArtifact
2015
+ };
2016
+ }
2017
+ async appendAcpResponseParsedTrace(runDir, state, prompt, attempt) {
2018
+ await this.store.appendTrace(runDir, state, {
2019
+ scope: "acp",
2020
+ type: "acp_response_parsed",
2021
+ nodeId: attempt.nodeId,
2022
+ attemptId: attempt.attemptId,
2023
+ sessionId: prompt.sessionInfo.bundleId,
2024
+ payload: {
2025
+ sessionId: prompt.sessionInfo.bundleId,
2026
+ conversation: prompt.conversation,
2027
+ rawResponseArtifact: prompt.rawResponseArtifact
2028
+ }
2029
+ });
2030
+ }
2031
+ async parseAcpOutput(node, context, rawText) {
2032
+ context.attempt.assertActive();
2033
+ const output = node.parse ? await node.parse(rawText, context.nodeContext) : rawText;
2034
+ context.attempt.assertActive();
2035
+ return output;
2036
+ }
2037
+ startHeartbeat(runDir, state, node, attempt) {
2038
+ const heartbeatMs = Math.max(0, Math.round(node.heartbeatMs ?? DEFAULT_FLOW_HEARTBEAT_MS));
2039
+ if (heartbeatMs === 0) return () => {};
2040
+ let pending = false;
2041
+ const heartbeat = async () => {
2042
+ if (!attempt.active || pending) return;
2043
+ pending = true;
2044
+ try {
2045
+ await attempt.own(async () => {
2046
+ state.lastHeartbeatAt = isoNow$1();
2047
+ state.updatedAt = state.lastHeartbeatAt;
2048
+ await this.store.writeLive(runDir, state, {
2049
+ scope: "node",
2050
+ type: "node_heartbeat",
2051
+ nodeId: attempt.nodeId,
2052
+ attemptId: attempt.attemptId,
2053
+ payload: { statusDetail: state.statusDetail }
2054
+ });
2055
+ }, { bestEffort: true });
2056
+ } catch {} finally {
2057
+ pending = false;
2058
+ }
2059
+ };
2060
+ const timer = setInterval(() => {
2061
+ heartbeat();
2062
+ }, heartbeatMs);
2063
+ return () => clearInterval(timer);
2064
+ }
2065
+ async ensureSessionBinding(runDir, state, flow, node, agent, attempt) {
2066
+ const handle = node.session?.handle ?? "main";
2067
+ const key = createSessionBindingKey(agent.agentCommand, agent.cwd, handle, agent.agentArgv);
2068
+ const existing = state.sessionBindings[key];
2069
+ if (existing) {
2070
+ await attempt.own(() => this.store.ensureSessionBundle(runDir, state, existing));
2071
+ return existing;
2072
+ }
2073
+ const name = createSessionName(flow.name, handle, agent.cwd, state.runId);
2074
+ const created = await attempt.own(async () => {
2075
+ const acquired = await createSessionWithClient({
2076
+ agentCommand: agent.agentCommand,
2077
+ agentArgv: agent.agentArgv,
2078
+ cwd: agent.cwd,
2079
+ name,
2080
+ ...this.connectionOptions,
2081
+ signal: attempt.signal,
2082
+ handleProcessInterrupts: false,
2083
+ sessionOptions: this.sessionOptions
2084
+ });
2085
+ this.pendingClientReleases.set(acquired.client, attempt.registerCancellation(async () => {
2086
+ const clients = this.pendingPersistentSessionClients.get(runDir);
2087
+ if (clients?.get(key) === acquired.client) clients.delete(key);
2088
+ await acquired.client.close();
2089
+ }));
2090
+ return acquired;
2091
+ });
2092
+ attempt.assertActive();
2093
+ const binding = {
2094
+ key,
2095
+ handle,
2096
+ bundleId: createSessionBundleId(handle, key),
2097
+ name,
2098
+ profile: node.profile,
2099
+ agentName: agent.agentName,
2100
+ agentCommand: agent.agentCommand,
2101
+ agentArgv: agent.agentArgv,
2102
+ cwd: agent.cwd,
2103
+ acpxRecordId: created.record.acpxRecordId,
2104
+ acpSessionId: created.record.acpSessionId,
2105
+ agentSessionId: created.record.agentSessionId
2106
+ };
2107
+ state.sessionBindings[key] = binding;
2108
+ let clients = this.pendingPersistentSessionClients.get(runDir);
2109
+ if (!clients) {
2110
+ clients = /* @__PURE__ */ new Map();
2111
+ this.pendingPersistentSessionClients.set(runDir, clients);
2112
+ }
2113
+ clients.set(binding.key, created.client);
2114
+ await attempt.own(() => this.store.ensureSessionBundle(runDir, state, binding, created.record));
2115
+ return binding;
2116
+ }
2117
+ createPromptEventCapture(runDir, binding) {
2118
+ const pending = /* @__PURE__ */ new Set();
2119
+ let ordinal = 0;
2120
+ let failure;
2121
+ let eventStartSeq;
2122
+ let eventEndSeq = 0;
2123
+ const snapshot = (outcome) => ({
2124
+ outcome,
2125
+ events: !failure && eventStartSeq !== void 0 ? {
2126
+ eventStartSeq,
2127
+ eventEndSeq
2128
+ } : void 0,
2129
+ lastSeq: eventEndSeq
2130
+ });
2131
+ return {
2132
+ onAcpMessage: (direction, message) => {
2133
+ const index = ordinal++;
2134
+ const write = this.store.appendSessionEvent(runDir, binding, direction, message).then((seq) => {
2135
+ eventStartSeq = Math.min(eventStartSeq ?? seq, seq);
2136
+ eventEndSeq = Math.max(eventEndSeq, seq);
2137
+ }, (reason) => {
2138
+ if (!failure || index < failure.ordinal) failure = {
2139
+ ordinal: index,
2140
+ reason
2141
+ };
2142
+ }).finally(() => pending.delete(write));
2143
+ pending.add(write);
2144
+ },
2145
+ async run(operation, finalize) {
2146
+ let result;
2147
+ try {
2148
+ result = {
2149
+ status: "fulfilled",
2150
+ value: await operation()
2151
+ };
2152
+ } catch (reason) {
2153
+ result = {
2154
+ status: "rejected",
2155
+ reason
2156
+ };
2157
+ }
2158
+ await Promise.all(pending);
2159
+ let finalized;
2160
+ try {
2161
+ finalized = {
2162
+ status: "fulfilled",
2163
+ value: await finalize(snapshot(result))
2164
+ };
2165
+ } catch (reason) {
2166
+ finalized = {
2167
+ status: "rejected",
2168
+ reason
2169
+ };
2170
+ }
2171
+ if (result.status === "rejected") throw result.reason;
2172
+ if (failure) throw failure.reason;
2173
+ if (eventStartSeq === void 0) throw new Error(`Missing ACP event capture for session ${binding.bundleId}`);
2174
+ if (finalized.status === "rejected") throw finalized.reason;
2175
+ return finalized.value;
2176
+ }
2177
+ };
2178
+ }
2179
+ async runPersistentPrompt(runDir, state, binding, prepared) {
2180
+ const { attempt, prompt } = prepared;
2181
+ const capture = createQuietCaptureOutput();
2182
+ const beforeRecord = await resolveSessionRecord(binding.acpxRecordId);
2183
+ attempt.assertActive();
2184
+ const events = this.createPromptEventCapture(runDir, binding);
2185
+ const clients = this.pendingPersistentSessionClients.get(runDir);
2186
+ const initialClient = clients?.get(binding.key);
2187
+ if (initialClient) {
2188
+ clients?.delete(binding.key);
2189
+ this.pendingClientReleases.get(initialClient)?.();
2190
+ this.pendingClientReleases.delete(initialClient);
2191
+ }
2192
+ return await events.run(() => sendSessionDirect({
2193
+ sessionId: binding.acpxRecordId,
2194
+ prompt,
2195
+ resumePolicy: "same-session-only",
2196
+ ...this.connectionOptions,
2197
+ outputFormatter: capture.formatter,
2198
+ errorEmissionPolicy: { queueErrorAlreadyEmitted: false },
2199
+ onAcpMessage: events.onAcpMessage,
2200
+ suppressSdkConsoleErrors: this.suppressSdkConsoleErrors,
2201
+ client: initialClient
2202
+ }, {
2203
+ signal: attempt.signal,
2204
+ handleProcessInterrupts: false
2205
+ }), async (receipt) => {
2206
+ const rawText = capture.read();
2207
+ prepared.result.rawText = rawText;
2208
+ const afterRecord = await resolveSessionRecord(binding.acpxRecordId);
2209
+ const sessionInfo = {
2210
+ ...binding,
2211
+ acpSessionId: afterRecord.acpSessionId,
2212
+ agentSessionId: afterRecord.agentSessionId
2213
+ };
2214
+ state.sessionBindings[sessionInfo.key] = sessionInfo;
2215
+ return await this.publishAcpCapture(runDir, state, prepared, sessionInfo, afterRecord, findConversationDeltaStart(beforeRecord.messages, afterRecord.messages), rawText, receipt.events);
2216
+ });
2217
+ }
2218
+ async closePendingPersistentSessionClients(runDir) {
2219
+ const pendingClients = [...this.pendingPersistentSessionClients.get(runDir)?.values() ?? []];
2220
+ this.pendingPersistentSessionClients.delete(runDir);
2221
+ const failure = (await Promise.allSettled(pendingClients.map(async (client) => {
2222
+ this.pendingClientReleases.get(client)?.();
2223
+ this.pendingClientReleases.delete(client);
2224
+ await client.close();
2225
+ }))).find((result) => result.status === "rejected");
2226
+ if (failure?.status === "rejected") throw failure.reason;
2227
+ }
2228
+ async runIsolatedPrompt(runDir, state, binding, prepared) {
2229
+ const { agentInfo: agent, prompt, attempt } = prepared;
2230
+ const capture = createQuietCaptureOutput();
2231
+ const conversation = createSessionConversation(attempt.startedAt);
2232
+ let acpxState;
2233
+ recordPromptSubmission(conversation, prompt, attempt.startedAt);
2234
+ const events = this.createPromptEventCapture(runDir, binding);
2235
+ return await events.run(() => runOnce({
2236
+ agentCommand: agent.agentCommand,
2237
+ agentArgv: agent.agentArgv,
2238
+ cwd: agent.cwd,
2239
+ prompt,
2240
+ ...this.connectionOptions,
2241
+ outputFormatter: capture.formatter,
2242
+ errorEmissionPolicy: { queueErrorAlreadyEmitted: false },
2243
+ onAcpMessage: events.onAcpMessage,
2244
+ onSessionUpdate: (notification) => {
2245
+ acpxState = recordSessionUpdate(conversation, acpxState, notification);
2246
+ },
2247
+ onClientOperation: (operation) => {
2248
+ acpxState = recordClientOperation(conversation, acpxState, operation);
2249
+ },
2250
+ suppressSdkConsoleErrors: this.suppressSdkConsoleErrors,
2251
+ sessionOptions: this.sessionOptions
2252
+ }, {
2253
+ signal: attempt.signal,
2254
+ handleProcessInterrupts: false
2255
+ }), async (receipt) => {
2256
+ const rawText = capture.read();
2257
+ prepared.result.rawText = rawText;
2258
+ const sessionId = receipt.outcome.status === "fulfilled" ? receipt.outcome.value.sessionId : capture.sessionId();
2259
+ const sessionInfo = sessionId === void 0 ? binding : {
2260
+ ...binding,
2261
+ acpxRecordId: sessionId,
2262
+ acpSessionId: sessionId
2263
+ };
2264
+ const record = createSyntheticSessionRecord({
2265
+ binding: sessionInfo,
2266
+ createdAt: attempt.startedAt,
2267
+ updatedAt: conversation.updated_at,
2268
+ conversation,
2269
+ acpxState: cloneSessionAcpxState(acpxState),
2270
+ lastSeq: receipt.lastSeq
2271
+ });
2272
+ return await this.publishAcpCapture(runDir, state, prepared, sessionInfo, record, 0, rawText, receipt.events);
2273
+ });
2274
+ }
2275
+ };
2276
+ //#endregion
2277
+ //#region src/flows/json.ts
2278
+ function normalizeJsonText(text) {
2279
+ if (typeof text === "string") return text.trim();
2280
+ if (text == null) return "";
2281
+ if (typeof text === "number" || typeof text === "boolean" || typeof text === "bigint" || typeof text === "symbol") return String(text).trim();
2282
+ return "";
2283
+ }
2284
+ function parseJsonObject(text, options = {}) {
2285
+ const trimmed = normalizeJsonText(text);
2286
+ if (!trimmed) throw new Error("Expected JSON output, got empty text");
2287
+ const mode = options.mode ?? "compat";
2288
+ const direct = tryParse(trimmed);
2289
+ if (direct.ok) return direct.value;
2290
+ const fenced = parseFencedJsonIfAllowed(trimmed, mode);
2291
+ if (fenced.ok) return fenced.value;
2292
+ if (mode === "compat") {
2293
+ const balanced = parseBalancedJsonCandidate(trimmed);
2294
+ if (balanced.ok) return balanced.value;
2295
+ }
2296
+ throw new Error(`Could not parse JSON from assistant output:\n${trimmed}`);
2297
+ }
2298
+ function parseFencedJsonIfAllowed(text, mode) {
2299
+ if (mode !== "fenced" && mode !== "compat") return { ok: false };
2300
+ const fencedText = extractFencedJsonText(text);
2301
+ return fencedText === null ? { ok: false } : tryParse(fencedText);
2302
+ }
2303
+ const COMPAT_JSON_WORK_MULTIPLIER = 8;
2304
+ function consumeRecoveryWork(budget, units) {
2305
+ if (units > budget.remaining) {
2306
+ budget.remaining = 0;
2307
+ return false;
2308
+ }
2309
+ budget.remaining -= units;
2310
+ return true;
2311
+ }
2312
+ function parseBalancedJsonCandidate(text) {
2313
+ const budget = { remaining: text.length * COMPAT_JSON_WORK_MULTIPLIER };
2314
+ for (let index = 0; index < text.length && budget.remaining > 0; index += 1) {
2315
+ if (text[index] !== "{" && text[index] !== "[") continue;
2316
+ const end = scanBalanced(text, index, budget);
2317
+ if (end === null) continue;
2318
+ if (!consumeRecoveryWork(budget, end - index)) return { ok: false };
2319
+ const parsed = tryParse(text.slice(index, end));
2320
+ if (parsed.ok) return parsed;
2321
+ }
2322
+ return { ok: false };
2323
+ }
2324
+ function parseStrictJsonObject(text) {
2325
+ return parseJsonObject(text, { mode: "strict" });
2326
+ }
2327
+ function extractJsonObject(text) {
2328
+ return parseJsonObject(text, { mode: "compat" });
2329
+ }
2330
+ function tryParse(text) {
2331
+ try {
2332
+ return {
2333
+ ok: true,
2334
+ value: JSON.parse(text)
2335
+ };
2336
+ } catch {
2337
+ return { ok: false };
2338
+ }
2339
+ }
2340
+ function extractFencedJsonText(text) {
2341
+ const openingFenceIndex = text.indexOf("```");
2342
+ if (openingFenceIndex === -1) return null;
2343
+ let contentStart = openingFenceIndex + 3;
2344
+ if (text.slice(contentStart, contentStart + 4).toLowerCase() === "json" && isFenceWhitespace(text[contentStart + 4])) contentStart += 4;
2345
+ while (isFenceWhitespace(text[contentStart])) contentStart += 1;
2346
+ const closingFenceIndex = text.indexOf("```", contentStart);
2347
+ if (closingFenceIndex === -1) return null;
2348
+ return text.slice(contentStart, closingFenceIndex).trim();
2349
+ }
2350
+ function isFenceWhitespace(char) {
2351
+ return char === " " || char === "\n" || char === "\r" || char === " ";
2352
+ }
2353
+ function scanBalanced(text, startIndex, budget) {
2354
+ const stack = [];
2355
+ let inString = false;
2356
+ let escaped = false;
2357
+ for (let index = startIndex; index < text.length; index += 1) {
2358
+ if (!consumeRecoveryWork(budget, 1)) return null;
2359
+ const char = text[index];
2360
+ if (inString) {
2361
+ const next = scanStringChar(char, escaped);
2362
+ escaped = next.escaped;
2363
+ inString = next.inString;
2364
+ continue;
2365
+ }
2366
+ if (char === "\"") {
2367
+ inString = true;
2368
+ continue;
2369
+ }
2370
+ const result = scanBalancedToken(index, char, stack);
2371
+ if (result !== SCAN_CONTINUE) return result;
2372
+ }
2373
+ return null;
2374
+ }
2375
+ const SCAN_CONTINUE = Symbol("scan-continue");
2376
+ function scanBalancedToken(index, char, stack) {
2377
+ if (char === "{" || char === "[") {
2378
+ stack.push(char);
2379
+ return SCAN_CONTINUE;
2380
+ }
2381
+ if (char !== "}" && char !== "]") return SCAN_CONTINUE;
2382
+ if (!balancedClosingTokenMatches(stack.at(-1), char)) return null;
2383
+ stack.pop();
2384
+ return stack.length === 0 ? index + 1 : SCAN_CONTINUE;
2385
+ }
2386
+ function balancedClosingTokenMatches(open, close) {
2387
+ if (open === "{") return close === "}";
2388
+ if (open === "[") return close === "]";
2389
+ return false;
2390
+ }
2391
+ function scanStringChar(char, escaped) {
2392
+ if (escaped) return {
2393
+ escaped: false,
2394
+ inString: true
2395
+ };
2396
+ if (char === "\\") return {
2397
+ escaped: true,
2398
+ inString: true
2399
+ };
2400
+ return {
2401
+ escaped: false,
2402
+ inString: char !== "\""
2403
+ };
2404
+ }
2405
+ //#endregion
2406
+ //#region src/flows/decision.ts
2407
+ const DEFAULT_FIELD = "route";
2408
+ const SIMPLE_FIELD_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
2409
+ function decision(definition) {
2410
+ const { question, choices, field: fieldOverride, ...acpOptions } = definition;
2411
+ const field = normalizeField(fieldOverride);
2412
+ assertValidChoices(choices);
2413
+ const allowed = new Set(choices);
2414
+ return acp({
2415
+ ...acpOptions,
2416
+ async prompt(context) {
2417
+ return formatDecisionPrompt(typeof question === "function" ? await question(context) : question, choices, field);
2418
+ },
2419
+ parse(text) {
2420
+ const raw = extractJsonObject(text);
2421
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`Decision response must be a JSON object, got ${typeof raw}`);
2422
+ const value = raw[field];
2423
+ if (typeof value !== "string" || !allowed.has(value)) {
2424
+ const allowedLabels = choices.map((choice) => JSON.stringify(choice)).join(", ");
2425
+ throw new Error(`Decision returned invalid ${field}=${JSON.stringify(value)}; expected one of ${allowedLabels}`);
2426
+ }
2427
+ return raw;
2428
+ }
2429
+ });
2430
+ }
2431
+ function decisionEdge(args) {
2432
+ const field = normalizeField(args.field);
2433
+ assertValidChoices(args.choices);
2434
+ for (const choice of args.choices) if (!Object.hasOwn(args.cases, choice)) throw new Error(`Decision edge is missing case for choice ${JSON.stringify(choice)}`);
2435
+ return {
2436
+ from: args.from,
2437
+ switch: {
2438
+ on: `$.${field}`,
2439
+ cases: args.cases
2440
+ }
2441
+ };
2442
+ }
2443
+ function assertValidChoices(choices) {
2444
+ if (choices.length === 0) throw new Error("Decision choices must include at least one value");
2445
+ const seen = /* @__PURE__ */ new Set();
2446
+ for (const choice of choices) {
2447
+ if (typeof choice !== "string" || choice.length === 0) throw new Error("Decision choices must be non-empty strings");
2448
+ if (seen.has(choice)) throw new Error(`Decision choices must be unique; duplicate ${JSON.stringify(choice)}`);
2449
+ seen.add(choice);
2450
+ }
2451
+ }
2452
+ function normalizeField(fieldOverride) {
2453
+ const field = fieldOverride ?? DEFAULT_FIELD;
2454
+ if (!SIMPLE_FIELD_PATTERN.test(field)) throw new Error(`Decision field must be a simple JSON key matching ${SIMPLE_FIELD_PATTERN.source}`);
2455
+ return field;
2456
+ }
2457
+ function formatDecisionPrompt(question, choices, field) {
2458
+ const allowed = choices.map((choice) => JSON.stringify(choice)).join(" | ");
2459
+ return [
2460
+ question,
2461
+ "",
2462
+ "Return exactly one JSON object with this shape:",
2463
+ "{",
2464
+ ` ${JSON.stringify(field)}: ${allowed},`,
2465
+ " \"reason\": \"short justification\"",
2466
+ "}",
2467
+ "",
2468
+ "Do not include any other text outside the JSON object."
2469
+ ].join("\n");
2470
+ }
2471
+ //#endregion
2472
+ export { parseStrictJsonObject as a, validateFlowDefinition as c, checkpoint as d, compute as f, isDefinedFlow as h, parseJsonObject as i, acp as l, shell as m, decisionEdge as n, FlowRunner as o, defineFlow as p, extractJsonObject as r, flowRunsBaseDir as s, decision as t, action as u };
2473
+
2474
+ //# sourceMappingURL=flows-CiJSCy4D.js.map