fascicle 0.11.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.12.0 — 2026-08-18
4
+
5
+ ### Added
6
+
7
+ - **`chain`: named steps over a growing typed record.** `chain(input_name?)` builds a `Step` from `.step(name, fn)` bindings that each merge one named value into the record, `.stage(name, project?)` markers that conclude a phase (with `project`, narrowing the record), and a final `.output(fn)` projection. A step body receives the record plus the run context, so a binding can `ctx.call` a composed arm directly; passing that arm as step-level `{ arm }` metadata records it as a describe-only child, so `describe` still renders the full tree under the binding.
8
+
9
+ - **`model_step`: the default model boundary.** Takes the same config as `model_call` and returns a `Step` whose output is the content alone: a `string`, or the schema-validated value when `schema` is set. Implemented as `model_call` with `project` preset to the content, so the leaf is a single node in `describe` and the trajectory; reach for `model_call` when the caller needs the `GenerateResult` envelope (usage, cost, tool calls, finish reason).
10
+
11
+ - **`run.until_suspended`: suspension as a typed outcome.** Where plain `run` signals a `suspend` gate by throwing `suspended_error`, `run.until_suspended(flow, input, options?)` resolves `{ kind: 'suspended', id, resume }`; calling `resume(data)` re-runs the flow with the decision and resolves to the next outcome. Completion is `{ kind: 'done', output }`; real errors still throw. This supersedes the try/catch dance around `suspended_error`, which remains for plain `run`.
12
+
13
+ - **A `project` option on the six envelope composites and on `model_call`.** `adversarial`, `ensemble`, `ensemble_step`, `tournament`, `consensus`, and `improve` can now map their result envelope into the step's output at the source (`project: (r) => r.candidate`), so downstream steps see the value instead of the wrapper; `model_call` takes the same option over its `GenerateResult` (`project: (r) => ({ text: r.content, cost: r.cost })`), which is also how `model_step` is now built. In every case the projection runs inside the step, so `describe` and the trajectory gain no wrapper node; omitted, the envelope stays the output, as before.
14
+
15
+ - **The `fascicle/testing` subpath.** `make_stub_engine(canned, options?)` routes canned responses by system-prompt prefix, validates each one through the call's schema, and throws on an unmatched system; `make_capture_engine(options?)` records every call's `GenerateOptions` into a live `calls` array and answers with a canned result. Types: `StubEngineOptions`, `StubResponse`, `CaptureEngine`, `CaptureEngineOptions`.
16
+
17
+ - **Compile-time joint checking for literal `sequence` tuples.** Each child of a literal tuple must accept its predecessor's output, and a mismatch errors on the offending element. Arrays built at runtime still degrade to unknown boundaries; annotate the outer `Step<In, Out>` to keep the flow's boundary checked.
18
+
19
+ - **Docs for the layering.** `docs/leaf-arm-spine.md` names the leaf / arm / spine shape and the decision rules at each layer, `docs/advanced-composition.md` covers the demoted tier (`scope`/`stash`/`use`, plain `ensemble`, `tournament`, `improve`/`learn`), and `examples/newsroom.ts` is the vocabulary tour that uses every primary primitive once.
20
+
21
+ - **A one-file style pair in the examples.** `examples/release_notes.ts` and `examples/release_notes_direct.ts` build the same release-notes flow two ways — composed through `chain` and arms, and written straight through as one function — so the cost and the benefit of composing are readable side by side rather than asserted. `docs/blueprint.md` is rebuilt around `chain` and points at the pair.
22
+
23
+ ### Changed
24
+
25
+ - **The `Step` type is sound.** `run` is a function property rather than a method, so a step's input is checked contravariantly, and `AnyStep` (`Step<never, unknown>`) is added as the erased supertype for code that handles steps generically. **Breaking** for consumers that relied on method bivariance: an assignment that only type-checked under that looser method-parameter rule now errors, which is the point of the change.
26
+
27
+ - **The examples fleet migrated to the `chain` / `model_step` / arm idioms.** The single-file demos and the reference apps now read as leaves, arms, and one spine per flow, matching the layering `docs/leaf-arm-spine.md` names.
28
+
29
+ - **The prose surface moved onto the `chain` / `model_step` idiom.** `README.md`, `docs/getting-started.md`, `docs/concepts.md`, `docs/api-reference.md`, `docs/cookbook.md`, `docs/composition.md`, `docs/writing-a-harness.md`, and the site pages now teach leaf / arm / spine first and present `pipe`, `sequence`, and `model_call` as the lower tier those primitives sit on. `docs/concepts.md` and `docs/api-reference.md` also state the sound `Step` shape and `AnyStep`.
30
+
31
+ ### Internal
32
+
33
+ - Re-baselined the duplication report after the stub-engine paydown, and added the `.firecrawl` web-research scratch directory to `.gitignore`.
34
+
3
35
  ## v0.11.1 — 2026-08-13
