fascicle 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +150 -0
  2. package/README.md +8 -8
  3. package/dist/acp.d.ts +16 -2
  4. package/dist/acp.js +1406 -1307
  5. package/dist/acp.js.map +1 -1
  6. package/dist/{adapters-DNnzeLxr.js → adapters-CDUzZlby.js} +35 -13
  7. package/dist/adapters-CDUzZlby.js.map +1 -0
  8. package/dist/adapters.d.ts +8 -1
  9. package/dist/adapters.js +1 -1
  10. package/dist/agents.d.ts +1 -1
  11. package/dist/agents.js +15 -8
  12. package/dist/agents.js.map +1 -1
  13. package/dist/bin/fascicle-viewer.js +4 -1
  14. package/dist/console-CdB4pcFO.js +37 -0
  15. package/dist/console-CdB4pcFO.js.map +1 -0
  16. package/dist/{core-CDrz0NM1.js → core-CErsxGF6.js} +246 -147
  17. package/dist/core-CErsxGF6.js.map +1 -0
  18. package/dist/diagram_bin.js +2 -2
  19. package/dist/diagram_bin.js.map +1 -1
  20. package/dist/{engine-BDWB2jdn.js → engine-CR8q2IqV.js} +683 -511
  21. package/dist/engine-CR8q2IqV.js.map +1 -0
  22. package/dist/index.d.ts +529 -73
  23. package/dist/index.js +440 -137
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-tjTjZLHj.js → invoke-COaeZ-vy.js} +98 -26
  26. package/dist/invoke-COaeZ-vy.js.map +1 -0
  27. package/dist/{json_schema_to_standard-r21kW2LI.js → json_schema_to_standard-C4F4lXHE.js} +11 -32
  28. package/dist/json_schema_to_standard-C4F4lXHE.js.map +1 -0
  29. package/dist/{leading_system-BQe_405V.js → leading_system-PoHzNHuV.js} +277 -3
  30. package/dist/leading_system-PoHzNHuV.js.map +1 -0
  31. package/dist/mcp.d.ts +6 -5
  32. package/dist/mcp.js +11 -6
  33. package/dist/mcp.js.map +1 -1
  34. package/dist/otel.js +10 -10
  35. package/dist/otel.js.map +1 -1
  36. package/dist/records-1HU7mWXf.js +22 -0
  37. package/dist/records-1HU7mWXf.js.map +1 -0
  38. package/dist/{search-CqH5hmuF.js → search-CpCJYMUm.js} +73 -10
  39. package/dist/search-CpCJYMUm.js.map +1 -0
  40. package/dist/search_worker.js +1 -1
  41. package/dist/stdio.js +7 -3
  42. package/dist/stdio.js.map +1 -1
  43. package/dist/testing.d.ts +1 -1
  44. package/dist/testing.js +3 -3
  45. package/dist/testing.js.map +1 -1
  46. package/dist/{trajectory-Bm-mOtqw.d.ts → trajectory-BKGNxi7u.d.ts} +10 -9
  47. package/dist/{trajectory-BI-mrVFT.js → trajectory-DeURWIhj.js} +6 -5
  48. package/dist/trajectory-DeURWIhj.js.map +1 -0
  49. package/dist/{types-C_Rmcgck.d.ts → types-Sw0oHW-_.d.ts} +47 -9
  50. package/dist/ui.d.ts +2 -1
  51. package/dist/ui.js +8 -1
  52. package/dist/ui.js.map +1 -1
  53. package/dist/viewer-app/assets/index-BYF5Dp7d.js +2 -0
  54. package/dist/viewer-app/index.html +2 -1
  55. package/dist/viewer.d.ts +26 -12
  56. package/dist/viewer.js +282 -63
  57. package/dist/viewer.js.map +1 -1
  58. package/package.json +4 -4
  59. package/dist/adapters-DNnzeLxr.js.map +0 -1
  60. package/dist/core-CDrz0NM1.js.map +0 -1
  61. package/dist/engine-BDWB2jdn.js.map +0 -1
  62. package/dist/invoke-tjTjZLHj.js.map +0 -1
  63. package/dist/json_schema_to_standard-r21kW2LI.js.map +0 -1
  64. package/dist/leading_system-BQe_405V.js.map +0 -1
  65. package/dist/search-CqH5hmuF.js.map +0 -1
  66. package/dist/trajectory-BI-mrVFT.js.map +0 -1
  67. package/dist/viewer-app/assets/index-Fnh5HKSU.js +0 -2
