fascicle 0.9.6 → 0.9.9
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 +53 -0
- package/README.md +33 -5
- package/dist/{adapters-Dbx3M8m-.js → adapters-CJnu1687.js} +44 -5
- package/dist/adapters-CJnu1687.js.map +1 -0
- package/dist/adapters.d.ts +26 -1
- package/dist/adapters.js +1 -1
- package/dist/agents.d.ts +39 -0
- package/dist/agents.js +174 -0
- package/dist/agents.js.map +1 -0
- package/dist/{core-CYpxskeT.js → core-DNH8ddMT.js} +340 -45
- package/dist/core-DNH8ddMT.js.map +1 -0
- package/dist/{index-DyjXGal_.d.ts → index-Bfjpd_3o.d.ts} +33 -18
- package/dist/{index-JhJahQNi.d.ts → index-SkPG_Rew.d.ts} +140 -5
- package/dist/index.d.ts +186 -2
- package/dist/index.js +1438 -276
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +28 -2
- package/dist/mcp.js +136 -11
- package/dist/mcp.js.map +1 -1
- package/dist/otel.d.ts +8 -1
- package/dist/otel.js +29 -4
- package/dist/otel.js.map +1 -1
- package/dist/stdio.d.ts +18 -1
- package/dist/stdio.js +53 -2
- package/dist/stdio.js.map +1 -1
- package/dist/ui.d.ts +12 -2
- package/dist/ui.js +39 -2
- package/dist/ui.js.map +1 -1
- package/package.json +14 -7
- package/dist/adapters-Dbx3M8m-.js.map +0 -1
- package/dist/core-CYpxskeT.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,58 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## v0.9.9 — 2026-07-24
|
|
4
|
+
|
|
5
|
+
No library behavior changes in this release. Every `src/` edit in this range is
|
|
6
|
+
a documentation comment, so the published runtime is unchanged from v0.9.8; the
|
|
7
|
+
work is in the docs surface, the example apps, and the check suite.
|
|
8
|
+
|
|
9
|
+
### Changed
|
|
10
|
+
|
|
11
|
+
- **The public docs surface is now written for the public.** `research/` and the internal build trees are untracked, and the adoption and comparison pages are back in sync with the native transports: the AI SDK is the *default* path for seven of the eight providers rather than the only path, and both pages' AI-SDK-backed versus native counts are corrected.
|
|
12
|
+
- **Every example app now matches [docs/blueprint.md](./docs/blueprint.md).** `pr-improve`, the canonical reference, moved its four system prompts into markdown files with frontmatter, renamed its schemas to `snake_case`, and moved the field-level output rules out of prose and into `.describe()` on the schemas, where they travel to the model as part of the JSON schema. `red-green-refactor`, `swebench`, and `amplify` predated the blueprint and were translated: one `create_engine` call site each, markdown prompts, and `state`/`stages`/`services` splits. `amplify`'s round loop was a `while` over mutable parent state driving an `ensemble` whose score callback populated a captured map; it is now `loop` + `map` + `branch` over immutable carry-state, with `fallback` replacing a buried try/catch, so the stop rule, the fan-out, and the accept/reject decision are all visible in the trajectory.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- **`docs/blueprint.md`'s `state.ts` snippet did not compile.** It declared its scope-state readers over `ReadonlyMap` and called `.get()`, but `use(keys, fn)` hands `fn` a plain object projection of the requested keys. The snippet now shows the real shape, with the `ReadonlyMap` variant documented for readers that go through `ctx.state` inside a step body instead.
|
|
17
|
+
- **`examples/pr-improve` could not run on its own default provider.** It defaulted every role to `'sonnet'`/`'opus'` and claimed in comments that the engine expands those per provider. It does not — `model` is passed to the provider verbatim — so the documented default path (`FASCICLE_PROVIDER=anthropic`) sent a literal `"sonnet"` and got a not-found error. There is now one per-provider model table, resolved once and threaded as data, which also removes a second copy of that table and makes the `FASCICLE_MODEL_*` overrides reach the flow; they were previously parsed and discarded.
|
|
18
|
+
|
|
19
|
+
### Internal
|
|
20
|
+
|
|
21
|
+
- **The check suite is now [checkride](https://www.npmjs.com/package/checkride) 0.6.0**, replacing the hand-rolled orchestrator. `scripts/check.mjs`, `check-links.mjs`, `check-doc-snippets.mjs`, and `check-publish.mjs` are deleted (~960 lines) in favour of built-in slots; `scripts/check-deps.mjs` stays as the one custom check, since the core/engine dependency invariant is fascicle-specific. The `pnpm check` / `check:all` / `check:json` / `check:bail` contract is unchanged and `pnpm check --changed` is new.
|
|
22
|
+
- **Existing debt is grandfathered in `checkride.baseline.json`** (308 diagnostics across lint, struct, dead, dupes, health, spell). The gate ratchets: frozen debt passes, new findings fail. The `dupes` and `health` slots are now enforced rather than folded into a single fallow invocation that could not fail on them.
|
|
23
|
+
- The packaging gate gains `publint` and splits the old monolithic `publish` step into `pack`, `smoke`, and `attw` (pinned to the `esm-only` profile). Doc snippets are typechecked against the built `.d.ts` as part of `pnpm check:publish`, rather than as a separate CI step.
|
|
24
|
+
- **The blueprint is machine-checked on the examples.** All six composition apps carry its ast-grep rules, run for every app by a new `examples` check slot; `check:rules` was previously invoked by no CI job and no slot, and the library's own rules never matched the example apps because their `files:` globs are anchored at the repo root. `vitest` now globs `examples/*/src/**/__tests__`, so `swebench`'s and `amplify`'s suites, which had never executed, run in CI: 13 example tests became 51.
|
|
25
|
+
- Every module-level function in `src/` now carries a doc block, enforced by `rules/function-comment-required.yml`, and the comments are written in the present tense with no design-history references.
|
|
26
|
+
- Tooling: fallow 3.6.0, `publint` added, and the marketing site dropped from analysis (it reported every file as unused and its DOM handlers as complexity findings).
|
|
27
|
+
|
|
28
|
+
## v0.9.8 — 2026-07-19
|
|
29
|
+
|
|
30
|
+
### Added
|
|
31
|
+
|
|
32
|
+
- **`define_agent` call-shaping config.** `DefineAgentConfig` accepts `model` and `schema_repair_attempts`, closing the gap where the blueprint's "models are threaded as data" rule could not be followed on the `fascicle/agents` surface (and where schema repair — set on every model call observed in production consumers — required dropping to a stage factory). Precedence: `config.model` > frontmatter `model` > engine default; the blueprint's stage-factory section now states the same rule.
|
|
33
|
+
- Two blueprint reference apps translated from production consumers, workspace-wired with stub-engine tests and the blueprint's ast-grep rules: `examples/change-triage/` (deterministic detectors + one schema-mode model call, a score floor the model cannot undercut, a privacy screen on the model's view) and `examples/docs-concierge/` (grounded Q&A with number-based citations, a `define_agent` stage, and a one-way gate that prefers abstaining over confidently wrong).
|
|
34
|
+
|
|
35
|
+
### Changed
|
|
36
|
+
|
|
37
|
+
- `docs/blueprint.md` and `site/blueprint.html` now state model precedence consistently (threaded model wins, frontmatter is the role default, engine default is the last resort), and the stage-factory snippet no longer implies frontmatter overrides a threaded model.
|
|
38
|
+
|
|
39
|
+
## v0.9.7 — 2026-07-17
|
|
40
|
+
|
|
41
|
+
### Added
|
|
42
|
+
|
|
43
|
+
- **`fascicle/agents` subpath.** `define_agent` — the markdown-plus-schema agent loader the blueprint recommends for simple one-prompt agents — is now importable by consumers via `import { define_agent } from 'fascicle/agents'`. It was previously reachable only inside the repo. Ships as its own bundle entry (`dist/agents.js`), smoke-verified at build time.
|
|
44
|
+
- A dedicated architecture page on the site (`site/blueprint.html`): the agent blueprint's one rule, adoption tiers, module contracts, anti-patterns, and ast-grep enforcement story, linked from both existing pages. `AGENTS.md` and the README now route agents and humans building *on* fascicle to `docs/blueprint.md` first, and a new `examples/README.md` indexes the example apps around it.
|
|
45
|
+
- Opt-in `build` + `publish` steps in the check runner, included by `pnpm check:all`: the tsdown bundle with export smoke imports, and the npm pack manifest + `@arethetypeswrong/cli` validation. Packaging regressions now fail the done-gate instead of surfacing at release time.
|
|
46
|
+
|
|
47
|
+
### Changed
|
|
48
|
+
|
|
49
|
+
- Documentation synced with the implementation across `docs/` and the site. The composition surface is documented as 21 primitives (adding `ensemble_step`, `improve`, and `learn` to every list and to the site's interactive tour); site code samples now show the real config-object APIs (`branch` / `map` / `ensemble` / `tournament` / `consensus`, `adversarial`'s required `accept`, `suspend`'s required `on`, `retry`'s `backoff_ms`); engine docs corrected for `claude_cli` reasoning-effort forwarding (`CLAUDE_CODE_EFFORT_LEVEL`), the `'timeout'` member of `DEFAULT_RETRY.retry_on`, the real missing-peer error message, `inherit_env` semantics, the full `EngineConfig` shape, and the complete error and Engine-method lists.
|
|
50
|
+
- The reference agents (reviewer, documenter, researcher) moved from `src/agents/` to `examples/agents/` as copy-pasteable demo code — they were never published (their markdown prompts do not ship in `dist/`), and their own docstring called them canonical examples. Their behavior tests still run in the default suite. `src/agents` now contains exactly the published surface: `define_agent`.
|
|
51
|
+
|
|
52
|
+
### Internal
|
|
53
|
+
|
|
54
|
+
- Hardened `define_agent` mutation coverage from 91.8% to 98.2% ahead of publication (frontmatter quoting and key-trim edges, primitive-input placeholder substitution, system-key omission, the pre-call abort guard); the three residual survivors are documented equivalent mutants.
|
|
55
|
+
|
|
3
56
|
## v0.9.6 — 2026-07-17
|
|
4
57
|
|
|
5
58
|
### Added
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|