4
36
 
5
37
  ### Fixed
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ![A substrate for agents — three mushrooms (model_call, step, tool) fruit from a shared mycelium network; every mushroom is a Step<i, o>, every thread is a composition](./mycelium.svg)
4
4
 
5
- Compose agents out of LLM calls, tool calls, and plain functions. Everything is a `Step<i, o>`. Wire steps together with 21 primitives (`sequence`, `parallel`, `branch`, `retry`, `loop`, `ensemble`, `checkpoint`, …) and run them as plain values. One `generate` surface fronts eight provider adapters: Anthropic, OpenAI, Google, OpenRouter, AWS Bedrock, Ollama, LM Studio, and a `claude_cli` subprocess that drives the Claude Code CLI.
5
+ Compose agents out of LLM calls, tool calls, and plain functions. Everything is a `Step<i, o>`. Wire steps together with 22 primitives (`sequence`, `parallel`, `chain`, `branch`, `retry`, `loop`, `ensemble_step`, `checkpoint`, …) and run them as plain values. One `generate` surface fronts eight provider adapters: Anthropic, OpenAI, Google, OpenRouter, AWS Bedrock, Ollama, LM Studio, and a `claude_cli` subprocess that drives the Claude Code CLI.
6
6
 
7
7
  No framework lifecycle. No ambient state. No decorators. Adapters are passed in per run.
8
8
 
@@ -32,7 +32,7 @@ Add a model call:
32
32
 
33
33
  <!-- snippet: check -->
34
34
  ```typescript
35
- import { create_engine, model_call, pipe, run, sequence, step } from 'fascicle';
35
+ import { create_engine, model_step, run, sequence, step } from 'fascicle';
36
36
 
37
37
  const engine = create_engine({
38
38
  providers: { anthropic: { api_key: process.env.ANTHROPIC_API_KEY! } },
@@ -40,10 +40,7 @@ const engine = create_engine({
40
40
 
41
41
  const flow = sequence([
42
42
  step('brief', (topic: string) => `Write a 2-sentence brief on: ${topic}`),
43
- pipe(
44
- model_call({ engine, model: 'sonnet', system: 'No preamble.' }),
45
- (r) => r.content,
46
- ),
43
+ model_step({ engine, model: 'sonnet', system: 'No preamble.' }),
47
44
  ]);
48
45
 
49
46
  try {
@@ -53,11 +50,11 @@ try {
53
50
  }
54
51
  ```
55
52
 
56
- `model_call` is the only sanctioned bridge between composition and the engine. It threads `ctx.abort`, `ctx.trajectory`, and streaming chunks for you.
53
+ `model_step` returns the model's answer (a `string`, or the schema-validated value when `schema` is set), keeping flows at the `step, step, model_step, step` cadence. Underneath sits `model_call`, the only sanctioned bridge between composition and the engine: same config, but it returns the full `GenerateResult` envelope (usage, cost, tool calls, finish reason), with an optional `project` to map a slice of it at the source. Both thread `ctx.abort`, `ctx.trajectory`, and streaming chunks for you.
57
54
 
58
55
  ## What's in the box
59
56
 
