fascicle 0.11.1 → 0.12.1

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.
@@ -35,6 +35,7 @@ var flow_schema_default = {
35
35
  { "required": ["checkpoint"] },
36
36
  { "required": ["suspend"] },
37
37
  { "required": ["scope"] },
38
+ { "required": ["chain"] },
38
39
  { "required": ["ref"] }
39
40
  ],
40
41
  "properties": {
@@ -56,6 +57,7 @@ var flow_schema_default = {
56
57
  "checkpoint": { "$ref": "#/$defs/checkpoint_config" },
57
58
  "suspend": { "$ref": "#/$defs/suspend_config" },
58
59
  "scope": { "$ref": "#/$defs/scope_config" },
60
+ "chain": { "$ref": "#/$defs/chain_config" },
59
61
  "ref": { "type": "string" }
60
62
  }
61
63
  },
@@ -281,6 +283,36 @@ var flow_schema_default = {
281
283
  "do": { "$ref": "#/$defs/node" }
282
284
  }
283
285
  }]
286
+ },
287
+ "chain_config": {
288
+ "type": "object",
289
+ "required": ["steps", "output"],
290
+ "properties": {
291
+ "input": { "type": "string" },
292
+ "steps": {
293
+ "type": "array",
294
+ "items": { "$ref": "#/$defs/chain_entry" }
295
+ },
296
+ "output": { "type": "string" }
297
+ }
298
+ },
299
+ "chain_entry": {
300
+ "type": "object",
301
+ "oneOf": [{
302
+ "type": "object",
303
+ "required": ["step", "fn"],
304
+ "properties": {
305
+ "step": { "type": "string" },
306
+ "fn": { "type": "string" }
307
+ }
308
+ }, {
309
+ "type": "object",
310
+ "required": ["stage"],
311
+ "properties": {
312
+ "stage": { "type": "string" },
313
+ "project": { "type": "string" }
314
+ }
315
+ }]
284
316
  }
285
317
  }
286
318
  };
@@ -404,7 +436,7 @@ var aborted_error = class extends Error {
404
436
  super(message);
405
437
  this.name = "aborted_error";
406
438
  if (metadata.reason !== void 0) this.reason = metadata.reason;
407
- this.step_index = metadata.step_index ?? 0;
439
+ if (metadata.step_index !== void 0) this.step_index = metadata.step_index;
408
440
  if (metadata.tool_call_in_flight !== void 0) this.tool_call_in_flight = metadata.tool_call_in_flight;
409
441
  }
410
442
  };
@@ -420,6 +452,23 @@ var aborted_error = class extends Error {
420
452
  function is_control_flow_error(err) {
421
453
  return err instanceof suspended_error || err instanceof aborted_error;
422
454
  }
455
+ /**
456
+ * Read the step-id path off any error that crossed the runner's dispatch.
457
+ *
458
+ * The runner attaches `path` to whatever escapes a step, including
459
+ * user-thrown errors the declared class fields cannot type, so a catch block
460
+ * needs a narrowing read rather than a cast. Returns the ids only when the
461
+ * property is present and well-formed (an all-string array); anything else,
462
+ * including non-object inputs, is `undefined`.
463
+ */
464
+ function error_path(err) {
465
+ if (err === null || typeof err !== "object") return void 0;
466
+ const path = Reflect.get(err, "path");
467
+ if (!Array.isArray(path)) return void 0;
468
+ const entries = path;
469
+ const ids = entries.filter((v) => typeof v === "string");
470
+ return ids.length === entries.length ? ids : void 0;
471
+ }
423
472
  //#endregion
424
473
  //#region src/core/streaming.ts
425
474
  const STREAMING_HIGH_WATER_MARK = 1e4;
@@ -598,12 +647,32 @@ function register_traced_kind(kind) {
598
647
  } catch (err) {
599
648
  ctx.trajectory.end_span(span_id, {
600
649
  id: flow.id,
601
- error: err instanceof Error ? err.message : String(err)
650
+ ...error_meta(err)
602
651
  });
603
652
  throw err;
604
653
  }
605
654
  });
606
655
  }
