fascicle 0.6.3 → 0.8.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1846 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ //#region src/core/flow-schema.json
4
+ var flow_schema_default = {
5
+ $schema: "https://json-schema.org/draft/2020-12/schema",
6
+ $id: "https://robmclarty.dev/schemas/flow-schema.json",
7
+ title: "fascicle Flow DSL",
8
+ description: "YAML/JSON representation of a composition tree. Documentation-only in v1. See spec.md §5.17.",
9
+ type: "array",
10
+ items: { "$ref": "#/$defs/compose_entry" },
11
+ $defs: {
12
+ "compose_entry": {
13
+ "type": "object",
14
+ "required": ["compose"],
15
+ "properties": { "compose": { "type": "string" } },
16
+ "allOf": [{ "$ref": "#/$defs/node" }]
17
+ },
18
+ "node": {
19
+ "type": "object",
20
+ "anyOf": [
21
+ { "required": ["step"] },
22
+ { "required": ["sequence"] },
23
+ { "required": ["parallel"] },
24
+ { "required": ["branch"] },
25
+ { "required": ["map"] },
26
+ { "required": ["pipe"] },
27
+ { "required": ["retry"] },
28
+ { "required": ["fallback"] },
29
+ { "required": ["timeout"] },
30
+ { "required": ["loop"] },
31
+ { "required": ["compose_node"] },
32
+ { "required": ["adversarial"] },
33
+ { "required": ["ensemble"] },
34
+ { "required": ["tournament"] },
35
+ { "required": ["consensus"] },
36
+ { "required": ["checkpoint"] },
37
+ { "required": ["suspend"] },
38
+ { "required": ["scope"] },
39
+ { "required": ["ref"] }
40
+ ],
41
+ "properties": {
42
+ "step": { "$ref": "#/$defs/step_config" },
43
+ "sequence": { "$ref": "#/$defs/sequence_config" },
44
+ "parallel": { "$ref": "#/$defs/parallel_config" },
45
+ "branch": { "$ref": "#/$defs/branch_config" },
46
+ "map": { "$ref": "#/$defs/map_config" },
47
+ "pipe": { "$ref": "#/$defs/pipe_config" },
48
+ "retry": { "$ref": "#/$defs/retry_config" },
49
+ "fallback": { "$ref": "#/$defs/fallback_config" },
50
+ "timeout": { "$ref": "#/$defs/timeout_config" },
51
+ "loop": { "$ref": "#/$defs/loop_config" },
52
+ "compose_node": { "$ref": "#/$defs/compose_node_config" },
53
+ "adversarial": { "$ref": "#/$defs/adversarial_config" },
54
+ "ensemble": { "$ref": "#/$defs/ensemble_config" },
55
+ "tournament": { "$ref": "#/$defs/tournament_config" },
56
+ "consensus": { "$ref": "#/$defs/consensus_config" },
57
+ "checkpoint": { "$ref": "#/$defs/checkpoint_config" },
58
+ "suspend": { "$ref": "#/$defs/suspend_config" },
59
+ "scope": { "$ref": "#/$defs/scope_config" },
60
+ "ref": { "type": "string" }
61
+ }
62
+ },
63
+ "step_config": {
64
+ "type": "object",
65
+ "required": ["fn"],
66
+ "properties": {
67
+ "id": { "type": "string" },
68
+ "fn": { "type": "string" }
69
+ }
70
+ },
71
+ "sequence_config": {
72
+ "type": "array",
73
+ "items": { "$ref": "#/$defs/node" }
74
+ },
75
+ "parallel_config": {
76
+ "type": "object",
77
+ "additionalProperties": { "$ref": "#/$defs/node" }
78
+ },
79
+ "branch_config": {
80
+ "type": "object",
81
+ "required": [
82
+ "when",
83
+ "then",
84
+ "otherwise"
85
+ ],
86
+ "properties": {
87
+ "when": { "type": "string" },
88
+ "then": { "$ref": "#/$defs/node" },
89
+ "otherwise": { "$ref": "#/$defs/node" }
90
+ }
91
+ },
92
+ "map_config": {
93
+ "type": "object",
94
+ "required": ["items", "do"],
95
+ "properties": {
96
+ "items": { "type": "string" },
97
+ "do": { "$ref": "#/$defs/node" },
98
+ "concurrency": {
99
+ "type": "integer",
100
+ "minimum": 1
101
+ }
102
+ }
103
+ },
104
+ "pipe_config": {
105
+ "type": "object",
106
+ "required": ["of", "fn"],
107
+ "properties": {
108
+ "of": { "$ref": "#/$defs/node" },
109
+ "fn": { "type": "string" }
110
+ }
111
+ },
112
+ "retry_config": {
113
+ "type": "object",
114
+ "required": ["do", "max_attempts"],
115
+ "properties": {
116
+ "do": { "$ref": "#/$defs/node" },
117
+ "max_attempts": {
118
+ "type": "integer",
119
+ "minimum": 1
120
+ },
121
+ "backoff_ms": {
122
+ "type": "integer",
123
+ "minimum": 0
124
+ }
125
+ }
126
+ },
127
+ "fallback_config": {
128
+ "type": "object",
129
+ "required": ["primary", "backup"],
130
+ "properties": {
131
+ "primary": { "$ref": "#/$defs/node" },
132
+ "backup": { "$ref": "#/$defs/node" }
133
+ }
134
+ },
135
+ "timeout_config": {
136
+ "type": "object",
137
+ "required": ["do", "ms"],
138
+ "properties": {
139
+ "do": { "$ref": "#/$defs/node" },
140
+ "ms": {
141
+ "type": "integer",
142
+ "minimum": 1
143
+ }
144
+ }
145
+ },
146
+ "compose_node_config": {
147
+ "type": "object",
148
+ "required": ["name", "do"],
149
+ "properties": {
150
+ "name": {
151
+ "type": "string",
152
+ "minLength": 1
153
+ },
154
+ "do": { "$ref": "#/$defs/node" }
155
+ }
156
+ },
157
+ "loop_config": {
158
+ "type": "object",
159
+ "required": ["body", "max_rounds"],
160
+ "properties": {
161
+ "name": {
162
+ "type": "string",
163
+ "minLength": 1
164
+ },
165
+ "init": { "type": "string" },
166
+ "body": { "$ref": "#/$defs/node" },
167
+ "guard": { "$ref": "#/$defs/node" },
168
+ "finish": { "type": "string" },
169
+ "max_rounds": {
170
+ "type": "integer",
171
+ "minimum": 1
172
+ }
173
+ }
174
+ },
175
+ "adversarial_config": {
176
+ "type": "object",
177
+ "required": [
178
+ "build",
179
+ "critique",
180
+ "accept",
181
+ "max_rounds"
182
+ ],
183
+ "properties": {
184
+ "build": { "$ref": "#/$defs/node" },
185
+ "critique": { "$ref": "#/$defs/node" },
186
+ "accept": { "type": "string" },
187
+ "max_rounds": {
188
+ "type": "integer",
189
+ "minimum": 1
190
+ }
191
+ }
192
+ },
193
+ "ensemble_config": {
194
+ "type": "object",
195
+ "required": ["members", "score"],
196
+ "properties": {
197
+ "members": {
198
+ "type": "object",
199
+ "additionalProperties": { "$ref": "#/$defs/node" }
200
+ },
201
+ "score": { "type": "string" },
202
+ "select": {
203
+ "type": "string",
204
+ "enum": ["max", "min"]
205
+ }
206
+ }
207
+ },
208
+ "tournament_config": {
209
+ "type": "object",
210
+ "required": ["members", "compare"],
211
+ "properties": {
212
+ "members": {
213
+ "type": "object",
214
+ "additionalProperties": { "$ref": "#/$defs/node" }
215
+ },
216
+ "compare": { "type": "string" }
217
+ }
218
+ },
219
+ "consensus_config": {
220
+ "type": "object",
221
+ "required": [
222
+ "members",
223
+ "agree",
224
+ "max_rounds"
225
+ ],
226
+ "properties": {
227
+ "members": {
228
+ "type": "object",
229
+ "additionalProperties": { "$ref": "#/$defs/node" }
230
+ },
231
+ "agree": { "type": "string" },
232
+ "max_rounds": {
233
+ "type": "integer",
234
+ "minimum": 1
235
+ }
236
+ }
237
+ },
238
+ "checkpoint_config": {
239
+ "type": "object",
240
+ "required": ["do", "key"],
241
+ "properties": {
242
+ "do": { "$ref": "#/$defs/node" },
243
+ "key": { "type": "string" }
244
+ }
245
+ },
246
+ "suspend_config": {
247
+ "type": "object",
248
+ "required": [
249
+ "id",
250
+ "on",
251
+ "resume_schema",
252
+ "combine"
253
+ ],
254
+ "properties": {
255
+ "id": { "type": "string" },
256
+ "on": { "type": "string" },
257
+ "resume_schema": { "type": "string" },
258
+ "combine": { "type": "string" }
259
+ }
260
+ },
261
+ "scope_config": {
262
+ "type": "array",
263
+ "items": { "$ref": "#/$defs/scope_entry" }
264
+ },
265
+ "scope_entry": {
266
+ "type": "object",
267
+ "oneOf": [{
268
+ "type": "object",
269
+ "required": ["stash", "do"],
270
+ "properties": {
271
+ "stash": { "type": "string" },
272
+ "do": { "$ref": "#/$defs/node" }
273
+ }
274
+ }, {
275
+ "type": "object",
276
+ "required": ["use", "do"],
277
+ "properties": {
278
+ "use": {
279
+ "type": "array",
280
+ "items": { "type": "string" }
281
+ },
282
+ "do": { "$ref": "#/$defs/node" }
283
+ }
284
+ }]
285
+ }
286
+ }
287
+ };
288
+ //#endregion
289
+ //#region src/core/cleanup.ts
290
+ const HANDLER_TIMEOUT_MS = 5e3;
291
+ function create_cleanup_registry(trajectory) {
292
+ const handlers = [];
293
+ let ran = false;
294
+ function register(fn) {
295
+ if (ran) {
296
+ trajectory.record({ kind: "cleanup_registered_after_flush" });
297
+ return;
298
+ }
299
+ handlers.push(fn);
300
+ }
301
+ async function run_all() {
302
+ if (ran) return;
303
+ ran = true;
304
+ for (let i = handlers.length - 1; i >= 0; i -= 1) {
305
+ const fn = handlers[i];
306
+ if (!fn) continue;
307
+ await run_one(fn, trajectory);
308
+ }
309
+ }
310
+ return {
311
+ register,
312
+ run_all
313
+ };
314
+ }
315
+ async function run_one(fn, trajectory) {
316
+ let timeout_id = null;
317
+ try {
318
+ await new Promise((resolve) => {
319
+ timeout_id = setTimeout(() => {
320
+ trajectory.record({
321
+ kind: "cleanup_timeout",
322
+ timeout_ms: HANDLER_TIMEOUT_MS
323
+ });
324
+ resolve();
325
+ }, HANDLER_TIMEOUT_MS);
326
+ Promise.resolve().then(() => fn()).then(() => {
327
+ if (timeout_id) clearTimeout(timeout_id);
328
+ resolve();
329
+ }, (err) => {
330
+ if (timeout_id) clearTimeout(timeout_id);
331
+ trajectory.record({
332
+ kind: "cleanup_error",
333
+ error: err instanceof Error ? err.message : String(err)
334
+ });
335
+ resolve();
336
+ });
337
+ });
338
+ } finally {
339
+ if (timeout_id) clearTimeout(timeout_id);
340
+ }
341
+ }
342
+ //#endregion
343
+ //#region src/core/errors.ts
344
+ /**
345
+ * Typed errors for the composition layer.
346
+ *
347
+ * This is the only source file in packages/core/src/ that uses the `class`
348
+ * keyword. `Error` is a built-in and `instanceof` branching is how composers
349
+ * like `retry` and `fallback` distinguish failure modes. See constraints.md §2.
350
+ */
351
+ var timeout_error = class extends Error {
352
+ kind = "timeout_error";
353
+ timeout_ms;
354
+ constructor(message, timeout_ms) {
355
+ super(message);
356
+ this.name = "timeout_error";
357
+ this.timeout_ms = timeout_ms;
358
+ }
359
+ };
360
+ var suspended_error = class extends Error {
361
+ kind = "suspended_error";
362
+ suspend_id;
363
+ payload;
364
+ constructor(suspend_id, payload, message) {
365
+ super(message ?? `suspended at ${suspend_id}`);
366
+ this.name = "suspended_error";
367
+ this.suspend_id = suspend_id;
368
+ this.payload = payload;
369
+ }
370
+ };
371
+ var resume_validation_error = class extends Error {
372
+ kind = "resume_validation_error";
373
+ issues;
374
+ constructor(message, issues) {
375
+ super(message);
376
+ this.name = "resume_validation_error";
377
+ this.issues = issues;
378
+ }
379
+ };
380
+ var describe_cycle_error = class extends Error {
381
+ kind = "describe_cycle_error";
382
+ step_id;
383
+ constructor(step_id, message) {
384
+ super(message ?? `describe: cycle detected at step id: ${step_id}`);
385
+ this.name = "describe_cycle_error";
386
+ this.step_id = step_id;
387
+ }
388
+ };
389
+ var aborted_error = class extends Error {
390
+ kind = "aborted_error";
391
+ reason;
392
+ step_index;
393
+ tool_call_in_flight;
394
+ constructor(message = "aborted", metadata = {}) {
395
+ super(message);
396
+ this.name = "aborted_error";
397
+ if (metadata.reason !== void 0) this.reason = metadata.reason;
398
+ this.step_index = metadata.step_index ?? 0;
399
+ if (metadata.tool_call_in_flight !== void 0) this.tool_call_in_flight = metadata.tool_call_in_flight;
400
+ }
401
+ };
402
+ /**
403
+ * Control-flow signals are not application failures. `suspended_error` is a
404
+ * human-approval gate pausing the run for later resume; `aborted_error` is
405
+ * cancellation. Resilience composers (`retry`, `fallback`) must rethrow these
406
+ * rather than retry past a suspend or run a backup under an aborted context.
407
+ *
408
+ * Kept internal to core: not re-exported by index.ts, so it does not
409
+ * widen the public surface.
410
+ */
411
+ function is_control_flow_error(err) {
412
+ return err instanceof suspended_error || err instanceof aborted_error;
413
+ }
414
+ //#endregion
415
+ //#region src/core/streaming.ts
416
+ const STREAMING_HIGH_WATER_MARK = 1e4;
417
+ function create_streaming_channel(base, high_water_mark = STREAMING_HIGH_WATER_MARK) {
418
+ const buffer = [];
419
+ let dropped = 0;
420
+ let closed = false;
421
+ let marker_emitted = false;
422
+ let waiter = null;
423
+ function enqueue(event) {
424
+ if (closed) return;
425
+ if (waiter) {
426
+ const resolve = waiter;
427
+ waiter = null;
428
+ resolve({
429
+ value: event,
430
+ done: false
431
+ });
432
+ return;
433
+ }
434
+ if (buffer.length >= high_water_mark) {
435
+ buffer.shift();
436
+ dropped += 1;
437
+ return;
438
+ }
439
+ buffer.push(event);
440
+ }
441
+ function close() {
442
+ if (closed) return;
443
+ closed = true;
444
+ if (dropped > 0 && !marker_emitted) {
445
+ marker_emitted = true;
446
+ buffer.push({
447
+ kind: "events_dropped",
448
+ count: dropped
449
+ });
450
+ }
451
+ if (waiter) {
452
+ const resolve = waiter;
453
+ waiter = null;
454
+ resolve({
455
+ value: void 0,
456
+ done: true
457
+ });
458
+ }
459
+ }
460
+ return {
461
+ logger: {
462
+ record: (event) => {
463
+ base.record(event);
464
+ enqueue(event);
465
+ },
466
+ start_span: (name, meta) => {
467
+ const id = base.start_span(name, meta);
468
+ enqueue({
469
+ kind: "span_start",
470
+ span_id: id,
471
+ name,
472
+ ...meta
473
+ });
474
+ return id;
475
+ },
476
+ end_span: (id, meta) => {
477
+ base.end_span(id, meta);
478
+ enqueue({
479
+ kind: "span_end",
480
+ span_id: id,
481
+ ...meta
482
+ });
483
+ }
484
+ },
485
+ events: { [Symbol.asyncIterator]() {
486
+ return {
487
+ next() {
488
+ if (buffer.length > 0) {
489
+ const next_event = buffer.shift();
490
+ if (next_event !== void 0) return Promise.resolve({
491
+ value: next_event,
492
+ done: false
493
+ });
494
+ }
495
+ if (closed) return Promise.resolve({
496
+ value: void 0,
497
+ done: true
498
+ });
499
+ return new Promise((resolve) => {
500
+ waiter = resolve;
501
+ });
502
+ },
503
+ return() {
504
+ close();
505
+ return Promise.resolve({
506
+ value: void 0,
507
+ done: true
508
+ });
509
+ }
510
+ };
511
+ } },
512
+ close
513
+ };
514
+ }
515
+ //#endregion
516
+ //#region src/core/runner.ts
517
+ /**
518
+ * Runner.
519
+ *
520
+ * Dispatches a step to its kind-specific handler. `runner.ts` contains no
521
+ * composer-specific logic beyond a Map lookup on `step.kind`; each composer
522
+ * file registers its handler at module load via `register_kind(...)`.
523
+ *
524
+ * `run(flow, input, options?)` constructs a fresh `RunContext` per top-level
525
+ * call, installs process signal handlers (opt-out via options), forwards an
526
+ * optional caller-supplied `AbortSignal` into the run, and guarantees cleanup
527
+ * handlers execute in LIFO order on success, failure, or abort.
528
+ *
529
+ * `run.stream(flow, input, options?)` is a secondary entry point returning
530
+ * `{ events, result }`. Streaming is purely observational; the step graph is
531
+ * identical to `run(...)`.
532
+ */
533
+ const dispatch = /* @__PURE__ */ new Map();
534
+ function register_kind(kind, fn) {
535
+ dispatch.set(kind, fn);
536
+ }
537
+ /**
538
+ * Resolve the trajectory span label for a step. Prefers a non-empty
539
+ * `display_name` from `flow.config`; otherwise falls back to the supplied
540
+ * default (typically the step's `kind`).
541
+ *
542
+ * Dispatch handlers use this so that any composer carrying a user-supplied
543
+ * `name` surfaces under that label in the trajectory, while unconfigured
544
+ * composers retain their kind-based label.
545
+ */
546
+ function resolve_span_label(flow, fallback) {
547
+ const display = flow.config?.["display_name"];
548
+ return typeof display === "string" && display.length > 0 ? display : fallback;
549
+ }
550
+ /**
551
+ * Register the standard span-wrapping dispatch handler for a composer kind.
552
+ *
553
+ * Every composer wraps `flow.run` in a span identically; this centralizes that
554
+ * boilerplate and threads span parentage: the span opens with the current
555
+ * `ctx.parent_span_id` as its parent, and `flow.run` receives a child context
556
+ * whose `parent_span_id` is this span. Children dispatched from within
557
+ * (including concurrent ones under `parallel`/`map`, which spread the context)
558
+ * therefore nest correctly instead of leaving `parent_span_id` unpopulated.
559
+ */
560
+ function register_traced_kind(kind) {
561
+ register_kind(kind, async (flow, input, ctx) => {
562
+ const label = resolve_span_label(flow, kind);
563
+ const span_meta = { id: flow.id };
564
+ if (ctx.parent_span_id !== void 0) span_meta["parent_span_id"] = ctx.parent_span_id;
565
+ const span_id = ctx.trajectory.start_span(label, span_meta);
566
+ const child_ctx = {
567
+ ...ctx,
568
+ parent_span_id: span_id
569
+ };
570
+ try {
571
+ const out = await flow.run(input, child_ctx);
572
+ ctx.trajectory.end_span(span_id, { id: flow.id });
573
+ return out;
574
+ } catch (err) {
575
+ ctx.trajectory.end_span(span_id, {
576
+ id: flow.id,
577
+ error: err instanceof Error ? err.message : String(err)
578
+ });
579
+ throw err;
580
+ }
581
+ });
582
+ }
583
+ const active_runs = /* @__PURE__ */ new Set();
584
+ let signal_handler_installed = false;
585
+ let sigint_handler = null;
586
+ let sigterm_handler = null;
587
+ function ensure_signal_handlers() {
588
+ if (signal_handler_installed) return;
589
+ signal_handler_installed = true;
590
+ const abort_all = (signal_name) => () => {
591
+ for (const controller of active_runs) controller.abort(new aborted_error(`received ${signal_name}`, { reason: { signal: signal_name } }));
592
+ };
593
+ sigint_handler = abort_all("SIGINT");
594
+ sigterm_handler = abort_all("SIGTERM");
595
+ process.on("SIGINT", sigint_handler);
596
+ process.on("SIGTERM", sigterm_handler);
597
+ }
598
+ function release_signal_handlers() {
599
+ if (!signal_handler_installed) return;
600
+ if (active_runs.size > 0) return;
601
+ signal_handler_installed = false;
602
+ if (sigint_handler) process.off("SIGINT", sigint_handler);
603
+ if (sigterm_handler) process.off("SIGTERM", sigterm_handler);
604
+ sigint_handler = null;
605
+ sigterm_handler = null;
606
+ }
607
+ const noop_logger = {
608
+ record: () => {},
609
+ start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,
610
+ end_span: () => {}
611
+ };
612
+ /**
613
+ * Wrap a logger so every emitted event automatically carries `run_id` and a
614
+ * `ts` (epoch milliseconds) stamped at emission.
615
+ *
616
+ * Studios and other downstream consumers multiplex events across runs by
617
+ * `run_id` and reconstruct real timing from `ts` instead of fabricating it at
618
+ * ingest. Either field already present on an event or its meta is preserved;
619
+ * we never overwrite a caller-supplied value.
620
+ */
621
+ function decorate_logger(inner, run_id) {
622
+ const stamp_meta = (meta) => {
623
+ const out = { ...meta };
624
+ if (!("run_id" in out)) out["run_id"] = run_id;
625
+ if (!("ts" in out)) out["ts"] = Date.now();
626
+ return out;
627
+ };
628
+ return {
629
+ record: (event) => {
630
+ if ("run_id" in event && "ts" in event) {
631
+ inner.record(event);
632
+ return;
633
+ }
634
+ const extra = {};
635
+ if (!("run_id" in event)) extra["run_id"] = run_id;
636
+ if (!("ts" in event)) extra["ts"] = Date.now();
637
+ inner.record({
638
+ ...event,
639
+ ...extra
640
+ });
641
+ },
642
+ start_span: (name, meta) => inner.start_span(name, stamp_meta(meta)),
643
+ end_span: (id, meta) => {
644
+ inner.end_span(id, stamp_meta(meta));
645
+ }
646
+ };
647
+ }
648
+ async function dispatch_step(flow, input, ctx) {
649
+ const handler = dispatch.get(flow.kind);
650
+ if (!handler) throw new Error(`unknown step kind: ${flow.kind} (step id: ${flow.id})`);
651
+ try {
652
+ return await handler(flow, input, ctx);
653
+ } catch (err) {
654
+ prepend_path(err, flow.id);
655
+ throw err;
656
+ }
657
+ }
658
+ function prepend_path(err, id) {
659
+ if (err === null || typeof err !== "object") return;
660
+ const existing = Reflect.get(err, "path");
661
+ const next = Array.isArray(existing) ? [id, ...existing.filter((v) => typeof v === "string")] : [id];
662
+ Reflect.set(err, "path", next);
663
+ }
664
+ /**
665
+ * Throw the abort reason if the context has been cancelled. Composers that
666
+ * iterate over children (`sequence`, `scope`, `loop`) call this between steps
667
+ * so a pending abort is honored before the next child starts, not only when a
668
+ * downstream dispatch happens to observe it.
669
+ */
670
+ function throw_if_aborted(ctx) {
671
+ if (!ctx.abort.aborted) return;
672
+ const reason = ctx.abort.reason;
673
+ throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
674
+ }
675
+ /**
676
+ * Forward a caller-owned AbortSignal into the run's internal controller and
677
+ * return an unlink function. The reason is preserved so the original
678
+ * cancellation cause propagates out of `run`. The listener is `once` and the
679
+ * returned unlink is called when the run settles, so a long-lived host (an MCP
680
+ * server, an HTTP worker) firing many short runs against one external signal
681
+ * does not accumulate listeners.
682
+ */
683
+ function link_external_abort(controller, external) {
684
+ if (external === void 0) return () => {};
685
+ if (external.aborted) {
686
+ controller.abort(external.reason);
687
+ return () => {};
688
+ }
689
+ const on_abort = () => {
690
+ controller.abort(external.reason);
691
+ };
692
+ external.addEventListener("abort", on_abort, { once: true });
693
+ return () => {
694
+ external.removeEventListener("abort", on_abort);
695
+ };
696
+ }
697
+ function start_run(flow, input, options, high_water_mark) {
698
+ const install_signal_handlers = options.install_signal_handlers !== false;
699
+ const base_logger = options.trajectory ?? noop_logger;
700
+ const streaming = high_water_mark !== null;
701
+ const controller = new AbortController();
702
+ const unlink_abort = link_external_abort(controller, options.abort);
703
+ const run_id = randomUUID();
704
+ let stream_events = empty_async_iterable();
705
+ let close_stream = null;
706
+ let inner = base_logger;
707
+ if (streaming) {
708
+ const channel = create_streaming_channel(base_logger, high_water_mark);
709
+ inner = channel.logger;
710
+ stream_events = channel.events;
711
+ close_stream = channel.close;
712
+ }
713
+ const logger = decorate_logger(inner, run_id);
714
+ const cleanup = create_cleanup_registry(logger);
715
+ const ctx = {
716
+ run_id,
717
+ trajectory: logger,
718
+ state: /* @__PURE__ */ new Map(),
719
+ abort: controller.signal,
720
+ emit: (event) => {
721
+ logger.record({
722
+ ...event,
723
+ kind: "emit"
724
+ });
725
+ },
726
+ on_cleanup: (fn) => {
727
+ cleanup.register(fn);
728
+ },
729
+ checkpoint_store: options.checkpoint_store,
730
+ resume_data: options.resume_data,
731
+ streaming
732
+ };
733
+ active_runs.add(controller);
734
+ if (install_signal_handlers) ensure_signal_handlers();
735
+ const result = (async () => {
736
+ try {
737
+ throw_if_aborted(ctx);
738
+ return await dispatch_step(flow, input, ctx);
739
+ } catch (err) {
740
+ if (controller.signal.aborted && !(err instanceof aborted_error)) {
741
+ const reason = controller.signal.reason;
742
+ if (reason instanceof aborted_error) throw reason;
743
+ }
744
+ throw err;
745
+ } finally {
746
+ try {
747
+ await cleanup.run_all();
748
+ } finally {
749
+ unlink_abort();
750
+ active_runs.delete(controller);
751
+ release_signal_handlers();
752
+ if (close_stream) close_stream();
753
+ }
754
+ }
755
+ })();
756
+ return {
757
+ events: stream_events,
758
+ result
759
+ };
760
+ }
761
+ function empty_async_iterable() {
762
+ return { [Symbol.asyncIterator]() {
763
+ return { next: () => Promise.resolve({
764
+ value: void 0,
765
+ done: true
766
+ }) };
767
+ } };
768
+ }
769
+ async function run_impl(flow, input, options = {}) {
770
+ const { result } = start_run(flow, input, options, null);
771
+ return result;
772
+ }
773
+ function run_stream(flow, input, options = {}) {
774
+ const { events, result } = start_run(flow, input, options, STREAMING_HIGH_WATER_MARK);
775
+ return {
776
+ events,
777
+ result
778
+ };
779
+ }
780
+ const run = Object.assign(run_impl, { stream: run_stream });
781
+ //#endregion
782
+ //#region src/core/step.ts
783
+ /**
784
+ * step() factory.
785
+ *
786
+ * Three forms:
787
+ * step(id, fn) — named step. id is rendered in trajectory spans and describe().
788
+ * step(id, fn, meta) — named step with optional human-readable metadata for studio,
789
+ * codegen, and similar consumers. `meta` is purely descriptive
790
+ * and never affects runtime semantics.
791
+ * step(fn) — anonymous step. id is `anon_<counter>`; cannot be checkpointed.
792
+ *
793
+ * Anonymous steps carry an internal `anonymous: true` flag so checkpoint can
794
+ * reject them synchronously at flow construction time (spec.md §9 F6 / §7 invariant 8).
795
+ */
796
+ let anon_counter = 0;
797
+ function next_anon_id() {
798
+ anon_counter += 1;
799
+ return `anon_${anon_counter}`;
800
+ }
801
+ function step(id_or_fn, maybe_fn, meta) {
802
+ if (typeof id_or_fn === "function") return {
803
+ id: next_anon_id(),
804
+ kind: "step",
805
+ run: id_or_fn,
806
+ anonymous: true
807
+ };
808
+ if (typeof maybe_fn !== "function") throw new TypeError("step(id, fn): fn must be a function");
809
+ if (meta) return {
810
+ id: id_or_fn,
811
+ kind: "step",
812
+ run: maybe_fn,
813
+ meta
814
+ };
815
+ return {
816
+ id: id_or_fn,
817
+ kind: "step",
818
+ run: maybe_fn
819
+ };
820
+ }
821
+ register_traced_kind("step");
822
+ //#endregion
823
+ //#region src/core/describe.ts
824
+ /**
825
+ * describe(step) and describe.json(step) — composition introspection.
826
+ *
827
+ * `describe(step)` is the text-tree renderer. Multi-line string with
828
+ * hierarchical indentation. Function values render as `<fn>` (or
829
+ * `<fn:name>` when the function has a non-empty `name`); zod schemas
830
+ * render as `<schema>`.
831
+ *
832
+ * `describe.json(step)` returns a `FlowNode` tree (kind, id, config, children)
833
+ * for tooling (Studio UI, Mermaid renderers, diff tools). Function values
834
+ * serialize as `{ kind: '<fn>', name? }` and schemas as `{ kind: '<schema>' }`.
835
+ *
836
+ * Both forms detect cycles. Under the default (loose) mode, back-references
837
+ * render as `<cycle>(id)` in text and `{ kind: '<cycle>', id }` in JSON. Under
838
+ * `{ strict: true }`, cycles throw `describe_cycle_error`.
839
+ */
840
+ const INDENT = " ";
841
+ function describe_text(root, options) {
842
+ const lines = [];
843
+ const strict = Boolean(options?.strict);
844
+ render_text(root, 0, lines, /* @__PURE__ */ new Set(), strict);
845
+ return lines.join("\n");
846
+ }
847
+ function describe_json(root, options) {
848
+ const strict = Boolean(options?.strict);
849
+ return render_json(root, /* @__PURE__ */ new Set(), strict);
850
+ }
851
+ const describe = Object.assign(describe_text, { json: describe_json });
852
+ function render_text(node, depth, lines, path, strict) {
853
+ const prefix = INDENT.repeat(depth);
854
+ if (path.has(node)) {
855
+ if (strict) throw new describe_cycle_error(node.id);
856
+ lines.push(`${prefix}<cycle>(${node.id})`);
857
+ return;
858
+ }
859
+ path.add(node);
860
+ try {
861
+ const display = node.config?.["display_name"];
862
+ const label = typeof display === "string" && display.length > 0 ? display : node.kind;
863
+ lines.push(`${prefix}${label}(${node.id})`);
864
+ if (node.config) for (const [key, value] of Object.entries(node.config)) {
865
+ if (key === "display_name") continue;
866
+ lines.push(`${prefix}${INDENT}${key}: ${render_value_text(value, path, strict)}`);
867
+ }
868
+ if (node.children && node.children.length > 0) for (const child of node.children) render_text(child, depth + 1, lines, path, strict);
869
+ } finally {
870
+ path.delete(node);
871
+ }
872
+ }
873
+ function render_value_text(value, path, strict) {
874
+ if (typeof value === "function") {
875
+ const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
876
+ return name ? `<fn:${name}>` : "<fn>";
877
+ }
878
+ if (value === null) return "null";
879
+ if (value === void 0) return "undefined";
880
+ if (is_zod_schema(value)) return "<schema>";
881
+ if (is_step$1(value)) {
882
+ if (path.has(value)) {
883
+ if (strict) throw new describe_cycle_error(value.id);
884
+ return `<cycle>(${value.id})`;
885
+ }
886
+ return `${value.kind}(${value.id})`;
887
+ }
888
+ if (Array.isArray(value)) return `[${value.map((item) => render_value_text(item, path, strict)).join(", ")}]`;
889
+ if (typeof value === "object") return `{ ${Object.entries({ ...value }).map(([k, v]) => `${k}: ${render_value_text(v, path, strict)}`).join(", ")} }`;
890
+ if (typeof value === "string") return JSON.stringify(value);
891
+ if (typeof value === "bigint") return `${value.toString()}n`;
892
+ if (typeof value === "symbol") return value.toString();
893
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
894
+ return JSON.stringify(value);
895
+ }
896
+ function render_json(node, path, strict) {
897
+ if (path.has(node)) {
898
+ if (strict) throw new describe_cycle_error(node.id);
899
+ return {
900
+ kind: "<cycle>",
901
+ id: node.id
902
+ };
903
+ }
904
+ path.add(node);
905
+ try {
906
+ const result = {
907
+ kind: node.kind,
908
+ id: node.id
909
+ };
910
+ if (node.config) {
911
+ const config = {};
912
+ for (const [key, value] of Object.entries(node.config)) config[key] = render_value_json(value, path, strict);
913
+ result.config = config;
914
+ }
915
+ if (node.children && node.children.length > 0) result.children = node.children.map((child) => render_json(child, path, strict));
916
+ if (node.meta) result.meta = node.meta;
917
+ return result;
918
+ } finally {
919
+ path.delete(node);
920
+ }
921
+ }
922
+ function render_value_json(value, path, strict) {
923
+ if (typeof value === "function") {
924
+ const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
925
+ return name ? {
926
+ kind: "<fn>",
927
+ name
928
+ } : { kind: "<fn>" };
929
+ }
930
+ if (value === null) return null;
931
+ if (value === void 0) return null;
932
+ if (is_zod_schema(value)) return { kind: "<schema>" };
933
+ if (is_step$1(value)) {
934
+ if (path.has(value)) {
935
+ if (strict) throw new describe_cycle_error(value.id);
936
+ return {
937
+ kind: "<cycle>",
938
+ id: value.id
939
+ };
940
+ }
941
+ return {
942
+ kind: value.kind,
943
+ id: value.id
944
+ };
945
+ }
946
+ if (Array.isArray(value)) return value.map((item) => render_value_json(item, path, strict));
947
+ if (typeof value === "object") {
948
+ const out = {};
949
+ for (const [k, v] of Object.entries({ ...value })) out[k] = render_value_json(v, path, strict);
950
+ return out;
951
+ }
952
+ if (typeof value === "string") return value;
953
+ if (typeof value === "number" || typeof value === "boolean") return value;
954
+ if (typeof value === "bigint") return `${value.toString()}n`;
955
+ if (typeof value === "symbol") return value.toString();
956
+ return JSON.stringify(value);
957
+ }
958
+ function is_step$1(value) {
959
+ if (typeof value !== "object" || value === null) return false;
960
+ if (!("id" in value) || !("kind" in value) || !("run" in value)) return false;
961
+ const { id, kind, run } = value;
962
+ return typeof id === "string" && typeof kind === "string" && typeof run === "function";
963
+ }
964
+ function is_zod_schema(value) {
965
+ if (typeof value !== "object" || value === null) return false;
966
+ return "_zod" in value || "_def" in value;
967
+ }
968
+ //#endregion
969
+ //#region src/core/sequence.ts
970
+ /**
971
+ * sequence: chain child outputs.
972
+ *
973
+ * `sequence([a, b, c])` runs a, b, c in declared order. The input to sequence
974
+ * is passed to the first child; each subsequent child receives the previous
975
+ * child's output. The composer returns the last child's output.
976
+ *
977
+ * See spec.md §5.2 and §6.1.
978
+ */
979
+ let sequence_counter = 0;
980
+ function next_id$10() {
981
+ sequence_counter += 1;
982
+ return `sequence_${sequence_counter}`;
983
+ }
984
+ function sequence(children, options) {
985
+ const id = next_id$10();
986
+ const children_ref = children;
987
+ const run_fn = async (input, ctx) => {
988
+ let acc = input;
989
+ for (const child of children_ref) {
990
+ throw_if_aborted(ctx);
991
+ acc = await dispatch_step(child, acc, ctx);
992
+ }
993
+ return acc;
994
+ };
995
+ const config_meta = options?.name === void 0 ? void 0 : { display_name: options.name };
996
+ return {
997
+ id,
998
+ kind: "sequence",
999
+ children,
1000
+ ...config_meta ? { config: config_meta } : {},
1001
+ run: run_fn
1002
+ };
1003
+ }
1004
+ register_traced_kind("sequence");
1005
+ //#endregion
1006
+ //#region src/core/parallel.ts
1007
+ /**
1008
+ * parallel: concurrent execution of named children.
1009
+ *
1010
+ * `parallel({ a, b })` runs a and b concurrently with the same input. Output
1011
+ * is an object keyed by the child name; all children must accept the same
1012
+ * input type.
1013
+ *
1014
+ * Cancellation (constraints.md §5.1, spec.md §6.8): each child runs with a
1015
+ * composed abort signal — `AbortSignal.any([ctx.abort, child_local])`. On
1016
+ * abort the composer awaits all in-flight children (success, failure, or
1017
+ * aborted) before rethrowing `ctx.abort.reason`. This matches the
1018
+ * "agent-pattern" composer contract in spec.md §6.8.
1019
+ *
1020
+ * When several children fail, a `suspended_error` is preferred over an
1021
+ * application error so a human-approval gate inside a branch stays resumable
1022
+ * rather than being masked by a sibling's failure. Otherwise the first error
1023
+ * in declared order propagates.
1024
+ */
1025
+ let parallel_counter = 0;
1026
+ function next_id$9() {
1027
+ parallel_counter += 1;
1028
+ return `parallel_${parallel_counter}`;
1029
+ }
1030
+ function parallel(members, options) {
1031
+ const id = next_id$9();
1032
+ const entries = Object.entries(members);
1033
+ const child_list = entries.map(([, s]) => s);
1034
+ const keys = entries.map(([k]) => k);
1035
+ const run_fn = async (input, ctx) => {
1036
+ const controllers = entries.map(() => new AbortController());
1037
+ const on_parent_abort = () => {
1038
+ for (const c of controllers) c.abort(ctx.abort.reason);
1039
+ };
1040
+ if (ctx.abort.aborted) on_parent_abort();
1041
+ else ctx.abort.addEventListener("abort", on_parent_abort, { once: true });
1042
+ try {
1043
+ const settled = await Promise.all(entries.map(async ([key, child], idx) => {
1044
+ const local = controllers[idx];
1045
+ if (!local) throw new Error("parallel: missing controller");
1046
+ const composed = AbortSignal.any([ctx.abort, local.signal]);
1047
+ const child_ctx = {
1048
+ ...ctx,
1049
+ abort: composed
1050
+ };
1051
+ try {
1052
+ return {
1053
+ status: "ok",
1054
+ key,
1055
+ value: await dispatch_step(child, input, child_ctx)
1056
+ };
1057
+ } catch (err) {
1058
+ return {
1059
+ status: "err",
1060
+ key,
1061
+ err
1062
+ };
1063
+ }
1064
+ }));
1065
+ if (ctx.abort.aborted) {
1066
+ const reason = ctx.abort.reason;
1067
+ throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1068
+ }
1069
+ let first_err;
1070
+ let has_err = false;
1071
+ let suspended;
1072
+ let has_suspended = false;
1073
+ for (const s of settled) {
1074
+ if (s.status !== "err") continue;
1075
+ if (!has_err) {
1076
+ first_err = s.err;
1077
+ has_err = true;
1078
+ }
1079
+ if (!has_suspended && s.err instanceof suspended_error) {
1080
+ suspended = s.err;
1081
+ has_suspended = true;
1082
+ }
1083
+ }
1084
+ if (has_suspended) throw suspended;
1085
+ if (has_err) throw first_err;
1086
+ const out = {};
1087
+ for (const s of settled) if (s.status === "ok") out[s.key] = s.value;
1088
+ return out;
1089
+ } finally {
1090
+ ctx.abort.removeEventListener("abort", on_parent_abort);
1091
+ }
1092
+ };
1093
+ const config_meta = { keys };
1094
+ if (options?.name !== void 0) config_meta["display_name"] = options.name;
1095
+ return {
1096
+ id,
1097
+ kind: "parallel",
1098
+ children: child_list,
1099
+ config: config_meta,
1100
+ run: run_fn
1101
+ };
1102
+ }
1103
+ register_traced_kind("parallel");
1104
+ //#endregion
1105
+ //#region src/core/branch.ts
1106
+ /**
1107
+ * branch: conditional routing.
1108
+ *
1109
+ * `branch({ when, then, otherwise })` evaluates `when(input)`; if truthy, runs
1110
+ * `then`, else runs `otherwise`. Both branches must return the same output
1111
+ * type.
1112
+ *
1113
+ * See spec.md §5.4.
1114
+ */
1115
+ let branch_counter = 0;
1116
+ function next_id$8() {
1117
+ branch_counter += 1;
1118
+ return `branch_${branch_counter}`;
1119
+ }
1120
+ function branch(config) {
1121
+ const id = next_id$8();
1122
+ const { when, then: then_step, otherwise: otherwise_step, name } = config;
1123
+ const run_fn = async (input, ctx) => {
1124
+ return dispatch_step(await when(input) ? then_step : otherwise_step, input, ctx);
1125
+ };
1126
+ const config_meta = {
1127
+ when,
1128
+ then: then_step,
1129
+ otherwise: otherwise_step
1130
+ };
1131
+ if (name !== void 0) config_meta["display_name"] = name;
1132
+ return {
1133
+ id,
1134
+ kind: "branch",
1135
+ children: [then_step, otherwise_step],
1136
+ config: config_meta,
1137
+ run: run_fn
1138
+ };
1139
+ }
1140
+ register_traced_kind("branch");
1141
+ //#endregion
1142
+ //#region src/core/map.ts
1143
+ /**
1144
+ * map: per-item execution.
1145
+ *
1146
+ * `map({ items, do, concurrency? })` extracts an array via `items(input)`,
1147
+ * runs `do` once per element, returns an array in the same order as inputs.
1148
+ * `concurrency` caps simultaneous in-flight items; omitted means full
1149
+ * parallelism.
1150
+ *
1151
+ * Cancellation (constraints.md §5.1, spec.md §6.8): each in-flight item runs
1152
+ * with a composed abort signal via `AbortSignal.any([ctx.abort, child_local])`.
1153
+ * On abort no new items start. The composer awaits all in-flight items before
1154
+ * rethrowing `ctx.abort.reason`.
1155
+ */
1156
+ let map_counter = 0;
1157
+ function next_id$7() {
1158
+ map_counter += 1;
1159
+ return `map_${map_counter}`;
1160
+ }
1161
+ function map(config) {
1162
+ const id = next_id$7();
1163
+ const { items, do: per_item, concurrency, name } = config;
1164
+ const run_fn = async (input, ctx) => {
1165
+ const list = await items(input);
1166
+ if (list.length === 0) return [];
1167
+ const results = Array.from({ length: list.length });
1168
+ const limit = concurrency === void 0 ? list.length : Math.max(1, concurrency);
1169
+ const controllers = [];
1170
+ const on_parent_abort = () => {
1171
+ for (const c of controllers) c.abort(ctx.abort.reason);
1172
+ };
1173
+ if (ctx.abort.aborted) on_parent_abort();
1174
+ else ctx.abort.addEventListener("abort", on_parent_abort, { once: true });
1175
+ let cursor = 0;
1176
+ let worker_error = void 0;
1177
+ const run_one = async (idx) => {
1178
+ const local = new AbortController();
1179
+ controllers.push(local);
1180
+ const composed = AbortSignal.any([ctx.abort, local.signal]);
1181
+ const child_ctx = {
1182
+ ...ctx,
1183
+ abort: composed
1184
+ };
1185
+ const item_value = list[idx];
1186
+ results[idx] = await dispatch_step(per_item, item_value, child_ctx);
1187
+ };
1188
+ const worker = async () => {
1189
+ while (true) {
1190
+ if (ctx.abort.aborted || worker_error !== void 0) return;
1191
+ const idx = cursor;
1192
+ cursor += 1;
1193
+ if (idx >= list.length) return;
1194
+ try {
1195
+ await run_one(idx);
1196
+ } catch (err) {
1197
+ if (worker_error === void 0) worker_error = err;
1198
+ return;
1199
+ }
1200
+ }
1201
+ };
1202
+ try {
1203
+ const worker_count = Math.min(limit, list.length);
1204
+ const workers = [];
1205
+ for (let w = 0; w < worker_count; w += 1) workers.push(worker());
1206
+ await Promise.all(workers);
1207
+ if (ctx.abort.aborted) {
1208
+ const reason = ctx.abort.reason;
1209
+ throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1210
+ }
1211
+ if (worker_error !== void 0) throw worker_error;
1212
+ return results;
1213
+ } finally {
1214
+ ctx.abort.removeEventListener("abort", on_parent_abort);
1215
+ }
1216
+ };
1217
+ const config_meta = { items };
1218
+ if (concurrency !== void 0) config_meta["concurrency"] = concurrency;
1219
+ if (name !== void 0) config_meta["display_name"] = name;
1220
+ return {
1221
+ id,
1222
+ kind: "map",
1223
+ children: [per_item],
1224
+ config: config_meta,
1225
+ run: run_fn
1226
+ };
1227
+ }
1228
+ register_traced_kind("map");
1229
+ //#endregion
1230
+ //#region src/core/pipe.ts
1231
+ /**
1232
+ * pipe: transform output.
1233
+ *
1234
+ * `pipe(inner, fn)` runs `inner`, passes its output to `fn`, returns `fn`'s
1235
+ * result. Use for shape adaptation when composing heterogeneous steps.
1236
+ *
1237
+ * See spec.md §5.6.
1238
+ */
1239
+ let pipe_counter = 0;
1240
+ function next_id$6() {
1241
+ pipe_counter += 1;
1242
+ return `pipe_${pipe_counter}`;
1243
+ }
1244
+ function pipe(inner, fn, options) {
1245
+ const id = next_id$6();
1246
+ const run_fn = async (input, ctx) => {
1247
+ return fn(await dispatch_step(inner, input, ctx));
1248
+ };
1249
+ const config_meta = { fn };
1250
+ if (options?.name !== void 0) config_meta["display_name"] = options.name;
1251
+ return {
1252
+ id,
1253
+ kind: "pipe",
1254
+ children: [inner],
1255
+ config: config_meta,
1256
+ run: run_fn
1257
+ };
1258
+ }
1259
+ register_traced_kind("pipe");
1260
+ //#endregion
1261
+ //#region src/core/retry.ts
1262
+ /**
1263
+ * retry: re-run on failure.
1264
+ *
1265
+ * `retry(inner, { max_attempts, backoff_ms?, on_error? })` runs `inner`. If it
1266
+ * throws an application error, retries up to `max_attempts - 1` more times with
1267
+ * exponential backoff (`backoff_ms * 2^(attempt-1)`). `on_error` is called on
1268
+ * every such failure. The last error is rethrown if all attempts fail.
1269
+ *
1270
+ * Control-flow signals (`suspended_error`, `aborted_error`) are not failures:
1271
+ * they propagate immediately without consuming an attempt, firing `on_error`,
1272
+ * or scheduling a backoff. A suspend's `on()` side effect therefore runs once
1273
+ * per run, not once per attempt.
1274
+ *
1275
+ * Cancellation / cleanup (constraints.md §5.2, spec.md §6.8): cleanup handlers
1276
+ * registered by the inner step accumulate across attempts. The parent
1277
+ * `ctx.abort` is honored between attempts — a pending abort short-circuits
1278
+ * the backoff and propagates. See spec.md §5.7 and §9 F11.
1279
+ */
1280
+ const DEFAULT_BACKOFF_MS = 1e3;
1281
+ let retry_counter = 0;
1282
+ function next_id$5() {
1283
+ retry_counter += 1;
1284
+ return `retry_${retry_counter}`;
1285
+ }
1286
+ async function abortable_wait(ms, ctx) {
1287
+ if (ms <= 0) return;
1288
+ await new Promise((resolve, reject) => {
1289
+ if (ctx.abort.aborted) {
1290
+ const reason = ctx.abort.reason;
1291
+ reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
1292
+ return;
1293
+ }
1294
+ const timer = setTimeout(() => {
1295
+ ctx.abort.removeEventListener("abort", on_abort);
1296
+ resolve();
1297
+ }, ms);
1298
+ const on_abort = () => {
1299
+ clearTimeout(timer);
1300
+ const reason = ctx.abort.reason;
1301
+ reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
1302
+ };
1303
+ ctx.abort.addEventListener("abort", on_abort, { once: true });
1304
+ });
1305
+ }
1306
+ function retry(inner, config) {
1307
+ const id = next_id$5();
1308
+ const max_attempts = Math.max(1, Math.floor(config.max_attempts));
1309
+ const backoff_ms = config.backoff_ms ?? DEFAULT_BACKOFF_MS;
1310
+ const on_error = config.on_error;
1311
+ const run_fn = async (input, ctx) => {
1312
+ let last_err = void 0;
1313
+ for (let attempt = 1; attempt <= max_attempts; attempt += 1) {
1314
+ if (ctx.abort.aborted) {
1315
+ const reason = ctx.abort.reason;
1316
+ throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1317
+ }
1318
+ try {
1319
+ return await dispatch_step(inner, input, ctx);
1320
+ } catch (err) {
1321
+ if (is_control_flow_error(err)) throw err;
1322
+ last_err = err;
1323
+ if (on_error) on_error(err, attempt);
1324
+ if (attempt >= max_attempts) break;
1325
+ await abortable_wait(backoff_ms * 2 ** (attempt - 1), ctx);
1326
+ }
1327
+ }
1328
+ throw last_err;
1329
+ };
1330
+ const config_meta = {
1331
+ max_attempts,
1332
+ backoff_ms
1333
+ };
1334
+ if (on_error) config_meta["on_error"] = on_error;
1335
+ if (config.name !== void 0) config_meta["display_name"] = config.name;
1336
+ return {
1337
+ id,
1338
+ kind: "retry",
1339
+ children: [inner],
1340
+ config: config_meta,
1341
+ run: run_fn
1342
+ };
1343
+ }
1344
+ register_traced_kind("retry");
1345
+ //#endregion
1346
+ //#region src/core/fallback.ts
1347
+ /**
1348
+ * fallback: primary-or-backup.
1349
+ *
1350
+ * `fallback(primary, backup)` runs `primary`. If it throws an application
1351
+ * error, runs `backup` with the same input. If `backup` also throws, the
1352
+ * `backup` error propagates. Control-flow signals (`suspended_error`,
1353
+ * `aborted_error`) are not failures: they propagate instead of triggering the
1354
+ * backup, so a human-approval gate is never silently bypassed and the backup
1355
+ * never runs under an aborted context. See spec.md §5.8.
1356
+ */
1357
+ let fallback_counter = 0;
1358
+ function next_id$4() {
1359
+ fallback_counter += 1;
1360
+ return `fallback_${fallback_counter}`;
1361
+ }
1362
+ function fallback(primary, backup, options) {
1363
+ const id = next_id$4();
1364
+ const run_fn = async (input, ctx) => {
1365
+ try {
1366
+ return await dispatch_step(primary, input, ctx);
1367
+ } catch (err) {
1368
+ if (is_control_flow_error(err)) throw err;
1369
+ return dispatch_step(backup, input, ctx);
1370
+ }
1371
+ };
1372
+ const config_meta = options?.name === void 0 ? void 0 : { display_name: options.name };
1373
+ return {
1374
+ id,
1375
+ kind: "fallback",
1376
+ children: [primary, backup],
1377
+ ...config_meta ? { config: config_meta } : {},
1378
+ run: run_fn
1379
+ };
1380
+ }
1381
+ register_traced_kind("fallback");
1382
+ //#endregion
1383
+ //#region src/core/timeout.ts
1384
+ /**
1385
+ * timeout: bound execution.
1386
+ *
1387
+ * `timeout(inner, ms)` runs `inner` with a composed `AbortSignal` that fires
1388
+ * at `ms` milliseconds. If the inner step does not complete in time, throws
1389
+ * `timeout_error`. The inner step is responsible for honoring `ctx.abort`;
1390
+ * a step that ignores the signal still triggers `timeout_error` on schedule
1391
+ * but continues running in the background (spec.md §9 F4).
1392
+ *
1393
+ * Cancellation (constraints.md §5.1, spec.md §6.8): the inner step runs with
1394
+ * `AbortSignal.any([ctx.abort, timeout_local])`. On timer expiry, the local
1395
+ * controller aborts with a `timeout_error` as its reason; on parent abort
1396
+ * the parent reason flows through. The timer is always cleared in a finally
1397
+ * block so it does not leak across retries.
1398
+ */
1399
+ let timeout_counter = 0;
1400
+ function next_id$3() {
1401
+ timeout_counter += 1;
1402
+ return `timeout_${timeout_counter}`;
1403
+ }
1404
+ function timeout(inner, ms, options) {
1405
+ const id = next_id$3();
1406
+ const run_fn = async (input, ctx) => {
1407
+ const local = new AbortController();
1408
+ const composed = AbortSignal.any([ctx.abort, local.signal]);
1409
+ const child_ctx = {
1410
+ ...ctx,
1411
+ abort: composed
1412
+ };
1413
+ let timed_out = false;
1414
+ const timer = setTimeout(() => {
1415
+ timed_out = true;
1416
+ local.abort(new timeout_error(`timeout after ${ms}ms`, ms));
1417
+ }, ms);
1418
+ const deadline = new Promise((_, reject) => {
1419
+ const on_local_abort = () => {
1420
+ if (timed_out) reject(new timeout_error(`timeout after ${ms}ms`, ms));
1421
+ else {
1422
+ const reason = ctx.abort.reason;
1423
+ reject(reason instanceof Error ? reason : new aborted_error("aborted", { reason }));
1424
+ }
1425
+ };
1426
+ if (composed.aborted) {
1427
+ on_local_abort();
1428
+ return;
1429
+ }
1430
+ composed.addEventListener("abort", on_local_abort, { once: true });
1431
+ });
1432
+ try {
1433
+ return await Promise.race([dispatch_step(inner, input, child_ctx), deadline]);
1434
+ } finally {
1435
+ clearTimeout(timer);
1436
+ }
1437
+ };
1438
+ const config_meta = { ms };
1439
+ if (options?.name !== void 0) config_meta["display_name"] = options.name;
1440
+ return {
1441
+ id,
1442
+ kind: "timeout",
1443
+ children: [inner],
1444
+ config: config_meta,
1445
+ run: run_fn
1446
+ };
1447
+ }
1448
+ register_traced_kind("timeout");
1449
+ //#endregion
1450
+ //#region src/core/loop.ts
1451
+ /**
1452
+ * loop: bounded iteration with carry-state.
1453
+ *
1454
+ * `loop({ init, body, guard?, finish, max_rounds, name? })` runs `body` up to
1455
+ * `max_rounds` times, threading `state` through each iteration. After every
1456
+ * `body` call, an optional `guard` step inspects (and may transform) the state
1457
+ * and decides whether to stop. When `guard.stop` is true, the loop exits
1458
+ * "converged"; otherwise it continues until `max_rounds`. `finish` projects
1459
+ * the final state to the loop's output value.
1460
+ *
1461
+ * Non-convergence is data, not error: when `max_rounds` is exhausted without
1462
+ * `guard` returning stop, the loop returns `{ value, converged: false, rounds }`.
1463
+ * This matches the existing convention from adversarial/consensus.
1464
+ *
1465
+ * Cancellation: between rounds the parent `ctx.abort` is honored — a pending
1466
+ * abort short-circuits and propagates `ctx.abort.reason`. The body and guard
1467
+ * receive the parent context unchanged; their own dispatch routes already
1468
+ * thread cancellation per the runner contract.
1469
+ */
1470
+ let loop_counter = 0;
1471
+ function next_id$2(name) {
1472
+ loop_counter += 1;
1473
+ return `${name ?? "loop"}_${loop_counter}`;
1474
+ }
1475
+ function loop(config) {
1476
+ const { init, body, guard, finish, name } = config;
1477
+ const rounds_limit = Math.max(1, Math.floor(config.max_rounds));
1478
+ const id = next_id$2(name);
1479
+ const run_fn = async (input, ctx) => {
1480
+ let state = init(input);
1481
+ let round = 0;
1482
+ let converged = false;
1483
+ while (round < rounds_limit) {
1484
+ throw_if_aborted(ctx);
1485
+ round += 1;
1486
+ state = await dispatch_step(body, state, ctx);
1487
+ if (guard) {
1488
+ throw_if_aborted(ctx);
1489
+ const guard_out = await dispatch_step(guard, state, ctx);
1490
+ state = guard_out.state;
1491
+ if (guard_out.stop) {
1492
+ converged = true;
1493
+ break;
1494
+ }
1495
+ }
1496
+ }
1497
+ return {
1498
+ value: finish(state, round),
1499
+ converged,
1500
+ rounds: round
1501
+ };
1502
+ };
1503
+ const config_meta = { max_rounds: rounds_limit };
1504
+ if (name !== void 0) config_meta["display_name"] = name;
1505
+ return {
1506
+ id,
1507
+ kind: "loop",
1508
+ children: guard ? [body, guard] : [body],
1509
+ config: config_meta,
1510
+ run: run_fn
1511
+ };
1512
+ }
1513
+ register_traced_kind("loop");
1514
+ //#endregion
1515
+ //#region src/core/compose.ts
1516
+ /**
1517
+ * compose: name a composite step.
1518
+ *
1519
+ * `compose(name, inner)` wraps any step and labels its trajectory span with
1520
+ * `name`. The inner step's own span (e.g. a `sequence`) appears as a child of
1521
+ * the compose span — the implementation tree is preserved while the user's
1522
+ * intent ("this whole thing is an ensemble") is surfaced in observability.
1523
+ *
1524
+ * Used by the composites package to make built-in patterns appear under
1525
+ * their familiar names, and available to library consumers who want their own
1526
+ * named composites to show up in logs as first-class components.
1527
+ *
1528
+ * The primitive's `kind` is always `'compose'`; the user-supplied label lives
1529
+ * in `config.display_name` and is the span name the dispatcher opens.
1530
+ */
1531
+ let compose_counter = 0;
1532
+ function next_id$1(name) {
1533
+ compose_counter += 1;
1534
+ return `${name}_${compose_counter}`;
1535
+ }
1536
+ function compose(name, inner) {
1537
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("compose(name, inner): name must be a non-empty string");
1538
+ const id = next_id$1(name);
1539
+ const run_fn = (input, ctx) => dispatch_step(inner, input, ctx);
1540
+ return {
1541
+ id,
1542
+ kind: "compose",
1543
+ children: [inner],
1544
+ config: { display_name: name },
1545
+ run: run_fn
1546
+ };
1547
+ }
1548
+ register_traced_kind("compose");
1549
+ //#endregion
1550
+ //#region src/core/checkpoint.ts
1551
+ /**
1552
+ * checkpoint: persist and resume.
1553
+ *
1554
+ * `checkpoint(inner, { key })` checks a persistent store for a completed
1555
+ * result at `key` before running `inner`. On a hit, returns the stored
1556
+ * value. On a miss, runs `inner`, persists its result at `key`, and returns
1557
+ * it. Corrupted reads (store throws on `get`) are treated as a miss.
1558
+ *
1559
+ * Fail-fast (constraints.md §7 invariant 8, spec.md §9 F6): wrapping an
1560
+ * anonymous inner step throws synchronously at construction time with the
1561
+ * message `checkpoint requires a named step; got anonymous`.
1562
+ *
1563
+ * See spec.md §5.14, §6.3.
1564
+ */
1565
+ let checkpoint_counter = 0;
1566
+ function next_id() {
1567
+ checkpoint_counter += 1;
1568
+ return `checkpoint_${checkpoint_counter}`;
1569
+ }
1570
+ function checkpoint(inner, config) {
1571
+ if (inner.anonymous === true) throw new Error("checkpoint requires a named step; got anonymous");
1572
+ const id = next_id();
1573
+ const key_spec = config.key;
1574
+ const run_fn = async (input, ctx) => {
1575
+ const key = typeof key_spec === "function" ? key_spec(input) : key_spec;
1576
+ const store = ctx.checkpoint_store;
1577
+ if (store) {
1578
+ let cached = void 0;
1579
+ let hit = false;
1580
+ try {
1581
+ cached = await store.get(key);
1582
+ hit = cached !== null && cached !== void 0;
1583
+ } catch {
1584
+ hit = false;
1585
+ }
1586
+ if (hit) return cached;
1587
+ }
1588
+ const result = await dispatch_step(inner, input, ctx);
1589
+ if (store) await store.set(key, result);
1590
+ return result;
1591
+ };
1592
+ const config_meta = { key: key_spec };
1593
+ if (config.name !== void 0) config_meta["display_name"] = config.name;
1594
+ return {
1595
+ id,
1596
+ kind: "checkpoint",
1597
+ children: [inner],
1598
+ config: config_meta,
1599
+ run: run_fn
1600
+ };
1601
+ }
1602
+ register_traced_kind("checkpoint");
1603
+ //#endregion
1604
+ //#region src/core/suspend.ts
1605
+ /**
1606
+ * suspend: human-in-the-loop pause.
1607
+ *
1608
+ * `suspend({ id, on, resume_schema, combine })` pauses a flow waiting on
1609
+ * external input (a notification, an approval, an uploaded file). On first
1610
+ * encounter with no resume data, it calls `on(input, ctx)` (side effect) and
1611
+ * throws `suspended_error` carrying the run state. On resume (re-invocation
1612
+ * with `run_options.resume_data[id]` populated), the provided value is
1613
+ * validated against `resume_schema` and passed to `combine(input, resume,
1614
+ * ctx)`; the result is returned. Invalid resume data throws
1615
+ * `resume_validation_error` built from zod 4's `.flatten()` (spec.md §9 F5).
1616
+ *
1617
+ * See spec.md §5.15, §6.4.
1618
+ */
1619
+ function is_step(value) {
1620
+ if (typeof value !== "object" || value === null) return false;
1621
+ if (!("id" in value) || !("kind" in value) || !("run" in value)) return false;
1622
+ const { id, kind, run } = value;
1623
+ return typeof id === "string" && typeof kind === "string" && typeof run === "function";
1624
+ }
1625
+ function suspend(config) {
1626
+ const suspend_id = config.id;
1627
+ const on_fn = config.on;
1628
+ const resume_schema = config.resume_schema;
1629
+ const combine_fn = config.combine;
1630
+ const run_fn = async (input, ctx) => {
1631
+ const resume_value = ctx.resume_data?.[suspend_id];
1632
+ if (resume_value === void 0) {
1633
+ await on_fn(input, ctx);
1634
+ throw new suspended_error(suspend_id, { input });
1635
+ }
1636
+ const parsed = resume_schema.safeParse(resume_value);
1637
+ if (!parsed.success) {
1638
+ const issues = z.flattenError(parsed.error);
1639
+ throw new resume_validation_error(`resume data for ${suspend_id} failed validation`, issues);
1640
+ }
1641
+ const result = await combine_fn(input, parsed.data, ctx);
1642
+ if (is_step(result)) return dispatch_step(result, input, ctx);
1643
+ return result;
1644
+ };
1645
+ const config_meta = { id: suspend_id };
1646
+ if (config.name !== void 0) config_meta["display_name"] = config.name;
1647
+ return {
1648
+ id: suspend_id,
1649
+ kind: "suspend",
1650
+ config: config_meta,
1651
+ run: run_fn
1652
+ };
1653
+ }
1654
+ register_traced_kind("suspend");
1655
+ //#endregion
1656
+ //#region src/core/scope.ts
1657
+ /**
1658
+ * scope / stash / use: named state.
1659
+ *
1660
+ * `scope([...children])` introduces a scope-local `Map<string, unknown>` and
1661
+ * runs its children in order, chaining outputs like `sequence`. `stash(key,
1662
+ * source)` runs `source`, writes its output to the scope's state at `key`,
1663
+ * and passes the value through. `use(keys, fn)` reads the named values from
1664
+ * state and runs `fn` with the projection. Inner scopes inherit outer state;
1665
+ * writes only affect the inner map.
1666
+ *
1667
+ * Using `stash` or `use` outside a `scope` is a runtime error with a clear
1668
+ * message (spec.md §9 F1).
1669
+ *
1670
+ * See spec.md §5.16.
1671
+ */
1672
+ const scope_states = /* @__PURE__ */ new WeakSet();
1673
+ function is_scope_state(state) {
1674
+ return scope_states.has(state);
1675
+ }
1676
+ let scope_counter = 0;
1677
+ let stash_counter = 0;
1678
+ let use_counter = 0;
1679
+ function next_scope_id() {
1680
+ scope_counter += 1;
1681
+ return `scope_${scope_counter}`;
1682
+ }
1683
+ function next_stash_id() {
1684
+ stash_counter += 1;
1685
+ return `stash_${stash_counter}`;
1686
+ }
1687
+ function next_use_id() {
1688
+ use_counter += 1;
1689
+ return `use_${use_counter}`;
1690
+ }
1691
+ function scope(children, options) {
1692
+ const id = next_scope_id();
1693
+ const children_ref = children;
1694
+ const run_fn = async (input, ctx) => {
1695
+ const local = new Map(ctx.state);
1696
+ scope_states.add(local);
1697
+ const scope_ctx = {
1698
+ ...ctx,
1699
+ state: local
1700
+ };
1701
+ let acc = input;
1702
+ for (const child of children_ref) {
1703
+ throw_if_aborted(scope_ctx);
1704
+ acc = await dispatch_step(child, acc, scope_ctx);
1705
+ }
1706
+ return acc;
1707
+ };
1708
+ const config_meta = options?.name === void 0 ? void 0 : { display_name: options.name };
1709
+ return {
1710
+ id,
1711
+ kind: "scope",
1712
+ children,
1713
+ ...config_meta ? { config: config_meta } : {},
1714
+ run: run_fn
1715
+ };
1716
+ }
1717
+ function stash(key, source, options) {
1718
+ const id = next_stash_id();
1719
+ const run_fn = async (input, ctx) => {
1720
+ if (!is_scope_state(ctx.state)) throw new Error("stash() may only appear inside scope(); got: top-level");
1721
+ const value = await dispatch_step(source, input, ctx);
1722
+ ctx.state.set(key, value);
1723
+ return value;
1724
+ };
1725
+ const config_meta = { key };
1726
+ if (options?.name !== void 0) config_meta["display_name"] = options.name;
1727
+ return {
1728
+ id,
1729
+ kind: "stash",
1730
+ children: [source],
1731
+ config: config_meta,
1732
+ run: run_fn
1733
+ };
1734
+ }
1735
+ function use(keys, fn, options) {
1736
+ const id = next_use_id();
1737
+ const run_fn = async (input, ctx) => {
1738
+ if (!is_scope_state(ctx.state)) throw new Error("use() may only appear inside scope(); got: top-level");
1739
+ const projection = {};
1740
+ for (const k of keys) projection[k] = ctx.state.get(k);
1741
+ return fn(projection, input, ctx);
1742
+ };
1743
+ const config_meta = { keys: [...keys] };
1744
+ if (options?.name !== void 0) config_meta["display_name"] = options.name;
1745
+ return {
1746
+ id,
1747
+ kind: "use",
1748
+ config: config_meta,
1749
+ run: run_fn
1750
+ };
1751
+ }
1752
+ register_traced_kind("scope");
1753
+ register_traced_kind("stash");
1754
+ register_traced_kind("use");
1755
+ //#endregion
1756
+ //#region src/core/step_kinds.ts
1757
+ /**
1758
+ * Closed registry of every `Step.kind` produced by the composition layer.
1759
+ *
1760
+ * Studio (and any other consumer that needs to enumerate primitives — palette,
1761
+ * docs, code generation) can rely on this being the exhaustive set. New
1762
+ * primitives must add their kind here. The `step_kinds_cover_runner` contract
1763
+ * test in `step_kinds.test.ts` asserts every dispatch handler corresponds to a
1764
+ * kind listed here.
1765
+ */
1766
+ const STEP_KINDS = [
1767
+ "step",
1768
+ "sequence",
1769
+ "parallel",
1770
+ "branch",
1771
+ "map",
1772
+ "pipe",
1773
+ "retry",
1774
+ "fallback",
1775
+ "timeout",
1776
+ "loop",
1777
+ "compose",
1778
+ "adversarial",
1779
+ "ensemble",
1780
+ "tournament",
1781
+ "consensus",
1782
+ "checkpoint",
1783
+ "suspend",
1784
+ "scope",
1785
+ "stash",
1786
+ "use"
1787
+ ];
1788
+ function is_step_kind(value) {
1789
+ return typeof value === "string" && STEP_KINDS.includes(value);
1790
+ }
1791
+ //#endregion
1792
+ //#region src/core/trajectory.ts
1793
+ /**
1794
+ * Wire-format schema for trajectory events.
1795
+ *
1796
+ * `TrajectoryEvent` (in `types.ts`) is the loose internal type — any code that
1797
+ * calls `trajectory.record(event)` or `start_span(name, meta)` produces values
1798
+ * conforming to it. This file defines the *narrower* shapes that the studio
1799
+ * (and any other downstream consumer) can parse out of the wire stream:
1800
+ *
1801
+ * span_start — composer span open
1802
+ * span_end — composer span close
1803
+ * emit — user-emitted event from inside a step (ctx.emit)
1804
+ * <other> — falls through `custom_event_schema`, which only requires a
1805
+ * string `kind` and tolerates any extra fields
1806
+ *
1807
+ * The discriminated union is **ordered**: well-known shapes are tried before
1808
+ * the permissive `custom` schema, so a `{ kind: 'span_start', ... }` event
1809
+ * always parses as `SpanStartEvent`, never as `CustomTrajectoryEvent`.
1810
+ *
1811
+ * Every well-known schema and `custom_event_schema` use `.passthrough()` so
1812
+ * additional fields (e.g. `run_id`, `id`, provider-specific metadata) survive
1813
+ * a parse / re-serialize round-trip without loss.
1814
+ */
1815
+ const span_start_event_schema = z.object({
1816
+ kind: z.literal("span_start"),
1817
+ span_id: z.string(),
1818
+ name: z.string()
1819
+ }).passthrough();
1820
+ const span_end_event_schema = z.object({
1821
+ kind: z.literal("span_end"),
1822
+ span_id: z.string()
1823
+ }).passthrough();
1824
+ const emit_event_schema = z.object({ kind: z.literal("emit") }).passthrough();
1825
+ const custom_event_schema = z.object({ kind: z.string() }).passthrough();
1826
+ const trajectory_event_schema = z.union([
1827
+ span_start_event_schema,
1828
+ span_end_event_schema,
1829
+ emit_event_schema,
1830
+ custom_event_schema
1831
+ ]);
1832
+ //#endregion
1833
+ //#region src/core/index.ts
1834
+ /**
1835
+ * Public surface for core.
1836
+ *
1837
+ * Side-effect imports ensure every composer registers itself with the runner
1838
+ * at module load. Importing anything from `core` populates the
1839
+ * dispatch table with the core primitives. Built-in composites
1840
+ * (adversarial, ensemble, tournament, consensus) live in composites
1841
+ * and surface through the umbrella package.
1842
+ */
1843
+ //#endregion
1844
+ export { timeout_error as A, describe as C, describe_cycle_error as D, aborted_error as E, resume_validation_error as O, sequence as S, run as T, retry as _, trajectory_event_schema as a, branch as b, scope as c, suspend as d, checkpoint as f, fallback as g, timeout as h, span_start_event_schema as i, flow_schema_default as j, suspended_error as k, stash as l, loop as m, emit_event_schema as n, STEP_KINDS as o, compose as p, span_end_event_schema as r, is_step_kind as s, custom_event_schema as t, use as u, pipe as v, step as w, parallel as x, map as y };
1845
+
1846
+ //# sourceMappingURL=core-dRSAN1Q2.js.map