fascicle 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,48 @@
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
+
35
+ ## v0.11.1 — 2026-08-13
36
+
37
+ ### Fixed
38
+ - Broke an import cycle between the viewer CLI and its barrel module.
39
+
40
+ ### Internal
41
+ - Reduced complexity across the engine, core, composites, and adapter layers by decomposing large functions (provider dispatch, tool-loop orchestration, generate, retry, native-provider streaming, and more) to clear the health complexity gate.
42
+ - Removed dead exports, types, and duplicate re-exports surfaced by dead-code analysis; extracted shared test and trajectory-logger scaffolding to cut duplication.
43
+ - Health's complexity metric (CRAP) now reads real test coverage instead of an estimate; closed the viewer CLI's coverage gap with new in-process tests and retired the mutation-testing excludes that existed only because those files were untested.
44
+ - Scoped health complexity checks to production source only, de-flaked a claude_cli timing test, and tuned fallow/lint config.
45
+
3
46
  ## v0.11.0 — 2026-08-12
4
47
 
5
48
  ### Changed
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
@@ -2,25 +2,27 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
4
  import { appendFileSync, mkdirSync } from "node:fs";
5
- //#region src/adapters/line_logger.ts
5
+ //#region src/adapters/trajectory_recorder.ts
6
6
  /**
7
- * Shared line-oriented trajectory logger core.
7
+ * Shared span/record core for trajectory loggers.
8
+ *
9
+ * Every fascicle trajectory logger emits the same wire format (one JSON object
10
+ * per event) and differs only in where each event goes: `line_logger` writes a
11
+ * line, `http_logger` POSTs NDJSON. This module holds the span bookkeeping they
12
+ * share, parameterized by a single `emit` sink.
8
13
  *
9
- * `filesystem_logger` and `stderr_logger` emit the same wire format (one JSON
10
- * object per line) and differ only in where the line goes. This module holds
11
- * the common span bookkeeping: `start_span` and `end_span` each emit a line;
12
- * `record` emits the event as written. When the caller supplies
13
- * `parent_span_id` in the span meta (the runner threads the true structural
14
- * parent through `RunContext`), that value is used verbatim, so span trees are
15
- * correct even for concurrent children under `parallel`/`map`. Only when no
16
- * parent is supplied does the logger fall back to an in-memory stack of
17
- * still-open spans, which is best-effort under concurrency.
14
+ * `start_span` and `end_span` each emit one event; `record` emits the event as
15
+ * written. When the caller supplies `parent_span_id` in the span meta (the
16
+ * runner threads the true structural parent through `RunContext`), that value is
17
+ * used verbatim, so span trees are correct even for concurrent children under
18
+ * `parallel`/`map`. Only when no parent is supplied does the recorder fall back
19
+ * to an in-memory stack of still-open spans, which is best-effort under
20
+ * concurrency.
18
21
  */
19
22
  /**
20
- * Create a `TrajectoryLogger` that writes one JSON object per line via
21
- * `write_line`.
23
+ * Build a `TrajectoryLogger` whose events are handed, one at a time, to `emit`.
22
24
  */