|
|
4
4
|
|
|
5
|
-
Compose agents out of LLM calls, tool calls, and plain functions. Everything is a `Step<i, o>`. Wire steps together with
|
|
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.
|
|
6
6
|
|
|
7
7
|
No framework lifecycle. No ambient state. No decorators. Adapters are passed in per run.
|
|
8
8
|
|
|
@@ -57,7 +57,7 @@ try {
|
|
|
57
57
|
|
|
58
58
|
## What's in the box
|
|
59
59
|
|
|
60
|
-
**Composition primitives (
|
|
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.
|
|
61
61
|
|
|
62
62
|
| Primitive | Shape |
|
|
63
63
|
| --- | --- |
|
|
@@ -74,11 +74,14 @@ try {
|
|
|
74
74
|
| `compose` | label a composite so it shows up by intent in trajectories |
|
|
75
75
|
| `adversarial` | build, critique, repeat until accept or `max_rounds` |
|
|
76
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) |
|
|
77
78
|
| `tournament` | single-elimination bracket |
|
|
78
79
|
| `consensus` | run N concurrently, accept when an `agree` predicate holds |
|
|
79
80
|
| `checkpoint` | memoize an inner step by key in a `CheckpointStore` |
|
|
80
81
|
| `suspend` | pause for external input; resume later with `resume_data` |
|
|
81
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 |
|
|
82
85
|
|
|
83
86
|
Plus `run`, `run.stream`, and `describe`.
|
|
84
87
|
|
|
@@ -101,6 +104,25 @@ await run(flow, input, {
|
|
|
101
104
|
|
|
102
105
|
`run.stream(flow, input)` returns `{ events, result }` for incremental observation.
|
|
103
106
|
|
|
107
|
+
**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
|
+
|
|
109
|
+
<!-- snippet: check -->
|
|
110
|
+
```typescript
|
|
111
|
+
import { z } from 'zod';
|
|
112
|
+
import { create_engine } from 'fascicle';
|
|
113
|
+
import { define_agent } from 'fascicle/agents';
|
|
114
|
+
|
|
115
|
+
const engine = create_engine({ providers: { claude_cli: { auth_mode: 'oauth' } } });
|
|
116
|
+
|
|
117
|
+
const reviewer = define_agent({
|
|
118
|
+
md_path: new URL('./prompts/reviewer.md', import.meta.url),
|
|
119
|
+
schema: z.object({ findings: z.array(z.string()), summary: z.string() }),
|
|
120
|
+
engine,
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
This is the [blueprint's](./docs/blueprint.md) recommended shape for simple one-prompt agents; reference agents built on it (reviewer, documenter, researcher) live in [examples/agents/](./examples/agents/).
|
|
125
|
+
|
|
104
126
|
**MCP bridge.** The `fascicle/mcp` subpath connects flows to the Model Context Protocol both ways. `mcp_client` turns an external MCP server's tools into plain `Tool[]`; `serve_flow` exposes a composed flow as an MCP tool to hosts like Claude Desktop or Cursor. It is pure adapter glue over the existing `Tool` and `run` contracts, and `@modelcontextprotocol/sdk` is an optional peer you only install when you use it.
|
|
105
127
|
|
|
106
128
|
<!-- snippet: check -->
|
|
@@ -167,11 +189,18 @@ await handle.close();
|
|
|
167
189
|
|
|
168
190
|
For zero-latency streaming from inside a long-running flow, pair it with `http_logger` from `fascicle/adapters`. See [docs/viewer.md](./docs/viewer.md) for the full transport story.
|
|
169
191
|
|
|
192
|
+
## Building an app on fascicle
|
|
193
|
+
|
|
194
|
+
**[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.
|
|
195
|
+
|
|
196
|
+
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).
|
|
197
|
+
|
|
170
198
|
## Where to go next
|
|
171
199
|
|
|
200
|
+
- [docs/blueprint.md](./docs/blueprint.md) — **the agent blueprint**: the standard app architecture (start here when building an app)
|
|
172
201
|
- [docs/getting-started.md](./docs/getting-started.md) — install and run your first flow
|
|
173
202
|
- [docs/concepts.md](./docs/concepts.md) — step-as-value, trajectories, cancellation
|
|
174
|
-
- [docs/composition.md](./docs/composition.md) — full composition surface: the
|
|
203
|
+
- [docs/composition.md](./docs/composition.md) — full composition surface: the 21 primitives, run/stream, checkpointing
|
|
175
204
|
- [docs/api-reference.md](./docs/api-reference.md) — the public surface at a glance
|
|
176
205
|
- [docs/configuration.md](./docs/configuration.md) — engine config, defaults, pricing, retries
|
|
177
206
|
- [docs/providers.md](./docs/providers.md) — per-provider adapter notes
|
|
@@ -179,7 +208,6 @@ For zero-latency streaming from inside a long-running flow, pair it with `http_l
|
|
|
179
208
|
- [docs/cookbook.md](./docs/cookbook.md) — retries, fan-out, judges, HITL, tool loops
|
|
180
209
|
- [docs/human-in-the-loop.md](./docs/human-in-the-loop.md) — suspend/resume approval over HTTP and streaming to a `useChat` UI via `fascicle/ui`
|
|
181
210
|
- [docs/writing-a-harness.md](./docs/writing-a-harness.md) — building a runner around fascicle
|
|
182
|
-
- [docs/blueprint.md](./docs/blueprint.md) is the agent blueprint: the standard app architecture (one composition layer, markdown prompts, normalized module shapes)
|
|
183
211
|
- [docs/embedding-under-a-harness.md](./docs/embedding-under-a-harness.md) — running a fascicle agent as somebody's child process
|
|
184
212
|
- [docs/troubleshooting.md](./docs/troubleshooting.md) — first-run errors and what they mean
|
|
185
213
|
- [docs/comparison.md](./docs/comparison.md) — how fascicle compares to LangChain, Mastra, and others
|
|
@@ -198,7 +226,7 @@ This repo is a **single package**. The code is organized as deep modules under `
|
|
|
198
226
|
```bash
|
|
199
227
|
pnpm install
|
|
200
228
|
pnpm check # types, lint, structural rules, dead-code, tests, docs, spell
|
|
201
|
-
pnpm check:all # adds Stryker mutation testing (
|
|
229
|
+
pnpm check:all # adds Stryker mutation testing + the packaging gate (final gate)
|
|
202
230
|
```
|
|
203
231
|
|
|
204
232
|
`pnpm check` is the single source of truth for "is this done?". Output lands in `.check/` (one JSON per check). See [AGENTS.md](./AGENTS.md) for the full contract and [CLAUDE.md](./CLAUDE.md) for Claude-specific notes.
|
|
@@ -16,6 +16,10 @@ import { appendFileSync, mkdirSync } from "node:fs";
|
|
|
16
16
|
* parent is supplied does the logger fall back to an in-memory stack of
|
|
17
17
|
* still-open spans, which is best-effort under concurrency.
|
|
18
18
|
*/
|
|
19
|
+
/**
|
|
20
|
+
* Create a `TrajectoryLogger` that writes one JSON object per line via
|
|
21
|
+
* `write_line`.
|
|
22
|
+
*/
|
|
19
23
|
function line_logger(write_line) {
|
|
20
24
|
const stack = [];
|
|
21
25
|
const start_span = (name, meta) => {
|
|
@@ -62,6 +66,10 @@ function line_logger(write_line) {
|
|
|
62
66
|
*
|
|
63
67
|
* Paths are accepted at construction; the logger never reads `process.env`.
|
|
64
68
|
*/
|
|
69
|
+
/**
|
|
70
|
+
* Create a `TrajectoryLogger` that appends one JSON object per line to
|
|
71
|
+
* `output_path`, creating the parent directory if needed.
|
|
72
|
+
*/
|
|
65
73
|
function filesystem_logger(options) {
|
|
66
74
|
const { output_path } = options;
|
|
67
75
|
mkdirSync(dirname(output_path), { recursive: true });
|
|
@@ -76,7 +84,7 @@ function filesystem_logger(options) {
|
|
|
76
84
|
*
|
|
77
85
|
* Conforms to `TrajectoryLogger`. POSTs each event as a single line of
|
|
78
86
|
* newline-delimited JSON to a configured URL. Pairs naturally with the
|
|
79
|
-
* fascicle viewer's `/api/ingest` endpoint, but is a generic adapter
|
|
87
|
+
* fascicle viewer's `/api/ingest` endpoint, but is a generic adapter: the
|
|
80
88
|
* receiver can be anything that accepts NDJSON over HTTP.
|
|
81
89
|
*
|
|
82
90
|
* Failure policy: drop on transport error and invoke the optional `on_error`
|
|
@@ -86,6 +94,9 @@ function filesystem_logger(options) {
|
|
|
86
94
|
* Hierarchical span ids are tracked in-process, mirroring `filesystem_logger`
|
|
87
95
|
* so the wire format is identical.
|
|
88
96
|
*/
|
|
97
|
+
/**
|
|
98
|
+
* Default `HttpLoggerFetch`, backed by the global `fetch`.
|
|
99
|
+
*/
|
|
89
100
|
const default_fetch = async (url, init) => {
|
|
90
101
|
const res = await fetch(url, init);
|
|
91
102
|
return {
|
|
@@ -93,6 +104,14 @@ const default_fetch = async (url, init) => {
|
|
|
93
104
|
status: res.status
|
|
94
105
|
};
|
|
95
106
|
};
|
|
107
|
+
/**
|
|
108
|
+
* Create a `TrajectoryLogger` that POSTs each event as NDJSON to
|
|
109
|
+
* `options.url`.
|
|
110
|
+
*
|
|
111
|
+
* Never throws: a transport failure is dropped and reported through the
|
|
112
|
+
* optional `on_error` callback, so a dev viewer being unreachable never
|
|
113
|
+
* blocks the flow.
|
|
114
|
+
*/
|
|
96
115
|
function http_logger(options) {
|
|
97
116
|
const { url, on_error } = options;
|
|
98
117
|
const send = options.fetch ?? default_fetch;
|
|
@@ -149,6 +168,9 @@ function http_logger(options) {
|
|
|
149
168
|
* output. Used as the default when no logger is supplied to `run(...)` and as
|
|
150
169
|
* a cheap fallback in tests that do not care about trajectory output.
|
|
151
170
|
*/
|
|
171
|
+
/**
|
|
172
|
+
* Create a `TrajectoryLogger` whose methods do nothing.
|
|
173
|
+
*/
|
|
152
174
|
function noop_logger() {
|
|
153
175
|
return {
|
|
154
176
|
record: () => {},
|
|
@@ -158,6 +180,10 @@ function noop_logger() {
|
|
|
158
180
|
}
|
|
159
181
|
//#endregion
|
|
160
182
|
//#region src/adapters/stderr_logger.ts
|
|
183
|
+
/**
|
|
184
|
+
* Create a `TrajectoryLogger` that writes one JSON object per line to
|
|
185
|
+
* stderr, or to `options.stream` when supplied.
|
|
186
|
+
*/
|
|
161
187
|
function stderr_logger(options = {}) {
|
|
162
188
|
const stream = options.stream ?? process.stderr;
|
|
163
189
|
return line_logger((event) => {
|
|
@@ -168,6 +194,9 @@ function stderr_logger(options = {}) {
|
|
|
168
194
|
}
|
|
169
195
|
//#endregion
|
|
170
196
|
//#region src/adapters/tee_logger.ts
|
|
197
|
+
/**
|
|
198
|
+
* Create a `TrajectoryLogger` that fans every call out to `loggers`.
|
|
199
|
+
*/
|
|
171
200
|
function tee_logger(...loggers) {
|
|
172
201
|
if (loggers.length === 0) throw new Error("tee_logger: at least one logger required");
|
|
173
202
|
const id_map = /* @__PURE__ */ new Map();
|
|
@@ -213,16 +242,26 @@ function tee_logger(...loggers) {
|
|
|
213
242
|
* a JSON file under the configured root directory. Writes are all-or-nothing:
|
|
214
243
|
* values are written to a temporary sibling file and then atomically renamed
|
|
215
244
|
* into place, so an interrupted write never leaves a partially-written file
|
|
216
|
-
* at the target key
|
|
217
|
-
*
|
|
218
|
-
*
|
|
245
|
+
* at the target key. On `get`, a missing file, a partial temp file that was
|
|
246
|
+
* never atomically renamed, or a JSON parse failure each read as a cache
|
|
247
|
+
* miss (returning `null`) rather than an error.
|
|
219
248
|
*
|
|
220
249
|
* Paths are accepted at construction; the store never reads `process.env`.
|
|
221
250
|
*/
|
|
251
|
+
/**
|
|
252
|
+
* Turn a checkpoint key into a filesystem-safe filename.
|
|
253
|
+
*
|
|
254
|
+
* Slugs the key down to `[a-zA-Z0-9._-]` and appends a short hash of the
|
|
255
|
+
* full key, so two keys that slug to the same string still land on distinct
|
|
256
|
+
* files.
|
|
257
|
+
*/
|
|
222
258
|
function safe_filename(key) {
|
|
223
259
|
const hash = createHash("sha256").update(key).digest("hex").slice(0, 12);
|
|
224
260
|
return `${key.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64)}.${hash}.json`;
|
|
225
261
|
}
|
|
262
|
+
/**
|
|
263
|
+
* Create a `CheckpointStore` backed by JSON files under `options.root_dir`.
|
|
264
|
+
*/
|
|
226
265
|
function filesystem_store(options) {
|
|
227
266
|
const { root_dir } = options;
|
|
228
267
|
const ensure_root = async () => {
|
|
@@ -262,4 +301,4 @@ function filesystem_store(options) {
|
|
|
262
301
|
//#endregion
|
|
263
302
|
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 };
|
|
264
303
|
|
|
265
|
-
//# sourceMappingURL=adapters-
|
|
304
|
+
//# sourceMappingURL=adapters-CJnu1687.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapters-CJnu1687.js","names":[],"sources":["../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 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. This module holds\n * the common span bookkeeping: `start_span` and `end_span` each emit a line;\n * `record` emits the event as written. When the caller supplies\n * `parent_span_id` in the span meta (the runner threads the true structural\n * parent through `RunContext`), that value is used verbatim, so span trees are\n * correct even for concurrent children under `parallel`/`map`. Only when no\n * parent is supplied does the logger fall back to an in-memory stack of\n * still-open spans, which is best-effort under concurrency.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\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 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 if (event['parent_span_id'] === undefined && stack.length > 0) {\n event['parent_span_id'] = stack[stack.length - 1]\n }\n write_line(event)\n stack.push(span_id)\n return span_id\n }\n\n const end_span: TrajectoryLogger['end_span'] = (id, meta) => {\n write_line({ 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 write_line({ ...event })\n }\n\n return { record, start_span, end_span }\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 * Hierarchical span ids are tracked in-process, mirroring `filesystem_logger`\n * so the wire format is identical.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\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 const stack: string[] = []\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 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 post(event)\n stack.push(span_id)\n return span_id\n }\n\n const end_span: TrajectoryLogger['end_span'] = (id, meta) => {\n post({ 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 post({ ...event })\n }\n\n return { record, start_span, end_span }\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":";;;;;;;;;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G,EAC9C,EAAE,GAAG,KAAK;AACzB;;;;AAKA,SAAgB,iBAAiB,SAAkD;CACjF,MAAM,EAAE,aAAa;CAErB,MAAM,cAAc,YAA2B;EAC7C,MAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;CAC3C;CAEA,MAAM,YAAY,QAAwB,KAAK,UAAU,cAAc,GAAG,CAAC;CAE3E,MAAM,MAAM,OAAO,QAAkC;EACnD,MAAM,OAAO,SAAS,GAAG;EACzB,IAAI;EACJ,IAAI;GACF,MAAM,MAAM,SAAS,MAAM,MAAM;EACnC,QAAQ;GACN,OAAO;EACT;EACA,IAAI;GACF,OAAO,KAAK,MAAM,GAAG;EACvB,QAAQ;GACN,OAAO;EACT;CACF;CAEA,MAAM,MAAM,OAAO,KAAa,UAAkC;EAChE,MAAM,YAAY;EAClB,MAAM,SAAS,SAAS,GAAG;EAC3B,MAAM,MAAM,GAAG,OAAO,GAAG,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;EAClD,MAAM,UAAU,KAAK,KAAK,UAAU,KAAK,GAAG,MAAM;EAClD,MAAM,OAAO,KAAK,MAAM;CAC1B;CAEA,MAAM,aAAa,OAAO,QAA+B;EAEvD,MAAM,GADS,SAAS,GACV,GAAG,EAAE,OAAO,KAAK,CAAC;CAClC;CAEA,OAAO;EAAE;EAAK;EAAK,QAAQ;CAAW;AACxC"}
|
package/dist/adapters.d.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { J as TrajectoryLogger, U as CheckpointStore } from "./index-
|
|
1
|
+
import { J as TrajectoryLogger, U as CheckpointStore } from "./index-SkPG_Rew.js";
|
|
2
2
|
|
|
3
3
|
//#region src/adapters/filesystem_logger.d.ts
|
|
4
4
|
type FilesystemLoggerOptions = {
|
|
5
5
|
readonly output_path: string;
|
|
6
6
|
};
|
|
7
|
+
/**
|
|
8
|
+
* Create a `TrajectoryLogger` that appends one JSON object per line to
|
|
9
|
+
* `output_path`, creating the parent directory if needed.
|
|
10
|
+
*/
|
|
7
11
|
declare function filesystem_logger(options: FilesystemLoggerOptions): TrajectoryLogger;
|
|
8
12
|
//#endregion
|
|
9
13
|
//#region src/adapters/http_logger.d.ts
|
|
@@ -20,9 +24,20 @@ type HttpLoggerOptions = {
|
|
|
20
24
|
readonly fetch?: HttpLoggerFetch;
|
|
21
25
|
readonly on_error?: (err: unknown) => void;
|
|
22
26
|
};
|
|
27
|
+
/**
|
|
28
|
+
* Create a `TrajectoryLogger` that POSTs each event as NDJSON to
|
|
29
|
+
* `options.url`.
|
|
30
|
+
*
|
|
31
|
+
* Never throws: a transport failure is dropped and reported through the
|
|
32
|
+
* optional `on_error` callback, so a dev viewer being unreachable never
|
|
33
|
+
* blocks the flow.
|
|
34
|
+
*/
|
|
23
35
|
declare function http_logger(options: HttpLoggerOptions): TrajectoryLogger;
|
|
24
36
|
//#endregion
|
|
25
37
|
//#region src/adapters/noop_logger.d.ts
|
|
38
|
+
/**
|
|
39
|
+
* Create a `TrajectoryLogger` whose methods do nothing.
|
|
40
|
+
*/
|
|
26
41
|
declare function noop_logger(): TrajectoryLogger;
|
|
27
42
|
//#endregion
|
|
28
43
|
//#region src/adapters/stderr_logger.d.ts
|
|
@@ -31,15 +46,25 @@ type StderrLoggerOptions = {
|
|
|
31
46
|
write(chunk: string): unknown;
|
|
32
47
|
};
|
|
33
48
|
};
|
|
49
|
+
/**
|
|
50
|
+
* Create a `TrajectoryLogger` that writes one JSON object per line to
|
|
51
|
+
* stderr, or to `options.stream` when supplied.
|
|
52
|
+
*/
|
|
34
53
|
declare function stderr_logger(options?: StderrLoggerOptions): TrajectoryLogger;
|
|
35
54
|
//#endregion
|
|
36
55
|
//#region src/adapters/tee_logger.d.ts
|
|
56
|
+
/**
|
|
57
|
+
* Create a `TrajectoryLogger` that fans every call out to `loggers`.
|
|
58
|
+
*/
|
|
37
59
|
declare function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger;
|
|
38
60
|
//#endregion
|
|
39
61
|
//#region src/adapters/filesystem_store.d.ts
|
|
40
62
|
type FilesystemStoreOptions = {
|
|
41
63
|
readonly root_dir: string;
|
|
42
64
|
};
|
|
65
|
+
/**
|
|
66
|
+
* Create a `CheckpointStore` backed by JSON files under `options.root_dir`.
|
|
67
|
+
*/
|
|
43
68
|
declare function filesystem_store(options: FilesystemStoreOptions): CheckpointStore;
|
|
44
69
|
//#endregion
|
|
45
70
|
export { type FilesystemLoggerOptions, type FilesystemStoreOptions, type HttpLoggerFetch, type HttpLoggerOptions, type StderrLoggerOptions, filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
|
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-
|
|
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";
|
|
2
2
|
export { filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
|
package/dist/agents.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { G as Step } from "./index-SkPG_Rew.js";
|
|
2
|
+
import { y as Engine } from "./index-Bfjpd_3o.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
//#region src/agents/define_agent.d.ts
|
|
6
|
+
type AgentBuiltPrompt = string | {
|
|
7
|
+
readonly user: string;
|
|
8
|
+
readonly system?: string;
|
|
9
|
+
};
|
|
10
|
+
type DefineAgentConfig<i, o> = {
|
|
11
|
+
readonly md_path: string | URL;
|
|
12
|
+
readonly schema: z.ZodType<o>;
|
|
13
|
+
readonly engine: Engine;
|
|
14
|
+
readonly name?: string;
|
|
15
|
+
readonly build_prompt?: (input: i) => AgentBuiltPrompt;
|
|
16
|
+
/**
|
|
17
|
+
* Model for this agent's calls, typically threaded from the app's resolved
|
|
18
|
+
* role-to-model table. Wins over frontmatter `model`; when both are absent
|
|
19
|
+
* the engine default applies.
|
|
20
|
+
*/
|
|
21
|
+
readonly model?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Forwarded to `engine.generate`: how many times the engine may re-prompt
|
|
24
|
+
* the model to repair schema-invalid output before failing the call.
|
|
25
|
+
*/
|
|
26
|
+
readonly schema_repair_attempts?: number;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Load a markdown-defined agent as a `Step<i, o>`.
|
|
30
|
+
*
|
|
31
|
+
* Reads and parses the file once at factory time; each run resolves the
|
|
32
|
+
* user/system prompts (via `build_prompt` or `{{key}}` substitution), calls
|
|
33
|
+
* `engine.generate` with the schema and threaded abort/trajectory, and
|
|
34
|
+
* records an `agent.call` event with the resolved model and usage.
|
|
35
|
+
*/
|
|
36
|
+
declare function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o>;
|
|
37
|
+
//#endregion
|
|
38
|
+
export { type AgentBuiltPrompt, type DefineAgentConfig, define_agent };
|
|
39
|
+
//# sourceMappingURL=agents.d.ts.map
|
package/dist/agents.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { E as aborted_error, w as step } from "./core-DNH8ddMT.js";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
//#region src/agents/define_agent.ts
|
|
5
|
+
/**
|
|
6
|
+
* define_agent: markdown-driven loader for simple agents.
|
|
7
|
+
*
|
|
8
|
+
* Most "agents" in practice are a system prompt and an output schema with a
|
|
9
|
+
* thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`
|
|
10
|
+
* folds those into a `Step<i, o>`:
|
|
11
|
+
*
|
|
12
|
+
* - The markdown file is read once at factory time. Its YAML-style frontmatter
|
|
13
|
+
* (`name`, `description`, `model`, `temperature`) is parsed into the agent's
|
|
14
|
+
* step name and engine call defaults; the body is the system prompt.
|
|
15
|
+
* - Without `build_prompt`, the body (after `{{key}}` substitution against
|
|
16
|
+
* top-level string fields of the input) is the user prompt and no system is
|
|
17
|
+
* sent; the markdown carries the full instruction.
|
|
18
|
+
* - With `build_prompt`, the body is the system prompt and `build_prompt(input)`
|
|
19
|
+
* produces the user message (string, or `{ user, system? }` to override).
|
|
20
|
+
* - `config.model` and `config.schema_repair_attempts` shape the call from
|
|
21
|
+
* code. An explicit `model` wins over frontmatter `model` (frontmatter stays
|
|
22
|
+
* the role default when the app threads nothing; the engine default is the
|
|
23
|
+
* last resort), so a resolved role-to-model table and env overrides actually
|
|
24
|
+
* reach the call.
|
|
25
|
+
*
|
|
26
|
+
* The factory keeps no engine state. Each call delegates to `engine.generate`
|
|
27
|
+
* with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`
|
|
28
|
+
* threaded through. An `agent.call` trajectory event carries the agent name,
|
|
29
|
+
* resolved model id, and engine-reported usage. No retry or fallback is baked
|
|
30
|
+
* in; wrap with `retry()` from core if you need it.
|
|
31
|
+
*
|
|
32
|
+
* Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`
|
|
33
|
+
* lines, optional `'`/`"` quotes, `temperature` coerced to number. Anything
|
|
34
|
+
* richer should go through `build_prompt`.
|
|
35
|
+
*/
|
|
36
|
+
const FRONTMATTER_OPEN = /^---\s*\r?\n/;
|
|
37
|
+
const FRONTMATTER_CLOSE = /^---\s*$/m;
|
|
38
|
+
const PLACEHOLDER_RE = /\{\{(\w+)\}\}/g;
|
|
39
|
+
/**
|
|
40
|
+
* Strip one matching pair of surrounding single or double quotes.
|
|
41
|
+
*/
|
|
42
|
+
function unquote(raw) {
|
|
43
|
+
if (raw.length >= 2) {
|
|
44
|
+
const first = raw[0];
|
|
45
|
+
const last = raw[raw.length - 1];
|
|
46
|
+
if (first === "\"" && last === "\"" || first === "'" && last === "'") return raw.slice(1, -1);
|
|
47
|
+
}
|
|
48
|
+
return raw;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Split a markdown file into frontmatter fields and prompt body.
|
|
52
|
+
*
|
|
53
|
+
* Parses only the flat `key: value` subset of YAML that agent files need:
|
|
54
|
+
* recognized keys are `name`, `description`, `model`, and `temperature`
|
|
55
|
+
* (coerced to a number); unrecognized keys are ignored. A file without an
|
|
56
|
+
* opening `---` is all body. Malformed frontmatter throws rather than
|
|
57
|
+
* silently producing a wrong prompt.
|
|
58
|
+
*/
|
|
59
|
+
function parse_frontmatter(content) {
|
|
60
|
+
const open_match = content.match(FRONTMATTER_OPEN);
|
|
61
|
+
if (!open_match) return {
|
|
62
|
+
frontmatter: {},
|
|
63
|
+
body: content
|
|
64
|
+
};
|
|
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
|
+
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
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
frontmatter: out,
|
|
93
|
+
body
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Read the markdown file from a filesystem path, `URL`, or `file://` string.
|
|
98
|
+
*
|
|
99
|
+
* Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`
|
|
100
|
+
* or its string form without caring about the difference.
|
|
101
|
+
*/
|
|
102
|
+
function read_md_sync(path) {
|
|
103
|
+
if (path instanceof URL) return readFileSync(fileURLToPath(path), "utf8");
|
|
104
|
+
if (path.startsWith("file://")) return readFileSync(fileURLToPath(path), "utf8");
|
|
105
|
+
return readFileSync(path, "utf8");
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Replace `{{key}}` placeholders with top-level string fields of the input.
|
|
109
|
+
*
|
|
110
|
+
* Non-string values and unknown keys leave the placeholder untouched, so a
|
|
111
|
+
* typo'd placeholder is visible in the sent prompt instead of vanishing.
|
|
112
|
+
*/
|
|
113
|
+
function substitute(template, input) {
|
|
114
|
+
if (input === null || typeof input !== "object") return template;
|
|
115
|
+
const obj = input;
|
|
116
|
+
return template.replace(PLACEHOLDER_RE, (match, key) => {
|
|
117
|
+
const v = obj[key];
|
|
118
|
+
return typeof v === "string" ? v : match;
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Load a markdown-defined agent as a `Step<i, o>`.
|
|
123
|
+
*
|
|
124
|
+
* Reads and parses the file once at factory time; each run resolves the
|
|
125
|
+
* user/system prompts (via `build_prompt` or `{{key}}` substitution), calls
|
|
126
|
+
* `engine.generate` with the schema and threaded abort/trajectory, and
|
|
127
|
+
* records an `agent.call` event with the resolved model and usage.
|
|
128
|
+
*/
|
|
129
|
+
function define_agent(config) {
|
|
130
|
+
const { frontmatter, body } = parse_frontmatter(read_md_sync(config.md_path));
|
|
131
|
+
const display_name = config.name ?? frontmatter.name ?? "agent";
|
|
132
|
+
return step(display_name, async (input, ctx) => {
|
|
133
|
+
if (ctx.abort.aborted) throw new aborted_error("aborted before agent call");
|
|
134
|
+
let user_prompt;
|
|
135
|
+
let system_prompt;
|
|
136
|
+
if (config.build_prompt) {
|
|
137
|
+
const built = config.build_prompt(input);
|
|
138
|
+
if (typeof built === "string") {
|
|
139
|
+
user_prompt = built;
|
|
140
|
+
system_prompt = body;
|
|
141
|
+
} else {
|
|
142
|
+
user_prompt = built.user;
|
|
143
|
+
system_prompt = built.system ?? body;
|
|
144
|
+
}
|
|
145
|
+
} else {
|
|
146
|
+
user_prompt = substitute(body, input);
|
|
147
|
+
system_prompt = void 0;
|
|
148
|
+
}
|
|
149
|
+
const opts = {
|
|
150
|
+
prompt: user_prompt,
|
|
151
|
+
schema: config.schema,
|
|
152
|
+
abort: ctx.abort,
|
|
153
|
+
trajectory: ctx.trajectory
|
|
154
|
+
};
|
|
155
|
+
if (system_prompt !== void 0 && system_prompt !== "") opts.system = system_prompt;
|
|
156
|
+
const model = config.model ?? frontmatter.model;
|
|
157
|
+
if (model !== void 0) opts.model = model;
|
|
158
|
+
if (frontmatter.temperature !== void 0) opts.temperature = frontmatter.temperature;
|
|
159
|
+
if (config.schema_repair_attempts !== void 0) opts.schema_repair_attempts = config.schema_repair_attempts;
|
|
160
|
+
const result = await config.engine.generate(opts);
|
|
161
|
+
const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`;
|
|
162
|
+
ctx.trajectory.record({
|
|
163
|
+
kind: "agent.call",
|
|
164
|
+
name: display_name,
|
|
165
|
+
model: resolved_model,
|
|
166
|
+
usage: result.usage
|
|
167
|
+
});
|
|
168
|
+
return result.content;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
//#endregion
|
|
172
|
+
export { define_agent };
|
|
173
|
+
|
|
174
|
+
//# sourceMappingURL=agents.js.map
|
|
@@ -0,0 +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 { z } from 'zod'\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: z.ZodType<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\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,kBAAkB,SAA+B;CACxD,MAAM,aAAa,QAAQ,MAAM,gBAAgB;CACjD,IAAI,CAAC,YAAY,OAAO;EAAE,aAAa,CAAC;EAAG,MAAM;CAAQ;CACzD,MAAM,aAAa,QAAQ,MAAM,WAAW,EAAE,CAAC,MAAM;CACrD,MAAM,cAAc,kBAAkB,KAAK,UAAU;CACrD,IAAI,aAAa,UAAU,KAAA,GACzB,MAAM,IAAI,MAAM,6DAA6D;CAE/E,MAAM,aAAa,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