@@ -75,6 +75,10 @@ function line_logger(write_line) {
75
75
  * `line_logger`. Two concurrent `run(...)` calls that pass distinct logger
76
76
  * instances (constructed with distinct `output_path`s) share nothing.
77
77
  *
78
+ * Failure policy: an event that can't be serialized or appended is dropped
79
+ * and reported, through the optional `on_error` callback or else as one line
80
+ * on stderr. Never throws into the flow, the same as every adapter logger.
81
+ *
78
82
  * Paths are accepted at construction; the logger never reads `process.env`.
79
83
  */
80
84
  /**
@@ -83,11 +87,26 @@ function line_logger(write_line) {
83
87
  */
84
88
  function filesystem_logger(config) {
85
89
  const { output_path } = config;
90
+ const report = config.on_error ?? ((err) => report_to_stderr(output_path, err));
86
91
  mkdirSync(dirname(output_path), { recursive: true });
87
92
  return line_logger((event) => {
88
- appendFileSync(output_path, `${JSON.stringify(event)}\n`);
93
+ try {
94
+ appendFileSync(output_path, `${JSON.stringify(event)}\n`);
95
+ } catch (err) {
96
+ try {
97
+ report(err);
98
+ } catch {}
99
+ }
89
100
  });
90
101
  }
102
+ /**
103
+ * The default reporter: one stderr line that names the file and the reason
104
+ * an event was dropped.
105
+ */
106
+ function report_to_stderr(output_path, err) {
107
+ const reason = err instanceof Error ? err.message : String(err);
108
+ process.stderr.write(`filesystem_logger: dropped an event it could not write to ${output_path} (${reason}). Check that the path is a writable file and that every emitted value is JSON-serializable.\n`);
109
+ }
91
110
  //#endregion
92
111
  //#region src/adapters/http_logger.ts
93
112
  /**
@@ -104,7 +123,8 @@ const default_fetch = async (url, init) => {
104
123
  * Create a `TrajectoryLogger` that POSTs each event as NDJSON to
105
124
  * `config.url`.
106
125
  *
107
- * Never throws: a transport failure is dropped and reported through the
126
+ * Never throws: a transport failure, an event JSON can't serialize, and a
127
+ * custom `fetch` that throws are each dropped and reported through the
108
128
  * optional `on_error` callback, so a dev viewer being unreachable never
109
129
  * blocks the flow.
110
130
  */
@@ -112,12 +132,13 @@ function http_logger(config) {
112
132
  const { url, on_error } = config;
113
133
  const send = config.fetch ?? default_fetch;
114
134
  const post = (event) => {
115
- const body = `${JSON.stringify(event)}\n`;
116
- send(url, {
135
+ new Promise((resolve) => {
136
+ resolve(`${JSON.stringify(event)}\n`);
137
+ }).then(async (body) => send(url, {
117
138
  method: "POST",
118
139
  headers: { "content-type": "application/x-ndjson" },
119
140
  body
120
- }).then((res) => {
141
+ })).then((res) => {
121
142
  if (!res.ok && on_error) on_error(/* @__PURE__ */ new Error(`http_logger: POST ${url} -> ${res.status}`));
122
143
  }).catch((err) => {
123
144
  if (on_error) on_error(err);
@@ -131,8 +152,9 @@ function http_logger(config) {
131
152
  * No-op trajectory logger.
132
153
  *
133
154
  * Satisfies `TrajectoryLogger` from `core` without emitting any
134
- * output. Used as the default when no logger is supplied to `run(...)` and as
135
- * a cheap fallback in tests that do not care about trajectory output.
155
+ * output. A caller passes it where a logger is required and nothing should be
156
+ * recorded, such as a test that does not care about trajectory output.
157
+ * `run(...)` keeps its own private no-op for a run given no logger.
136
158
  */
137
159
  /**
138
160
  * Create a `TrajectoryLogger` whose methods do nothing.
@@ -164,7 +186,7 @@ function stderr_logger(options = {}) {
164
186
  * Create a `TrajectoryLogger` that fans every call out to `loggers`.
165
187
  */
166
188
  function tee_logger(...loggers) {
167
- if (loggers.length === 0) throw new Error("tee_logger: at least one logger required");
189
+ if (loggers.length === 0) throw new Error("tee_logger needs at least one logger: pass the sinks to fan out to, as in `tee_logger(stderr_logger(), http_logger(config))`");
168
190
  const id_map = /* @__PURE__ */ new Map();
169
191
  const safe_each = (fn) => {
170
192
  for (let i = 0; i < loggers.length; i += 1) {
@@ -180,11 +202,11 @@ function tee_logger(...loggers) {
180
202
  safe_each((l) => l.record(event));
181
203
  },
182
204
  start_span: (name, meta) => {
183
- const ids = [];
184
- safe_each((l) => {
185
- ids.push(l.start_span(name, meta));
205
+ const ids = loggers.map(() => void 0);
206
+ safe_each((l, idx) => {
207
+ ids[idx] = l.start_span(name, meta);
186
208
  });
187
- const canonical = ids[0] ?? `${name}:tee`;
209
+ const canonical = ids.find((sink_id) => sink_id !== void 0) ?? `${name}:tee`;
188
210
  if (loggers.length > 1) id_map.set(canonical, ids);
189
211
  return canonical;
190
212
  },
@@ -444,4 +466,4 @@ function filesystem_store(config) {
444
466
  //#endregion
445
467
  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 };
446
468
 
447
- //# sourceMappingURL=adapters-DNnzeLxr.js.map
469
+ //# sourceMappingURL=adapters-CDUzZlby.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapters-CDUzZlby.js","names":[],"sources":["../src/adapters/trajectory_recorder.ts","../src/adapters/line_logger.ts","../src/adapters/filesystem_logger.ts","../src/adapters/http_logger.ts","../src/adapters/noop_logger.ts","../src/adapters/stderr_logger.ts","../src/adapters/tee_logger.ts","../src/adapters/filesystem_store.ts"],"sourcesContent":["/**\n * Shared span/record core for trajectory loggers.\n *\n * Every Fascicle trajectory logger emits the same wire format (one JSON object\n * per event) and differs only in where each event goes: `line_logger` writes a\n * line, `http_logger` POSTs NDJSON. This module holds the span bookkeeping they\n * share, parameterized by a single `emit` sink.\n *\n * `start_span` and `end_span` each emit one event; `record` emits the event as\n * written. When the caller supplies `parent_span_id` in the span meta (the\n * runner threads the true structural parent through `RunContext`), that value is\n * used verbatim, so span trees are correct even for concurrent children under\n * `parallel`/`map`. Only when no parent is supplied does the recorder fall back\n * to an in-memory stack of still-open spans, which is best-effort under\n * concurrency.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Build a `TrajectoryLogger` whose events are handed, one at a time, to `emit`.\n */\nexport function trajectory_recorder(\n emit: (event: Record<string, unknown>) => void,\n): TrajectoryLogger {\n const stack: string[] = []\n\n const start_span: TrajectoryLogger['start_span'] = (name, meta) => {\n const span_id = `${name}:${randomUUID().slice(0, 8)}`\n const event: Record<string, unknown> = { kind: 'span_start', span_id, name, ...meta }\n // Prefer the caller-threaded structural parent; fall back to the open-span\n // stack only when none was supplied (best-effort under concurrency).\n if (event['parent_span_id'] === undefined && stack.length > 0) {\n event['parent_span_id'] = stack[stack.length - 1]\n }\n emit(event)\n stack.push(span_id)\n return span_id\n }\n\n const end_span: TrajectoryLogger['end_span'] = (id, meta) => {\n emit({ kind: 'span_end', span_id: id, ...meta })\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n }\n\n const record: TrajectoryLogger['record'] = (event) => {\n emit({ ...event })\n }\n\n return { record, start_span, end_span }\n}\n","/**\n * Line-oriented trajectory logger core.\n *\n * `filesystem_logger` and `stderr_logger` emit the same wire format (one JSON\n * object per line) and differ only in where the line goes. Both build on this:\n * `line_logger` adapts the shared span/record core (`trajectory_recorder`) to a\n * `write_line` sink, so the span bookkeeping and `parent_span_id` handling that\n * keep span trees correct under `parallel`/`map` live in exactly one place.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { trajectory_recorder } from './trajectory_recorder.js'\n\n/**\n * Create a `TrajectoryLogger` that writes one JSON object per line via\n * `write_line`.\n */\nexport function line_logger(write_line: (event: Record<string, unknown>) => void): TrajectoryLogger {\n return trajectory_recorder(write_line)\n}\n","/**\n * Filesystem JSONL trajectory logger.\n *\n * Appends one JSON object per line to a configured output file. Span\n * bookkeeping (including the `parent_span_id` handling that keeps span trees\n * correct for concurrent children under `parallel`/`map`) lives in\n * `line_logger`. Two concurrent `run(...)` calls that pass distinct logger\n * instances (constructed with distinct `output_path`s) share nothing.\n *\n * Failure policy: an event that can't be serialized or appended is dropped\n * and reported, through the optional `on_error` callback or else as one line\n * on stderr. Never throws into the flow, the same as every adapter logger.\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 FilesystemLoggerConfig = {\n readonly output_path: string\n /**\n * Called with the error when an event can't be serialized or appended.\n * Omitted, each failure writes one `filesystem_logger:` line to stderr.\n * Either way the event is dropped and the flow carries on.\n */\n readonly on_error?: (err: unknown) => void\n}\n\n/**\n * Create a `TrajectoryLogger` that appends one JSON object per line to\n * `output_path`, creating the parent directory if needed.\n */\nexport function filesystem_logger(config: FilesystemLoggerConfig): TrajectoryLogger {\n const { output_path } = config\n const report = config.on_error ?? ((err: unknown) => report_to_stderr(output_path, err))\n mkdirSync(dirname(output_path), { recursive: true })\n\n return line_logger((event) => {\n try {\n appendFileSync(output_path, `${JSON.stringify(event)}\\n`)\n } catch (err: unknown) {\n try {\n report(err)\n } catch {\n // A reporter that throws is dropped too: the flow always wins.\n }\n }\n })\n}\n\n/**\n * The default reporter: one stderr line that names the file and the reason\n * an event was dropped.\n */\nfunction report_to_stderr(output_path: string, err: unknown): void {\n const reason = err instanceof Error ? err.message : String(err)\n process.stderr.write(\n `filesystem_logger: dropped an event it could not write to ${output_path} (${reason}). Check that the path is a writable file and that every emitted value is JSON-serializable.\\n`,\n )\n}\n","/**\n * HTTP push trajectory logger.\n *\n * Conforms to `TrajectoryLogger`. POSTs each event as a single line of\n * newline-delimited JSON to a configured URL. Pairs naturally with the\n * Fascicle viewer's `/api/ingest` endpoint, but is a generic adapter: the\n * receiver can be anything that accepts NDJSON over HTTP.\n *\n * Failure policy: drop on transport error and invoke the optional `on_error`\n * callback. Never throws, never blocks the user's flow on a dev tool being\n * up. The flow always wins; the viewer is best-effort.\n *\n * Span bookkeeping (including the `parent_span_id` handling that mirrors\n * `filesystem_logger` so the wire format is identical) lives in the shared\n * `trajectory_recorder`; this adapter only supplies the emit sink.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { trajectory_recorder } from './trajectory_recorder.js'\n\nexport type HttpLoggerFetch = (\n url: string,\n init: { method: 'POST'; headers: Record<string, string>; body: string },\n) => Promise<{ ok: boolean; status: number }>\n\nexport type HttpLoggerConfig = {\n readonly url: string\n readonly fetch?: HttpLoggerFetch\n readonly on_error?: (err: unknown) => void\n}\n\n/**\n * Default `HttpLoggerFetch`, backed by the global `fetch`.\n */\nconst default_fetch: HttpLoggerFetch = async (url, init) => {\n const res = await fetch(url, init)\n return { ok: res.ok, status: res.status }\n}\n\n/**\n * Create a `TrajectoryLogger` that POSTs each event as NDJSON to\n * `config.url`.\n *\n * Never throws: a transport failure, an event JSON can't serialize, and a\n * custom `fetch` that throws are each dropped and reported through the\n * optional `on_error` callback, so a dev viewer being unreachable never\n * blocks the flow.\n */\nexport function http_logger(config: HttpLoggerConfig): TrajectoryLogger {\n const { url, on_error } = config\n const send = config.fetch ?? default_fetch\n\n const post = (event: Record<string, unknown>): void => {\n // The executor serializes the event as it is now, and a throw there or\n // in `send` rejects into the catch below rather than into the flow.\n void new Promise<string>((resolve) => {\n resolve(`${JSON.stringify(event)}\\n`)\n })\n .then(async (body) =>\n send(url, {\n method: 'POST',\n headers: { 'content-type': 'application/x-ndjson' },\n body,\n }),\n )\n .then((res) => {\n if (!res.ok && on_error) on_error(new Error(`http_logger: POST ${url} -> ${res.status}`))\n })\n .catch((err: unknown) => {\n if (on_error) on_error(err)\n })\n }\n\n return trajectory_recorder(post)\n}\n","/**\n * No-op trajectory logger.\n *\n * Satisfies `TrajectoryLogger` from `core` without emitting any\n * output. A caller passes it where a logger is required and nothing should be\n * recorded, such as a test that does not care about trajectory output.\n * `run(...)` keeps its own private no-op for a run given no logger.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` whose methods do nothing.\n */\nexport function noop_logger(): TrajectoryLogger {\n return {\n record: () => {},\n start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,\n end_span: () => {},\n }\n}\n","/**\n * Stderr JSONL trajectory logger.\n *\n * Writes one JSON object per line to stderr (or an injected stream), leaving\n * stdout untouched. This is the blessed console logger for agents that run as\n * somebody's child process: under the stdio agent contract, stdout carries the\n * result envelope and belongs to the parent, so trajectory must go elsewhere.\n * The wire format is identical to `filesystem_logger`, so captured stderr is a\n * valid trajectory JSONL file (`2>events.jsonl`) the viewer parses unchanged.\n *\n * Writes never throw: a broken pipe or closed stream drops the event rather\n * than failing the flow.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { line_logger } from './line_logger.js'\n\nexport type StderrLoggerOptions = {\n readonly stream?: { write(chunk: string): unknown }\n}\n\n/**\n * Create a `TrajectoryLogger` that writes one JSON object per line to\n * stderr, or to `options.stream` when supplied.\n */\nexport function stderr_logger(options: StderrLoggerOptions = {}): TrajectoryLogger {\n const stream = options.stream ?? process.stderr\n return line_logger((event) => {\n try {\n stream.write(`${JSON.stringify(event)}\\n`)\n } catch {\n // Never throw from a logger; the flow always wins.\n }\n })\n}\n","/**\n * tee_logger: fan one TrajectoryLogger contract out to many sinks.\n *\n * Each sink receives every record/start_span/end_span call. Sinks are called\n * in registration order and exceptions in one sink do not prevent the others\n * from receiving the event.\n *\n * The id from the first sink whose `start_span` returns is canonical and goes\n * back to the caller, or `<name>:tee` when every sink throws. The tee\n * remembers each sink's own id by its position, so that\n * `end_span(canonical_id, ...)` translates back to the right id for each sink,\n * and a sink that threw on `start_span` gets the canonical id. Within any one\n * sink the wire format stays internally consistent; only the across-sink ids\n * may differ.\n */\n\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` that fans every call out to `loggers`.\n */\nexport function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger {\n if (loggers.length === 0) {\n throw new Error(\n 'tee_logger needs at least one logger: pass the sinks to fan out to, as in `tee_logger(stderr_logger(), http_logger(config))`',\n )\n }\n\n const id_map = new Map<string, ReadonlyArray<string | undefined>>()\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: Array<string | undefined> = loggers.map(() => undefined)\n safe_each((l, idx) => {\n ids[idx] = l.start_span(name, meta)\n })\n const canonical = ids.find((sink_id) => sink_id !== undefined) ?? `${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`, every optional capability\n * included. Each key is stored as\n * a JSON file under the configured root directory. Writes are all-or-nothing:\n * values are written to a temporary sibling file and then atomically renamed\n * into place, so an interrupted write never leaves a partially written file\n * at the target key. On `get`, a missing file, a partial temp file that was\n * never atomically renamed, or a JSON parse failure each read as a cache\n * miss (returning `null`) rather than an error. Any other failure to read\n * (a permission error, a failing disk) surfaces, because reading it as a miss\n * could start a durable run over, or hand a live claim to a second owner.\n *\n * A scope is a directory beside the values (`<prefix>.scope/`), which makes\n * `clear` one recursive delete. A claim is a directory of numbered\n * generations (`<key>.claim/<n>.json`), and the newest one is the claim. A\n * claimer takes a free or expired key by creating the next generation with\n * `link`, which makes the file appear whole and refuses a target that\n * already exists, so two claimers can't both create it. Taking an expired\n * claim never overwrites a live one, which a rename into place couldn't\n * promise, and a claimer that finds a newer generation than its own has lost.\n * All of this leans on `link` and `rename` being atomic and on a directory\n * listing being current, which a local filesystem gives and a network\n * filesystem may not.\n *\n * Paths are accepted at construction; the store never reads `process.env`.\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { link, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nexport type FilesystemStoreConfig = {\n readonly root_dir: string\n}\n\n/**\n * What `filesystem_store` returns: a `CheckpointStore` with every optional\n * capability, which is what `durable` needs from its store.\n */\nexport type FilesystemStore = {\n readonly get: (key: string) => Promise<unknown>\n readonly set: (key: string, value: unknown) => Promise<void>\n readonly delete: (key: string) => Promise<void>\n readonly scope: (prefix: string) => FilesystemScopedStore\n readonly claim: (key: string, owner: string, ttl_ms: number) => Promise<boolean>\n readonly release: (key: string, owner: string) => Promise<void>\n}\n\n/**\n * A scope of a `filesystem_store`, which can also `clear`.\n */\nexport type FilesystemScopedStore = FilesystemStore & {\n readonly clear: () => Promise<void>\n}\n\ntype ClaimRecord = {\n readonly owner: string\n readonly expires_at: number\n}\n\n/**\n * Turn a key or a scope prefix into a filesystem-safe name.\n *\n * Slugs it down to `[a-zA-Z0-9._-]` and appends a short hash of the whole\n * string, so two strings that slug alike still land on distinct names.\n */\nfunction safe_name(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}`\n}\n\n/**\n * Read the `code` a Node filesystem error carries, if it has one.\n */\nfunction error_code(err: unknown): unknown {\n return err instanceof Error ? Reflect.get(err, 'code') : undefined\n}\n\n/**\n * Serialize a value for disk. A value JSON has no text for (`undefined`, a\n * bare function) is written as `null`, which reads back as a miss.\n */\nfunction to_json(value: unknown): string {\n const text: string | undefined = JSON.stringify(value)\n return text ?? 'null'\n}\n\n/**\n * Write `value` to `path` through a temporary sibling and a rename, so a\n * reader sees the old file or the new one and never a torn one.\n */\nasync function write_atomic(path: string, value: unknown): Promise<void> {\n // Stryker disable next-line MethodExpression: the temporary name only has to be unique, which the whole UUID is as well.\n const tmp = `${path}.${randomUUID().slice(0, 8)}.tmp`\n await writeFile(tmp, to_json(value))\n await rename(tmp, path)\n}\n\n/**\n * Create `path` holding `value` unless something is already there.\n *\n * The JSON goes to a temporary file first and is hard-linked into place, so\n * the file appears whole, and `link` refuses an existing target, so exactly\n * one of several racing creators sees true.\n */\nasync function create_exclusive(path: string, value: unknown): Promise<boolean> {\n // Stryker disable next-line MethodExpression: the temporary name only has to be unique, which the whole UUID is as well.\n const tmp = `${path}.${randomUUID().slice(0, 8)}.tmp`\n await writeFile(tmp, to_json(value))\n try {\n await link(tmp, path)\n return true\n } catch (err) {\n if (error_code(err) === 'EEXIST') return false\n throw err\n } finally {\n await rm(tmp)\n }\n}\n\n/**\n * The path of one generation in a claim directory.\n */\nfunction generation_path(dir: string, generation: number): string {\n return join(dir, `${generation}.json`)\n}\n\n/**\n * The newest generation in a claim directory, or 0 when it holds none or\n * doesn't exist yet.\n */\nasync function latest_generation(dir: string): Promise<number> {\n return Math.max(0, ...(await generations(dir)))\n}\n\n/**\n * Every generation number present in a claim directory.\n */\nasync function generations(dir: string): Promise<number[]> {\n let names: string[]\n try {\n names = await readdir(dir)\n } catch (err) {\n if (error_code(err) === 'ENOENT') return []\n throw err\n }\n return names.flatMap((name) => {\n const match = /^(\\d+)\\.json$/.exec(name)\n return match === null ? [] : [Number(match[1])]\n })\n}\n\n/**\n * Read and parse the JSON at `path`, or `null` when the file is missing or\n * doesn't parse. Any other failure surfaces.\n */\nasync function read_json(path: string): Promise<unknown> {\n let raw: string\n try {\n // Stryker disable next-line StringLiteral: without an encoding readFile hands back a Buffer, which JSON.parse turns into the same text before parsing.\n raw = await readFile(path, 'utf8')\n } catch (err) {\n if (error_code(err) === 'ENOENT') return null\n throw err\n }\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n}\n\n/**\n * Read the claim one generation holds, or null when the file is gone or\n * doesn't hold a claim.\n */\nasync function read_claim(path: string): Promise<ClaimRecord | null> {\n const parsed = await read_json(path)\n return is_claim_record(parsed) ? parsed : null\n}\n\n/**\n * True for the `{ owner, expires_at }` shape a generation file holds.\n */\nfunction is_claim_record(value: unknown): value is ClaimRecord {\n // Stryker disable next-line BooleanLiteral: a value that isn't an object reads as free either way, since null fails the null check and a primitive has no expiry to keep it live.\n if (typeof value !== 'object' || value === null) return false\n return (\n typeof Reflect.get(value, 'owner') === 'string' &&\n typeof Reflect.get(value, 'expires_at') === 'number'\n )\n}\n\n/**\n * Delete every generation older than `keep`. A claimer only reads the newest\n * generation, so the older ones are history and nothing waits on them.\n */\nasync function prune(dir: string, keep: number): Promise<void> {\n const stale = (await generations(dir)).filter((generation) => generation < keep)\n await Promise.all(stale.map((generation) => rm(generation_path(dir, generation), { force: true })))\n}\n\n/**\n * Take or renew the claim in `dir` for `owner`.\n *\n * A live claim held by `owner` is renewed in place. Anything else that isn't\n * a live claim is taken by creating the next generation, and the claimer\n * still loses if a newer generation shows up before it confirms. Only a live\n * claim is ever renewed in place, so an expired one changes hands through\n * `create_exclusive` alone and two claimers can't both win it. A renewal that\n * lands at the very instant its claim expires can still race a takeover, and\n * it loses whenever the takeover's generation appears before it confirms.\n */\nasync function claim_in(dir: string, owner: string, ttl_ms: number): Promise<boolean> {\n await mkdir(dir, { recursive: true })\n const generation = await latest_generation(dir)\n const current = await read_claim(generation_path(dir, generation))\n const now = Date.now()\n const claim: ClaimRecord = { owner, expires_at: now + ttl_ms }\n if (current !== null && current.expires_at > now) {\n if (current.owner !== owner) return false\n await write_atomic(generation_path(dir, generation), claim)\n return (await latest_generation(dir)) === generation\n }\n const next = generation + 1\n if (!(await create_exclusive(generation_path(dir, next), claim))) return false\n if ((await latest_generation(dir)) !== next) return false\n await prune(dir, next)\n return true\n}\n\n/**\n * Release the claim in `dir` when `owner` holds it.\n *\n * The newest generation is rewritten as expired rather than deleted, so\n * generation numbers only ever grow and a slow claimer can't recreate one\n * that was already taken. A directory that vanished meanwhile (its scope was\n * cleared) has nothing left to release.\n */\nasync function release_in(dir: string, owner: string): Promise<void> {\n const generation = await latest_generation(dir)\n const path = generation_path(dir, generation)\n const current = await read_claim(path)\n if (current?.owner !== owner) return\n try {\n await write_atomic(path, { owner, expires_at: 0 })\n } catch (err) {\n if (error_code(err) !== 'ENOENT') throw err\n }\n}\n\n/**\n * Build the store rooted at `root_dir`, scopes and claims included.\n */\nfunction store_at(root_dir: string): FilesystemStore {\n const value_path = (key: string): string => join(root_dir, `${safe_name(key)}.json`)\n const claim_dir = (key: string): string => join(root_dir, `${safe_name(key)}.claim`)\n\n const get = (key: string): Promise<unknown> => read_json(value_path(key))\n\n const set = async (key: string, value: unknown): Promise<void> => {\n await mkdir(root_dir, { recursive: true })\n await write_atomic(value_path(key), value)\n }\n\n const delete_key = async (key: string): Promise<void> => {\n await rm(value_path(key), { force: true })\n }\n\n const scope = (prefix: string): FilesystemScopedStore => {\n const dir = join(root_dir, `${safe_name(prefix)}.scope`)\n return {\n ...store_at(dir),\n clear: () => rm(dir, { recursive: true, force: true }),\n }\n }\n\n return {\n get,\n set,\n delete: delete_key,\n scope,\n claim: (key, owner, ttl_ms) => claim_in(claim_dir(key), owner, ttl_ms),\n release: (key, owner) => release_in(claim_dir(key), owner),\n }\n}\n\n/**\n * Create a `CheckpointStore` backed by JSON files under `config.root_dir`.\n */\nexport function filesystem_store(config: FilesystemStoreConfig): FilesystemStore {\n return store_at(config.root_dir)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,oBACd,MACkB;CAClB,MAAM,QAAkB,CAAC;CAEzB,MAAM,cAA8C,MAAM,SAAS;EACjE,MAAM,UAAU,GAAG,KAAK,GAAG,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC;EAClD,MAAM,QAAiC;GAAE,MAAM;GAAc;GAAS;GAAM,GAAG;EAAK;EAGpF,IAAI,MAAM,sBAAsB,KAAA,KAAa,MAAM,SAAS,GAC1D,MAAM,oBAAoB,MAAM,MAAM,SAAS;EAEjD,KAAK,KAAK;EACV,MAAM,KAAK,OAAO;EAClB,OAAO;CACT;CAEA,MAAM,YAA0C,IAAI,SAAS;EAC3D,KAAK;GAAE,MAAM;GAAY,SAAS;GAAI,GAAG;EAAK,CAAC;EAC/C,MAAM,MAAM,MAAM,YAAY,EAAE;EAChC,IAAI,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CACrC;CAEA,MAAM,UAAsC,UAAU;EACpD,KAAK,EAAE,GAAG,MAAM,CAAC;CACnB;CAEA,OAAO;EAAE;EAAQ;EAAY;CAAS;AACxC;;;;;;;ACnCA,SAAgB,YAAY,YAAwE;CAClG,OAAO,oBAAoB,UAAU;AACvC;;;;;;;;;;;;;;;;;;;;;;ACgBA,SAAgB,kBAAkB,QAAkD;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AEA,MAAM,SAAS,WAA0C;EACvD,MAAM,MAAM,KAAK,UAAU,GAAG,UAAU,MAAM,EAAE,OAAO;EACvD,OAAO;GACL,GAAG,SAAS,GAAG;GACf,aAAa,GAAG,KAAK;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;EACvD;CACF;CAEA,OAAO;EACL;EACA;EACA,QAAQ;EACR;EACA,QAAQ,KAAK,OAAO,WAAW,SAAS,UAAU,GAAG,GAAG,OAAO,MAAM;EACrE,UAAU,KAAK,UAAU,WAAW,UAAU,GAAG,GAAG,KAAK;CAC3D;AACF;;;;AAKA,SAAgB,iBAAiB,QAAgD;CAC/E,OAAO,SAAS,OAAO,QAAQ;AACjC"}
@@ -2,6 +2,12 @@ import { h as TrajectoryLogger } from "./types-CPqLZOEr.js";
2
2
  //#region src/adapters/filesystem_logger.d.ts
3
3
  type FilesystemLoggerConfig = {
4
4
  readonly output_path: string;
5
+ /**
6
+ * Called with the error when an event can't be serialized or appended.
7
+ * Omitted, each failure writes one `filesystem_logger:` line to stderr.
8
+ * Either way the event is dropped and the flow carries on.
9
+ */
10
+ readonly on_error?: (err: unknown) => void;
5
11
  };
6
12
  /**
7
13
  * Create a `TrajectoryLogger` that appends one JSON object per line to
@@ -27,7 +33,8 @@ type HttpLoggerConfig = {
27
33
  * Create a `TrajectoryLogger` that POSTs each event as NDJSON to
28
34
  * `config.url`.
29
35
  *
30
- * Never throws: a transport failure is dropped and reported through the
36
+ * Never throws: a transport failure, an event JSON can't serialize, and a
37
+ * custom `fetch` that throws are each dropped and reported through the
31
38
  * optional `on_error` callback, so a dev viewer being unreachable never
32
39
  * blocks the flow.
33
40
  */
package/dist/adapters.js CHANGED
@@ -1 +1 @@
1
- export { o as filesystem_logger, t as filesystem_store, a as http_logger, i as noop_logger, r as stderr_logger, n as tee_logger } from "./adapters-DNnzeLxr.js";
1
+ export { o as filesystem_logger, t as filesystem_store, a as http_logger, i as noop_logger, r as stderr_logger, n as tee_logger } from "./adapters-CDUzZlby.js";
package/dist/agents.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { c as Step } from "./types-CPqLZOEr.js";
2
2
  import { r as ToolSchema } from "./types-BK0UW28o.js";
3
- import { a as Engine, i as EffortLevel } from "./types-C_Rmcgck.js";
3
+ import { o as EffortLevel, s as Engine } from "./types-Sw0oHW-_.js";
4
4
  //#region src/agents/define_agent.d.ts
5
5
  type AgentBuiltPrompt = string | {
6
6
  readonly user: string;
package/dist/agents.js CHANGED
@@ -1,4 +1,4 @@
1
- import { S as assert_valid_step_id, k as aborted_error, x as step } from "./core-CDrz0NM1.js";
1
+ import { b as assert_valid_step_id, k as aborted_error, y as step } from "./core-CErsxGF6.js";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  //#region src/agents/define_agent.ts
@@ -11,8 +11,9 @@ import { fileURLToPath } from "node:url";
11
11
  *
12
12
  * - The markdown file is read once at factory time. Its YAML-style frontmatter
13
13
  * (`name`, `description`, `model`, `provider`, `effort`, `temperature`,
14
- * `max_tokens`, `top_p`) is parsed into the agent's step name and engine
15
- * call defaults; the body is the system prompt.
14
+ * `max_tokens`, `top_p`) is parsed into the agent's step name, its step
15
+ * description, and its engine call defaults. The rest of the file is the
16
+ * body, and `build_prompt` decides which prompt it becomes.
16
17
  * - Without `build_prompt`, the body (after `{{key}}` substitution against
17
18
  * top-level string fields of the input) is the user prompt and no system is
18
19
  * sent; the markdown carries the full instruction.
@@ -170,9 +171,9 @@ function substitute(template, input) {
170
171
  }
171
172
  /**
172
173
  * Fold the caller-shaped generation knobs onto `opts` with code config
173
- * winning over frontmatter (the precedence `model` has always used; the
174
- * engine default stays the last resort). Unset knobs leave their key off the
175
- * options object entirely rather than present-as-undefined.
174
+ * winning over frontmatter and the engine default as the last resort. Unset
175
+ * knobs leave their key off the options object entirely rather than
176
+ * present-as-undefined.
176
177
  */
177
178
  function apply_call_knobs(opts, config, frontmatter) {
178
179
  const model = config.model ?? frontmatter.model;
@@ -202,7 +203,10 @@ function define_agent(config) {
202
203
  const id = config.id ?? display_name;
203
204
  assert_valid_step_id(id, "define_agent: agent id", "pass config.id and leave the prose spelling in config.name");
204
205
  const run_agent = async (input, ctx) => {
205
- if (ctx.abort.aborted) throw new aborted_error("aborted before agent call");
206
+ if (ctx.abort.aborted) {
207
+ const reason = ctx.abort.reason;
208
+ throw reason instanceof Error ? reason : new aborted_error("aborted before agent call", { reason });
209
+ }
206
210
  let user_prompt;
207
211
  let system_prompt;
208
212
  if (config.build_prompt) {
@@ -238,7 +242,10 @@ function define_agent(config) {
238
242
  });
239
243
  return result.content;
240
244
  };
241
- return id === display_name ? step(id, run_agent) : step(id, run_agent, { name: display_name });
245
+ return step(id, run_agent, {
246
+ ...id === display_name ? {} : { name: display_name },
247
+ ...frontmatter.description === void 0 ? {} : { description: frontmatter.description }
248
+ });
242
249
  }
243
250
  //#endregion
244
251
  export { define_agent };
@@ -1 +1 @@
1
- {"version":3,"file":"agents.js","names":[],"sources":["../src/agents/define_agent.ts"],"sourcesContent":["/**\n * define_agent: markdown-driven loader for simple agents.\n *\n * Most \"agents\" in practice are a system prompt and an output schema with a\n * thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`\n * folds those into a `Step<i, o>`:\n *\n * - The markdown file is read once at factory time. Its YAML-style frontmatter\n * (`name`, `description`, `model`, `provider`, `effort`, `temperature`,\n * `max_tokens`, `top_p`) is parsed into the agent's step name and engine\n * call defaults; the body is the system prompt.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model`, `config.provider`, `config.effort`, `config.temperature`,\n * `config.max_tokens`, `config.top_p`, and `config.schema_repair_attempts`\n * shape the call from code. Code wins over frontmatter (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent id and\n * display name, resolved model id, and engine-reported usage. Identity and\n * display stay separate: `config.id` is the step id and must be\n * identifier-shaped, while `config.name` is free prose that labels the span.\n * No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature`/`max_tokens`/`top_p` coerced\n * to number, `effort` validated against the engine's levels. Anything richer\n * should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, assert_valid_step_id, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { EffortLevel, Engine, GenerateOptions } from '#engine'\nimport type { ToolSchema } from '#schema'\n\nexport type AgentBuiltPrompt =\n | string\n | { readonly user: string; readonly system?: string }\n\nexport type DefineAgentConfig<i, o> = {\n readonly md_path: string | URL\n readonly schema: ToolSchema<o>\n readonly engine: Engine\n /**\n * Display label for the agent's span, `describe` line, and `agent.call`\n * event. Free prose. Defaults to the frontmatter `name`.\n */\n readonly name?: string\n /**\n * Step id for the agent, which must be identifier-shaped. Defaults to the\n * resolved display name, so an agent whose label is already a plain\n * identifier needs nothing here; set it explicitly when the label is prose.\n */\n readonly id?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Transport for the model. Same precedence as `model`: code wins over\n * frontmatter `provider`, and the engine default is the last resort.\n */\n readonly provider?: string\n /** Reasoning effort for the call. Wins over frontmatter `effort`. */\n readonly effort?: EffortLevel\n /** Sampling temperature. Wins over frontmatter `temperature`. */\n readonly temperature?: number\n /** Output token cap. Wins over frontmatter `max_tokens`. */\n readonly max_tokens?: number\n /** Nucleus sampling cutoff. Wins over frontmatter `top_p`. */\n readonly top_p?: number\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly provider?: string\n readonly effort?: EffortLevel\n readonly temperature?: number\n readonly max_tokens?: number\n readonly top_p?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\ntype MutableFrontmatter = { -readonly [K in keyof Frontmatter]: Frontmatter[K] }\n\n/**\n * Locate the frontmatter block and split it from the body.\n *\n * Returns `null` when there is no opening `---` (the file is all body).\n * A block opened but never closed throws rather than silently producing a\n * wrong prompt.\n */\nfunction split_frontmatter(\n content: string,\n): { readonly yaml_block: string; readonly body: string } | null {\n const open_match = content.match(FRONTMATTER_OPEN)\n if (!open_match) return null\n const after_open = content.slice(open_match[0].length)\n const close_match = FRONTMATTER_CLOSE.exec(after_open)\n if (close_match?.index === undefined) {\n throw new Error('define_agent: malformed frontmatter (missing closing `---`)')\n }\n const yaml_block = after_open.slice(0, close_match.index)\n const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\\r?\\n/, '')\n return { yaml_block, body }\n}\n\n/**\n * Coerce a numeric frontmatter value to a finite number, throwing on anything\n * else. `raw` is the pre-unquote text, so the error message echoes what the\n * file held.\n */\nfunction parse_number(key: string, value: string, raw: string): number {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: ${key} must be a number, got: ${raw}`)\n }\n return n\n}\n\n// A Record keyed by EffortLevel so tsc flags this table whenever the engine's\n// union gains or loses a member; the runtime lookup then validates frontmatter.\nconst EFFORT_LEVELS: Readonly<Record<EffortLevel, true>> = {\n none: true,\n low: true,\n medium: true,\n high: true,\n xhigh: true,\n max: true,\n}\n\n/**\n * Validate an `effort` value against the engine's `EffortLevel` union,\n * throwing at factory time so a typo'd level never reaches a live call.\n */\nfunction parse_effort(value: string, raw: string): EffortLevel {\n if (!Object.hasOwn(EFFORT_LEVELS, value)) {\n throw new Error(\n `define_agent: effort must be one of ${Object.keys(EFFORT_LEVELS).join(', ')}, got: ${raw}`,\n )\n }\n // The hasOwn check above proves membership in the union.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as EffortLevel\n}\n\n/**\n * Parse one `key: value` frontmatter line into `out`. Blank and `#` comment\n * lines are skipped; a line without a colon throws; unrecognized keys are\n * ignored so only the `Frontmatter` fields reach the agent.\n */\nfunction assign_frontmatter_field(out: MutableFrontmatter, raw: string): void {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) return\n const colon_idx = line.indexOf(':')\n if (colon_idx === -1) {\n throw new Error(`define_agent: malformed frontmatter line: ${raw}`)\n }\n const key = line.slice(0, colon_idx).trim()\n const value_raw = line.slice(colon_idx + 1).trim()\n const value = unquote(value_raw)\n if (key === 'name' || key === 'description' || key === 'model' || key === 'provider') {\n out[key] = value\n return\n }\n if (key === 'temperature' || key === 'max_tokens' || key === 'top_p') {\n out[key] = parse_number(key, value, value_raw)\n return\n }\n if (key === 'effort') {\n out.effort = parse_effort(value, value_raw)\n }\n}\n\n/**\n * Split a markdown file into frontmatter fields and prompt body.\n *\n * Parses only the flat `key: value` subset of YAML that agent files need:\n * recognized keys are `name`, `description`, `model`, `provider`, `effort`\n * (validated against the engine's levels), and `temperature`/`max_tokens`/\n * `top_p` (coerced to numbers); unrecognized keys are ignored. A file without\n * an opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const split = split_frontmatter(content)\n if (split === null) return { frontmatter: {}, body: content }\n const out: MutableFrontmatter = {}\n for (const raw of split.yaml_block.split(/\\r?\\n/)) {\n assign_frontmatter_field(out, raw)\n }\n return { frontmatter: out, body: split.body }\n}\n\n/**\n * Read the markdown file from a filesystem path, `URL`, or `file://` string.\n *\n * Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`\n * or its string form without caring about the difference.\n */\nfunction read_md_sync(path: string | URL): string {\n if (path instanceof URL) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n if (path.startsWith('file://')) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Replace `{{key}}` placeholders with top-level string fields of the input.\n *\n * Non-string values and unknown keys leave the placeholder untouched, so a\n * typo'd placeholder is visible in the sent prompt instead of vanishing.\n */\nfunction substitute(template: string, input: unknown): string {\n if (input === null || typeof input !== 'object') return template\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const obj = input as Record<string, unknown>\n return template.replace(PLACEHOLDER_RE, (match, key: string) => {\n const v = obj[key]\n return typeof v === 'string' ? v : match\n })\n}\n\n/**\n * Fold the caller-shaped generation knobs onto `opts` with code config\n * winning over frontmatter (the precedence `model` has always used; the\n * engine default stays the last resort). Unset knobs leave their key off the\n * options object entirely rather than present-as-undefined.\n */\nfunction apply_call_knobs<i, o>(\n opts: GenerateOptions<o>,\n config: DefineAgentConfig<i, o>,\n frontmatter: Frontmatter,\n): void {\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n const provider = config.provider ?? frontmatter.provider\n if (provider !== undefined) opts.provider = provider\n const effort = config.effort ?? frontmatter.effort\n if (effort !== undefined) opts.effort = effort\n const temperature = config.temperature ?? frontmatter.temperature\n if (temperature !== undefined) opts.temperature = temperature\n const max_tokens = config.max_tokens ?? frontmatter.max_tokens\n if (max_tokens !== undefined) opts.max_tokens = max_tokens\n const top_p = config.top_p ?? frontmatter.top_p\n if (top_p !== undefined) opts.top_p = top_p\n}\n\n/**\n * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n const id = config.id ?? display_name\n assert_valid_step_id(\n id,\n 'define_agent: agent id',\n 'pass config.id and leave the prose spelling in config.name',\n )\n\n const run_agent = async (input: i, ctx: RunContext): Promise<o> => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before agent call')\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n apply_call_knobs(opts, config, frontmatter)\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n id,\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content\n }\n\n return id === display_name\n ? step<i, o>(id, run_agent)\n : step<i, o>(id, run_agent, { name: display_name })\n}\n"],"mappings":";;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ClB;EAEA,MAAM,OAA2B;GAC/B,QAAQ;GACR,QAAQ,OAAO;GACf,OAAO,IAAI;GACX,YAAY,IAAI;EAClB;EACA,IAAI,kBAAkB,KAAA,KAAa,kBAAkB,IACnD,KAAK,SAAS;EAEhB,iBAAiB,MAAM,QAAQ,WAAW;EAC1C,IAAI,OAAO,2BAA2B,KAAA,GACpC,KAAK,yBAAyB,OAAO;EAGvC,MAAM,SAAS,MAAM,OAAO,OAAO,SAAY,IAAI;EAEnD,MAAM,iBAAiB,GAAG,OAAO,eAAe,SAAS,GAAG,OAAO,eAAe;EAClF,IAAI,WAAW,OAAO;GACpB,MAAM;GACN;GACA,MAAM;GACN,OAAO;GACP,OAAO,OAAO;EAChB,CAAC;EAED,OAAO,OAAO;CAChB;CAEA,OAAO,OAAO,eACV,KAAW,IAAI,SAAS,IACxB,KAAW,IAAI,WAAW,EAAE,MAAM,aAAa,CAAC;AACtD"}
1
+ {"version":3,"file":"agents.js","names":[],"sources":["../src/agents/define_agent.ts"],"sourcesContent":["/**\n * define_agent: markdown-driven loader for simple agents.\n *\n * Most \"agents\" in practice are a system prompt and an output schema with a\n * thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`\n * folds those into a `Step<i, o>`:\n *\n * - The markdown file is read once at factory time. Its YAML-style frontmatter\n * (`name`, `description`, `model`, `provider`, `effort`, `temperature`,\n * `max_tokens`, `top_p`) is parsed into the agent's step name, its step\n * description, and its engine call defaults. The rest of the file is the\n * body, and `build_prompt` decides which prompt it becomes.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model`, `config.provider`, `config.effort`, `config.temperature`,\n * `config.max_tokens`, `config.top_p`, and `config.schema_repair_attempts`\n * shape the call from code. Code wins over frontmatter (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent id and\n * display name, resolved model id, and engine-reported usage. Identity and\n * display stay separate: `config.id` is the step id and must be\n * identifier-shaped, while `config.name` is free prose that labels the span.\n * No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature`/`max_tokens`/`top_p` coerced\n * to number, `effort` validated against the engine's levels. Anything richer\n * should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, assert_valid_step_id, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { EffortLevel, Engine, GenerateOptions } from '#engine'\nimport type { ToolSchema } from '#schema'\n\nexport type AgentBuiltPrompt =\n | string\n | { readonly user: string; readonly system?: string }\n\nexport type DefineAgentConfig<i, o> = {\n readonly md_path: string | URL\n readonly schema: ToolSchema<o>\n readonly engine: Engine\n /**\n * Display label for the agent's span, `describe` line, and `agent.call`\n * event. Free prose. Defaults to the frontmatter `name`.\n */\n readonly name?: string\n /**\n * Step id for the agent, which must be identifier-shaped. Defaults to the\n * resolved display name, so an agent whose label is already a plain\n * identifier needs nothing here; set it explicitly when the label is prose.\n */\n readonly id?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Transport for the model. Same precedence as `model`: code wins over\n * frontmatter `provider`, and the engine default is the last resort.\n */\n readonly provider?: string\n /** Reasoning effort for the call. Wins over frontmatter `effort`. */\n readonly effort?: EffortLevel\n /** Sampling temperature. Wins over frontmatter `temperature`. */\n readonly temperature?: number\n /** Output token cap. Wins over frontmatter `max_tokens`. */\n readonly max_tokens?: number\n /** Nucleus sampling cutoff. Wins over frontmatter `top_p`. */\n readonly top_p?: number\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly provider?: string\n readonly effort?: EffortLevel\n readonly temperature?: number\n readonly max_tokens?: number\n readonly top_p?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\ntype MutableFrontmatter = { -readonly [K in keyof Frontmatter]: Frontmatter[K] }\n\n/**\n * Locate the frontmatter block and split it from the body.\n *\n * Returns `null` when there is no opening `---` (the file is all body).\n * A block opened but never closed throws rather than silently producing a\n * wrong prompt.\n */\nfunction split_frontmatter(\n content: string,\n): { readonly yaml_block: string; readonly body: string } | null {\n const open_match = content.match(FRONTMATTER_OPEN)\n if (!open_match) return null\n const after_open = content.slice(open_match[0].length)\n const close_match = FRONTMATTER_CLOSE.exec(after_open)\n if (close_match?.index === undefined) {\n throw new Error('define_agent: malformed frontmatter (missing closing `---`)')\n }\n const yaml_block = after_open.slice(0, close_match.index)\n const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\\r?\\n/, '')\n return { yaml_block, body }\n}\n\n/**\n * Coerce a numeric frontmatter value to a finite number, throwing on anything\n * else. `raw` is the pre-unquote text, so the error message echoes what the\n * file held.\n */\nfunction parse_number(key: string, value: string, raw: string): number {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: ${key} must be a number, got: ${raw}`)\n }\n return n\n}\n\n// A Record keyed by EffortLevel so tsc flags this table whenever the engine's\n// union gains or loses a member; the runtime lookup then validates frontmatter.\nconst EFFORT_LEVELS: Readonly<Record<EffortLevel, true>> = {\n none: true,\n low: true,\n medium: true,\n high: true,\n xhigh: true,\n max: true,\n}\n\n/**\n * Validate an `effort` value against the engine's `EffortLevel` union,\n * throwing at factory time so a typo'd level never reaches a live call.\n */\nfunction parse_effort(value: string, raw: string): EffortLevel {\n if (!Object.hasOwn(EFFORT_LEVELS, value)) {\n throw new Error(\n `define_agent: effort must be one of ${Object.keys(EFFORT_LEVELS).join(', ')}, got: ${raw}`,\n )\n }\n // The hasOwn check above proves membership in the union.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as EffortLevel\n}\n\n/**\n * Parse one `key: value` frontmatter line into `out`. Blank and `#` comment\n * lines are skipped; a line without a colon throws; unrecognized keys are\n * ignored so only the `Frontmatter` fields reach the agent.\n */\nfunction assign_frontmatter_field(out: MutableFrontmatter, raw: string): void {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) return\n const colon_idx = line.indexOf(':')\n if (colon_idx === -1) {\n throw new Error(`define_agent: malformed frontmatter line: ${raw}`)\n }\n const key = line.slice(0, colon_idx).trim()\n const value_raw = line.slice(colon_idx + 1).trim()\n const value = unquote(value_raw)\n if (key === 'name' || key === 'description' || key === 'model' || key === 'provider') {\n out[key] = value\n return\n }\n if (key === 'temperature' || key === 'max_tokens' || key === 'top_p') {\n out[key] = parse_number(key, value, value_raw)\n return\n }\n if (key === 'effort') {\n out.effort = parse_effort(value, value_raw)\n }\n}\n\n/**\n * Split a markdown file into frontmatter fields and prompt body.\n *\n * Parses only the flat `key: value` subset of YAML that agent files need:\n * recognized keys are `name`, `description`, `model`, `provider`, `effort`\n * (validated against the engine's levels), and `temperature`/`max_tokens`/\n * `top_p` (coerced to numbers); unrecognized keys are ignored. A file without\n * an opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const split = split_frontmatter(content)\n if (split === null) return { frontmatter: {}, body: content }\n const out: MutableFrontmatter = {}\n for (const raw of split.yaml_block.split(/\\r?\\n/)) {\n assign_frontmatter_field(out, raw)\n }\n return { frontmatter: out, body: split.body }\n}\n\n/**\n * Read the markdown file from a filesystem path, `URL`, or `file://` string.\n *\n * Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`\n * or its string form without caring about the difference.\n */\nfunction read_md_sync(path: string | URL): string {\n if (path instanceof URL) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n if (path.startsWith('file://')) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Replace `{{key}}` placeholders with top-level string fields of the input.\n *\n * Non-string values and unknown keys leave the placeholder untouched, so a\n * typo'd placeholder is visible in the sent prompt instead of vanishing.\n */\nfunction substitute(template: string, input: unknown): string {\n if (input === null || typeof input !== 'object') return template\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const obj = input as Record<string, unknown>\n return template.replace(PLACEHOLDER_RE, (match, key: string) => {\n const v = obj[key]\n return typeof v === 'string' ? v : match\n })\n}\n\n/**\n * Fold the caller-shaped generation knobs onto `opts` with code config\n * winning over frontmatter and the engine default as the last resort. Unset\n * knobs leave their key off the options object entirely rather than\n * present-as-undefined.\n */\nfunction apply_call_knobs<i, o>(\n opts: GenerateOptions<o>,\n config: DefineAgentConfig<i, o>,\n frontmatter: Frontmatter,\n): void {\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n const provider = config.provider ?? frontmatter.provider\n if (provider !== undefined) opts.provider = provider\n const effort = config.effort ?? frontmatter.effort\n if (effort !== undefined) opts.effort = effort\n const temperature = config.temperature ?? frontmatter.temperature\n if (temperature !== undefined) opts.temperature = temperature\n const max_tokens = config.max_tokens ?? frontmatter.max_tokens\n if (max_tokens !== undefined) opts.max_tokens = max_tokens\n const top_p = config.top_p ?? frontmatter.top_p\n if (top_p !== undefined) opts.top_p = top_p\n}\n\n/**\n * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n const id = config.id ?? display_name\n assert_valid_step_id(\n id,\n 'define_agent: agent id',\n 'pass config.id and leave the prose spelling in config.name',\n )\n\n const run_agent = async (input: i, ctx: RunContext): Promise<o> => {\n // Core's throw_if_aborted contract: the caller's own Error surfaces as is,\n // and anything else rides on aborted_error as its reason.\n if (ctx.abort.aborted) {\n const reason: unknown = ctx.abort.reason\n throw reason instanceof Error ? reason : new aborted_error('aborted before agent call', { reason })\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n apply_call_knobs(opts, config, frontmatter)\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n id,\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content\n }\n\n return step<i, o>(id, run_agent, {\n ...(id === display_name ? {} : { name: display_name }),\n ...(frontmatter.description === undefined ? {} : { description: frontmatter.description }),\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;;;;AAKvB,SAAS,QAAQ,KAAqB;CACpC,IAAI,IAAI,UAAU,GAAG;EACnB,MAAM,QAAQ,IAAI;EAClB,MAAM,OAAO,IAAI,IAAI,SAAS;EAC9B,IAAK,UAAU,QAAO,SAAS,QAAS,UAAU,OAAO,SAAS,KAChE,OAAO,IAAI,MAAM,GAAG,EAAE;CAE1B;CACA,OAAO;AACT;;;;;;;;AAWA,SAAS,kBACP,SAC+D;CAC/D,MAAM,aAAa,QAAQ,MAAM,gBAAgB;CACjD,IAAI,CAAC,YAAY,OAAO;CACxB,MAAM,aAAa,QAAQ,MAAM,WAAW,EAAE,CAAC,MAAM;CACrD,MAAM,cAAc,kBAAkB,KAAK,UAAU;CACrD,IAAI,aAAa,UAAU,KAAA,GACzB,MAAM,IAAI,MAAM,6DAA6D;CAI/E,OAAO;EAAE,YAFU,WAAW,MAAM,GAAG,YAAY,KAEjC;EAAG,MADR,WAAW,MAAM,YAAY,QAAQ,YAAY,EAAE,CAAC,MAAM,CAAC,CAAC,QAAQ,UAAU,EACnE;CAAE;AAC5B;;;;;;AAOA,SAAS,aAAa,KAAa,OAAe,KAAqB;CACrE,MAAM,IAAI,OAAO,KAAK;CACtB,IAAI,CAAC,OAAO,SAAS,CAAC,GACpB,MAAM,IAAI,MAAM,iBAAiB,IAAI,0BAA0B,KAAK;CAEtE,OAAO;AACT;AAIA,MAAM,gBAAqD;CACzD,MAAM;CACN,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;AAMA,SAAS,aAAa,OAAe,KAA0B;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IAAI,OAAO,cAAc;GACvB,MAAM,QAAQ,OAAO,aAAa,KAAK;GACvC,IAAI,OAAO,UAAU,UAAU;IAC7B,cAAc;IACd,gBAAgB;GAClB,OAAO;IACL,cAAc,MAAM;IACpB,gBAAgB,MAAM,UAAU;GAClC;EACF,OAAO;GACL,cAAc,WAAW,MAAM,KAAK;GACpC,gBAAgB,KAAA;EAClB;EAEA,MAAM,OAA2B;GAC/B,QAAQ;GACR,QAAQ,OAAO;GACf,OAAO,IAAI;GACX,YAAY,IAAI;EAClB;EACA,IAAI,kBAAkB,KAAA,KAAa,kBAAkB,IACnD,KAAK,SAAS;EAEhB,iBAAiB,MAAM,QAAQ,WAAW;EAC1C,IAAI,OAAO,2BAA2B,KAAA,GACpC,KAAK,yBAAyB,OAAO;EAGvC,MAAM,SAAS,MAAM,OAAO,OAAO,SAAY,IAAI;EAEnD,MAAM,iBAAiB,GAAG,OAAO,eAAe,SAAS,GAAG,OAAO,eAAe;EAClF,IAAI,WAAW,OAAO;GACpB,MAAM;GACN;GACA,MAAM;GACN,OAAO;GACP,OAAO,OAAO;EAChB,CAAC;EAED,OAAO,OAAO;CAChB;CAEA,OAAO,KAAW,IAAI,WAAW;EAC/B,GAAI,OAAO,eAAe,CAAC,IAAI,EAAE,MAAM,aAAa;EACpD,GAAI,YAAY,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,aAAa,YAAY,YAAY;CAC1F,CAAC;AACH"}
@@ -6,4 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  const here = dirname(fileURLToPath(import.meta.url));
7
7
  const dist_viewer = resolve(here, '..', 'viewer.js');
8
8
  const mod = await import(pathToFileURL(dist_viewer).href);
9
- await mod.run_viewer_cli(process.argv.slice(2));
9
+ await mod.run_viewer_cli(process.argv.slice(2)).catch((err) => {
10
+ process.stderr.write(`fascicle-viewer: ${err instanceof Error ? err.message : String(err)}\n`);
11
+ process.exit(1);
12
+ });
@@ -0,0 +1,37 @@
1
+ import { Console } from "node:console";
2
+ //#region src/process/console.ts
3
+ /**
4
+ * console: keep a process's console off its stdout.
5
+ *
6
+ * A process whose stdout carries something a parent reads (the ACP protocol
7
+ * under `serve_acp`, the one result document under `run_stdio`) breaks when a
8
+ * flow or a dependency logs, because `console.log` writes to stdout by
9
+ * default. Routing the console's stdout methods to stderr keeps that stream
10
+ * to its one job.
11
+ */
12
+ /**
13
+ * Route `target`'s stdout methods (`log`, `info`, `debug`, `dirxml`, and
14
+ * `dir`) to stderr for as long as `target` lives.
15
+ *
16
+ * Four of them call `target.error`, which already writes to stderr. `dir`
17
+ * writes to its console's own stream rather than through `log`, so it comes
18
+ * from a console bound to `stderr`, which honors options such as `depth`.
19
+ * A write that goes straight to `process.stdout` still lands there.
20
+ */
21
+ function route_console_to_stderr(target, stderr) {
22
+ const stderr_console = new Console(stderr);
23
+ const to_stderr = target.error.bind(target);
24
+ Object.assign(target, {
25
+ log: to_stderr,
26
+ info: to_stderr,
27
+ debug: to_stderr,
28
+ dirxml: to_stderr,
29
+ dir: (item, options) => {
30
+ stderr_console.dir(item, options);
31
+ }
32
+ });
33
+ }
34
+ //#endregion
35
+ export { route_console_to_stderr as t };
36
+
37
+ //# sourceMappingURL=console-CdB4pcFO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console-CdB4pcFO.js","names":[],"sources":["../src/process/console.ts"],"sourcesContent":["/**\n * console: keep a process's console off its stdout.\n *\n * A process whose stdout carries something a parent reads (the ACP protocol\n * under `serve_acp`, the one result document under `run_stdio`) breaks when a\n * flow or a dependency logs, because `console.log` writes to stdout by\n * default. Routing the console's stdout methods to stderr keeps that stream\n * to its one job.\n */\n\nimport { Console } from 'node:console'\nimport type { InspectOptions } from 'node:util'\n\n/**\n * Route `target`'s stdout methods (`log`, `info`, `debug`, `dirxml`, and\n * `dir`) to stderr for as long as `target` lives.\n *\n * Four of them call `target.error`, which already writes to stderr. `dir`\n * writes to its console's own stream rather than through `log`, so it comes\n * from a console bound to `stderr`, which honors options such as `depth`.\n * A write that goes straight to `process.stdout` still lands there.\n */\nexport function route_console_to_stderr(target: typeof console, stderr: NodeJS.WritableStream): void {\n const stderr_console = new Console(stderr)\n const to_stderr = target.error.bind(target)\n Object.assign(target, {\n log: to_stderr,\n info: to_stderr,\n debug: to_stderr,\n dirxml: to_stderr,\n dir: (item: unknown, options?: InspectOptions) => {\n stderr_console.dir(item, options)\n },\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,wBAAwB,QAAwB,QAAqC;CACnG,MAAM,iBAAiB,IAAI,QAAQ,MAAM;CACzC,MAAM,YAAY,OAAO,MAAM,KAAK,MAAM;CAC1C,OAAO,OAAO,QAAQ;EACpB,KAAK;EACL,MAAM;EACN,OAAO;EACP,QAAQ;EACR,MAAM,MAAe,YAA6B;GAChD,eAAe,IAAI,MAAM,OAAO;EAClC;CACF,CAAC;AACH"}