23
- function line_logger(write_line) {
25
+ function trajectory_recorder(emit) {
24
26
  const stack = [];
25
27
  const start_span = (name, meta) => {
26
28
  const span_id = `${name}:${randomUUID().slice(0, 8)}`;
@@ -31,12 +33,12 @@ function line_logger(write_line) {
31
33
  ...meta
32
34
  };
33
35
  if (event["parent_span_id"] === void 0 && stack.length > 0) event["parent_span_id"] = stack[stack.length - 1];
34
- write_line(event);
36
+ emit(event);
35
37
  stack.push(span_id);
36
38
  return span_id;
37
39
  };
38
40
  const end_span = (id, meta) => {
39
- write_line({
41
+ emit({
40
42
  kind: "span_end",
41
43
  span_id: id,
42
44
  ...meta
@@ -45,7 +47,7 @@ function line_logger(write_line) {
45
47
  if (idx !== -1) stack.splice(idx, 1);
46
48
  };
47
49
  const record = (event) => {
48
- write_line({ ...event });
50
+ emit({ ...event });
49
51
  };
50
52
  return {
51
53
  record,
@@ -54,6 +56,15 @@ function line_logger(write_line) {
54
56
  };
55
57
  }
56
58
  //#endregion
59
+ //#region src/adapters/line_logger.ts
60
+ /**
61
+ * Create a `TrajectoryLogger` that writes one JSON object per line via
62
+ * `write_line`.
63
+ */
64
+ function line_logger(write_line) {
65
+ return trajectory_recorder(write_line);
66
+ }
67
+ //#endregion
57
68
  //#region src/adapters/filesystem_logger.ts
58
69
  /**
59
70
  * Filesystem JSONL trajectory logger.
@@ -80,21 +91,6 @@ function filesystem_logger(options) {
80
91
  //#endregion
81
92
  //#region src/adapters/http_logger.ts
82
93
  /**
83
- * HTTP push trajectory logger.
84
- *
85
- * Conforms to `TrajectoryLogger`. POSTs each event as a single line of
86
- * newline-delimited JSON to a configured URL. Pairs naturally with the
87
- * fascicle viewer's `/api/ingest` endpoint, but is a generic adapter: the
88
- * receiver can be anything that accepts NDJSON over HTTP.
89
- *
90
- * Failure policy: drop on transport error and invoke the optional `on_error`
91
- * callback. Never throws, never blocks the user's flow on a dev tool being
92
- * up. The flow always wins; the viewer is best-effort.
93
- *
94
- * Hierarchical span ids are tracked in-process, mirroring `filesystem_logger`
95
- * so the wire format is identical.
96
- */
97
- /**
98
94
  * Default `HttpLoggerFetch`, backed by the global `fetch`.
99
95
  */
100
96
  const default_fetch = async (url, init) => {
@@ -115,7 +111,6 @@ const default_fetch = async (url, init) => {
115
111
  function http_logger(options) {
116
112
  const { url, on_error } = options;
117
113
  const send = options.fetch ?? default_fetch;
118
- const stack = [];
119
114
  const post = (event) => {
120
115
  const body = `${JSON.stringify(event)}\n`;
121
116
  send(url, {
@@ -128,36 +123,7 @@ function http_logger(options) {
128
123
  if (on_error) on_error(err);
129
124
  });
130
125
  };
131
- const start_span = (name, meta) => {
132
- const span_id = `${name}:${randomUUID().slice(0, 8)}`;
133
- const event = {
134
- kind: "span_start",
135
- span_id,
136
- name,
137
- ...meta
138
- };
139
- if (event["parent_span_id"] === void 0 && stack.length > 0) event["parent_span_id"] = stack[stack.length - 1];
140
- post(event);
141
- stack.push(span_id);
142
- return span_id;
143
- };
144
- const end_span = (id, meta) => {
145
- post({
146
- kind: "span_end",
147
- span_id: id,
148
- ...meta
149
- });
150
- const idx = stack.lastIndexOf(id);
151
- if (idx !== -1) stack.splice(idx, 1);
152
- };
153
- const record = (event) => {
154
- post({ ...event });
155
- };
156
- return {
157
- record,
158
- start_span,
159
- end_span
160
- };
126
+ return trajectory_recorder(post);
161
127
  }
162
128
  //#endregion
163
129
  //#region src/adapters/noop_logger.ts
@@ -301,4 +267,4 @@ function filesystem_store(options) {
301
267
  //#endregion
302
268
  export { http_logger as a, noop_logger as i, tee_logger as n, filesystem_logger as o, stderr_logger as r, filesystem_store as t };
303
269
 
304
- //# sourceMappingURL=adapters-CJnu1687.js.map
270
+ //# sourceMappingURL=adapters-hmnJOOgf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters-hmnJOOgf.js","names":[],"sources":["../src/adapters/trajectory_recorder.ts","../src/adapters/line_logger.ts","../src/adapters/filesystem_logger.ts","../src/adapters/http_logger.ts","../src/adapters/noop_logger.ts","../src/adapters/stderr_logger.ts","../src/adapters/tee_logger.ts","../src/adapters/filesystem_store.ts"],"sourcesContent":["/**\n * Shared span/record core for trajectory loggers.\n *\n * Every fascicle trajectory logger emits the same wire format (one JSON object\n * per event) and differs only in where each event goes: `line_logger` writes a\n * line, `http_logger` POSTs NDJSON. This module holds the span bookkeeping they\n * share, parameterized by a single `emit` sink.\n *\n * `start_span` and `end_span` each emit one event; `record` emits the event as\n * written. When the caller supplies `parent_span_id` in the span meta (the\n * runner threads the true structural parent through `RunContext`), that value is\n * used verbatim, so span trees are correct even for concurrent children under\n * `parallel`/`map`. Only when no parent is supplied does the recorder fall back\n * to an in-memory stack of still-open spans, which is best-effort under\n * concurrency.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Build a `TrajectoryLogger` whose events are handed, one at a time, to `emit`.\n */\nexport function trajectory_recorder(\n emit: (event: Record<string, unknown>) => void,\n): TrajectoryLogger {\n const stack: string[] = []\n\n const start_span: TrajectoryLogger['start_span'] = (name, meta) => {\n const span_id = `${name}:${randomUUID().slice(0, 8)}`\n const event: Record<string, unknown> = { kind: 'span_start', span_id, name, ...meta }\n // Prefer the caller-threaded structural parent; fall back to the open-span\n // stack only when none was supplied (best-effort under concurrency).\n if (event['parent_span_id'] === undefined && stack.length > 0) {\n event['parent_span_id'] = stack[stack.length - 1]\n }\n emit(event)\n stack.push(span_id)\n return span_id\n }\n\n const end_span: TrajectoryLogger['end_span'] = (id, meta) => {\n emit({ kind: 'span_end', span_id: id, ...meta })\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n }\n\n const record: TrajectoryLogger['record'] = (event) => {\n emit({ ...event })\n }\n\n return { record, start_span, end_span }\n}\n","/**\n * Line-oriented trajectory logger core.\n *\n * `filesystem_logger` and `stderr_logger` emit the same wire format (one JSON\n * object per line) and differ only in where the line goes. Both build on this:\n * `line_logger` adapts the shared span/record core (`trajectory_recorder`) to a\n * `write_line` sink, so the span bookkeeping and `parent_span_id` handling that\n * keep span trees correct under `parallel`/`map` live in exactly one place.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { trajectory_recorder } from './trajectory_recorder.js'\n\n/**\n * Create a `TrajectoryLogger` that writes one JSON object per line via\n * `write_line`.\n */\nexport function line_logger(write_line: (event: Record<string, unknown>) => void): TrajectoryLogger {\n return trajectory_recorder(write_line)\n}\n","/**\n * Filesystem JSONL trajectory logger.\n *\n * Appends one JSON object per line to a configured output file. Span\n * bookkeeping (including the `parent_span_id` handling that keeps span trees\n * correct for concurrent children under `parallel`/`map`) lives in\n * `line_logger`. Two concurrent `run(...)` calls that pass distinct logger\n * instances (constructed with distinct `output_path`s) share nothing.\n *\n * Paths are accepted at construction; the logger never reads `process.env`.\n */\n\nimport { appendFileSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { TrajectoryLogger } from '#core'\nimport { line_logger } from './line_logger.js'\n\nexport type FilesystemLoggerOptions = {\n readonly output_path: string\n}\n\n/**\n * Create a `TrajectoryLogger` that appends one JSON object per line to\n * `output_path`, creating the parent directory if needed.\n */\nexport function filesystem_logger(options: FilesystemLoggerOptions): TrajectoryLogger {\n const { output_path } = options\n mkdirSync(dirname(output_path), { recursive: true })\n\n return line_logger((event) => {\n appendFileSync(output_path, `${JSON.stringify(event)}\\n`)\n })\n}\n","/**\n * HTTP push trajectory logger.\n *\n * Conforms to `TrajectoryLogger`. POSTs each event as a single line of\n * newline-delimited JSON to a configured URL. Pairs naturally with the\n * fascicle viewer's `/api/ingest` endpoint, but is a generic adapter: the\n * receiver can be anything that accepts NDJSON over HTTP.\n *\n * Failure policy: drop on transport error and invoke the optional `on_error`\n * callback. Never throws, never blocks the user's flow on a dev tool being\n * up. The flow always wins; the viewer is best-effort.\n *\n * Span bookkeeping (including the `parent_span_id` handling that mirrors\n * `filesystem_logger` so the wire format is identical) lives in the shared\n * `trajectory_recorder`; this adapter only supplies the emit sink.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { trajectory_recorder } from './trajectory_recorder.js'\n\nexport type HttpLoggerFetch = (\n url: string,\n init: { method: 'POST'; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number }>\n\nexport type HttpLoggerOptions = {\n readonly url: string\n readonly fetch?: HttpLoggerFetch\n readonly on_error?: (err: unknown) => void\n}\n\n/**\n * Default `HttpLoggerFetch`, backed by the global `fetch`.\n */\nconst default_fetch: HttpLoggerFetch = async (url, init) => {\n const res = await fetch(url, init)\n return { ok: res.ok, status: res.status }\n}\n\n/**\n * Create a `TrajectoryLogger` that POSTs each event as NDJSON to\n * `options.url`.\n *\n * Never throws: a transport failure is dropped and reported through the\n * optional `on_error` callback, so a dev viewer being unreachable never\n * blocks the flow.\n */\nexport function http_logger(options: HttpLoggerOptions): TrajectoryLogger {\n const { url, on_error } = options\n const send = options.fetch ?? default_fetch\n\n const post = (event: Record<string, unknown>): void => {\n const body = `${JSON.stringify(event)}\\n`\n void send(url, {\n method: 'POST',\n headers: { 'content-type': 'application/x-ndjson' },\n body,\n })\n .then((res) => {\n if (!res.ok && on_error) on_error(new Error(`http_logger: POST ${url} -> ${res.status}`))\n })\n .catch((err: unknown) => {\n if (on_error) on_error(err)\n })\n }\n\n return trajectory_recorder(post)\n}\n","/**\n * No-op trajectory logger.\n *\n * Satisfies `TrajectoryLogger` from `core` without emitting any\n * output. Used as the default when no logger is supplied to `run(...)` and as\n * a cheap fallback in tests that do not care about trajectory output.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` whose methods do nothing.\n */\nexport function noop_logger(): TrajectoryLogger {\n return {\n record: () => {},\n start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,\n end_span: () => {},\n }\n}\n","/**\n * Stderr JSONL trajectory logger.\n *\n * Writes one JSON object per line to stderr (or an injected stream), leaving\n * stdout untouched. This is the blessed console logger for agents that run as\n * somebody's child process: under the stdio agent contract, stdout carries the\n * result envelope and belongs to the parent, so trajectory must go elsewhere.\n * The wire format is identical to `filesystem_logger`, so captured stderr is a\n * valid trajectory JSONL file (`2>events.jsonl`) the viewer parses unchanged.\n *\n * Writes never throw: a broken pipe or closed stream drops the event rather\n * than failing the flow.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { line_logger } from './line_logger.js'\n\nexport type StderrLoggerOptions = {\n readonly stream?: { write(chunk: string): unknown }\n}\n\n/**\n * Create a `TrajectoryLogger` that writes one JSON object per line to\n * stderr, or to `options.stream` when supplied.\n */\nexport function stderr_logger(options: StderrLoggerOptions = {}): TrajectoryLogger {\n const stream = options.stream ?? process.stderr\n return line_logger((event) => {\n try {\n stream.write(`${JSON.stringify(event)}\\n`)\n } catch {\n // Never throw from a logger; the flow always wins.\n }\n })\n}\n","/**\n * tee_logger: fan one TrajectoryLogger contract out to many sinks.\n *\n * Each sink receives every record/start_span/end_span call. Sinks are called\n * in registration order and exceptions in one sink do not prevent the others\n * from receiving the event.\n *\n * The first sink's `start_span` return value is treated as canonical and\n * returned to the caller; the tee remembers each sink's per-sink id so that\n * `end_span(canonical_id, ...)` translates back to the right id for each sink.\n * Within any one sink the wire format stays internally consistent; only the\n * across-sink ids may differ.\n */\n\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` that fans every call out to `loggers`.\n */\nexport function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger {\n if (loggers.length === 0) {\n throw new Error('tee_logger: at least one logger required')\n }\n\n const id_map = new Map<string, ReadonlyArray<string>>()\n\n const safe_each = (fn: (l: TrajectoryLogger, idx: number) => void): void => {\n for (let i = 0; i < loggers.length; i += 1) {\n const l = loggers[i]\n if (l === undefined) continue\n try {\n fn(l, i)\n } catch {\n // best-effort fan-out: a misbehaving sink must not derail the others\n }\n }\n }\n\n return {\n record: (event) => {\n safe_each((l) => l.record(event))\n },\n start_span: (name, meta) => {\n const ids: string[] = []\n safe_each((l) => {\n ids.push(l.start_span(name, meta))\n })\n const canonical = ids[0] ?? `${name}:tee`\n if (loggers.length > 1) id_map.set(canonical, ids)\n return canonical\n },\n end_span: (id, meta) => {\n const ids = id_map.get(id)\n if (ids === undefined) {\n safe_each((l) => l.end_span(id, meta))\n return\n }\n id_map.delete(id)\n safe_each((l, idx) => l.end_span(ids[idx] ?? id, meta))\n },\n }\n}\n","/**\n * Filesystem-backed checkpoint store.\n *\n * Satisfies `CheckpointStore` from `core`. Each key is stored as\n * a JSON file under the configured root directory. Writes are all-or-nothing:\n * values are written to a temporary sibling file and then atomically renamed\n * into place, so an interrupted write never leaves a partially-written file\n * at the target key. On `get`, a missing file, a partial temp file that was\n * never atomically renamed, or a JSON parse failure each read as a cache\n * miss (returning `null`) rather than an error.\n *\n * Paths are accepted at construction; the store never reads `process.env`.\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { CheckpointStore } from '#core'\n\nexport type FilesystemStoreOptions = {\n readonly root_dir: string\n}\n\n/**\n * Turn a checkpoint key into a filesystem-safe filename.\n *\n * Slugs the key down to `[a-zA-Z0-9._-]` and appends a short hash of the\n * full key, so two keys that slug to the same string still land on distinct\n * files.\n */\nfunction safe_filename(key: string): string {\n const hash = createHash('sha256').update(key).digest('hex').slice(0, 12)\n const slug = key.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64)\n return `${slug}.${hash}.json`\n}\n\n/**\n * Create a `CheckpointStore` backed by JSON files under `options.root_dir`.\n */\nexport function filesystem_store(options: FilesystemStoreOptions): CheckpointStore {\n const { root_dir } = options\n\n const ensure_root = async (): Promise<void> => {\n await mkdir(root_dir, { recursive: true })\n }\n\n const path_for = (key: string): string => join(root_dir, safe_filename(key))\n\n const get = async (key: string): Promise<unknown> => {\n const path = path_for(key)\n let raw: string\n try {\n raw = await readFile(path, 'utf8')\n } catch {\n return null\n }\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n }\n\n const set = async (key: string, value: unknown): Promise<void> => {\n await ensure_root()\n const target = path_for(key)\n const tmp = `${target}.${randomUUID().slice(0, 8)}.tmp`\n await writeFile(tmp, JSON.stringify(value), 'utf8')\n await rename(tmp, target)\n }\n\n const delete_key = async (key: string): Promise<void> => {\n const target = path_for(key)\n await rm(target, { force: true })\n }\n\n return { get, set, delete: delete_key }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,oBACd,MACkB;CAClB,MAAM,QAAkB,CAAC;CAEzB,MAAM,cAA8C,MAAM,SAAS;EACjE,MAAM,UAAU,GAAG,KAAK,GAAG,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC;EAClD,MAAM,QAAiC;GAAE,MAAM;GAAc;GAAS;GAAM,GAAG;EAAK;EAGpF,IAAI,MAAM,sBAAsB,KAAA,KAAa,MAAM,SAAS,GAC1D,MAAM,oBAAoB,MAAM,MAAM,SAAS;EAEjD,KAAK,KAAK;EACV,MAAM,KAAK,OAAO;EAClB,OAAO;CACT;CAEA,MAA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as CheckpointStore } from "./types-CVdTBXE_.js";
2
2
 
3
3
  //#region src/adapters/filesystem_logger.d.ts
4
4
  type FilesystemLoggerOptions = {
package/dist/adapters.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as http_logger, i as noop_logger, n as tee_logger, o as filesystem_logger, r as stderr_logger, t as filesystem_store } from "./adapters-CJnu1687.js";
1
+ import { a as http_logger, i as noop_logger, n as tee_logger, o as filesystem_logger, r as stderr_logger, t as filesystem_store } from "./adapters-hmnJOOgf.js";
2
2
  export { filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
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-Ww6An4CS.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
@@ -48,6 +48,52 @@ function unquote(raw) {
48
48
  return raw;
49
49
  }
50
50
  /**
51
+ * Locate the frontmatter block and split it from the body.
52
+ *
53
+ * Returns `null` when there is no opening `---` (the file is all body).
54
+ * A block opened but never closed throws rather than silently producing a
55
+ * wrong prompt.
56
+ */
57
+ function split_frontmatter(content) {
58
+ const open_match = content.match(FRONTMATTER_OPEN);
59
+ if (!open_match) return null;
60
+ const after_open = content.slice(open_match[0].length);
61
+ const close_match = FRONTMATTER_CLOSE.exec(after_open);
62
+ if (close_match?.index === void 0) throw new Error("define_agent: malformed frontmatter (missing closing `---`)");
63
+ return {
64
+ yaml_block: after_open.slice(0, close_match.index),
65
+ body: after_open.slice(close_match.index + close_match[0].length).replace(/^\r?\n/, "")
66
+ };
67
+ }
68
+ /**
69
+ * Coerce a `temperature` value to a finite number, throwing on anything else.
70
+ * `raw` is the pre-unquote text, so the error message echoes what the file held.
71
+ */
72
+ function parse_temperature(value, raw) {
73
+ const n = Number(value);
74
+ if (!Number.isFinite(n)) throw new Error(`define_agent: temperature must be a number, got: ${raw}`);
75
+ return n;
76
+ }
77
+ /**
78
+ * Parse one `key: value` frontmatter line into `out`. Blank and `#` comment
79
+ * lines are skipped; a line without a colon throws; unrecognized keys are
80
+ * ignored so only `name`/`description`/`model`/`temperature` reach the agent.
81
+ */
82
+ function assign_frontmatter_field(out, raw) {
83
+ const line = raw.trim();
84
+ if (line === "" || line.startsWith("#")) return;
85
+ const colon_idx = line.indexOf(":");
86
+ if (colon_idx === -1) throw new Error(`define_agent: malformed frontmatter line: ${raw}`);
87
+ const key = line.slice(0, colon_idx).trim();
88
+ const value_raw = line.slice(colon_idx + 1).trim();
89
+ const value = unquote(value_raw);
90
+ if (key === "name" || key === "description" || key === "model") {
91
+ out[key] = value;
92
+ return;
93
+ }
94
+ if (key === "temperature") out.temperature = parse_temperature(value, value_raw);
95
+ }
96
+ /**
51
97
  * Split a markdown file into frontmatter fields and prompt body.
52
98
  *
53
99
  * Parses only the flat `key: value` subset of YAML that agent files need:
@@ -57,40 +103,16 @@ function unquote(raw) {
57
103
  * silently producing a wrong prompt.
58
104
  */
59
105
  function parse_frontmatter(content) {
60
- const open_match = content.match(FRONTMATTER_OPEN);
61
- if (!open_match) return {
106
+ const split = split_frontmatter(content);
107
+ if (split === null) return {
62
108
  frontmatter: {},
63
109
  body: content
64
110
  };
65
- const after_open = content.slice(open_match[0].length);
66
- const close_match = FRONTMATTER_CLOSE.exec(after_open);
67
- if (close_match?.index === void 0) throw new Error("define_agent: malformed frontmatter (missing closing `---`)");
68
- const yaml_block = after_open.slice(0, close_match.index);
69
- const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\r?\n/, "");
70
111
  const out = {};
71
- const lines = yaml_block.split(/\r?\n/);
72
- for (const raw of lines) {
73
- const line = raw.trim();
74
- if (line === "" || line.startsWith("#")) continue;
75
- const colon_idx = line.indexOf(":");
76
- if (colon_idx === -1) throw new Error(`define_agent: malformed frontmatter line: ${raw}`);
77
- const key = line.slice(0, colon_idx).trim();
78
- const value_raw = line.slice(colon_idx + 1).trim();
79
- const value = unquote(value_raw);
80
- if (key === "name" || key === "description" || key === "model") {
81
- out[key] = value;
82
- continue;
83
- }
84
- if (key === "temperature") {
85
- const n = Number(value);
86
- if (!Number.isFinite(n)) throw new Error(`define_agent: temperature must be a number, got: ${value_raw}`);
87
- out.temperature = n;
88
- continue;
89
- }
90
- }
112
+ for (const raw of split.yaml_block.split(/\r?\n/)) assign_frontmatter_field(out, raw);
91
113
  return {
92
114
  frontmatter: out,
93
- body
115
+ body: split.body
94
116
  };
95
117
  }
96
118
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"agents.js","names":[],"sources":["../src/agents/define_agent.ts"],"sourcesContent":["/**\n * define_agent: markdown-driven loader for simple agents.\n *\n * Most \"agents\" in practice are a system prompt and an output schema with a\n * thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`\n * folds those into a `Step<i, o>`:\n *\n * - The markdown file is read once at factory time. Its YAML-style frontmatter\n * (`name`, `description`, `model`, `temperature`) is parsed into the agent's\n * step name and engine call defaults; the body is the system prompt.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model` and `config.schema_repair_attempts` shape the call from\n * code. An explicit `model` wins over frontmatter `model` (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent name,\n * resolved model id, and engine-reported usage. No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature` coerced to number. Anything\n * richer should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { Engine, GenerateOptions } from '#engine'\nimport type { ToolSchema } from '#schema'\n\nexport type AgentBuiltPrompt =\n | string\n | { readonly user: string; readonly system?: string }\n\nexport type DefineAgentConfig<i, o> = {\n readonly md_path: string | URL\n readonly schema: ToolSchema<o>\n readonly engine: Engine\n readonly name?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly temperature?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\n/**\n * Split a markdown file into frontmatter fields and prompt body.\n *\n * Parses only the flat `key: value` subset of YAML that agent files need:\n * recognized keys are `name`, `description`, `model`, and `temperature`\n * (coerced to a number); unrecognized keys are ignored. A file without an\n * opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const open_match = content.match(FRONTMATTER_OPEN)\n if (!open_match) return { frontmatter: {}, body: content }\n const after_open = content.slice(open_match[0].length)\n const close_match = FRONTMATTER_CLOSE.exec(after_open)\n if (close_match?.index === undefined) {\n throw new Error('define_agent: malformed frontmatter (missing closing `---`)')\n }\n const yaml_block = after_open.slice(0, close_match.index)\n const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\\r?\\n/, '')\n\n const out: { -readonly [K in keyof Frontmatter]: Frontmatter[K] } = {}\n const lines = yaml_block.split(/\\r?\\n/)\n for (const raw of lines) {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) continue\n const colon_idx = line.indexOf(':')\n if (colon_idx === -1) {\n throw new Error(`define_agent: malformed frontmatter line: ${raw}`)\n }\n const key = line.slice(0, colon_idx).trim()\n const value_raw = line.slice(colon_idx + 1).trim()\n const value = unquote(value_raw)\n if (key === 'name' || key === 'description' || key === 'model') {\n out[key] = value\n continue\n }\n if (key === 'temperature') {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: temperature must be a number, got: ${value_raw}`)\n }\n out.temperature = n\n continue\n }\n }\n return { frontmatter: out, body }\n}\n\n/**\n * Read the markdown file from a filesystem path, `URL`, or `file://` string.\n *\n * Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`\n * or its string form without caring about the difference.\n */\nfunction read_md_sync(path: string | URL): string {\n if (path instanceof URL) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n if (path.startsWith('file://')) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Replace `{{key}}` placeholders with top-level string fields of the input.\n *\n * Non-string values and unknown keys leave the placeholder untouched, so a\n * typo'd placeholder is visible in the sent prompt instead of vanishing.\n */\nfunction substitute(template: string, input: unknown): string {\n if (input === null || typeof input !== 'object') return template\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const obj = input as Record<string, unknown>\n return template.replace(PLACEHOLDER_RE, (match, key: string) => {\n const v = obj[key]\n return typeof v === 'string' ? v : match\n })\n}\n\n/**\n * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n\n return step<i, o>(display_name, async (input, ctx: RunContext): Promise<o> => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before agent call')\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n if (frontmatter.temperature !== undefined) opts.temperature = frontmatter.temperature\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content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,KAAA;EAClB;EAEA,MAAM,OAA2B;GAC/B,QAAQ;GACR,QAAQ,OAAO;GACf,OAAO,IAAI;GACX,YAAY,IAAI;EAClB;EACA,IAAI,kBAAkB,KAAA,KAAa,kBAAkB,IACnD,KAAK,SAAS;EAEhB,MAAM,QAAQ,OAAO,SAAS,YAAY;EAC1C,IAAI,UAAU,KAAA,GAAW,KAAK,QAAQ;EACtC,IAAI,YAAY,gBAAgB,KAAA,GAAW,KAAK,cAAc,YAAY;EAC1E,IAAI,OAAO,2BAA2B,KAAA,GACpC,KAAK,yBAAyB,OAAO;EAGvC,MAAM,SAAS,MAAM,OAAO,OAAO,SAAY,IAAI;EAEnD,MAAM,iBAAiB,GAAG,OAAO,eAAe,SAAS,GAAG,OAAO,eAAe;EAClF,IAAI,WAAW,OAAO;GACpB,MAAM;GACN,MAAM;GACN,OAAO;GACP,OAAO,OAAO;EAChB,CAAC;EAED,OAAO,OAAO;CAChB,CAAC;AACH"}
1
+ {"version":3,"file":"agents.js","names":[],"sources":["../src/agents/define_agent.ts"],"sourcesContent":["/**\n * define_agent: markdown-driven loader for simple agents.\n *\n * Most \"agents\" in practice are a system prompt and an output schema with a\n * thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`\n * folds those into a `Step<i, o>`:\n *\n * - The markdown file is read once at factory time. Its YAML-style frontmatter\n * (`name`, `description`, `model`, `temperature`) is parsed into the agent's\n * step name and engine call defaults; the body is the system prompt.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model` and `config.schema_repair_attempts` shape the call from\n * code. An explicit `model` wins over frontmatter `model` (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent name,\n * resolved model id, and engine-reported usage. No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature` coerced to number. Anything\n * richer should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { Engine, GenerateOptions } from '#engine'\nimport type { ToolSchema } from '#schema'\n\nexport type AgentBuiltPrompt =\n | string\n | { readonly user: string; readonly system?: string }\n\nexport type DefineAgentConfig<i, o> = {\n readonly md_path: string | URL\n readonly schema: ToolSchema<o>\n readonly engine: Engine\n readonly name?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly temperature?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\ntype MutableFrontmatter = { -readonly [K in keyof Frontmatter]: Frontmatter[K] }\n\n/**\n * Locate the frontmatter block and split it from the body.\n *\n * Returns `null` when there is no opening `---` (the file is all body).\n * A block opened but never closed throws rather than silently producing a\n * wrong prompt.\n */\nfunction split_frontmatter(\n content: string,\n): { readonly yaml_block: string; readonly body: string } | null {\n const open_match = content.match(FRONTMATTER_OPEN)\n if (!open_match) return null\n const after_open = content.slice(open_match[0].length)\n const close_match = FRONTMATTER_CLOSE.exec(after_open)\n if (close_match?.index === undefined) {\n throw new Error('define_agent: malformed frontmatter (missing closing `---`)')\n }\n const yaml_block = after_open.slice(0, close_match.index)\n const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\\r?\\n/, '')\n return { yaml_block, body }\n}\n\n/**\n * Coerce a `temperature` value to a finite number, throwing on anything else.\n * `raw` is the pre-unquote text, so the error message echoes what the file held.\n */\nfunction parse_temperature(value: string, raw: string): number {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: temperature must be a number, got: ${raw}`)\n }\n return n\n}\n\n/**\n * Parse one `key: value` frontmatter line into `out`. Blank and `#` comment\n * lines are skipped; a line without a colon throws; unrecognized keys are\n * ignored so only `name`/`description`/`model`/`temperature` reach the agent.\n */\nfunction assign_frontmatter_field(out: MutableFrontmatter, raw: string): void {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) return\n const colon_idx = line.indexOf(':')\n if (colon_idx === -1) {\n throw new Error(`define_agent: malformed frontmatter line: ${raw}`)\n }\n const key = line.slice(0, colon_idx).trim()\n const value_raw = line.slice(colon_idx + 1).trim()\n const value = unquote(value_raw)\n if (key === 'name' || key === 'description' || key === 'model') {\n out[key] = value\n return\n }\n if (key === 'temperature') {\n out.temperature = parse_temperature(value, value_raw)\n }\n}\n\n/**\n * Split a markdown file into frontmatter fields and prompt body.\n *\n * Parses only the flat `key: value` subset of YAML that agent files need:\n * recognized keys are `name`, `description`, `model`, and `temperature`\n * (coerced to a number); unrecognized keys are ignored. A file without an\n * opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const split = split_frontmatter(content)\n if (split === null) return { frontmatter: {}, body: content }\n const out: MutableFrontmatter = {}\n for (const raw of split.yaml_block.split(/\\r?\\n/)) {\n assign_frontmatter_field(out, raw)\n }\n return { frontmatter: out, body: split.body }\n}\n\n/**\n * Read the markdown file from a filesystem path, `URL`, or `file://` string.\n *\n * Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`\n * or its string form without caring about the difference.\n */\nfunction read_md_sync(path: string | URL): string {\n if (path instanceof URL) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n if (path.startsWith('file://')) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Replace `{{key}}` placeholders with top-level string fields of the input.\n *\n * Non-string values and unknown keys leave the placeholder untouched, so a\n * typo'd placeholder is visible in the sent prompt instead of vanishing.\n */\nfunction substitute(template: string, input: unknown): string {\n if (input === null || typeof input !== 'object') return template\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const obj = input as Record<string, unknown>\n return template.replace(PLACEHOLDER_RE, (match, key: string) => {\n const v = obj[key]\n return typeof v === 'string' ? v : match\n })\n}\n\n/**\n * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n\n return step<i, o>(display_name, async (input, ctx: RunContext): Promise<o> => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before agent call')\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n if (frontmatter.temperature !== undefined) opts.temperature = frontmatter.temperature\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;;;;AAKvB,SAAS,QAAQ,KAAqB;CACpC,IAAI,IAAI,UAAU,GAAG;EACnB,MAAM,QAAQ,IAAI;EAClB,MAAM,OAAO,IAAI,IAAI,SAAS;EAC9B,IAAK,UAAU,QAAO,SAAS,QAAS,UAAU,OAAO,SAAS,KAChE,OAAO,IAAI,MAAM,GAAG,EAAE;CAE1B;CACA,OAAO;AACT;;;;;;;;AAWA,SAAS,kBACP,SAC+D;CAC/D,MAAM,aAAa,QAAQ,MAAM,gBAAgB;CACjD,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,aAAa,QAAQ,MAAM,WAAW,EAAE,CAAC,MAAM;CACrD,MAAM,cAAc,kBAAkB,KAAK,UAAU;CACrD,IAAI,aAAa,UAAU,KAAA,GACzB,MAAM,IAAI,MAAM,6DAA6D;CAI/E,OAAO;EAAE,YAFU,WAAW,MAAM,GAAG,YAAY,KAEjC;EAAG,MADR,WAAW,MAAM,YAAY,QAAQ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