fascicle 0.8.1 → 0.8.11

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,111 @@
1
1
  # Changelog
2
2
 
3
+ ## v0.8.11 — 2026-07-03
4
+
5
+ ### Added
6
+
7
+ - `fascicle/stdio`: run any flow as a single-shot child process with `run_stdio(flow, options)`. Reads JSON from stdin, optionally validates it against a zod `input_schema`, runs the flow, optionally validates the result against an `output_schema`, and writes exactly one JSON document to stdout. Exit code is the verdict (0 = result is authoritative, 1 = flow failure, 2 = contract violation), and a machine-readable failure object is always the last stderr line on non-zero exit.
8
+ - `stderr_logger` in `fascicle/adapters`: a JSONL trajectory logger to stderr, the default under `run_stdio` so stdout stays clean for the result envelope.
9
+
10
+ ### Fixed
11
+
12
+ - `check-publish`'s `@arethetypeswrong/cli` step no longer silently truncates its report when the output exceeds the OS pipe buffer (first hit once the `./stdio` subpath pushed the report past 64 KiB).
13
+
14
+ ### Internal
15
+
16
+ - Recorded the design rationale for the stdio agent contract as a research note.
17
+
18
+ ## v0.8.10 — 2026-06-20
19
+
20
+ ### Added
21
+
22
+ - Native constrained decoding for schema-constrained `model_call` on local providers (Ollama and LM Studio), exposed as a new `structured_output` provider capability: the schema now constrains the provider's decode (e.g. Ollama's `format`) instead of prompting for JSON and scraping it, so local-model structured output no longer fails validation on the first call. The prompt-based path remains the fallback, and hosted providers are unchanged.
23
+ - Live GitHub star count on the marketing site's nav button.
24
+
25
+ ### Internal
26
+
27
+ - Section taglines on marketing site sections 01, 02, and 05.
28
+
29
+ ## v0.8.9 — 2026-06-19
30
+
31
+ ### Internal
32
+
33
+ - Deepened mutation-testing coverage: bench (judge skipping on failed/undefined output, throwing-judge abstentions, non-finite cost filtering, nested `trajectory_dir` creation, live_url HTTP logging, run_id/flow_name resolution, concurrency limits, and the newly exported `normalize_score` helper), plus describe rendering and `define_agent` frontmatter.
34
+ - Added two Phase 3 essays latent in the codebase and updated the roadmap to reflect the Phase 2 MCP ship and the start of the memory system.
35
+ - Added `frontmatter` to the cspell dictionary.
36
+
37
+ ## v0.8.8 — 2026-06-19
38
+
39
+ ### Added
40
+
41
+ - `fascicle/mcp` bridge: serve any flow over the Model Context Protocol with `serve_flow`, and call MCP tools from inside flows with `mcp_client`.
42
+
43
+ ### Changed
44
+
45
+ - Release pipeline now emits a GitHub Release from the pushed tag instead of publishing to npm; CI workflows hardened (third-party actions pinned to commit SHAs, persisted credentials dropped, tag jobs env-guarded).
46
+
47
+ ### Internal
48
+
49
+ - Large mutation-testing campaign raised the real Stryker score from ~61% to ~81% and ratcheted the break gate 50 → 70 → 78. Added genuine tests across the MCP bridge, engine errors, the provider adapters (openai, google, openrouter, bedrock, lmstudio, ollama), model_call, both retry paths, schema, regression, tool_loop, generate (pure helpers and orchestration), composites/judges, claude_cli spawn and sandbox, the viewer HTTP server, the researcher agent, and the core branch/map/timeout/pipe combinators.
50
+ - Froze the ridgeline build specs and centralized planning in the roadmap.
51
+
52
+ ## v0.8.7 — 2026-06-18
53
+
54
+ ### Internal
55
+
56
+ - Added security policy, troubleshooting guide, API reference, and a comparison page under `docs/`.
57
+ - Reorganized project docs: reconciled `spec/`, `plans/`, and `adr/` into `docs/` and `research/`, and relocated the core and viewer READMEs into `docs/`.
58
+ - Added shared research diagrams (architecture layers, the 20 `STEP_KINDS` taxonomy, and the trajectory event pipeline) as Mermaid sources under `research/diagrams/`.
59
+
60
+ ## v0.8.6 — 2026-06-18
61
+
62
+ ### Internal
63
+
64
+ - Consolidated the `observability/` and `stores/` modules plus the `adapters.ts` umbrella into a single flat `src/adapters/` module with one barrel, renaming files to match their factories (`filesystem_logger.ts`, `filesystem_store.ts`, …) and retiring the `#observability`/`#stores` import aliases in favour of `#adapters`. The published `fascicle/adapters` subpath and its exports are unchanged.
65
+
66
+ ## v0.8.5 — 2026-06-18
67
+
68
+ ### Internal
69
+
70
+ - Restructured every `index.ts` barrel to be import/export only, moving inline logic into named sibling files (`agent.ts`, `start_viewer.ts`, `adapter.ts`, `make_builder_tools.ts`); public exports are unchanged.
71
+ - Added `rules/no-logic-in-barrel.yml` (ast-grep) to keep barrels declaration-free, with a documenting note in `AGENTS.md`.
72
+
73
+ ## v0.8.4 — 2026-06-18
74
+
75
+ ### Internal
76
+
77
+ - Relocated each module's `test/` tree to `__tests__/`, lifted the shared SIGINT loader bootstrap and core wiring integration test to a repo-root `test/` tree, and updated cspell, fallow, and ast-grep rule globs to match.
78
+ - Dropped lockstep versioning in favor of a single root manifest, so a bump now rewrites exactly one version field.
79
+
80
+ ## v0.8.3 — 2026-06-18
81
+
82
+ ### Added
83
+
84
+ - npm `keywords` covering core concepts, the AI SDK ecosystem, and every supported provider, so the package surfaces in npm search.
85
+
86
+ ### Changed
87
+
88
+ - Package metadata now points at the new documentation and marketing site: `homepage` links to https://robmclarty.github.io/fascicle/, and the npm description leads with the "compose agents like plain values" pitch.
89
+
90
+ ### Fixed
91
+
92
+ - The documentation site listed only 16 composition primitives; it now lists all 18, with the missing `loop` and `compose` entries added to both the homepage chip list and the API reference.
93
+
94
+ ### Internal
95
+
96
+ - GitHub Pages serves the static site without a generator step, oxlint ignores `site/**`, and the runtime task lock is excluded from version control.
97
+
98
+ ## v0.8.2 — 2026-06-18
99
+
100
+ ### Added
101
+
102
+ - Published a project site to GitHub Pages: a landing page (`index.html`), a docs page (`docs.html`), and a support script, deployed by a new `Deploy Pages` workflow that uploads the `site/` directory as a Pages artifact on every push to `main`.
103
+
104
+ ### Internal
105
+
106
+ - No change to the published `fascicle` surface or bundle. Renamed the existing `ci` and `release` workflow files from `.yml` to `.yaml` so every workflow shares one extension.
107
+ - Realigned the docs to the v0.7.0 Bedrock provider and dropped stale model-alias mentions.
108
+
3
109
  ## v0.8.1 — 2026-06-17
