fascicle 0.9.8 → 0.9.10

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/dist/stdio.js CHANGED
@@ -1,7 +1,16 @@
1
- import { T as run } from "./core-CYpxskeT.js";
2
- import { r as stderr_logger } from "./adapters-Dbx3M8m-.js";
1
+ import { T as run } from "./core-DNH8ddMT.js";
2
+ import { r as stderr_logger } from "./adapters-CJnu1687.js";
3
3
  import { text } from "node:stream/consumers";
4
4
  //#region src/stdio/execute_stdio.ts
5
+ /**
6
+ * Runs the stdio agent contract over injected `io`: read input, run the
7
+ * flow, dispose the engine, write output, and return the outcome as a
8
+ * value.
9
+ *
10
+ * Disposes the engine before writing output so a teardown failure on the
11
+ * success path yields code 1 and no stdout, keeping "code 0 means stdout
12
+ * carries an authoritative result" true even when disposal fails.
13
+ */
5
14
  async function execute_stdio(flow, options, io) {
6
15
  const produced = await produce_output(flow, options, io);
7
16
  const dispose_failure = await dispose_engine(options.engine);
@@ -23,6 +32,14 @@ async function execute_stdio(flow, options, io) {
23
32
  }
24
33
  return { code: 0 };
25
34
  }
