fascicle 0.12.13 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +27 -1
  2. package/dist/adapters-DNnzeLxr.js +447 -0
  3. package/dist/adapters-DNnzeLxr.js.map +1 -0
  4. package/dist/adapters.d.ts +54 -9
  5. package/dist/adapters.js +1 -1
  6. package/dist/agents.d.ts +12 -9
  7. package/dist/agents.js +1 -1
  8. package/dist/{core-BVCVUMmH.js → core-B-M7nAkg.js} +704 -33
  9. package/dist/core-B-M7nAkg.js.map +1 -0
  10. package/dist/diagram_bin.d.ts +1 -2
  11. package/dist/diagram_bin.js +1 -1
  12. package/dist/diagram_bin.js.map +1 -1
  13. package/dist/{engine-Ct4LBzb9.js → engine-BRzVcTBB.js} +366 -36
  14. package/dist/engine-BRzVcTBB.js.map +1 -0
  15. package/dist/index.d.ts +325 -179
  16. package/dist/index.js +149 -123
  17. package/dist/index.js.map +1 -1
  18. package/dist/{invoke-BcPDqE5C.js → invoke-CIdhjChw.js} +3 -3
  19. package/dist/{invoke-BcPDqE5C.js.map → invoke-CIdhjChw.js.map} +1 -1
  20. package/dist/mcp.d.ts +8 -9
  21. package/dist/mcp.js +1 -1
  22. package/dist/otel.d.ts +3 -4
  23. package/dist/stdio.d.ts +4 -5
  24. package/dist/stdio.js +2 -2
  25. package/dist/testing.d.ts +46 -10
  26. package/dist/testing.js +540 -4
  27. package/dist/testing.js.map +1 -1
  28. package/dist/{trajectory-D1eq9eue.js → trajectory-BI-mrVFT.js} +25 -2
  29. package/dist/trajectory-BI-mrVFT.js.map +1 -0
  30. package/dist/{trajectory-ByoOQZ6T.d.ts → trajectory-Bm-mOtqw.d.ts} +34 -3
  31. package/dist/{types-BasW4Wwb.d.ts → types-CPqLZOEr.d.ts} +40 -2
  32. package/dist/{types-bEpfDrys.d.ts → types-CZ83Q5nm.d.ts} +12 -7
  33. package/dist/ui.d.ts +11 -10
  34. package/dist/ui.js +3 -2
  35. package/dist/ui.js.map +1 -1
  36. package/dist/viewer-app/assets/index-DXsB0byD.js +2 -0
  37. package/dist/viewer-app/index.html +1 -1
  38. package/dist/viewer.d.ts +7 -8
  39. package/dist/viewer.js +2 -2
  40. package/dist/viewer.js.map +1 -1
  41. package/package.json +28 -28
  42. package/dist/adapters-CutexJd3.js +0 -270
  43. package/dist/adapters-CutexJd3.js.map +0 -1
  44. package/dist/core-BVCVUMmH.js.map +0 -1
  45. package/dist/engine-Ct4LBzb9.js.map +0 -1
  46. package/dist/leading_system-CfOIc5fi.js +0 -330
  47. package/dist/leading_system-CfOIc5fi.js.map +0 -1
  48. package/dist/trajectory-D1eq9eue.js.map +0 -1
  49. package/dist/viewer-app/assets/index-BBEYkjnQ.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"diagram_bin.js","names":[],"sources":["../src/diagram_cli.ts","../src/diagram_bin.ts"],"sourcesContent":["/**\n * fascicle-diagram CLI.\n *\n * fascicle-diagram <module> print the diagram of the module's `flow`\n * fascicle-diagram <module> --export <name> read another export instead\n *\n * Flags: --export <name> --width <n> --prefix <text> --help\n *\n * The export is a Step, or a function that builds one with no arguments,\n * which is where an app wires its flow to stub dependencies so that drawing\n * it needs no credentials. The diagram is `describe.diagram` of that Step, so\n * it is what the code builds today and can be compared with the header in\n * `flow.ts` at a glance.\n *\n * This file holds every decision the command makes and touches nothing of\n * the process: output and module loading arrive through `DiagramCliIo`.\n * diagram_bin.ts binds that io to the real streams and to the project's\n * `tsx`, and is the entry that the package's bin shim runs.\n */\n\nimport { resolve } from 'node:path'\nimport { parseArgs } from 'node:util'\nimport { describe, is_step } from '#core'\nimport type { DiagramOptions } from '#core'\n\nexport type DiagramCliIo = {\n readonly out: (text: string) => void\n readonly err: (text: string) => void\n /** Import the module at an absolute path and return its exports. */\n readonly load: (path: string) => Promise<Readonly<Record<string, unknown>>>\n}\n\ntype CliArgs = {\n readonly module: string\n readonly export_name: string\n readonly options: DiagramOptions\n}\n\ntype Parsed =\n | { readonly kind: 'help' }\n | { readonly kind: 'usage'; readonly message: string }\n | { readonly kind: 'run'; readonly args: CliArgs }\n\nconst HELP = `\\\nfascicle-diagram prints a flow as an annotated box-drawing tree.\n\nUsage:\n fascicle-diagram <module> draw the module's \\`flow\\` export\n fascicle-diagram <module> --export <name> draw another export instead\n\nThe export is a Step, or a function that builds one with no arguments.\n\nOptions:\n --export <name> the export to draw (default flow)\n --width <n> wrap descriptions so no line runs wider than n\n --prefix <text> start every line with text, for example ' * '\n --help show this message\n`\n\n\n/**\n * Run the CLI over `argv` and resolve to its exit code: 0 once the diagram is\n * printed, 1 when the module cannot be loaded or holds no Step, and 2 for a\n * usage error. Output and loading go through `io`, so the caller owns the\n * process.\n */\nexport async function run_diagram_cli(argv: readonly string[], io: DiagramCliIo): Promise<number> {\n const parsed = parse(argv)\n if (parsed.kind === 'help') {\n io.out(HELP)\n return 0\n }\n if (parsed.kind === 'usage') {\n io.err(`fascicle-diagram: ${parsed.message}\\n\\n${HELP}`)\n return 2\n }\n const { module, export_name, options } = parsed.args\n const path = resolve(module)\n let exports: Readonly<Record<string, unknown>>\n try {\n exports = await io.load(path)\n } catch (err) {\n io.err(`fascicle-diagram: could not load ${module}: ${message_of(err)}\\n`)\n return 1\n }\n if (!(export_name in exports)) {\n const names = Object.keys(exports).join(', ') || 'nothing'\n io.err(\n `fascicle-diagram: ${module} has no export named ${export_name}: pass --export <name> (it exports ${names})\\n`,\n )\n return 1\n }\n let flow: unknown\n try {\n flow = await build(exports[export_name])\n } catch (err) {\n io.err(\n `fascicle-diagram: calling ${export_name}() in ${module} threw: ${message_of(err)}\\n` +\n 'Export a function that builds the flow with no arguments, wired to stub dependencies.\\n',\n )\n return 1\n }\n if (!is_step(flow)) {\n io.err(\n `fascicle-diagram: ${export_name} in ${module} is not a Step: export the flow itself, or a function that builds it with no arguments\\n`,\n )\n return 1\n }\n io.out(`${describe.diagram(flow, options)}\\n`)\n return 0\n}\n\n/**\n * Parse argv into a run request, a help request, or a usage error. Unknown\n * flags and a missing module are usage errors, and so is a width that is not\n * a positive integer.\n */\nfunction parse(argv: readonly string[]): Parsed {\n let parsed: ReturnType<typeof parse_flags>\n try {\n parsed = parse_flags(argv)\n } catch (err) {\n return { kind: 'usage', message: message_of(err) }\n }\n const { values, positionals } = parsed\n if (values.help === true) return { kind: 'help' }\n const [module, ...extra] = positionals\n if (module === undefined) return { kind: 'usage', message: 'a <module> to draw is required' }\n if (extra.length > 0) return { kind: 'usage', message: `expected one <module>, got ${positionals.join(' ')}` }\n const options: { width?: number; prefix?: string } = {}\n if (values.width !== undefined) {\n const width = Number(values.width)\n if (!Number.isInteger(width) || width <= 0) {\n return { kind: 'usage', message: `invalid --width '${values.width}': expected a positive integer` }\n }\n options.width = width\n }\n if (values.prefix !== undefined) options.prefix = values.prefix\n return { kind: 'run', args: { module, export_name: values.export ?? 'flow', options } }\n}\n\n/**\n * Read the CLI's flags with `node:util`'s strict parser, which throws on a\n * flag it does not know.\n */\nfunction parse_flags(argv: readonly string[]) {\n return parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n export: { type: 'string' },\n width: { type: 'string' },\n prefix: { type: 'string' },\n help: { type: 'boolean' },\n },\n })\n}\n\n/**\n * The Step an export stands for: the export itself, or what calling it with\n * no arguments returns (awaited, so an async builder works too).\n */\nasync function build(value: unknown): Promise<unknown> {\n return typeof value === 'function' ? await value() : value\n}\n\n/**\n * Render a thrown value as its message.\n */\nfunction message_of(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The process side of the fascicle-diagram bin: the real streams, and module\n * loading through the project's own `tsx`.\n *\n * Every decision the command makes lives in diagram_cli.ts, which is unit\n * tested through an injected io. This file only binds that io to the process,\n * so it is exercised by spawning it (__tests__/diagram_bin.test.ts) and kept\n * out of mutation testing, which cannot see a spawned child's coverage.\n *\n * A TypeScript module loads through `tsx` because Node's built-in type\n * stripping cannot follow the `./flow.js` specifiers that point at `.ts`\n * files under NodeNext resolution. Anything else, or a project without\n * `tsx`, goes through a plain `import()`.\n */\n\nimport { createRequire } from 'node:module'\nimport { resolve } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { run_diagram_cli } from './diagram_cli.js'\n\nconst TS_MODULE = /\\.[cm]?tsx?$/\n\n/**\n * Run the fascicle-diagram command over `argv` against the real process, and\n * leave its exit code on `process.exitCode`. A reader that closes the pipe\n * early (`| head`) ends the output quietly instead of crashing the command on\n * an unhandled EPIPE.\n */\nexport async function run_diagram_bin(argv: readonly string[]): Promise<void> {\n process.stdout.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code !== 'EPIPE') throw err\n })\n process.exitCode = await run_diagram_cli(argv, {\n out: (text) => process.stdout.write(text),\n err: (text) => process.stderr.write(text),\n load: load_module,\n })\n}\n\n/**\n * Import the module at `path`. A TypeScript module goes through the `tsx`\n * that the project installs, looked up from the module's own directory and\n * then from the working directory. Everything else is a plain dynamic import.\n */\nasync function load_module(path: string): Promise<Readonly<Record<string, unknown>>> {\n const url = pathToFileURL(path).href\n if (!TS_MODULE.test(path)) return as_record(await import(url))\n const tsx = find_tsx([path, resolve('package.json')])\n if (tsx === undefined) return import_without_tsx(url)\n const api: unknown = await import(pathToFileURL(tsx).href)\n const ts_import = as_record(api)['tsImport']\n if (typeof ts_import !== 'function') return as_record(await import(url))\n return as_record(await ts_import(url, import.meta.url))\n}\n\n/**\n * Import a TypeScript module with Node's own type stripping, which handles\n * only erasable syntax and specifiers that name real files. A failure says\n * that tsx is the fix, since this path is taken only when none was found.\n */\nasync function import_without_tsx(url: string): Promise<Readonly<Record<string, unknown>>> {\n try {\n return as_record(await import(url))\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`${reason} (no tsx was found to load TypeScript: install it with pnpm add -D tsx)`, {\n cause: err,\n })\n }\n}\n\n/**\n * Resolve tsx's programmatic API from the first of `origins` that can see it,\n * or `undefined` when none can.\n */\nfunction find_tsx(origins: readonly string[]): string | undefined {\n for (const origin of origins) {\n try {\n return createRequire(origin).resolve('tsx/esm/api')\n } catch {\n // Not installed where this origin looks; try the next one.\n }\n }\n return undefined\n}\n\n/**\n * View a loaded module namespace as a record of its exports.\n */\nfunction as_record(value: unknown): Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null ? { ...value } : {}\n}\n\n// Auto-run only when this file is the entry script (`tsx src/diagram_bin.ts`),\n// never when the bundle that contains it is imported. The path comparison is\n// the same guard the viewer CLI uses.\nconst invoked_directly =\n process.argv[1] !== undefined && process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) void run_diagram_bin(process.argv.slice(2))\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;AAuBb,eAAsB,gBAAgB,MAAyB,IAAmC;CAChG,MAAM,SAAS,MAAM,IAAI;CACzB,IAAI,OAAO,SAAS,QAAQ;EAC1B,GAAG,IAAI,IAAI;EACX,OAAO;CACT;CACA,IAAI,OAAO,SAAS,SAAS;EAC3B,GAAG,IAAI,qBAAqB,OAAO,QAAQ,MAAM,MAAM;EACvD,OAAO;CACT;CACA,MAAM,EAAE,QAAQ,aAAa,YAAY,OAAO;CAChD,MAAM,OAAO,QAAQ,MAAM;CAC3B,IAAI;CACJ,IAAI;EACF,UAAU,MAAM,GAAG,KAAK,IAAI;CAC9B,SAAS,KAAK;EACZ,GAAG,IAAI,oCAAoC,OAAO,IAAI,WAAW,GAAG,EAAE,GAAG;EACzE,OAAO;CACT;CACA,IAAI,EAAE,eAAe,UAAU;EAC7B,MAAM,QAAQ,OAAO,KAAK,OAAO,CAAC,CAAC,KAAK,IAAI,KAAK;EACjD,GAAG,IACD,qBAAqB,OAAO,uBAAuB,YAAY,qCAAqC,MAAM,IAC5G;EACA,OAAO;CACT;CACA,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,MAAM,QAAQ,YAAY;CACzC,SAAS,KAAK;EACZ,GAAG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AI,MAAM,GAAG,OAAO,0EAA0E,EAClG,OAAO,IACT,CAAC;CACH;AACF;;;;;AAMA,SAAS,SAAS,SAAgD;CAChE,KAAK,MAAM,UAAU,SACnB,IAAI;EACF,OAAO,cAAc,MAAM,CAAC,CAAC,QAAQ,aAAa;CACpD,QAAQ,CAER;AAGJ;;;;AAKA,SAAS,UAAU,OAAmD;CACpE,OAAO,OAAO,UAAU,YAAY,UAAU,OAAO,EAAE,GAAG,MAAM,IAAI,CAAC;AACvE;AAQA,IAFE,QAAQ,KAAK,OAAO,KAAA,KAAa,QAAQ,KAAK,OAAO,cAAc,OAAO,KAAK,GAAG,GAE9D,gBAAqB,QAAQ,KAAK,MAAM,CAAC,CAAC"}
