fascicle 0.12.0 → 0.12.3
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 +148 -32
- package/README.md +25 -15
- package/dist/{adapters-hmnJOOgf.js → adapters-CutexJd3.js} +12 -12
- package/dist/adapters-CutexJd3.js.map +1 -0
- package/dist/adapters.d.ts +10 -10
- package/dist/adapters.js +1 -1
- package/dist/agents.d.ts +22 -3
- package/dist/agents.js +74 -24
- package/dist/agents.js.map +1 -1
- package/dist/bin/fascicle-viewer.js +2 -2
- package/dist/{core-BkB2l1-e.js → core-DdJEhyQc.js} +314 -501
- package/dist/core-DdJEhyQc.js.map +1 -0
- package/dist/engine-J4lIxpw5.js +7000 -0
- package/dist/engine-J4lIxpw5.js.map +1 -0
- package/dist/index.d.ts +237 -178
- package/dist/index.js +617 -7771
- package/dist/index.js.map +1 -1
- package/dist/{invoke-JkzNf7-Y.js → invoke-CH_eJZeS.js} +8 -8
- package/dist/{invoke-JkzNf7-Y.js.map → invoke-CH_eJZeS.js.map} +1 -1
- package/dist/{leading_system-BVtGMweY.js → leading_system-BUCT-PwD.js} +31 -8
- package/dist/leading_system-BUCT-PwD.js.map +1 -0
- package/dist/mcp.d.ts +5 -5
- package/dist/mcp.js +10 -9
- package/dist/mcp.js.map +1 -1
- package/dist/otel.d.ts +1 -1
- package/dist/otel.js +4 -4
- package/dist/otel.js.map +1 -1
- package/dist/static/viewer.html +2 -1
- package/dist/stdio.d.ts +2 -2
- package/dist/stdio.js +2 -2
- package/dist/testing.d.ts +66 -15
- package/dist/testing.js +200 -34
- package/dist/testing.js.map +1 -1
- package/dist/trajectory-ByoOQZ6T.d.ts +114 -0
- package/dist/trajectory-D1eq9eue.js +81 -0
- package/dist/trajectory-D1eq9eue.js.map +1 -0
- package/dist/{types-BCtKsxrX.d.ts → types-BK0UW28o.d.ts} +3 -3
- package/dist/{types-CVdTBXE_.d.ts → types-DBpU27sQ.d.ts} +20 -3
- package/dist/{types-4l54cexm.d.ts → types-DU6cvoA4.d.ts} +9 -5
- package/dist/ui.d.ts +2 -2
- package/dist/ui.js +1 -1
- package/dist/ui.js.map +1 -1
- package/dist/viewer.d.ts +117 -0
- package/dist/viewer.js +659 -0
- package/dist/viewer.js.map +1 -0
- package/package.json +26 -12
- package/dist/adapters-hmnJOOgf.js.map +0 -1
- package/dist/core-BkB2l1-e.js.map +0 -1
- package/dist/leading_system-BVtGMweY.js.map +0 -1
|
@@ -6,7 +6,7 @@ import { appendFileSync, mkdirSync } from "node:fs";
|
|
|
6
6
|
/**
|
|
7
7
|
* Shared span/record core for trajectory loggers.
|
|
8
8
|
*
|
|
9
|
-
* Every
|
|
9
|
+
* Every Fascicle trajectory logger emits the same wire format (one JSON object
|
|
10
10
|
* per event) and differs only in where each event goes: `line_logger` writes a
|
|
11
11
|
* line, `http_logger` POSTs NDJSON. This module holds the span bookkeeping they
|
|
12
12
|
* share, parameterized by a single `emit` sink.
|
|
@@ -81,8 +81,8 @@ function line_logger(write_line) {
|
|
|
81
81
|
* Create a `TrajectoryLogger` that appends one JSON object per line to
|
|
82
82
|
* `output_path`, creating the parent directory if needed.
|
|
83
83
|
*/
|
|
84
|
-
function filesystem_logger(
|
|
85
|
-
const { output_path } =
|
|
84
|
+
function filesystem_logger(config) {
|
|
85
|
+
const { output_path } = config;
|
|
86
86
|
mkdirSync(dirname(output_path), { recursive: true });
|
|
87
87
|
return line_logger((event) => {
|
|
88
88
|
appendFileSync(output_path, `${JSON.stringify(event)}\n`);
|
|
@@ -102,15 +102,15 @@ const default_fetch = async (url, init) => {
|
|
|
102
102
|
};
|
|
103
103
|
/**
|
|
104
104
|
* Create a `TrajectoryLogger` that POSTs each event as NDJSON to
|
|
105
|
-
* `
|
|
105
|
+
* `config.url`.
|
|
106
106
|
*
|
|
107
107
|
* Never throws: a transport failure is dropped and reported through the
|
|
108
108
|
* optional `on_error` callback, so a dev viewer being unreachable never
|
|
109
109
|
* blocks the flow.
|
|
110
110
|
*/
|
|
111
|
-
function http_logger(
|
|
112
|
-
const { url, on_error } =
|
|
113
|
-
const send =
|
|
111
|
+
function http_logger(config) {
|
|
112
|
+
const { url, on_error } = config;
|
|
113
|
+
const send = config.fetch ?? default_fetch;
|
|
114
114
|
const post = (event) => {
|
|
115
115
|
const body = `${JSON.stringify(event)}\n`;
|
|
116
116
|
send(url, {
|
|
@@ -207,7 +207,7 @@ function tee_logger(...loggers) {
|
|
|
207
207
|
* Satisfies `CheckpointStore` from `core`. Each key is stored as
|
|
208
208
|
* a JSON file under the configured root directory. Writes are all-or-nothing:
|
|
209
209
|
* values are written to a temporary sibling file and then atomically renamed
|
|
210
|
-
* into place, so an interrupted write never leaves a partially
|
|
210
|
+
* into place, so an interrupted write never leaves a partially written file
|
|
211
211
|
* at the target key. On `get`, a missing file, a partial temp file that was
|
|
212
212
|
* never atomically renamed, or a JSON parse failure each read as a cache
|
|
213
213
|
* miss (returning `null`) rather than an error.
|
|
@@ -226,10 +226,10 @@ function safe_filename(key) {
|
|
|
226
226
|
return `${key.replace(/[^a-zA-Z0-9._-]/g, "_").slice(0, 64)}.${hash}.json`;
|
|
227
227
|
}
|
|
228
228
|
/**
|
|
229
|
-
* Create a `CheckpointStore` backed by JSON files under `
|
|
229
|
+
* Create a `CheckpointStore` backed by JSON files under `config.root_dir`.
|
|
230
230
|
*/
|
|
231
|
-
function filesystem_store(
|
|
232
|
-
const { root_dir } =
|
|
231
|
+
function filesystem_store(config) {
|
|
232
|
+
const { root_dir } = config;
|
|
233
233
|
const ensure_root = async () => {
|
|
234
234
|
await mkdir(root_dir, { recursive: true });
|
|
235
235
|
};
|
|
@@ -267,4 +267,4 @@ function filesystem_store(options) {
|
|
|
267
267
|
//#endregion
|
|
268
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 };
|
|
269
269
|
|
|
270
|
-
//# sourceMappingURL=adapters-
|
|
270
|
+
//# sourceMappingURL=adapters-CutexJd3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapters-CutexJd3.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 FilesystemLoggerConfig = {\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(config: FilesystemLoggerConfig): TrajectoryLogger {\n const { output_path } = config\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 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 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(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 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 FilesystemStoreConfig = {\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 `config.root_dir`.\n */\nexport function filesystem_store(config: FilesystemStoreConfig): CheckpointStore {\n const { root_dir } = config\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,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;;;;;;;;;;;;;;;;;;ACMA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AAM,cAAc,YAA2B;EAC7C,MAAM,MAAM,UAAU,EAAE,WAAW,KAAK,CAAC;CAC3C;CAEA,MAAM,YAAY,QAAwB,KAAK,UAAU,cAAc,GAAG,CAAC;CAE3E,MAAM,MAAM,OAAO,QAAkC;EACnD,MAAM,OAAO,SAAS,GAAG;EACzB,IAAI;EACJ,IAAI;GACF,MAAM,MAAM,SAAS,MAAM,MAAM;EACnC,QAAQ;GACN,OAAO;EACT;EACA,IAAI;GACF,OAAO,KAAK,MAAM,GAAG;EACvB,QAAQ;GACN,OAAO;EACT;CACF;CAEA,MAAM,MAAM,OAAO,KAAa,UAAkC;EAChE,MAAM,YAAY;EAClB,MAAM,SAAS,SAAS,GAAG;EAC3B,MAAM,MAAM,GAAG,OAAO,GAAG,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;EAClD,MAAM,UAAU,KAAK,KAAK,UAAU,KAAK,GAAG,MAAM;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.d.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { d as TrajectoryLogger, n as CheckpointStore } from "./types-DBpU27sQ.js";
|
|
2
2
|
|
|
3
3
|
//#region src/adapters/filesystem_logger.d.ts
|
|
4
|
-
type
|
|
4
|
+
type FilesystemLoggerConfig = {
|
|
5
5
|
readonly output_path: string;
|
|
6
6
|
};
|
|
7
7
|
/**
|
|
8
8
|
* Create a `TrajectoryLogger` that appends one JSON object per line to
|
|
9
9
|
* `output_path`, creating the parent directory if needed.
|
|
10
10
|
*/
|
|
11
|
-
declare function filesystem_logger(
|
|
11
|
+
declare function filesystem_logger(config: FilesystemLoggerConfig): TrajectoryLogger;
|
|
12
12
|
//#endregion
|
|
13
13
|
//#region src/adapters/http_logger.d.ts
|
|
14
14
|
type HttpLoggerFetch = (url: string, init: {
|
|
@@ -19,20 +19,20 @@ type HttpLoggerFetch = (url: string, init: {
|
|
|
19
19
|
ok: boolean;
|
|
20
20
|
status: number;
|
|
21
21
|
}>;
|
|
22
|
-
type
|
|
22
|
+
type HttpLoggerConfig = {
|
|
23
23
|
readonly url: string;
|
|
24
24
|
readonly fetch?: HttpLoggerFetch;
|
|
25
25
|
readonly on_error?: (err: unknown) => void;
|
|
26
26
|
};
|
|
27
27
|
/**
|
|
28
28
|
* Create a `TrajectoryLogger` that POSTs each event as NDJSON to
|
|
29
|
-
* `
|
|
29
|
+
* `config.url`.
|
|
30
30
|
*
|
|
31
31
|
* Never throws: a transport failure is dropped and reported through the
|
|
32
32
|
* optional `on_error` callback, so a dev viewer being unreachable never
|
|
33
33
|
* blocks the flow.
|
|
34
34
|
*/
|
|
35
|
-
declare function http_logger(
|
|
35
|
+
declare function http_logger(config: HttpLoggerConfig): TrajectoryLogger;
|
|
36
36
|
//#endregion
|
|
37
37
|
//#region src/adapters/noop_logger.d.ts
|
|
38
38
|
/**
|
|
@@ -59,13 +59,13 @@ declare function stderr_logger(options?: StderrLoggerOptions): TrajectoryLogger;
|
|
|
59
59
|
declare function tee_logger(...loggers: ReadonlyArray<TrajectoryLogger>): TrajectoryLogger;
|
|
60
60
|
//#endregion
|
|
61
61
|
//#region src/adapters/filesystem_store.d.ts
|
|
62
|
-
type
|
|
62
|
+
type FilesystemStoreConfig = {
|
|
63
63
|
readonly root_dir: string;
|
|
64
64
|
};
|
|
65
65
|
/**
|
|
66
|
-
* Create a `CheckpointStore` backed by JSON files under `
|
|
66
|
+
* Create a `CheckpointStore` backed by JSON files under `config.root_dir`.
|
|
67
67
|
*/
|
|
68
|
-
declare function filesystem_store(
|
|
68
|
+
declare function filesystem_store(config: FilesystemStoreConfig): CheckpointStore;
|
|
69
69
|
//#endregion
|
|
70
|
-
export { type
|
|
70
|
+
export { type FilesystemLoggerConfig, type FilesystemStoreConfig, type HttpLoggerConfig, type HttpLoggerFetch, type StderrLoggerOptions, filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
|
|
71
71
|
//# sourceMappingURL=adapters.d.ts.map
|
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-CutexJd3.js";
|
|
2
2
|
export { filesystem_logger, filesystem_store, http_logger, noop_logger, stderr_logger, tee_logger };
|
package/dist/agents.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as ToolSchema } from "./types-
|
|
3
|
-
import { a as Engine } from "./types-
|
|
1
|
+
import { a as Step } from "./types-DBpU27sQ.js";
|
|
2
|
+
import { r as ToolSchema } from "./types-BK0UW28o.js";
|
|
3
|
+
import { a as Engine, i as EffortLevel } from "./types-DU6cvoA4.js";
|
|
4
4
|
|
|
5
5
|
//#region src/agents/define_agent.d.ts
|
|
6
6
|
type AgentBuiltPrompt = string | {
|
|
@@ -11,7 +11,17 @@ type DefineAgentConfig<i, o> = {
|
|
|
11
11
|
readonly md_path: string | URL;
|
|
12
12
|
readonly schema: ToolSchema<o>;
|
|
13
13
|
readonly engine: Engine;
|
|
14
|
+
/**
|
|
15
|
+
* Display label for the agent's span, `describe` line, and `agent.call`
|
|
16
|
+
* event. Free prose. Defaults to the frontmatter `name`.
|
|
17
|
+
*/
|
|
14
18
|
readonly name?: string;
|
|
19
|
+
/**
|
|
20
|
+
* Step id for the agent, which must be identifier-shaped. Defaults to the
|
|
21
|
+
* resolved display name, so an agent whose label is already a plain
|
|
22
|
+
* identifier needs nothing here; set it explicitly when the label is prose.
|
|
23
|
+
*/
|
|
24
|
+
readonly id?: string;
|
|
15
25
|
readonly build_prompt?: (input: i) => AgentBuiltPrompt;
|
|
16
26
|
/**
|
|
17
27
|
* Model for this agent's calls, typically threaded from the app's resolved
|
|
@@ -19,6 +29,15 @@ type DefineAgentConfig<i, o> = {
|
|
|
19
29
|
* the engine default applies.
|
|
20
30
|
*/
|
|
21
31
|
readonly model?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Transport for the model. Same precedence as `model`: code wins over
|
|
34
|
+
* frontmatter `provider`, and the engine default is the last resort.
|
|
35
|
+
*/
|
|
36
|
+
readonly provider?: string; /** Reasoning effort for the call. Wins over frontmatter `effort`. */
|
|
37
|
+
readonly effort?: EffortLevel; /** Sampling temperature. Wins over frontmatter `temperature`. */
|
|
38
|
+
readonly temperature?: number; /** Output token cap. Wins over frontmatter `max_tokens`. */
|
|
39
|
+
readonly max_tokens?: number; /** Nucleus sampling cutoff. Wins over frontmatter `top_p`. */
|
|
40
|
+
readonly top_p?: number;
|
|
22
41
|
/**
|
|
23
42
|
* Forwarded to `engine.generate`: how many times the engine may re-prompt
|
|
24
43
|
* the model to repair schema-invalid output before failing the call.
|
package/dist/agents.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { C as step, O as aborted_error, w as assert_valid_step_id } from "./core-DdJEhyQc.js";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
//#region src/agents/define_agent.ts
|
|
@@ -10,28 +10,34 @@ import { fileURLToPath } from "node:url";
|
|
|
10
10
|
* folds those into a `Step<i, o>`:
|
|
11
11
|
*
|
|
12
12
|
* - The markdown file is read once at factory time. Its YAML-style frontmatter
|
|
13
|
-
* (`name`, `description`, `model`, `
|
|
14
|
-
*
|
|
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.
|
|
15
16
|
* - Without `build_prompt`, the body (after `{{key}}` substitution against
|
|
16
17
|
* top-level string fields of the input) is the user prompt and no system is
|
|
17
18
|
* sent; the markdown carries the full instruction.
|
|
18
19
|
* - With `build_prompt`, the body is the system prompt and `build_prompt(input)`
|
|
19
20
|
* produces the user message (string, or `{ user, system? }` to override).
|
|
20
|
-
* - `config.model`
|
|
21
|
-
*
|
|
21
|
+
* - `config.model`, `config.provider`, `config.effort`, `config.temperature`,
|
|
22
|
+
* `config.max_tokens`, `config.top_p`, and `config.schema_repair_attempts`
|
|
23
|
+
* shape the call from code. Code wins over frontmatter (frontmatter stays
|
|
22
24
|
* the role default when the app threads nothing; the engine default is the
|
|
23
25
|
* last resort), so a resolved role-to-model table and env overrides actually
|
|
24
26
|
* reach the call.
|
|
25
27
|
*
|
|
26
28
|
* The factory keeps no engine state. Each call delegates to `engine.generate`
|
|
27
29
|
* with the resolved prompts, the schema, and `ctx.abort` / `ctx.trajectory`
|
|
28
|
-
* threaded through. An `agent.call` trajectory event carries the agent
|
|
29
|
-
* resolved model id, and engine-reported usage.
|
|
30
|
+
* threaded through. An `agent.call` trajectory event carries the agent id and
|
|
31
|
+
* display name, resolved model id, and engine-reported usage. Identity and
|
|
32
|
+
* display stay separate: `config.id` is the step id and must be
|
|
33
|
+
* identifier-shaped, while `config.name` is free prose that labels the span.
|
|
34
|
+
* No retry or fallback is baked
|
|
30
35
|
* in; wrap with `retry()` from core if you need it.
|
|
31
36
|
*
|
|
32
37
|
* Frontmatter parser is intentionally tiny (no gray-matter): bare `key: value`
|
|
33
|
-
* lines, optional `'`/`"` quotes, `temperature` coerced
|
|
34
|
-
*
|
|
38
|
+
* lines, optional `'`/`"` quotes, `temperature`/`max_tokens`/`top_p` coerced
|
|
39
|
+
* to number, `effort` validated against the engine's levels. Anything richer
|
|
40
|
+
* should go through `build_prompt`.
|
|
35
41
|
*/
|
|
36
42
|
const FRONTMATTER_OPEN = /^---\s*\r?\n/;
|
|
37
43
|
const FRONTMATTER_CLOSE = /^---\s*$/m;
|
|
@@ -66,18 +72,35 @@ function split_frontmatter(content) {
|
|
|
66
72
|
};
|
|
67
73
|
}
|
|
68
74
|
/**
|
|
69
|
-
* Coerce a
|
|
70
|
-
* `raw` is the pre-unquote text, so the error message echoes what the
|
|
75
|
+
* Coerce a numeric frontmatter value to a finite number, throwing on anything
|
|
76
|
+
* else. `raw` is the pre-unquote text, so the error message echoes what the
|
|
77
|
+
* file held.
|
|
71
78
|
*/
|
|
72
|
-
function
|
|
79
|
+
function parse_number(key, value, raw) {
|
|
73
80
|
const n = Number(value);
|
|
74
|
-
if (!Number.isFinite(n)) throw new Error(`define_agent:
|
|
81
|
+
if (!Number.isFinite(n)) throw new Error(`define_agent: ${key} must be a number, got: ${raw}`);
|
|
75
82
|
return n;
|
|
76
83
|
}
|
|
84
|
+
const EFFORT_LEVELS = {
|
|
85
|
+
none: true,
|
|
86
|
+
low: true,
|
|
87
|
+
medium: true,
|
|
88
|
+
high: true,
|
|
89
|
+
xhigh: true,
|
|
90
|
+
max: true
|
|
91
|
+
};
|
|
92
|
+
/**
|
|
93
|
+
* Validate an `effort` value against the engine's `EffortLevel` union,
|
|
94
|
+
* throwing at factory time so a typo'd level never reaches a live call.
|
|
95
|
+
*/
|
|
96
|
+
function parse_effort(value, raw) {
|
|
97
|
+
if (!Object.hasOwn(EFFORT_LEVELS, value)) throw new Error(`define_agent: effort must be one of ${Object.keys(EFFORT_LEVELS).join(", ")}, got: ${raw}`);
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
77
100
|
/**
|
|
78
101
|
* Parse one `key: value` frontmatter line into `out`. Blank and `#` comment
|
|
79
102
|
* lines are skipped; a line without a colon throws; unrecognized keys are
|
|
80
|
-
* ignored so only `
|
|
103
|
+
* ignored so only the `Frontmatter` fields reach the agent.
|
|
81
104
|
*/
|
|
82
105
|
function assign_frontmatter_field(out, raw) {
|
|
83
106
|
const line = raw.trim();
|
|
@@ -87,19 +110,24 @@ function assign_frontmatter_field(out, raw) {
|
|
|
87
110
|
const key = line.slice(0, colon_idx).trim();
|
|
88
111
|
const value_raw = line.slice(colon_idx + 1).trim();
|
|
89
112
|
const value = unquote(value_raw);
|
|
90
|
-
if (key === "name" || key === "description" || key === "model") {
|
|
113
|
+
if (key === "name" || key === "description" || key === "model" || key === "provider") {
|
|
91
114
|
out[key] = value;
|
|
92
115
|
return;
|
|
93
116
|
}
|
|
94
|
-
if (key === "temperature"
|
|
117
|
+
if (key === "temperature" || key === "max_tokens" || key === "top_p") {
|
|
118
|
+
out[key] = parse_number(key, value, value_raw);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (key === "effort") out.effort = parse_effort(value, value_raw);
|
|
95
122
|
}
|
|
96
123
|
/**
|
|
97
124
|
* Split a markdown file into frontmatter fields and prompt body.
|
|
98
125
|
*
|
|
99
126
|
* Parses only the flat `key: value` subset of YAML that agent files need:
|
|
100
|
-
* recognized keys are `name`, `description`, `model`,
|
|
101
|
-
* (
|
|
102
|
-
*
|
|
127
|
+
* recognized keys are `name`, `description`, `model`, `provider`, `effort`
|
|
128
|
+
* (validated against the engine's levels), and `temperature`/`max_tokens`/
|
|
129
|
+
* `top_p` (coerced to numbers); unrecognized keys are ignored. A file without
|
|
130
|
+
* an opening `---` is all body. Malformed frontmatter throws rather than
|
|
103
131
|
* silently producing a wrong prompt.
|
|
104
132
|
*/
|
|
105
133
|
function parse_frontmatter(content) {
|
|
@@ -141,6 +169,26 @@ function substitute(template, input) {
|
|
|
141
169
|
});
|
|
142
170
|
}
|
|
143
171
|
/**
|
|
172
|
+
* 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.
|
|
176
|
+
*/
|
|
177
|
+
function apply_call_knobs(opts, config, frontmatter) {
|
|
178
|
+
const model = config.model ?? frontmatter.model;
|
|
179
|
+
if (model !== void 0) opts.model = model;
|
|
180
|
+
const provider = config.provider ?? frontmatter.provider;
|
|
181
|
+
if (provider !== void 0) opts.provider = provider;
|
|
182
|
+
const effort = config.effort ?? frontmatter.effort;
|
|
183
|
+
if (effort !== void 0) opts.effort = effort;
|
|
184
|
+
const temperature = config.temperature ?? frontmatter.temperature;
|
|
185
|
+
if (temperature !== void 0) opts.temperature = temperature;
|
|
186
|
+
const max_tokens = config.max_tokens ?? frontmatter.max_tokens;
|
|
187
|
+
if (max_tokens !== void 0) opts.max_tokens = max_tokens;
|
|
188
|
+
const top_p = config.top_p ?? frontmatter.top_p;
|
|
189
|
+
if (top_p !== void 0) opts.top_p = top_p;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
144
192
|
* Load a markdown-defined agent as a `Step<i, o>`.
|
|
145
193
|
*
|
|
146
194
|
* Reads and parses the file once at factory time; each run resolves the
|
|
@@ -151,7 +199,9 @@ function substitute(template, input) {
|
|
|
151
199
|
function define_agent(config) {
|
|
152
200
|
const { frontmatter, body } = parse_frontmatter(read_md_sync(config.md_path));
|
|
153
201
|
const display_name = config.name ?? frontmatter.name ?? "agent";
|
|
154
|
-
|
|
202
|
+
const id = config.id ?? display_name;
|
|
203
|
+
assert_valid_step_id(id, "define_agent: agent id", "pass config.id and leave the prose spelling in config.name");
|
|
204
|
+
const run_agent = async (input, ctx) => {
|
|
155
205
|
if (ctx.abort.aborted) throw new aborted_error("aborted before agent call");
|
|
156
206
|
let user_prompt;
|
|
157
207
|
let system_prompt;
|
|
@@ -175,20 +225,20 @@ function define_agent(config) {
|
|
|
175
225
|
trajectory: ctx.trajectory
|
|
176
226
|
};
|
|
177
227
|
if (system_prompt !== void 0 && system_prompt !== "") opts.system = system_prompt;
|
|
178
|
-
|
|
179
|
-
if (model !== void 0) opts.model = model;
|
|
180
|
-
if (frontmatter.temperature !== void 0) opts.temperature = frontmatter.temperature;
|
|
228
|
+
apply_call_knobs(opts, config, frontmatter);
|
|
181
229
|
if (config.schema_repair_attempts !== void 0) opts.schema_repair_attempts = config.schema_repair_attempts;
|
|
182
230
|
const result = await config.engine.generate(opts);
|
|
183
231
|
const resolved_model = `${result.model_resolved.provider}:${result.model_resolved.model_id}`;
|
|
184
232
|
ctx.trajectory.record({
|
|
185
233
|
kind: "agent.call",
|
|
234
|
+
id,
|
|
186
235
|
name: display_name,
|
|
187
236
|
model: resolved_model,
|
|
188
237
|
usage: result.usage
|
|
189
238
|
});
|
|
190
239
|
return result.content;
|
|
191
|
-
}
|
|
240
|
+
};
|
|
241
|
+
return id === display_name ? step(id, run_agent) : step(id, run_agent, { name: display_name });
|
|
192
242
|
}
|
|
193
243
|
//#endregion
|
|
194
244
|
export { define_agent };
|
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\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,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;;;;;AAMA,SAAS,kBAAkB,OAAe,KAAqB;CA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AAC;AACH"}
|
|
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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GA,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,a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AAC;AACtD"}
|
|
@@ -4,6 +4,6 @@ import { dirname, resolve } from 'node:path';
|
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
|
|
6
6
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
7
|
-
const
|
|
8
|
-
const mod = await import(pathToFileURL(
|
|
7
|
+
const dist_viewer = resolve(here, '..', 'viewer.js');
|
|
8
|
+
const mod = await import(pathToFileURL(dist_viewer).href);
|
|
9
9
|
await mod.run_viewer_cli(process.argv.slice(2));
|