fascicle 0.8.10 → 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,20 @@
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
+
3
18
  ## v0.8.10 — 2026-06-20
4
19
 
5
20
  ### Added
package/README.md CHANGED
@@ -176,6 +176,7 @@ For zero-latency streaming from inside a long-running flow, pair it with `http_l
176
176
  - [docs/cli.md](./docs/cli.md) — the `claude_cli` subprocess adapter
177
177
  - [docs/cookbook.md](./docs/cookbook.md) — retries, fan-out, judges, HITL, tool loops
178
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
179
180
  - [docs/troubleshooting.md](./docs/troubleshooting.md) — first-run errors and what they mean
180
181
  - [docs/comparison.md](./docs/comparison.md) — how fascicle compares to LangChain, Mastra, and others
181
182
  - [examples/](./examples/) — runnable reference flows
@@ -2,29 +2,22 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
4
  import { appendFileSync, mkdirSync } from "node:fs";
5
- //#region src/adapters/filesystem_logger.ts
5
+ //#region src/adapters/line_logger.ts
6
6
  /**
7
- * Filesystem JSONL trajectory logger.
8
- *
9
- * Appends one JSON object per line to a configured output file. `start_span`
10
- * and `end_span` each emit a line; `record` emits a line with the event as
11
- * written. When the caller supplies `parent_span_id` in the span meta (the
12
- * runner threads the true structural parent through `RunContext`), that value
13
- * is used verbatim, so span trees are correct even for concurrent children
14
- * under `parallel`/`map`. Only when no parent is supplied does the logger fall
15
- * back to an in-memory stack of still-open spans, which is best-effort under
16
- * concurrency. Two concurrent `run(...)` calls that pass distinct logger
17
- * instances (constructed with distinct `output_path`s) share nothing.
7
+ * Shared line-oriented trajectory logger core.
18
8
  *
19
- * 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.
20
18
  */
21
- function filesystem_logger(options) {
22
- const { output_path } = options;
23
- mkdirSync(dirname(output_path), { recursive: true });
19
+ function line_logger(write_line) {
24
20
  const stack = [];
25
- const write_line = (event) => {
26
- appendFileSync(output_path, `${JSON.stringify(event)}\n`);
27
- };
28
21
  const start_span = (name, meta) => {
29
22
  const span_id = `${name}:${randomUUID().slice(0, 8)}`;
30
23
  const event = {
@@ -57,6 +50,26 @@ function filesystem_logger(options) {
57
50
  };
58
51
  }
59
52
  //#endregion
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
60
73
  //#region src/adapters/http_logger.ts
61
74
  /**
62
75
  * HTTP push trajectory logger.
@@ -143,6 +156,16 @@ function noop_logger() {
143
156
  };
144
157
  }
145
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
146
169
  //#region src/adapters/tee_logger.ts
147
170
  function tee_logger(...loggers) {
148
171
  if (loggers.length === 0) throw new Error("tee_logger: at least one logger required");
@@ -236,6 +259,6 @@ function filesystem_store(options) {
236
259
  };
237
260
  }
238
261
  //#endregion
239
- export { filesystem_logger as a, http_logger as i, tee_logger as n, noop_logger as r, filesystem_store as t };
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 };
240
263
 
241
- //# sourceMappingURL=adapters-BS8cBOjL.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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,SAAS,IAAI,EACX,EAAE,OAAO,MAAM,CAAC;;AAGnC,QAAO;EAAE;EAAK;EAAK,QAAQ;EAAY"}
@@ -25,6 +25,14 @@ declare function http_logger(options: HttpLoggerOptions): TrajectoryLogger;
25
25
  //#region src/adapters/noop_logger.d.ts
26
26
  declare function noop_logger(): TrajectoryLogger;
27
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
28
36
  //#region src/adapters/tee_logger.d.ts
29
37
  declare function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger;
30
38
  //#endregion
@@ -34,5 +42,5 @@ type FilesystemStoreOptions = {
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,2 +1,2 @@
1
- import { a as filesystem_logger, i as http_logger, n as tee_logger, r as noop_logger, t as filesystem_store } from "./adapters-BS8cBOjL.js";
2
- export { filesystem_logger, filesystem_store, http_logger, noop_logger, tee_logger };
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 };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { A as timeout_error, C as describe, D as describe_cycle_error, E as aborted_error, O as resume_validation_error, S as sequence, T as run, _ as retry, a as trajectory_event_schema, b as branch, c as scope, d as suspend, f as checkpoint, g as fallback, h as timeout, i as span_start_event_schema, j as flow_schema_default, k as suspended_error, l as stash, m as loop, n as emit_event_schema, o as STEP_KINDS, p as compose, r as span_end_event_schema, s as is_step_kind, t as custom_event_schema, u as use, v as pipe, w as step, x as parallel, y as map } from "./core-dRSAN1Q2.js";
2
- import { a as filesystem_logger, i as http_logger, n as tee_logger } from "./adapters-BS8cBOjL.js";
2
+ import { a as http_logger, n as tee_logger, o as filesystem_logger } from "./adapters-DdUx-_b3.js";
3
3
  import { createHash } from "node:crypto";
4
4
  import { z } from "zod";
5
5
  import { mkdir, open, readFile, readdir, stat, writeFile } from "node:fs/promises";
@@ -0,0 +1,38 @@
1
+ import { G as Step, J as TrajectoryLogger } from "./index-CEj6hY9z.js";
2
+ import { z } from "zod";
3
+
4
+ //#region src/stdio/execute_stdio.d.ts
5
+ type RunStdioOptions<i, o> = {
6
+ readonly input_schema?: z.ZodType<i>;
7
+ readonly output_schema?: z.ZodType<o>;
8
+ readonly engine?: {
9
+ readonly dispose: () => Promise<void>;
10
+ };
11
+ readonly trajectory?: TrajectoryLogger;
12
+ readonly abort?: AbortSignal;
13
+ };
14
+ type StdioFailure = {
15
+ readonly error: string;
16
+ readonly stage?: 'read' | 'parse' | 'validate_input' | 'run' | 'validate_output' | 'serialize' | 'write' | 'dispose';
17
+ readonly cause?: unknown;
18
+ };
19
+ type StdioOutcome = {
20
+ readonly code: 0;
21
+ } | {
22
+ readonly code: 1 | 2;
23
+ readonly failure: StdioFailure;
24
+ };
25
+ type StdioIo = {
26
+ readonly read_input: () => Promise<string>;
27
+ readonly write_output: (text: string) => Promise<void>;
28
+ readonly error_stream: {
29
+ write(chunk: string): unknown;
30
+ };
31
+ };
32
+ declare function execute_stdio<i, o>(flow: Step<i, o>, options: RunStdioOptions<i, o>, io: StdioIo): Promise<StdioOutcome>;
33
+ //#endregion
34
+ //#region src/stdio/run_stdio.d.ts
35
+ declare function run_stdio<i, o>(flow: Step<i, o>, options?: RunStdioOptions<i, o>): Promise<void>;
36
+ //#endregion
37
+ export { type RunStdioOptions, type StdioFailure, type StdioIo, type StdioOutcome, execute_stdio, run_stdio };
38
+ //# sourceMappingURL=stdio.d.ts.map
package/dist/stdio.js ADDED
@@ -0,0 +1,191 @@
1
+ import { T as run } from "./core-dRSAN1Q2.js";
2
+ import { r as stderr_logger } from "./adapters-DdUx-_b3.js";
3
+ import { text } from "node:stream/consumers";
4
+ //#region src/stdio/execute_stdio.ts
5
+ async function execute_stdio(flow, options, io) {
6
+ const produced = await produce_output(flow, options, io);
7
+ const dispose_failure = await dispose_engine(options.engine);
8
+ if (produced.kind === "failed") return {
9
+ code: produced.code,
10
+ failure: produced.failure
11
+ };
12
+ if (dispose_failure !== null) return {
13
+ code: 1,
14
+ failure: dispose_failure
15
+ };
16
+ try {
17
+ await io.write_output(`${produced.json}\n`);
18
+ } catch (err) {
19
+ return {
20
+ code: 1,
21
+ failure: make_failure("write", err)
22
+ };
23
+ }
24
+ return { code: 0 };
25
+ }
26
+ async function produce_output(flow, options, io) {
27
+ let raw;
28
+ try {
29
+ raw = await io.read_input();
30
+ } catch (err) {
31
+ return {
32
+ kind: "failed",
33
+ code: 2,
34
+ failure: make_failure("read", err)
35
+ };
36
+ }
37
+ let parsed;
38
+ try {
39
+ parsed = JSON.parse(raw);
40
+ } catch (err) {
41
+ return {
42
+ kind: "failed",
43
+ code: 2,
44
+ failure: make_failure("parse", err)
45
+ };
46
+ }
47
+ let input;
48
+ if (options.input_schema !== void 0) {
49
+ const checked = options.input_schema.safeParse(parsed);
50
+ if (!checked.success) return {
51
+ kind: "failed",
52
+ code: 2,
53
+ failure: {
54
+ error: "input failed schema validation",
55
+ stage: "validate_input",
56
+ cause: to_json_safe(checked.error.issues)
57
+ }
58
+ };
59
+ input = checked.data;
60
+ } else input = parsed;
61
+ const trajectory = options.trajectory ?? stderr_logger({ stream: io.error_stream });
62
+ let result;
63
+ try {
64
+ result = await run(flow, input, {
65
+ trajectory,
66
+ ...options.abort !== void 0 ? { abort: options.abort } : {}
67
+ });
68
+ } catch (err) {
69
+ return {
70
+ kind: "failed",
71
+ code: 1,
72
+ failure: make_failure("run", err)
73
+ };
74
+ }
75
+ let output = result;
76
+ if (options.output_schema !== void 0) {
77
+ const checked = options.output_schema.safeParse(result);
78
+ if (!checked.success) return {
79
+ kind: "failed",
80
+ code: 2,
81
+ failure: {
82
+ error: "flow result failed schema validation",
83
+ stage: "validate_output",
84
+ cause: to_json_safe(checked.error.issues)
85
+ }
86
+ };
87
+ output = checked.data;
88
+ }
89
+ let json;
90
+ try {
91
+ json = JSON.stringify(output);
92
+ } catch (err) {
93
+ return {
94
+ kind: "failed",
95
+ code: 2,
96
+ failure: make_failure("serialize", err)
97
+ };
98
+ }
99
+ if (json === void 0) return {
100
+ kind: "failed",
101
+ code: 2,
102
+ failure: {
103
+ error: "flow result is not JSON-serializable",
104
+ stage: "serialize"
105
+ }
106
+ };
107
+ return {
108
+ kind: "ok",
109
+ json
110
+ };
111
+ }
112
+ async function dispose_engine(engine) {
113
+ if (engine === void 0) return null;
114
+ try {
115
+ await engine.dispose();
116
+ return null;
117
+ } catch (err) {
118
+ return make_failure("dispose", err);
119
+ }
120
+ }
121
+ function make_failure(stage, err) {
122
+ const cause = safe_cause(err);
123
+ return {
124
+ error: err instanceof Error ? err.message : String(err),
125
+ stage,
126
+ ...cause !== void 0 ? { cause } : {}
127
+ };
128
+ }
129
+ function safe_cause(err) {
130
+ if (err instanceof Error) {
131
+ const path = Reflect.get(err, "path");
132
+ return {
133
+ name: err.name,
134
+ message: err.message,
135
+ ...Array.isArray(path) ? { path: to_json_safe(path) } : {}
136
+ };
137
+ }
138
+ return to_json_safe(err);
139
+ }
140
+ function to_json_safe(value) {
141
+ try {
142
+ const json = JSON.stringify(value);
143
+ if (json === void 0) return void 0;
144
+ return JSON.parse(json);
145
+ } catch {
146
+ return;
147
+ }
148
+ }
149
+ //#endregion
150
+ //#region src/stdio/run_stdio.ts
151
+ /**
152
+ * Process glue for the stdio agent contract.
153
+ *
154
+ * Binds `execute_stdio` to the real process: stdin to EOF in, exactly one JSON
155
+ * document on stdout out, trajectory on stderr, exit code as the verdict
156
+ * (0 = result on stdout is authoritative, 1 = flow failure, 2 = contract
157
+ * violation). On a non-zero exit the LAST stderr line is the `StdioFailure`
158
+ * as a single JSON object, so parents that want machine-readable detail take
159
+ * the tail line.
160
+ *
161
+ * Final writes await the write callback before `process.exit`: on pipes,
162
+ * exiting with buffered data truncates it, and a large JSON result is exactly
163
+ * the risk case. Signal handlers stay at the runner's default (installed): a
164
+ * single-shot child must die when the parent forwards SIGINT.
165
+ *
166
+ * Excluded from mutation testing as process/IO glue (see stryker.config.mjs);
167
+ * the spawn-based contract tests in `__tests__/e2e/` exercise it for real.
168
+ */
169
+ async function run_stdio(flow, options = {}) {
170
+ const outcome = await execute_stdio(flow, options, {
171
+ read_input: () => text(process.stdin),
172
+ write_output: (chunk) => write_flushed(process.stdout, chunk),
173
+ error_stream: process.stderr
174
+ });
175
+ if (outcome.code !== 0) try {
176
+ await write_flushed(process.stderr, `${JSON.stringify(outcome.failure)}\n`);
177
+ } catch {}
178
+ process.exit(outcome.code);
179
+ }
180
+ function write_flushed(stream, chunk) {
181
+ return new Promise((resolve, reject) => {
182
+ stream.write(chunk, (err) => {
183
+ if (err) reject(err);
184
+ else resolve();
185
+ });
186
+ });
187
+ }
188
+ //#endregion
189
+ export { execute_stdio, run_stdio };
190
+
191
+ //# sourceMappingURL=stdio.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stdio.js","names":[],"sources":["../src/stdio/execute_stdio.ts","../src/stdio/run_stdio.ts"],"sourcesContent":["/**\n * The stdio agent contract, minus the process.\n *\n * `execute_stdio` is everything `run_stdio` does (read, parse, validate, run,\n * validate, serialize, dispose), expressed over an injected `StdioIo` and\n * returning a `StdioOutcome` instead of touching `process.*` or exiting. The\n * split keeps the contract's branching unit-testable; the thin glue in\n * `run_stdio.ts` owns the real streams and the exit.\n *\n * The governing invariant: code 0 if and only if stdout carries an\n * authoritative result. That is why the engine is disposed before the output\n * is written (a teardown failure on the success path yields code 1 and no\n * stdout) and why every failure class short-circuits before `write_output`.\n * Code 1 means the flow did not produce a result (including a forwarded\n * SIGINT/SIGTERM aborting the run, or a failed delivery); code 2 means the\n * contract itself was violated (unparseable stdin, schema mismatch in either\n * direction, unserializable result).\n */\n\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { stderr_logger } from '#adapters'\n\nexport type RunStdioOptions<i, o> = {\n readonly input_schema?: z.ZodType<i>\n readonly output_schema?: z.ZodType<o>\n // Structural on purpose: anything with an async dispose qualifies, and the\n // stdio module never imports the engine layer.\n readonly engine?: { readonly dispose: () => Promise<void> }\n readonly trajectory?: TrajectoryLogger\n readonly abort?: AbortSignal\n}\n\nexport type StdioFailure = {\n readonly error: string\n readonly stage?:\n | 'read'\n | 'parse'\n | 'validate_input'\n | 'run'\n | 'validate_output'\n | 'serialize'\n | 'write'\n | 'dispose'\n readonly cause?: unknown\n}\n\nexport type StdioOutcome =\n | { readonly code: 0 }\n | { readonly code: 1 | 2; readonly failure: StdioFailure }\n\nexport type StdioIo = {\n readonly read_input: () => Promise<string>\n // Resolves once the bytes are flushed to the OS, so the caller may exit.\n readonly write_output: (text: string) => Promise<void>\n readonly error_stream: { write(chunk: string): unknown }\n}\n\nexport async function execute_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<StdioOutcome> {\n const produced = await produce_output(flow, options, io)\n const dispose_failure = await dispose_engine(options.engine)\n if (produced.kind === 'failed') return { code: produced.code, failure: produced.failure }\n if (dispose_failure !== null) return { code: 1, failure: dispose_failure }\n try {\n await io.write_output(`${produced.json}\\n`)\n } catch (err) {\n return { code: 1, failure: make_failure('write', err) }\n }\n return { code: 0 }\n}\n\ntype ProduceResult =\n | { readonly kind: 'ok'; readonly json: string }\n | { readonly kind: 'failed'; readonly code: 1 | 2; readonly failure: StdioFailure }\n\nasync function produce_output<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o>,\n io: StdioIo,\n): Promise<ProduceResult> {\n let raw: string\n try {\n raw = await io.read_input()\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('read', err) }\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('parse', err) }\n }\n\n let input: i\n if (options.input_schema !== undefined) {\n const checked = options.input_schema.safeParse(parsed)\n if (!checked.success) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'input failed schema validation',\n stage: 'validate_input',\n cause: to_json_safe(checked.error.issues),\n },\n }\n }\n input = checked.data\n } else {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n input = parsed as i\n }\n\n const trajectory = options.trajectory ?? stderr_logger({ stream: io.error_stream })\n\n let result: o\n try {\n result = await run(flow, input, {\n trajectory,\n ...(options.abort !== undefined ? { abort: options.abort } : {}),\n })\n } catch (err) {\n return { kind: 'failed', code: 1, failure: make_failure('run', err) }\n }\n\n let output: unknown = result\n if (options.output_schema !== undefined) {\n const checked = options.output_schema.safeParse(result)\n if (!checked.success) {\n return {\n kind: 'failed',\n code: 2,\n failure: {\n error: 'flow result failed schema validation',\n stage: 'validate_output',\n cause: to_json_safe(checked.error.issues),\n },\n }\n }\n output = checked.data\n }\n\n let json: string | undefined\n try {\n json = JSON.stringify(output)\n } catch (err) {\n return { kind: 'failed', code: 2, failure: make_failure('serialize', err) }\n }\n if (json === undefined) {\n return {\n kind: 'failed',\n code: 2,\n failure: { error: 'flow result is not JSON-serializable', stage: 'serialize' },\n }\n }\n return { kind: 'ok', json }\n}\n\nasync function dispose_engine(\n engine: RunStdioOptions<never, never>['engine'],\n): Promise<StdioFailure | null> {\n if (engine === undefined) return null\n try {\n await engine.dispose()\n return null\n } catch (err) {\n return make_failure('dispose', err)\n }\n}\n\nfunction make_failure(stage: NonNullable<StdioFailure['stage']>, err: unknown): StdioFailure {\n const cause = safe_cause(err)\n return {\n error: err instanceof Error ? err.message : String(err),\n stage,\n ...(cause !== undefined ? { cause } : {}),\n }\n}\n\nfunction safe_cause(err: unknown): unknown {\n if (err instanceof Error) {\n const path = Reflect.get(err, 'path')\n return {\n name: err.name,\n message: err.message,\n ...(Array.isArray(path) ? { path: to_json_safe(path) } : {}),\n }\n }\n return to_json_safe(err)\n}\n\n// The glue serializes the failure with JSON.stringify; cause must never make\n// that throw (circular refs, BigInt) or silently vanish (undefined-only).\nfunction to_json_safe(value: unknown): unknown {\n try {\n const json = JSON.stringify(value)\n if (json === undefined) return undefined\n return JSON.parse(json) as unknown\n } catch {\n return undefined\n }\n}\n","/**\n * Process glue for the stdio agent contract.\n *\n * Binds `execute_stdio` to the real process: stdin to EOF in, exactly one JSON\n * document on stdout out, trajectory on stderr, exit code as the verdict\n * (0 = result on stdout is authoritative, 1 = flow failure, 2 = contract\n * violation). On a non-zero exit the LAST stderr line is the `StdioFailure`\n * as a single JSON object, so parents that want machine-readable detail take\n * the tail line.\n *\n * Final writes await the write callback before `process.exit`: on pipes,\n * exiting with buffered data truncates it, and a large JSON result is exactly\n * the risk case. Signal handlers stay at the runner's default (installed): a\n * single-shot child must die when the parent forwards SIGINT.\n *\n * Excluded from mutation testing as process/IO glue (see stryker.config.mjs);\n * the spawn-based contract tests in `__tests__/e2e/` exercise it for real.\n */\n\nimport { text } from 'node:stream/consumers'\nimport type { Step } from '#core'\nimport { execute_stdio } from './execute_stdio.js'\nimport type { RunStdioOptions } from './execute_stdio.js'\n\nexport async function run_stdio<i, o>(\n flow: Step<i, o>,\n options: RunStdioOptions<i, o> = {},\n): Promise<void> {\n const outcome = await execute_stdio(flow, options, {\n read_input: () => text(process.stdin),\n write_output: (chunk) => write_flushed(process.stdout, chunk),\n error_stream: process.stderr,\n })\n if (outcome.code !== 0) {\n try {\n await write_flushed(process.stderr, `${JSON.stringify(outcome.failure)}\\n`)\n } catch {\n // stderr is gone; the exit code still carries the verdict.\n }\n }\n process.exit(outcome.code)\n}\n\nfunction write_flushed(stream: NodeJS.WriteStream, chunk: string): Promise<void> {\n return new Promise((resolve, reject) => {\n stream.write(chunk, (err) => {\n if (err) reject(err)\n else resolve()\n })\n })\n}\n"],"mappings":";;;;AA2DA,eAAsB,cACpB,MACA,SACA,IACuB;CACvB,MAAM,WAAW,MAAM,eAAe,MAAM,SAAS,GAAG;CACxD,MAAM,kBAAkB,MAAM,eAAe,QAAQ,OAAO;AAC5D,KAAI,SAAS,SAAS,SAAU,QAAO;EAAE,MAAM,SAAS;EAAM,SAAS,SAAS;EAAS;AACzF,KAAI,oBAAoB,KAAM,QAAO;EAAE,MAAM;EAAG,SAAS;EAAiB;AAC1E,KAAI;AACF,QAAM,GAAG,aAAa,GAAG,SAAS,KAAK,IAAI;UACpC,KAAK;AACZ,SAAO;GAAE,MAAM;GAAG,SAAS,aAAa,SAAS,IAAI;GAAE;;AAEzD,QAAO,EAAE,MAAM,GAAG;;AAOpB,eAAe,eACb,MACA,SACA,IACwB;CACxB,IAAI;AACJ,KAAI;AACF,QAAM,MAAM,GAAG,YAAY;UACpB,KAAK;AACZ,SAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,QAAQ,IAAI;GAAE;;CAGxE,IAAI;AACJ,KAAI;AACF,WAAS,KAAK,MAAM,IAAI;UACjB,KAAK;AACZ,SAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,SAAS,IAAI;GAAE;;CAGzE,IAAI;AACJ,KAAI,QAAQ,iBAAiB,KAAA,GAAW;EACtC,MAAM,UAAU,QAAQ,aAAa,UAAU,OAAO;AACtD,MAAI,CAAC,QAAQ,QACX,QAAO;GACL,MAAM;GACN,MAAM;GACN,SAAS;IACP,OAAO;IACP,OAAO;IACP,OAAO,aAAa,QAAQ,MAAM,OAAO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,EAAE;EACzC;;AAGH,SAAS,WAAW,KAAuB;AACzC,KAAI,eAAe,OAAO;EACxB,MAAM,OAAO,QAAQ,IAAI,KAAK,OAAO;AACrC,SAAO;GACL,MAAM,IAAI;GACV,SAAS,IAAI;GACb,GAAI,MAAM,QAAQ,KAAK,GAAG,EAAE,MAAM,aAAa,KAAK,EAAE,GAAG,EAAE;GAC5D;;AAEH,QAAO,aAAa,IAAI;;AAK1B,SAAS,aAAa,OAAyB;AAC7C,KAAI;EACF,MAAM,OAAO,KAAK,UAAU,MAAM;AAClC,MAAI,SAAS,KAAA,EAAW,QAAO,KAAA;AAC/B,SAAO,KAAK,MAAM,KAAK;SACjB;AACN;;;;;;;;;;;;;;;;;;;;;;;ACrLJ,eAAsB,UACpB,MACA,UAAiC,EAAE,EACpB;CACf,MAAM,UAAU,MAAM,cAAc,MAAM,SAAS;EACjD,kBAAkB,KAAK,QAAQ,MAAM;EACrC,eAAe,UAAU,cAAc,QAAQ,QAAQ,MAAM;EAC7D,cAAc,QAAQ;EACvB,CAAC;AACF,KAAI,QAAQ,SAAS,EACnB,KAAI;AACF,QAAM,cAAc,QAAQ,QAAQ,GAAG,KAAK,UAAU,QAAQ,QAAQ,CAAC,IAAI;SACrE;AAIV,SAAQ,KAAK,QAAQ,KAAK;;AAG5B,SAAS,cAAc,QAA4B,OAA8B;AAC/E,QAAO,IAAI,SAAS,SAAS,WAAW;AACtC,SAAO,MAAM,QAAQ,QAAQ;AAC3B,OAAI,IAAK,QAAO,IAAI;OACf,UAAS;IACd;GACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fascicle",
3
- "version": "0.8.10",
3
+ "version": "0.8.11",
4
4
  "description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
5
5
  "keywords": [
6
6
  "agents",
@@ -53,6 +53,10 @@
53
53
  "./mcp": {
54
54
  "types": "./dist/mcp.d.ts",
55
55
  "import": "./dist/mcp.js"
56
+ },
57
+ "./stdio": {
58
+ "types": "./dist/stdio.d.ts",
59
+ "import": "./dist/stdio.js"
56
60
  }
57
61
  },
58
62
  "imports": {
@@ -61,7 +65,8 @@
61
65
  "#composites": "./src/composites/index.ts",
62
66
  "#adapters": "./src/adapters/index.ts",
63
67
  "#viewer": "./src/viewer/index.ts",
64
- "#agents": "./src/agents/index.ts"
68
+ "#agents": "./src/agents/index.ts",
69
+ "#stdio": "./src/stdio/index.ts"
65
70
  },
66
71
  "bin": {
67
72
  "fascicle-viewer": "./dist/bin/fascicle-viewer.js"
@@ -1 +0,0 @@
1
- {"version":3,"file":"adapters-BS8cBOjL.js","names":[],"sources":["../src/adapters/filesystem_logger.ts","../src/adapters/http_logger.ts","../src/adapters/noop_logger.ts","../src/adapters/tee_logger.ts","../src/adapters/filesystem_store.ts"],"sourcesContent":["/**\n * Filesystem JSONL trajectory logger.\n *\n * Appends one JSON object per line to a configured output file. `start_span`\n * and `end_span` each emit a line; `record` emits a line with the event as\n * written. When the caller supplies `parent_span_id` in the span meta (the\n * runner threads the true structural parent through `RunContext`), that value\n * is used verbatim, so span trees are correct even for concurrent children\n * under `parallel`/`map`. Only when no parent is supplied does the logger fall\n * back to an in-memory stack of still-open spans, which is best-effort under\n * concurrency. 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 { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\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 const stack: string[] = []\n\n const write_line = (event: Record<string, unknown>): void => {\n appendFileSync(output_path, `${JSON.stringify(event)}\\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 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 * 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 * 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":";;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,kBAAkB,SAAoD;CACpF,MAAM,EAAE,gBAAgB;AACxB,WAAU,QAAQ,YAAY,EAAE,EAAE,WAAW,MAAM,CAAC;CAEpD,MAAM,QAAkB,EAAE;CAE1B,MAAM,cAAc,UAAyC;AAC3D,iBAAe,aAAa,GAAG,KAAK,UAAU,MAAM,CAAC,IAAI;;CAG3D,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;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