60
- **Composition primitives (21).** Every composer takes `Step<i, o>` and returns `Step<i, o>`. Anything that fits a step fits any composition of steps.
57
+ **Composition primitives.** Every composer takes `Step<i, o>` and returns `Step<i, o>`. Anything that fits a step fits any composition of steps. The everyday surface is small; most flows are built entirely from these nine:
61
58
 
62
59
  | Primitive | Shape |
63
60
  | --- | --- |
@@ -68,22 +65,12 @@ try {
68
65
  | `map` | run a step per array element, optional concurrency cap |
69
66
  | `pipe` | post-process an inner step's output with a plain function |
70
67
  | `retry` | re-run on failure with exponential backoff |
71
- | `fallback` | run a backup if the primary throws |
72
- | `timeout` | cancel an inner step after N ms |
73
- | `loop` | bounded iteration with carry-state and an optional convergence guard |
74
- | `compose` | label a composite so it shows up by intent in trajectories |
75
- | `adversarial` | build, critique, repeat until accept or `max_rounds` |
76
- | `ensemble` | run N members, pick the highest-scoring result |
77
- | `ensemble_step` | pick-best where the scorer is itself a `Step` (a model judge with its own span) |
78
- | `tournament` | single-elimination bracket |
79
- | `consensus` | run N concurrently, accept when an `agree` predicate holds |
80
- | `checkpoint` | memoize an inner step by key in a `CheckpointStore` |
81
- | `suspend` | pause for external input; resume later with `resume_data` |
82
- | `scope` / `stash` / `use` | named state across non-adjacent steps |
83
- | `improve` | bounded online propose → score → accept/reject self-improvement loop |
84
- | `learn` | offline reflection over recorded trajectories |
85
-
86
- Plus `run`, `run.stream`, and `describe`.
68
+ | `model_step` | the model's answer as a step (`model_call` projected to its content) |
69
+ | `chain` | named steps over a typed record: `.step` binds, `.stage` concludes a phase, `.output` projects |
70
+
71
+ The remaining primitives are specialized composers with the same contract, so they drop into any flow when the task calls for them: control flow (`loop`, `fallback`, `timeout`, `compose`), multi-model orchestration (`adversarial`, `ensemble_step`, `consensus`), and durability (`checkpoint`, `suspend`). Behind those sits an advanced tier — the pick-best variants `ensemble` and `tournament`, the raw named-state primitives `scope` / `stash` / `use` underlying `chain`, and the self-improvement pair `improve` / `learn` — covered in [docs/advanced-composition.md](./docs/advanced-composition.md), each entry paired with the primary primitive to try first. One-liners for all of them live in [docs/composition.md](./docs/composition.md), full shapes in [docs/api-reference.md](./docs/api-reference.md), and [docs/leaf-arm-spine.md](./docs/leaf-arm-spine.md) is the decision guide for which layer each belongs to.
72
+
73
+ Plus `run`, `run.stream`, and `describe`. And inside any step body, `ctx.call(step, input)` runs another Step with spans, abort, and error paths intact: the direct-style counterpart to composing, for control flow too dynamic to declare.
87
74
 
88
75
  **AI engine.** `create_engine(config)` returns one `generate` surface across eight providers. Two axes: `model` is an opaque id sent to the provider verbatim (`claude-opus-4-8`, `gpt-4o`, `us.anthropic.claude-sonnet-4-20250514-v1:0`), and `provider` names the transport (`anthropic`, `bedrock`, `openrouter`, `claude_cli`, …) — swap `provider` to move a call between transports. Reasoning effort (`'none'` through `'max'`) is translated per provider. Cost estimation uses a pricing table with per-engine overrides.
89
76
 
@@ -102,7 +89,17 @@ await run(flow, input, {
102
89
 
103
90
  `filesystem_logger` writes synchronously and the bundled span stacks aren't async-context-aware — fine for dev tools and short-lived runs, see [docs/concepts.md](./docs/concepts.md#adapter-limits) before wiring it into a long-running server. The `TrajectoryLogger` and `CheckpointStore` contracts (exported from `fascicle`) are tiny — roll your own to push events to Honeycomb, S3, etc.
104
91
 
105
- `run.stream(flow, input)` returns `{ events, result }` for incremental observation.
92
+ `run.stream(flow, input)` returns `{ events, result }` for incremental observation, and `run.until_suspended(flow, input)` drives human-in-the-loop flows: a `suspend` gate resolves to a typed outcome with a `resume` closure instead of throwing.
93
+
94
+ **Stub engines for tests.** The `fascicle/testing` subpath ships the two doubles an app needs — `make_stub_engine` routes canned responses by the system prompt's stable first line and validates them through the call's own schema, `make_capture_engine` records every `GenerateOptions` for assertions — so tests run the real flow through the real `run()` with zero network and no mocking framework:
95
+
96
+ ```typescript
97
+ import { make_stub_engine } from 'fascicle/testing';
98
+
99
+ const engine = make_stub_engine([
100
+ { prefix: 'myapp/reviewer', content: { findings: [], summary: 'clean' } },
101
+ ]);
102
+ ```
106
103
 
107
104
  **Markdown-defined agents.** When an agent is just a prompt plus an output schema, `define_agent` (the `fascicle/agents` subpath) folds a markdown file — frontmatter `name` / `model` / `temperature`, body as the prompt — and a zod schema into a `Step<i, o>`:
108
105
 
@@ -200,7 +197,9 @@ The canonical worked example is [examples/pr-improve/](./examples/pr-improve/),
200
197
  - [docs/blueprint.md](./docs/blueprint.md) — **the agent blueprint**: the standard app architecture (start here when building an app)
201
198
  - [docs/getting-started.md](./docs/getting-started.md) — install and run your first flow
202
199
  - [docs/concepts.md](./docs/concepts.md) — step-as-value, trajectories, cancellation
203
- - [docs/composition.md](./docs/composition.md) — full composition surface: the 21 primitives, run/stream, checkpointing
200
+ - [docs/composition.md](./docs/composition.md) — full composition surface: the 22 primitives, run/stream, checkpointing
201
+ - [docs/leaf-arm-spine.md](./docs/leaf-arm-spine.md) — the three-layer shape of a fascicle flow and how to choose the right primitive at each layer
202
+ - [docs/advanced-composition.md](./docs/advanced-composition.md) — the primitives to reach for last (`scope`/`stash`/`use`, `ensemble`, `tournament`, `improve`/`learn`) and when they earn their keep
204
203
  - [docs/api-reference.md](./docs/api-reference.md) — the public surface at a glance
205
204
  - [docs/configuration.md](./docs/configuration.md) — engine config, defaults, pricing, retries
206
205
  - [docs/providers.md](./docs/providers.md) — per-provider adapter notes
@@ -212,7 +211,7 @@ The canonical worked example is [examples/pr-improve/](./examples/pr-improve/),
212
211
  - [docs/troubleshooting.md](./docs/troubleshooting.md) — first-run errors and what they mean
213
212
  - [docs/comparison.md](./docs/comparison.md) — how fascicle compares to LangChain, Mastra, and others
214
213
  - [docs/adoption-decision.md](./docs/adoption-decision.md) weighs whether to adopt fascicle: the honest case, the risks, and when to reach for something else
215
- - [examples/](./examples/) — runnable reference flows
214
+ - [examples/](./examples/) — runnable reference flows; start with [examples/newsroom.ts](./examples/newsroom.ts), the vocabulary tour
216
215
  - [docs/viewer.md](./docs/viewer.md) — viewer details and transport options
217
216
 
218
217
  ## Contributing
@@ -1,4 +1,4 @@
1
- import { s as TrajectoryLogger, t as CheckpointStore } from "./types-BDSbSUAO.js";
1
+ import { c as TrajectoryLogger, n as CheckpointStore } from "./types-CVdTBXE_.js";
2
2
 
3
3
  //#region src/adapters/filesystem_logger.d.ts
4
4
  type FilesystemLoggerOptions = {
package/dist/agents.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { r as Step } from "./types-BDSbSUAO.js";
1
+ import { i as Step } from "./types-CVdTBXE_.js";
2
2
  import { r as ToolSchema } from "./types-BCtKsxrX.js";
3
- import { a as Engine } from "./types-B3HIsBBD.js";
3
+ import { a as Engine } from "./types-4l54cexm.js";
4
4
 
5
5
  //#region src/agents/define_agent.d.ts
6
6
  type AgentBuiltPrompt = string | {
package/dist/agents.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as aborted_error, O as step } from "./core-DgH4mDbK.js";
1
+ import { j as aborted_error, k as step } from "./core-BkB2l1-e.js";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  //#region src/agents/define_agent.ts
@@ -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
  };
@@ -805,6 +837,10 @@ function start_run(flow, input, options, high_water_mark) {
805
837
  on_cleanup: (fn) => {
806
838
  cleanup.register(fn);
807
839
  },
840
+ call(s, child_input) {
841
+ throw_if_aborted(this);
842
+ return dispatch_step(s, child_input, this);
843
+ },
808
844
  checkpoint_store: options.checkpoint_store,
809
845
  resume_data: options.resume_data,
810
846
  streaming
@@ -869,14 +905,54 @@ function run_stream(flow, input, options = {}) {
869
905
  };
870
906
  }
871
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
+ /**
872
944
  * The public entry point for executing a flow.
873
945
  *
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.
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.
878
951
  */
879
- 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
+ });
880
956
  //#endregion
881
957
  //#region src/core/step.ts
882
958
  /**
@@ -1182,6 +1258,12 @@ function is_renderable_object(value) {
1182
1258
  * `sequence([a, b, c])` runs a, b, c in declared order. The input to sequence
1183
1259
  * is passed to the first child; each subsequent child receives the previous
1184
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.
1185
1267
  */
1186
1268
  let sequence_counter = 0;
1187
1269
  /**
@@ -1194,9 +1276,13 @@ function next_id$10() {
1194
1276
  /**
1195
1277
  * Build a step that chains children, each feeding the next.
1196
1278
  *
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.
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.
1200
1286
  */
1201
1287
  function sequence(children, options) {
1202
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])`);
@@ -1218,7 +1304,7 @@ function sequence(children, options) {
1218
1304
  return {
1219
1305
  id,
1220
1306
  kind: "sequence",
1221
- children,
1307
+ children: children_ref,
1222
1308
  ...config_meta ? { config: config_meta } : {},
1223
1309
  run: run_fn
1224
1310
  };
@@ -1316,10 +1402,11 @@ function pick_error(settled) {
1316
1402
  /**
1317
1403
  * Build a step that runs named children concurrently on the same input.
1318
1404
  *
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.
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.
1323
1410
  */
1324
1411
  function parallel(members, options) {
1325
1412
  const id = next_id$9();
@@ -2233,6 +2320,159 @@ register_traced_kind("scope");
2233
2320
  register_traced_kind("stash");
2234
2321
  register_traced_kind("use");
2235
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
2236
2476
  //#region src/core/step_kinds.ts
2237
2477
  /**
2238
2478
  * Closed registry of every `Step.kind` produced by the composition layer.
@@ -2263,7 +2503,8 @@ const STEP_KINDS = [
2263
2503
  "suspend",
2264
2504
  "scope",
2265
2505
  "stash",
2266
- "use"
2506
+ "use",
2507
+ "chain"
2267
2508
  ];
2268
2509
  /**
2269
2510
  * Check whether a value is one of the registered `Step.kind` strings.
@@ -2327,6 +2568,6 @@ function parse_trajectory_event(value) {
2327
2568
  * and surface through the umbrella package.
2328
2569
  */
2329
2570
  //#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 };
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 };
2331
2572
 
2332
- //# sourceMappingURL=core-DgH4mDbK.js.map
2573
+ //# sourceMappingURL=core-BkB2l1-e.js.map