fascicle 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  };
@@ -552,8 +584,8 @@ const dispatch = /* @__PURE__ */ new Map();
552
584
  /**
553
585
  * Register the dispatch handler for a step kind.
554
586
  *
555
- * Composer files call this (directly or via `register_traced_kind`) at module
556
- * load, which is how the runner stays free of composer-specific logic.
587
+ * Composer files call this via `register_traced_kind` at module load, which is
588
+ * how the runner stays free of composer-specific logic.
557
589
  */
558
590
  function register_kind(kind, fn) {
559
591
  dispatch.set(kind, fn);
@@ -723,6 +755,26 @@ function throw_if_aborted(ctx) {
723
755
  throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
724
756
  }
725
757
  /**
758
+ * Install a fan-out abort listener over a set of child controllers: when
759
+ * `ctx.abort` fires, every controller currently in `controllers` is aborted
760
+ * with the same reason. An already-aborted parent fires immediately instead
761
+ * of registering a listener.
762
+ *
763
+ * Concurrent composers (`map`, `parallel`) use this to propagate a parent
764
+ * abort into each in-flight child's composed signal. `controllers` is read by
765
+ * reference, so a caller that appends to the array after installing (as
766
+ * `map` does per newly-started item) is still covered by later aborts.
767
+ * Returns the listener so the caller can remove it once its children settle.
768
+ */
769
+ function install_abort_fan_out(ctx, controllers) {
770
+ const on_parent_abort = () => {
771
+ for (const c of controllers) c.abort(ctx.abort.reason);
772
+ };
773
+ if (ctx.abort.aborted) on_parent_abort();
774
+ else ctx.abort.addEventListener("abort", on_parent_abort, { once: true });
775
+ return on_parent_abort;
776
+ }
777
+ /**
726
778
  * Forward a caller-owned AbortSignal into the run's internal controller and
727
779
  * return an unlink function. The reason is preserved so the original
728
780
  * cancellation cause propagates out of `run`. The listener is `once` and the
@@ -785,6 +837,10 @@ function start_run(flow, input, options, high_water_mark) {
785
837
  on_cleanup: (fn) => {
786
838
  cleanup.register(fn);
787
839
  },
840
+ call(s, child_input) {
841
+ throw_if_aborted(this);
842
+ return dispatch_step(s, child_input, this);
843
+ },
788
844
  checkpoint_store: options.checkpoint_store,
789
845
  resume_data: options.resume_data,
790
846
  streaming
@@ -849,14 +905,54 @@ function run_stream(flow, input, options = {}) {
849
905
  };
850
906
  }
851
907
  /**
908
+ * Execute a flow, reporting suspension as a typed outcome instead of a
909
+ * thrown `suspended_error`.
910
+ *
911
+ * Resolves `{ kind: 'done', output }` on completion. When a `suspend` gate
912
+ * fires, resolves `{ kind: 'suspended', id, resume }` where `id` is the
913
+ * gate's suspend id and `resume(data)` re-runs the flow from the original
914
+ * input with `resume_data[id] = data` merged over the caller's options: the
915
+ * same full re-run semantics as calling `run` again yourself, so pure
916
+ * prefixes replay and `checkpoint`ed steps are served from the store. The
917
+ * returned promise resolves to the next outcome, so a flow with several
918
+ * gates is driven by awaiting `resume` repeatedly. Real errors still throw,
919
+ * from the initial call and from `resume` alike.
920
+ */
921
+ async function run_until_suspended(flow, input, options = {}) {
922
+ try {
923
+ return {
924
+ kind: "done",
925
+ output: await run_impl(flow, input, options)
926
+ };
927
+ } catch (err) {
928
+ if (!(err instanceof suspended_error)) throw err;
929
+ const id = err.suspend_id;
930
+ return {
931
+ kind: "suspended",
932
+ id,
933
+ resume: (data) => run_until_suspended(flow, input, {
934
+ ...options,
935
+ resume_data: {
936
+ ...options.resume_data,
937
+ [id]: data
938
+ }
939
+ })
940
+ };
941
+ }
942
+ }
943
+ /**
852
944
  * The public entry point for executing a flow.
853
945
  *
854
- * Callable as `run(flow, input, options?)` for a plain result, or
855
- * `run.stream(flow, input, options?)` for `{ events, result }`. Both share
856
- * one implementation, so a streamed run and a plain run of the same flow
857
- * produce identical output.
946
+ * Callable as `run(flow, input, options?)` for a plain result,
947
+ * `run.stream(flow, input, options?)` for `{ events, result }`, or
948
+ * `run.until_suspended(flow, input, options?)` for a `RunOutcome` that
949
+ * carries suspension as data. All share one implementation, so every entry
950
+ * point runs the same graph identically.
858
951
  */
859
- const run = Object.assign(run_impl, { stream: run_stream });
952
+ const run = Object.assign(run_impl, {
953
+ stream: run_stream,
954
+ until_suspended: run_until_suspended
955
+ });
860
956
  //#endregion
861
957
  //#region src/core/step.ts
862
958
  /**
@@ -909,7 +1005,7 @@ register_traced_kind("step");
909
1005
  * True when the value has a string `id`, a string `kind`, and a callable
910
1006
  * `run`.
911
1007
  */
912
- function is_step$1(value) {
1008
+ function is_step(value) {
913
1009
  if (typeof value !== "object" || value === null) return false;
914
1010
  if (!("id" in value) || !("kind" in value) || !("run" in value)) return false;
915
1011
  const { id, kind, run } = value;
@@ -989,8 +1085,35 @@ function render_text(node, depth, lines, path, strict) {
989
1085
  * Functions become `<fn>` or `<fn:name>`, zod schemas `<schema>`, and Step
990
1086
  * references `kind(id)`; arrays and plain objects recurse. Strings are
991
1087
  * JSON-quoted so empty and whitespace values stay visible.
1088
+ *
1089
+ * Steps, arrays, and renderable objects each own a branch; everything else
1090
+ * (functions, the empty markers, schemas, primitives) resolves through
1091
+ * `render_scalar_text`. The three object-shaped cases are mutually exclusive at
1092
+ * runtime, so their order relative to the scalar cases is immaterial.
992
1093
  */
993
1094
  function render_value_text(value, path, strict) {
1095
+ if (is_step(value)) return render_step_text(value, path, strict);
1096
+ if (Array.isArray(value)) return `[${value.map((item) => render_value_text(item, path, strict)).join(", ")}]`;
1097
+ if (is_renderable_object(value)) return `{ ${Object.entries({ ...value }).map(([k, v]) => `${k}: ${render_value_text(v, path, strict)}`).join(", ")} }`;
1098
+ return render_scalar_text(value);
1099
+ }
1100
+ /**
1101
+ * Render a Step reference for the text tree: a back-reference on the current
1102
+ * path becomes `<cycle>(id)` (or throws under strict mode); otherwise `kind(id)`.
1103
+ */
1104
+ function render_step_text(value, path, strict) {
1105
+ if (path.has(value)) {
1106
+ if (strict) throw new describe_cycle_error(value.id);
1107
+ return `<cycle>(${value.id})`;
1108
+ }
1109
+ return `${value.kind}(${value.id})`;
1110
+ }
1111
+ /**
1112
+ * Render the non-recursive value cases for the text tree: functions (`<fn>` or
1113
+ * `<fn:name>`), the empty markers, zod schemas, and (via `render_primitive_text`)
1114
+ * raw primitives.
1115
+ */
1116
+ function render_scalar_text(value) {
994
1117
  if (typeof value === "function") {
995
1118
  const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
996
1119
  return name ? `<fn:${name}>` : "<fn>";
@@ -998,15 +1121,14 @@ function render_value_text(value, path, strict) {
998
1121
  if (value === null) return "null";
999
1122
  if (value === void 0) return "undefined";
1000
1123
  if (is_zod_schema(value)) return "<schema>";
1001
- if (is_step$1(value)) {
1002
- if (path.has(value)) {
1003
- if (strict) throw new describe_cycle_error(value.id);
1004
- return `<cycle>(${value.id})`;
1005
- }
1006
- return `${value.kind}(${value.id})`;
1007
- }
1008
- if (Array.isArray(value)) return `[${value.map((item) => render_value_text(item, path, strict)).join(", ")}]`;
1009
- if (typeof value === "object") return `{ ${Object.entries({ ...value }).map(([k, v]) => `${k}: ${render_value_text(v, path, strict)}`).join(", ")} }`;
1124
+ return render_primitive_text(value);
1125
+ }
1126
+ /**
1127
+ * Render a primitive (or unrecognized) value for the text tree. Strings are
1128
+ * JSON-quoted so empty and whitespace values stay visible; bigints keep an `n`
1129
+ * suffix; anything unexpected falls back to JSON.
1130
+ */
1131
+ function render_primitive_text(value) {
1010
1132
  if (typeof value === "string") return JSON.stringify(value);
1011
1133
  if (typeof value === "bigint") return `${value.toString()}n`;
1012
1134
  if (typeof value === "symbol") return value.toString();
@@ -1052,8 +1174,42 @@ function render_json(node, path, strict) {
1052
1174
  * `{ kind: '<schema>' }`, Step references as `{ kind, id }`. `undefined`
1053
1175
  * maps to `null` and bigints/symbols to strings so the result survives
1054
1176
  * `JSON.stringify` without loss.
1177
+ *
1178
+ * Mirrors `render_value_text`: steps, arrays, and renderable objects each own a
1179
+ * branch, and everything else resolves through `render_scalar_json`.
1055
1180
  */
1056
1181
  function render_value_json(value, path, strict) {
1182
+ if (is_step(value)) return render_step_json(value, path, strict);
1183
+ if (Array.isArray(value)) return value.map((item) => render_value_json(item, path, strict));
1184
+ if (is_renderable_object(value)) {
1185
+ const out = {};
1186
+ for (const [k, v] of Object.entries({ ...value })) out[k] = render_value_json(v, path, strict);
1187
+ return out;
1188
+ }
1189
+ return render_scalar_json(value);
1190
+ }
1191
+ /**
1192
+ * Serialize a Step reference: a back-reference on the current path becomes
1193
+ * `{ kind: '<cycle>', id }` (or throws under strict mode); otherwise `{ kind, id }`.
1194
+ */
1195
+ function render_step_json(value, path, strict) {
1196
+ if (path.has(value)) {
1197
+ if (strict) throw new describe_cycle_error(value.id);
1198
+ return {
1199
+ kind: "<cycle>",
1200
+ id: value.id
1201
+ };
1202
+ }
1203
+ return {
1204
+ kind: value.kind,
1205
+ id: value.id
1206
+ };
1207
+ }
1208
+ /**
1209
+ * Serialize the non-recursive value cases: functions, the empty markers, zod
1210
+ * schemas, and (via `render_primitive_json`) raw primitives.
1211
+ */
1212
+ function render_scalar_json(value) {
1057
1213
  if (typeof value === "function") {
1058
1214
  const name = typeof value.name === "string" && value.name.length > 0 ? value.name : "";
1059
1215
  return name ? {
@@ -1064,25 +1220,14 @@ function render_value_json(value, path, strict) {
1064
1220
  if (value === null) return null;
1065
1221
  if (value === void 0) return null;
1066
1222
  if (is_zod_schema(value)) return { kind: "<schema>" };
1067
- if (is_step$1(value)) {
1068
- if (path.has(value)) {
1069
- if (strict) throw new describe_cycle_error(value.id);
1070
- return {
1071
- kind: "<cycle>",
1072
- id: value.id
1073
- };
1074
- }
1075
- return {
1076
- kind: value.kind,
1077
- id: value.id
1078
- };
1079
- }
1080
- if (Array.isArray(value)) return value.map((item) => render_value_json(item, path, strict));
1081
- if (typeof value === "object") {
1082
- const out = {};
1083
- for (const [k, v] of Object.entries({ ...value })) out[k] = render_value_json(v, path, strict);
1084
- return out;
1085
- }
1223
+ return render_primitive_json(value);
1224
+ }
1225
+ /**
1226
+ * Serialize a primitive (or unrecognized) value. `undefined` already resolves
1227
+ * to `null` in `render_scalar_json`; bigints and symbols become strings so the
1228
+ * result survives `JSON.stringify` without loss.
1229
+ */
1230
+ function render_primitive_json(value) {
1086
1231
  if (typeof value === "string") return value;
1087
1232
  if (typeof value === "number" || typeof value === "boolean") return value;
1088
1233
  if (typeof value === "bigint") return `${value.toString()}n`;
@@ -1097,6 +1242,14 @@ function is_zod_schema(value) {
1097
1242
  if (typeof value !== "object" || value === null) return false;
1098
1243
  return "_zod" in value || "_def" in value;
1099
1244
  }
1245
+ /**
1246
+ * True for a plain object rendered by recursing into its own entries: an object
1247
+ * that is neither null nor a zod schema. The Step and array cases are checked
1248
+ * before this at every call site, so they never reach it.
1249
+ */
1250
+ function is_renderable_object(value) {
1251
+ return typeof value === "object" && value !== null && !is_zod_schema(value);
1252
+ }
1100
1253
  //#endregion
1101
1254
  //#region src/core/sequence.ts
1102
1255
  /**
@@ -1105,6 +1258,12 @@ function is_zod_schema(value) {
1105
1258
  * `sequence([a, b, c])` runs a, b, c in declared order. The input to sequence
1106
1259
  * is passed to the first child; each subsequent child receives the previous
1107
1260
  * child's output. The composer returns the last child's output.
1261
+ *
1262
+ * For a literal tuple of children, every joint is checked at compile time:
1263
+ * each child after the first must accept its predecessor's output, and a
1264
+ * mismatch errors on the offending element. Arrays built at runtime carry no
1265
+ * positional types, so they degrade to the outer boundary (`unknown` in and
1266
+ * out) while each element is still checked to be a Step.
1108
1267
  */
1109
1268
  let sequence_counter = 0;
1110
1269
  /**
@@ -1117,14 +1276,18 @@ function next_id$10() {
1117
1276
  /**
1118
1277
  * Build a step that chains children, each feeding the next.
1119
1278
  *
1120
- * Validates every element up front so a non-Step (usually a bare function)
1121
- * fails at construction with a pointed message rather than at run time.
1122
- * Checks `ctx.abort` before each child so aborts land on step boundaries.
1279
+ * The children parameter is checked joint by joint for literal tuples via
1280
+ * `CheckedChildren`; the intersection with the bare `children` parameter is
1281
+ * what lets inference read the precise tuple while the checked shape
1282
+ * constrains it. Validates every element up front so a non-Step (usually a
1283
+ * bare function) fails at construction with a pointed message rather than at
1284
+ * run time. Checks `ctx.abort` before each child so aborts land on step
1285
+ * boundaries.
1123
1286
  */
1124
1287
  function sequence(children, options) {
1125
1288
  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])`);
1126
1289
  children.forEach((child, index) => {
1127
- if (is_step$1(child)) return;
1290
+ if (is_step(child)) return;
1128
1291
  throw new TypeError(`sequence(children): children[${index}] is not a Step, got ${typeof child}${typeof child === "function" ? " — wrap plain functions with step(fn), or use pipe(inner, fn) to transform output" : ""}`);
1129
1292
  });
1130
1293
  const id = next_id$10();
@@ -1141,7 +1304,7 @@ function sequence(children, options) {
1141
1304
  return {
1142
1305
  id,
1143
1306
  kind: "sequence",
1144
- children,
1307
+ children: children_ref,
1145
1308
  ...config_meta ? { config: config_meta } : {},
1146
1309
  run: run_fn
1147
1310
  };
@@ -1175,12 +1338,75 @@ function next_id$9() {
1175
1338
  return `parallel_${parallel_counter}`;
1176
1339
  }
1177
1340
  /**
1341
+ * Run one child under its own composed abort signal and settle it: an
1342
+ * `'ok'`/`'err'` record rather than a thrown error, so a sibling's failure
1343
+ * never short-circuits `Promise.all` before every child has finished.
1344
+ */
1345
+ async function run_child(entry, local, input, ctx) {
1346
+ const [key, child] = entry;
1347
+ if (!local) throw new Error("parallel: missing controller");
1348
+ const composed = AbortSignal.any([ctx.abort, local.signal]);
1349
+ const child_ctx = {
1350
+ ...ctx,
1351
+ abort: composed
1352
+ };
1353
+ try {
1354
+ return {
1355
+ status: "ok",
1356
+ key,
1357
+ value: await dispatch_step(child, input, child_ctx)
1358
+ };
1359
+ } catch (err) {
1360
+ return {
1361
+ status: "err",
1362
+ key,
1363
+ err
1364
+ };
1365
+ }
1366
+ }
1367
+ /**
1368
+ * Choose which settled error (if any) `run_fn` should rethrow: a
1369
+ * `suspended_error` wins over any application error so a human-approval gate
1370
+ * inside a branch stays resumable rather than masked by a sibling's failure;
1371
+ * otherwise the first error in declared order propagates.
1372
+ */
1373
+ function pick_error(settled) {
1374
+ let first_err;
1375
+ let has_err = false;
1376
+ let suspended;
1377
+ let has_suspended = false;
1378
+ for (const s of settled) {
1379
+ if (s.status !== "err") continue;
1380
+ if (!has_err) {
1381
+ first_err = s.err;
1382
+ has_err = true;
1383
+ }
1384
+ if (!has_suspended && s.err instanceof suspended_error) {
1385
+ suspended = s.err;
1386
+ has_suspended = true;
1387
+ }
1388
+ }
1389
+ if (has_suspended) return {
1390
+ thrown: true,
1391
+ err: suspended
1392
+ };
1393
+ if (has_err) return {
1394
+ thrown: true,
1395
+ err: first_err
1396
+ };
1397
+ return {
1398
+ thrown: false,
1399
+ err: void 0
1400
+ };
1401
+ }
1402
+ /**
1178
1403
  * Build a step that runs named children concurrently on the same input.
1179
1404
  *
1180
- * Returns an object keyed by child name. All children settle before any
1181
- * error propagates; a `suspended_error` wins over application errors so a
1182
- * human-approval gate stays resumable instead of being masked by a sibling's
1183
- * failure.
1405
+ * The step's input type is the intersection of the children's inputs, since
1406
+ * every child receives the input verbatim. Returns an object keyed by child
1407
+ * name. All children settle before any error propagates; a `suspended_error`
1408
+ * wins over application errors so a human-approval gate stays resumable
1409
+ * instead of being masked by a sibling's failure.
1184
1410
  */
1185
1411
  function parallel(members, options) {
1186
1412
  const id = next_id$9();
@@ -1189,55 +1415,12 @@ function parallel(members, options) {
1189
1415
  const keys = entries.map(([k]) => k);
1190
1416
  const run_fn = async (input, ctx) => {
1191
1417
  const controllers = entries.map(() => new AbortController());
1192
- const on_parent_abort = () => {
1193
- for (const c of controllers) c.abort(ctx.abort.reason);
1194
- };
1195
- if (ctx.abort.aborted) on_parent_abort();
1196
- else ctx.abort.addEventListener("abort", on_parent_abort, { once: true });
1418
+ const on_parent_abort = install_abort_fan_out(ctx, controllers);
1197
1419
  try {
1198
- const settled = await Promise.all(entries.map(async ([key, child], idx) => {
1199
- const local = controllers[idx];
1200
- if (!local) throw new Error("parallel: missing controller");
1201
- const composed = AbortSignal.any([ctx.abort, local.signal]);
1202
- const child_ctx = {
1203
- ...ctx,
1204
- abort: composed
1205
- };
1206
- try {
1207
- return {
1208
- status: "ok",
1209
- key,
1210
- value: await dispatch_step(child, input, child_ctx)
1211
- };
1212
- } catch (err) {
1213
- return {
1214
- status: "err",
1215
- key,
1216
- err
1217
- };
1218
- }
1219
- }));
1220
- if (ctx.abort.aborted) {
1221
- const reason = ctx.abort.reason;
1222
- throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1223
- }
1224
- let first_err;
1225
- let has_err = false;
1226
- let suspended;
1227
- let has_suspended = false;
1228
- for (const s of settled) {
1229
- if (s.status !== "err") continue;
1230
- if (!has_err) {
1231
- first_err = s.err;
1232
- has_err = true;
1233
- }
1234
- if (!has_suspended && s.err instanceof suspended_error) {
1235
- suspended = s.err;
1236
- has_suspended = true;
1237
- }
1238
- }
1239
- if (has_suspended) throw suspended;
1240
- if (has_err) throw first_err;
1420
+ const settled = await Promise.all(entries.map((entry, idx) => run_child(entry, controllers[idx], input, ctx)));
1421
+ throw_if_aborted(ctx);
1422
+ const choice = pick_error(settled);
1423
+ if (choice.thrown) throw choice.err;
1241
1424
  const out = {};
1242
1425
  for (const s of settled) if (s.status === "ok") out[s.key] = s.value;
1243
1426
  return out;
@@ -1340,11 +1523,7 @@ function map(config) {
1340
1523
  const results = Array.from({ length: list.length });
1341
1524
  const limit = concurrency === void 0 ? list.length : Math.max(1, concurrency);
1342
1525
  const controllers = [];
1343
- const on_parent_abort = () => {
1344
- for (const c of controllers) c.abort(ctx.abort.reason);
1345
- };
1346
- if (ctx.abort.aborted) on_parent_abort();
1347
- else ctx.abort.addEventListener("abort", on_parent_abort, { once: true });
1526
+ const on_parent_abort = install_abort_fan_out(ctx, controllers);
1348
1527
  let cursor = 0;
1349
1528
  let worker_error = void 0;
1350
1529
  const run_one = async (idx) => {
@@ -1378,10 +1557,7 @@ function map(config) {
1378
1557
  const workers = [];
1379
1558
  for (let w = 0; w < worker_count; w += 1) workers.push(worker());
1380
1559
  await Promise.all(workers);
1381
- if (ctx.abort.aborted) {
1382
- const reason = ctx.abort.reason;
1383
- throw reason instanceof Error ? reason : new aborted_error("aborted", { reason });
1384
- }
1560
+ throw_if_aborted(ctx);
1385
1561
  if (worker_error !== void 0) throw worker_error;
1386
1562
  return results;
1387
1563
  } finally {
@@ -1424,12 +1600,12 @@ function next_id$6() {
1424
1600
  * `sequence([...])` instead of failing obscurely at run time.
1425
1601
  */
1426
1602
  function pipe(inner, fn, options) {
1427
- 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)" : ""}`);
1603
+ if (!is_step(inner)) throw new TypeError(`pipe(inner, fn): inner must be a Step, got ${typeof inner}${typeof inner === "function" ? " — wrap plain functions with step(fn)" : ""}`);
1428
1604
  if (typeof fn !== "function") {
1429
- if (is_step$1(fn)) throw new TypeError("pipe(inner, fn): fn must be a function, got a Step — pipe is not variadic; to chain Steps use sequence([...])");
1605
+ if (is_step(fn)) throw new TypeError("pipe(inner, fn): fn must be a function, got a Step — pipe is not variadic; to chain Steps use sequence([...])");
1430
1606
  throw new TypeError(`pipe(inner, fn): fn must be a function, got ${typeof fn}`);
1431
1607
  }
1432
- if (is_step$1(options)) throw new TypeError("pipe(inner, fn, options): got a Step as the third argument — pipe is not variadic; to chain Steps use sequence([...])");
1608
+ if (is_step(options)) throw new TypeError("pipe(inner, fn, options): got a Step as the third argument — pipe is not variadic; to chain Steps use sequence([...])");
1433
1609
  const id = next_id$6();
1434
1610
  const run_fn = async (input, ctx) => {
1435
1611
  return fn(await dispatch_step(inner, input, ctx));
@@ -1977,18 +2153,6 @@ function format_issue(issue) {
1977
2153
  * `resume_validation_error` carrying the vendor-neutral issue list.
1978
2154
  */
1979
2155
  /**
1980
- * Structurally detect a `Step` returned from `combine`.
1981
- *
1982
- * `combine` may return either a plain value or a Step to dispatch; this local
1983
- * check distinguishes the two without importing the shared helper.
1984
- */
1985
- function is_step(value) {
1986
- if (typeof value !== "object" || value === null) return false;
1987
- if (!("id" in value) || !("kind" in value) || !("run" in value)) return false;
1988
- const { id, kind, run } = value;
1989
- return typeof id === "string" && typeof kind === "string" && typeof run === "function";
1990
- }
1991
- /**
1992
2156
  * Build a human-in-the-loop pause step.
1993
2157
  *
1994
2158
  * First run fires the `on` side effect and throws `suspended_error`; a resume
@@ -2156,6 +2320,159 @@ register_traced_kind("scope");
2156
2320
  register_traced_kind("stash");
2157
2321
  register_traced_kind("use");
2158
2322
  //#endregion
2323
+ //#region src/core/chain.ts
2324
+ /**
2325
+ * chain: named steps over a growing record.
2326
+ *
2327
+ * `chain<i>(input_name?)` opens a builder whose threaded value is a record of
2328
+ * named outputs rather than a single value. `.step(name, fn)` runs `fn` over
2329
+ * the record and merges its output back in under `name`; `.stage(name,
2330
+ * project?)` concludes a phase: it opens a grouping span in the trajectory
2331
+ * and, when `project` is given, replaces the record with the projection so
2332
+ * earlier bindings go out of scope; `.output(fn)` closes the builder and
2333
+ * returns an ordinary `Step<i, o>`.
2334
+ *
2335
+ * Each `.step` entry is a regular `step(name, fn)` whose input happens to be
2336
+ * the record, so anything true of steps (spans, error paths, abort checks
2337
+ * between entries) is true of chain entries, and the binding name doubles as
2338
+ * the entry's id in trajectories. Invoking another Step from inside a
2339
+ * binding is `ctx.call`, exactly as in a hand-written step body; passing
2340
+ * that Step as `.step(name, fn, { arm })` additionally records it as the
2341
+ * binding's child so `describe` renders the arm's subtree. The arm is
2342
+ * metadata only: dispatch runs `fn` and ignores it.
2343
+ *
2344
+ * Builder values are immutable: every method returns a new chain, so a
2345
+ * prefix can be shared and extended in different directions safely.
2346
+ */
2347
+ let chain_counter = 0;
2348
+ /**
2349
+ * Generate a unique step id of the form `chain_<n>`.
2350
+ */
2351
+ function next_chain_id() {
2352
+ chain_counter += 1;
2353
+ return `chain_${chain_counter}`;
2354
+ }
2355
+ /**
2356
+ * Assemble the runnable chain Step from its entries and output node.
2357
+ *
2358
+ * Runs entries in order over a record seeded with the input under
2359
+ * `input_name`. Step entries merge their output under their name; stage
2360
+ * entries end the previous stage span, open a new one that subsequent
2361
+ * entries nest under, and, when projecting, replace the record. The output
2362
+ * node runs last and its value is the chain's output. `config.plan` lists
2363
+ * the entry names in order so `describe` shows the topology without running.
2364
+ *
2365
+ * The `Step<unknown, unknown>` return is the concrete type, not an erased
2366
+ * top type: the run function genuinely accepts any input, seeding the record
2367
+ * with whatever arrives. The typed `chain` surface narrows it at the cast.
2368
+ */
2369
+ function build_chain(input_name, entries, output_node) {
2370
+ const id = next_chain_id();
2371
+ const plan = [...entries.map((e) => e.kind === "stage" ? `stage:${e.name}` : e.name), "output"];
2372
+ const children = [...entries.flatMap((e) => e.kind === "step" ? [e.node] : []), output_node];
2373
+ const run_fn = async (input, ctx) => {
2374
+ let record = { [input_name]: input };
2375
+ let current_ctx = ctx;
2376
+ let stage_span;
2377
+ let stage_id;
2378
+ const end_stage = (error) => {
2379
+ if (stage_span === void 0) return;
2380
+ const meta = { id: stage_id };
2381
+ if (error !== void 0) meta["error"] = error;
2382
+ ctx.trajectory.end_span(stage_span, meta);
2383
+ stage_span = void 0;
2384
+ };
2385
+ try {
2386
+ for (const entry of entries) {
2387
+ throw_if_aborted(current_ctx);
2388
+ if (entry.kind === "stage") {
2389
+ end_stage();
2390
+ stage_id = `stage:${entry.name}`;
2391
+ const meta = { id: stage_id };
2392
+ if (ctx.parent_span_id !== void 0) meta["parent_span_id"] = ctx.parent_span_id;
2393
+ stage_span = ctx.trajectory.start_span(entry.name, meta);
2394
+ current_ctx = {
2395
+ ...ctx,
2396
+ parent_span_id: stage_span
2397
+ };
2398
+ if (entry.project !== void 0) record = await entry.project(record, current_ctx);
2399
+ } else {
2400
+ const value = await dispatch_step(entry.node, record, current_ctx);
2401
+ record = {
2402
+ ...record,
2403
+ [entry.name]: value
2404
+ };
2405
+ }
2406
+ }
2407
+ throw_if_aborted(current_ctx);
2408
+ const out = await dispatch_step(output_node, record, current_ctx);
2409
+ end_stage();
2410
+ return out;
2411
+ } catch (err) {
2412
+ end_stage(err instanceof Error ? err.message : String(err));
2413
+ throw err;
2414
+ }
2415
+ };
2416
+ return {
2417
+ id,
2418
+ kind: "chain",
2419
+ children,
2420
+ config: {
2421
+ input: input_name,
2422
+ plan
2423
+ },
2424
+ run: run_fn
2425
+ };
2426
+ }
2427
+ /**
2428
+ * Internal untyped builder behind `chain`.
2429
+ *
2430
+ * `bound` holds the binding names of the current stage segment so duplicate
2431
+ * names fail at build time (the typed surface would silently intersect
2432
+ * them); a projecting stage resets it because the projection's keys are only
2433
+ * known to the type system.
2434
+ */
2435
+ function make_chain(input_name, entries, bound) {
2436
+ return {
2437
+ step: (name, fn, options) => {
2438
+ if (bound.has(name)) throw new TypeError(`chain.step: binding '${name}' is already defined in this stage; names are single-assignment`);
2439
+ const base = step(name, fn);
2440
+ const node = options?.arm === void 0 ? base : {
2441
+ ...base,
2442
+ children: [options.arm]
2443
+ };
2444
+ return make_chain(input_name, [...entries, {
2445
+ kind: "step",
2446
+ name,
2447
+ node
2448
+ }], /* @__PURE__ */ new Set([...bound, name]));
2449
+ },
2450
+ stage: (name, project) => make_chain(input_name, [...entries, project === void 0 ? {
2451
+ kind: "stage",
2452
+ name
2453
+ } : {
2454
+ kind: "stage",
2455
+ name,
2456
+ project
2457
+ }], project === void 0 ? bound : /* @__PURE__ */ new Set()),
2458
+ output: (fn) => build_chain(input_name, entries, step("output", fn))
2459
+ };
2460
+ }
2461
+ /**
2462
+ * Open a chain builder whose record starts as `{ [input_name]: input }`.
2463
+ *
2464
+ * `input_name` defaults to `'input'`. The builder is typed: each `.step`
2465
+ * narrows subsequent callbacks to the record accumulated so far, and
2466
+ * `.stage` with a projection re-types the record to the projection's
2467
+ * return, so binding names and views are checked at compile time with no
2468
+ * declared state shape.
2469
+ */
2470
+ function chain(input_name) {
2471
+ const name = input_name ?? "input";
2472
+ return make_chain(name, [], /* @__PURE__ */ new Set([name]));
2473
+ }
2474
+ register_traced_kind("chain");
2475
+ //#endregion
2159
2476
  //#region src/core/step_kinds.ts
2160
2477
  /**
2161
2478
  * Closed registry of every `Step.kind` produced by the composition layer.
@@ -2186,7 +2503,8 @@ const STEP_KINDS = [
2186
2503
  "suspend",
2187
2504
  "scope",
2188
2505
  "stash",
2189
- "use"
2506
+ "use",
2507
+ "chain"
2190
2508
  ];
2191
2509
  /**
2192
2510
  * Check whether a value is one of the registered `Step.kind` strings.
@@ -2250,6 +2568,6 @@ function parse_trajectory_event(value) {
2250
2568
  * and surface through the umbrella package.
2251
2569
  */
2252
2570
  //#endregion
2253
- 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 };
2571
+ export { run as A, pipe as C, sequence as D, parallel as E, timeout_error as F, flow_schema_default as I, describe_cycle_error as M, resume_validation_error as N, describe as O, suspended_error as P, wait_with_abort as S, branch as T, loop as _, parse_trajectory_event as a, retry as b, chain as c, use as d, suspend as f, compose as g, checkpoint as h, is_span_start_event as i, aborted_error as j, step as k, scope as l, validate_schema as m, is_emit_event as n, STEP_KINDS as o, format_schema_issues as p, is_span_end_event as r, is_step_kind as s, is_custom_trajectory_event as t, stash as u, timeout as v, map as w, compute_backoff as x, fallback as y };
2254
2572
 
2255
- //# sourceMappingURL=core-Ww6An4CS.js.map
2573
+ //# sourceMappingURL=core-BkB2l1-e.js.map