fascicle 0.16.3 → 0.16.4

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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.16.4 — 2026-10-21
4
+
5
+ ### Added
6
+
7
+ - **The package ships a primer for coding agents, as `dist/AGENTS.md`.** An agent in a project that installs Fascicle knows little or nothing about it from training, and the primer it needs lived only in the repository, at `docs/learn/agent-primer.md`, which a project could reach only by cloning. The build now copies it into the package, with each link into the docs pointed at the same file on GitHub at the release's tag, so a `CLAUDE.md` can import `@node_modules/fascicle/dist/AGENTS.md` and get the copy that matches the installed version. The README says where it is.
8
+
9
+ ### Changed
10
+
11
+ - **A call with a `schema` shows the model the schema.** The engine asked for "a single JSON value that conforms to the expected schema" and never said what the schema was. Only an `ai_sdk` adapter with the `structured_output` capability hands the schema to the provider, and only on a call without tools, so everywhere else the model guessed the field names, and the repair loop taught them one failed reply at a time. The instruction now carries the schema as compact JSON Schema, closed with `additionalProperties: false` as a tool's schema is, so the first reply can fit. On OpenRouter's Claude Haiku 5.5, a three-field extraction with no example in its prompt took two round trips before and one after, at about half the cost, and a 4B model on Ollama that never found the right fields now does. A schema that JSON Schema can't express, such as one that holds a `Date`, keeps the bare request and still validates its replies. The `.describe()` text on a zod field reaches the model the same way, which is what the blueprint's advice to keep field rules there assumed.
12
+ - **`branch` returns the union of its arms' outputs.** Both arms had to return the same type, so a branch that answered `null` on one side and a number on the other failed to compile until you wrote `branch<Pair, number | null>(...)`, and the course had to teach that spelling before it taught anything else about `branch`. The otherwise arm now has its own output type, defaulting to the then arm's, and the branch returns either, so the union is inferred. Naming one output type, as in `branch<Pair, string>`, still holds both arms to it, so every existing call compiles unchanged.
13
+ - **`describe.diagram` draws a named composite as the steps it was built from.** `adversarial`, `consensus`, `ensemble_step`, `gate`, and `improve` are made of scopes, stashes, and loops, and the diagram drew all of it, so an `adversarial` over a draft and a check took fourteen rows of `stash` and `snapshot` around the two steps that the caller wrote, and a lesson that taught the pattern had to use `loop` instead to stay legible. `compose` takes `parts`, the steps inside it that a reader should see, by role, and records the path to each, so the diagram draws the composite as one row over its parts (`build` and `critique`, the members and the `score`, the gated work and its approval), while `describe.json` keeps the whole tree that the viewer maps spans onto. `{ internals: true }`, or `--internals` on `fascicle-diagram`, draws the insides as before. A part that isn't inside `inner` throws at construction, since the diagram would have nothing to draw for it, and roles that collide, such as a member named `score` beside the judge, get a numbered suffix.
14
+
15
+ ### Fixed
16
+
17
+ - **A chain opened without its input type says how to fix it.** An unannotated `chain('pair')` typed its input as `never`, so the first field read failed with `Property 'a' does not exist on type 'never'` and `run` with an argument that wasn't assignable to `never`, and neither said what to do. The input now defaults to a branded type that nothing satisfies, so the same mistakes fail where they did, as `Property 'a' does not exist on type 'ChainInputUndeclared<"call .input<T>() on the chain to say what it takes">'`. A chain without an input type in a `parallel` now constrains the parallel's input as well, where `never` constrained nothing.
18
+ - **`fascicle-viewer` labels a loop's guard `guard`.** A loop wraps a guard function in an anonymous step whose id it makes up, as `loop_1_guard`, and the canvas labelled the puck with that id, which `describe.diagram` never shows. An anonymous step now reads as the role its parent gives it, `guard` for a loop's second child, and otherwise as its kind, which is how the diagram reads one.
19
+ - **`checkpoint_store_conformance` no longer fails a correct store's renewal when the machine stalls.** The renewal check claims a key, renews it halfway through its lifetime, then has a second owner try for it after the original lifetime is up, and a store that restarts the clock on renewal refuses. The check skipped judging when it woke too late, but it read the clock before the second claim, so a machine that stalled inside that claim reached the end of the renewed lifetime, the store rightly handed the key over, and a correct store failed. It reads the clock after the claim now. It flaked this way under the load of the repository's own full check.
20
+ - **`fascicle-viewer` counts each place in a flow apart, and labels a step or a composer by the name you gave it.** The canvas joined every span to its node by step id alone, so steps that shared an id pooled their runs. Every chain closes on a step called `output`, so in the course's commit tool, a chain inside a loop inside another chain, a run of three rounds drew the inner `output` as `×4` and the flow's last step as `TERMINUS ×4`. A chain binding that shares the id of the step it wraps doubled the same way. A span now joins the place that its parent span's node holds it in, the canvas keys every place apart, and a suspension or a checkpoint lookup, which names its step by id, lands on the place whose span is open. A group label reads the composer's `name` before its id, so a loop named `draft_until_clean` is `DRAFT_UNTIL_CLEAN` where it was `LOOP_1`, and a step's `name` labels its puck, since core resolves names in that order.
21
+ - **`parallel` takes an input that every member accepts, even when a member accepts a union.** The input type pooled every member's input into one union and then intersected its parts, so a member that took `string | readonly Message[]`, as a `model_step` does, beside a member that took a `string` made the input `string & readonly Message[]`, which no string satisfies, and a member that took either of two object shapes demanded both. Each member's input now stays whole while the intersection is taken across the members, so the first case takes a `string`, and the second takes either shape along with the other member's fields. A member whose input reads as `never`, which is what a zero-parameter function's becomes once a generic wrapper loses it, still constrains nothing.
22
+ - **A stub's inline `content` function gets its parameter types.** `StubResponse['content']` was typed `unknown`, which absorbs a function type, so `content: (opts, call_index) => ...` written inline failed strict mode with an implicit `any` on both parameters, the example in docs/testing.md included, and every function needed `(opts: GenerateOptions, call_index: number)` by hand. `content` is now a `StubContent`, which is `StubContentFn` alongside any other value, so an inline function takes its parameter types from `StubContentFn`, and a value typed `unknown` is still accepted. `StubContent` is exported from `fascicle/testing`.
23
+ - **A `sequence` with a step out of order reports the joint that broke.** TypeScript 7 reports a call that matches no overload against the last overload alone, and the last one was the fallback for runtime arrays, so a step out of order got two errors that only said each step had to be a `Step<T, T>`. The joint-checked signature now comes last as well, and the same mistake gets one error, on the step that can't take its input, naming the joint, the type that arrives there, and the type that the step accepts: `SequenceJointMismatch<"after children[1]", string, number>`. A call that compiles resolves exactly as before.
24
+
3
25
  ## v0.16.3 — 2026-10-19
