fascicle 0.16.3 → 0.16.5

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.16.5 — 2026-10-21
4
+
5
+ ### Fixed
6
+
7
+ - **A `claude_cli` session that isn't logged in says so.** A `claude -p` with no session to call with writes its reason to stdout, as a message in the model's place with the `authentication_failed` error code and an error result that reads "Not logged in · Please run /login", and it leaves stderr empty. The adapter read only stderr, so the call failed as `claude_cli_error: claude CLI exited with code 1:` with nothing after the colon. It reads the stream's error code as well now and throws `provider_auth_error` in the CLI's own words, `claude CLI reported an auth failure: Not logged in · Please run /login`, and any other failed exit with nothing on stderr carries the text of the CLI's error result. The error's `refresh_command` is `claude auth login`, since the CLI reads `claude login` as a prompt and opens a session.
8
+
9
+ ### Internal
10
+
11
+ - The `claude_cli` examples and their READMEs say `claude auth login` where they said `claude login`.
12
+
13
+ ## v0.16.4 — 2026-10-21
14
+
15
+ ### Added
16
+
17
+ - **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.
18
+
19
+ ### Changed
20
+
21
+ - **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.
22
+ - **`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.
23
+ - **`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.
24
+
25
+ ### Fixed
26
+
27
+ - **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.
28
+ - **`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.
29
+ - **`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.
30
+ - **`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.
31
+ - **`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.
32
+ - **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`.
33
+ - **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.
34
+
3
35
  ## v0.16.3 — 2026-10-19
4
36
 
5
37
  ### 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.5/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.5/docs/blueprint.md) for the layout of a growing app.
349
+ - [leaf-arm-spine.md](https://github.com/robmclarty/fascicle/blob/v0.16.5/docs/leaf-arm-spine.md) for choosing a primitive at each
350
+ layer.
351
+ - [composition.md](https://github.com/robmclarty/fascicle/blob/v0.16.5/docs/composition.md) for one line on every composer.
352
+ - [cookbook.md](https://github.com/robmclarty/fascicle/blob/v0.16.5/docs/cookbook.md) for worked patterns, including tool loops with
353
+ `define_tool`.
354
+ - [testing.md](https://github.com/robmclarty/fascicle/blob/v0.16.5/docs/testing.md) for the stand-in engines.
355
+ - [troubleshooting.md](https://github.com/robmclarty/fascicle/blob/v0.16.5/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