fascicle 0.11.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/dist/{adapters-CJnu1687.js → adapters-hmnJOOgf.js} +30 -64
- package/dist/adapters-hmnJOOgf.js.map +1 -0
- package/dist/adapters.js +1 -1
- package/dist/agents.js +51 -29
- package/dist/agents.js.map +1 -1
- package/dist/{core-Ww6An4CS.js → core-DgH4mDbK.js} +182 -105
- package/dist/core-DgH4mDbK.js.map +1 -0
- package/dist/index.d.ts +7 -13
- package/dist/index.js +2231 -1620
- package/dist/index.js.map +1 -1
- package/dist/{invoke-CWjm1Y_R.js → invoke-BjrbCBSV.js} +101 -66
- package/dist/invoke-BjrbCBSV.js.map +1 -0
- package/dist/{types-NnSvmpjg.js → leading_system-CpkjHoCQ.js} +57 -3
- package/dist/leading_system-CpkjHoCQ.js.map +1 -0
- package/dist/mcp.js +1 -1
- package/dist/stdio.js +2 -2
- package/package.json +1 -1
- package/dist/adapters-CJnu1687.js.map +0 -1
- package/dist/core-Ww6An4CS.js.map +0 -1
- package/dist/invoke-CWjm1Y_R.js.map +0 -1
- package/dist/types-NnSvmpjg.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## v0.11.1 — 2026-08-13
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
- Broke an import cycle between the viewer CLI and its barrel module.
|
|
7
|
+
|
|
8
|
+
### Internal
|
|
9
|
+
- Reduced complexity across the engine, core, composites, and adapter layers by decomposing large functions (provider dispatch, tool-loop orchestration, generate, retry, native-provider streaming, and more) to clear the health complexity gate.
|
|
10
|
+
- Removed dead exports, types, and duplicate re-exports surfaced by dead-code analysis; extracted shared test and trajectory-logger scaffolding to cut duplication.
|
|
11
|
+
- Health's complexity metric (CRAP) now reads real test coverage instead of an estimate; closed the viewer CLI's coverage gap with new in-process tests and retired the mutation-testing excludes that existed only because those files were untested.
|
|
12
|
+
- Scoped health complexity checks to production source only, de-flaked a claude_cli timing test, and tuned fallow/lint config.
|
|
13
|
+
|
|
3
14
|
## v0.11.0 — 2026-08-12
|
|
4
15
|
|
|
5
16
|
### Changed
|
|
@@ -2,25 +2,27 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { appendFileSync, mkdirSync } from "node:fs";
|
|
5
|
-
//#region src/adapters/
|
|
5
|
+
//#region src/adapters/trajectory_recorder.ts
|
|
6
6
|
/**
|
|
7
|
-
* Shared
|
|
7
|
+
* Shared span/record core for trajectory loggers.
|
|
8
|
+
*
|
|
9
|
+
* Every fascicle trajectory logger emits the same wire format (one JSON object
|
|
10
|
+
* per event) and differs only in where each event goes: `line_logger` writes a
|
|
11
|
+
* line, `http_logger` POSTs NDJSON. This module holds the span bookkeeping they
|
|
12
|
+
* share, parameterized by a single `emit` sink.
|
|
8
13
|
*
|
|
9
|
-
* `
|
|
10
|
-
*
|
|
11
|
-
* the
|
|
12
|
-
*
|
|
13
|
-
* `
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* parent is supplied does the logger fall back to an in-memory stack of
|
|
17
|
-
* still-open spans, which is best-effort under concurrency.
|
|
14
|
+
* `start_span` and `end_span` each emit one event; `record` emits the event as
|
|
15
|
+
* written. When the caller supplies `parent_span_id` in the span meta (the
|
|
16
|
+
* runner threads the true structural parent through `RunContext`), that value is
|
|
17
|
+
* used verbatim, so span trees are correct even for concurrent children under
|
|
18
|
+
* `parallel`/`map`. Only when no parent is supplied does the recorder fall back
|
|
19
|
+
* to an in-memory stack of still-open spans, which is best-effort under
|
|
20
|
+
* concurrency.
|
|
18
21
|
*/
|
|
19
22
|
/**
|
|
20
|
-
*
|
|
21
|
-
* `write_line`.
|
|
23
|
+
* Build a `TrajectoryLogger` whose events are handed, one at a time, to `emit`.
|
|
22
24
|
*/
|
|
23
|
-
function
|
|
25
|
+
function trajectory_recorder(emit) {
|
|
24
26
|
const stack = [];
|
|
25
27
|
const start_span = (name, meta) => {
|
|
26
28
|
const span_id = `${name}:${randomUUID().slice(0, 8)}`;
|
|
@@ -31,12 +33,12 @@ function line_logger(write_line) {
|
|
|
31
33
|
...meta
|
|
32
34
|
};
|
|
33
35
|
if (event["parent_span_id"] === void 0 && stack.length > 0) event["parent_span_id"] = stack[stack.length - 1];
|
|
34
|
-
|
|
36
|
+
emit(event);
|
|
35
37
|
stack.push(span_id);
|
|
36
38
|
return span_id;
|
|
37
39
|
};
|
|
38
40
|
const end_span = (id, meta) => {
|
|
39
|
-
|
|
41
|
+
emit({
|
|
40
42
|
kind: "span_end",
|
|
41
43
|
span_id: id,
|
|
42
44
|
...meta
|
|
@@ -45,7 +47,7 @@ function line_logger(write_line) {
|
|
|
45
47
|
if (idx !== -1) stack.splice(idx, 1);
|
|
46
48
|
};
|
|
47
49
|
const record = (event) => {
|
|
48
|
-
|
|
50
|
+
emit({ ...event });
|
|
49
51
|
};
|
|
50
52
|
return {
|
|
51
53
|
record,
|
|
@@ -54,6 +56,15 @@ function line_logger(write_line) {
|
|
|
54
56
|
};
|
|
55
57
|
}
|
|
56
58
|
//#endregion
|
|
59
|
+
//#region src/adapters/line_logger.ts
|
|
60
|
+
/**
|
|
61
|
+
* Create a `TrajectoryLogger` that writes one JSON object per line via
|
|
62
|
+
* `write_line`.
|
|
63
|
+
*/
|
|
64
|
+
function line_logger(write_line) {
|
|
65
|
+
return trajectory_recorder(write_line);
|
|
66
|
+
}
|
|
67
|
+
//#endregion
|
|
57
68
|
//#region src/adapters/filesystem_logger.ts
|
|
58
69
|
/**
|
|
59
70
|
* Filesystem JSONL trajectory logger.
|
|
@@ -80,21 +91,6 @@ function filesystem_logger(options) {
|
|
|
80
91
|
//#endregion
|
|
81
92
|
//#region src/adapters/http_logger.ts
|
|
82
93
|
/**
|
|
83
|
-
* HTTP push trajectory logger.
|
|
84
|
-
*
|
|
85
|
-
* Conforms to `TrajectoryLogger`. POSTs each event as a single line of
|
|
86
|
-
* newline-delimited JSON to a configured URL. Pairs naturally with the
|
|
87
|
-
* fascicle viewer's `/api/ingest` endpoint, but is a generic adapter: the
|
|
88
|
-
* receiver can be anything that accepts NDJSON over HTTP.
|
|
89
|
-
*
|
|
90
|
-
* Failure policy: drop on transport error and invoke the optional `on_error`
|
|
91
|
-
* callback. Never throws, never blocks the user's flow on a dev tool being
|
|
92
|
-
* up. The flow always wins; the viewer is best-effort.
|
|
93
|
-
*
|
|
94
|
-
* Hierarchical span ids are tracked in-process, mirroring `filesystem_logger`
|
|
95
|
-
* so the wire format is identical.
|
|
96
|
-
*/
|
|
97
|
-
/**
|
|
98
94
|
* Default `HttpLoggerFetch`, backed by the global `fetch`.
|
|
99
95
|
*/
|
|
100
96
|
const default_fetch = async (url, init) => {
|
|
@@ -115,7 +111,6 @@ const default_fetch = async (url, init) => {
|
|
|
115
111
|
function http_logger(options) {
|
|
116
112
|
const { url, on_error } = options;
|
|
117
113
|
const send = options.fetch ?? default_fetch;
|
|
118
|
-
const stack = [];
|
|
119
114
|
const post = (event) => {
|
|
120
115
|
const body = `${JSON.stringify(event)}\n`;
|
|
121
116
|
send(url, {
|
|
@@ -128,36 +123,7 @@ function http_logger(options) {
|
|
|
128
123
|
if (on_error) on_error(err);
|
|
129
124
|
});
|
|
130
125
|
};
|
|
131
|
-
|
|
132
|
-
const span_id = `${name}:${randomUUID().slice(0, 8)}`;
|
|
133
|
-
const event = {
|
|
134
|
-
kind: "span_start",
|
|
135
|
-
span_id,
|
|
136
|
-
name,
|
|
137
|
-
...meta
|
|
138
|
-
};
|
|
139
|
-
if (event["parent_span_id"] === void 0 && stack.length > 0) event["parent_span_id"] = stack[stack.length - 1];
|
|
140
|
-
post(event);
|
|
141
|
-
stack.push(span_id);
|
|
142
|
-
return span_id;
|
|
143
|
-
};
|
|
144
|
-
const end_span = (id, meta) => {
|
|
145
|
-
post({
|
|
146
|
-
kind: "span_end",
|
|
147
|
-
span_id: id,
|
|
148
|
-
...meta
|
|
149
|
-
});
|
|
150
|
-
const idx = stack.lastIndexOf(id);
|
|
151
|
-
if (idx !== -1) stack.splice(idx, 1);
|
|
152
|
-
};
|
|
153
|
-
const record = (event) => {
|
|
154
|
-
post({ ...event });
|
|
155
|
-
};
|
|
156
|
-
return {
|
|
157
|
-
record,
|
|
158
|
-
start_span,
|
|
159
|
-
end_span
|
|
160
|
-
};
|
|
126
|
+
return trajectory_recorder(post);
|
|
161
127
|
}
|
|
162
128
|
//#endregion
|
|
163
129
|
//#region src/adapters/noop_logger.ts
|
|
@@ -301,4 +267,4 @@ function filesystem_store(options) {
|
|
|
301
267
|
//#endregion
|
|
302
268
|
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 };
|
|
303
269
|
|
|
304
|
-
//# sourceMappingURL=adapters-
|
|
270
|
+
//# sourceMappingURL=adapters-hmnJOOgf.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapters-hmnJOOgf.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 * Paths are accepted at construction; the logger never reads `process.env`.\n */\n\nimport { appendFileSync, mkdirSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { TrajectoryLogger } from '#core'\nimport { line_logger } from './line_logger.js'\n\nexport type FilesystemLoggerOptions = {\n readonly output_path: string\n}\n\n/**\n * Create a `TrajectoryLogger` that appends one JSON object per line to\n * `output_path`, creating the parent directory if needed.\n */\nexport function filesystem_logger(options: FilesystemLoggerOptions): TrajectoryLogger {\n const { output_path } = options\n mkdirSync(dirname(output_path), { recursive: true })\n\n return line_logger((event) => {\n appendFileSync(output_path, `${JSON.stringify(event)}\\n`)\n })\n}\n","/**\n * HTTP push trajectory logger.\n *\n * Conforms to `TrajectoryLogger`. POSTs each event as a single line of\n * newline-delimited JSON to a configured URL. Pairs naturally with the\n * fascicle viewer's `/api/ingest` endpoint, but is a generic adapter: the\n * receiver can be anything that accepts NDJSON over HTTP.\n *\n * Failure policy: drop on transport error and invoke the optional `on_error`\n * callback. Never throws, never blocks the user's flow on a dev tool being\n * up. The flow always wins; the viewer is best-effort.\n *\n * 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 HttpLoggerOptions = {\n readonly url: string\n readonly fetch?: HttpLoggerFetch\n readonly on_error?: (err: unknown) => void\n}\n\n/**\n * Default `HttpLoggerFetch`, backed by the global `fetch`.\n */\nconst default_fetch: HttpLoggerFetch = async (url, init) => {\n const res = await fetch(url, init)\n return { ok: res.ok, status: res.status }\n}\n\n/**\n * Create a `TrajectoryLogger` that POSTs each event as NDJSON to\n * `options.url`.\n *\n * Never throws: a transport failure is dropped and reported through the\n * optional `on_error` callback, so a dev viewer being unreachable never\n * blocks the flow.\n */\nexport function http_logger(options: HttpLoggerOptions): TrajectoryLogger {\n const { url, on_error } = options\n const send = options.fetch ?? default_fetch\n\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 return trajectory_recorder(post)\n}\n","/**\n * No-op trajectory logger.\n *\n * Satisfies `TrajectoryLogger` from `core` without emitting any\n * output. Used as the default when no logger is supplied to `run(...)` and as\n * a cheap fallback in tests that do not care about trajectory output.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` whose methods do nothing.\n */\nexport function noop_logger(): TrajectoryLogger {\n return {\n record: () => {},\n start_span: (name) => `${name}:${randomUUID().slice(0, 8)}`,\n end_span: () => {},\n }\n}\n","/**\n * Stderr JSONL trajectory logger.\n *\n * Writes one JSON object per line to stderr (or an injected stream), leaving\n * stdout untouched. This is the blessed console logger for agents that run as\n * somebody's child process: under the stdio agent contract, stdout carries the\n * result envelope and belongs to the parent, so trajectory must go elsewhere.\n * The wire format is identical to `filesystem_logger`, so captured stderr is a\n * valid trajectory JSONL file (`2>events.jsonl`) the viewer parses unchanged.\n *\n * Writes never throw: a broken pipe or closed stream drops the event rather\n * than failing the flow.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport { line_logger } from './line_logger.js'\n\nexport type StderrLoggerOptions = {\n readonly stream?: { write(chunk: string): unknown }\n}\n\n/**\n * Create a `TrajectoryLogger` that writes one JSON object per line to\n * stderr, or to `options.stream` when supplied.\n */\nexport function stderr_logger(options: StderrLoggerOptions = {}): TrajectoryLogger {\n const stream = options.stream ?? process.stderr\n return line_logger((event) => {\n try {\n stream.write(`${JSON.stringify(event)}\\n`)\n } catch {\n // Never throw from a logger; the flow always wins.\n }\n })\n}\n","/**\n * tee_logger: fan one TrajectoryLogger contract out to many sinks.\n *\n * Each sink receives every record/start_span/end_span call. Sinks are called\n * in registration order and exceptions in one sink do not prevent the others\n * from receiving the event.\n *\n * The first sink's `start_span` return value is treated as canonical and\n * returned to the caller; the tee remembers each sink's per-sink id so that\n * `end_span(canonical_id, ...)` translates back to the right id for each sink.\n * Within any one sink the wire format stays internally consistent; only the\n * across-sink ids may differ.\n */\n\nimport type { TrajectoryLogger } from '#core'\n\n/**\n * Create a `TrajectoryLogger` that fans every call out to `loggers`.\n */\nexport function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger {\n if (loggers.length === 0) {\n throw new Error('tee_logger: at least one logger required')\n }\n\n const id_map = new Map<string, ReadonlyArray<string>>()\n\n const safe_each = (fn: (l: TrajectoryLogger, idx: number) => void): void => {\n for (let i = 0; i < loggers.length; i += 1) {\n const l = loggers[i]\n if (l === undefined) continue\n try {\n fn(l, i)\n } catch {\n // best-effort fan-out: a misbehaving sink must not derail the others\n }\n }\n }\n\n return {\n record: (event) => {\n safe_each((l) => l.record(event))\n },\n start_span: (name, meta) => {\n const ids: string[] = []\n safe_each((l) => {\n ids.push(l.start_span(name, meta))\n })\n const canonical = ids[0] ?? `${name}:tee`\n if (loggers.length > 1) id_map.set(canonical, ids)\n return canonical\n },\n end_span: (id, meta) => {\n const ids = id_map.get(id)\n if (ids === undefined) {\n safe_each((l) => l.end_span(id, meta))\n return\n }\n id_map.delete(id)\n safe_each((l, idx) => l.end_span(ids[idx] ?? id, meta))\n },\n }\n}\n","/**\n * Filesystem-backed checkpoint store.\n *\n * Satisfies `CheckpointStore` from `core`. Each key is stored as\n * a JSON file under the configured root directory. Writes are all-or-nothing:\n * values are written to a temporary sibling file and then atomically renamed\n * into place, so an interrupted write never leaves a partially-written file\n * at the target key. On `get`, a missing file, a partial temp file that was\n * never atomically renamed, or a JSON parse failure each read as a cache\n * miss (returning `null`) rather than an error.\n *\n * Paths are accepted at construction; the store never reads `process.env`.\n */\n\nimport { createHash, randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { CheckpointStore } from '#core'\n\nexport type FilesystemStoreOptions = {\n readonly root_dir: string\n}\n\n/**\n * Turn a checkpoint key into a filesystem-safe filename.\n *\n * Slugs the key down to `[a-zA-Z0-9._-]` and appends a short hash of the\n * full key, so two keys that slug to the same string still land on distinct\n * files.\n */\nfunction safe_filename(key: string): string {\n const hash = createHash('sha256').update(key).digest('hex').slice(0, 12)\n const slug = key.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64)\n return `${slug}.${hash}.json`\n}\n\n/**\n * Create a `CheckpointStore` backed by JSON files under `options.root_dir`.\n */\nexport function filesystem_store(options: FilesystemStoreOptions): CheckpointStore {\n const { root_dir } = options\n\n const ensure_root = async (): Promise<void> => {\n await mkdir(root_dir, { recursive: true })\n }\n\n const path_for = (key: string): string => join(root_dir, safe_filename(key))\n\n const get = async (key: string): Promise<unknown> => {\n const path = path_for(key)\n let raw: string\n try {\n raw = await readFile(path, 'utf8')\n } catch {\n return null\n }\n try {\n return JSON.parse(raw) as unknown\n } catch {\n return null\n }\n }\n\n const set = async (key: string, value: unknown): Promise<void> => {\n await ensure_root()\n const target = path_for(key)\n const tmp = `${target}.${randomUUID().slice(0, 8)}.tmp`\n await writeFile(tmp, JSON.stringify(value), 'utf8')\n await rename(tmp, target)\n }\n\n const delete_key = async (key: string): Promise<void> => {\n const target = path_for(key)\n await rm(target, { force: true })\n }\n\n return { get, set, delete: delete_key }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,oBACd,MACkB;CAClB,MAAM,QAAkB,CAAC;CAEzB,MAAM,cAA8C,MAAM,SAAS;EACjE,MAAM,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;EAClD,MAAM,OAAO,KAAK,MAAM;CAC1B;CAEA,MAAM,aAAa,OAAO,QAA+B;EAEvD,MAAM,GADS,SAAS,GACV,GAAG,EAAE,OAAO,KAAK,CAAC;CAClC;CAEA,OAAO;EAAE;EAAK;EAAK,QAAQ;CAAW;AACxC"}
|
package/dist/adapters.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as http_logger, i as noop_logger, n as tee_logger, o as filesystem_logger, r as stderr_logger, t as filesystem_store } from "./adapters-
|
|
1
|
+
import { a as http_logger, i as noop_logger, n as tee_logger, o as filesystem_logger, r as stderr_logger, t as filesystem_store } from "./adapters-hmnJOOgf.js";
|
|
2
2
|
export { filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
|
package/dist/agents.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { A as aborted_error, O as step } from "./core-
|
|
1
|
+
import { A as aborted_error, O as step } from "./core-DgH4mDbK.js";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
//#region src/agents/define_agent.ts
|
|
@@ -48,6 +48,52 @@ function unquote(raw) {
|
|
|
48
48
|
return raw;
|
|
49
49
|
}
|
|
50
50
|
/**
|
|
51
|
+
* Locate the frontmatter block and split it from the body.
|
|
52
|
+
*
|
|
53
|
+
* Returns `null` when there is no opening `---` (the file is all body).
|
|
54
|
+
* A block opened but never closed throws rather than silently producing a
|
|
55
|
+
* wrong prompt.
|
|
56
|
+
*/
|
|
57
|
+
function split_frontmatter(content) {
|
|
58
|
+
const open_match = content.match(FRONTMATTER_OPEN);
|
|
59
|
+
if (!open_match) return null;
|
|
60
|
+
const after_open = content.slice(open_match[0].length);
|
|
61
|
+
const close_match = FRONTMATTER_CLOSE.exec(after_open);
|
|
62
|
+
if (close_match?.index === void 0) throw new Error("define_agent: malformed frontmatter (missing closing `---`)");
|
|
63
|
+
return {
|
|
64
|
+
yaml_block: after_open.slice(0, close_match.index),
|
|
65
|
+
body: after_open.slice(close_match.index + close_match[0].length).replace(/^\r?\n/, "")
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Coerce a `temperature` value to a finite number, throwing on anything else.
|
|
70
|
+
* `raw` is the pre-unquote text, so the error message echoes what the file held.
|
|
71
|
+
*/
|
|
72
|
+
function parse_temperature(value, raw) {
|
|
73
|
+
const n = Number(value);
|
|
74
|
+
if (!Number.isFinite(n)) throw new Error(`define_agent: temperature must be a number, got: ${raw}`);
|
|
75
|
+
return n;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Parse one `key: value` frontmatter line into `out`. Blank and `#` comment
|
|
79
|
+
* lines are skipped; a line without a colon throws; unrecognized keys are
|
|
80
|
+
* ignored so only `name`/`description`/`model`/`temperature` reach the agent.
|
|
81
|
+
*/
|
|
82
|
+
function assign_frontmatter_field(out, raw) {
|
|
83
|
+
const line = raw.trim();
|
|
84
|
+
if (line === "" || line.startsWith("#")) return;
|
|
85
|
+
const colon_idx = line.indexOf(":");
|
|
86
|
+
if (colon_idx === -1) throw new Error(`define_agent: malformed frontmatter line: ${raw}`);
|
|
87
|
+
const key = line.slice(0, colon_idx).trim();
|
|
88
|
+
const value_raw = line.slice(colon_idx + 1).trim();
|
|
89
|
+
const value = unquote(value_raw);
|
|
90
|
+
if (key === "name" || key === "description" || key === "model") {
|
|
91
|
+
out[key] = value;
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (key === "temperature") out.temperature = parse_temperature(value, value_raw);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
51
97
|
* Split a markdown file into frontmatter fields and prompt body.
|
|
52
98
|
*
|
|
53
99
|
* Parses only the flat `key: value` subset of YAML that agent files need:
|
|
@@ -57,40 +103,16 @@ function unquote(raw) {
|
|
|
57
103
|
* silently producing a wrong prompt.
|
|
58
104
|
*/
|
|
59
105
|
function parse_frontmatter(content) {
|
|
60
|
-
const
|
|
61
|
-
if (
|
|
106
|
+
const split = split_frontmatter(content);
|
|
107
|
+
if (split === null) return {
|
|
62
108
|
frontmatter: {},
|
|
63
109
|
body: content
|
|
64
110
|
};
|
|
65
|
-
const after_open = content.slice(open_match[0].length);
|
|
66
|
-
const close_match = FRONTMATTER_CLOSE.exec(after_open);
|
|
67
|
-
if (close_match?.index === void 0) throw new Error("define_agent: malformed frontmatter (missing closing `---`)");
|
|
68
|
-
const yaml_block = after_open.slice(0, close_match.index);
|
|
69
|
-
const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\r?\n/, "");
|
|
70
111
|
const out = {};
|
|
71
|
-
const
|
|
72
|
-
for (const raw of lines) {
|
|
73
|
-
const line = raw.trim();
|
|
74
|
-
if (line === "" || line.startsWith("#")) continue;
|
|
75
|
-
const colon_idx = line.indexOf(":");
|
|
76
|
-
if (colon_idx === -1) throw new Error(`define_agent: malformed frontmatter line: ${raw}`);
|
|
77
|
-
const key = line.slice(0, colon_idx).trim();
|
|
78
|
-
const value_raw = line.slice(colon_idx + 1).trim();
|
|
79
|
-
const value = unquote(value_raw);
|
|
80
|
-
if (key === "name" || key === "description" || key === "model") {
|
|
81
|
-
out[key] = value;
|
|
82
|
-
continue;
|
|
83
|
-
}
|
|
84
|
-
if (key === "temperature") {
|
|
85
|
-
const n = Number(value);
|
|
86
|
-
if (!Number.isFinite(n)) throw new Error(`define_agent: temperature must be a number, got: ${value_raw}`);
|
|
87
|
-
out.temperature = n;
|
|
88
|
-
continue;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
112
|
+
for (const raw of split.yaml_block.split(/\r?\n/)) assign_frontmatter_field(out, raw);
|
|
91
113
|
return {
|
|
92
114
|
frontmatter: out,
|
|
93
|
-
body
|
|
115
|
+
body: split.body
|
|
94
116
|
};
|
|
95
117
|
}
|
|
96
118
|
/**
|
package/dist/agents.js.map
CHANGED
|
@@ -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`, `temperature`) is parsed into the agent's\n * step name and engine call defaults; the body is the system prompt.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model` and `config.schema_repair_attempts` shape the call from\n * code. An explicit `model` wins over frontmatter `model` (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent name,\n * resolved model id, and engine-reported usage. No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature` coerced to number. Anything\n * richer should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { Engine, GenerateOptions } from '#engine'\nimport type { 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 readonly name?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly temperature?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\n/**\n * Split a markdown file into frontmatter fields and prompt body.\n *\n * Parses only the flat `key: value` subset of YAML that agent files need:\n * recognized keys are `name`, `description`, `model`, and `temperature`\n * (coerced to a number); unrecognized keys are ignored. A file without an\n * opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const open_match = content.match(FRONTMATTER_OPEN)\n if (!open_match) return { frontmatter: {}, body: content }\n const after_open = content.slice(open_match[0].length)\n const close_match = FRONTMATTER_CLOSE.exec(after_open)\n if (close_match?.index === undefined) {\n throw new Error('define_agent: malformed frontmatter (missing closing `---`)')\n }\n const yaml_block = after_open.slice(0, close_match.index)\n const body = after_open.slice(close_match.index + close_match[0].length).replace(/^\\r?\\n/, '')\n\n const out: { -readonly [K in keyof Frontmatter]: Frontmatter[K] } = {}\n const lines = yaml_block.split(/\\r?\\n/)\n for (const raw of lines) {\n const line = raw.trim()\n if (line === '' || line.startsWith('#')) continue\n const colon_idx = line.indexOf(':')\n if (colon_idx === -1) {\n throw new Error(`define_agent: malformed frontmatter line: ${raw}`)\n }\n const key = line.slice(0, colon_idx).trim()\n const value_raw = line.slice(colon_idx + 1).trim()\n const value = unquote(value_raw)\n if (key === 'name' || key === 'description' || key === 'model') {\n out[key] = value\n continue\n }\n if (key === 'temperature') {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: temperature must be a number, got: ${value_raw}`)\n }\n out.temperature = n\n continue\n }\n }\n return { frontmatter: out, body }\n}\n\n/**\n * Read the markdown file from a filesystem path, `URL`, or `file://` string.\n *\n * Accepting all three lets callers pass `new URL('./x.md', import.meta.url)`\n * or its string form without caring about the difference.\n */\nfunction read_md_sync(path: string | URL): string {\n if (path instanceof URL) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n if (path.startsWith('file://')) {\n return readFileSync(fileURLToPath(path), 'utf8')\n }\n return readFileSync(path, 'utf8')\n}\n\n/**\n * Replace `{{key}}` placeholders with top-level string fields of the input.\n *\n * Non-string values and unknown keys leave the placeholder untouched, so a\n * typo'd placeholder is visible in the sent prompt instead of vanishing.\n */\nfunction substitute(template: string, input: unknown): string {\n if (input === null || typeof input !== 'object') return template\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const obj = input as Record<string, unknown>\n return template.replace(PLACEHOLDER_RE, (match, key: string) => {\n const v = obj[key]\n return typeof v === 'string' ? v : match\n })\n}\n\n/**\n * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n\n return step<i, o>(display_name, async (input, ctx: RunContext): Promise<o> => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before agent call')\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n if (frontmatter.temperature !== undefined) opts.temperature = frontmatter.temperature\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;;;;AAKvB,SAAS,QAAQ,KAAqB;CACpC,IAAI,IAAI,UAAU,GAAG;EACnB,MAAM,QAAQ,IAAI;EAClB,MAAM,OAAO,IAAI,IAAI,SAAS;EAC9B,IAAK,UAAU,QAAO,SAAS,QAAS,UAAU,OAAO,SAAS,KAChE,OAAO,IAAI,MAAM,GAAG,EAAE;CAE1B;CACA,OAAO;AACT;;;;;;;;;;AAWA,SAAS,kBAAkB,SAA+B;CACxD,MAAM,aAAa,QAAQ,MAAM,gBAAgB;CACjD,IAAI,CAAC,YAAY,OAAO;EAAE,aAAa,CAAC;EAAG,MAAM;CAAQ;CACzD,MAAM,aAAa,QAAQ,MAAM,WAAW,EAAE,CAAC,MAAM;CACrD,MAAM,cAAc,kBAAkB,KAAK,UAAU;CACrD,IAAI,aAAa,UAAU,KAAA,GACzB,MAAM,IAAI,MAAM,6DAA6D;C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ent":["/**\n * define_agent: markdown-driven loader for simple agents.\n *\n * Most \"agents\" in practice are a system prompt and an output schema with a\n * thin wrapper. `define_agent({ md_path, schema, engine, build_prompt? })`\n * folds those into a `Step<i, o>`:\n *\n * - The markdown file is read once at factory time. Its YAML-style frontmatter\n * (`name`, `description`, `model`, `temperature`) is parsed into the agent's\n * step name and engine call defaults; the body is the system prompt.\n * - Without `build_prompt`, the body (after `{{key}}` substitution against\n * top-level string fields of the input) is the user prompt and no system is\n * sent; the markdown carries the full instruction.\n * - With `build_prompt`, the body is the system prompt and `build_prompt(input)`\n * produces the user message (string, or `{ user, system? }` to override).\n * - `config.model` and `config.schema_repair_attempts` shape the call from\n * code. An explicit `model` wins over frontmatter `model` (frontmatter stays\n * the role default when the app threads nothing; the engine default is the\n * last resort), so a resolved role-to-model table and env overrides actually\n * reach the call.\n *\n * The factory keeps no engine state. Each call delegates to `engine.generate`\n * with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`\n * threaded through. An `agent.call` trajectory event carries the agent name,\n * resolved model id, and engine-reported usage. No retry or fallback is baked\n * in; wrap with `retry()` from core if you need it.\n *\n * Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`\n * lines, optional `'`/`\"` quotes, `temperature` coerced to number. Anything\n * richer should go through `build_prompt`.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { fileURLToPath } from 'node:url'\nimport { aborted_error, step } from '#core'\nimport type { RunContext, Step } from '#core'\nimport type { Engine, GenerateOptions } from '#engine'\nimport type { 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 readonly name?: string\n readonly build_prompt?: (input: i) => AgentBuiltPrompt\n /**\n * Model for this agent's calls, typically threaded from the app's resolved\n * role-to-model table. Wins over frontmatter `model`; when both are absent\n * the engine default applies.\n */\n readonly model?: string\n /**\n * Forwarded to `engine.generate`: how many times the engine may re-prompt\n * the model to repair schema-invalid output before failing the call.\n */\n readonly schema_repair_attempts?: number\n}\n\ntype Frontmatter = {\n readonly name?: string\n readonly description?: string\n readonly model?: string\n readonly temperature?: number\n}\n\ntype ParsedPrompt = {\n readonly frontmatter: Frontmatter\n readonly body: string\n}\n\nconst FRONTMATTER_OPEN = /^---\\s*\\r?\\n/\nconst FRONTMATTER_CLOSE = /^---\\s*$/m\nconst PLACEHOLDER_RE = /\\{\\{(\\w+)\\}\\}/g\n\n/**\n * Strip one matching pair of surrounding single or double quotes.\n */\nfunction unquote(raw: string): string {\n if (raw.length >= 2) {\n const first = raw[0]\n const last = raw[raw.length - 1]\n if ((first === '\"' && last === '\"') || (first === \"'\" && last === \"'\")) {\n return raw.slice(1, -1)\n }\n }\n return raw\n}\n\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 `temperature` value to a finite number, throwing on anything else.\n * `raw` is the pre-unquote text, so the error message echoes what the file held.\n */\nfunction parse_temperature(value: string, raw: string): number {\n const n = Number(value)\n if (!Number.isFinite(n)) {\n throw new Error(`define_agent: temperature must be a number, got: ${raw}`)\n }\n return n\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 `name`/`description`/`model`/`temperature` 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') {\n out[key] = value\n return\n }\n if (key === 'temperature') {\n out.temperature = parse_temperature(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`, and `temperature`\n * (coerced to a number); unrecognized keys are ignored. A file without an\n * opening `---` is all body. Malformed frontmatter throws rather than\n * silently producing a wrong prompt.\n */\nfunction parse_frontmatter(content: string): ParsedPrompt {\n const 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 * Load a markdown-defined agent as a `Step<i, o>`.\n *\n * Reads and parses the file once at factory time; each run resolves the\n * user/system prompts (via `build_prompt` or `{{key}}` substitution), calls\n * `engine.generate` with the schema and threaded abort/trajectory, and\n * records an `agent.call` event with the resolved model and usage.\n */\nexport function define_agent<i, o>(config: DefineAgentConfig<i, o>): Step<i, o> {\n const text = read_md_sync(config.md_path)\n const { frontmatter, body } = parse_frontmatter(text)\n\n const display_name = config.name ?? frontmatter.name ?? 'agent'\n\n return step<i, o>(display_name, async (input, ctx: RunContext): Promise<o> => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before agent call')\n }\n \n let user_prompt: string\n let system_prompt: string | undefined\n if (config.build_prompt) {\n const built = config.build_prompt(input)\n if (typeof built === 'string') {\n user_prompt = built\n system_prompt = body\n } else {\n user_prompt = built.user\n system_prompt = built.system ?? body\n }\n } else {\n user_prompt = substitute(body, input)\n system_prompt = undefined\n }\n \n const opts: GenerateOptions<o> = {\n prompt: user_prompt,\n schema: config.schema,\n abort: ctx.abort,\n trajectory: ctx.trajectory,\n }\n if (system_prompt !== undefined && system_prompt !== '') {\n opts.system = system_prompt\n }\n const model = config.model ?? frontmatter.model\n if (model !== undefined) opts.model = model\n if (frontmatter.temperature !== undefined) opts.temperature = frontmatter.temperature\n if (config.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = config.schema_repair_attempts\n }\n \n const result = await config.engine.generate<o>(opts)\n \n const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`\n ctx.trajectory.record({\n kind: 'agent.call',\n name: display_name,\n model: resolved_model,\n usage: result.usage,\n })\n \n return result.content\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,mBAAmB;AACzB,MAAM,oBAAoB;AAC1B,MAAM,iBAAiB;;;;AAKvB,SAA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