4
26
 
5
27
  ### Fixed
package/README.md CHANGED
@@ -214,12 +214,15 @@ For zero-latency streaming from inside a long-running flow, pair it with `http_l
214
214
 
215
215
  **[docs/blueprint.md](./docs/blueprint.md) is the recommended architecture for apps built on Fascicle** — distilled from the reference apps and production consumers. One composition layer (`flow.ts`) that holds the whole topology, `create_engine` confined to one file, prompts as markdown with frontmatter, zod schemas as the stage contracts, stub-engine testing, and [ast-grep rules](./examples/pr-improve/rules/) that turn each boundary into a build failure. If you are a coding agent scaffolding a new Fascicle app, follow the blueprint and its checklist.
216
216
 
217
+ **Coding agents get a primer of their own.** The package ships `dist/AGENTS.md`, written for an agent whose training data holds little or nothing about Fascicle: the vocabulary, the rules that bite, each with the error message it produces, and the checks to run before calling a flow done. Point your agent at `node_modules/fascicle/dist/AGENTS.md`, or import it into a `CLAUDE.md` with `@node_modules/fascicle/dist/AGENTS.md`.
218
+
217
219
  The canonical worked example is [examples/pr-improve/](./examples/pr-improve/), with its design rationale in [examples/pr-improve/docs/architecture.md](./examples/pr-improve/docs/architecture.md).
218
220
 
219
221
  ## Where to go next
220
222
 
221
223
  - [docs/blueprint.md](./docs/blueprint.md) — **the agent blueprint**: the standard app architecture (start here when building an app)
222
224
  - [docs/getting-started.md](./docs/getting-started.md) — install and run your first flow
225
+ - [docs/learn/](./docs/learn/README.md) is a course in fourteen short lessons that starts from a single step and ends with designing your own flows, with notes written for your coding agent as well
223
226
  - [docs/concepts.md](./docs/concepts.md) — step-as-value, trajectories, cancellation
224
227
  - [docs/composition.md](./docs/composition.md) — full composition surface: the 23 primitives, run/stream, checkpointing
225
228
  - [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
package/dist/AGENTS.md ADDED
@@ -0,0 +1,355 @@
1
+ # Fascicle Primer for Coding Agents
2
+
3
+ This file is for a coding agent (Claude Code, Codex, Cursor, or another) that's
4
+ working in a project which uses the published `fascicle` package. A person who
5
+ is learning Fascicle will usually import it from their `CLAUDE.md`, as
6
+ [lesson 0](https://github.com/robmclarty/fascicle/blob/v0.16.4/docs/learn/00-set-up.md) shows. Every shape, rule, and error message below
7
+ was checked against `fascicle` 0.16.3, and against 0.15.0 where the two differ,
8
+ and a rule that a later release changes says what changed.
9
+
10
+ Your training data probably holds little or nothing about Fascicle, so treat
11
+ this file and the installed type declarations as the truth, and don't fill gaps
12
+ from other agent frameworks.
13
+
14
+ ## Ground Truth
15
+
16
+ - **The installed types are authoritative.** Before you use an API that you
17
+ haven't used yet in this session, read its declaration in
18
+ `node_modules/fascicle/dist/index.d.ts`, or in `adapters.d.ts`,
19
+ `testing.d.ts`, `agents.d.ts`, or `viewer.d.ts` for the subpaths. Don't
20
+ invent options. Follow the imports, too. Core types such as `Step`,
21
+ `RunContext` (which holds `ctx.call` and `ctx.abort`), and `StepOptions` live
22
+ in files with generated names like `dist/types-<hash>.d.ts`, so search
23
+ `dist/*.d.ts` for a name when `index.d.ts` only re-exports it.
24
+ - **The package README** ships at `node_modules/fascicle/README.md`, and
25
+ releases after 0.16.3 ship this primer too, at
26
+ `node_modules/fascicle/dist/AGENTS.md`, with its links pointed at GitHub.
27
+ - **The repository**, when the person has it cloned (often at `../fascicle`),
28
+ holds the docs and the runnable examples. `docs/blueprint.md` is the app
29
+ architecture, and `docs/composition.md` has one line on every composer.
30
+ - **The two checked versions differ only in the viewer.** On 0.15 it mishandles
31
+ a trajectory file that holds more than one run, so delete `.trajectory.jsonl`
32
+ between runs, and from 0.16 on it follows the newest run.
33
+
34
+ ## The Model in Four Sentences
35
+
36
+ Everything is a `Step<i, o>`, a plain object with an `id`, a `kind`, and a
37
+ `run` function. Composers take steps and return a step, so a whole flow is one
38
+ step, and a tree of plain objects that you can print before it runs.
39
+ `run(flow, input, options?)` executes it and returns a promise of the output.
40
+ An engine (`create_engine`) talks to model providers, and `model_step` or
41
+ `model_call` turns an engine call into a step.
42
+
43
+ ## Imports
44
+
45
+ | From | What |
46
+ | --- | --- |
47
+ | `fascicle` | `run`, `step`, `sequence`, `parallel`, `branch`, `map`, `pipe`, `chain`, `loop`, `retry`, `fallback`, `timeout`, `compose`, `adversarial`, `ensemble_step`, `consensus`, `checkpoint`, `suspend`, `gate`, `describe`, `model_step`, `model_call`, `create_engine`, `define_tool`, `error_path`, the error classes, and the types (`Step`, `Engine`, `RunContext`, `GenerateOptions`, ...) |
48
+ | `fascicle/adapters` | `filesystem_logger`, `http_logger`, `stderr_logger`, `tee_logger`, `noop_logger`, `filesystem_store` |
49
+ | `fascicle/testing` | `make_stub_engine`, `make_script_engine`, `make_capture_engine`, `text_of`, `engine_from_generate` |
50
+ | `fascicle/agents` | `define_agent` |
51
+ | `fascicle/viewer` | `start_viewer` |
52
+
53
+ Two commands ship in the package: `fascicle-viewer <trajectory.jsonl>` and
54
+ `fascicle-diagram <module.ts>`, both run with `pnpm exec`. `fascicle-diagram`
55
+ reads the module's `flow` export, which is either a Step or a function with no
56
+ arguments that builds one, and it takes `--prefix ' * '`, `--width <n>`, and
57
+ `--export <name>`, plus `--internals` after 0.16.3.
58
+
59
+ ## The Core Vocabulary
60
+
61
+ ```ts
62
+ step('add', ({ a, b }: Pair) => a + b) // Step<Pair, number>
63
+ step('add', fn, { name: 'Add two numbers', description: 'shown in diagrams' })
64
+ step('solve', async (question: string, ctx) => ctx.call(inner, question), { arm: inner })
65
+ step('diff', (repo: string, ctx) => staged_diff(repo, ctx.abort)) // ctx.abort is the run's AbortSignal
66
+
67
+ await run(flow, input) // resolves to the output
68
+ await run(flow, input, { trajectory: filesystem_logger({ output_path: '.trajectory.jsonl' }) })
69
+ await run(flow, input, { install_signal_handlers: false }) // tests and long-running hosts
70
+
71
+ sequence([a, b, c]) // each step gets the previous output
72
+ parallel({ sum: add, product: multiply }) // same input to all; returns { sum, product }
73
+ branch({ when: (x: X) => boolean, then: step_a, otherwise: step_b }) // either arm's output
74
+ map({ items: (input: In) => list, do: per_item, concurrency: 4 }) // array out, in order
75
+ pipe(step_a, (value) => reshape(value)) // one step and one plain function, no more
76
+
77
+ chain('question').input<string>() // record starts as { question }
78
+ .step('problem', extract, ({ question }) => question) // step form: a Step plus a selector
79
+ .step('answer', ({ problem }) => calculate(problem), { description: 'code does the math' }) // function form, with options
80
+ .output(({ answer }) => `${answer}`) // closes into a Step<string, string>
81
+
82
+ loop({
83
+ init: (input: In): State => initial, // input to starting state
84
+ body: one_round, // Step<State, State>, runs before the guard
85
+ guard: (state) => done(state), // true stops; or a Step returning { stop, state }
86
+ finish: (state, { converged, rounds }) => result,
87
+ max_rounds: 3, // required
88
+ })
89
+
90
+ retry(leaf, { max_attempts: 3, backoff_ms: 500 }) // reruns on a throw, never on abort or suspend
91
+ timeout(leaf, 30_000) // throws timeout_error
92
+ fallback(primary, backup) // backup runs when primary throws
93
+
94
+ describe(flow) // text tree (prints system prompts in full)
95
+ describe.diagram(flow) // compact annotated tree; best for showing a person
96
+ describe.diagram(flow, { prefix: ' * ' }) // ready to paste into a doc comment
97
+ describe.json(flow) // the tree as data
98
+ ```
99
+
100
+ Model steps and engines:
101
+
102
+ ```ts
103
+ const engine = create_engine({ providers: { openrouter: { api_key, transport: 'native' } } })
104
+
105
+ const extract = model_step({
106
+ engine, model: 'anthropic/claude-haiku-5.5',
107
+ system: EXTRACT_PROMPT, // first line is a role id, such as 'solver/extract'
108
+ schema: problem_schema, // any Standard Schema, usually zod; the output is typed by it
109
+ id: 'extract', description: 'the model reads the numbers out of the question',
110
+ }) // Step<string | readonly Message[], Problem>
111
+
112
+ model_call({ ...same config }) // the GenerateResult envelope: content, usage, cost, finish_reason
113
+ await engine.dispose() // always, in finally
114
+ ```
115
+
116
+ Five providers need no extra package on `transport: 'native'`. They're
117
+ `openrouter`, `anthropic`, and `openai`, each with an `api_key`, and `ollama`
118
+ and `lmstudio`, each with a `base_url`, usually `http://localhost:11434` and
119
+ `http://localhost:1234/v1`.
120
+
121
+ ## Rules That Bite
122
+
123
+ Each of these was hit while the lessons were being checked, and the quoted
124
+ messages are the real ones.
125
+
126
+ 1. **Step ids are identifiers.** `step('add numbers', ...)` throws at
127
+ construction: `TypeError: step id "add numbers" is not a valid identifier:
128
+ ids are read back as property names, so use add_numbers and put the label in
129
+ meta.name`. Put prose in `{ name }`.
130
+ 2. **A step takes one input.** Bundle several values into an object.
131
+ 3. **Open a chain with its input type**, `chain('name').input<T>()` or the
132
+ equivalent `chain<T, 'name'>('name')`. Without it, through 0.16.3 the input
133
+ type is `never`, and you'll see `Property 'a' does not exist on type 'never'`.
134
+ Later releases type it as `ChainInputUndeclared<"call .input<T>() on the chain to say what it takes">`, which says the same thing outright.
135
+ 4. **A mis-wired literal `sequence`** reports `TS2769: No overload matches this
136
+ call`. Through 0.16.3 it reports it on more than one element, so read the
137
+ last `Type 'X' is not assignable to type 'Y'` line, which names the joint.
138
+ Later releases report it once, on the step that can't take its input, and
139
+ the type names the joint, what arrives there, and what the step accepts, as
140
+ in `SequenceJointMismatch<"after children[1]", string, number>`.
141
+ 5. **Through 0.16.3, `branch` arms must share an output type.** Otherwise
142
+ you'll get `Type 'Step<Pair, number>' is not assignable to type 'Step<Pair, string>'`,
143
+ so state the union, as in `branch<Pair, number | null>({ ... })`. Later
144
+ releases return the union of the arms' outputs, and naming one output type
145
+ still holds both arms to it.
146
+ 6. **`model_step`'s input type is `string | readonly Message[]`.** Annotate a
147
+ model leaf as `Step<string, T>` before you combine it. Through 0.16.3, an
148
+ unannotated model leaf beside a string step in a `parallel` makes the input
149
+ `string & readonly Message[]`, which no value satisfies. Later releases take
150
+ the input that every member accepts, a `string` there, and the annotation
151
+ still keeps the types easy to read.
152
+ 7. **Through 0.16.3, the schema never reaches the model on the native
153
+ transport.** The engine asks for JSON that matches "the expected schema,"
154
+ validates the reply, and repairs once after a failure
155
+ (`schema_repair_attempts`, default 1). So on those versions, put an example
156
+ of the exact JSON shape, with its field names, in the system prompt:
157
+ `Reply with JSON only, shaped like this: {"a": 10, "b": 2, "op": "subtract"}`.
158
+ Without one, the first reply usually fails and costs a second round trip, and
159
+ small local models may never recover. Text in a zod `.describe()` doesn't
160
+ reach the model on those versions either. Releases after 0.16.3 put the JSON
161
+ Schema itself in that instruction, so the example becomes optional and the
162
+ advice in `docs/blueprint.md` to keep field rules in `.describe()` holds.
163
+ The installed version is in `node_modules/fascicle/package.json`.
164
+ 8. **The system prompt's first line is a stable role id**, like
165
+ `solver/extract`. `make_stub_engine` routes canned answers by prefix on it,
166
+ and an unmatched system prompt throws
167
+ `make_stub_engine: no canned response for system: ...`.
168
+ 9. **Through 0.16.3, a stub's `content` function has no inferred parameter
169
+ types**, because `content` is typed `unknown`, so annotate them:
170
+ `(opts: GenerateOptions, call_index: number) => ...`. Later releases infer
171
+ them for a function written inline.
172
+ 10. **Inside a step body, run other steps with `ctx.call(step, input)`**, never
173
+ `step.run(...)`, which loses the span and cancellation. Declare what the body
174
+ calls with `{ arm: step }` or `{ arm: [a, b] }`, so `describe` shows it.
175
+ 11. **`pipe` is binary.** To chain steps, use `sequence`.
176
+ 12. **Model ids go to the provider verbatim**, and each provider spells them its
177
+ own way: `anthropic/claude-haiku-5.5` on OpenRouter, `claude-haiku-5-5` on
178
+ Anthropic, `gpt-5-mini` on OpenAI, `qwen3:4b-instruct-2507-q4_K_M` on Ollama.
179
+ A wrong id fails with the provider's own message, such as
180
+ `provider_error: openrouter API error 400: anthropic/claude-haiku-9 is not a
181
+ valid model ID`.
182
+ 13. **The engine never reads `process.env`.** Your code reads keys and passes
183
+ them in. Keep keys in `.env` and run with `pnpm exec tsx --env-file=.env`.
184
+ A bad key throws `provider_auth_error`.
185
+ 14. **`create_engine` belongs in one module**, and everything else receives an
186
+ `Engine`. Dispose engines in `finally`.
187
+ 15. **Run TypeScript with `tsx`.** Local imports end in `.js` under NodeNext
188
+ resolution, and plain `node` won't map a `.js` specifier to a `.ts` file.
189
+ 16. **In vitest files, rename Fascicle's `describe`**, as
190
+ `import { describe as describe_flow } from 'fascicle'`, since vitest has
191
+ one too. Pass `install_signal_handlers: false` to `run` in tests.
192
+ 17. **`describe(flow)` prints counter ids** like `chain_1`, which also appear in
193
+ `error_path`, and it prints system prompts in full. `describe.diagram` never
194
+ shows counter ids, so it's stable enough to snapshot in a test.
195
+ 18. **A trajectory holds no per-call message or reply text.** Its first event,
196
+ `flow_structure`, does carry every model step's system prompt, so treat the
197
+ file as sensitive. Beyond that it records spans, timings, token counts,
198
+ cost, and how the run ended. For a model's reply, read `raw_text` and
199
+ `schema_issues` on a `schema_validation_error`.
200
+ 19. **Through 0.16.3, `adversarial` draws its inner machinery** in a diagram:
201
+ `scope` and `stash` nodes, and internal steps such as `snapshot`. For a
202
+ draft, check, and redraft loop that a person has to read, a `loop` with a
203
+ code guard draws more simply there. Later releases draw a named composite
204
+ as the steps that it was built from (`build` and `critique`), and
205
+ `describe.diagram(flow, { internals: true })` draws the rest.
206
+ 20. **The `then` key in `branch`** can trip the `unicorn/no-thenable` lint rule.
207
+ It's a false positive.
208
+ 21. **The engine retries some network failures itself**, inside a model call.
209
+ `retry` works one level up and reruns the whole step when it fails, a schema
210
+ failure included, while an abort or a suspend passes straight through.
211
+
212
+ ## Decision Rules
213
+
214
+ - **Leaves, arms, spine.** A leaf is one boundary (a function step or a model
215
+ step). An arm composes around leaves (`retry`, `timeout`, `fallback`,
216
+ `checkpoint`, `map`, `parallel`, `sequence`, and the multi-model composites).
217
+ One `chain` per flow is the spine, and `branch` and `loop` steer it.
218
+ - **`sequence` or `chain`.** If every step needs only its predecessor's output,
219
+ use `sequence`. Once any step needs something older, use `chain`.
220
+ - **`model_step` or `model_call`.** Use `model_step` for the answer, and
221
+ `model_call` when you need usage, cost, tool calls, or the finish reason.
222
+ - **Declarative or direct.** Compose by default, so the shape shows in the
223
+ diagram. Use a named step with `ctx.call` when the control flow depends on the
224
+ data, and say why in a comment.
225
+ - **Don't over-compose.** A decision or a loop that's part of the flow's story
226
+ gets a composer. A detail inside one piece of work stays plain code in a step.
227
+ Wrapping a single step in `compose` or `sequence` only to name it adds nothing.
228
+ - **The model proposes, code decides.** Keep arithmetic, rules, filtering, and
229
+ file or network access in code. Give the model reading and writing.
230
+ - **Check every model output that matters**, with a schema, a rule in code, a
231
+ second model, or a person.
232
+ - **Suggest hardening, don't impose it.** Offer `retry`, `timeout`, and
233
+ `fallback` around network calls. Add them when asked.
234
+
235
+ ## From the Person's Words to Code
236
+
237
+ | They say | You build |
238
+ | --- | --- |
239
+ | "first, then" | `sequence` |
240
+ | "remember this for later," "use the original input" | a `chain` binding |
241
+ | "at the same time," "independently" | `parallel` |
242
+ | "for each," "every item" | `map`, with `concurrency` when they say "at most N at once" |
243
+ | "if, otherwise," "depending on" | `branch` |
244
+ | "until," "keep going while" | `loop`, always with `max_rounds` |
245
+ | "ask the model," "have it read or write" | `model_step` with a `schema` |
246
+ | "try again" | `retry` |
247
+ | "if that fails" | `fallback` |
248
+ | "give up after" | `timeout` |
249
+ | "check its work and redo it" | a `loop` with a code guard, or `adversarial` |
250
+ | "pick the best of" | `ensemble_step` |
251
+ | "only if they agree" | `consensus` |
252
+ | "ask me first," "wait for approval" | `suspend` or `gate`, with `run.until_suspended` |
253
+ | "don't redo the expensive part" | `checkpoint`, with a `checkpoint_store` |
254
+
255
+ ## Check Your Own Work
256
+
257
+ Before you tell the person that a flow is done:
258
+
259
+ 1. `pnpm exec tsc --noEmit` is clean.
260
+ 2. Print the diagram (`describe.diagram(flow)`, or
261
+ `pnpm exec fascicle-diagram <module>` against a module that exports
262
+ `flow`), compare it with what was asked, and show it to the person.
263
+ 3. Run it against a stub engine, which is free and gives the same answer every
264
+ time.
265
+ 4. Run the tests (`pnpm exec vitest run`) if the project has any.
266
+ 5. Run it live only after that, and only with the person's go-ahead when it
267
+ costs money. Offer `--env-file=.env` and the viewer command,
268
+ `pnpm exec fascicle-viewer .trajectory.jsonl`.
269
+
270
+ When something fails, read the whole message, then `error_path(err)` for where,
271
+ then the trajectory for timing and cost, then reproduce it with a stub before
272
+ you change anything.
273
+
274
+ ## Shapes to Copy
275
+
276
+ These are minimal sketches, not the course's code. When the person is working
277
+ through a lesson, the lesson's code wins.
278
+
279
+ One engine module that picks the provider from settings, with a stub when none
280
+ is set:
281
+
282
+ ```ts
283
+ // engine.ts
284
+ import { create_engine } from 'fascicle'
285
+ import type { Engine } from 'fascicle'
286
+
287
+ export function engine_from_env(make_stub: () => Engine, env = process.env): { engine: Engine; model: string } {
288
+ const provider = env['FASCICLE_PROVIDER'] ?? 'stub'
289
+ if (provider === 'stub') return { engine: make_stub(), model: 'stub' }
290
+ if (provider === 'openrouter') {
291
+ const api_key = env['OPENROUTER_API_KEY']
292
+ if (!api_key) throw new Error('OPENROUTER_API_KEY is not set: add it to .env, or export it in your shell')
293
+ return {
294
+ engine: create_engine({ providers: { openrouter: { api_key, transport: 'native' } } }),
295
+ model: env['FASCICLE_MODEL'] ?? 'anthropic/claude-haiku-5.5',
296
+ }
297
+ }
298
+ throw new Error(`unknown FASCICLE_PROVIDER "${provider}": use stub or openrouter`)
299
+ }
300
+ ```
301
+
302
+ A spine with a model leaf, where the model reads and code computes:
303
+
304
+ ```ts
305
+ // calc_flow.ts
306
+ import { chain, model_step } from 'fascicle'
307
+ import type { Engine, Step } from 'fascicle'
308
+ import { calculate, problem_schema } from './calc.js'
309
+ import type { Problem } from './calc.js'
310
+
311
+ const EXTRACT = `calc/extract
312
+ Read an arithmetic word problem and pull out the two numbers and the one
313
+ operation that answers it. Reply with JSON only, shaped like this:
314
+ {"a": 10, "b": 2, "op": "subtract"}`
315
+
316
+ export function build_calculator(engine: Engine, model: string): Step<string, number> {
317
+ const extract: Step<string, Problem> = model_step({ engine, model, system: EXTRACT, schema: problem_schema, id: 'extract' })
318
+ return chain('question').input<string>()
319
+ .step('problem', extract, ({ question }) => question)
320
+ .step('answer', ({ problem }) => calculate(problem))
321
+ .output(({ answer }) => answer)
322
+ }
323
+ ```
324
+
325
+ A test that runs the real flow on a stub:
326
+
327
+ ```ts
328
+ // calc_flow.test.ts
329
+ import { describe, expect, it } from 'vitest'
330
+ import { describe as describe_flow, run } from 'fascicle'
331
+ import { make_stub_engine } from 'fascicle/testing'
332
+ import { build_calculator } from './calc_flow.js'
333
+
334
+ describe('the calculator', () => {
335
+ it('computes the answer in code', async () => {
336
+ const engine = make_stub_engine([{ prefix: 'calc/extract', content: { a: 3, b: 4, op: 'add' } }])
337
+ expect(await run(build_calculator(engine, 'stub'), 'Sam has 3 apples and buys 4 more.', { install_signal_handlers: false })).toBe(7)
338
+ })
339
+
340
+ it('keeps its shape', () => {
341
+ expect(describe_flow.diagram(build_calculator(make_stub_engine([]), 'stub'))).toMatchInlineSnapshot()
342
+ })
343
+ })
344
+ ```
345
+
346
+ ## Where to Look Next
347
+
348
+ - [blueprint.md](https://github.com/robmclarty/fascicle/blob/v0.16.4/docs/blueprint.md) for the layout of a growing app.
349
+ - [leaf-arm-spine.md](https://github.com/robmclarty/fascicle/blob/v0.16.4/docs/leaf-arm-spine.md) for choosing a primitive at each
350
+ layer.
351
+ - [composition.md](https://github.com/robmclarty/fascicle/blob/v0.16.4/docs/composition.md) for one line on every composer.
352
+ - [cookbook.md](https://github.com/robmclarty/fascicle/blob/v0.16.4/docs/cookbook.md) for worked patterns, including tool loops with
353
+ `define_tool`.
354
+ - [testing.md](https://github.com/robmclarty/fascicle/blob/v0.16.4/docs/testing.md) for the stand-in engines.
355
+ - [troubleshooting.md](https://github.com/robmclarty/fascicle/blob/v0.16.4/docs/troubleshooting.md) for errors and their causes.
package/dist/acp.js CHANGED
@@ -1,4 +1,4 @@
1
- import { E as run, k as aborted_error } from "./core-CErsxGF6.js";
1
+ import { E as run, k as aborted_error } from "./core-BOFcG3tp.js";
2
2
  import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
3
3
  import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
4
4
  import { a as read_file_tool, c as resolve_roots, i as is_binary, l as shown_path, n as search_tool, o as contain_writable, r as list_files_tool, s as error_code } from "./search-CpCJYMUm.js";
package/dist/agents.js CHANGED
@@ -1,4 +1,4 @@
1
- import { b as assert_valid_step_id, k as aborted_error, y as step } from "./core-CErsxGF6.js";
1
+ import { b as assert_valid_step_id, k as aborted_error, y as step } from "./core-BOFcG3tp.js";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  //#region src/agents/define_agent.ts
@@ -308,7 +308,10 @@ const COLUMN_GAP = 2;
308
308
  */
