fascicle 0.9.6 → 0.9.9

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.
@@ -288,6 +288,14 @@ var flow_schema_default = {
288
288
  //#endregion
289
289
  //#region src/core/cleanup.ts
290
290
  const HANDLER_TIMEOUT_MS = 5e3;
291
+ /**
292
+ * Create the per-run cleanup registry.
293
+ *
294
+ * `register` collects handlers during the run; `run_all` fires them once in
295
+ * LIFO order and is idempotent. A registration arriving after the flush is
296
+ * not executed; it is recorded as `cleanup_registered_after_flush` so the
297
+ * leak is visible in the trajectory instead of silently dropped.
298
+ */
291
299
  function create_cleanup_registry(trajectory) {
292
300
  const handlers = [];
293
301
  let ran = false;
@@ -312,6 +320,15 @@ function create_cleanup_registry(trajectory) {
312
320
  run_all
313
321
  };
314
322
  }
323
+ /**
324
+ * Run a single cleanup handler, never letting it fail the run.
325
+ *
326
+ * Races the handler against a 5-second timer. Whichever loses the race only
327
+ * results in a trajectory record (`cleanup_timeout` or `cleanup_error`); the
328
+ * returned promise always resolves so the remaining handlers still execute.
329
+ * A timed-out handler keeps running in the background; it is abandoned, not
330
+ * killed.
331
+ */
315
332
  async function run_one(fn, trajectory) {
316
333
  let timeout_id = null;
317
334
  try {
@@ -344,9 +361,9 @@ async function run_one(fn, trajectory) {
344
361
  /**
345
362
  * Typed errors for the composition layer.
346
363
  *
347
- * This is the only source file in packages/core/src/ that uses the `class`
364
+ * This is the only source file in the core layer that uses the `class`
348
365
  * keyword. `Error` is a built-in and `instanceof` branching is how composers
349
- * like `retry` and `fallback` distinguish failure modes. See constraints.md §2.
366
+ * like `retry` and `fallback` distinguish failure modes.
350
367
  */
351
368
  var timeout_error = class extends Error {
352
369
  kind = "timeout_error";
@@ -414,6 +431,15 @@ function is_control_flow_error(err) {
414
431
  //#endregion
415
432
  //#region src/core/streaming.ts
416
433
  const STREAMING_HIGH_WATER_MARK = 1e4;
434
+ /**
435
+ * Build the logger/iterable pair backing `run.stream`.
436
+ *
437
+ * Wraps a base `TrajectoryLogger` so every recorded event is also enqueued
438
+ * for the async iterable. A single pending `waiter` hands events straight to
439
+ * a blocked consumer; otherwise events buffer up to `high_water_mark`, after
440
+ * which the oldest are dropped and counted for the `events_dropped` marker
441
+ * emitted at close.
442
+ */
417
443
  function create_streaming_channel(base, high_water_mark = STREAMING_HIGH_WATER_MARK) {
418
444
  const buffer = [];
419
445
  let dropped = 0;
@@ -531,6 +557,12 @@ function create_streaming_channel(base, high_water_mark = STREAMING_HIGH_WATER_M
531
557
  * identical to `run(...)`.
532
558
  */
533
559
  const dispatch = /* @__PURE__ */ new Map();
560
+ /**
561
+ * Register the dispatch handler for a step kind.
562
+ *
563
+ * Composer files call this (directly or via `register_traced_kind`) at module
564
+ * load, which is how the runner stays free of composer-specific logic.
565
+ */
534
566
  function register_kind(kind, fn) {
535
567
  dispatch.set(kind, fn);
536
568
  }
@@ -584,6 +616,13 @@ const active_runs = /* @__PURE__ */ new Set();
584
616
  let signal_handler_installed = false;
585
617
  let sigint_handler = null;
586
618
  let sigterm_handler = null;
619
+ /**
620
+ * Install process-wide SIGINT/SIGTERM handlers once.
621
+ *
622
+ * The handlers abort every active run with an `aborted_error` naming the
623
+ * signal, so a Ctrl-C tears down all in-flight flows through the normal
624
+ * abort/cleanup path instead of killing the process mid-step.
625
+ */
587
626
  function ensure_signal_handlers() {
588
627
  if (signal_handler_installed) return;
589
628
  signal_handler_installed = true;
@@ -595,6 +634,12 @@ function ensure_signal_handlers() {
595
634
  process.on("SIGINT", sigint_handler);
596
635
  process.on("SIGTERM", sigterm_handler);
597
636
  }
637
+ /**
638
+ * Remove the process signal handlers once the last active run settles.
639
+ *
640
+ * Keeps a library embed from leaving stray `process.on` listeners behind
641
+ * after all runs complete.
642
+ */
598
643
  function release_signal_handlers() {
599
644
  if (!signal_handler_installed) return;
600
645
  if (active_runs.size > 0) return;
@@ -645,6 +690,13 @@ function decorate_logger(inner, run_id) {
645
690
  }
646
691
  };
647
692
  }
693
+ /**
694
+ * Route a step to its registered kind handler.
695
+ *
696
+ * This is the single entry point composers use to run children. On failure
697
+ * the step's id is prepended to the error's `path`, so an error surfacing
698
+ * from a deep tree carries the chain of step ids it crossed.
699
+ */
648
700
  async function dispatch_step(flow, input, ctx) {
649
701
  const handler = dispatch.get(flow.kind);
650
702
  if (!handler) throw new Error(`unknown step kind: ${flow.kind} (step id: ${flow.id})`);
@@ -655,6 +707,12 @@ async function dispatch_step(flow, input, ctx) {
655
707
  throw err;
656
708
  }
657
709
  }
710
+ /**
711
+ * Prepend a step id to the `path` array carried on an error object.
712
+ *
713
+ * Mutates the error in place so the path accumulates as the error bubbles up
714
+ * through nested dispatches. Non-object errors are left untouched.
715
+ */
658
716
  function prepend_path(err, id) {
659
717
  if (err === null || typeof err !== "object") return;
660
718
  const existing = Reflect.get(err, "path");
@@ -694,6 +752,15 @@ function link_external_abort(controller, external) {
694
752
  external.removeEventListener("abort", on_abort);
695
753
  };
696
754
  }
755
+ /**
756
+ * Construct a run context and execute a flow to settlement.
757
+ *
758
+ * Shared engine behind `run` and `run.stream`; `high_water_mark` selects the
759
+ * mode (null means no streaming channel). Owns the full run lifecycle:
760
+ * abort wiring, logger decoration, cleanup registration, signal handlers,
761
+ * and the settle-time teardown ordering (cleanup handlers first, then
762
+ * unlinking and stream close).
763
+ */
697
764
  function start_run(flow, input, options, high_water_mark) {
698
765
  const install_signal_handlers = options.install_signal_handlers !== false;
699
766
  const base_logger = options.trajectory ?? noop_logger;
@@ -758,6 +825,12 @@ function start_run(flow, input, options, high_water_mark) {
758
825
  result
759
826
  };
760
827
  }
828
+ /**
829
+ * Build an async iterable that is immediately done.
830
+ *
831
+ * Non-streaming runs hand this to callers so the `events` field always has
832
+ * the same shape regardless of mode.
833
+ */
761
834
  function empty_async_iterable() {
762
835
  return { [Symbol.asyncIterator]() {
763
836
  return { next: () => Promise.resolve({
@@ -766,10 +839,16 @@ function empty_async_iterable() {
766
839
  }) };
767
840
  } };
768
841
  }
842
+ /**
843
+ * Execute a flow and resolve with its final output.
844
+ */
769
845
  async function run_impl(flow, input, options = {}) {
770
846
  const { result } = start_run(flow, input, options, null);
771
847
  return result;
772
848
  }
849
+ /**
850
+ * Execute a flow while exposing its trajectory events as an async iterable.
851
+ */
773
852
  function run_stream(flow, input, options = {}) {
774
853
  const { events, result } = start_run(flow, input, options, STREAMING_HIGH_WATER_MARK);
775
854
  return {
@@ -777,6 +856,14 @@ function run_stream(flow, input, options = {}) {
777
856
  result
778
857
  };
779
858
  }
859
+ /**
860
+ * The public entry point for executing a flow.
861
+ *
862
+ * Callable as `run(flow, input, options?)` for a plain result, or
863
+ * `run.stream(flow, input, options?)` for `{ events, result }`. Both share
864
+ * one implementation, so a streamed run and a plain run of the same flow
865
+ * produce identical output.
866
+ */
780
867
  const run = Object.assign(run_impl, { stream: run_stream });
781
868
  //#endregion
782
869
  //#region src/core/step.ts
@@ -784,16 +871,19 @@ const run = Object.assign(run_impl, { stream: run_stream });
784
871
  * step() factory.
785
872
  *
786
873
  * 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.
874
+ * step(id, fn): named step. id is rendered in trajectory spans and describe().
875
+ * step(id, fn, meta): named step with optional human-readable metadata for studio,
876
+ * codegen, and similar consumers. `meta` is purely descriptive
877
+ * and never affects runtime semantics.
878
+ * step(fn): anonymous step. id is `anon_<counter>`; cannot be checkpointed.
792
879
  *
793
880
  * 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).
881
+ * reject them synchronously at flow construction time.
795
882
  */
796
883
  let anon_counter = 0;
884
+ /**
885
+ * Generate a unique id of the form `anon_<n>` for anonymous steps.
886
+ */
797
887
  function next_anon_id() {
798
888
  anon_counter += 1;
799
889
  return `anon_${anon_counter}`;
@@ -821,6 +911,12 @@ function step(id_or_fn, maybe_fn, meta) {
821
911
  register_traced_kind("step");
822
912
  //#endregion
823
913
  //#region src/core/is_step.ts
914
+ /**
915
+ * Check whether a value is structurally a `Step`.
916
+ *
917
+ * True when the value has a string `id`, a string `kind`, and a callable
918
+ * `run`.
919
+ */
824
920
  function is_step$1(value) {
825
921
  if (typeof value !== "object" || value === null) return false;
826
922
  if (!("id" in value) || !("kind" in value) || !("run" in value)) return false;
@@ -830,7 +926,7 @@ function is_step$1(value) {
830
926
  //#endregion
831
927
  //#region src/core/describe.ts
832
928
  /**
833
- * describe(step) and describe.json(step) — composition introspection.
929
+ * describe(step) and describe.json(step): composition introspection.
834
930
  *
835
931
  * `describe(step)` is the text-tree renderer. Multi-line string with
836
932
  * hierarchical indentation. Function values render as `<fn>` (or
@@ -846,17 +942,34 @@ function is_step$1(value) {
846
942
  * `{ strict: true }`, cycles throw `describe_cycle_error`.
847
943
  */
848
944
  const INDENT = " ";
945
+ /**
946
+ * Render a step tree as an indented multi-line string.
947
+ */
849
948
  function describe_text(root, options) {
850
949
  const lines = [];
851
950
  const strict = Boolean(options?.strict);
852
951
  render_text(root, 0, lines, /* @__PURE__ */ new Set(), strict);
853
952
  return lines.join("\n");
854
953
  }
954
+ /**
955
+ * Render a step tree as a serializable `FlowNode` tree.
956
+ */
855
957
  function describe_json(root, options) {
856
958
  const strict = Boolean(options?.strict);
857
959
  return render_json(root, /* @__PURE__ */ new Set(), strict);
858
960
  }
961
+ /**
962
+ * Public entry point: `describe(step)` for text, `describe.json(step)` for
963
+ * the `FlowNode` tree.
964
+ */
859
965
  const describe = Object.assign(describe_text, { json: describe_json });
966
+ /**
967
+ * Append one node (label line, config lines, then children) to `lines`.
968
+ *
969
+ * `path` holds the steps on the current root-to-node path for cycle
970
+ * detection; membership is added before recursing and removed in a `finally`
971
+ * so shared (diamond) references are not misreported as cycles.
972
+ */
860
973
  function render_text(node, depth, lines, path, strict) {
861
974
  const prefix = INDENT.repeat(depth);
862
975
  if (path.has(node)) {
@@ -878,6 +991,13 @@ function render_text(node, depth, lines, path, strict) {
878
991
  path.delete(node);
879
992
  }
880
993
  }
994
+ /**
995
+ * Render a single config value for the text tree.
996
+ *
997
+ * Functions become `<fn>` or `<fn:name>`, zod schemas `<schema>`, and Step
998
+ * references `kind(id)`; arrays and plain objects recurse. Strings are
999
+ * JSON-quoted so empty and whitespace values stay visible.
1000
+ */
881
1001
  function render_value_text(value, path, strict) {
882
1002
  if (typeof value === "function") {
883
1003
  const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
@@ -901,6 +1021,12 @@ function render_value_text(value, path, strict) {
901
1021
  if (typeof value === "number" || typeof value === "boolean") return String(value);
902
1022
  return JSON.stringify(value);
903
1023
  }
1024
+ /**
1025
+ * Convert one step node to a `FlowNode`, recursing into config and children.
1026
+ *
1027
+ * Uses the same path-based cycle detection as `render_text`: back-references
1028
+ * become `{ kind: '<cycle>', id }` in loose mode and throw in strict mode.
1029
+ */
904
1030
  function render_json(node, path, strict) {
905
1031
  if (path.has(node)) {
906
1032
  if (strict) throw new describe_cycle_error(node.id);
@@ -927,6 +1053,14 @@ function render_json(node, path, strict) {
927
1053
  path.delete(node);
928
1054
  }
929
1055
  }
1056
+ /**
1057
+ * Convert a single config value to a JSON-safe `FlowValue`.
1058
+ *
1059
+ * Functions serialize as `{ kind: '<fn>', name? }`, schemas as
1060
+ * `{ kind: '<schema>' }`, Step references as `{ kind, id }`. `undefined`
1061
+ * maps to `null` and bigints/symbols to strings so the result survives
1062
+ * `JSON.stringify` without loss.
1063
+ */
930
1064
  function render_value_json(value, path, strict) {
931
1065
  if (typeof value === "function") {
932
1066
  const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
@@ -963,6 +1097,10 @@ function render_value_json(value, path, strict) {
963
1097
  if (typeof value === "symbol") return value.toString();
964
1098
  return JSON.stringify(value);
965
1099
  }
1100
+ /**
1101
+ * Detect a zod schema by its internal marker properties (`_zod` in zod 4,
1102
+ * `_def` in zod 3) without importing zod.
1103
+ */
966
1104
  function is_zod_schema(value) {
967
1105
  if (typeof value !== "object" || value === null) return false;
968
1106
  return "_zod" in value || "_def" in value;
@@ -975,14 +1113,22 @@ function is_zod_schema(value) {
975
1113
  * `sequence([a, b, c])` runs a, b, c in declared order. The input to sequence
976
1114
  * is passed to the first child; each subsequent child receives the previous
977
1115
  * child's output. The composer returns the last child's output.
978
- *
979
- * See spec.md §5.2 and §6.1.
980
1116
  */
981
1117
  let sequence_counter = 0;
1118
+ /**
1119
+ * Generate a unique step id of the form `sequence_<n>`.
1120
+ */
982
1121
  function next_id$10() {
983
1122
  sequence_counter += 1;
984
1123
  return `sequence_${sequence_counter}`;
985
1124
  }
1125
+ /**
1126
+ * Build a step that chains children, each feeding the next.
1127
+ *
1128
+ * Validates every element up front so a non-Step (usually a bare function)
1129
+ * fails at construction with a pointed message rather than at run time.
1130
+ * Checks `ctx.abort` before each child so aborts land on step boundaries.
1131
+ */
986
1132
  function sequence(children, options) {
987
1133
  if (!Array.isArray(children)) throw new TypeError(`sequence(children): children must be an array of Steps, got ${typeof children} — sequence takes a single array, e.g. sequence([a, b, c])`);
988
1134
  children.forEach((child, index) => {
@@ -1018,11 +1164,10 @@ register_traced_kind("sequence");
1018
1164
  * is an object keyed by the child name; all children must accept the same
1019
1165
  * input type.
1020
1166
  *
1021
- * Cancellation (constraints.md §5.1, spec.md §6.8): each child runs with a
1022
- * composed abort signal — `AbortSignal.any([ctx.abort, child_local])`. On
1023
- * abort the composer awaits all in-flight children (success, failure, or
1024
- * aborted) before rethrowing `ctx.abort.reason`. This matches the
1025
- * "agent-pattern" composer contract in spec.md §6.8.
1167
+ * Cancellation: each child runs with a composed abort signal,
1168
+ * `AbortSignal.any([ctx.abort, child_local])`. On abort the composer awaits
1169
+ * all in-flight children (success, failure, or aborted) before rethrowing
1170
+ * `ctx.abort.reason`.
1026
1171
  *
1027
1172
  * When several children fail, a `suspended_error` is preferred over an
1028
1173
  * application error so a human-approval gate inside a branch stays resumable
@@ -1030,10 +1175,21 @@ register_traced_kind("sequence");
1030
1175
  * in declared order propagates.
1031
1176
  */
1032
1177
  let parallel_counter = 0;
1178
+ /**
1179
+ * Generate a unique step id of the form `parallel_<n>`.
1180
+ */
1033
1181
  function next_id$9() {
1034
1182
  parallel_counter += 1;
1035
1183
  return `parallel_${parallel_counter}`;
1036
1184
  }
1185
+ /**
1186
+ * Build a step that runs named children concurrently on the same input.
1187
+ *
1188
+ * Returns an object keyed by child name. All children settle before any
1189
+ * error propagates; a `suspended_error` wins over application errors so a
1190
+ * human-approval gate stays resumable instead of being masked by a sibling's
1191
+ * failure.
1192
+ */
1037
1193
  function parallel(members, options) {
1038
1194
  const id = next_id$9();
1039
1195
  const entries = Object.entries(members);
@@ -1116,14 +1272,22 @@ register_traced_kind("parallel");
1116
1272
  * `branch({ when, then, otherwise })` evaluates `when(input)`; if truthy, runs
1117
1273
  * `then`, else runs `otherwise`. Both branches must return the same output
1118
1274
  * type.
1119
- *
1120
- * See spec.md §5.4.
1121
1275
  */
1122
1276
  let branch_counter = 0;
1277
+ /**
1278
+ * Generate a unique step id of the form `branch_<n>`.
1279
+ */
1123
1280
  function next_id$8() {
1124
1281
  branch_counter += 1;
1125
1282
  return `branch_${branch_counter}`;
1126
1283
  }
1284
+ /**
1285
+ * Build a conditional-routing step.
1286
+ *
1287
+ * Evaluates `when(input)` at run time and dispatches to `then` or `otherwise`.
1288
+ * Both branches appear as children so `describe()` renders the full tree even
1289
+ * though only one branch runs.
1290
+ */
1127
1291
  function branch(config) {
1128
1292
  const id = next_id$8();
1129
1293
  const { when, then: then_step, otherwise: otherwise_step, name } = config;
@@ -1155,16 +1319,26 @@ register_traced_kind("branch");
1155
1319
  * `concurrency` caps simultaneous in-flight items; omitted means full
1156
1320
  * parallelism.
1157
1321
  *
1158
- * Cancellation (constraints.md §5.1, spec.md §6.8): each in-flight item runs
1159
- * with a composed abort signal via `AbortSignal.any([ctx.abort, child_local])`.
1322
+ * Cancellation: each in-flight item runs with a composed abort signal via
1323
+ * `AbortSignal.any([ctx.abort, child_local])`.
1160
1324
  * On abort no new items start. The composer awaits all in-flight items before
1161
1325
  * rethrowing `ctx.abort.reason`.
1162
1326
  */
1163
1327
  let map_counter = 0;
1328
+ /**
1329
+ * Generate a unique step id of the form `map_<n>`.
1330
+ */
1164
1331
  function next_id$7() {
1165
1332
  map_counter += 1;
1166
1333
  return `map_${map_counter}`;
1167
1334
  }
1335
+ /**
1336
+ * Build a per-item execution step.
1337
+ *
1338
+ * Extracts an array via `items(input)`, runs `do` once per element through a
1339
+ * bounded worker pool, and returns results in input order. The first item
1340
+ * failure stops new work and propagates after in-flight items settle.
1341
+ */
1168
1342
  function map(config) {
1169
1343
  const id = next_id$7();
1170
1344
  const { items, do: per_item, concurrency, name } = config;
@@ -1241,14 +1415,22 @@ register_traced_kind("map");
1241
1415
  *
1242
1416
  * `pipe(inner, fn)` runs `inner`, passes its output to `fn`, returns `fn`'s
1243
1417
  * result. Use for shape adaptation when composing heterogeneous steps.
1244
- *
1245
- * See spec.md §5.6.
1246
1418
  */
1247
1419
  let pipe_counter = 0;
1420
+ /**
1421
+ * Generate a unique step id of the form `pipe_<n>`.
1422
+ */
1248
1423
  function next_id$6() {
1249
1424
  pipe_counter += 1;
1250
1425
  return `pipe_${pipe_counter}`;
1251
1426
  }
1427
+ /**
1428
+ * Build an output-transforming step around `inner`.
1429
+ *
1430
+ * The argument checks reject Steps passed where functions belong: `pipe` is
1431
+ * not variadic, and the early `TypeError`s point misuse at `step(fn)` or
1432
+ * `sequence([...])` instead of failing obscurely at run time.
1433
+ */
1252
1434
  function pipe(inner, fn, options) {
1253
1435
  if (!is_step$1(inner)) throw new TypeError(`pipe(inner, fn): inner must be a Step, got ${typeof inner}${typeof inner === "function" ? " — wrap plain functions with step(fn)" : ""}`);
1254
1436
  if (typeof fn !== "function") {
@@ -1286,17 +1468,25 @@ register_traced_kind("pipe");
1286
1468
  * or scheduling a backoff. A suspend's `on()` side effect therefore runs once
1287
1469
  * per run, not once per attempt.
1288
1470
  *
1289
- * Cancellation / cleanup (constraints.md §5.2, spec.md §6.8): cleanup handlers
1290
- * registered by the inner step accumulate across attempts. The parent
1291
- * `ctx.abort` is honored between attempts — a pending abort short-circuits
1292
- * the backoff and propagates. See spec.md §5.7 and §9 F11.
1471
+ * Cancellation / cleanup: cleanup handlers registered by the inner step
1472
+ * accumulate across attempts. The parent `ctx.abort` is honored between
1473
+ * attempts; a pending abort short-circuits the backoff and propagates.
1293
1474
  */
1294
1475
  const DEFAULT_BACKOFF_MS = 1e3;
1295
1476
  let retry_counter = 0;
1477
+ /**
1478
+ * Generate a unique step id of the form `retry_<n>`.
1479
+ */
1296
1480
  function next_id$5() {
1297
1481
  retry_counter += 1;
1298
1482
  return `retry_${retry_counter}`;
1299
1483
  }
1484
+ /**
1485
+ * Sleep for `ms` unless the run is aborted first.
1486
+ *
1487
+ * Rejects immediately with the abort reason (or an `aborted_error`) when
1488
+ * `ctx.abort` fires, so a pending abort never waits out a backoff delay.
1489
+ */
1300
1490
  async function abortable_wait(ms, ctx) {
1301
1491
  if (ms <= 0) return;
1302
1492
  await new Promise((resolve, reject) => {
@@ -1317,6 +1507,13 @@ async function abortable_wait(ms, ctx) {
1317
1507
  ctx.abort.addEventListener("abort", on_abort, { once: true });
1318
1508
  });
1319
1509
  }
1510
+ /**
1511
+ * Build a retrying step around `inner`.
1512
+ *
1513
+ * Runs `inner` up to `max_attempts` times with exponential backoff between
1514
+ * failures. Application errors consume an attempt and fire `on_error`;
1515
+ * control-flow signals propagate untouched.
1516
+ */
1320
1517
  function retry(inner, config) {
1321
1518
  const id = next_id$5();
1322
1519
  const max_attempts = Math.max(1, Math.floor(config.max_attempts));
@@ -1366,13 +1563,22 @@ register_traced_kind("retry");
1366
1563
  * `backup` error propagates. Control-flow signals (`suspended_error`,
1367
1564
  * `aborted_error`) are not failures: they propagate instead of triggering the
1368
1565
  * backup, so a human-approval gate is never silently bypassed and the backup
1369
- * never runs under an aborted context. See spec.md §5.8.
1566
+ * never runs under an aborted context.
1370
1567
  */
1371
1568
  let fallback_counter = 0;
1569
+ /**
1570
+ * Generate a unique step id of the form `fallback_<n>`.
1571
+ */
1372
1572
  function next_id$4() {
1373
1573
  fallback_counter += 1;
1374
1574
  return `fallback_${fallback_counter}`;
1375
1575
  }
1576
+ /**
1577
+ * Build a primary-or-backup step.
1578
+ *
1579
+ * Runs `primary`; on an application error runs `backup` with the same input.
1580
+ * Control-flow signals propagate without triggering the backup.
1581
+ */
1376
1582
  function fallback(primary, backup, options) {
1377
1583
  const id = next_id$4();
1378
1584
  const run_fn = async (input, ctx) => {
@@ -1402,19 +1608,29 @@ register_traced_kind("fallback");
1402
1608
  * at `ms` milliseconds. If the inner step does not complete in time, throws
1403
1609
  * `timeout_error`. The inner step is responsible for honoring `ctx.abort`;
1404
1610
  * a step that ignores the signal still triggers `timeout_error` on schedule
1405
- * but continues running in the background (spec.md §9 F4).
1611
+ * but continues running in the background.
1406
1612
  *
1407
- * Cancellation (constraints.md §5.1, spec.md §6.8): the inner step runs with
1613
+ * Cancellation: the inner step runs with
1408
1614
  * `AbortSignal.any([ctx.abort, timeout_local])`. On timer expiry, the local
1409
1615
  * controller aborts with a `timeout_error` as its reason; on parent abort
1410
1616
  * the parent reason flows through. The timer is always cleared in a finally
1411
1617
  * block so it does not leak across retries.
1412
1618
  */
1413
1619
  let timeout_counter = 0;
1620
+ /**
1621
+ * Generate a unique step id of the form `timeout_<n>`.
1622
+ */
1414
1623
  function next_id$3() {
1415
1624
  timeout_counter += 1;
1416
1625
  return `timeout_${timeout_counter}`;
1417
1626
  }
1627
+ /**
1628
+ * Build a deadline-bounded step around `inner`.
1629
+ *
1630
+ * Races the inner dispatch against a timer that aborts the composed signal
1631
+ * with `timeout_error`. The `timed_out` flag distinguishes timer expiry from
1632
+ * a parent abort so the right error propagates.
1633
+ */
1418
1634
  function timeout(inner, ms, options) {
1419
1635
  const id = next_id$3();
1420
1636
  const run_fn = async (input, ctx) => {
@@ -1473,19 +1689,30 @@ register_traced_kind("timeout");
1473
1689
  * the final state to the loop's output value.
1474
1690
  *
1475
1691
  * Non-convergence is data, not error: when `max_rounds` is exhausted without
1476
- * `guard` returning stop, the loop returns `{ value, converged: false, rounds }`.
1477
- * This matches the existing convention from adversarial/consensus.
1692
+ * `guard` returning stop, the loop returns `{ value, converged: false, rounds }`,
1693
+ * the same convention `adversarial` and `consensus` use.
1478
1694
  *
1479
- * Cancellation: between rounds the parent `ctx.abort` is honored — a pending
1695
+ * Cancellation: between rounds the parent `ctx.abort` is honored; a pending
1480
1696
  * abort short-circuits and propagates `ctx.abort.reason`. The body and guard
1481
1697
  * receive the parent context unchanged; their own dispatch routes already
1482
1698
  * thread cancellation per the runner contract.
1483
1699
  */
1484
1700
  let loop_counter = 0;
1701
+ /**
1702
+ * Generate a unique step id, prefixed with the display name when one is set.
1703
+ */
1485
1704
  function next_id$2(name) {
1486
1705
  loop_counter += 1;
1487
1706
  return `${name ?? "loop"}_${loop_counter}`;
1488
1707
  }
1708
+ /**
1709
+ * Build a bounded iteration step with carry-state.
1710
+ *
1711
+ * Threads `state` through up to `max_rounds` runs of `body`, lets the
1712
+ * optional `guard` stop early, then projects the final state through
1713
+ * `finish`. Returns `{ value, converged, rounds }` so callers can tell a
1714
+ * converged run from an exhausted one.
1715
+ */
1489
1716
  function loop(config) {
1490
1717
  const { init, body, guard, finish, name } = config;
1491
1718
  const rounds_limit = Math.max(1, Math.floor(config.max_rounds));
@@ -1532,7 +1759,7 @@ register_traced_kind("loop");
1532
1759
  *
1533
1760
  * `compose(name, inner)` wraps any step and labels its trajectory span with
1534
1761
  * `name`. The inner step's own span (e.g. a `sequence`) appears as a child of
1535
- * the compose span — the implementation tree is preserved while the user's
1762
+ * the compose span: the implementation tree is preserved while the user's
1536
1763
  * intent ("this whole thing is an ensemble") is surfaced in observability.
1537
1764
  *
1538
1765
  * Used by the composites package to make built-in patterns appear under
@@ -1543,10 +1770,21 @@ register_traced_kind("loop");
1543
1770
  * in `config.display_name` and is the span name the dispatcher opens.
1544
1771
  */
1545
1772
  let compose_counter = 0;
1773
+ /**
1774
+ * Generate a unique step id of the form `<name>_<n>`, using the user-supplied
1775
+ * label so compose ids read naturally in traces.
1776
+ */
1546
1777
  function next_id$1(name) {
1547
1778
  compose_counter += 1;
1548
1779
  return `${name}_${compose_counter}`;
1549
1780
  }
1781
+ /**
1782
+ * Wrap `inner` in a named composite step.
1783
+ *
1784
+ * The step's `kind` is always `'compose'`; `name` becomes the
1785
+ * `display_name` used as the span label. Throws a `TypeError` when `name`
1786
+ * is not a non-empty string, catching the mistake at construction time.
1787
+ */
1550
1788
  function compose(name, inner) {
1551
1789
  if (typeof name !== "string" || name.length === 0) throw new TypeError("compose(name, inner): name must be a non-empty string");
1552
1790
  const id = next_id$1(name);
@@ -1570,17 +1808,27 @@ register_traced_kind("compose");
1570
1808
  * value. On a miss, runs `inner`, persists its result at `key`, and returns
1571
1809
  * it. Corrupted reads (store throws on `get`) are treated as a miss.
1572
1810
  *
1573
- * Fail-fast (constraints.md §7 invariant 8, spec.md §9 F6): wrapping an
1574
- * anonymous inner step throws synchronously at construction time with the
1575
- * message `checkpoint requires a named step; got anonymous`.
1576
- *
1577
- * See spec.md §5.14, §6.3.
1811
+ * Wrapping an anonymous inner step throws synchronously at construction time
1812
+ * with the message `checkpoint requires a named step; got anonymous`, because
1813
+ * a cached result must map back to a stable, identifiable step.
1578
1814
  */
1579
1815
  let checkpoint_counter = 0;
1816
+ /**
1817
+ * Generate a unique step id of the form `checkpoint_<n>`.
1818
+ */
1580
1819
  function next_id() {
1581
1820
  checkpoint_counter += 1;
1582
1821
  return `checkpoint_${checkpoint_counter}`;
1583
1822
  }
1823
+ /**
1824
+ * Wrap `inner` with persist-and-resume behavior keyed by `config.key`.
1825
+ *
1826
+ * `key` is a fixed string or a function of the input. Without a
1827
+ * `checkpoint_store` on the run context, the wrapper runs `inner` directly.
1828
+ * A stored `null` or `undefined` counts as a miss, so those values are
1829
+ * re-computed rather than replayed. Throws at construction time when `inner`
1830
+ * is anonymous.
1831
+ */
1584
1832
  function checkpoint(inner, config) {
1585
1833
  if (inner.anonymous === true) throw new Error("checkpoint requires a named step; got anonymous");
1586
1834
  const id = next_id();
@@ -1626,9 +1874,13 @@ register_traced_kind("checkpoint");
1626
1874
  * with `run_options.resume_data[id]` populated), the provided value is
1627
1875
  * validated against `resume_schema` and passed to `combine(input, resume,
1628
1876
  * ctx)`; the result is returned. Invalid resume data throws
1629
- * `resume_validation_error` built from zod 4's `.flatten()` (spec.md §9 F5).
1877
+ * `resume_validation_error` built from zod 4's flattened issue format.
1878
+ */
1879
+ /**
1880
+ * Structurally detect a `Step` returned from `combine`.
1630
1881
  *
1631
- * See spec.md §5.15, §6.4.
1882
+ * `combine` may return either a plain value or a Step to dispatch; this local
1883
+ * check distinguishes the two without importing the shared helper.
1632
1884
  */
1633
1885
  function is_step(value) {
1634
1886
  if (typeof value !== "object" || value === null) return false;
@@ -1636,6 +1888,14 @@ function is_step(value) {
1636
1888
  const { id, kind, run } = value;
1637
1889
  return typeof id === "string" && typeof kind === "string" && typeof run === "function";
1638
1890
  }
1891
+ /**
1892
+ * Build a human-in-the-loop pause step.
1893
+ *
1894
+ * First run fires the `on` side effect and throws `suspended_error`; a resume
1895
+ * run validates `resume_data[id]` against `resume_schema` and feeds it to
1896
+ * `combine`. The step's id is the user-supplied suspend id so resume data can
1897
+ * be addressed to it.
1898
+ */
1639
1899
  function suspend(config) {
1640
1900
  const suspend_id = config.id;
1641
1901
  const on_fn = config.on;
@@ -1679,29 +1939,49 @@ register_traced_kind("suspend");
1679
1939
  * writes only affect the inner map.
1680
1940
  *
1681
1941
  * Using `stash` or `use` outside a `scope` is a runtime error with a clear
1682
- * message (spec.md §9 F1).
1683
- *
1684
- * See spec.md §5.16.
1942
+ * message.
1685
1943
  */
1686
1944
  const scope_states = /* @__PURE__ */ new WeakSet();
1945
+ /**
1946
+ * Check whether a state map was created by `scope`.
1947
+ *
1948
+ * The root `RunContext.state` map is not registered in `scope_states`, which
1949
+ * is how `stash`/`use` detect they are running outside any scope.
1950
+ */
1687
1951
  function is_scope_state(state) {
1688
1952
  return scope_states.has(state);
1689
1953
  }
1690
1954
  let scope_counter = 0;
1691
1955
  let stash_counter = 0;
1692
1956
  let use_counter = 0;
1957
+ /**
1958
+ * Generate a unique step id of the form `scope_<n>`.
1959
+ */
1693
1960
  function next_scope_id() {
1694
1961
  scope_counter += 1;
1695
1962
  return `scope_${scope_counter}`;
1696
1963
  }
1964
+ /**
1965
+ * Generate a unique step id of the form `stash_<n>`.
1966
+ */
1697
1967
  function next_stash_id() {
1698
1968
  stash_counter += 1;
1699
1969
  return `stash_${stash_counter}`;
1700
1970
  }
1971
+ /**
1972
+ * Generate a unique step id of the form `use_<n>`.
1973
+ */
1701
1974
  function next_use_id() {
1702
1975
  use_counter += 1;
1703
1976
  return `use_${use_counter}`;
1704
1977
  }
1978
+ /**
1979
+ * Build a step that runs children in sequence under a fresh state map.
1980
+ *
1981
+ * The local map is seeded from the parent state (inner scopes read outer
1982
+ * values) and registered so `stash`/`use` inside recognize it; writes stay
1983
+ * local to this scope. Outputs chain like `sequence`.
1984
+ */
1705
1985
  function scope(children, options) {
1706
1986
  const id = next_scope_id();
1707
1987
  const children_ref = children;
@@ -1728,6 +2008,12 @@ function scope(children, options) {
1728
2008
  run: run_fn
1729
2009
  };
1730
2010
  }
2011
+ /**
2012
+ * Build a step that stores its source's output in scope state at `key`.
2013
+ *
2014
+ * Passes the value through unchanged so it composes mid-chain. Throws when
2015
+ * run outside a `scope`.
2016
+ */
1731
2017
  function stash(key, source, options) {
1732
2018
  const id = next_stash_id();
1733
2019
  const run_fn = async (input, ctx) => {
@@ -1746,6 +2032,12 @@ function stash(key, source, options) {
1746
2032
  run: run_fn
1747
2033
  };
1748
2034
  }
2035
+ /**
2036
+ * Build a step that projects named scope values into a function call.
2037
+ *
2038
+ * Reads `keys` from scope state (missing keys project as `undefined`) and
2039
+ * invokes `fn(projection, input, ctx)`. Throws when run outside a `scope`.
2040
+ */
1749
2041
  function use(keys, fn, options) {
1750
2042
  const id = next_use_id();
1751
2043
  const run_fn = async (input, ctx) => {
@@ -1771,7 +2063,7 @@ register_traced_kind("use");
1771
2063
  /**
1772
2064
  * Closed registry of every `Step.kind` produced by the composition layer.
1773
2065
  *
1774
- * Studio (and any other consumer that needs to enumerate primitives — palette,
2066
+ * Studio (and any other consumer that needs to enumerate primitives: palette,
1775
2067
  * docs, code generation) can rely on this being the exhaustive set. New
1776
2068
  * primitives must add their kind here. The `step_kinds_cover_runner` contract
1777
2069
  * test in `step_kinds.test.ts` asserts every dispatch handler corresponds to a
@@ -1799,6 +2091,9 @@ const STEP_KINDS = [
1799
2091
  "stash",
1800
2092
  "use"
1801
2093
  ];
2094
+ /**
2095
+ * Check whether a value is one of the registered `Step.kind` strings.
2096
+ */
1802
2097
  function is_step_kind(value) {
1803
2098
  return typeof value === "string" && STEP_KINDS.includes(value);
1804
2099
  }
@@ -1857,4 +2152,4 @@ const trajectory_event_schema = z.union([
1857
2152
  //#endregion
1858
2153
  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 };
1859
2154
 
1860
- //# sourceMappingURL=core-CYpxskeT.js.map
2155
+ //# sourceMappingURL=core-DNH8ddMT.js.map