35
+ /**
36
+ * Reads stdin, parses and validates it against the input schema, runs the
37
+ * flow, then validates and serializes the result.
38
+ *
39
+ * Returns a tagged result instead of throwing so `execute_stdio` can dispose
40
+ * the engine and choose the right exit code regardless of which stage
41
+ * failed.
42
+ */
26
43
  async function produce_output(flow, options, io) {
27
44
  let raw;
28
45
  try {
@@ -109,6 +126,10 @@ async function produce_output(flow, options, io) {
109
126
  json
110
127
  };
111
128
  }
129
+ /**
130
+ * Disposes the caller's engine when one was supplied, returning a
131
+ * `StdioFailure` if disposal throws and `null` otherwise.
132
+ */
112
133
  async function dispose_engine(engine) {
113
134
  if (engine === void 0) return null;
114
135
  try {
@@ -118,6 +139,9 @@ async function dispose_engine(engine) {
118
139
  return make_failure("dispose", err);
119
140
  }
120
141
  }
142
+ /**
143
+ * Builds a `StdioFailure` for the given stage from a thrown value.
144
+ */
121
145
  function make_failure(stage, err) {
122
146
  const cause = safe_cause(err);
123
147
  return {
@@ -126,6 +150,13 @@ function make_failure(stage, err) {
126
150
  ...cause !== void 0 ? { cause } : {}
127
151
  };
128
152
  }
153
+ /**
154
+ * Reduces a thrown value to a JSON-safe cause for `StdioFailure`.
155
+ *
156
+ * An `Error` is reduced to its `name`, `message`, and Zod's `path` property
157
+ * when present (`safeParse` issues carry one); anything else is passed
158
+ * through `to_json_safe`.
159
+ */
129
160
  function safe_cause(err) {
130
161
  if (err instanceof Error) {
131
162
  const path = Reflect.get(err, "path");
@@ -137,6 +168,14 @@ function safe_cause(err) {
137
168
  }
138
169
  return to_json_safe(err);
139
170
  }
171
+ /**
172
+ * Round-trips a value through `JSON.stringify`/`parse` so it is safe to
173
+ * embed in a `StdioFailure` that the glue will serialize again.
174
+ *
175
+ * Never throws and never returns a value that would make that later
176
+ * serialization throw or silently vanish: a circular reference or a BigInt
177
+ * becomes `undefined` instead.
178
+ */
140
179
  function to_json_safe(value) {
141
180
  try {
142
181
  const json = JSON.stringify(value);
@@ -166,6 +205,14 @@ function to_json_safe(value) {
166
205
  * Excluded from mutation testing as process/IO glue (see stryker.config.mjs);
167
206
  * the spawn-based contract tests in `__tests__/e2e/` exercise it for real.
168
207
  */
208
+ /**
209
+ * Runs a flow as the stdio agent contract against the real process streams,
210
+ * then exits with the outcome's code.
211
+ *
212
+ * On a non-zero outcome, writes the `StdioFailure` as the last line on
213
+ * stderr so a parent process can take the tail line as machine-readable
214
+ * detail.
215
+ */
169
216
  async function run_stdio(flow, options = {}) {
170
217
  const outcome = await execute_stdio(flow, options, {
171
218
  read_input: () => text(process.stdin),
@@ -177,6 +224,10 @@ async function run_stdio(flow, options = {}) {
177
224
  } catch {}
178
225
  process.exit(outcome.code);
179
226
  }
227
+ /**
228
+ * Writes a chunk to a stream and resolves only once it is flushed, so the
229
+ * caller can safely exit the process afterward without truncating output.
230
+ */
180
231
  function write_flushed(stream, chunk) {
181
232
  return new Promise((resolve, reject) => {
182
233
  stream.write(chunk, (err) => {
package/dist/stdio.js.map CHANGED
@@ -1 +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,EAAE;CACvD,MAAM,kBAAkB,MAAM,eAAe,QAAQ,MAAM;CAC3D,IAAI,SAAS,SAAS,UAAU,OAAO;EAAE,MAAM,SAAS;EAAM,SAAS,SAAS;CAAQ;CACxF,IAAI,oBAAoB,MAAM,OAAO;EAAE,MAAM;EAAG,SAAS;CAAgB;CACzE,IAAI;EACF,MAAM,GAAG,aAAa,GAAG,SAAS,KAAK,GAAG;CAC5C,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAG,SAAS,aAAa,SAAS,GAAG;EAAE;CACxD;CACA,OAAO,EAAE,MAAM,EAAE;AACnB;AAMA,eAAe,eACb,MACA,SACA,IACwB;CACxB,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,GAAG,WAAW;CAC5B,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,QAAQ,GAAG;EAAE;CACvE;CAEA,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAA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AA8B;CAC/E,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,OAAO,MAAM,QAAQ,QAAQ;GAC3B,IAAI,KAAK,OAAO,GAAG;QACd,QAAQ;EACf,CAAC;CACH,CAAC;AACH"}
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\n/**\n * Runs the stdio agent contract over injected `io`: read input, run the\n * flow, dispose the engine, write output, and return the outcome as a\n * value.\n *\n * Disposes the engine before writing output so a teardown failure on the\n * success path yields code 1 and no stdout, keeping \"code 0 means stdout\n * carries an authoritative result\" true even when disposal fails.\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\n/**\n * Reads stdin, parses and validates it against the input schema, runs the\n * flow, then validates and serializes the result.\n *\n * Returns a tagged result instead of throwing so `execute_stdio` can dispose\n * the engine and choose the right exit code regardless of which stage\n * failed.\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\n/**\n * Disposes the caller's engine when one was supplied, returning a\n * `StdioFailure` if disposal throws and `null` otherwise.\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\n/**\n * Builds a `StdioFailure` for the given stage from a thrown value.\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\n/**\n * Reduces a thrown value to a JSON-safe cause for `StdioFailure`.\n *\n * An `Error` is reduced to its `name`, `message`, and Zod's `path` property\n * when present (`safeParse` issues carry one); anything else is passed\n * through `to_json_safe`.\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/**\n * Round-trips a value through `JSON.stringify`/`parse` so it is safe to\n * embed in a `StdioFailure` that the glue will serialize again.\n *\n * Never throws and never returns a value that would make that later\n * serialization throw or silently vanish: a circular reference or a BigInt\n * becomes `undefined` instead.\n */\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\n/**\n * Runs a flow as the stdio agent contract against the real process streams,\n * then exits with the outcome's code.\n *\n * On a non-zero outcome, writes the `StdioFailure` as the last line on\n * stderr so a parent process can take the tail line as machine-readable\n * detail.\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\n/**\n * Writes a chunk to a stream and resolves only once it is flushed, so the\n * caller can safely exit the process afterward without truncating output.\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":";;;;;;;;;;;;;AAoEA,eAAsB,cACpB,MACA,SACA,IACuB;CACvB,MAAM,WAAW,MAAM,eAAe,MAAM,SAAS,EAAE;CACvD,MAAM,kBAAkB,MAAM,eAAe,QAAQ,MAAM;CAC3D,IAAI,SAAS,SAAS,UAAU,OAAO;EAAE,MAAM,SAAS;EAAM,SAAS,SAAS;CAAQ;CACxF,IAAI,oBAAoB,MAAM,OAAO;EAAE,MAAM;EAAG,SAAS;CAAgB;CACzE,IAAI;EACF,MAAM,GAAG,aAAa,GAAG,SAAS,KAAK,GAAG;CAC5C,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAG,SAAS,aAAa,SAAS,GAAG;EAAE;CACxD;CACA,OAAO,EAAE,MAAM,EAAE;AACnB;;;;;;;;;AAcA,eAAe,eACb,MACA,SACA,IACwB;CACxB,IAAI;CACJ,IAAI;EACF,MAAM,MAAM,GAAG,WAAW;CAC5B,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,QAAQ,GAAG;EAAE;CACvE;CAEA,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,SAAS,KAAK;EACZ,OAAO;GAAE,MAAM;GAAU,MAAM;GAAG,SAAS,aAAa,SAAS,GAAG;EAAE;CACxE;CAEA,IAAI;CACJ,IAAI,QAAQ,iBAAiB,KAAA,GAAW;EACtC,MAAM,UAAU,QAAQ,aAAa,UAAU,MAAM;EACrD,IAAI,CAAC,QAAQ,SACX,OAAO;GACL,MAAM;GACN,MAAM;GACN,SAAS;IACP,OAAO;IACP,OAAO;IACP,OAAO,aAAa,QAAQ,MAAM,M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  import { UIMessageChunk } from "ai";
3
3
  import { ServerResponse } from "node:http";
4
4
 
@@ -25,11 +25,21 @@ type UiMapperState = {
25
25
  readonly open_reasoning: Set<number>;
26
26
  readonly tool_names: Map<string, string>;
27
27
  };
28
+ /**
29
+ * Create an empty `UiMapperState` for a new stream.
30
+ */
28
31
  declare function create_ui_mapper_state(): UiMapperState;
32
+ /**
33
+ * Close every text/reasoning block still open in `state`, returning the
34
+ * `*-end` chunks needed.
35
+ *
36
+ * Used on stream `finish` and to flush any blocks still open when the
37
+ * underlying event iterable ends.
38
+ */
29
39
  declare function close_open_blocks(state: UiMapperState): UIMessageChunk[];
30
40
  /**
31
41
  * Map one run event to zero or more UI message chunks, advancing `state`.
32
- * Non-`model_chunk` events (spans, cost, user emits) yield nothing in v1.
42
+ * Non-`model_chunk` events (spans, cost, user emits) yield nothing.
33
43
  */
34
44
  declare function to_ui_message_chunks(event: TrajectoryEvent, state: UiMapperState): UIMessageChunk[];
35
45
  /**
package/dist/ui.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createUIMessageStream, createUIMessageStreamResponse, pipeUIMessageStreamToResponse } from "ai";
2
2
  //#region src/ui/to_ui_message_stream.ts
3
3
  /**
4
- * fascicle/ui — bridge a run's event stream to the AI SDK "UI message stream".
4
+ * fascicle/ui: bridge a run's event stream to the AI SDK "UI message stream".
5
5
  *
6
6
  * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,
7
7
  * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.
@@ -18,6 +18,9 @@ import { createUIMessageStream, createUIMessageStreamResponse, pipeUIMessageStre
18
18
  * vocabulary has no generated-file kind (those provider parts drop at the
19
19
  * inbound mapping), so there is nothing here to translate them from.
20
20
  */
21
+ /**
22
+ * Create an empty `UiMapperState` for a new stream.
23
+ */
21
24
  function create_ui_mapper_state() {
22
25
  return {
23
26
  open_text: /* @__PURE__ */ new Set(),
@@ -25,12 +28,25 @@ function create_ui_mapper_state() {
25
28
  tool_names: /* @__PURE__ */ new Map()
26
29
  };
27
30
  }
31
+ /**
32
+ * Build the UI message chunk id for a step's text block.
33
+ */
28
34
  function text_id(step_index) {
29
35
  return `text-${step_index}`;
30
36
  }
37
+ /**
38
+ * Build the UI message chunk id for a step's reasoning block.
39
+ */
31
40
  function reasoning_id(step_index) {
32
41
  return `reasoning-${step_index}`;
33
42
  }
43
+ /**
44
+ * Close the text/reasoning blocks open for one step, returning the
45
+ * `*-end` chunks needed and updating `state` in place.
46
+ *
47
+ * Called on a `step_finish` chunk, so only that step's blocks close; blocks
48
+ * open for other steps are untouched.
49
+ */
34
50
  function close_step_blocks(step_index, state) {
35
51
  const parts = [];
36
52
  if (state.open_text.delete(step_index)) parts.push({
@@ -43,6 +59,13 @@ function close_step_blocks(step_index, state) {
43
59
  });
44
60
  return parts;
45
61
  }
62
+ /**
63
+ * Close every text/reasoning block still open in `state`, returning the
64
+ * `*-end` chunks needed.
65
+ *
66
+ * Used on stream `finish` and to flush any blocks still open when the
67
+ * underlying event iterable ends.
68
+ */
46
69
  function close_open_blocks(state) {
47
70
  const parts = [];
48
71
  for (const step_index of state.open_text) parts.push({
@@ -57,6 +80,10 @@ function close_open_blocks(state) {
57
80
  state.open_reasoning.clear();
58
81
  return parts;
59
82
  }
83
+ /**
84
+ * Map a single engine `StreamChunk` to the `UIMessageChunk`s it produces,
85
+ * opening and closing text/reasoning blocks in `state` as needed.
86
+ */
60
87
  function map_chunk(chunk, state) {
61
88
  switch (chunk.kind) {
62
89
  case "text": {
@@ -125,6 +152,11 @@ function map_chunk(chunk, state) {
125
152
  default: return [];
126
153
  }
127
154
  }
155
+ /**
156
+ * Narrow an untyped `TrajectoryEvent['chunk']` payload to a `StreamChunk`
157
+ * when it looks like one (an object with a string `kind`), otherwise
158
+ * return `undefined`.
159
+ */
128
160
  function as_stream_chunk(value) {
129
161
  if (typeof value !== "object" || value === null) return void 0;
130
162
  if (typeof Reflect.get(value, "kind") !== "string") return void 0;
@@ -132,13 +164,18 @@ function as_stream_chunk(value) {
132
164
  }
133
165
  /**
134
166
  * Map one run event to zero or more UI message chunks, advancing `state`.
135
- * Non-`model_chunk` events (spans, cost, user emits) yield nothing in v1.
167
+ * Non-`model_chunk` events (spans, cost, user emits) yield nothing.
136
168
  */
137
169
  function to_ui_message_chunks(event, state) {
138
170
  if (event.kind !== "model_chunk") return [];
139
171
  const chunk = as_stream_chunk(event["chunk"]);
140
172
  return chunk === void 0 ? [] : map_chunk(chunk, state);
141
173
  }
174
+ /**
175
+ * Build the `ReadableStream<UIMessageChunk>` that drives a `run.stream(...)`
176
+ * handle through `to_ui_message_chunks`, used by both the `Response` and
177
+ * Node `ServerResponse` entry points below.
178
+ */
142
179
  function build_stream(handle, options) {
143
180
  const on_error = options.on_error;
144
181
  return createUIMessageStream({
package/dist/ui.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ui.js","names":[],"sources":["../src/ui/to_ui_message_stream.ts"],"sourcesContent":["/**\n * fascicle/ui — bridge a run's event stream to the AI SDK \"UI message stream\".\n *\n * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,\n * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.\n * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a\n * fascicle flow can back a `useChat` endpoint rendered by AI Elements /\n * Streamdown, with zero bespoke glue.\n *\n * It is the outbound inverse of the engine's inbound provider->StreamChunk\n * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the\n * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this\n * file only translates chunk shapes and manages open text/reasoning blocks.\n *\n * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk\n * vocabulary has no generated-file kind (those provider parts drop at the\n * inbound mapping), so there is nothing here to translate them from.\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n pipeUIMessageStreamToResponse,\n} from 'ai'\nimport type { UIMessageChunk } from 'ai'\nimport type { ServerResponse } from 'node:http'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\n\n/**\n * The structural shape of a `run.stream(...)` handle. Typed structurally rather\n * than importing the core `StreamingRunHandle` so this module depends on no\n * core value and a caller can pass `run.stream(...)` directly.\n */\nexport type RunStreamLike = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<unknown>\n}\n\nexport type ToUiStreamOptions = {\n /** Map a thrown run error to the text of an `error` part. */\n readonly on_error?: (error: unknown) => string\n}\n\n/**\n * Per-stream state: which text/reasoning blocks are open (so `*-start` fires\n * once and `*-end` closes them) and the tool name for each in-flight call (so\n * `tool-input-available` can echo it after only the id arrives at close).\n */\nexport type UiMapperState = {\n readonly open_text: Set<number>\n readonly open_reasoning: Set<number>\n readonly tool_names: Map<string, string>\n}\n\nexport function create_ui_mapper_state(): UiMapperState {\n return { open_text: new Set(), open_reasoning: new Set(), tool_names: new Map() }\n}\n\nfunction text_id(step_index: number): string {\n return `text-${step_index}`\n}\n\nfunction reasoning_id(step_index: number): string {\n return `reasoning-${step_index}`\n}\n\nfunction close_step_blocks(step_index: number, state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n if (state.open_text.delete(step_index)) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n if (state.open_reasoning.delete(step_index)) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n return parts\n}\n\nexport function close_open_blocks(state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n for (const step_index of state.open_text) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n for (const step_index of state.open_reasoning) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n state.open_text.clear()\n state.open_reasoning.clear()\n return parts\n}\n\nfunction map_chunk(chunk: StreamChunk, state: UiMapperState): UIMessageChunk[] {\n switch (chunk.kind) {\n case 'text': {\n const id = text_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_text.has(chunk.step_index)) {\n state.open_text.add(chunk.step_index)\n parts.push({ type: 'text-start', id })\n }\n parts.push({ type: 'text-delta', id, delta: chunk.text })\n return parts\n }\n case 'reasoning': {\n const id = reasoning_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_reasoning.has(chunk.step_index)) {\n state.open_reasoning.add(chunk.step_index)\n parts.push({ type: 'reasoning-start', id })\n }\n parts.push({ type: 'reasoning-delta', id, delta: chunk.text })\n return parts\n }\n case 'tool_call_start': {\n state.tool_names.set(chunk.id, chunk.name)\n return [{ type: 'tool-input-start', toolCallId: chunk.id, toolName: chunk.name }]\n }\n case 'tool_call_input_delta':\n return [{ type: 'tool-input-delta', toolCallId: chunk.id, inputTextDelta: chunk.delta }]\n case 'tool_call_end':\n return [\n {\n type: 'tool-input-available',\n toolCallId: chunk.id,\n toolName: state.tool_names.get(chunk.id) ?? '',\n input: chunk.input,\n },\n ]\n case 'tool_result':\n return chunk.error !== undefined\n ? [{ type: 'tool-output-error', toolCallId: chunk.id, errorText: chunk.error.message }]\n : [{ type: 'tool-output-available', toolCallId: chunk.id, output: chunk.output }]\n case 'step_finish':\n return close_step_blocks(chunk.step_index, state)\n case 'finish':\n return close_open_blocks(state)\n default:\n return []\n }\n}\n\nfunction as_stream_chunk(value: unknown): StreamChunk | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const kind = Reflect.get(value, 'kind')\n if (typeof kind !== 'string') return undefined\n // The value rode a loose TrajectoryEvent bag; model_call only records real\n // StreamChunks under `chunk`, and map_chunk narrows on `kind`, so treating it\n // as a StreamChunk is sound. Unknown kinds fall through to `[]`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as StreamChunk\n}\n\n/**\n * Map one run event to zero or more UI message chunks, advancing `state`.\n * Non-`model_chunk` events (spans, cost, user emits) yield nothing in v1.\n */\nexport function to_ui_message_chunks(\n event: TrajectoryEvent,\n state: UiMapperState,\n): UIMessageChunk[] {\n if (event.kind !== 'model_chunk') return []\n const chunk = as_stream_chunk(event['chunk'])\n return chunk === undefined ? [] : map_chunk(chunk, state)\n}\n\nfunction build_stream(\n handle: RunStreamLike,\n options: ToUiStreamOptions,\n): ReadableStream<UIMessageChunk> {\n const on_error = options.on_error\n return createUIMessageStream({\n execute: async ({ writer }) => {\n const state = create_ui_mapper_state()\n for await (const event of handle.events) {\n for (const part of to_ui_message_chunks(event, state)) writer.write(part)\n }\n for (const part of close_open_blocks(state)) writer.write(part)\n await handle.result\n },\n ...(on_error !== undefined ? { onError: on_error } : {}),\n })\n}\n\n/**\n * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint\n * can return directly.\n */\nexport function to_ui_message_response(\n handle: RunStreamLike,\n options: ToUiStreamOptions = {},\n): Response {\n return createUIMessageStreamResponse({ stream: build_stream(handle, options) })\n}\n\n/**\n * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for\n * `node:http` servers that hold a `ServerResponse` rather than returning a\n * web `Response`.\n */\nexport function pipe_ui_message_stream_to_response(\n handle: RunStreamLike,\n response: ServerResponse,\n options: ToUiStreamOptions = {},\n): void {\n pipeUIMessageStreamToResponse({ response, stream: build_stream(handle, options) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,IAAI,IAAI;CAAE;AAClF;AAEA,SAAS,QAAQ,YAA4B;CAC3C,OAAO,QAAQ;AACjB;AAEA,SAAS,aAAa,YAA4B;CAChD,OAAO,aAAa;AACtB;AAEA,SAAS,kBAAkB,YAAoB,OAAwC;CACrF,MAAM,QAA0B,CAAC;CACjC,IAAI,MAAM,UAAU,OAAO,UAAU,GACnC,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,IAAI,MAAM,eAAe,OAAO,UAAU,GACxC,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,aAAa,UAAU;CAAE,CAAC;CAE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BACd,QACA,UAA6B,CAAC,GACpB;CACV,OAAO,8BAA8B,EAAE,QAAQ,aAAa,QAAQ,OAAO,EAAE,CAAC;AAChF;;;;;;AAOA,SAAgB,mCACd,QACA,UACA,UAA6B,CAAC,GACxB;CACN,8BAA8B;EAAE;EAAU,QAAQ,aAAa,QAAQ,OAAO;CAAE,CAAC;AACnF"}
1
+ {"version":3,"file":"ui.js","names":[],"sources":["../src/ui/to_ui_message_stream.ts"],"sourcesContent":["/**\n * fascicle/ui: bridge a run's event stream to the AI SDK \"UI message stream\".\n *\n * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,\n * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.\n * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a\n * fascicle flow can back a `useChat` endpoint rendered by AI Elements /\n * Streamdown, with zero bespoke glue.\n *\n * It is the outbound inverse of the engine's inbound provider->StreamChunk\n * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the\n * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this\n * file only translates chunk shapes and manages open text/reasoning blocks.\n *\n * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk\n * vocabulary has no generated-file kind (those provider parts drop at the\n * inbound mapping), so there is nothing here to translate them from.\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n pipeUIMessageStreamToResponse,\n} from 'ai'\nimport type { UIMessageChunk } from 'ai'\nimport type { ServerResponse } from 'node:http'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\n\n/**\n * The structural shape of a `run.stream(...)` handle. Typed structurally rather\n * than importing the core `StreamingRunHandle` so this module depends on no\n * core value and a caller can pass `run.stream(...)` directly.\n */\nexport type RunStreamLike = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<unknown>\n}\n\nexport type ToUiStreamOptions = {\n /** Map a thrown run error to the text of an `error` part. */\n readonly on_error?: (error: unknown) => string\n}\n\n/**\n * Per-stream state: which text/reasoning blocks are open (so `*-start` fires\n * once and `*-end` closes them) and the tool name for each in-flight call (so\n * `tool-input-available` can echo it after only the id arrives at close).\n */\nexport type UiMapperState = {\n readonly open_text: Set<number>\n readonly open_reasoning: Set<number>\n readonly tool_names: Map<string, string>\n}\n\n/**\n * Create an empty `UiMapperState` for a new stream.\n */\nexport function create_ui_mapper_state(): UiMapperState {\n return { open_text: new Set(), open_reasoning: new Set(), tool_names: new Map() }\n}\n\n/**\n * Build the UI message chunk id for a step's text block.\n */\nfunction text_id(step_index: number): string {\n return `text-${step_index}`\n}\n\n/**\n * Build the UI message chunk id for a step's reasoning block.\n */\nfunction reasoning_id(step_index: number): string {\n return `reasoning-${step_index}`\n}\n\n/**\n * Close the text/reasoning blocks open for one step, returning the\n * `*-end` chunks needed and updating `state` in place.\n *\n * Called on a `step_finish` chunk, so only that step's blocks close; blocks\n * open for other steps are untouched.\n */\nfunction close_step_blocks(step_index: number, state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n if (state.open_text.delete(step_index)) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n if (state.open_reasoning.delete(step_index)) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n return parts\n}\n\n/**\n * Close every text/reasoning block still open in `state`, returning the\n * `*-end` chunks needed.\n *\n * Used on stream `finish` and to flush any blocks still open when the\n * underlying event iterable ends.\n */\nexport function close_open_blocks(state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n for (const step_index of state.open_text) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n for (const step_index of state.open_reasoning) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n state.open_text.clear()\n state.open_reasoning.clear()\n return parts\n}\n\n/**\n * Map a single engine `StreamChunk` to the `UIMessageChunk`s it produces,\n * opening and closing text/reasoning blocks in `state` as needed.\n */\nfunction map_chunk(chunk: StreamChunk, state: UiMapperState): UIMessageChunk[] {\n switch (chunk.kind) {\n case 'text': {\n const id = text_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_text.has(chunk.step_index)) {\n state.open_text.add(chunk.step_index)\n parts.push({ type: 'text-start', id })\n }\n parts.push({ type: 'text-delta', id, delta: chunk.text })\n return parts\n }\n case 'reasoning': {\n const id = reasoning_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_reasoning.has(chunk.step_index)) {\n state.open_reasoning.add(chunk.step_index)\n parts.push({ type: 'reasoning-start', id })\n }\n parts.push({ type: 'reasoning-delta', id, delta: chunk.text })\n return parts\n }\n case 'tool_call_start': {\n state.tool_names.set(chunk.id, chunk.name)\n return [{ type: 'tool-input-start', toolCallId: chunk.id, toolName: chunk.name }]\n }\n case 'tool_call_input_delta':\n return [{ type: 'tool-input-delta', toolCallId: chunk.id, inputTextDelta: chunk.delta }]\n case 'tool_call_end':\n return [\n {\n type: 'tool-input-available',\n toolCallId: chunk.id,\n toolName: state.tool_names.get(chunk.id) ?? '',\n input: chunk.input,\n },\n ]\n case 'tool_result':\n return chunk.error !== undefined\n ? [{ type: 'tool-output-error', toolCallId: chunk.id, errorText: chunk.error.message }]\n : [{ type: 'tool-output-available', toolCallId: chunk.id, output: chunk.output }]\n case 'step_finish':\n return close_step_blocks(chunk.step_index, state)\n case 'finish':\n return close_open_blocks(state)\n default:\n return []\n }\n}\n\n/**\n * Narrow an untyped `TrajectoryEvent['chunk']` payload to a `StreamChunk`\n * when it looks like one (an object with a string `kind`), otherwise\n * return `undefined`.\n */\nfunction as_stream_chunk(value: unknown): StreamChunk | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const kind = Reflect.get(value, 'kind')\n if (typeof kind !== 'string') return undefined\n // The value rode a loose TrajectoryEvent bag; model_call only records real\n // StreamChunks under `chunk`, and map_chunk narrows on `kind`, so treating it\n // as a StreamChunk is sound. Unknown kinds fall through to `[]`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as StreamChunk\n}\n\n/**\n * Map one run event to zero or more UI message chunks, advancing `state`.\n * Non-`model_chunk` events (spans, cost, user emits) yield nothing.\n */\nexport function to_ui_message_chunks(\n event: TrajectoryEvent,\n state: UiMapperState,\n): UIMessageChunk[] {\n if (event.kind !== 'model_chunk') return []\n const chunk = as_stream_chunk(event['chunk'])\n return chunk === undefined ? [] : map_chunk(chunk, state)\n}\n\n/**\n * Build the `ReadableStream<UIMessageChunk>` that drives a `run.stream(...)`\n * handle through `to_ui_message_chunks`, used by both the `Response` and\n * Node `ServerResponse` entry points below.\n */\nfunction build_stream(\n handle: RunStreamLike,\n options: ToUiStreamOptions,\n): ReadableStream<UIMessageChunk> {\n const on_error = options.on_error\n return createUIMessageStream({\n execute: async ({ writer }) => {\n const state = create_ui_mapper_state()\n for await (const event of handle.events) {\n for (const part of to_ui_message_chunks(event, state)) writer.write(part)\n }\n for (const part of close_open_blocks(state)) writer.write(part)\n await handle.result\n },\n ...(on_error !== undefined ? { onError: on_error } : {}),\n })\n}\n\n/**\n * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint\n * can return directly.\n */\nexport function to_ui_message_response(\n handle: RunStreamLike,\n options: ToUiStreamOptions = {},\n): Response {\n return createUIMessageStreamResponse({ stream: build_stream(handle, options) })\n}\n\n/**\n * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for\n * `node:http` servers that hold a `ServerResponse` rather than returning a\n * web `Response`.\n */\nexport function pipe_ui_message_stream_to_response(\n handle: RunStreamLike,\n response: ServerResponse,\n options: ToUiStreamOptions = {},\n): void {\n pipeUIMessageStreamToResponse({ response, stream: build_stream(handle, options) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,IAAI,IAAI;CAAE;AAClF;;;;AAKA,SAAS,QAAQ,YAA4B;CAC3C,OAAO,QAAQ;AACjB;;;;AA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AsB;EAC3B,SAAS,OAAO,EAAE,aAAa;GAC7B,MAAM,QAAQ,uBAAuB;GACrC,WAAW,MAAM,SAAS,OAAO,QAC/B,KAAK,MAAM,QAAQ,qBAAqB,OAAO,KAAK,GAAG,OAAO,MAAM,IAAI;GAE1E,KAAK,MAAM,QAAQ,kBAAkB,KAAK,GAAG,OAAO,MAAM,IAAI;GAC9D,MAAM,OAAO;EACf;EACA,GAAI,aAAa,KAAA,IAAY,EAAE,SAAS,SAAS,IAAI,CAAC;CACxD,CAAC;AACH;;;;;AAMA,SAAgB,uBACd,QACA,UAA6B,CAAC,GACpB;CACV,OAAO,8BAA8B,EAAE,QAAQ,aAAa,QAAQ,OAAO,EAAE,CAAC;AAChF;;;;;;AAOA,SAAgB,mCACd,QACA,UACA,UAA6B,CAAC,GACxB;CACN,8BAA8B;EAAE;EAAU,QAAQ,aAAa,QAAQ,OAAO;CAAE,CAAC;AACnF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fascicle",
3
- "version": "0.9.8",
3
+ "version": "0.9.10",
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",
@@ -104,13 +104,14 @@
104
104
  },
105
105
  "scripts": {
106
106
  "build": "node scripts/build.mjs",
107
- "check": "node scripts/check.mjs",
108
- "check:all": "node scripts/check.mjs --all",
109
- "check:json": "node scripts/check.mjs --json",
110
- "check:bail": "node scripts/check.mjs --bail",
107
+ "check": "checkride",
108
+ "check:all": "checkride --all",
109
+ "check:json": "checkride --json",
110
+ "check:bail": "checkride --bail",
111
+ "check:changed": "checkride --changed",
111
112
  "check:fix": "pnpm exec oxlint --type-aware --fix && node scripts/strip-semicolons.mjs && pnpm exec fallow fix",
112
113
  "check:mutation": "stryker run",
113
- "check:publish": "node scripts/check-publish.mjs",
114
+ "check:publish": "checkride --only publint,attw,pack,smoke,snippets",
114
115
  "check:security": "pnpm audit --audit-level=high",
115
116
  "prepublishOnly": "pnpm check && pnpm build && pnpm check:publish",
116
117
  "test": "vitest run",
@@ -173,11 +174,13 @@
173
174
  "@stryker-mutator/vitest-runner": "9.6.1",
174
175
  "@types/node": "26.1.0",
175
176
  "@vitest/coverage-v8": "4.1.10",
177
+ "checkride": "0.6.0",
176
178
  "cspell": "10.0.1",
177
- "fallow": "3.2.0",
179
+ "fallow": "3.6.0",
178
180
  "markdownlint-cli2": "0.23.0",
179
181
  "oxlint": "1.73.0",
180
182
  "oxlint-tsgolint": "0.24.0",
183
+ "publint": "0.3.21",
181
184
  "tsdown": "0.22.3",
182
185
  "tsx": "4.23.0",
183
186
  "typescript": "6.0.3",
@@ -1 +0,0 @@
1
- {"version":3,"file":"adapters-Dbx3M8m-.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,CAAC;CAEzB,MAAM,cAA8C,MAAM,SAAS;EACjE,MAAM,UAAU,GAAG,KAAK,GAAG,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC;EAClD,MAAM,QAAiC;GAAE,MAAM;GAAc;GAAS;GAAM,GAAG;EAAK;EACpF,IAAI,MAAM,sBAAsB,KAAA,KAAa,MAAM,SAAS,GAC1D,MAAM,oBAAoB,MAAM,MAAM,SAAS;EAEjD,WAAW,KAAK;EAChB,MAAM,KAAK,OAAO;EAClB,OAAO;CACT;CAEA,MAAM,YAA0C,IAAI,SAAS;EAC3D,WAAW;GAAE,MAAM;GAAY,SAAS;GAAI,GAAG;EAAK,CAAC;EACrD,MAAM,MAAM,MAAM,YAAY,EAAE;EAChC,IAAI,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CACrC;CAEA,MAAM,UAAsC,UAAU;EACpD,WAAW,EAAE,GAAG,MAAM,CAAC;CACzB;CAEA,OAAO;EAAE;EAAQ;EAAY;CAAS;AACxC;;;;;;;;;;;;;;ACrBA,SAAgB,kBAAkB,SAAoD;CACpF,MAAM,EAAE,gBAAgB;CACxB,UAAU,QAAQ,WAAW,GAAG,EAAE,WAAW,KAAK,CAAC;CAEnD,OAAO,aAAa,UAAU;EAC5B,eAAe,aAAa,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;CAC1D,CAAC;AACH;;;;;;;;;;;;;;;;;;ACEA,MAAM,gBAAiC,OAAO,KAAK,SAAS;CAC1D,MAAM,MAAM,MAAM,MAAM,KAAK,IAAI;CACjC,OAAO;EAAE,IAAI,IAAI;EAAI,QAAQ,IAAI;CAAO;AAC1C;AAEA,SAAgB,YAAY,S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