309
309
  function render_diagram(root, options) {
310
310
  const rows = [];
311
- flatten(to_item(root, void 0, options?.replays === true ? replay_gates(root) : /* @__PURE__ */ new Map()), "", "", rows);
311
+ flatten(to_item(root, void 0, {
312
+ marks: options?.replays === true ? replay_gates(root) : /* @__PURE__ */ new Map(),
313
+ internals: options?.internals === true
314
+ }), "", "", rows);
312
315
  const column = Math.max(...rows.map((row) => row.lead.length + row.head.length)) + COLUMN_GAP;
313
316
  const prefix = options?.prefix ?? "";
314
317
  const limit = options?.width === void 0 ? Number.POSITIVE_INFINITY : options.width - prefix.length - column;
@@ -358,12 +361,12 @@ function wrap(words, limit) {
358
361
  * Convert one node into the item the layout draws. `role` is the name the
359
362
  * parent gives this child, and it is dropped when it only repeats the label.
360
363
  */
361
- function to_item(node, role, marks) {
364
+ function to_item(node, role, draw) {
362
365
  const { label, by_kind } = label_of(node);
363
366
  return {
364
367
  head: role === void 0 || role === label ? label : `${role} ${label}`,
365
- note: [...note_of(node, by_kind), ...replay_note(marks.get(node))],
366
- children: child_items(node, marks)
368
+ note: [...note_of(node, by_kind), ...replay_note(draw.marks.get(node))],
369
+ children: child_items(node, draw)
367
370
  };
368
371
  }
369
372
  /**
@@ -391,16 +394,58 @@ function note_of(node, by_kind) {
391
394
  * Convert a node's children, naming each by the role its parent's kind gives
392
395
  * it.
393
396
  */
394
- function child_items(node, marks) {
397
+ function child_items(node, draw) {
395
398
  const children = node.children ?? [];
396
- if (node.kind === "branch") return children.map((child, i) => to_item(child, BRANCH_ROLES[i], marks));
397
- if (node.kind === "loop") return children.map((child, i) => to_item(child, i === 1 ? "guard" : void 0, marks));
399
+ const parts = draw.internals ? [] : part_nodes(node);
400
+ if (parts.length > 0) return parts.map(([role, part]) => to_item(part, role, draw));
401
+ if (node.kind === "branch") return children.map((child, i) => to_item(child, BRANCH_ROLES[i], draw));
402
+ if (node.kind === "loop") return children.map((child, i) => to_item(child, i === 1 ? "guard" : void 0, draw));
398
403
  if (node.kind === "parallel") {
399
404
  const keys = string_list(node.config?.["keys"]);
400
- return children.map((child, i) => to_item(child, keys[i], marks));
405
+ return children.map((child, i) => to_item(child, keys[i], draw));
401
406
  }
402
- if (node.kind === "chain") return staged_items(children, string_list(node.config?.["plan"]), marks);
403
- return children.map((child) => to_item(child, void 0, marks));
407
+ if (node.kind === "chain") return staged_items(children, string_list(node.config?.["plan"]), draw);
408
+ return children.map((child) => to_item(child, void 0, draw));
409
+ }
410
+ /**
411
+ * The parts that a named composite records, by role, each resolved to the
412
+ * node its path leads to. A composite that records none, or a path that leads
413
+ * nowhere (a hand-edited tree, say), reads as no parts, and the composite's
414
+ * own children are drawn instead.
415
+ */
416
+ function part_nodes(node) {
417
+ const parts = node.config?.["parts"];
418
+ if (node.kind !== "compose" || !is_flow_record(parts)) return [];
419
+ const resolved = [];
420
+ for (const [role, path] of Object.entries(parts)) {
421
+ const part = follow(node, path);
422
+ if (part === void 0) return [];
423
+ resolved.push([role, part]);
424
+ }
425
+ return resolved;
426
+ }
427
+ /**
428
+ * The node that a path of child indices leads to from `from`, or `undefined`
429
+ * when the path isn't a list of indices that each name a child.
430
+ */
431
+ function follow(from, path) {
432
+ if (!Array.isArray(path)) return void 0;
433
+ const steps = path;
434
+ let current = from;
435
+ for (const index of steps) {
436
+ if (typeof index !== "number") return void 0;
437
+ current = current?.children?.[index];
438
+ }
439
+ return current === from ? void 0 : current;
440
+ }
441
+ /**
442
+ * True for a config value that's a record rather than a list or a scalar. A
443
+ * marker such as a function's reads as a record too, and `follow` turns it
444
+ * away, since none of its values is a path.
445
+ */
446
+ function is_flow_record(value) {
447
+ if (value === null || Array.isArray(value)) return false;
448
+ return typeof value === "object";
404
449
  }
405
450
  /**
406
451
  * Convert a chain's children in plan order, nesting the entries after each
@@ -408,7 +453,7 @@ function child_items(node, marks) {
408
453
  * encloses them in the trajectory. Children the plan does not account for
409
454
  * follow in order, so a node without a plan still draws every child.
410
455
  */
411
- function staged_items(children, plan, marks) {
456
+ function staged_items(children, plan, draw) {
412
457
  const top = [];
413
458
  let target = top;
414
459
  let next = 0;
@@ -423,9 +468,9 @@ function staged_items(children, plan, marks) {
423
468
  } else {
424
469
  const child = children[next];
425
470
  next += 1;
426
- if (child !== void 0) target.push(to_item(child, void 0, marks));
471
+ if (child !== void 0) target.push(to_item(child, void 0, draw));
427
472
  }
428
- for (const child of children.slice(next)) target.push(to_item(child, void 0, marks));
473
+ for (const child of children.slice(next)) target.push(to_item(child, void 0, draw));
429
474
  return top;
430
475
  }
431
476
  /**
@@ -2330,8 +2375,9 @@ register_traced_kind("parallel");
2330
2375
  * branch: conditional routing.
2331
2376
  *
2332
2377
  * `branch({ when, then, otherwise })` evaluates `when(input)`; if truthy, runs
2333
- * `then`, else runs `otherwise`. Both branches must return the same output
2334
- * type.
2378
+ * `then`, else runs `otherwise`. The branch returns whichever arm ran, so its
2379
+ * output type is the union of the two arms' outputs, and naming one output
2380
+ * type, as in `branch<Pair, number | null>`, holds both arms to it.
2335
2381
  */
2336
2382
  let branch_counter = 0;
2337
2383
  /**
@@ -2352,7 +2398,7 @@ function branch(config) {
2352
2398
  const id = next_id$8();
2353
2399
  const { when, then: then_step, otherwise: otherwise_step, name } = config;
2354
2400
  const run_fn = async (input, ctx) => {
2355
- return dispatch_step(await when(input) ? then_step : otherwise_step, input, ctx);
2401
+ return await when(input) ? dispatch_step(then_step, input, ctx) : dispatch_step(otherwise_step, input, ctx);
2356
2402
  };
2357
2403
  const config_meta = {
2358
2404
  when,
@@ -3050,21 +3096,61 @@ function next_id$1() {
3050
3096
  * The step's `kind` is always `'compose'`; `config.name` becomes the
3051
3097
  * `display_name` used as the span label. Throws a `TypeError` when `name`
3052
3098
  * is not a non-empty string, catching the mistake at construction time.
3099
+ *
3100
+ * Each of `config.parts` is recorded as the path of child indices that leads
3101
+ * to it from the composite, so `describe.json` keeps the whole tree that the
3102
+ * viewer maps spans onto while `describe.diagram` can draw just the parts. A
3103
+ * part that isn't inside `inner` throws, since there would be no path to draw.
3053
3104
  */
3054
3105
  function compose(inner, config) {
3055
3106
  const name = config?.name;
3056
3107
  if (typeof name !== "string" || name.length === 0) throw new TypeError("compose(inner, { name }): name must be a non-empty string");
3108
+ const parts = part_paths(inner, config.parts);
3057
3109
  const id = next_id$1();
3058
3110
  const run_fn = (input, ctx) => dispatch_step(inner, input, ctx);
3059
3111
  return {
3060
3112
  id,
3061
3113
  kind: "compose",
3062
3114
  children: [inner],
3063
- config: { display_name: name },
3115
+ config: parts === void 0 ? { display_name: name } : {
3116
+ display_name: name,
3117
+ parts
3118
+ },
3064
3119
  ...description_meta(config.description),
3065
3120
  run: run_fn
3066
3121
  };
3067
3122
  }
3123
+ /**
3124
+ * The path of child indices from the composite to each part, by role, or
3125
+ * `undefined` when there are no parts. Every path starts at `inner`, the
3126
+ * composite's only child.
3127
+ */
3128
+ function part_paths(inner, parts) {
3129
+ if (parts === void 0) return void 0;
3130
+ const paths = {};
3131
+ for (const [role, part] of Object.entries(parts)) {
3132
+ const path = path_to(inner, part, /* @__PURE__ */ new Set());
3133
+ if (path === void 0) throw new TypeError(`compose(inner, { parts }): part "${role}" (${part.kind} ${part.id}) is not inside inner, so the diagram would have nothing to draw for it`);
3134
+ paths[role] = [0, ...path];
3135
+ }
3136
+ return paths;
3137
+ }
3138
+ /**
3139
+ * The child indices that lead from `from` to `target`, found depth first by
3140
+ * identity, or `undefined` when `target` isn't below it. `seen` keeps a shared
3141
+ * step from being walked twice.
3142
+ */
3143
+ function path_to(from, target, seen) {
3144
+ if (from === target) return [];
3145
+ if (seen.has(from)) return void 0;
3146
+ seen.add(from);
3147
+ const children = from.children;
3148
+ if (children === void 0) return void 0;
3149
+ for (const [index, child] of children.entries()) {
3150
+ const rest = path_to(child, target, seen);
3151
+ if (rest !== void 0) return [index, ...rest];
3152
+ }
3153
+ }
3068
3154
  register_traced_kind("compose");
3069
3155
  //#endregion
3070
3156
  //#region src/core/checkpoint.ts
@@ -3437,8 +3523,9 @@ register_traced_kind("use");
3437
3523
  * `chain<i>(input_name?)` opens a builder whose threaded value is a record of
3438
3524
  * named outputs rather than a single value. The input type must be stated,
3439
3525
  * either as the type argument or via `.input<t>()` on the freshly opened
3440
- * chain; an unannotated `chain()` defaults to `never` so the omission fails
3441
- * at the `run` call site instead of accepting anything. `.step(name, fn)`
3526
+ * chain. An unannotated `chain()` takes a branded type that nothing satisfies,
3527
+ * so the omission fails at the first field read or the `run` call site, with
3528
+ * the fix spelled out in the message, instead of accepting anything. `.step(name, fn)`
3442
3529
  * runs `fn` over the record and merges its output back in under `name`;
3443
3530
  * `.stage(name, project?)` concludes a phase: it opens a grouping span in
3444
3531
  * the trajectory and, when `project` is given, replaces the record with the
@@ -3597,9 +3684,9 @@ function make_chain(input_name, entries, bound) {
3597
3684
  /**
3598
3685
  * Open a chain builder whose record starts as `{ [input_name]: input }`.
3599
3686
  *
3600
- * `input_name` defaults to `'input'`. The input type defaults to `never`, so
3601
- * a chain that never states it produces a `Step<never, o>` that no real
3602
- * input satisfies at `run`; state it as the type argument or, when the
3687
+ * `input_name` defaults to `'input'`. The input type defaults to a branded
3688
+ * `ChainInputUndeclared` that no real input satisfies at `run`, and whose
3689
+ * name in an error says what to do; state it as the type argument or, when the
3603
3690
  * binding is renamed, once via `.input<t>()` on the fresh builder. Each
3604
3691
  * `.step` narrows subsequent callbacks to the record accumulated so far, and
3605
3692
  * `.stage` with a projection re-types the record to the projection's
@@ -3619,4 +3706,4 @@ register_traced_kind("chain");
3619
3706
  //#endregion
3620
3707
  export { describe_cycle_error as A, durable as C, describe as D, run as E, suspended_error as F, timeout_error as I, STEP_KINDS as L, flow_changed_error as M, resume_validation_error as N, is_step as O, run_not_found_error as P, is_step_kind as R, suggest_step_id as S, validate_schema as T, parallel as _, suspend as a, assert_valid_step_id as b, loop as c, retry as d, compute_backoff as f, branch as g, map as h, use as i, error_path as j, aborted_error as k, timeout as l, pipe as m, scope as n, checkpoint as o, wait_with_abort as p, stash as r, compose as s, chain as t, fallback as u, sequence as v, format_schema_issues as w, is_valid_step_id as x, step as y, resolve_display_name as z };
3621
3708
 
3622
- //# sourceMappingURL=core-CErsxGF6.js.map
3709
+ //# sourceMappingURL=core-BOFcG3tp.js.map