656
+ /**
657
+ * Project an escaping error onto trajectory meta fields.
658
+ *
659
+ * `error` is always present (the message); `error_name` and `error_kind`
660
+ * surface the class name and the `kind` discriminant the typed error classes
661
+ * carry, so a consumer can classify a failure without regex-matching the
662
+ * message. `error_path` is the chain of step ids the error crossed below this
663
+ * point, already accumulated on the error by `prepend_path` as it bubbled up.
664
+ */
665
+ function error_meta(err) {
666
+ const meta = { error: err instanceof Error ? err.message : String(err) };
667
+ if (err instanceof Error && err.name.length > 0) meta["error_name"] = err.name;
668
+ if (err !== null && typeof err === "object") {
669
+ const kind = Reflect.get(err, "kind");
670
+ if (typeof kind === "string") meta["error_kind"] = kind;
671
+ const path = Reflect.get(err, "path");
672
+ if (Array.isArray(path)) meta["error_path"] = path.filter((v) => typeof v === "string");
673
+ }
674
+ return meta;
675
+ }
607
676
  const active_runs = /* @__PURE__ */ new Set();
608
677
  let signal_handler_installed = false;
609
678
  let sigint_handler = null;
@@ -805,6 +874,10 @@ function start_run(flow, input, options, high_water_mark) {
805
874
  on_cleanup: (fn) => {
806
875
  cleanup.register(fn);
807
876
  },
877
+ call(s, child_input) {
878
+ throw_if_aborted(this);
879
+ return dispatch_step(s, child_input, this);
880
+ },
808
881
  checkpoint_store: options.checkpoint_store,
809
882
  resume_data: options.resume_data,
810
883
  streaming
@@ -812,19 +885,27 @@ function start_run(flow, input, options, high_water_mark) {
812
885
  active_runs.add(controller);
813
886
  if (install_signal_handlers) ensure_signal_handlers();
814
887
  const result = (async () => {
888
+ let terminal = {
889
+ kind: "run_end",
890
+ status: "done"
891
+ };
815
892
  try {
816
893
  throw_if_aborted(ctx);
817
894
  return await dispatch_step(flow, input, ctx);
818
895
  } catch (err) {
896
+ let thrown = err;
819
897
  if (controller.signal.aborted && !(err instanceof aborted_error)) {
820
898
  const reason = controller.signal.reason;
821
- if (reason instanceof aborted_error) throw reason;
899
+ if (reason instanceof aborted_error) thrown = reason;
822
900
  }
823
- throw err;
901
+ const was_aborted = thrown instanceof aborted_error || controller.signal.aborted && thrown === controller.signal.reason;
902
+ terminal = run_end_event(thrown, was_aborted);
903
+ throw thrown;
824
904
  } finally {
825
905
  try {
826
906
  await cleanup.run_all();
827
907
  } finally {
908
+ logger.record(terminal);
828
909
  unlink_abort();
829
910
  active_runs.delete(controller);
830
911
  release_signal_handlers();
@@ -838,6 +919,30 @@ function start_run(flow, input, options, high_water_mark) {
838
919
  };
839
920
  }
840
921
  /**
922
+ * Build the terminal `run_end` event for a run that did not complete.
923
+ *
924
+ * Control-flow endings get their own statuses (`aborted`, `suspended`) so a
925
+ * consumer never has to sniff error text to tell a cancellation or a pending
926
+ * approval from a real failure; only `failed` carries the full error meta.
927
+ */
928
+ function run_end_event(err, was_aborted) {
929
+ if (err instanceof suspended_error) return {
930
+ kind: "run_end",
931
+ status: "suspended",
932
+ suspend_id: err.suspend_id
933
+ };
934
+ if (was_aborted) return {
935
+ kind: "run_end",
936
+ status: "aborted",
937
+ error: err instanceof Error ? err.message : String(err)
938
+ };
939
+ return {
940
+ kind: "run_end",
941
+ status: "failed",
942
+ ...error_meta(err)
943
+ };
944
+ }
945
+ /**
841
946
  * Build an async iterable that is immediately done.
842
947
  *
843
948
  * Non-streaming runs hand this to callers so the `events` field always has
@@ -869,14 +974,56 @@ function run_stream(flow, input, options = {}) {
869
974
  };
870
975
  }
871
976
  /**
977
+ * Execute a flow, reporting suspension as a typed outcome instead of a
978
+ * thrown `suspended_error`.
979
+ *
980
+ * Resolves `{ kind: 'done', output }` on completion. When a `suspend` gate
981
+ * fires, resolves `{ kind: 'suspended', id, payload, resume }` where `id` is
982
+ * the gate's suspend id, `payload` is what the gate raised on its
983
+ * `suspended_error`, and `resume(data)` re-runs the flow from the original
984
+ * input with `resume_data[id] = data` merged over the caller's options: the
985
+ * same full re-run semantics as calling `run` again yourself, so pure
986
+ * prefixes replay and `checkpoint`ed steps are served from the store. The
987
+ * returned promise resolves to the next outcome, so a flow with several
988
+ * gates is driven by awaiting `resume` repeatedly. Real errors still throw,
989
+ * from the initial call and from `resume` alike.
990
+ */
991
+ async function run_until_suspended(flow, input, options = {}) {
992
+ try {
993
+ return {
994
+ kind: "done",
995
+ output: await run_impl(flow, input, options)
996
+ };
997
+ } catch (err) {
998
+ if (!(err instanceof suspended_error)) throw err;
999
+ const id = err.suspend_id;
1000
+ return {
1001
+ kind: "suspended",
1002
+ id,
1003
+ payload: err.payload,
1004
+ resume: (data) => run_until_suspended(flow, input, {
1005
+ ...options,
1006
+ resume_data: {
1007
+ ...options.resume_data,
1008
+ [id]: data
1009
+ }
1010
+ })
1011
+ };
1012
+ }
1013
+ }
1014
+ /**
872
1015
  * The public entry point for executing a flow.
873
1016
  *
874
- * Callable as `run(flow, input, options?)` for a plain result, or
875
- * `run.stream(flow, input, options?)` for `{ events, result }`. Both share
876
- * one implementation, so a streamed run and a plain run of the same flow
877
- * produce identical output.
1017
+ * Callable as `run(flow, input, options?)` for a plain result,
1018
+ * `run.stream(flow, input, options?)` for `{ events, result }`, or
1019
+ * `run.until_suspended(flow, input, options?)` for a `RunOutcome` that
1020
+ * carries suspension as data. All share one implementation, so every entry
1021
+ * point runs the same graph identically.
878
1022
  */
879
- const run = Object.assign(run_impl, { stream: run_stream });
1023
+ const run = Object.assign(run_impl, {
1024
+ stream: run_stream,
1025
+ until_suspended: run_until_suspended
1026
+ });
880
1027
  //#endregion
881
1028
  //#region src/core/step.ts
882
1029
  /**
@@ -887,22 +1034,22 @@ const run = Object.assign(run_impl, { stream: run_stream });
887
1034
  * step(id, fn, meta): named step with optional human-readable metadata for studio,
888
1035
  * codegen, and similar consumers. `meta` is purely descriptive
889
1036
  * and never affects runtime semantics.
890
- * step(fn): anonymous step. id is `anon_<counter>`; cannot be checkpointed.
1037
+ * step(fn): anonymous step. id is `step_<counter>`; cannot be checkpointed.
891
1038
  *
892
1039
  * Anonymous steps carry an internal `anonymous: true` flag so checkpoint can
893
1040
  * reject them synchronously at flow construction time.
894
1041
  */
895
- let anon_counter = 0;
1042
+ let step_counter = 0;
896
1043
  /**
897
- * Generate a unique id of the form `anon_<n>` for anonymous steps.
1044
+ * Generate a unique id of the form `step_<n>` for anonymous steps.
898
1045
  */
899
- function next_anon_id() {
900
- anon_counter += 1;
901
- return `anon_${anon_counter}`;
1046
+ function next_step_id() {
1047
+ step_counter += 1;
1048
+ return `step_${step_counter}`;
902
1049
  }
903
1050
  function step(id_or_fn, maybe_fn, meta) {
904
1051
  if (typeof id_or_fn === "function") return {
905
- id: next_anon_id(),
1052
+ id: next_step_id(),
906
1053
  kind: "step",
907
1054
  run: id_or_fn,
908
1055
  anonymous: true
@@ -1182,6 +1329,17 @@ function is_renderable_object(value) {
1182
1329
  * `sequence([a, b, c])` runs a, b, c in declared order. The input to sequence
1183
1330
  * is passed to the first child; each subsequent child receives the previous
1184
1331
  * child's output. The composer returns the last child's output.
1332
+ *
1333
+ * For a literal tuple of children, every joint is checked at compile time:
1334
+ * each child after the first must accept its predecessor's output, and a
1335
+ * mismatch resolves the offending element to a branded SequenceJointMismatch
1336
+ * so the error names the joint and both types. A spread segment inside a
1337
+ * tuple (`sequence([first, ...mids, last])`) is checked as a homogeneous
1338
+ * self-composing segment rather than index-zipped, since its positions are
1339
+ * not statically known. Arrays built at runtime carry no positional types,
1340
+ * so they must be homogeneous `ReadonlyArray<Step<T, T>>` and produce a
1341
+ * `Step<T, T>`; heterogeneous runtime arrays are rejected rather than
1342
+ * silently degrading to `Step<unknown, unknown>`.
1185
1343
  */
1186
1344
  let sequence_counter = 0;
1187
1345
  /**
@@ -1191,13 +1349,6 @@ function next_id$10() {
1191
1349
  sequence_counter += 1;
1192
1350
  return `sequence_${sequence_counter}`;
1193
1351
  }
1194
- /**
1195
- * Build a step that chains children, each feeding the next.
1196
- *
1197
- * Validates every element up front so a non-Step (usually a bare function)
1198
- * fails at construction with a pointed message rather than at run time.
1199
- * Checks `ctx.abort` before each child so aborts land on step boundaries.
1200
- */
1201
1352
  function sequence(children, options) {
1202
1353
  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])`);
1203
1354
  children.forEach((child, index) => {
@@ -1218,7 +1369,7 @@ function sequence(children, options) {
1218
1369
  return {
1219
1370
  id,
1220
1371
  kind: "sequence",
1221
- children,
1372
+ children: children_ref,
1222
1373
  ...config_meta ? { config: config_meta } : {},
1223
1374
  run: run_fn
1224
1375
  };
@@ -1316,10 +1467,11 @@ function pick_error(settled) {
1316
1467
  /**
1317
1468
  * Build a step that runs named children concurrently on the same input.
1318
1469
  *
1319
- * Returns an object keyed by child name. All children settle before any
1320
- * error propagates; a `suspended_error` wins over application errors so a
1321
- * human-approval gate stays resumable instead of being masked by a sibling's
1322
- * failure.
1470
+ * The step's input type is the intersection of the children's inputs, since
1471
+ * every child receives the input verbatim. Returns an object keyed by child
1472
+ * name. All children settle before any error propagates; a `suspended_error`
1473
+ * wins over application errors so a human-approval gate stays resumable
1474
+ * instead of being masked by a sibling's failure.
1323
1475
  */
1324
1476
  function parallel(members, options) {
1325
1477
  const id = next_id$9();
@@ -1634,6 +1786,7 @@ function to_abort_error(reason) {
1634
1786
  * control-flow signals propagate untouched.
1635
1787
  */
1636
1788
  function retry(inner, config) {
1789
+ if (!Number.isFinite(config.max_attempts)) throw new TypeError(`retry: max_attempts must be a finite number, got ${config.max_attempts}`);
1637
1790
  const id = next_id$5();
1638
1791
  const max_attempts = Math.max(1, Math.floor(config.max_attempts));
1639
1792
  const backoff_ms = config.backoff_ms ?? DEFAULT_BACKOFF_MS;
@@ -1659,7 +1812,7 @@ function retry(inner, config) {
1659
1812
  await wait_with_abort(compute_backoff(backoff_policy, attempt - 1), ctx.abort, to_abort_error);
1660
1813
  }
1661
1814
  }
1662
- throw last_err;
1815
+ throw last_err ?? /* @__PURE__ */ new Error("retry: no attempts executed");
1663
1816
  };
1664
1817
  const config_meta = {
1665
1818
  max_attempts,
@@ -1686,7 +1839,9 @@ register_traced_kind("retry");
1686
1839
  * `fallback(primary, backup)` runs `primary`. If it throws an application
1687
1840
  * error, runs `backup` with the same input, or with `handoff(input, err)`
1688
1841
  * when the `handoff` option is set, so the backup can be told why it is
1689
- * running. If `backup` also throws, the `backup` error propagates.
1842
+ * running. If `backup` also throws, the `backup` error propagates with the
1843
+ * primary's error attached as its `cause` (unless it already carries one),
1844
+ * so the original failure stays diagnosable from the escaping error.
1690
1845
  * Control-flow signals (`suspended_error`, `aborted_error`) are not
1691
1846
  * failures: they propagate instead of triggering the backup, so a
1692
1847
  * human-approval gate is never silently bypassed and the backup never runs
@@ -1715,7 +1870,13 @@ function fallback(primary, backup, options) {
1715
1870
  return await dispatch_step(primary, input, ctx);
1716
1871
  } catch (err) {
1717
1872
  if (is_control_flow_error(err)) throw err;
1718
- return dispatch_step(backup, handoff === void 0 ? input : handoff(input, err), ctx);
1873
+ const backup_input = handoff === void 0 ? input : handoff(input, err);
1874
+ try {
1875
+ return await dispatch_step(backup, backup_input, ctx);
1876
+ } catch (backup_err) {
1877
+ if (!is_control_flow_error(backup_err) && backup_err instanceof Error && !("cause" in backup_err)) backup_err.cause = err;
1878
+ throw backup_err;
1879
+ }
1719
1880
  }
1720
1881
  };
1721
1882
  const config_meta = options?.name === void 0 ? void 0 : { display_name: options.name };
@@ -1813,7 +1974,9 @@ register_traced_kind("timeout");
1813
1974
  * `loop({ init, body, guard?, finish, max_rounds, name? })` runs `body` up to
1814
1975
  * `max_rounds` times, threading `state` through each iteration. After every
1815
1976
  * `body` call, an optional `guard` step inspects (and may transform) the state
1816
- * and decides whether to stop. When `guard.stop` is true, the loop exits
1977
+ * and decides whether to stop; a bare `(state) => boolean` predicate is
1978
+ * accepted as shorthand for a guard that stops without transforming.
1979
+ * When `guard.stop` is true, the loop exits
1817
1980
  * "converged"; otherwise it continues until `max_rounds`. `finish` projects
1818
1981
  * the final state to the loop's output value, and is the loop's only output
1819
1982
  * channel: `loop` returns `Step<i, o>`, not an envelope around `o`.
@@ -1838,6 +2001,22 @@ function next_id$2(name) {
1838
2001
  return `${name ?? "loop"}_${loop_counter}`;
1839
2002
  }
1840
2003
  /**
2004
+ * Normalize the guard config to its step form.
2005
+ *
2006
+ * A bare predicate is sugar for the state-preserving guard step, wrapped here
2007
+ * (with an id derived from the loop's, so trees with several loops stay
2008
+ * unambiguous) rather than special-cased in the run loop: the predicate form
2009
+ * then dispatches, traces, and terminates identically to a hand-written guard.
2010
+ */
2011
+ function wrap_guard(guard, loop_id) {
2012
+ if (guard === void 0) return void 0;
2013
+ if (typeof guard !== "function") return guard;
2014
+ return step(`${loop_id}_guard`, async (state) => ({
2015
+ stop: await guard(state),
2016
+ state
2017
+ }));
2018
+ }
2019
+ /**
1841
2020
  * Build a bounded iteration step with carry-state.
1842
2021
  *
1843
2022
  * Threads `state` through up to `max_rounds` runs of `body`, lets the
@@ -1847,9 +2026,10 @@ function next_id$2(name) {
1847
2026
  * its output.
1848
2027
  */
1849
2028
  function loop(config) {
1850
- const { init, body, guard, finish, name } = config;
2029
+ const { init, body, finish, name } = config;
1851
2030
  const rounds_limit = Math.max(1, Math.floor(config.max_rounds));
1852
2031
  const id = next_id$2(name);
2032
+ const guard = wrap_guard(config.guard, id);
1853
2033
  const run_fn = async (input, ctx) => {
1854
2034
  let state = init(input);
1855
2035
  let round = 0;
@@ -1938,7 +2118,9 @@ register_traced_kind("compose");
1938
2118
  * `checkpoint(inner, { key })` checks a persistent store for a completed
1939
2119
  * result at `key` before running `inner`. On a hit, returns the stored
1940
2120
  * value. On a miss, runs `inner`, persists its result at `key`, and returns
1941
- * it. Corrupted reads (store throws on `get`) are treated as a miss.
2121
+ * it. Corrupted reads (store throws on `get`) are treated as a miss. Every
2122
+ * lookup records a `checkpoint` trajectory event with
2123
+ * `status: 'hit' | 'miss' | 'read_error'`.
1942
2124
  *
1943
2125
  * Wrapping an anonymous inner step throws synchronously at construction time
1944
2126
  * with the message `checkpoint requires a named step; got anonymous`, because
@@ -1971,11 +2153,27 @@ function checkpoint(inner, config) {
1971
2153
  if (store) {
1972
2154
  let cached = void 0;
1973
2155
  let hit = false;
2156
+ const lookup_meta = {
2157
+ id,
2158
+ key
2159
+ };
2160
+ if (ctx.parent_span_id !== void 0) lookup_meta["span_id"] = ctx.parent_span_id;
1974
2161
  try {
1975
2162
  cached = await store.get(key);
1976
2163
  hit = cached !== null && cached !== void 0;
1977
- } catch {
2164
+ ctx.trajectory.record({
2165
+ kind: "checkpoint",
2166
+ status: hit ? "hit" : "miss",
2167
+ ...lookup_meta
2168
+ });
2169
+ } catch (err) {
1978
2170
  hit = false;
2171
+ ctx.trajectory.record({
2172
+ kind: "checkpoint",
2173
+ status: "read_error",
2174
+ error: err instanceof Error ? err.message : String(err),
2175
+ ...lookup_meta
2176
+ });
1979
2177
  }
1980
2178
  if (hit) return cached;
1981
2179
  }
@@ -2233,6 +2431,193 @@ register_traced_kind("scope");
2233
2431
  register_traced_kind("stash");
2234
2432
  register_traced_kind("use");
2235
2433
  //#endregion
2434
+ //#region src/core/chain.ts
2435
+ /**
2436
+ * chain: named steps over a growing record.
2437
+ *
2438
+ * `chain<i>(input_name?)` opens a builder whose threaded value is a record of
2439
+ * named outputs rather than a single value. The input type must be stated,
2440
+ * either as the type argument or via `.input<t>()` on the freshly opened
2441
+ * chain; an unannotated `chain()` defaults to `never` so the omission fails
2442
+ * at the `run` call site instead of accepting anything. `.step(name, fn)`
2443
+ * runs `fn` over the record and merges its output back in under `name`;
2444
+ * `.stage(name, project?)` concludes a phase: it opens a grouping span in
2445
+ * the trajectory and, when `project` is given, replaces the record with the
2446
+ * projection so earlier bindings go out of scope; `.output(fn)` closes the
2447
+ * builder and returns an ordinary `Step<i, o>`.
2448
+ *
2449
+ * Each `.step` entry is a regular `step(name, fn)` whose input happens to be
2450
+ * the record, so anything true of steps (spans, error paths, abort checks
2451
+ * between entries) is true of chain entries, and the binding name doubles as
2452
+ * the entry's id in trajectories. A binding whose whole job is to invoke an
2453
+ * arm is `.step(name, arm, select)`: the chain projects the record through
2454
+ * `select`, dispatches the arm via `ctx.call`, and records it as the
2455
+ * binding's child, so what `describe` renders and what runs cannot diverge.
2456
+ * The escape hatch for bodies that need code around the call is
2457
+ * `.step(name, fn, { arm })`: the body does its own `ctx.call` and the arm
2458
+ * is metadata only, recorded for `describe` but never dispatched.
2459
+ *
2460
+ * Builder values are immutable: every method returns a new chain, so a
2461
+ * prefix can be shared and extended in different directions safely.
2462
+ */
2463
+ let chain_counter = 0;
2464
+ /**
2465
+ * Generate a unique step id of the form `chain_<n>`.
2466
+ */
2467
+ function next_chain_id() {
2468
+ chain_counter += 1;
2469
+ return `chain_${chain_counter}`;
2470
+ }
2471
+ /**
2472
+ * Assemble the runnable chain Step from its entries and output node.
2473
+ *
2474
+ * Runs entries in order over a record seeded with the input under
2475
+ * `input_name`. Step entries merge their output under their name; stage
2476
+ * entries end the previous stage span, open a new one that subsequent
2477
+ * entries nest under, and, when projecting, replace the record. The output
2478
+ * node runs last and its value is the chain's output. `config.plan` lists
2479
+ * the entry names in order so `describe` shows the topology without running.
2480
+ *
2481
+ * The `Step<unknown, unknown>` return is the concrete type, not an erased
2482
+ * top type: the run function genuinely accepts any input, seeding the record
2483
+ * with whatever arrives. The typed `chain` surface narrows it at the cast.
2484
+ */
2485
+ function build_chain(input_name, entries, output_node) {
2486
+ const id = next_chain_id();
2487
+ const plan = [...entries.map((e) => e.kind === "stage" ? `stage:${e.name}` : e.name), "output"];
2488
+ const children = [...entries.flatMap((e) => e.kind === "step" ? [e.node] : []), output_node];
2489
+ const run_fn = async (input, ctx) => {
2490
+ let record = { [input_name]: input };
2491
+ let current_ctx = ctx;
2492
+ let stage_span;
2493
+ let stage_id;
2494
+ const end_stage = (error) => {
2495
+ if (stage_span === void 0) return;
2496
+ const meta = { id: stage_id };
2497
+ if (error !== void 0) meta["error"] = error;
2498
+ ctx.trajectory.end_span(stage_span, meta);
2499
+ stage_span = void 0;
2500
+ };
2501
+ try {
2502
+ for (const entry of entries) {
2503
+ throw_if_aborted(current_ctx);
2504
+ if (entry.kind === "stage") {
2505
+ end_stage();
2506
+ stage_id = `stage:${entry.name}`;
2507
+ const meta = { id: stage_id };
2508
+ if (ctx.parent_span_id !== void 0) meta["parent_span_id"] = ctx.parent_span_id;
2509
+ stage_span = ctx.trajectory.start_span(entry.name, meta);
2510
+ current_ctx = {
2511
+ ...ctx,
2512
+ parent_span_id: stage_span
2513
+ };
2514
+ if (entry.project !== void 0) record = await entry.project(record, current_ctx);
2515
+ } else {
2516
+ const value = await dispatch_step(entry.node, record, current_ctx);
2517
+ record = {
2518
+ ...record,
2519
+ [entry.name]: value
2520
+ };
2521
+ }
2522
+ }
2523
+ throw_if_aborted(current_ctx);
2524
+ const out = await dispatch_step(output_node, record, current_ctx);
2525
+ end_stage();
2526
+ return out;
2527
+ } catch (err) {
2528
+ end_stage(err instanceof Error ? err.message : String(err));
2529
+ throw err;
2530
+ }
2531
+ };
2532
+ return {
2533
+ id,
2534
+ kind: "chain",
2535
+ children,
2536
+ config: {
2537
+ input: input_name,
2538
+ plan
2539
+ },
2540
+ run: run_fn
2541
+ };
2542
+ }
2543
+ /**
2544
+ * Build the binding node for the arm-first `.step(name, arm, select)` form.
2545
+ *
2546
+ * The chain owns the dispatch: the synthesized body projects the record
2547
+ * through `select` and hands the result to the arm via `ctx.call`, and the
2548
+ * same arm is recorded as the binding's child, so the subtree `describe`
2549
+ * renders and the step that runs are one value by construction.
2550
+ */
2551
+ function arm_node(name, arm, select) {
2552
+ if (typeof select !== "function") throw new TypeError("chain.step(name, arm, select): select must be a function");
2553
+ return {
2554
+ ...step(name, (s, ctx) => ctx.call(arm, select(s))),
2555
+ children: [arm]
2556
+ };
2557
+ }
2558
+ /**
2559
+ * Build the binding node for the body form `.step(name, fn, { arm? })`.
2560
+ */
2561
+ function body_node(name, fn, options) {
2562
+ const base = step(name, fn);
2563
+ const arm = typeof options === "function" ? void 0 : options?.arm;
2564
+ return arm === void 0 ? base : {
2565
+ ...base,
2566
+ children: [arm]
2567
+ };
2568
+ }
2569
+ /**
2570
+ * Internal untyped builder behind `chain`.
2571
+ *
2572
+ * `bound` holds the binding names of the current stage segment so duplicate
2573
+ * names fail at build time (the typed surface would silently intersect
2574
+ * them); a projecting stage resets it because the projection's keys are only
2575
+ * known to the type system.
2576
+ */
2577
+ function make_chain(input_name, entries, bound) {
2578
+ return {
2579
+ step: (name, fn_or_arm, options_or_select) => {
2580
+ if (bound.has(name)) throw new TypeError(`chain.step: binding '${name}' is already defined in this stage; names are single-assignment`);
2581
+ const node = is_step(fn_or_arm) ? arm_node(name, fn_or_arm, options_or_select) : body_node(name, fn_or_arm, options_or_select);
2582
+ return make_chain(input_name, [...entries, {
2583
+ kind: "step",
2584
+ name,
2585
+ node
2586
+ }], /* @__PURE__ */ new Set([...bound, name]));
2587
+ },
2588
+ stage: (name, project) => make_chain(input_name, [...entries, project === void 0 ? {
2589
+ kind: "stage",
2590
+ name
2591
+ } : {
2592
+ kind: "stage",
2593
+ name,
2594
+ project
2595
+ }], project === void 0 ? bound : /* @__PURE__ */ new Set()),
2596
+ output: (fn) => build_chain(input_name, entries, step("output", fn))
2597
+ };
2598
+ }
2599
+ /**
2600
+ * Open a chain builder whose record starts as `{ [input_name]: input }`.
2601
+ *
2602
+ * `input_name` defaults to `'input'`. The input type defaults to `never`, so
2603
+ * a chain that never states it produces a `Step<never, o>` that no real
2604
+ * input satisfies at `run`; state it as the type argument or, when the
2605
+ * binding is renamed, once via `.input<t>()` on the fresh builder. Each
2606
+ * `.step` narrows subsequent callbacks to the record accumulated so far, and
2607
+ * `.stage` with a projection re-types the record to the projection's
2608
+ * return, so binding names and views are checked at compile time with no
2609
+ * declared state shape.
2610
+ */
2611
+ function chain(input_name) {
2612
+ const name = input_name ?? "input";
2613
+ const open = make_chain(name, [], /* @__PURE__ */ new Set([name]));
2614
+ return {
2615
+ ...open,
2616
+ input: () => open
2617
+ };
2618
+ }
2619
+ register_traced_kind("chain");
2620
+ //#endregion
2236
2621
  //#region src/core/step_kinds.ts
2237
2622
  /**
2238
2623
  * Closed registry of every `Step.kind` produced by the composition layer.
@@ -2263,7 +2648,8 @@ const STEP_KINDS = [
2263
2648
  "suspend",
2264
2649
  "scope",
2265
2650
  "stash",
2266
- "use"
2651
+ "use",
2652
+ "chain"
2267
2653
  ];
2268
2654
  /**
2269
2655
  * Check whether a value is one of the registered `Step.kind` strings.
@@ -2299,6 +2685,40 @@ function is_span_end_event(value) {
2299
2685
  function is_emit_event(value) {
2300
2686
  return is_custom_trajectory_event(value) && value.kind === "emit";
2301
2687
  }
2688
+ const RUN_END_STATUSES = /* @__PURE__ */ new Set([
2689
+ "done",
2690
+ "failed",
2691
+ "aborted",
2692
+ "suspended"
2693
+ ]);
2694
+ /**
2695
+ * A terminal run event: `status` must be one of the known run outcomes, so the
2696
+ * narrowed type's `status` union is truthful. An unknown future status still
2697
+ * passes the wire gate as a custom event.
2698
+ */
2699
+ function is_run_end_event(value) {
2700
+ if (!is_custom_trajectory_event(value)) return false;
2701
+ if (value.kind !== "run_end") return false;
2702
+ const status = value["status"];
2703
+ return typeof status === "string" && RUN_END_STATUSES.has(status);
2704
+ }
2705
+ const CHECKPOINT_STATUSES = /* @__PURE__ */ new Set([
2706
+ "hit",
2707
+ "miss",
2708
+ "read_error"
2709
+ ]);
2710
+ /**
2711
+ * A checkpoint lookup event: `status` must be a known lookup outcome and `key`
2712
+ * the store key that was consulted, for the same truthful-narrowing reason as
2713
+ * `is_run_end_event`.
2714
+ */
2715
+ function is_checkpoint_event(value) {
2716
+ if (!is_custom_trajectory_event(value)) return false;
2717
+ if (value.kind !== "checkpoint") return false;
2718
+ const status = value["status"];
2719
+ if (typeof status !== "string" || !CHECKPOINT_STATUSES.has(status)) return false;
2720
+ return typeof value["key"] === "string";
2721
+ }
2302
2722
  /**
2303
2723
  * Parse one wire value into a trajectory event, `safeParse`-shaped.
2304
2724
  *
@@ -2327,6 +2747,6 @@ function parse_trajectory_event(value) {
2327
2747
  * and surface through the umbrella package.
2328
2748
  */
2329
2749
  //#endregion
2330
- export { aborted_error as A, map as C, describe as D, sequence as E, flow_schema_default as F, resume_validation_error as M, suspended_error as N, step as O, timeout_error as P, pipe as S, parallel as T, timeout as _, parse_trajectory_event as a, compute_backoff as b, scope as c, suspend as d, format_schema_issues as f, loop as g, compose as h, is_span_start_event as i, describe_cycle_error as j, run as k, stash as l, checkpoint as m, is_emit_event as n, STEP_KINDS as o, validate_schema as p, is_span_end_event as r, is_step_kind as s, is_custom_trajectory_event as t, use as u, fallback as v, branch as w, wait_with_abort as x, retry as y };
2750
+ export { describe as A, flow_schema_default as B, compute_backoff as C, branch as D, map as E, describe_cycle_error as F, error_path as I, resume_validation_error as L, step as M, run as N, parallel as O, aborted_error as P, suspended_error as R, retry as S, pipe as T, checkpoint as _, is_span_end_event as a, timeout as b, STEP_KINDS as c, scope as d, stash as f, validate_schema as g, format_schema_issues as h, is_run_end_event as i, is_step as j, sequence as k, is_step_kind as l, suspend as m, is_custom_trajectory_event as n, is_span_start_event as o, use as p, is_emit_event as r, parse_trajectory_event as s, is_checkpoint_event as t, chain as u, compose as v, wait_with_abort as w, fallback as x, loop as y, timeout_error as z };
2331
2751
 
2332
- //# sourceMappingURL=core-DgH4mDbK.js.map
2752
+ //# sourceMappingURL=core-DDRhHu5P.js.map