1
+ {"version":3,"file":"diagram_bin.js","names":[],"sources":["../src/diagram_cli.ts","../src/diagram_bin.ts"],"sourcesContent":["/**\n * fascicle-diagram CLI.\n *\n * fascicle-diagram <module> print the diagram of the module's `flow`\n * fascicle-diagram <module> --export <name> read another export instead\n *\n * Flags: --export <name> --width <n> --prefix <text> --help\n *\n * The export is a Step, or a function that builds one with no arguments,\n * which is where an app wires its flow to stub dependencies so that drawing\n * it needs no credentials. The diagram is `describe.diagram` of that Step, so\n * it is what the code builds today and can be compared with the header in\n * `flow.ts` at a glance.\n *\n * This file holds every decision the command makes and touches nothing of\n * the process: output and module loading arrive through `DiagramCliIo`.\n * diagram_bin.ts binds that io to the real streams and to the project's\n * `tsx`, and is the entry that the package's bin shim runs.\n */\n\nimport { resolve } from 'node:path'\nimport { parseArgs } from 'node:util'\nimport { describe, is_step } from '#core'\nimport type { DiagramOptions } from '#core'\n\nexport type DiagramCliIo = {\n readonly out: (text: string) => void\n readonly err: (text: string) => void\n /** Import the module at an absolute path and return its exports. */\n readonly load: (path: string) => Promise<Readonly<Record<string, unknown>>>\n}\n\ntype CliArgs = {\n readonly module: string\n readonly export_name: string\n readonly options: DiagramOptions\n}\n\ntype Parsed =\n | { readonly kind: 'help' }\n | { readonly kind: 'usage'; readonly message: string }\n | { readonly kind: 'run'; readonly args: CliArgs }\n\nconst HELP = `\\\nfascicle-diagram prints a flow as an annotated box-drawing tree.\n\nUsage:\n fascicle-diagram <module> draw the module's \\`flow\\` export\n fascicle-diagram <module> --export <name> draw another export instead\n\nThe export is a Step, or a function that builds one with no arguments.\n\nOptions:\n --export <name> the export to draw (default flow)\n --width <n> wrap descriptions so no line runs wider than n\n --prefix <text> start every line with text, for example ' * '\n --help show this message\n`\n\n\n/**\n * Run the CLI over `argv` and resolve to its exit code: 0 once the diagram is\n * printed, 1 when the module cannot be loaded or holds no Step, and 2 for a\n * usage error. Output and loading go through `io`, so the caller owns the\n * process.\n */\nexport async function run_diagram_cli(argv: readonly string[], io: DiagramCliIo): Promise<number> {\n const parsed = parse(argv)\n if (parsed.kind === 'help') {\n io.out(HELP)\n return 0\n }\n if (parsed.kind === 'usage') {\n io.err(`fascicle-diagram: ${parsed.message}\\n\\n${HELP}`)\n return 2\n }\n const { module, export_name, options } = parsed.args\n const path = resolve(module)\n let exports: Readonly<Record<string, unknown>>\n try {\n exports = await io.load(path)\n } catch (err) {\n io.err(`fascicle-diagram: could not load ${module}: ${message_of(err)}\\n`)\n return 1\n }\n if (!(export_name in exports)) {\n const names = Object.keys(exports).join(', ') || 'nothing'\n io.err(\n `fascicle-diagram: ${module} has no export named ${export_name}: pass --export <name> (it exports ${names})\\n`,\n )\n return 1\n }\n let flow: unknown\n try {\n flow = await build(exports[export_name])\n } catch (err) {\n io.err(\n `fascicle-diagram: calling ${export_name}() in ${module} threw: ${message_of(err)}\\n` +\n 'Export a function that builds the flow with no arguments, wired to stub dependencies.\\n',\n )\n return 1\n }\n if (!is_step(flow)) {\n io.err(\n `fascicle-diagram: ${export_name} in ${module} is not a Step: export the flow itself, or a function that builds it with no arguments\\n`,\n )\n return 1\n }\n io.out(`${describe.diagram(flow, options)}\\n`)\n return 0\n}\n\n/**\n * Parse argv into a run request, a help request, or a usage error. Unknown\n * flags and a missing module are usage errors, and so is a width that is not\n * a positive integer.\n */\nfunction parse(argv: readonly string[]): Parsed {\n let parsed: ReturnType<typeof parse_flags>\n try {\n parsed = parse_flags(argv)\n } catch (err) {\n return { kind: 'usage', message: message_of(err) }\n }\n const { values, positionals } = parsed\n if (values.help === true) return { kind: 'help' }\n const [module, ...extra] = positionals\n if (module === undefined) return { kind: 'usage', message: 'a <module> to draw is required' }\n if (extra.length > 0) return { kind: 'usage', message: `expected one <module>, got ${positionals.join(' ')}` }\n const options: { width?: number; prefix?: string } = {}\n if (values.width !== undefined) {\n const width = Number(values.width)\n if (!Number.isInteger(width) || width <= 0) {\n return { kind: 'usage', message: `invalid --width '${values.width}': expected a positive integer` }\n }\n options.width = width\n }\n if (values.prefix !== undefined) options.prefix = values.prefix\n return { kind: 'run', args: { module, export_name: values.export ?? 'flow', options } }\n}\n\n/**\n * Read the CLI's flags with `node:util`'s strict parser, which throws on a\n * flag it does not know.\n */\nfunction parse_flags(argv: readonly string[]) {\n return parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n export: { type: 'string' },\n width: { type: 'string' },\n prefix: { type: 'string' },\n help: { type: 'boolean' },\n },\n })\n}\n\n/**\n * The Step an export stands for: the export itself, or what calling it with\n * no arguments returns (awaited, so an async builder works too).\n */\nasync function build(value: unknown): Promise<unknown> {\n return typeof value === 'function' ? await value() : value\n}\n\n/**\n * Render a thrown value as its message.\n */\nfunction message_of(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * The process side of the fascicle-diagram bin: the real streams, and module\n * loading through the project's own `tsx`.\n *\n * Every decision the command makes lives in diagram_cli.ts, which is unit\n * tested through an injected io. This file only binds that io to the process,\n * so it is exercised by spawning it (__tests__/diagram_bin.test.ts) and kept\n * out of mutation testing, which cannot see a spawned child's coverage.\n *\n * A TypeScript module loads through `tsx` because Node's built-in type\n * stripping cannot follow the `./flow.js` specifiers that point at `.ts`\n * files under NodeNext resolution. Anything else, or a project without\n * `tsx`, goes through a plain `import()`.\n */\n\nimport { createRequire } from 'node:module'\nimport { resolve } from 'node:path'\nimport { fileURLToPath, pathToFileURL } from 'node:url'\nimport { run_diagram_cli } from './diagram_cli.js'\n\nconst TS_MODULE = /\\.[cm]?tsx?$/\n\n/**\n * Run the fascicle-diagram command over `argv` against the real process, and\n * leave its exit code on `process.exitCode`. A reader that closes the pipe\n * early (`| head`) ends the output quietly instead of crashing the command on\n * an unhandled EPIPE.\n */\nexport async function run_diagram_bin(argv: readonly string[]): Promise<void> {\n process.stdout.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code !== 'EPIPE') throw err\n })\n process.exitCode = await run_diagram_cli(argv, {\n out: (text) => process.stdout.write(text),\n err: (text) => process.stderr.write(text),\n load: load_module,\n })\n}\n\n/**\n * Import the module at `path`. A TypeScript module goes through the `tsx`\n * that the project installs, looked up from the module's own directory and\n * then from the working directory. Everything else is a plain dynamic import.\n */\nasync function load_module(path: string): Promise<Readonly<Record<string, unknown>>> {\n const url = pathToFileURL(path).href\n if (!TS_MODULE.test(path)) return as_record(await import(url))\n const tsx = find_tsx([path, resolve('package.json')])\n if (tsx === undefined) return import_without_tsx(url)\n const api: unknown = await import(pathToFileURL(tsx).href)\n const ts_import = as_record(api)['tsImport']\n if (typeof ts_import !== 'function') return as_record(await import(url))\n return as_record(await ts_import(url, import.meta.url))\n}\n\n/**\n * Import a TypeScript module with Node's own type stripping, which handles\n * only erasable syntax and specifiers that name real files. A failure says\n * that tsx is the fix, since this path is taken only when none was found.\n */\nasync function import_without_tsx(url: string): Promise<Readonly<Record<string, unknown>>> {\n try {\n return as_record(await import(url))\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`${reason} (no tsx was found to load TypeScript: install it with pnpm add -D tsx)`, {\n cause: err,\n })\n }\n}\n\n/**\n * Resolve tsx's programmatic API from the first of `origins` that can see it,\n * or `undefined` when none can.\n */\nfunction find_tsx(origins: readonly string[]): string | undefined {\n for (const origin of origins) {\n try {\n return createRequire(origin).resolve('tsx/esm/api')\n } catch {\n // Not installed where this origin looks; try the next one.\n }\n }\n return undefined\n}\n\n/**\n * View a loaded module namespace as a record of its exports.\n */\nfunction as_record(value: unknown): Readonly<Record<string, unknown>> {\n return typeof value === 'object' && value !== null ? { ...value } : {}\n}\n\n// Auto-run only when this file is the entry script (`tsx src/diagram_bin.ts`),\n// never when the bundle that contains it is imported. The path comparison is\n// the same guard the viewer CLI uses.\nconst invoked_directly =\n process.argv[1] !== undefined && process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) void run_diagram_bin(process.argv.slice(2))\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,MAAM,OAAO;;;;;;;;;;;;;;;;;;;;;AAuBb,eAAsB,gBAAgB,MAAyB,IAAmC;CAChG,MAAM,SAAS,MAAM,IAAI;CACzB,IAAI,OAAO,SAAS,QAAQ;EAC1B,GAAG,IAAI,IAAI;EACX,OAAO;CACT;CACA,IAAI,OAAO,SAAS,SAAS;EAC3B,GAAG,IAAI,qBAAqB,OAAO,QAAQ,MAAM,MAAM;EACvD,OAAO;CACT;CACA,MAAM,EAAE,QAAQ,aAAa,YAAY,OAAO;CAChD,MAAM,OAAO,QAAQ,MAAM;CAC3B,IAAI;CACJ,IAAI;EACF,UAAU,MAAM,GAAG,KAAK,IAAI;CAC9B,SAAS,KAAK;EACZ,GAAG,IAAI,oCAAoC,OAAO,IAAI,WAAW,GAAG,EAAE,GAAG;EACzE,OAAO;CACT;CACA,IAAI,EAAE,eAAe,UAAU;EAC7B,MAAM,QAAQ,OAAO,KAAK,OAAO,CAAC,CAAC,KAAK,IAAI,KAAK;EACjD,GAAG,IACD,qBAAqB,OAAO,uBAAuB,YAAY,qCAAqC,MAAM,IAC5G;EACA,OAAO;CACT;CACA,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,MAAM,QAAQ,YAAY;CACzC,SAAS,KAAK;EACZ,GAAG,IACD,6BAA6B,YAAY,QAAQ,OAAO,UAAU,WAAW,GAAG,EAAE;CAEpF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MA,SAAS,SAAS,SAAgD;CAChE,KAAK,MAAM,UAAU,SACnB,IAAI;EACF,OAAO,cAAc,MAAM,CAAC,CAAC,QAAQ,aAAa;CACpD,QAAQ,CAER;AAGJ;;;;AAKA,SAAS,UAAU,OAAmD;CACpE,OAAO,OAAO,UAAU,YAAY,UAAU,OAAO,EAAE,GAAG,MAAM,IAAI,CAAC;AACvE;AAQA,IAFE,QAAQ,KAAK,OAAO,KAAA,KAAa,QAAQ,KAAK,OAAO,cAAc,YAAY,GAAG,GAE9D,gBAAqB,QAAQ,KAAK,MAAM,CAAC,CAAC"}
@@ -1,5 +1,4 @@
1
- import { O as aborted_error, h as wait_with_abort, m as compute_backoff, o as format_schema_issues, s as validate_schema } from "./core-BVCVUMmH.js";
2
- import { S as turn_timeout_error, _ as provider_required_error, a as normalize_local_usage, b as tool_approval_denied_error, c as engine_config_error, d as model_required_error, f as on_chunk_error, g as provider_not_configured_error, h as provider_error, i as missing_peer_error, l as engine_disposed_error, m as provider_capability_error, n as default_normalize_usage, o as resolve_transport, p as provider_auth_error, r as load_optional_peer, s as claude_cli_error, t as split_leading_system_run, u as incomplete_generation_error, v as rate_limit_error, x as tool_error, y as schema_validation_error } from "./leading_system-CfOIc5fi.js";
1
+ import { h as wait_with_abort, k as aborted_error, m as compute_backoff, o as format_schema_issues, s as validate_schema } from "./core-B-M7nAkg.js";
3
2
  import { join } from "node:path";
4
3
  import { mkdtempSync, writeFileSync } from "node:fs";
5
4
  import { tmpdir } from "node:os";
@@ -288,6 +287,214 @@ function compute_cost(usage, pricing, provider) {
288
287
  return breakdown;
289
288
  }
290
289
  //#endregion
290
+ //#region src/engine/errors.ts
291
+ var rate_limit_error = class extends Error {
292
+ kind = "rate_limit_error";
293
+ retry_after_ms;
294
+ attempts;
295
+ status;
296
+ constructor(message, metadata = {}) {
297
+ super(message);
298
+ this.name = "rate_limit_error";
299
+ this.retry_after_ms = metadata.retry_after_ms;
300
+ this.attempts = metadata.attempts ?? 0;
301
+ this.status = metadata.status;
302
+ }
303
+ };
304
+ var provider_error = class extends Error {
305
+ kind = "provider_error";
306
+ status;
307
+ body;
308
+ cause_kind;
309
+ constructor(message, metadata = {}) {
310
+ super(message);
311
+ this.name = "provider_error";
312
+ this.status = metadata.status;
313
+ this.body = metadata.body;
314
+ this.cause_kind = metadata.cause_kind;
315
+ }
316
+ };
317
+ /**
318
+ * Turn-timeout expiry. Thrown by the engine-owned retry_turn wrapper when a
319
+ * single invoke_turn exceeds `turn_timeout_ms` before any chunk streamed.
320
+ * Its `kind` is the RetryFailureKind wire value `'timeout'` (not the class
321
+ * name) on purpose: that is the discriminant classify_retryable /
322
+ * classify_provider_error already key on, so the shared classifier treats an
323
+ * expiry as retryable without any timeout-specific branch. A mid-stream
324
+ * expiry never reaches here; retry_turn converts it to a non-retryable
325
+ * stream interruption first.
326
+ */
327
+ var turn_timeout_error = class extends Error {
328
+ kind = "timeout";
329
+ timeout_ms;
330
+ step_index;
331
+ constructor(timeout_ms, step_index) {
332
+ super(`turn exceeded turn_timeout_ms budget of ${timeout_ms}ms`);
333
+ this.name = "turn_timeout_error";
334
+ this.timeout_ms = timeout_ms;
335
+ this.step_index = step_index;
336
+ }
337
+ };
338
+ var schema_validation_error = class extends Error {
339
+ kind = "schema_validation_error";
340
+ schema_issues;
341
+ raw_text;
342
+ constructor(message, schema_issues, raw_text) {
343
+ super(message);
344
+ this.name = "schema_validation_error";
345
+ this.schema_issues = schema_issues;
346
+ this.raw_text = raw_text;
347
+ }
348
+ };
349
+ var tool_error = class extends Error {
350
+ kind = "tool_error";
351
+ tool_name;
352
+ tool_call_id;
353
+ cause;
354
+ constructor(message, metadata) {
355
+ super(message);
356
+ this.name = "tool_error";
357
+ this.tool_name = metadata.tool_name;
358
+ this.tool_call_id = metadata.tool_call_id;
359
+ this.cause = metadata.cause;
360
+ }
361
+ };
362
+ var tool_approval_denied_error = class extends Error {
363
+ kind = "tool_approval_denied_error";
364
+ tool_name;
365
+ step_index;
366
+ tool_call_id;
367
+ constructor(message, metadata) {
368
+ super(message);
369
+ this.name = "tool_approval_denied_error";
370
+ this.tool_name = metadata.tool_name;
371
+ this.step_index = metadata.step_index;
372
+ this.tool_call_id = metadata.tool_call_id;
373
+ }
374
+ };
375
+ var model_required_error = class extends Error {
376
+ kind = "model_required_error";
377
+ constructor(message = "no model specified: pass `model` to generate() or set `defaults.model` on the engine") {
378
+ super(message);
379
+ this.name = "model_required_error";
380
+ }
381
+ };
382
+ /**
383
+ * A generate call named a provider the engine has no adapter for. Carries the
384
+ * configured names, and the message repeats them, so a typo is visible from
385
+ * the message alone rather than needing the engine config alongside it.
386
+ */
387
+ var provider_not_configured_error = class extends Error {
388
+ kind = "provider_not_configured_error";
389
+ provider;
390
+ configured;
391
+ constructor(provider, configured = []) {
392
+ const state = configured.length > 0 ? configured.join(", ") : "none";
393
+ super(`provider '${provider}' is not configured on this engine: pass it to create_engine({ providers }) (configured: ${state})`);
394
+ this.name = "provider_not_configured_error";
395
+ this.provider = provider;
396
+ this.configured = configured;
397
+ }
398
+ };
399
+ /**
400
+ * No provider could be resolved for a generate call: several providers are
401
+ * configured, the call named none, and no `defaults.provider` is set. Carries
402
+ * the configured provider names so the message tells the caller exactly what
403
+ * the engine can route to.
404
+ */
405
+ var provider_required_error = class extends Error {
406
+ kind = "provider_required_error";
407
+ configured;
408
+ constructor(configured) {
409
+ super(`no provider specified: pass \`provider\` to generate() or set \`defaults.provider\` (configured: ${configured.join(", ")})`);
410
+ this.name = "provider_required_error";
411
+ this.configured = configured;
412
+ }
413
+ };
414
+ var engine_config_error = class extends Error {
415
+ kind = "engine_config_error";
416
+ provider;
417
+ constructor(message, provider) {
418
+ super(message);
419
+ this.name = "engine_config_error";
420
+ this.provider = provider;
421
+ }
422
+ };
423
+ var on_chunk_error = class extends Error {
424
+ kind = "on_chunk_error";
425
+ cause;
426
+ constructor(message, cause) {
427
+ super(message);
428
+ this.name = "on_chunk_error";
429
+ this.cause = cause;
430
+ }
431
+ };
432
+ var provider_capability_error = class extends Error {
433
+ kind = "provider_capability_error";
434
+ provider;
435
+ capability;
436
+ constructor(provider, capability, detail) {
437
+ const suffix = detail !== void 0 ? `: ${detail}` : "";
438
+ super(`provider '${provider}' does not support '${capability}'${suffix}`);
439
+ this.name = "provider_capability_error";
440
+ this.provider = provider;
441
+ this.capability = capability;
442
+ }
443
+ };
444
+ var engine_disposed_error = class extends Error {
445
+ kind = "engine_disposed_error";
446
+ constructor(message = "engine has been disposed: build a new one with create_engine()") {
447
+ super(message);
448
+ this.name = "engine_disposed_error";
449
+ }
450
+ };
451
+ var claude_cli_error = class extends Error {
452
+ kind = "claude_cli_error";
453
+ reason;
454
+ status;
455
+ stderr_snippet;
456
+ constructor(reason, message, metadata = {}) {
457
+ super(message);
458
+ this.name = "claude_cli_error";
459
+ this.reason = reason;
460
+ this.status = metadata.status;
461
+ this.stderr_snippet = metadata.stderr_snippet;
462
+ }
463
+ };
464
+ var provider_auth_error = class extends Error {
465
+ kind = "provider_auth_error";
466
+ provider;
467
+ refresh_command;
468
+ constructor(provider, message, metadata = {}) {
469
+ super(message);
470
+ this.name = "provider_auth_error";
471
+ this.provider = provider;
472
+ this.refresh_command = metadata.refresh_command;
473
+ }
474
+ };
475
+ /**
476
+ * A generate call that set a schema finished for a reason other than 'stop'
477
+ * (content_filter, length, max_steps, tool_calls), so no schema-validated
478
+ * value exists and validation was never attempted. Carries the raw model text
479
+ * and the last provider-reported payload, so a guardrail trace or other
480
+ * block detail stays reachable from the catch. Distinct from
481
+ * schema_validation_error, which covers a response that completed normally
482
+ * and then failed validation after its repair attempts ran out.
483
+ */
484
+ var incomplete_generation_error = class extends Error {
485
+ kind = "incomplete_generation_error";
486
+ finish_reason;
487
+ raw_text;
488
+ provider_reported;
489
+ constructor(finish_reason, raw_text, provider_reported) {
490
+ super(`generation finished with '${finish_reason}' before a schema-validated response was produced`);
491
+ this.name = "incomplete_generation_error";
492
+ this.finish_reason = finish_reason;
493
+ this.raw_text = raw_text;
494
+ this.provider_reported = provider_reported;
495
+ }
496
+ };
497
+ //#endregion
291
498
  //#region src/engine/retry.ts
292
499
  const DEFAULT_RETRY = {
293
500
  max_attempts: 3,
@@ -509,6 +716,82 @@ function classify_retryable(err) {
509
716
  if (kind === "network" || kind === "timeout") return build_retryable_signal(err, kind);
510
717
  }
511
718
  //#endregion
719
+ //#region src/engine/providers/types.ts
720
+ /**
721
+ * Read the `transport` selector off a provider init. Defaults to 'ai_sdk';
722
+ * anything but the two known backends throws at construction so a typo
723
+ * fails loud instead of silently running the default.
724
+ */
725
+ function resolve_transport(init, provider) {
726
+ const raw = init["transport"];
727
+ if (raw === void 0 || raw === "ai_sdk") return "ai_sdk";
728
+ if (raw === "native") return "native";
729
+ throw new engine_config_error(`${provider} provider: transport must be 'ai_sdk' or 'native', got ${JSON.stringify(raw)}`, provider);
730
+ }
731
+ /**
732
+ * Map raw provider usage to UsageTotals, the mapper most adapters share.
733
+ *
734
+ * Missing usage zeroes the totals. Optional fields (reasoning and cache
735
+ * tokens) are set only when the raw payload carries them, reading the
736
+ * flattened field first and the AI SDK's *_details container second.
737
+ */
738
+ function default_normalize_usage(raw) {
739
+ if (raw === void 0) return {
740
+ input_tokens: 0,
741
+ output_tokens: 0
742
+ };
743
+ const totals = {
744
+ input_tokens: typeof raw.input_tokens === "number" ? raw.input_tokens : 0,
745
+ output_tokens: typeof raw.output_tokens === "number" ? raw.output_tokens : 0
746
+ };
747
+ if (typeof raw.reasoning_tokens === "number") totals.reasoning_tokens = raw.reasoning_tokens;
748
+ else if (typeof raw.output_token_details?.reasoning_tokens === "number") totals.reasoning_tokens = raw.output_token_details.reasoning_tokens;
749
+ if (typeof raw.cached_input_tokens === "number") totals.cached_input_tokens = raw.cached_input_tokens;
750
+ else if (typeof raw.input_token_details?.cached_tokens === "number") totals.cached_input_tokens = raw.input_token_details.cached_tokens;
751
+ if (typeof raw.cache_write_tokens === "number") totals.cache_write_tokens = raw.cache_write_tokens;
752
+ else if (typeof raw.input_token_details?.cache_creation_input_tokens === "number") totals.cache_write_tokens = raw.input_token_details.cache_creation_input_tokens;
753
+ return totals;
754
+ }
755
+ /**
756
+ * Usage mapper for local backends (Ollama, LM Studio) whose servers never
757
+ * report cache or reasoning tokens: default-normalize, then strip those
758
+ * fields so a stray *_details container cannot invent them.
759
+ */
760
+ function normalize_local_usage(raw) {
761
+ const base = default_normalize_usage(raw);
762
+ delete base.cached_input_tokens;
763
+ delete base.cache_write_tokens;
764
+ delete base.reasoning_tokens;
765
+ return base;
766
+ }
767
+ /**
768
+ * Build the standard missing-peer error: names the package and the install
769
+ * command so a missing peer is diagnosable from the message alone. Shared so
770
+ * every optional-peer failure reads identically, whether the failing
771
+ * `import()` names the peer directly (load_optional_peer below) or a local
772
+ * module that reaches the peer through its own static import (the ai_sdk
773
+ * turn seam in generate.ts, whose dynamic import must stay written in
774
+ * generate.ts for its relative specifier to resolve correctly).
775
+ */
776
+ function missing_peer_error(peer_name, cause) {
777
+ const message = `missing peer dependency '${peer_name}'. Install it with your package manager, e.g., \`pnpm add ${peer_name}\` or \`npm install ${peer_name}\`. Cause: ${cause instanceof Error ? cause.message : JSON.stringify(cause)}`;
778
+ return new Error(message, { cause });
779
+ }
780
+ /**
781
+ * Dynamically import an optional peer dependency, rethrowing an import
782
+ * failure via missing_peer_error so a missing peer is diagnosable from the
783
+ * message alone.
784
+ */
785
+ async function load_optional_peer(specifier) {
786
+ let mod;
787
+ try {
788
+ mod = await import(specifier);
789
+ } catch (err) {
790
+ throw missing_peer_error(specifier, err);
791
+ }
792
+ return mod;
793
+ }
794
+ //#endregion
512
795
  //#region src/engine/providers/native_shared.ts
513
796
  /**
514
797
  * The message under a JSON error envelope's `error` key, or undefined when
@@ -700,9 +983,7 @@ function map_messages_by_role(messages, wire) {
700
983
  case "assistant":
701
984
  out.push(wire.assistant(message.content));
702
985
  break;
703
- case "tool":
704
- out.push(wire.tool(message));
705
- break;
986
+ case "tool": out.push(wire.tool(message));
706
987
  }
707
988
  return out;
708
989
  }
@@ -888,13 +1169,11 @@ function to_anthropic_messages(messages) {
888
1169
  case "assistant":
889
1170
  push_blocks("assistant", to_assistant_blocks(message.content));
890
1171
  break;
891
- case "tool":
892
- push_blocks("user", [{
893
- type: "tool_result",
894
- tool_use_id: message.tool_call_id,
895
- content: message.content
896
- }]);
897
- break;
1172
+ case "tool": push_blocks("user", [{
1173
+ type: "tool_result",
1174
+ tool_use_id: message.tool_call_id,
1175
+ content: message.content
1176
+ }]);
898
1177
  }
899
1178
  return {
900
1179
  system: system_parts.length > 0 ? system_parts.join("\n\n") : void 0,
@@ -1241,7 +1520,6 @@ function create_stream_aggregator(step_index, dispatch) {
1241
1520
  });
1242
1521
  break;
1243
1522
  case "error": throw stream_event_error(event);
1244
- default: break;
1245
1523
  }
1246
1524
  },
1247
1525
  complete() {
@@ -1878,7 +2156,7 @@ const create_openai_adapter = (init) => {
1878
2156
  const create_openai_native_adapter = (init) => {
1879
2157
  const { api_key, base_url } = read_dialect_init(init, DEFAULT_BASE_URL$1);
1880
2158
  const organization = typeof init["organization"] === "string" ? init["organization"] : void 0;
1881
- return create_openai_compatible_adapter({
2159
+ const dialect = {
1882
2160
  name: "openai",
1883
2161
  base_url,
1884
2162
  auth: {
@@ -1889,7 +2167,8 @@ const create_openai_native_adapter = (init) => {
1889
2167
  stream_include_usage: true,
1890
2168
  tolerant_usage: false,
1891
2169
  ...organization !== void 0 ? { extra_headers: { "OpenAI-Organization": organization } } : {}
1892
- });
2170
+ };
2171
+ return create_openai_compatible_adapter(dialect);
1893
2172
  };
1894
2173
  /**
1895
2174
  * Build the OpenAI ai_sdk adapter: validates the required api_key and lazily
@@ -2495,7 +2774,7 @@ const create_openrouter_native_adapter = (init) => {
2495
2774
  const extra_headers = {};
2496
2775
  if (http_referer !== void 0) extra_headers["HTTP-Referer"] = http_referer;
2497
2776
  if (x_title !== void 0) extra_headers["X-Title"] = x_title;
2498
- return create_openai_compatible_adapter({
2777
+ const dialect = {
2499
2778
  name: "openrouter",
2500
2779
  base_url,
2501
2780
  auth: {
@@ -2506,7 +2785,8 @@ const create_openrouter_native_adapter = (init) => {
2506
2785
  stream_include_usage: true,
2507
2786
  tolerant_usage: false,
2508
2787
  ...Object.keys(extra_headers).length > 0 ? { extra_headers } : {}
2509
- });
2788
+ };
2789
+ return create_openai_compatible_adapter(dialect);
2510
2790
  };
2511
2791
  /**
2512
2792
  * Build the OpenRouter ai_sdk adapter: validates the required api_key and
@@ -2964,7 +3244,8 @@ function build_greywall_args(binary, sandbox) {
2964
3244
  * temp directory and return its path.
2965
3245
  */
2966
3246
  function write_greywall_settings(sandbox) {
2967
- const path = join(mkdtempSync(join(tmpdir(), `fascicle-greywall-${process.pid}-`)), "greywall.json");
3247
+ const dir = mkdtempSync(join(tmpdir(), `fascicle-greywall-${process.pid}-`));
3248
+ const path = join(dir, "greywall.json");
2968
3249
  const payload = {
2969
3250
  network: { allowHosts: [...sandbox.network_allowlist ?? []] },
2970
3251
  filesystem: { allowWrite: [...sandbox.additional_write_paths ?? []] }
@@ -3001,26 +3282,29 @@ function write_greywall_settings(sandbox) {
3001
3282
  const ALL_REGISTRIES = /* @__PURE__ */ new Set();
3002
3283
  let exit_handler_installed = false;
3003
3284
  /**
3004
- * Install the process-wide `exit` handler that SIGKILLs every live child
3005
- * across every spawn registry. Calling this more than once is a no-op.
3285
+ * SIGKILL every live child across every spawn registry.
3006
3286
  *
3007
3287
  * Children are spawned with `detached: true`, which makes each one the
3008
3288
  * leader of its own process group; signaling `-child.pid` (a negative pid)
3009
3289
  * targets the whole group instead of just the direct child, so any
3010
3290
  * grandchildren the CLI itself spawned die too.
3011
3291
  */
3292
+ function kill_live_children() {
3293
+ for (const reg of ALL_REGISTRIES) for (const child of reg) {
3294
+ if (child.pid === void 0 || child.exitCode !== null) continue;
3295
+ try {
3296
+ process.kill(-child.pid, "SIGKILL");
3297
+ } catch {}
3298
+ }
3299
+ }
3300
+ /**
3301
+ * Install the process-wide `exit` handler that kills every live child.
3302
+ * Calling this more than once is a no-op.
3303
+ */
3012
3304
  function install_exit_handler_once() {
3013
3305
  if (exit_handler_installed) return;
3014
3306
  exit_handler_installed = true;
3015
- const handler = () => {
3016
- for (const reg of ALL_REGISTRIES) for (const child of reg) {
3017
- if (child.pid === void 0 || child.exitCode !== null) continue;
3018
- try {
3019
- process.kill(-child.pid, "SIGKILL");
3020
- } catch {}
3021
- }
3022
- };
3023
- process.on("exit", handler);
3307
+ process.on("exit", kill_live_children);
3024
3308
  }
3025
3309
  /**
3026
3310
  * Build a `SpawnRuntime`: a per-adapter-instance registry of live children
@@ -3108,8 +3392,10 @@ function create_spawn_runtime() {
3108
3392
  const abort_listener = () => {
3109
3393
  escalate("abort");
3110
3394
  };
3111
- if (args.abort !== void 0) if (args.abort.aborted) abort_listener();
3112
- else args.abort.addEventListener("abort", abort_listener, { once: true });
3395
+ if (args.abort !== void 0) {
3396
+ if (args.abort.aborted) abort_listener();
3397
+ else args.abort.addEventListener("abort", abort_listener, { once: true });
3398
+ }
3113
3399
  const close_promise = new Promise((resolve) => {
3114
3400
  child.on("close", (code, signal) => {
3115
3401
  clear_all_timers();
@@ -4683,8 +4969,10 @@ function link_caller_abort(in_flight, caller_abort) {
4683
4969
  const on_caller_abort = () => {
4684
4970
  controller.abort(caller_abort?.reason);
4685
4971
  };
4686
- if (caller_abort !== void 0) if (caller_abort.aborted) controller.abort(caller_abort.reason);
4687
- else caller_abort.addEventListener("abort", on_caller_abort, { once: true });
4972
+ if (caller_abort !== void 0) {
4973
+ if (caller_abort.aborted) controller.abort(caller_abort.reason);
4974
+ else caller_abort.addEventListener("abort", on_caller_abort, { once: true });
4975
+ }
4688
4976
  return {
4689
4977
  controller,
4690
4978
  unlink: () => {
@@ -4961,6 +5249,48 @@ function get_provider_factory(name) {
4961
5249
  return factory;
4962
5250
  }
4963
5251
  //#endregion
5252
+ //#region src/engine/leading_system.ts
5253
+ /**
5254
+ * Collapse a leading run of system messages into a single joined string,
5255
+ * returning the remaining messages.
5256
+ *
5257
+ * Both message paths hoist a leading system run out of their list the same way:
5258
+ * the engine-Message side (generate.ts split_leading_system_messages) hands the
5259
+ * run to a native adapter's TurnRequest.system, and the AI SDK side
5260
+ * (providers/ai_sdk/invoke.ts split_leading_system) hands it to the SDK's
5261
+ * top-level `instructions` option. Same guard, same '\n\n' join, and the same
5262
+ * "return the list untouched when hoisting would leave `messages` empty" rule,
5263
+ * since provider APIs reject an empty messages array. They differ only in the
5264
+ * element type and how a system message's text is read, so each caller supplies
5265
+ * `system_text`; the traversal and its guards live here once.
5266
+ */
5267
+ function split_leading_system_run(messages, system_text) {
5268
+ let run_end = 0;
5269
+ const system_parts = [];
5270
+ while (run_end < messages.length) {
5271
+ const m = messages[run_end];
5272
+ if (!is_leading_system(m)) break;
5273
+ system_parts.push(system_text(m));
5274
+ run_end += 1;
5275
+ }
5276
+ const rest = messages.slice(run_end);
5277
+ if (system_parts.length === 0 || rest.length === 0) return { messages: [...messages] };
5278
+ return {
5279
+ system: system_parts.join("\n\n"),
5280
+ messages: rest
5281
+ };
5282
+ }
5283
+ /**
5284
+ * Narrow a possibly undefined message to the system member of its union.
5285
+ *
5286
+ * A cast-free type guard so `split_leading_system_run` can hand the narrowed
5287
+ * message straight to `system_text` without a `T`-eroding assertion; the
5288
+ * optional chain covers the out-of-bounds `undefined` the index access yields.
5289
+ */
5290
+ function is_leading_system(m) {
5291
+ return m?.role === "system";
5292
+ }
5293
+ //#endregion
4964
5294
  //#region src/engine/merge_defaults.ts
4965
5295
  /**
4966
5296
  * Default-merging helpers for engine-level `EngineDefaults`.
@@ -6634,7 +6964,7 @@ async function build_ai_sdk_transport(cfg) {
6634
6964
  const provider_options = combined_provider_options !== void 0 && Object.keys(combined_provider_options).length > 0 ? combined_provider_options : void 0;
6635
6965
  let ai_sdk_invoke_mod;
6636
6966
  try {
6637
- ai_sdk_invoke_mod = await import("./invoke-BcPDqE5C.js");
6967
+ ai_sdk_invoke_mod = await import("./invoke-CIdhjChw.js");
6638
6968
  } catch (err) {
6639
6969
  throw missing_peer_error("ai", err);
6640
6970
  }
@@ -7198,6 +7528,6 @@ function create_engine(config) {
7198
7528
  };
7199
7529
  }
7200
7530
  //#endregion
7201
- export { create_engine as t };
7531
+ export { schema_validation_error as _, claude_cli_error as a, incomplete_generation_error as c, provider_auth_error as d, provider_capability_error as f, rate_limit_error as g, provider_required_error as h, load_optional_peer as i, model_required_error as l, provider_not_configured_error as m, split_leading_system_run as n, engine_config_error as o, provider_error as p, default_normalize_usage as r, engine_disposed_error as s, create_engine as t, on_chunk_error as u, tool_approval_denied_error as v, tool_error as y };
7202
7532
 
7203
- //# sourceMappingURL=engine-Ct4LBzb9.js.map
7533
+ //# sourceMappingURL=engine-BRzVcTBB.js.map