4
110
 
5
111
  ### Internal
package/README.md CHANGED
@@ -99,6 +99,31 @@ await run(flow, input, {
99
99
 
100
100
  `run.stream(flow, input)` returns `{ events, result }` for incremental observation.
101
101
 
102
+ **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.
103
+
104
+ <!-- snippet: check -->
105
+ ```typescript
106
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
107
+ import { z } from 'zod';
108
+ import { step } from 'fascicle';
109
+ import { mcp_client, serve_flow } from 'fascicle/mcp';
110
+
111
+ // Consume an external MCP server's tools inside a flow.
112
+ const remote = await mcp_client({ transport: 'stdio', command: 'my-mcp-server' });
113
+ console.log(remote.tools.map((t) => t.name));
114
+ await remote.close();
115
+
116
+ // Expose a composed flow as an MCP tool on your own server.
117
+ const server = new McpServer({ name: 'my-app', version: '1.0.0' });
118
+ serve_flow({
119
+ server,
120
+ flow: step('greet', (input: { name: string }) => `Hello, ${input.name}!`),
121
+ name: 'greet',
122
+ description: 'Greet a person by name.',
123
+ input_schema: z.object({ name: z.string() }),
124
+ });
125
+ ```
126
+
102
127
  ## Provider matrix
103
128
 
104
129
  | Provider | Peer dep | Auth |
@@ -107,6 +132,7 @@ await run(flow, input, {
107
132
  | `openai` | `@ai-sdk/openai` | API key |
108
133
  | `google` | `@ai-sdk/google` | API key |
109
134
  | `openrouter` | `@openrouter/ai-sdk-provider` | API key |
135
+ | `bedrock` | `@ai-sdk/amazon-bedrock` | `region` + AWS credentials |
110
136
  | `ollama` | `ai-sdk-ollama` | local `base_url` |
111
137
  | `lmstudio` | `@ai-sdk/openai-compatible` | local `base_url` |
112
138
  | `claude_cli` | none (spawns `claude`) | OAuth or API key |
@@ -137,19 +163,24 @@ const handle = await start_viewer({ port: 4242 });
137
163
  await handle.close();
138
164
  ```
139
165
 
140
- For zero-latency streaming from inside a long-running flow, pair it with `http_logger` from `fascicle/adapters`. See [src/viewer/README.md](./src/viewer/README.md) for the full transport story.
166
+ 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.
141
167
 
142
168
  ## Where to go next
143
169
 
144
170
  - [docs/getting-started.md](./docs/getting-started.md) — install and run your first flow
145
171
  - [docs/concepts.md](./docs/concepts.md) — step-as-value, trajectories, cancellation
146
- - [docs/configuration.md](./docs/configuration.md) — engine config, aliases, pricing, retries
172
+ - [docs/composition.md](./docs/composition.md) — full composition surface: the 18 primitives, run/stream, checkpointing
173
+ - [docs/api-reference.md](./docs/api-reference.md) — the public surface at a glance
174
+ - [docs/configuration.md](./docs/configuration.md) — engine config, defaults, pricing, retries
147
175
  - [docs/providers.md](./docs/providers.md) — per-provider adapter notes
148
176
  - [docs/cli.md](./docs/cli.md) — the `claude_cli` subprocess adapter
149
177
  - [docs/cookbook.md](./docs/cookbook.md) — retries, fan-out, judges, HITL, tool loops
150
178
  - [docs/writing-a-harness.md](./docs/writing-a-harness.md) — building a runner around fascicle
179
+ - [docs/embedding-under-a-harness.md](./docs/embedding-under-a-harness.md) — running a fascicle agent as somebody's child process
180
+ - [docs/troubleshooting.md](./docs/troubleshooting.md) — first-run errors and what they mean
181
+ - [docs/comparison.md](./docs/comparison.md) — how fascicle compares to LangChain, Mastra, and others
151
182
  - [examples/](./examples/) — runnable reference flows
152
- - [src/viewer/README.md](./src/viewer/README.md) — viewer details and transport options
183
+ - [docs/viewer.md](./docs/viewer.md) — viewer details and transport options
153
184
 
154
185
  ## Contributing
155
186
 
@@ -157,7 +188,7 @@ Fascicle is early and not accepting outside pull requests yet. Bug reports and f
157
188
 
158
189
  ## Development
159
190
 
160
- This repo is a **single package**. The code is organized as deep modules under `src/` — `src/core`, `src/engine`, `src/composites`, `src/observability`, `src/stores`, `src/viewer`, `src/agents` — each reachable only through its barrel via the `#<module>` import alias. The umbrella surface at the `src/` root is what publishes to npm as `fascicle`. Architectural boundaries (e.g. core cannot import adapters; engine imports core type-only; no `process.env` outside the audited exceptions) are enforced by the ast-grep rules in `rules/` and a directory-level boundary DAG in `fallow.toml`. The 5 apps under `examples/*/` are separate workspace members that consume the library via `fascicle: workspace:*`.
191
+ This repo is a **single package**. The code is organized as deep modules under `src/` — `src/core`, `src/engine`, `src/composites`, `src/adapters`, `src/viewer`, `src/agents` — each reachable only through its barrel via the `#<module>` import alias. The umbrella surface at the `src/` root is what publishes to npm as `fascicle`. Architectural boundaries (e.g. core cannot import adapters; engine imports core type-only; no `process.env` outside the audited exceptions) are enforced by the ast-grep rules in `rules/` and a directory-level boundary DAG in `fallow.toml`. The 5 apps under `examples/*/` are separate workspace members that consume the library via `fascicle: workspace:*`.
161
192
 
162
193
  ```bash
163
194
  pnpm install
@@ -1,29 +1,23 @@
1
- import { randomUUID } from "node:crypto";
2
- import { dirname } from "node:path";
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
3
4
  import { appendFileSync, mkdirSync } from "node:fs";
4
- //#region src/observability/filesystem.ts
5
+ //#region src/adapters/line_logger.ts
5
6
  /**
6
- * Filesystem JSONL trajectory logger.
7
- *
8
- * Appends one JSON object per line to a configured output file. `start_span`
9
- * and `end_span` each emit a line; `record` emits a line with the event as
10
- * written. When the caller supplies `parent_span_id` in the span meta (the
11
- * runner threads the true structural parent through `RunContext`), that value
12
- * is used verbatim, so span trees are correct even for concurrent children
13
- * under `parallel`/`map`. Only when no parent is supplied does the logger fall
14
- * back to an in-memory stack of still-open spans, which is best-effort under
15
- * concurrency. Two concurrent `run(...)` calls that pass distinct logger
16
- * instances (constructed with distinct `output_path`s) share nothing.
7
+ * Shared line-oriented trajectory logger core.
17
8
  *
18
- * Paths are accepted at construction; the logger never reads `process.env`.
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.
19
18
  */
20
- function filesystem_logger(options) {
21
- const { output_path } = options;
22
- mkdirSync(dirname(output_path), { recursive: true });
19
+ function line_logger(write_line) {
23
20
  const stack = [];
24
- const write_line = (event) => {
25
- appendFileSync(output_path, `${JSON.stringify(event)}\n`);
26
- };
27
21
  const start_span = (name, meta) => {
28
22
  const span_id = `${name}:${randomUUID().slice(0, 8)}`;
29
23
  const event = {
@@ -56,7 +50,27 @@ function filesystem_logger(options) {
56
50
  };
57
51
  }
58
52
  //#endregion
59
- //#region src/observability/http.ts
53
+ //#region src/adapters/filesystem_logger.ts
54
+ /**
55
+ * Filesystem JSONL trajectory logger.
56
+ *
57
+ * Appends one JSON object per line to a configured output file. Span
58
+ * bookkeeping (including the `parent_span_id` handling that keeps span trees
59
+ * correct for concurrent children under `parallel`/`map`) lives in
60
+ * `line_logger`. Two concurrent `run(...)` calls that pass distinct logger
61
+ * instances (constructed with distinct `output_path`s) share nothing.
62
+ *
63
+ * Paths are accepted at construction; the logger never reads `process.env`.
64
+ */
65
+ function filesystem_logger(options) {
66
+ const { output_path } = options;
67
+ mkdirSync(dirname(output_path), { recursive: true });
68
+ return line_logger((event) => {
69
+ appendFileSync(output_path, `${JSON.stringify(event)}\n`);
70
+ });
71
+ }
72
+ //#endregion
73
+ //#region src/adapters/http_logger.ts
60
74
  /**
61
75
  * HTTP push trajectory logger.
62
76
  *
@@ -126,7 +140,33 @@ function http_logger(options) {
126
140
  };
127
141
  }
128
142
  //#endregion
129
- //#region src/observability/tee.ts
143
+ //#region src/adapters/noop_logger.ts
144
+ /**
145
+ * No-op trajectory logger.
146
+ *
147
+ * Satisfies `TrajectoryLogger` from `core` without emitting any
148
+ * output. Used as the default when no logger is supplied to `run(...)` and as
149
+ * a cheap fallback in tests that do not care about trajectory output.
150
+ */
151
+ function noop_logger() {
152
+ return {
153
+ record: () => {},
154
+ start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,
155
+ end_span: () => {}
156
+ };
157
+ }
158
+ //#endregion
159
+ //#region src/adapters/stderr_logger.ts
160
+ function stderr_logger(options = {}) {
161
+ const stream = options.stream ?? process.stderr;
162
+ return line_logger((event) => {
163
+ try {
164
+ stream.write(`${JSON.stringify(event)}\n`);
165
+ } catch {}
166
+ });
167
+ }
168
+ //#endregion
169
+ //#region src/adapters/tee_logger.ts
130
170
  function tee_logger(...loggers) {
131
171
  if (loggers.length === 0) throw new Error("tee_logger: at least one logger required");
132
172
  const id_map = /* @__PURE__ */ new Map();
@@ -164,6 +204,61 @@ function tee_logger(...loggers) {
164
204
  };
165
205
  }
166
206
  //#endregion
167
- export { http_logger as n, filesystem_logger as r, tee_logger as t };
207
+ //#region src/adapters/filesystem_store.ts
208
+ /**
209
+ * Filesystem-backed checkpoint store.
210
+ *
211
+ * Satisfies `CheckpointStore` from `core`. Each key is stored as
212
+ * a JSON file under the configured root directory. Writes are all-or-nothing:
213
+ * values are written to a temporary sibling file and then atomically renamed
214
+ * into place, so an interrupted write never leaves a partially-written file
215
+ * at the target key (spec.md §6.3, §6.8). On `get`, a missing file, a partial
216
+ * temp file that is not atomically renamed, or a JSON parse failure each read
217
+ * as a cache miss (returning `null`) rather than an error.
218
+ *
219
+ * Paths are accepted at construction; the store never reads `process.env`.
220
+ */
221
+ function safe_filename(key) {
222
+ const hash = createHash("sha256").update(key).digest("hex").slice(0, 12);
223
+ return `${key.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64)}.${hash}.json`;
224
+ }
225
+ function filesystem_store(options) {
226
+ const { root_dir } = options;
227
+ const ensure_root = async () => {
228
+ await mkdir(root_dir, { recursive: true });
229
+ };
230
+ const path_for = (key) => join(root_dir, safe_filename(key));
231
+ const get = async (key) => {
232
+ const path = path_for(key);
233
+ let raw;
234
+ try {
235
+ raw = await readFile(path, "utf8");
236
+ } catch {
237
+ return null;
238
+ }
239
+ try {
240
+ return JSON.parse(raw);
241
+ } catch {
242
+ return null;
243
+ }
244
+ };
245
+ const set = async (key, value) => {
246
+ await ensure_root();
247
+ const target = path_for(key);
248
+ const tmp = `${target}.${randomUUID().slice(0, 8)}.tmp`;
249
+ await writeFile(tmp, JSON.stringify(value), "utf8");
250
+ await rename(tmp, target);
251
+ };
252
+ const delete_key = async (key) => {
253
+ await rm(path_for(key), { force: true });
254
+ };
255
+ return {
256
+ get,
257
+ set,
258
+ delete: delete_key
259
+ };
260
+ }
261
+ //#endregion
262
+ 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 };
168
263
 
169
- //# sourceMappingURL=tee-B-MeNi7d.js.map
264
+ //# sourceMappingURL=adapters-DdUx-_b3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters-DdUx-_b3.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\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\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\nconst default_fetch: HttpLoggerFetch = async (url, init) => {\n const res = await fetch(url, init)\n return { ok: res.ok, status: res.status }\n}\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\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\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\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 (spec.md §6.3, §6.8). On `get`, a missing file, a partial\n * temp file that is not atomically renamed, or a JSON parse failure each read\n * as a cache 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\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\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":";;;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAY,YAAwE;CAClG,MAAM,QAAkB,EAAE;CAE1B,MAAM,cAA8C,MAAM,SAAS;EACjE,MAAM,UAAU,GAAG,KAAK,GAAG,YAAY,CAAC,MAAM,GAAG,EAAE;EACnD,MAAM,QAAiC;GAAE,MAAM;GAAc;GAAS;GAAM,GAAG;GAAM;AACrF,MAAI,MAAM,sBAAsB,KAAA,KAAa,MAAM,SAAS,EAC1D,OAAM,oBAAoB,MAAM,MAAM,SAAS;AAEjD,aAAW,MAAM;AACjB,QAAM,KAAK,QAAQ;AACnB,SAAO;;CAGT,MAAM,YAA0C,IAAI,SAAS;AAC3D,aAAW;GAAE,MAAM;GAAY,SAAS;GAAI,GAAG;GAAM,CAAC;EACtD,MAAM,MAAM,MAAM,YAAY,GAAG;AACjC,MAAI,QAAQ,GAAI,OAAM,OAAO,KAAK,EAAE;;CAGtC,MAAM,UAAsC,UAAU;AACpD,aAAW,EAAE,GAAG,OAAO,CAAC;;AAG1B,QAAO;EAAE;EAAQ;EAAY;EAAU;;;;;;;;;;;;;;;ACpBzC,SAAgB,kBAAkB,SAAoD;CACpF,MAAM,EAAE,gBAAgB;AACxB,WAAU,QAAQ,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;AAEpD,QAAO,aAAa,UAAU;AAC5B,iBAAe,aAAa,GAAG,KAAK,UAAU,MAAM,CAAC,IAAI;GACzD;;;;;;;;;;;;;;;;;;;ACGJ,MAAM,gBAAiC,OAAO,KAAK,SAAS;CAC1D,MAAM,MAA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AAI,QAAQ,oBAAoB,IAAI,CAAC,MAAM,GAAG,GAAG,CAC/C,GAAG,KAAK;;AAGzB,SAAgB,iBAAiB,SAAkD;CACjF,MAAM,EAAE,aAAa;CAErB,MAAM,cAAc,YAA2B;AAC7C,QAAM,MAAM,UAAU,EAAE,WAAW,MAAM,CAAC;;CAG5C,MAAM,YAAY,QAAwB,KAAK,UAAU,cAAc,IAAI,CAAC;CAE5E,MAAM,MAAM,OAAO,QAAkC;EACnD,MAAM,OAAO,SAAS,IAAI;EAC1B,IAAI;AACJ,MAAI;AACF,SAAM,MAAM,SAAS,MAAM,OAAO;UAC5B;AACN,UAAO;;AAET,MAAI;AACF,UAAO,KAAK,MAAM,IAAI;UAChB;AACN,UAAO;;;CAIX,MAAM,MAAM,OAAO,KAAa,UAAkC;AAChE,QAAM,aAAa;EACnB,MAAM,SAAS,SAAS,IAAI;EAC5B,MAAM,MAAM,GAAG,OAAO,GAAG,YAAY,CAAC,MAAM,GAAG,EAAE,CAAC;AAClD,QAAM,UAAU,KAAK,KAAK,UAAU,MAAM,EAAE,OAAO;AACnD,QAAM,OAAO,KAAK,OAAO;;CAG3B,MAAM,aAAa,OAAO,QAA+B;AAEvD,QAAM,GADS,SAAS,IAAI,EACX,EAAE,OAAO,MAAM,CAAC;;AAGnC,QAAO;EAAE;EAAK;EAAK,QAAQ;EAAY"}
@@ -1,15 +1,12 @@
1
- import { G as CheckpointStore, X as TrajectoryLogger } from "./index-BjOnbuc9.js";
1
+ import { J as TrajectoryLogger, U as CheckpointStore } from "./index-CEj6hY9z.js";
2
2
 
3
- //#region src/observability/noop.d.ts
4
- declare function noop_logger(): TrajectoryLogger;
5
- //#endregion
6
- //#region src/observability/filesystem.d.ts
3
+ //#region src/adapters/filesystem_logger.d.ts
7
4
  type FilesystemLoggerOptions = {
8
5
  readonly output_path: string;
9
6
  };
10
7
  declare function filesystem_logger(options: FilesystemLoggerOptions): TrajectoryLogger;
11
8
  //#endregion
12
- //#region src/observability/http.d.ts
9
+ //#region src/adapters/http_logger.d.ts
13
10
  type HttpLoggerFetch = (url: string, init: {
14
11
  method: 'POST';
15
12
  headers: Record<string, string>;
@@ -25,14 +22,25 @@ type HttpLoggerOptions = {
25
22
  };
26
23
  declare function http_logger(options: HttpLoggerOptions): TrajectoryLogger;
27
24
  //#endregion
28
- //#region src/observability/tee.d.ts
25
+ //#region src/adapters/noop_logger.d.ts
26
+ declare function noop_logger(): TrajectoryLogger;
27
+ //#endregion
28
+ //#region src/adapters/stderr_logger.d.ts
29
+ type StderrLoggerOptions = {
30
+ readonly stream?: {
31
+ write(chunk: string): unknown;
32
+ };
33
+ };
34
+ declare function stderr_logger(options?: StderrLoggerOptions): TrajectoryLogger;
35
+ //#endregion
36
+ //#region src/adapters/tee_logger.d.ts
29
37
  declare function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger;
30
38
  //#endregion
31
- //#region src/stores/filesystem.d.ts
39
+ //#region src/adapters/filesystem_store.d.ts
32
40
  type FilesystemStoreOptions = {
33
41
  readonly root_dir: string;
34
42
  };
35
43
  declare function filesystem_store(options: FilesystemStoreOptions): CheckpointStore;
36
44
  //#endregion
37
- export { type FilesystemLoggerOptions, type FilesystemStoreOptions, type HttpLoggerFetch, type HttpLoggerOptions, filesystem_logger, filesystem_store, http_logger, noop_logger, tee_logger };
45
+ export { type FilesystemLoggerOptions, type FilesystemStoreOptions, type HttpLoggerFetch, type HttpLoggerOptions, type StderrLoggerOptions, filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
38
46
  //# sourceMappingURL=adapters.d.ts.map
package/dist/adapters.js CHANGED
@@ -1,78 +1,2 @@
1
- import { n as http_logger, r as filesystem_logger, t as tee_logger } from "./tee-B-MeNi7d.js";
2
- import { createHash, randomUUID } from "node:crypto";
3
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
- import { join } from "node:path";
5
- //#region src/observability/noop.ts
6
- /**
7
- * No-op trajectory logger.
8
- *
9
- * Satisfies `TrajectoryLogger` from `core` without emitting any
10
- * output. Used as the default when no logger is supplied to `run(...)` and as
11
- * a cheap fallback in tests that do not care about trajectory output.
12
- */
13
- function noop_logger() {
14
- return {
15
- record: () => {},
16
- start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,
17
- end_span: () => {}
18
- };
19
- }
20
- //#endregion
21
- //#region src/stores/filesystem.ts
22
- /**
23
- * Filesystem-backed checkpoint store.
24
- *
25
- * Satisfies `CheckpointStore` from `core`. Each key is stored as
26
- * a JSON file under the configured root directory. Writes are all-or-nothing:
27
- * values are written to a temporary sibling file and then atomically renamed
28
- * into place, so an interrupted write never leaves a partially-written file
29
- * at the target key (spec.md §6.3, §6.8). On `get`, a missing file, a partial
30
- * temp file that is not atomically renamed, or a JSON parse failure each read
31
- * as a cache miss (returning `null`) rather than an error.
32
- *
33
- * Paths are accepted at construction; the store never reads `process.env`.
34
- */
35
- function safe_filename(key) {
36
- const hash = createHash("sha256").update(key).digest("hex").slice(0, 12);
37
- return `${key.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64)}.${hash}.json`;
38
- }
39
- function filesystem_store(options) {
40
- const { root_dir } = options;
41
- const ensure_root = async () => {
42
- await mkdir(root_dir, { recursive: true });
43
- };
44
- const path_for = (key) => join(root_dir, safe_filename(key));
45
- const get = async (key) => {
46
- const path = path_for(key);
47
- let raw;
48
- try {
49
- raw = await readFile(path, "utf8");
50
- } catch {
51
- return null;
52
- }
53
- try {
54
- return JSON.parse(raw);
55
- } catch {
56
- return null;
57
- }
58
- };
59
- const set = async (key, value) => {
60
- await ensure_root();
61
- const target = path_for(key);
62
- const tmp = `${target}.${randomUUID().slice(0, 8)}.tmp`;
63
- await writeFile(tmp, JSON.stringify(value), "utf8");
64
- await rename(tmp, target);
65
- };
66
- const delete_key = async (key) => {
67
- await rm(path_for(key), { force: true });
68
- };
69
- return {
70
- get,
71
- set,
72
- delete: delete_key
73
- };
74
- }
75
- //#endregion
76
- export { filesystem_logger, filesystem_store, http_logger, noop_logger, tee_logger };
77
-
78
- //# sourceMappingURL=adapters.js.map
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-DdUx-_b3.js";
2
+ export { filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };