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":"testing.js","names":[],"sources":["../src/testing/engine_from_generate.ts","../src/testing/make_capture_engine.ts","../src/testing/canned.ts","../src/testing/make_script_engine.ts","../src/testing/make_stub_engine.ts","../src/testing/text_of.ts"],"sourcesContent":["/**\n * Wrap a canned `generate` function in a complete `Engine`.\n *\n * The remaining members are inert: pricing calls are no-ops that resolve\n * nothing, `dispose` resolves immediately, and `with_providers` throws\n * because a canned engine has no provider registry to derive from. Both\n * testing factories share this shell so a test double differs from a real\n * engine only in how `generate` answers.\n */\n\nimport type { Engine } from '#engine'\n\n/**\n * Build an `Engine` whose only live member is the supplied `generate`.\n *\n * A custom double MUST implement only `generate`: accept `GenerateOptions`\n * and resolve a complete `GenerateResult` (content, tool_calls, steps,\n * usage, finish_reason, model_resolved). Honoring `opts.abort`,\n * `opts.on_chunk`, and `opts.schema` is optional; honor whichever the code\n * under test exercises. It need NOT implement pricing, `with_providers`, or\n * `dispose`: this shell supplies the inert versions.\n */\nexport function engine_from_generate(generate: Engine['generate']): Engine {\n return {\n generate,\n register_price: () => {},\n resolve_price: () => undefined,\n list_prices: () => ({}),\n with_providers: () => {\n throw new Error('testing engines do not support with_providers')\n },\n dispose: async () => {},\n }\n}\n","/**\n * make_capture_engine: an `Engine` that records every generate call.\n *\n * Returns the engine together with the live `calls` array, which receives\n * the `GenerateOptions` of each call in order. Every call resolves with the\n * same canned result (`options.result`, or a minimal `'ok'` result), so the\n * double is for asserting what reached the engine, not for scripting\n * multi-role conversations: that is `make_stub_engine`'s job.\n *\n * `options.on_generate` runs after the call is recorded and is awaited\n * before the result resolves, which is the hook for driving streaming\n * chunks, spans, or aborts against the captured options.\n */\n\nimport type { Engine, GenerateOptions, GenerateResult } from '#engine'\nimport { engine_from_generate } from './engine_from_generate.js'\n\nexport type CaptureEngineOptions = {\n readonly result?: GenerateResult<unknown>\n readonly on_generate?: (opts: GenerateOptions) => Promise<void> | void\n}\n\nexport type CaptureEngine = {\n readonly engine: Engine\n readonly calls: GenerateOptions[]\n}\n\nconst DEFAULT_RESULT: GenerateResult<unknown> = {\n content: 'ok',\n tool_calls: [],\n steps: [],\n usage: { input_tokens: 1, output_tokens: 1 },\n finish_reason: 'stop',\n model_resolved: { provider: 'stub', model_id: 'capture' },\n}\n\n/**\n * Build an `Engine` that records each call's `GenerateOptions` into the\n * returned `calls` array and answers with the canned result.\n */\nexport function make_capture_engine(options: CaptureEngineOptions = {}): CaptureEngine {\n const calls: GenerateOptions[] = []\n const result = options.result ?? DEFAULT_RESULT\n\n const engine = engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const loose = opts as GenerateOptions\n calls.push(loose)\n if (options.on_generate) await options.on_generate(loose)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return result as GenerateResult<t>\n },\n )\n return { engine, calls }\n}\n","/**\n * Shared plumbing for the canned engine doubles.\n *\n * make_stub_engine and make_script_engine answer calls from fixtures rather\n * than a provider, but the surrounding contract stays the engine's: a call\n * under an already-aborted signal throws `aborted_error`, a streaming caller\n * sees chunks before the result resolves, and content that fails the\n * caller's schema surfaces as `schema_validation_error` carrying the issues.\n * Keeping that contract here keeps every double interchangeable with a real\n * engine at the seams tests exercise.\n */\n\nimport { aborted_error, schema_validation_error } from '#engine'\nimport type { FinishReason, GenerateOptions, UsageTotals } from '#engine'\n\nexport const DEFAULT_USAGE: UsageTotals = { input_tokens: 40, output_tokens: 20 }\n\n/**\n * Mirror the engine's entry guard: a generate call under an already-aborted\n * signal never reaches a provider, so a double must refuse it the same way\n * for cancellation tests to be trustworthy.\n */\nexport function throw_if_aborted(abort: AbortSignal | undefined): void {\n if (abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: abort.reason })\n }\n}\n\n/**\n * Render canned content as the text a provider would have put on the wire:\n * strings pass through, everything else is serialized as JSON (which is what\n * a schema-bearing call would have streamed).\n */\nfunction render_text(content: unknown): string {\n if (typeof content === 'string') return content\n return JSON.stringify(content) ?? ''\n}\n\n/**\n * Emit the minimal chunk sequence a streaming caller expects: the whole\n * content as one text chunk, then the finish marker. Enough for model_chunk\n * trajectory events and stream-consuming UIs to fire without a network.\n */\nexport async function emit_chunks(\n on_chunk: GenerateOptions['on_chunk'],\n content: unknown,\n finish_reason: FinishReason,\n usage: UsageTotals,\n): Promise<void> {\n if (on_chunk === undefined) return\n await on_chunk({ kind: 'text', text: render_text(content), step_index: 0 })\n await on_chunk({ kind: 'finish', finish_reason, usage })\n}\n\ntype CannedIssue = {\n readonly message: string\n readonly path?: ReadonlyArray<PropertyKey>\n}\n\n/**\n * Render issues as one `path: message` line per issue, dotted the same way\n * the engine's own repair prompts and error messages format them.\n */\nfunction format_issues(issues: ReadonlyArray<CannedIssue>): string {\n return issues\n .map((issue) =>\n issue.path === undefined || issue.path.length === 0\n ? issue.message\n : `${issue.path.map(String).join('.')}: ${issue.message}`,\n )\n .join('; ')\n}\n\n/**\n * Validate canned content through the caller's schema, throwing the engine's\n * own `schema_validation_error` on failure so `instanceof` handling in the\n * code under test sees exactly what a real engine throws when its repair\n * attempts run out. Absent a schema, the content passes through untouched.\n */\nexport async function validate_canned(\n schema: GenerateOptions<unknown>['schema'],\n content: unknown,\n described: string,\n): Promise<unknown> {\n if (schema === undefined) return content\n const checked = await schema['~standard'].validate(content)\n if (checked.issues !== undefined) {\n // The spec allows a path segment to be a bare key or a `{ key }` wrapper;\n // normalize to bare keys so schema_issues reads one shape, as the real\n // engine's validator does.\n const issues: CannedIssue[] = checked.issues.map((issue) =>\n issue.path === undefined\n ? { message: issue.message }\n : {\n message: issue.message,\n path: issue.path.map((segment) =>\n typeof segment === 'object' ? segment.key : segment,\n ),\n },\n )\n throw new schema_validation_error(\n `${described} failed the caller's schema: ${format_issues(issues)}`,\n issues,\n render_text(content),\n )\n }\n return checked.value\n}\n","/**\n * make_script_engine: a queue of canned responses consumed in call order.\n *\n * Where make_stub_engine routes by system-prompt prefix and cannot tell\n * call 3 from call 1, a script cares only about order: the first generate\n * call gets the first entry, the second the next, and a call past the end\n * throws naming how many responses were scripted versus received, so a flow\n * that makes an unexpected extra model call fails loudly. That makes it the\n * double for loops that must converge, retry paths, and flows whose calls a\n * prefix cannot distinguish (a markdown-only define_agent sends no system\n * prompt at all, so every call looks alike to a stub).\n *\n * An entry is plain content, or a `ScriptResponse` object when the call\n * should carry tool calls, report a different finish reason or usage, or\n * throw a scripted error (a rate_limit_error, a provider_error) instead of\n * answering. Only an object whose keys ALL belong to the ScriptResponse\n * shape is treated as scripted; any other value, `{ verdict: 'ship' }`\n * included, becomes content as-is. Wrap literal content that collides with\n * the shape in `{ content }`.\n *\n * Scripted content is validated through the caller's schema, and the abort\n * and on_chunk contracts match make_stub_engine's; see ./canned.ts.\n */\n\nimport type {\n Engine,\n FinishReason,\n GenerateOptions,\n GenerateResult,\n ToolCallRecord,\n UsageTotals,\n} from '#engine'\nimport { DEFAULT_USAGE, emit_chunks, throw_if_aborted, validate_canned } from './canned.js'\nimport { engine_from_generate } from './engine_from_generate.js'\n\nexport type ScriptResponse = {\n readonly content?: unknown\n readonly tool_calls?: ReadonlyArray<ToolCallRecord>\n readonly finish_reason?: FinishReason\n readonly usage?: UsageTotals\n /** An error to throw for this call instead of answering. */\n readonly throw?: Error\n}\n\nexport type ScriptEngineOptions = {\n readonly usage?: UsageTotals\n readonly model_id?: string\n}\n\nconst SCRIPT_KEYS = new Set(['content', 'tool_calls', 'finish_reason', 'usage', 'throw'])\n\n/**\n * Decide whether a queue entry is a ScriptResponse or plain content. Only a\n * non-null, non-array object whose keys all belong to the ScriptResponse\n * shape is scripted, so an arbitrary content fixture with its own keys\n * passes through untouched rather than being half-read as a script entry.\n */\nfunction is_script_response(entry: unknown): entry is ScriptResponse {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return false\n const keys = Object.keys(entry)\n return keys.length > 0 && keys.every((key) => SCRIPT_KEYS.has(key))\n}\n\n/**\n * Build an `Engine` that answers generate calls strictly in call order from\n * `responses`, throwing once the queue is exhausted.\n *\n * `options` mirrors make_stub_engine's: `usage` is the default usage for\n * entries that do not set their own (default `{ input_tokens: 40,\n * output_tokens: 20 }`) and `model_id` sets `model_resolved.model_id`\n * (default `'script'`). The provider always reports as `'stub'`.\n */\nexport function make_script_engine(\n responses: ReadonlyArray<unknown>,\n options: ScriptEngineOptions = {},\n): Engine {\n const default_usage = options.usage ?? DEFAULT_USAGE\n const model_id = options.model_id ?? 'script'\n let call_count = 0\n\n return engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n throw_if_aborted(opts.abort)\n call_count += 1\n const index = call_count - 1\n if (index >= responses.length) {\n throw new Error(\n `make_script_engine: script exhausted: ${responses.length} response(s) scripted, call ${call_count} received`,\n )\n }\n const entry = responses[index]\n const scripted: ScriptResponse = is_script_response(entry) ? entry : { content: entry }\n if (scripted.throw !== undefined) throw scripted.throw\n const usage = scripted.usage ?? default_usage\n const finish_reason = scripted.finish_reason ?? 'stop'\n // Chunks carry the raw scripted content, before validation, mirroring a\n // real stream where text flows and only then gets validated.\n await emit_chunks(opts.on_chunk, scripted.content, finish_reason, usage)\n const content = await validate_canned(\n opts.schema,\n scripted.content,\n `make_script_engine: scripted response ${index}`,\n )\n return {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n content: content as t,\n tool_calls: scripted.tool_calls === undefined ? [] : [...scripted.tool_calls],\n steps: [],\n usage,\n finish_reason,\n model_resolved: { provider: 'stub', model_id },\n }\n },\n )\n}\n","/**\n * make_stub_engine: a canned, network-free `Engine` for tests and demos.\n *\n * Each generate call is routed by the system prompt's stable first line:\n * the first canned response whose `prefix` the system prompt starts with\n * answers the call, and an unmatched system throws, so a flow that grows a\n * new model boundary fails loudly instead of silently reusing a fixture.\n * A response with the empty-string prefix matches every call, which is the\n * single-model-boundary case.\n *\n * A response's `content` may be a function of `(opts, call_index)` for\n * routes a flow hits more than once (a converging loop, a judged retry):\n * `call_index` counts how many times that route has matched before,\n * starting at 0, so each pass can answer differently.\n *\n * Canned content is validated through the caller's own schema\n * (`opts.schema['~standard'].validate`), so fixtures cannot drift from the\n * contracts they stand in for. A failure throws the engine's own\n * `schema_validation_error` carrying the issues and the canned content as\n * `raw_text`, exactly what a real engine throws when repair attempts run\n * out, so `instanceof` handling in the code under test stays testable.\n *\n * The engine's streaming and cancellation contract holds too: an\n * already-aborted `opts.abort` throws `aborted_error`, and a provided\n * `opts.on_chunk` receives the canned content as a text chunk plus a finish\n * chunk before the result resolves.\n */\n\nimport type { Engine, GenerateOptions, GenerateResult, UsageTotals } from '#engine'\nimport { DEFAULT_USAGE, emit_chunks, throw_if_aborted, validate_canned } from './canned.js'\nimport { engine_from_generate } from './engine_from_generate.js'\n\n/**\n * The function form of canned content: called with the routed call's options\n * and how many times this prefix route has matched before (starting 0). May\n * be async; the returned value is validated and answered like static content.\n */\nexport type StubContentFn = (opts: GenerateOptions, call_index: number) => unknown\n\nexport type StubResponse = {\n readonly prefix: string\n /** Static content, or a `StubContentFn` invoked per matched call. */\n readonly content: unknown\n}\n\nexport type StubEngineOptions = {\n readonly usage?: UsageTotals\n readonly model_id?: string\n}\n\n/**\n * Build an `Engine` that answers every generate call from `canned`,\n * routed by system-prompt prefix.\n *\n * `options.usage` sets the usage totals reported on every result (default\n * `{ input_tokens: 40, output_tokens: 20 }`, so cost lines render non-zero\n * numbers); `options.model_id` sets `model_resolved.model_id` (default\n * `'stub'`). The provider always reports as `'stub'`.\n */\nexport function make_stub_engine(\n canned: ReadonlyArray<StubResponse>,\n options: StubEngineOptions = {},\n): Engine {\n const usage = options.usage ?? DEFAULT_USAGE\n const model_id = options.model_id ?? 'stub'\n const match_counts = new Map<StubResponse, number>()\n\n return engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n throw_if_aborted(opts.abort)\n const system = opts.system ?? ''\n const match = canned.find((c) => system.startsWith(c.prefix))\n if (match === undefined) {\n throw new Error(`make_stub_engine: no canned response for system: ${system || '(none)'}`)\n }\n const call_index = match_counts.get(match) ?? 0\n match_counts.set(match, call_index + 1)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const loose = opts as GenerateOptions\n const produced =\n typeof match.content === 'function'\n ? // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n await (match.content as StubContentFn)(loose, call_index)\n : match.content\n // Chunks carry the raw canned content, before validation, mirroring a\n // real stream where text flows and only then gets validated.\n await emit_chunks(opts.on_chunk, produced, 'stop', usage)\n const content = await validate_canned(\n opts.schema,\n produced,\n `make_stub_engine: canned response for prefix '${match.prefix}'`,\n )\n return {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n content: content as t,\n tool_calls: [],\n steps: [],\n usage,\n finish_reason: 'stop',\n model_resolved: { provider: 'stub', model_id },\n }\n },\n )\n}\n","/**\n * text_of: the user-visible prompt text of a captured GenerateOptions.\n *\n * Capture assertions care about what the model was asked, not how the prompt\n * was encoded. A prompt is a bare string or a Message[] whose user turns\n * carry either a string or typed content parts; navigating\n * `calls[0].prompt[0].content[0].text` by hand couples every assertion to\n * one encoding. System and assistant text are excluded on purpose: assert\n * those through `opts.system` and the raw messages.\n */\n\nimport type { GenerateOptions } from '#engine'\n\n/**\n * Flatten the prompt's user-facing text into one string: a string prompt\n * verbatim, otherwise every user turn's text (string content, or the `text`\n * parts of a content-part array) joined with newlines. Total: absent or\n * non-text content yields ''.\n */\nexport function text_of<t = unknown>(opts: GenerateOptions<t>): string {\n if (typeof opts.prompt === 'string') return opts.prompt\n const texts: string[] = []\n for (const message of opts.prompt) {\n if (message.role !== 'user') continue\n if (typeof message.content === 'string') {\n texts.push(message.content)\n continue\n }\n for (const part of message.content) {\n if (part.type === 'text') texts.push(part.text)\n }\n }\n return texts.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,SAAgB,qBAAqB,UAAsC;CACzE,OAAO;EACL;EACA,sBAAsB,CAAC;EACvB,qBAAqB,KAAA;EACrB,oBAAoB,CAAC;EACrB,sBAAsB;GACpB,MAAM,IAAI,MAAM,+CAA+C;EACjE;EACA,SAAS,YAAY,CAAC;CACxB;AACF;;;ACNA,MAAM,iBAA0C;CAC9C,SAAS;CACT,YAAY,CAAC;CACb,OAAO,CAAC;CACR,OAAO;EAAE,cAAc;EAAG,eAAe;CAAE;CAC3C,eAAe;CACf,gBAAgB;EAAE,UAAU;EAAQ,UAAU;CAAU;AAC1D;;;;;AAMA,SAAgB,oBAAoB,UAAgC,CAAC,GAAkB;CACrF,MAAM,QAA2B,CAAC;CAClC,MAAM,SAAS,QAAQ,UAAU;CAYjC,OAAO;EAAE,QAVM,qBACb,OAAmB,SAAyD;GAE1E,MAAM,QAAQ;GACd,MAAM,KAAK,KAAK;GAChB,IAAI,QAAQ,aAAa,MAAM,QAAQ,YAAY,KAAK;GAExD,OAAO;EACT,CAEY;EAAG;CAAM;AACzB;;;;;;;;;;;;;;ACxCA,MAAa,gBAA6B;CAAE,cAAc;CAAI,eAAe;AAAG;;;;;;AAOhF,SAAgB,iBAAiB,OAAsC;CACrE,IAAI,OAAO,YAAY,MACrB,MAAM,IAAI,cAAc,WAAW,EAAE,QAAQ,MAAM,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AM,OAAO,WAAW,EAAE,MAAM,CAAC;EAC5D,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,oDAAoD,UAAU,UAAU;EAE1F,MAAM,aAAa,aAAa,IAAI,KAAK,KAAK;EAC9C,aAAa,IAAI,OAAO,aAAa,CAAC;EAEtC,MAAM,QAAQ;EACd,MAAM,WACJ,OAAO,MAAM,YAAY,aAErB,MAAO,MAAM,QAA0B,OAAO,UAAU,IACxD,MAAM;EAGZ,MAAM,YAAY,KAAK,UAAU,UAAU,QAAQ,KAAK;EAMxD,OAAO;GAEL,SAAS,MAPW,gBACpB,KAAK,QACL,UACA,iDAAiD,MAAM,OAAO,EAChE;GAIE,YAAY,CAAC;GACb,OAAO,CAAC;GACR;GACA,eAAe;GACf,gBAAgB;IAAE,UAAU;IAAQ;GAAS;EAC/C;CACF,CACF;AACF;;;;;;;;;ACpFA,SAAgB,QAAqB,MAAkC;CACrE,IAAI,OAAO,KAAK,WAAW,UAAU,OAAO,KAAK;CACjD,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,WAAW,KAAK,QAAQ;EACjC,IAAI,QAAQ,SAAS,QAAQ;EAC7B,IAAI,OAAO,QAAQ,YAAY,UAAU;GACvC,MAAM,KAAK,QAAQ,OAAO;GAC1B;EACF;EACA,KAAK,MAAM,QAAQ,QAAQ,SACzB,IAAI,KAAK,SAAS,QAAQ,MAAM,KAAK,KAAK,IAAI;CAElD;CACA,OAAO,MAAM,KAAK,IAAI;AACxB"}
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/engine_from_generate.ts","../src/testing/checkpoint_store_conformance.ts","../src/testing/make_capture_engine.ts","../src/testing/canned.ts","../src/testing/make_script_engine.ts","../src/testing/make_stub_engine.ts","../src/testing/text_of.ts"],"sourcesContent":["/**\n * Wrap a canned `generate` function in a complete `Engine`.\n *\n * The remaining members are inert: pricing calls are no-ops that resolve\n * nothing, `dispose` resolves immediately, and `with_providers` throws\n * because a canned engine has no provider registry to derive from. Both\n * testing factories share this shell so a test double differs from a real\n * engine only in how `generate` answers.\n */\n\nimport type { Engine } from '#engine'\n\n/**\n * Build an `Engine` whose only live member is the supplied `generate`.\n *\n * A custom double MUST implement only `generate`: accept `GenerateOptions`\n * and resolve a complete `GenerateResult` (content, tool_calls, steps,\n * usage, finish_reason, model_resolved). Honoring `opts.abort`,\n * `opts.on_chunk`, and `opts.schema` is optional; honor whichever the code\n * under test exercises. It need NOT implement pricing, `with_providers`, or\n * `dispose`: this shell supplies the inert versions.\n */\nexport function engine_from_generate(generate: Engine['generate']): Engine {\n return {\n generate,\n register_price: () => {},\n resolve_price: () => undefined,\n list_prices: () => ({}),\n with_providers: () => {\n throw new Error('testing engines do not support with_providers')\n },\n dispose: async () => {},\n }\n}\n","/**\n * checkpoint_store_conformance: prove that a store keeps the\n * `CheckpointStore` contract.\n *\n * A store is three small functions, and their semantics are the subtle part.\n * A damaged value has to read as a miss rather than throw, two keys can't\n * share storage just because they encode alike, and a claim has to refuse a\n * second owner even when both ask at the same moment. The suite runs every\n * check against a fresh store from `make_store`, adds the scope and claim\n * checks when the store offers those capabilities, and reports what passed,\n * what failed, and what it skipped. It returns that report instead of\n * registering tests, so it works under any test runner: assert that `failed`\n * is empty.\n */\n\nimport type { CheckpointStore, ScopedCheckpointStore } from '#core'\n\nexport type StoreConformanceOptions = {\n /**\n * Damage the value stored at `key` the way a torn write or a bad disk\n * would. Given, the suite checks that a damaged value reads as a miss.\n */\n readonly corrupt?: (store: CheckpointStore, key: string) => Promise<void> | void\n /**\n * The claim lifetime, in milliseconds, of the checks that wait for a claim\n * to expire. A store with a coarse clock may need it longer. Default 200.\n */\n readonly ttl_ms?: number\n}\n\nexport type StoreConformanceFailure = {\n readonly check: string\n readonly message: string\n}\n\nexport type StoreConformanceReport = {\n readonly passed: ReadonlyArray<string>\n readonly failed: ReadonlyArray<StoreConformanceFailure>\n readonly skipped: ReadonlyArray<string>\n}\n\ntype CheckEnv = {\n readonly ttl_ms: number\n readonly corrupt: (store: CheckpointStore, key: string) => Promise<void> | void\n}\n\ntype Check = {\n readonly name: string\n readonly run: (store: CheckpointStore, env: CheckEnv) => Promise<void>\n}\n\ntype Suite = {\n readonly checks: ReadonlyArray<Check>\n readonly applies: (store: CheckpointStore, options: StoreConformanceOptions) => boolean\n}\n\ntype Claims = {\n readonly claim: (key: string, owner: string, ttl_ms: number) => Promise<boolean>\n readonly release: (key: string, owner: string) => Promise<void>\n}\n\nconst DEFAULT_TTL_MS = 200\n\n// Long enough that no check outlives it, so a claim taken with it stays held\n// for the whole check.\nconst HELD_MS = 60_000\n\nconst RACERS = 8\n\n// Stryker disable StringLiteral: the checks need their keys, prefixes, and\n// owners to differ from one another and nothing more, which any distinct\n// strings do, so trading one for another can't change what a check proves.\nconst KEY = 'k'\nconst MISSING = 'never-set'\nconst NULL_KEY = 'null'\nconst UNDEFINED_KEY = 'undefined'\nconst RACE_KEY = 'race'\nconst DAMAGED_KEY = 'damaged'\nconst CLAIMED_ONLY = 'claimed-only'\nconst UNCLAIMED = 'never-claimed'\nconst A = 'a'\nconst B = 'b'\nconst CHILD = 'child'\nconst INNER = 'inner'\nconst UNUSED = 'never-used'\nconst FIRST = 'first'\nconst SECOND = 'second'\nconst THIRD = 'third'\n// Stryker restore StringLiteral\n\nconst FRESH_SCOPE_CLAIM_REFUSED = 'a claim inside a fresh scope returned false'\nconst FREE_CLAIM_REFUSED = 'a claim on a key nobody holds returned false'\nconst RENEWAL_REFUSED = 'the owner could not renew its own live claim'\n\nconst SAMPLES: ReadonlyArray<unknown> = [\n { candidate: 'a', converged: true, rounds: 2 },\n { nested: { list: [1, 'two', { three: 3 }], empty: {} } },\n [1, 2, 3],\n [],\n {},\n 'plain text',\n '',\n 'unicode: naïve café, 世界, 🔑',\n 0,\n -1.5,\n true,\n false,\n]\n\n// Strings a naive encoder would merge: separators that slug to the same\n// character, case, path segments, and long strings that differ only at the\n// end.\nconst LOOKALIKES: ReadonlyArray<string> = [\n 'a/b',\n 'a_b',\n 'a:b',\n 'a b',\n 'A/B',\n 'a/b/',\n '../a',\n '.',\n '..',\n '鍵',\n '🔑',\n `${'k'.repeat(200)}1`,\n `${'k'.repeat(200)}2`,\n]\n\n// Prefixes a nested scope `a` then `b` could be confused with by a store\n// that joins prefixes into one string.\nconst FLATTENED = ['a/b', 'ab', 'a.b', 'a:b', 'b']\n\n// Prefixes that begin the way `a` does, or match it but for case, which a\n// store that clears scope `a` by deleting everything under a raw prefix (or a\n// case-blind one) sweeps away with it.\nconst BESIDE_A = ['a/b', 'a/', 'ab', 'a.b', 'a b', 'A']\n\n/**\n * Throw a check failure carrying `message` unless `condition` holds.\n */\nfunction ensure(condition: boolean, message: string): void {\n if (!condition) throw new Error(message)\n}\n\n/**\n * True for what the contract counts as a miss: `null` or `undefined`.\n */\nfunction is_miss(value: unknown): boolean {\n return value === null || value === undefined\n}\n\n/**\n * Render a value for a failure message, cut short so a large one stays\n * readable.\n */\nfunction show(value: unknown): string {\n const text: string | undefined = JSON.stringify(value)\n const shown = text ?? String(value)\n return shown.length > 80 ? `${shown.slice(0, 77)}...` : shown\n}\n\n/**\n * Serialize a value with its object keys sorted, so two values compare equal\n * when a store hands back the same data in a different key order (Postgres\n * `jsonb` does).\n */\nfunction canonical(value: unknown): string | undefined {\n const text: string | undefined = JSON.stringify(sort_keys(value))\n return text\n}\n\n/**\n * Copy a JSON value with every object's keys in sorted order.\n */\nfunction sort_keys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sort_keys)\n if (typeof value !== 'object' || value === null) return value\n // Stryker disable next-line EqualityOperator: object keys are unique, so `<=` sorts like `<`, and a reversed sort is applied to both sides of every comparison.\n const entries = Object.entries(value).toSorted(([x], [y]) => (x < y ? -1 : 1))\n return Object.fromEntries(entries.map(([k, v]) => [k, sort_keys(v)]))\n}\n\n/**\n * Wait `ms` milliseconds.\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Open the scope at `prefix`, or fail the check when the store handed to it\n * has no `scope` (a `make_store` whose stores don't all offer the same\n * capabilities).\n */\nfunction scope_of(store: CheckpointStore, prefix: string): ScopedCheckpointStore {\n if (store.scope === undefined) throw new Error('make_store returned a store without scope')\n return store.scope(prefix)\n}\n\n/**\n * The store's claim pair, or a failure naming the half that's missing. Both\n * are called on the store itself, the way `durable` calls them, so a store\n * whose methods lean on `this` works here too.\n */\nfunction claims_of(store: CheckpointStore): Claims {\n const { claim, release } = store\n if (claim === undefined && release === undefined) {\n throw new Error('the store has neither claim nor release')\n }\n if (claim === undefined) throw new Error('the store offers release without claim')\n if (release === undefined) throw new Error('the store offers claim without release')\n return {\n claim: (key, owner, ttl_ms) => claim.call(store, key, owner, ttl_ms),\n release: (key, owner) => release.call(store, key, owner),\n }\n}\n\n/**\n * Claim `key` for many owners at the same moment and count the winners.\n */\nasync function race_for(claims: Claims, key: string): Promise<number> {\n const owners = Array.from({ length: RACERS }, (_, i) => `racer-${i}`)\n const won = await Promise.all(owners.map((owner) => claims.claim(key, owner, HELD_MS)))\n return won.filter(Boolean).length\n}\n\nconst CONTRACT_CHECKS: ReadonlyArray<Check> = [\n {\n name: 'a missing key reads as a miss',\n run: async (store) => {\n const value = await store.get(MISSING)\n ensure(is_miss(value), `get on a key nobody set returned ${show(value)}`)\n },\n },\n {\n name: 'values round-trip as JSON',\n run: async (store) => {\n await Promise.all(SAMPLES.map((sample, i) => store.set(`sample-${i}`, sample)))\n const read = await Promise.all(SAMPLES.map((_, i) => store.get(`sample-${i}`)))\n SAMPLES.forEach((sample, i) => {\n ensure(\n canonical(read[i]) === canonical(sample),\n `set ${show(sample)} and got back ${show(read[i])}`,\n )\n })\n },\n },\n {\n name: 'set overwrites a value',\n run: async (store) => {\n await store.set(KEY, { v: 1 })\n await store.set(KEY, { v: 2 })\n const value = await store.get(KEY)\n ensure(canonical(value) === canonical({ v: 2 }), `a second set lost to the first: ${show(value)}`)\n },\n },\n {\n name: 'delete removes a value',\n run: async (store) => {\n await store.set(KEY, { v: 1 })\n await store.delete(KEY)\n const value = await store.get(KEY)\n ensure(is_miss(value), `get after delete returned ${show(value)}`)\n },\n },\n {\n name: 'deleting a missing key resolves',\n run: async (store) => {\n await store.delete(MISSING)\n },\n },\n {\n name: 'a stored null or undefined reads as a miss',\n run: async (store) => {\n await store.set(NULL_KEY, null)\n await store.set(UNDEFINED_KEY, undefined)\n ensure(is_miss(await store.get(NULL_KEY)), 'a stored null read back as a hit')\n ensure(is_miss(await store.get(UNDEFINED_KEY)), 'a stored undefined read back as a hit')\n },\n },\n {\n name: 'keys that encode alike stay apart',\n run: async (store) => {\n await Promise.all(LOOKALIKES.map((key, i) => store.set(key, i)))\n const read = await Promise.all(LOOKALIKES.map((key) => store.get(key)))\n LOOKALIKES.forEach((key, i) => {\n ensure(read[i] === i, `key ${show(key)} read back ${show(read[i])}, another key's value`)\n })\n },\n },\n {\n name: 'racing writes leave one whole value',\n run: async (store) => {\n const writes = Array.from({ length: RACERS }, (_, i) => ({\n writer: i,\n // Stryker disable next-line ArithmeticOperator: each write only has to differ from the others, which `writer` already ensures, so the body's exact length is immaterial.\n body: 'x'.repeat(4096 + i),\n }))\n await Promise.all(writes.map((write) => store.set(RACE_KEY, write)))\n const value = await store.get(RACE_KEY)\n ensure(\n writes.some((write) => canonical(write) === canonical(value)),\n `after ${RACERS} racing sets, get returned ${show(value)}, which none of them wrote`,\n )\n },\n },\n]\n\nconst DAMAGE_CHECK: Check = {\n name: 'a damaged value reads as a miss',\n run: async (store, env) => {\n await store.set(DAMAGED_KEY, { ok: true })\n await env.corrupt(store, DAMAGED_KEY)\n let value: unknown\n try {\n value = await store.get(DAMAGED_KEY)\n } catch (err) {\n // Stryker disable next-line ObjectLiteral: the report carries the message alone, so the cause is there for a debugger and nothing reads it.\n throw new Error(`get threw on a damaged value instead of missing: ${String(err)}`, {\n cause: err,\n })\n }\n ensure(is_miss(value), `get on a damaged value returned ${show(value)}`)\n },\n}\n\nconst SCOPE_CHECKS: ReadonlyArray<Check> = [\n {\n name: 'a scope is apart from its parent',\n run: async (store) => {\n const child = scope_of(store, CHILD)\n await store.set(KEY, 'parent')\n ensure(is_miss(await child.get(KEY)), \"a scope read its parent's value\")\n await child.set(KEY, 'child')\n ensure((await store.get(KEY)) === 'parent', \"a write in a scope changed its parent's value\")\n ensure((await child.get(KEY)) === 'child', 'a scope lost its own value')\n },\n },\n {\n name: 'one prefix reaches the same data, another prefix does not',\n run: async (store) => {\n await scope_of(store, A).set(KEY, 'a')\n ensure((await scope_of(store, A).get(KEY)) === 'a', 'reopening a scope lost its value')\n ensure(is_miss(await scope_of(store, B).get(KEY)), \"scope 'b' read a value set in scope 'a'\")\n },\n },\n {\n name: 'prefixes that encode alike stay apart',\n run: async (store) => {\n await Promise.all(LOOKALIKES.map((prefix, i) => scope_of(store, prefix).set(KEY, i)))\n const read = await Promise.all(LOOKALIKES.map((prefix) => scope_of(store, prefix).get(KEY)))\n LOOKALIKES.forEach((prefix, i) => {\n ensure(read[i] === i, `scope ${show(prefix)} read back ${show(read[i])}, another scope's`)\n })\n },\n },\n {\n name: 'nested scopes stay apart from look-alike prefixes',\n run: async (store) => {\n await scope_of(store, A).scope(B).set(KEY, 'nested')\n const read = await Promise.all(FLATTENED.map((prefix) => scope_of(store, prefix).get(KEY)))\n FLATTENED.forEach((prefix, i) => {\n ensure(is_miss(read[i]), `scope ${show(prefix)} read the value of scope 'b' in scope 'a'`)\n })\n const a = scope_of(store, A)\n ensure(is_miss(await a.get(KEY)), \"a nested scope's value showed up in its parent\")\n ensure((await a.scope(B).get(KEY)) === 'nested', 'reopening a nested scope lost its value')\n },\n },\n {\n name: 'clear empties a scope and nothing else',\n run: async (store) => {\n const a = scope_of(store, A)\n await Promise.all([\n store.set(KEY, 'root'),\n a.set(KEY, 'a'),\n a.scope(INNER).set(KEY, 'inner'),\n scope_of(store, B).set(KEY, 'b'),\n ])\n await a.clear()\n ensure(is_miss(await a.get(KEY)), 'a value survived clear')\n ensure(is_miss(await a.scope(INNER).get(KEY)), \"a nested scope's value survived clear\")\n ensure((await scope_of(store, B).get(KEY)) === 'b', \"clear removed a sibling's value\")\n ensure((await store.get(KEY)) === 'root', \"clear removed the parent's value\")\n await a.set(KEY, 'again')\n ensure((await a.get(KEY)) === 'again', 'a cleared scope refused a new value')\n },\n },\n {\n name: 'clear leaves look-alike scopes alone',\n run: async (store) => {\n await Promise.all(BESIDE_A.map((prefix, i) => scope_of(store, prefix).set(KEY, i)))\n await scope_of(store, A).clear()\n const read = await Promise.all(BESIDE_A.map((prefix) => scope_of(store, prefix).get(KEY)))\n BESIDE_A.forEach((prefix, i) => {\n ensure(read[i] === i, `clearing scope 'a' emptied scope ${show(prefix)}`)\n })\n },\n },\n {\n name: 'clearing an empty scope resolves',\n run: async (store) => {\n await scope_of(store, UNUSED).clear()\n },\n },\n]\n\nconst SCOPED_CLAIM_CHECKS: ReadonlyArray<Check> = [\n {\n name: 'scopes keep the claim capability',\n run: async (store) => {\n const claims = claims_of(scope_of(store, A))\n ensure(await claims.claim(KEY, FIRST, HELD_MS), FRESH_SCOPE_CLAIM_REFUSED)\n },\n },\n {\n name: 'claims in different scopes stay apart',\n run: async (store) => {\n const first = await claims_of(scope_of(store, A)).claim(KEY, FIRST, HELD_MS)\n const second = await claims_of(scope_of(store, B)).claim(KEY, SECOND, HELD_MS)\n const third = await claims_of(store).claim(KEY, THIRD, HELD_MS)\n ensure(first, FRESH_SCOPE_CLAIM_REFUSED)\n ensure(second, \"scope 'b' couldn't claim a key held in scope 'a'\")\n ensure(third, \"the parent couldn't claim a key held in a scope\")\n },\n },\n {\n name: 'clear drops the claims under a scope',\n run: async (store) => {\n const a = scope_of(store, A)\n ensure(await claims_of(a).claim(KEY, FIRST, HELD_MS), FRESH_SCOPE_CLAIM_REFUSED)\n await a.clear()\n ensure(await claims_of(a).claim(KEY, SECOND, HELD_MS), 'a claim survived clear')\n },\n },\n]\n\nconst CLAIM_CHECKS: ReadonlyArray<Check> = [\n {\n name: 'claim comes with release',\n run: async (store) => {\n claims_of(store)\n },\n },\n {\n name: 'a free key can be claimed',\n run: async (store) => {\n ensure(await claims_of(store).claim(KEY, FIRST, HELD_MS), FREE_CLAIM_REFUSED)\n },\n },\n {\n name: 'a held key refuses another owner',\n run: async (store) => {\n const claims = claims_of(store)\n await claims.claim(KEY, FIRST, HELD_MS)\n const second = await claims.claim(KEY, SECOND, HELD_MS)\n ensure(!second, 'a second owner claimed a key the first still holds')\n },\n },\n {\n name: 'the owner can renew its claim',\n run: async (store) => {\n const claims = claims_of(store)\n await claims.claim(KEY, FIRST, HELD_MS)\n ensure(await claims.claim(KEY, FIRST, HELD_MS), RENEWAL_REFUSED)\n },\n },\n {\n name: 'release lets another owner in',\n run: async (store) => {\n const claims = claims_of(store)\n await claims.claim(KEY, FIRST, HELD_MS)\n await claims.release(KEY, FIRST)\n ensure(await claims.claim(KEY, SECOND, HELD_MS), 'a released key refused the next owner')\n },\n },\n {\n name: 'release by another owner changes nothing',\n run: async (store) => {\n const claims = claims_of(store)\n await claims.claim(KEY, FIRST, HELD_MS)\n await claims.release(KEY, SECOND)\n const second = await claims.claim(KEY, SECOND, HELD_MS)\n ensure(!second, \"a release by a non-owner freed the owner's claim\")\n },\n },\n {\n name: 'releasing a key nobody holds resolves',\n run: async (store) => {\n await claims_of(store).release(UNCLAIMED, FIRST)\n },\n },\n {\n name: 'claims and values stay apart',\n run: async (store) => {\n const claims = claims_of(store)\n await store.set(KEY, 'value')\n ensure(await claims.claim(KEY, FIRST, HELD_MS), 'a key that holds a value refused a claim')\n ensure((await store.get(KEY)) === 'value', 'claiming a key changed its value')\n await store.delete(KEY)\n const second = await claims.claim(KEY, SECOND, HELD_MS)\n ensure(!second, 'deleting a value released the claim on the same key')\n await claims.claim(CLAIMED_ONLY, FIRST, HELD_MS)\n ensure(is_miss(await store.get(CLAIMED_ONLY)), 'claiming a key gave it a value')\n },\n },\n {\n name: 'different keys are claimed apart',\n run: async (store) => {\n const claims = claims_of(store)\n ensure(await claims.claim(A, FIRST, HELD_MS), FREE_CLAIM_REFUSED)\n ensure(await claims.claim(B, SECOND, HELD_MS), \"a claim on 'a' blocked a claim on 'b'\")\n },\n },\n {\n name: 'exactly one racing claimer wins a free key',\n run: async (store) => {\n const winners = await race_for(claims_of(store), KEY)\n ensure(winners === 1, `${RACERS} owners raced for a free key and ${winners} won`)\n },\n },\n {\n name: 'an expired claim passes to another owner',\n run: async (store, env) => {\n const claims = claims_of(store)\n await claims.claim(KEY, FIRST, env.ttl_ms)\n await sleep(env.ttl_ms * 2)\n const second = await claims.claim(KEY, SECOND, HELD_MS)\n ensure(second, `a claim was still held after its ${env.ttl_ms}ms ran out`)\n const first = await claims.claim(KEY, FIRST, HELD_MS)\n ensure(!first, 'the first owner took back a claim that had passed to another')\n },\n },\n {\n name: 'exactly one racing claimer takes an expired claim',\n run: async (store, env) => {\n const claims = claims_of(store)\n await claims.claim(KEY, FIRST, env.ttl_ms)\n await sleep(env.ttl_ms * 2)\n const winners = await race_for(claims, KEY)\n ensure(winners === 1, `${RACERS} owners raced for an expired claim and ${winners} won`)\n },\n },\n {\n name: 'renewing restarts the clock',\n run: async (store, env) => {\n const claims = claims_of(store)\n const started = Date.now()\n await claims.claim(KEY, FIRST, env.ttl_ms)\n await sleep(env.ttl_ms / 2)\n const renewed = Date.now()\n ensure(await claims.claim(KEY, FIRST, env.ttl_ms), RENEWAL_REFUSED)\n await sleep(Math.max(0, started + env.ttl_ms * 1.2 - Date.now()))\n // A machine slow enough to oversleep the renewed lifetime can't tell a\n // renewal from none, so the check only judges a wake inside it.\n if (Date.now() >= renewed + env.ttl_ms) return\n const second = await claims.claim(KEY, SECOND, HELD_MS)\n ensure(!second, 'a renewed claim expired on its original schedule')\n },\n },\n]\n\nconst SUITES: ReadonlyArray<Suite> = [\n { checks: CONTRACT_CHECKS, applies: () => true },\n { checks: [DAMAGE_CHECK], applies: (_, options) => options.corrupt !== undefined },\n { checks: SCOPE_CHECKS, applies: (store) => store.scope !== undefined },\n {\n checks: CLAIM_CHECKS,\n applies: (store) => store.claim !== undefined || store.release !== undefined,\n },\n {\n checks: SCOPED_CLAIM_CHECKS,\n applies: (store) => store.scope !== undefined && store.claim !== undefined,\n },\n]\n\n/**\n * Run one check against a fresh store, resolving its failure message or\n * `undefined` when it passed. A `make_store` that throws fails the check.\n */\nasync function run_check(\n check: Check,\n make_store: () => CheckpointStore | Promise<CheckpointStore>,\n env: CheckEnv,\n): Promise<string | undefined> {\n try {\n await check.run(await make_store(), env)\n return undefined\n } catch (err) {\n return err instanceof Error ? err.message : String(err)\n }\n}\n\n/**\n * Check a `CheckpointStore` against the contract, one fresh store per check.\n *\n * The capabilities are read off the first store `make_store` returns: scope\n * checks run when it has `scope`, claim checks when it has `claim` or\n * `release`, and the damage check when `options.corrupt` is given. Every\n * other check lands in `skipped`. Checks run one at a time, because some wait\n * on claim expiry and a store's backing service may be shared between the\n * stores `make_store` hands out.\n */\nexport async function checkpoint_store_conformance(\n make_store: () => CheckpointStore | Promise<CheckpointStore>,\n options: StoreConformanceOptions = {},\n): Promise<StoreConformanceReport> {\n const env: CheckEnv = {\n ttl_ms: options.ttl_ms ?? DEFAULT_TTL_MS,\n corrupt: options.corrupt ?? (() => {}),\n }\n const probe = await make_store()\n const passed: string[] = []\n const failed: StoreConformanceFailure[] = []\n const skipped: string[] = []\n for (const suite of SUITES) {\n if (!suite.applies(probe, options)) {\n skipped.push(...suite.checks.map((check) => check.name))\n continue\n }\n for (const check of suite.checks) {\n const message = await run_check(check, make_store, env)\n if (message === undefined) passed.push(check.name)\n else failed.push({ check: check.name, message })\n }\n }\n return { passed, failed, skipped }\n}\n","/**\n * make_capture_engine: an `Engine` that records every generate call.\n *\n * Returns the engine together with the live `calls` array, which receives\n * the `GenerateOptions` of each call in order. Every call resolves with the\n * same canned result (`options.result`, or a minimal `'ok'` result), so the\n * double is for asserting what reached the engine, not for scripting\n * multi-role conversations: that is `make_stub_engine`'s job.\n *\n * `options.on_generate` runs after the call is recorded and is awaited\n * before the result resolves, which is the hook for driving streaming\n * chunks, spans, or aborts against the captured options.\n */\n\nimport type { Engine, GenerateOptions, GenerateResult } from '#engine'\nimport { engine_from_generate } from './engine_from_generate.js'\n\nexport type CaptureEngineOptions = {\n readonly result?: GenerateResult<unknown>\n readonly on_generate?: (opts: GenerateOptions) => Promise<void> | void\n}\n\nexport type CaptureEngine = {\n readonly engine: Engine\n readonly calls: GenerateOptions[]\n}\n\nconst DEFAULT_RESULT: GenerateResult<unknown> = {\n content: 'ok',\n tool_calls: [],\n steps: [],\n usage: { input_tokens: 1, output_tokens: 1 },\n finish_reason: 'stop',\n model_resolved: { provider: 'stub', model_id: 'capture' },\n}\n\n/**\n * Build an `Engine` that records each call's `GenerateOptions` into the\n * returned `calls` array and answers with the canned result.\n */\nexport function make_capture_engine(options: CaptureEngineOptions = {}): CaptureEngine {\n const calls: GenerateOptions[] = []\n const result = options.result ?? DEFAULT_RESULT\n\n const engine = engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const loose = opts as GenerateOptions\n calls.push(loose)\n if (options.on_generate) await options.on_generate(loose)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return result as GenerateResult<t>\n },\n )\n return { engine, calls }\n}\n","/**\n * Shared plumbing for the canned engine doubles.\n *\n * make_stub_engine and make_script_engine answer calls from fixtures rather\n * than a provider, but the surrounding contract stays the engine's: a call\n * under an already-aborted signal throws `aborted_error`, a streaming caller\n * sees chunks before the result resolves, and content that fails the\n * caller's schema surfaces as `schema_validation_error` carrying the issues.\n * Keeping that contract here keeps every double interchangeable with a real\n * engine at the seams tests exercise.\n */\n\nimport { aborted_error, schema_validation_error } from '#engine'\nimport type { FinishReason, GenerateOptions, UsageTotals } from '#engine'\n\nexport const DEFAULT_USAGE: UsageTotals = { input_tokens: 40, output_tokens: 20 }\n\n/**\n * Mirror the engine's entry guard: a generate call under an already-aborted\n * signal never reaches a provider, so a double must refuse it the same way\n * for cancellation tests to be trustworthy.\n */\nexport function throw_if_aborted(abort: AbortSignal | undefined): void {\n if (abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: abort.reason })\n }\n}\n\n/**\n * Render canned content as the text a provider would have put on the wire:\n * strings pass through, everything else is serialized as JSON (which is what\n * a schema-bearing call would have streamed).\n */\nfunction render_text(content: unknown): string {\n if (typeof content === 'string') return content\n return JSON.stringify(content) ?? ''\n}\n\n/**\n * Emit the minimal chunk sequence a streaming caller expects: the whole\n * content as one text chunk, then the finish marker. Enough for model_chunk\n * trajectory events and stream-consuming UIs to fire without a network.\n */\nexport async function emit_chunks(\n on_chunk: GenerateOptions['on_chunk'],\n content: unknown,\n finish_reason: FinishReason,\n usage: UsageTotals,\n): Promise<void> {\n if (on_chunk === undefined) return\n await on_chunk({ kind: 'text', text: render_text(content), step_index: 0 })\n await on_chunk({ kind: 'finish', finish_reason, usage })\n}\n\ntype CannedIssue = {\n readonly message: string\n readonly path?: ReadonlyArray<PropertyKey>\n}\n\n/**\n * Render issues as one `path: message` line per issue, dotted the same way\n * the engine's own repair prompts and error messages format them.\n */\nfunction format_issues(issues: ReadonlyArray<CannedIssue>): string {\n return issues\n .map((issue) =>\n issue.path === undefined || issue.path.length === 0\n ? issue.message\n : `${issue.path.map(String).join('.')}: ${issue.message}`,\n )\n .join('; ')\n}\n\n/**\n * Validate canned content through the caller's schema, throwing the engine's\n * own `schema_validation_error` on failure so `instanceof` handling in the\n * code under test sees exactly what a real engine throws when its repair\n * attempts run out. Absent a schema, the content passes through untouched.\n */\nexport async function validate_canned(\n schema: GenerateOptions<unknown>['schema'],\n content: unknown,\n described: string,\n): Promise<unknown> {\n if (schema === undefined) return content\n const checked = await schema['~standard'].validate(content)\n if (checked.issues !== undefined) {\n // The spec allows a path segment to be a bare key or a `{ key }` wrapper;\n // normalize to bare keys so schema_issues reads one shape, as the real\n // engine's validator does.\n const issues: CannedIssue[] = checked.issues.map((issue) =>\n issue.path === undefined\n ? { message: issue.message }\n : {\n message: issue.message,\n path: issue.path.map((segment) =>\n typeof segment === 'object' ? segment.key : segment,\n ),\n },\n )\n throw new schema_validation_error(\n `${described} failed the caller's schema: ${format_issues(issues)}`,\n issues,\n render_text(content),\n )\n }\n return checked.value\n}\n","/**\n * make_script_engine: a queue of canned responses consumed in call order.\n *\n * Where make_stub_engine routes by system-prompt prefix and cannot tell\n * call 3 from call 1, a script cares only about order: the first generate\n * call gets the first entry, the second the next, and a call past the end\n * throws naming how many responses were scripted versus received, so a flow\n * that makes an unexpected extra model call fails loudly. That makes it the\n * double for loops that must converge, retry paths, and flows whose calls a\n * prefix cannot distinguish (a markdown-only define_agent sends no system\n * prompt at all, so every call looks alike to a stub).\n *\n * An entry is plain content, or a `ScriptResponse` object when the call\n * should carry tool calls, report a different finish reason or usage, or\n * throw a scripted error (a rate_limit_error, a provider_error) instead of\n * answering. Only an object whose keys ALL belong to the ScriptResponse\n * shape is treated as scripted; any other value, `{ verdict: 'ship' }`\n * included, becomes content as-is. Wrap literal content that collides with\n * the shape in `{ content }`.\n *\n * Scripted content is validated through the caller's schema, and the abort\n * and on_chunk contracts match make_stub_engine's; see ./canned.ts.\n */\n\nimport type {\n Engine,\n FinishReason,\n GenerateOptions,\n GenerateResult,\n ToolCallRecord,\n UsageTotals,\n} from '#engine'\nimport { DEFAULT_USAGE, emit_chunks, throw_if_aborted, validate_canned } from './canned.js'\nimport { engine_from_generate } from './engine_from_generate.js'\n\nexport type ScriptResponse = {\n readonly content?: unknown\n readonly tool_calls?: ReadonlyArray<ToolCallRecord>\n readonly finish_reason?: FinishReason\n readonly usage?: UsageTotals\n /** An error to throw for this call instead of answering. */\n readonly throw?: Error\n}\n\nexport type ScriptEngineOptions = {\n readonly usage?: UsageTotals\n readonly model_id?: string\n}\n\nconst SCRIPT_KEYS = new Set(['content', 'tool_calls', 'finish_reason', 'usage', 'throw'])\n\n/**\n * Decide whether a queue entry is a ScriptResponse or plain content. Only a\n * non-null, non-array object whose keys all belong to the ScriptResponse\n * shape is scripted, so an arbitrary content fixture with its own keys\n * passes through untouched rather than being half-read as a script entry.\n */\nfunction is_script_response(entry: unknown): entry is ScriptResponse {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return false\n const keys = Object.keys(entry)\n return keys.length > 0 && keys.every((key) => SCRIPT_KEYS.has(key))\n}\n\n/**\n * Build an `Engine` that answers generate calls strictly in call order from\n * `responses`, throwing once the queue is exhausted.\n *\n * `options` mirrors make_stub_engine's: `usage` is the default usage for\n * entries that do not set their own (default `{ input_tokens: 40,\n * output_tokens: 20 }`) and `model_id` sets `model_resolved.model_id`\n * (default `'script'`). The provider always reports as `'stub'`.\n */\nexport function make_script_engine(\n responses: ReadonlyArray<unknown>,\n options: ScriptEngineOptions = {},\n): Engine {\n const default_usage = options.usage ?? DEFAULT_USAGE\n const model_id = options.model_id ?? 'script'\n let call_count = 0\n\n return engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n throw_if_aborted(opts.abort)\n call_count += 1\n const index = call_count - 1\n if (index >= responses.length) {\n throw new Error(\n `make_script_engine: script exhausted: ${responses.length} response(s) scripted, call ${call_count} received`,\n )\n }\n const entry = responses[index]\n const scripted: ScriptResponse = is_script_response(entry) ? entry : { content: entry }\n if (scripted.throw !== undefined) throw scripted.throw\n const usage = scripted.usage ?? default_usage\n const finish_reason = scripted.finish_reason ?? 'stop'\n // Chunks carry the raw scripted content, before validation, mirroring a\n // real stream where text flows and only then gets validated.\n await emit_chunks(opts.on_chunk, scripted.content, finish_reason, usage)\n const content = await validate_canned(\n opts.schema,\n scripted.content,\n `make_script_engine: scripted response ${index}`,\n )\n return {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n content: content as t,\n tool_calls: scripted.tool_calls === undefined ? [] : [...scripted.tool_calls],\n steps: [],\n usage,\n finish_reason,\n model_resolved: { provider: 'stub', model_id },\n }\n },\n )\n}\n","/**\n * make_stub_engine: a canned, network-free `Engine` for tests and demos.\n *\n * Each generate call is routed by the system prompt's stable first line:\n * the first canned response whose `prefix` the system prompt starts with\n * answers the call, and an unmatched system throws, so a flow that grows a\n * new model boundary fails loudly instead of silently reusing a fixture.\n * A response with the empty-string prefix matches every call, which is the\n * single-model-boundary case.\n *\n * A response's `content` may be a function of `(opts, call_index)` for\n * routes a flow hits more than once (a converging loop, a judged retry):\n * `call_index` counts how many times that route has matched before,\n * starting at 0, so each pass can answer differently.\n *\n * Canned content is validated through the caller's own schema\n * (`opts.schema['~standard'].validate`), so fixtures cannot drift from the\n * contracts they stand in for. A failure throws the engine's own\n * `schema_validation_error` carrying the issues and the canned content as\n * `raw_text`, exactly what a real engine throws when repair attempts run\n * out, so `instanceof` handling in the code under test stays testable.\n *\n * The engine's streaming and cancellation contract holds too: an\n * already-aborted `opts.abort` throws `aborted_error`, and a provided\n * `opts.on_chunk` receives the canned content as a text chunk plus a finish\n * chunk before the result resolves.\n */\n\nimport type { Engine, GenerateOptions, GenerateResult, UsageTotals } from '#engine'\nimport { DEFAULT_USAGE, emit_chunks, throw_if_aborted, validate_canned } from './canned.js'\nimport { engine_from_generate } from './engine_from_generate.js'\n\n/**\n * The function form of canned content: called with the routed call's options\n * and how many times this prefix route has matched before (starting 0). May\n * be async; the returned value is validated and answered like static content.\n */\nexport type StubContentFn = (opts: GenerateOptions, call_index: number) => unknown\n\nexport type StubResponse = {\n readonly prefix: string\n /** Static content, or a `StubContentFn` invoked per matched call. */\n readonly content: unknown\n}\n\nexport type StubEngineOptions = {\n readonly usage?: UsageTotals\n readonly model_id?: string\n}\n\n/**\n * Build an `Engine` that answers every generate call from `canned`,\n * routed by system-prompt prefix.\n *\n * `options.usage` sets the usage totals reported on every result (default\n * `{ input_tokens: 40, output_tokens: 20 }`, so cost lines render non-zero\n * numbers); `options.model_id` sets `model_resolved.model_id` (default\n * `'stub'`). The provider always reports as `'stub'`.\n */\nexport function make_stub_engine(\n canned: ReadonlyArray<StubResponse>,\n options: StubEngineOptions = {},\n): Engine {\n const usage = options.usage ?? DEFAULT_USAGE\n const model_id = options.model_id ?? 'stub'\n const match_counts = new Map<StubResponse, number>()\n\n return engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n throw_if_aborted(opts.abort)\n const system = opts.system ?? ''\n const match = canned.find((c) => system.startsWith(c.prefix))\n if (match === undefined) {\n throw new Error(`make_stub_engine: no canned response for system: ${system || '(none)'}`)\n }\n const call_index = match_counts.get(match) ?? 0\n match_counts.set(match, call_index + 1)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const loose = opts as GenerateOptions\n const produced =\n typeof match.content === 'function'\n ? // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n await (match.content as StubContentFn)(loose, call_index)\n : match.content\n // Chunks carry the raw canned content, before validation, mirroring a\n // real stream where text flows and only then gets validated.\n await emit_chunks(opts.on_chunk, produced, 'stop', usage)\n const content = await validate_canned(\n opts.schema,\n produced,\n `make_stub_engine: canned response for prefix '${match.prefix}'`,\n )\n return {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n content: content as t,\n tool_calls: [],\n steps: [],\n usage,\n finish_reason: 'stop',\n model_resolved: { provider: 'stub', model_id },\n }\n },\n )\n}\n","/**\n * text_of: the user-visible prompt text of a captured GenerateOptions.\n *\n * Capture assertions care about what the model was asked, not how the prompt\n * was encoded. A prompt is a bare string or a Message[] whose user turns\n * carry either a string or typed content parts; navigating\n * `calls[0].prompt[0].content[0].text` by hand couples every assertion to\n * one encoding. System and assistant text are excluded on purpose: assert\n * those through `opts.system` and the raw messages.\n */\n\nimport type { GenerateOptions } from '#engine'\n\n/**\n * Flatten the prompt's user-facing text into one string: a string prompt\n * verbatim, otherwise every user turn's text (string content, or the `text`\n * parts of a content-part array) joined with newlines. Total: absent or\n * non-text content yields ''.\n */\nexport function text_of<t = unknown>(opts: GenerateOptions<t>): string {\n if (typeof opts.prompt === 'string') return opts.prompt\n const texts: string[] = []\n for (const message of opts.prompt) {\n if (message.role !== 'user') continue\n if (typeof message.content === 'string') {\n texts.push(message.content)\n continue\n }\n for (const part of message.content) {\n if (part.type === 'text') texts.push(part.text)\n }\n }\n return texts.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAgB,qBAAqB,UAAsC;CACzE,OAAO;EACL;EACA,sBAAsB,CAAC;EACvB,qBAAqB,KAAA;EACrB,oBAAoB,CAAC;EACrB,sBAAsB;GACpB,MAAM,IAAI,MAAM,+CAA+C;EACjE;EACA,SAAS,YAAY,CAAC;CACxB;AACF;;;AC4BA,MAAM,iBAAiB;AAIvB,MAAM,UAAU;AAEhB,MAAM,SAAS;AAKf,MAAM,MAAM;AACZ,MAAM,UAAU;AAChB,MAAM,WAAW;AACjB,MAAM,gBAAgB;AACtB,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,eAAe;AACrB,MAAM,YAAY;AAClB,MAAM,IAAI;AACV,MAAM,IAAI;AACV,MAAM,QAAQ;AACd,MAAM,QAAQ;AACd,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,SAAS;AACf,MAAM,QAAQ;AAGd,MAAM,4BAA4B;AAClC,MAAM,qBAAqB;AAC3B,MAAM,kBAAkB;AAExB,MAAM,UAAkC;CACtC;EAAE,WAAW;EAAK,WAAW;EAAM,QAAQ;CAAE;CAC7C,EAAE,QAAQ;EAAE,MAAM;GAAC;GAAG;GAAO,EAAE,OAAO,EAAE;EAAC;EAAG,OAAO,CAAC;CAAE,EAAE;CACxD;EAAC;EAAG;EAAG;CAAC;CACR,CAAC;CACD,CAAC;CACD;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAKA,MAAM,aAAoC;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG,IAAI,OAAO,GAAG,EAAE;CACnB,GAAG,IAAI,OAAO,GAAG,EAAE;AACrB;AAIA,MAAM,YAAY;CAAC;CAAO;CAAM;CAAO;CAAO;AAAG;AAKjD,MAAM,W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AU;GACvC,MAAM,KAAK,QAAQ,OAAO;GAC1B;EACF;EACA,KAAK,MAAM,QAAQ,QAAQ,SACzB,IAAI,KAAK,SAAS,QAAQ,MAAM,KAAK,KAAK,IAAI;CAElD;CACA,OAAO,MAAM,KAAK,IAAI;AACxB"}
@@ -60,6 +60,29 @@ function is_checkpoint_event(value) {
60
60
  return typeof value["key"] === "string";
61
61
  }
62
62
  /**
63
+ * A replay report: a step marked `side_effect` started before its resumed run
64
+ * reached the gates in `suspend_ids`, so the work it does was already paid for
65
+ * once. `step_id` names the step, and every gate id must be a string.
66
+ */
67
+ function is_step_replayed_event(value) {
68
+ if (!is_custom_trajectory_event(value)) return false;
69
+ if (value.kind !== "step_replayed") return false;
70
+ const suspend_ids = value["suspend_ids"];
71
+ if (!Array.isArray(suspend_ids)) return false;
72
+ const ids = suspend_ids;
73
+ return typeof value["step_id"] === "string" && ids.every((id) => typeof id === "string");
74
+ }
75
+ /**
76
+ * A failed item of a `map` that settles: `step_id` names the map, `index` is
77
+ * the item's position in the map's input, and `error` is the message. An
78
+ * error that carried a `kind` adds it as `error_kind`.
79
+ */
80
+ function is_map_item_failed_event(value) {
81
+ if (!is_custom_trajectory_event(value)) return false;
82
+ if (value.kind !== "map_item_failed") return false;
83
+ return typeof value["step_id"] === "string" && Number.isInteger(value["index"]) && typeof value["error"] === "string";
84
+ }
85
+ /**
63
86
  * Parse one wire value into a trajectory event, `safeParse`-shaped.
64
87
  *
65
88
  * On success `data` is the value itself, not a copy, so nothing on the line is
@@ -76,6 +99,6 @@ function parse_trajectory_event(value) {
76
99
  };
77
100
  }
78
101
  //#endregion
79
- export { is_span_end_event as a, is_run_end_event as i, is_custom_trajectory_event as n, is_span_start_event as o, is_emit_event as r, parse_trajectory_event as s, is_checkpoint_event as t };
102
+ export { is_run_end_event as a, is_step_replayed_event as c, is_map_item_failed_event as i, parse_trajectory_event as l, is_custom_trajectory_event as n, is_span_end_event as o, is_emit_event as r, is_span_start_event as s, is_checkpoint_event as t };
80
103
 
81
- //# sourceMappingURL=trajectory-D1eq9eue.js.map
104
+ //# sourceMappingURL=trajectory-BI-mrVFT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trajectory-BI-mrVFT.js","names":[],"sources":["../src/core/trajectory.ts"],"sourcesContent":["/**\n * Wire-format guards for trajectory events.\n *\n * `TrajectoryEvent` (in `types.ts`) is the loose internal type — any code that\n * calls `trajectory.record(event)` or `start_span(name, meta)` produces values\n * conforming to it. This file defines the *narrower* shapes that the studio\n * (and any other downstream consumer) can recognize in the wire stream:\n *\n * span_start: composer span open\n * span_end: composer span close\n * emit: user-emitted event from inside a step (ctx.emit)\n * run_end: terminal run event carrying the run's status, so a consumer\n * distinguishes done / failed / aborted / suspended without\n * inferring from silence\n * checkpoint: checkpoint store lookup outcome (hit / miss / read_error)\n * step_replayed: a step marked `side_effect` re-running before a resumed\n * run reached the gates it was resumed at\n * map_item_failed: an item of a `map` that settles threw, and its slot\n * holds the error instead of a value\n * <other>: anything else, recognized by `is_custom_trajectory_event`,\n * which only requires a string `kind`\n *\n * `parse_trajectory_event` is the wire gate, and it is deliberately permissive:\n * a value is a trajectory event iff it is a non-array object carrying a string\n * `kind`. The well-known guards layered on top are *recognizers*, not gates — a\n * `{ kind: 'span_start' }` line missing its `span_id` is still a valid event on\n * the wire, just not a `SpanStartEvent`. Anything stricter would have a viewer\n * drop lines a newer producer emits, which is the opposite of what a\n * forward-compatible wire format is for. `is_custom_trajectory_event` therefore\n * answers `true` for well-known kinds too: it is the fallback shape, not a\n * fifth disjoint case.\n *\n * Extra fields (`run_id`, `id`, provider-specific metadata) are neither\n * required nor stripped: a successful parse hands the value straight back, so a\n * parse / re-serialize round trip is lossless.\n */\n\nexport type SpanStartEvent = {\n readonly kind: 'span_start'\n readonly span_id: string\n readonly name: string\n} & { readonly [key: string]: unknown }\n\nexport type SpanEndEvent = {\n readonly kind: 'span_end'\n readonly span_id: string\n} & { readonly [key: string]: unknown }\n\nexport type EmitEvent = {\n readonly kind: 'emit'\n} & { readonly [key: string]: unknown }\n\nexport type RunEndStatus = 'done' | 'failed' | 'aborted' | 'suspended'\n\nexport type RunEndEvent = {\n readonly kind: 'run_end'\n readonly status: RunEndStatus\n} & { readonly [key: string]: unknown }\n\nexport type CheckpointStatus = 'hit' | 'miss' | 'read_error'\n\nexport type CheckpointEvent = {\n readonly kind: 'checkpoint'\n readonly status: CheckpointStatus\n readonly key: string\n} & { readonly [key: string]: unknown }\n\nexport type StepReplayedEvent = {\n readonly kind: 'step_replayed'\n readonly step_id: string\n readonly suspend_ids: ReadonlyArray<string>\n} & { readonly [key: string]: unknown }\n\nexport type MapItemFailedEvent = {\n readonly kind: 'map_item_failed'\n readonly step_id: string\n readonly index: number\n readonly error: string\n} & { readonly [key: string]: unknown }\n\nexport type CustomTrajectoryEvent = {\n readonly kind: string\n} & { readonly [key: string]: unknown }\n\nexport type ParsedTrajectoryEvent =\n | SpanStartEvent\n | SpanEndEvent\n | EmitEvent\n | RunEndEvent\n | CheckpointEvent\n | StepReplayedEvent\n | MapItemFailedEvent\n | CustomTrajectoryEvent\n\nexport type TrajectoryParseResult =\n | { readonly success: true; readonly data: ParsedTrajectoryEvent }\n | { readonly success: false; readonly error: Error }\n\n/**\n * The wire gate: a non-array object carrying a string `kind`.\n *\n * True for every well-known kind as well, since `custom` is the fallback shape\n * rather than a disjoint case.\n */\nexport function is_custom_trajectory_event(value: unknown): value is CustomTrajectoryEvent {\n if (typeof value !== 'object' || value === null) return false\n if (Array.isArray(value)) return false\n return typeof (value as { kind?: unknown }).kind === 'string'\n}\n\n/** A composer span open: both `span_id` and `name` must be present as strings. */\nexport function is_span_start_event(value: unknown): value is SpanStartEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'span_start') return false\n return typeof value['span_id'] === 'string' && typeof value['name'] === 'string'\n}\n\n/** A composer span close: `span_id` must be present as a string, `name` need not be. */\nexport function is_span_end_event(value: unknown): value is SpanEndEvent {\n if (!is_custom_trajectory_event(value)) return false\n return value.kind === 'span_end' && typeof value['span_id'] === 'string'\n}\n\n/** A `ctx.emit` event: the kind alone identifies it, the payload is the caller's. */\nexport function is_emit_event(value: unknown): value is EmitEvent {\n return is_custom_trajectory_event(value) && value.kind === 'emit'\n}\n\nconst RUN_END_STATUSES: ReadonlySet<string> = new Set(['done', 'failed', 'aborted', 'suspended'])\n\n/**\n * A terminal run event: `status` must be one of the known run outcomes, so the\n * narrowed type's `status` union is truthful. An unknown future status still\n * passes the wire gate as a custom event.\n */\nexport function is_run_end_event(value: unknown): value is RunEndEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'run_end') return false\n const status = value['status']\n return typeof status === 'string' && RUN_END_STATUSES.has(status)\n}\n\nconst CHECKPOINT_STATUSES: ReadonlySet<string> = new Set(['hit', 'miss', 'read_error'])\n\n/**\n * A checkpoint lookup event: `status` must be a known lookup outcome and `key`\n * the store key that was consulted, for the same truthful-narrowing reason as\n * `is_run_end_event`.\n */\nexport function is_checkpoint_event(value: unknown): value is CheckpointEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'checkpoint') return false\n const status = value['status']\n if (typeof status !== 'string' || !CHECKPOINT_STATUSES.has(status)) return false\n return typeof value['key'] === 'string'\n}\n\n/**\n * A replay report: a step marked `side_effect` started before its resumed run\n * reached the gates in `suspend_ids`, so the work it does was already paid for\n * once. `step_id` names the step, and every gate id must be a string.\n */\nexport function is_step_replayed_event(value: unknown): value is StepReplayedEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'step_replayed') return false\n const suspend_ids = value['suspend_ids']\n if (!Array.isArray(suspend_ids)) return false\n const ids: ReadonlyArray<unknown> = suspend_ids\n return typeof value['step_id'] === 'string' && ids.every((id) => typeof id === 'string')\n}\n\n/**\n * A failed item of a `map` that settles: `step_id` names the map, `index` is\n * the item's position in the map's input, and `error` is the message. An\n * error that carried a `kind` adds it as `error_kind`.\n */\nexport function is_map_item_failed_event(value: unknown): value is MapItemFailedEvent {\n if (!is_custom_trajectory_event(value)) return false\n if (value.kind !== 'map_item_failed') return false\n return (\n typeof value['step_id'] === 'string' &&\n Number.isInteger(value['index']) &&\n typeof value['error'] === 'string'\n )\n}\n\n/**\n * Parse one wire value into a trajectory event, `safeParse`-shaped.\n *\n * On success `data` is the value itself, not a copy, so nothing on the line is\n * dropped or reordered on the way through.\n */\nexport function parse_trajectory_event(value: unknown): TrajectoryParseResult {\n if (!is_custom_trajectory_event(value)) {\n return {\n success: false,\n error: new Error(\"not a trajectory event: expected an object with a string 'kind'\"),\n }\n }\n return { success: true, data: value }\n}\n"],"mappings":";;;;;;;AAwGA,SAAgB,2BAA2B,OAAgD;CACzF,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,OAAQ,MAA6B,SAAS;AACvD;;AAGA,SAAgB,oBAAoB,OAAyC;CAC3E,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,cAAc,OAAO;CACxC,OAAO,OAAO,MAAM,eAAe,YAAY,OAAO,MAAM,YAAY;AAC1E;;AAGA,SAAgB,kBAAkB,OAAuC;CACvE,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,OAAO,MAAM,SAAS,cAAc,OAAO,MAAM,eAAe;AAClE;;AAGA,SAAgB,cAAc,OAAoC;CAChE,OAAO,2BAA2B,KAAK,KAAK,MAAM,SAAS;AAC7D;AAEA,MAAM,mCAAwC,IAAI,IAAI;CAAC;CAAQ;CAAU;CAAW;AAAW,CAAC;;;;;;AAOhG,SAAgB,iBAAiB,OAAsC;CACrE,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,WAAW,OAAO;CACrC,MAAM,SAAS,MAAM;CACrB,OAAO,OAAO,WAAW,YAAY,iBAAiB,IAAI,MAAM;AAClE;AAEA,MAAM,sCAA2C,IAAI,IAAI;CAAC;CAAO;CAAQ;AAAY,CAAC;;;;;;AAOtF,SAAgB,oBAAoB,OAA0C;CAC5E,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,cAAc,OAAO;CACxC,MAAM,SAAS,MAAM;CACrB,IAAI,OAAO,WAAW,YAAY,CAAC,oBAAoB,IAAI,MAAM,GAAG,OAAO;CAC3E,OAAO,OAAO,MAAM,WAAW;AACjC;;;;;;AAOA,SAAgB,uBAAuB,OAA4C;CACjF,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,iBAAiB,OAAO;CAC3C,MAAM,cAAc,MAAM;CAC1B,IAAI,CAAC,MAAM,QAAQ,WAAW,GAAG,OAAO;CACxC,MAAM,MAA8B;CACpC,OAAO,OAAO,MAAM,eAAe,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,QAAQ;AACzF;;;;;;AAOA,SAAgB,yBAAyB,OAA6C;CACpF,IAAI,CAAC,2BAA2B,KAAK,GAAG,OAAO;CAC/C,IAAI,MAAM,SAAS,mBAAmB,OAAO;CAC7C,OACE,OAAO,MAAM,eAAe,YAC5B,OAAO,UAAU,MAAM,QAAQ,KAC/B,OAAO,MAAM,aAAa;AAE9B;;;;;;;AAQA,SAAgB,uBAAuB,OAAuC;CAC5E,IAAI,CAAC,2BAA2B,KAAK,GACnC,OAAO;EACL,SAAS;EACT,uBAAO,IAAI,MAAM,iEAAiE;CACpF;CAEF,OAAO;EAAE,SAAS;EAAM,MAAM;CAAM;AACtC"}
@@ -14,6 +14,10 @@
14
14
  * distinguishes done / failed / aborted / suspended without
15
15
  * inferring from silence
16
16
  * checkpoint: checkpoint store lookup outcome (hit / miss / read_error)
17
+ * step_replayed: a step marked `side_effect` re-running before a resumed
18
+ * run reached the gates it was resumed at
19
+ * map_item_failed: an item of a `map` that settles threw, and its slot
20
+ * holds the error instead of a value
17
21
  * <other>: anything else, recognized by `is_custom_trajectory_event`,
18
22
  * which only requires a string `kind`
19
23
  *
@@ -64,12 +68,27 @@ type CheckpointEvent = {
64
68
  } & {
65
69
  readonly [key: string]: unknown;
66
70
  };
71
+ type StepReplayedEvent = {
72
+ readonly kind: 'step_replayed';
73
+ readonly step_id: string;
74
+ readonly suspend_ids: ReadonlyArray<string>;
75
+ } & {
76
+ readonly [key: string]: unknown;
77
+ };
78
+ type MapItemFailedEvent = {
79
+ readonly kind: 'map_item_failed';
80
+ readonly step_id: string;
81
+ readonly index: number;
82
+ readonly error: string;
83
+ } & {
84
+ readonly [key: string]: unknown;
85
+ };
67
86
  type CustomTrajectoryEvent = {
68
87
  readonly kind: string;
69
88
  } & {
70
89
  readonly [key: string]: unknown;
71
90
  };
72
- type ParsedTrajectoryEvent = SpanStartEvent | SpanEndEvent | EmitEvent | RunEndEvent | CheckpointEvent | CustomTrajectoryEvent;
91
+ type ParsedTrajectoryEvent = SpanStartEvent | SpanEndEvent | EmitEvent | RunEndEvent | CheckpointEvent | StepReplayedEvent | MapItemFailedEvent | CustomTrajectoryEvent;
73
92
  type TrajectoryParseResult = {
74
93
  readonly success: true;
75
94
  readonly data: ParsedTrajectoryEvent;
@@ -102,6 +121,18 @@ declare function is_run_end_event(value: unknown): value is RunEndEvent;
102
121
  * `is_run_end_event`.
103
122
  */
104
123
  declare function is_checkpoint_event(value: unknown): value is CheckpointEvent;
124
+ /**
125
+ * A replay report: a step marked `side_effect` started before its resumed run
126
+ * reached the gates in `suspend_ids`, so the work it does was already paid for
127
+ * once. `step_id` names the step, and every gate id must be a string.
128
+ */
129
+ declare function is_step_replayed_event(value: unknown): value is StepReplayedEvent;
130
+ /**
131
+ * A failed item of a `map` that settles: `step_id` names the map, `index` is
132
+ * the item's position in the map's input, and `error` is the message. An
133
+ * error that carried a `kind` adds it as `error_kind`.
134
+ */
135
+ declare function is_map_item_failed_event(value: unknown): value is MapItemFailedEvent;
105
136
  /**
106
137
  * Parse one wire value into a trajectory event, `safeParse`-shaped.
107
138
  *
@@ -110,5 +141,5 @@ declare function is_checkpoint_event(value: unknown): value is CheckpointEvent;
110
141
  */
111
142
  declare function parse_trajectory_event(value: unknown): TrajectoryParseResult;
112
143
  //#endregion
113
- export { parse_trajectory_event as _, ParsedTrajectoryEvent as a, SpanEndEvent as c, is_checkpoint_event as d, is_custom_trajectory_event as f, is_span_start_event as g, is_span_end_event as h, EmitEvent as i, SpanStartEvent as l, is_run_end_event as m, CheckpointStatus as n, RunEndEvent as o, is_emit_event as p, CustomTrajectoryEvent as r, RunEndStatus as s, CheckpointEvent as t, TrajectoryParseResult as u };
114
- //# sourceMappingURL=trajectory-ByoOQZ6T.d.ts.map
144
+ export { is_run_end_event as _, MapItemFailedEvent as a, is_step_replayed_event as b, RunEndStatus as c, StepReplayedEvent as d, TrajectoryParseResult as f, is_map_item_failed_event as g, is_emit_event as h, EmitEvent as i, SpanEndEvent as l, is_custom_trajectory_event as m, CheckpointStatus as n, ParsedTrajectoryEvent as o, is_checkpoint_event as p, CustomTrajectoryEvent as r, RunEndEvent as s, CheckpointEvent as t, SpanStartEvent as u, is_span_end_event as v, parse_trajectory_event as x, is_span_start_event as y };
145
+ //# sourceMappingURL=trajectory-Bm-mOtqw.d.ts.map
@@ -22,10 +22,41 @@ type TrajectoryLogger = {
22
22
  readonly start_span: (name: string, meta?: Record<string, unknown>) => string;
23
23
  readonly end_span: (id: string, meta?: Record<string, unknown>) => void;
24
24
  };
25
+ /**
26
+ * Where checkpointed results, and a durable run's own records, are kept.
27
+ *
28
+ * `get`, `set`, and `delete` are the whole contract `checkpoint` needs. A
29
+ * stored `null` or `undefined` reads as a miss, and so should a value the
30
+ * store can't read back whole.
31
+ *
32
+ * The rest are optional capabilities, and `durable` needs all three. `scope`
33
+ * hands out a store whose keys, claims, and nested scopes are disjoint from
34
+ * this one's, and the same prefix always reaches the same data. `claim` takes
35
+ * `key` for `owner` until `ttl_ms` passes and resolves true when the caller
36
+ * owns it afterwards: the key was free, its last claim expired or was
37
+ * released, or `owner` already held it (a renewal, which restarts the clock).
38
+ * It resolves false while another owner holds the key. `release` frees a
39
+ * claim `owner` holds and does nothing otherwise. Claims live apart from
40
+ * values, so a claim never changes what `get` returns and `set` or `delete`
41
+ * never touch a claim. `checkpoint_store_conformance` in `fascicle/testing`
42
+ * checks a store against all of this.
43
+ */
25
44
  type CheckpointStore = {
26
45
  readonly get: (key: string) => Promise<unknown>;
27
46
  readonly set: (key: string, value: unknown) => Promise<void>;
28
47
  readonly delete: (key: string) => Promise<void>;
48
+ readonly scope?: (prefix: string) => ScopedCheckpointStore;
49
+ readonly claim?: (key: string, owner: string, ttl_ms: number) => Promise<boolean>;
50
+ readonly release?: (key: string, owner: string) => Promise<void>;
51
+ };
52
+ /**
53
+ * A store reached through `scope(prefix)`. It can scope again, and `clear`
54
+ * deletes every value, claim, and nested scope under its prefix while leaving
55
+ * its parent and its siblings alone. A cleared scope stays usable.
56
+ */
57
+ type ScopedCheckpointStore = Omit<CheckpointStore, 'scope'> & {
58
+ readonly scope: (prefix: string) => ScopedCheckpointStore;
59
+ readonly clear: () => Promise<void>;
29
60
  };
30
61
  type CleanupFn = () => Promise<void> | void;
31
62
  type RunContext = {
@@ -46,10 +77,17 @@ type StepFn<i, o> = (input: i, ctx: RunContext) => Promise<o> | o;
46
77
  * Descriptive metadata for a step. `name` is the display channel: it labels
47
78
  * trajectory spans and `describe` output, and changing it is always safe
48
79
  * because nothing keys off it. The step's `id` stays the identity channel.
80
+ *
81
+ * `side_effect` marks a step that isn't free to run twice, because it bills
82
+ * you (every `model_call` sets it) or it changes something outside the run.
83
+ * When a resumed run runs a marked step before reaching the gate it was
84
+ * resumed at, the runner records a `step_replayed` event, so the cost of
85
+ * replaying shows up in the trajectory.
49
86
  */
50
87
  type StepMetadata = {
51
88
  readonly name?: string;
52
89
  readonly description?: string;
90
+ readonly side_effect?: boolean;
53
91
  readonly port_labels?: Readonly<{
54
92
  readonly in?: string;
55
93
  readonly out?: string;
@@ -126,5 +164,5 @@ type StepInput<s> = s extends Step<infer i, unknown> ? i : never;
126
164
  */
127
165
  type StepOutput<s> = s extends Step<never, infer o> ? o : unknown;
128
166
  //#endregion
129
- export { FlowValue as a, StepFn as c, StepOptions as d, StepOutput as f, FlowNode as i, StepInput as l, TrajectoryLogger as m, CheckpointStore as n, RunContext as o, TrajectoryEvent as p, CleanupFn as r, Step as s, AnyStep as t, StepMetadata as u };
130
- //# sourceMappingURL=types-BasW4Wwb.d.ts.map
167
+ export { FlowValue as a, Step as c, StepMetadata as d, StepOptions as f, TrajectoryLogger as h, FlowNode as i, StepFn as l, TrajectoryEvent as m, CheckpointStore as n, RunContext as o, StepOutput as p, CleanupFn as r, ScopedCheckpointStore as s, AnyStep as t, StepInput as u };
168
+ //# sourceMappingURL=types-CPqLZOEr.d.ts.map
@@ -1,6 +1,5 @@
1
- import { m as TrajectoryLogger } from "./types-BasW4Wwb.js";
1
+ import { h as TrajectoryLogger } from "./types-CPqLZOEr.js";
2
2
  import { r as ToolSchema } from "./types-BK0UW28o.js";
3
-
4
3
  //#region src/engine/providers/claude_cli/types.d.ts
5
4
  /**
6
5
  * Public types for the claude_cli subprocess provider.
@@ -54,7 +53,8 @@ type ClaudeCliProviderConfig = {
54
53
  * under `provider_reported['claude_cli']`. Read it with `claude_cli_reported`.
55
54
  */
56
55
  type ClaudeCliProviderReported = {
57
- readonly session_id: string; /** The CLI's own wall clock for the run, tool execution included. */
56
+ readonly session_id: string;
57
+ /** The CLI's own wall clock for the run, tool execution included. */
58
58
  readonly duration_ms: number;
59
59
  /**
60
60
  * Time the run spent in API requests, summed across its turns. Present
@@ -190,8 +190,11 @@ type SalvageFormat = 'hermes' | 'json' | 'qwen_xml';
190
190
  * emitting output. See `throughput()` for the derived tokens-per-second view.
191
191
  */
192
192
  type StepTiming = {
193
- /** Epoch ms when the successful provider attempt started. */started_at: number; /** Wall-clock ms from attempt start to the turn result. */
194
- duration_ms: number; /** Streamed turns only: ms from attempt start to the first dispatched chunk. */
193
+ /** Epoch ms when the successful provider attempt started. */
194
+ started_at: number;
195
+ /** Wall-clock ms from attempt start to the turn result. */
196
+ duration_ms: number;
197
+ /** Streamed turns only: ms from attempt start to the first dispatched chunk. */
195
198
  first_chunk_ms?: number;
196
199
  };
197
200
  /**
@@ -202,7 +205,9 @@ type StepTiming = {
202
205
  * narrower view of one turn's provider round-trip.
203
206
  */
204
207
  type GenerateTiming = {
205
- /** Epoch ms when the generate call started. */started_at: number; /** Wall-clock ms from the call's start to its result. */
208
+ /** Epoch ms when the generate call started. */
209
+ started_at: number;
210
+ /** Wall-clock ms from the call's start to its result. */
206
211
  duration_ms: number;
207
212
  };
208
213
  type ToolCallRecord = {
@@ -672,4 +677,4 @@ type Engine = {
672
677
  };
673
678
  //#endregion
674
679
  export { ToolExecContext as A, ProviderCapability as B, StepRecord as C, ToolApprovalHandler as D, Tool as E, AiSdkProviderAdapter as F, ClaudeCliProviderReported as G, ProviderTransport as H, EffortTranslation as I, ExternalAgentAdapter as L, TurnResult as M, UsageTotals as N, ToolApprovalRequest as O, UserContentPart as P, NativeProviderAdapter as R, RetryPolicy as S, StreamChunk as T, RawProviderUsage as U, ProviderFactory as V, default_normalize_usage as W, PricingTable as _, Engine as a, ResolvedModel as b, FinishReason as c, GenerateTiming as d, Message as f, Pricing as g, PrepareStepResult as h, EffortLevel as i, TurnRequest as j, ToolCallRecord as k, GenerateOptions as l, PrepareStepHook as m, AssistantContentPart as n, EngineConfig as o, PrepareStepContext as p, CostBreakdown as r, EngineDefaults as s, AiSdkTelemetrySettings as t, GenerateResult as u, ProviderConfigMap as v, StepTiming as w, RetryFailureKind as x, ProviderInit as y, ProviderAdapter as z };
675
- //# sourceMappingURL=types-bEpfDrys.d.ts.map
680
+ //# sourceMappingURL=types-CZ83Q5nm.d.ts.map
package/dist/ui.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { p as TrajectoryEvent } from "./types-BasW4Wwb.js";
1
+ import { m as TrajectoryEvent } from "./types-CPqLZOEr.js";
2
2
  import { UIMessageChunk } from "ai";
3
3
  import { ServerResponse } from "node:http";
4
-
5
4
  //#region src/ui/to_ui_message_stream.d.ts
6
5
  /**
7
6
  * The structural shape of a `run.stream(...)` handle. Typed structurally rather
@@ -13,7 +12,8 @@ type RunStreamLike = {
13
12
  readonly result: Promise<unknown>;
14
13
  };
15
14
  type ToUiStreamOptions = {
16
- /** Map a thrown run error to the text of an `error` part. */readonly on_error?: (error: unknown) => string;
15
+ /** Map a thrown run error to the text of an `error` part. */
16
+ readonly on_error?: (error: unknown) => string;
17
17
  };
18
18
  /**
19
19
  * Per-stream state: which text/reasoning blocks are open (so `*-start` fires
@@ -28,7 +28,7 @@ type UiMapperState = {
28
28
  /**
29
29
  * Create an empty `UiMapperState` for a new stream.
30
30
  */
31
- declare function create_ui_mapper_state(): UiMapperState;
31
+ export declare function create_ui_mapper_state(): UiMapperState;
32
32
  /**
33
33
  * Close every text/reasoning block still open in `state`, returning the
34
34
  * `*-end` chunks needed.
@@ -36,23 +36,24 @@ declare function create_ui_mapper_state(): UiMapperState;
36
36
  * Used on stream `finish` and to flush any blocks still open when the
37
37
  * underlying event iterable ends.
38
38
  */
39
- declare function close_open_blocks(state: UiMapperState): UIMessageChunk[];
39
+ export declare function close_open_blocks(state: UiMapperState): UIMessageChunk[];
40
40
  /**
41
41
  * Map one run event to zero or more UI message chunks, advancing `state`.
42
42
  * Non-`model_chunk` events (spans, cost, user emits) yield nothing.
43
43
  */
44
- declare function to_ui_message_chunks(event: TrajectoryEvent, state: UiMapperState): UIMessageChunk[];
44
+ export declare function to_ui_message_chunks(event: TrajectoryEvent, state: UiMapperState): UIMessageChunk[];
45
45
  /**
46
46
  * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint
47
47
  * can return directly.
48
48
  */
49
- declare function to_ui_message_response(handle: RunStreamLike, options?: ToUiStreamOptions): Response;
49
+ export declare function to_ui_message_response(handle: RunStreamLike, options?: ToUiStreamOptions): Response;
50
50
  /**
51
51
  * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for
52
52
  * `node:http` servers that hold a `ServerResponse` rather than returning a
53
- * web `Response`.
53
+ * web `Response`. Resolves once the stream has ended the response, or stopped
54
+ * because the client went away.
54
55
  */
55
- declare function pipe_ui_message_stream_to_response(handle: RunStreamLike, response: ServerResponse, options?: ToUiStreamOptions): void;
56
+ export declare function pipe_ui_message_stream_to_response(handle: RunStreamLike, response: ServerResponse, options?: ToUiStreamOptions): Promise<void>;
56
57
  //#endregion
57
- export { type RunStreamLike, type ToUiStreamOptions, type UiMapperState, close_open_blocks, create_ui_mapper_state, pipe_ui_message_stream_to_response, to_ui_message_chunks, to_ui_message_response };
58
+ export type { RunStreamLike, ToUiStreamOptions, UiMapperState };
58
59
  //# sourceMappingURL=ui.d.ts.map
package/dist/ui.js CHANGED
@@ -198,10 +198,11 @@ function to_ui_message_response(handle, options = {}) {
198
198
  /**
199
199
  * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for
200
200
  * `node:http` servers that hold a `ServerResponse` rather than returning a
201
- * web `Response`.
201
+ * web `Response`. Resolves once the stream has ended the response, or stopped
202
+ * because the client went away.
202
203
  */
203
204
  function pipe_ui_message_stream_to_response(handle, response, options = {}) {
204
- pipeUIMessageStreamToResponse({
205
+ return pipeUIMessageStreamToResponse({
205
206
  response,
206
207
  stream: build_stream(handle, options)
207
208
  });
package/dist/ui.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ui.js","names":[],"sources":["../src/ui/to_ui_message_stream.ts"],"sourcesContent":["/**\n * fascicle/ui: bridge a run's event stream to the AI SDK \"UI message stream\".\n *\n * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,\n * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.\n * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a\n * Fascicle flow can back a `useChat` endpoint rendered by AI Elements /\n * Streamdown, with zero bespoke glue.\n *\n * It is the outbound inverse of the engine's inbound provider->StreamChunk\n * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the\n * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this\n * file only translates chunk shapes and manages open text/reasoning blocks.\n *\n * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk\n * vocabulary has no generated-file kind (those provider parts drop at the\n * inbound mapping), so there is nothing here to translate them from.\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n pipeUIMessageStreamToResponse,\n} from 'ai'\nimport type { UIMessageChunk } from 'ai'\nimport type { ServerResponse } from 'node:http'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\n\n/**\n * The structural shape of a `run.stream(...)` handle. Typed structurally rather\n * than importing the core `StreamingRunHandle` so this module depends on no\n * core value and a caller can pass `run.stream(...)` directly.\n */\nexport type RunStreamLike = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<unknown>\n}\n\nexport type ToUiStreamOptions = {\n /** Map a thrown run error to the text of an `error` part. */\n readonly on_error?: (error: unknown) => string\n}\n\n/**\n * Per-stream state: which text/reasoning blocks are open (so `*-start` fires\n * once and `*-end` closes them) and the tool name for each in-flight call (so\n * `tool-input-available` can echo it after only the id arrives at close).\n */\nexport type UiMapperState = {\n readonly open_text: Set<number>\n readonly open_reasoning: Set<number>\n readonly tool_names: Map<string, string>\n}\n\n/**\n * Create an empty `UiMapperState` for a new stream.\n */\nexport function create_ui_mapper_state(): UiMapperState {\n return { open_text: new Set(), open_reasoning: new Set(), tool_names: new Map() }\n}\n\n/**\n * Build the UI message chunk id for a step's text block.\n */\nfunction text_id(step_index: number): string {\n return `text-${step_index}`\n}\n\n/**\n * Build the UI message chunk id for a step's reasoning block.\n */\nfunction reasoning_id(step_index: number): string {\n return `reasoning-${step_index}`\n}\n\n/**\n * Close the text/reasoning blocks open for one step, returning the\n * `*-end` chunks needed and updating `state` in place.\n *\n * Called on a `step_finish` chunk, so only that step's blocks close; blocks\n * open for other steps are untouched.\n */\nfunction close_step_blocks(step_index: number, state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n if (state.open_text.delete(step_index)) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n if (state.open_reasoning.delete(step_index)) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n return parts\n}\n\n/**\n * Close every text/reasoning block still open in `state`, returning the\n * `*-end` chunks needed.\n *\n * Used on stream `finish` and to flush any blocks still open when the\n * underlying event iterable ends.\n */\nexport function close_open_blocks(state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n for (const step_index of state.open_text) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n for (const step_index of state.open_reasoning) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n state.open_text.clear()\n state.open_reasoning.clear()\n return parts\n}\n\n/**\n * Map a single engine `StreamChunk` to the `UIMessageChunk`s it produces,\n * opening and closing text/reasoning blocks in `state` as needed.\n */\nfunction map_chunk(chunk: StreamChunk, state: UiMapperState): UIMessageChunk[] {\n switch (chunk.kind) {\n case 'text': {\n const id = text_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_text.has(chunk.step_index)) {\n state.open_text.add(chunk.step_index)\n parts.push({ type: 'text-start', id })\n }\n parts.push({ type: 'text-delta', id, delta: chunk.text })\n return parts\n }\n case 'reasoning': {\n const id = reasoning_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_reasoning.has(chunk.step_index)) {\n state.open_reasoning.add(chunk.step_index)\n parts.push({ type: 'reasoning-start', id })\n }\n parts.push({ type: 'reasoning-delta', id, delta: chunk.text })\n return parts\n }\n case 'tool_call_start': {\n state.tool_names.set(chunk.id, chunk.name)\n return [{ type: 'tool-input-start', toolCallId: chunk.id, toolName: chunk.name }]\n }\n case 'tool_call_input_delta':\n return [{ type: 'tool-input-delta', toolCallId: chunk.id, inputTextDelta: chunk.delta }]\n case 'tool_call_end':\n return [\n {\n type: 'tool-input-available',\n toolCallId: chunk.id,\n toolName: state.tool_names.get(chunk.id) ?? '',\n input: chunk.input,\n },\n ]\n case 'tool_result':\n return chunk.error !== undefined\n ? [{ type: 'tool-output-error', toolCallId: chunk.id, errorText: chunk.error.message }]\n : [{ type: 'tool-output-available', toolCallId: chunk.id, output: chunk.output }]\n case 'step_finish':\n return close_step_blocks(chunk.step_index, state)\n case 'finish':\n return close_open_blocks(state)\n default:\n return []\n }\n}\n\n/**\n * Narrow an untyped `TrajectoryEvent['chunk']` payload to a `StreamChunk`\n * when it looks like one (an object with a string `kind`), otherwise\n * return `undefined`.\n */\nfunction as_stream_chunk(value: unknown): StreamChunk | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const kind = Reflect.get(value, 'kind')\n if (typeof kind !== 'string') return undefined\n // The value rode a loose TrajectoryEvent bag; model_call only records real\n // StreamChunks under `chunk`, and map_chunk narrows on `kind`, so treating it\n // as a StreamChunk is sound. Unknown kinds fall through to `[]`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as StreamChunk\n}\n\n/**\n * Map one run event to zero or more UI message chunks, advancing `state`.\n * Non-`model_chunk` events (spans, cost, user emits) yield nothing.\n */\nexport function to_ui_message_chunks(\n event: TrajectoryEvent,\n state: UiMapperState,\n): UIMessageChunk[] {\n if (event.kind !== 'model_chunk') return []\n const chunk = as_stream_chunk(event['chunk'])\n return chunk === undefined ? [] : map_chunk(chunk, state)\n}\n\n/**\n * Build the `ReadableStream<UIMessageChunk>` that drives a `run.stream(...)`\n * handle through `to_ui_message_chunks`, used by both the `Response` and\n * Node `ServerResponse` entry points below.\n */\nfunction build_stream(\n handle: RunStreamLike,\n options: ToUiStreamOptions,\n): ReadableStream<UIMessageChunk> {\n const on_error = options.on_error\n return createUIMessageStream({\n execute: async ({ writer }) => {\n const state = create_ui_mapper_state()\n for await (const event of handle.events) {\n for (const part of to_ui_message_chunks(event, state)) writer.write(part)\n }\n for (const part of close_open_blocks(state)) writer.write(part)\n await handle.result\n },\n ...(on_error !== undefined ? { onError: on_error } : {}),\n })\n}\n\n/**\n * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint\n * can return directly.\n */\nexport function to_ui_message_response(\n handle: RunStreamLike,\n options: ToUiStreamOptions = {},\n): Response {\n return createUIMessageStreamResponse({ stream: build_stream(handle, options) })\n}\n\n/**\n * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for\n * `node:http` servers that hold a `ServerResponse` rather than returning a\n * web `Response`.\n */\nexport function pipe_ui_message_stream_to_response(\n handle: RunStreamLike,\n response: ServerResponse,\n options: ToUiStreamOptions = {},\n): void {\n pipeUIMessageStreamToResponse({ response, stream: build_stream(handle, options) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,IAAI,IAAI;CAAE;AAClF;;;;AAKA,SAAS,QAAQ,YAA4B;CAC3C,OAAO,QAAQ;AACjB;;;;AAKA,SAAS,aAAa,YAA4B;CAChD,OAAO,aAAa;AACtB;;;;;;;;AASA,SAAS,kBAAkB,YAAoB,OAAwC;CACrF,MAAM,QAA0B,CAAC;CACjC,IAAI,MAAM,UAAU,OAAO,UAAU,GACnC,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,IAAI,MAAM,eAAe,OAAO,UAAU,GACxC,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,aAAa,UAAU;CAAE,CAAC;CAEpE,OAAO;AACT;;;;;;;;AASA,SAAgB,kBAAkB,OAAwC;CACxE,MAAM,QAA0B,CAAC;CACjC,KAAK,MAAM,cAAc,MAAM,WAC7B,MAAM,KAAK;EAAE,MAAM;EAAY,IAAI,QAAQ,UAAU;CAAE,CAAC;CAE1D,KAAK,MAAM,cAAc,MAAM,gBAC7B,MAAM,KAAK;EAAE,MAAM;EAAiB,IAAI,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+ {"version":3,"file":"ui.js","names":[],"sources":["../src/ui/to_ui_message_stream.ts"],"sourcesContent":["/**\n * fascicle/ui: bridge a run's event stream to the AI SDK \"UI message stream\".\n *\n * `run.stream(flow, input)` yields `TrajectoryEvent`s; under streaming,\n * `model_call` records `model_chunk` events carrying an engine `StreamChunk`.\n * This module maps those chunks onto the AI SDK `UIMessageChunk` protocol so a\n * Fascicle flow can back a `useChat` endpoint rendered by AI Elements /\n * Streamdown, with zero bespoke glue.\n *\n * It is the outbound inverse of the engine's inbound provider->StreamChunk\n * mapping. The wire framing (SSE, `data:` lines, terminal `[DONE]`, the\n * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this\n * file only translates chunk shapes and manages open text/reasoning blocks.\n *\n * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk\n * vocabulary has no generated-file kind (those provider parts drop at the\n * inbound mapping), so there is nothing here to translate them from.\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n pipeUIMessageStreamToResponse,\n} from 'ai'\nimport type { UIMessageChunk } from 'ai'\nimport type { ServerResponse } from 'node:http'\nimport type { TrajectoryEvent } from '#core'\nimport type { StreamChunk } from '#engine'\n\n/**\n * The structural shape of a `run.stream(...)` handle. Typed structurally rather\n * than importing the core `StreamingRunHandle` so this module depends on no\n * core value and a caller can pass `run.stream(...)` directly.\n */\nexport type RunStreamLike = {\n readonly events: AsyncIterable<TrajectoryEvent>\n readonly result: Promise<unknown>\n}\n\nexport type ToUiStreamOptions = {\n /** Map a thrown run error to the text of an `error` part. */\n readonly on_error?: (error: unknown) => string\n}\n\n/**\n * Per-stream state: which text/reasoning blocks are open (so `*-start` fires\n * once and `*-end` closes them) and the tool name for each in-flight call (so\n * `tool-input-available` can echo it after only the id arrives at close).\n */\nexport type UiMapperState = {\n readonly open_text: Set<number>\n readonly open_reasoning: Set<number>\n readonly tool_names: Map<string, string>\n}\n\n/**\n * Create an empty `UiMapperState` for a new stream.\n */\nexport function create_ui_mapper_state(): UiMapperState {\n return { open_text: new Set(), open_reasoning: new Set(), tool_names: new Map() }\n}\n\n/**\n * Build the UI message chunk id for a step's text block.\n */\nfunction text_id(step_index: number): string {\n return `text-${step_index}`\n}\n\n/**\n * Build the UI message chunk id for a step's reasoning block.\n */\nfunction reasoning_id(step_index: number): string {\n return `reasoning-${step_index}`\n}\n\n/**\n * Close the text/reasoning blocks open for one step, returning the\n * `*-end` chunks needed and updating `state` in place.\n *\n * Called on a `step_finish` chunk, so only that step's blocks close; blocks\n * open for other steps are untouched.\n */\nfunction close_step_blocks(step_index: number, state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n if (state.open_text.delete(step_index)) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n if (state.open_reasoning.delete(step_index)) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n return parts\n}\n\n/**\n * Close every text/reasoning block still open in `state`, returning the\n * `*-end` chunks needed.\n *\n * Used on stream `finish` and to flush any blocks still open when the\n * underlying event iterable ends.\n */\nexport function close_open_blocks(state: UiMapperState): UIMessageChunk[] {\n const parts: UIMessageChunk[] = []\n for (const step_index of state.open_text) {\n parts.push({ type: 'text-end', id: text_id(step_index) })\n }\n for (const step_index of state.open_reasoning) {\n parts.push({ type: 'reasoning-end', id: reasoning_id(step_index) })\n }\n state.open_text.clear()\n state.open_reasoning.clear()\n return parts\n}\n\n/**\n * Map a single engine `StreamChunk` to the `UIMessageChunk`s it produces,\n * opening and closing text/reasoning blocks in `state` as needed.\n */\nfunction map_chunk(chunk: StreamChunk, state: UiMapperState): UIMessageChunk[] {\n switch (chunk.kind) {\n case 'text': {\n const id = text_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_text.has(chunk.step_index)) {\n state.open_text.add(chunk.step_index)\n parts.push({ type: 'text-start', id })\n }\n parts.push({ type: 'text-delta', id, delta: chunk.text })\n return parts\n }\n case 'reasoning': {\n const id = reasoning_id(chunk.step_index)\n const parts: UIMessageChunk[] = []\n if (!state.open_reasoning.has(chunk.step_index)) {\n state.open_reasoning.add(chunk.step_index)\n parts.push({ type: 'reasoning-start', id })\n }\n parts.push({ type: 'reasoning-delta', id, delta: chunk.text })\n return parts\n }\n case 'tool_call_start': {\n state.tool_names.set(chunk.id, chunk.name)\n return [{ type: 'tool-input-start', toolCallId: chunk.id, toolName: chunk.name }]\n }\n case 'tool_call_input_delta':\n return [{ type: 'tool-input-delta', toolCallId: chunk.id, inputTextDelta: chunk.delta }]\n case 'tool_call_end':\n return [\n {\n type: 'tool-input-available',\n toolCallId: chunk.id,\n toolName: state.tool_names.get(chunk.id) ?? '',\n input: chunk.input,\n },\n ]\n case 'tool_result':\n return chunk.error !== undefined\n ? [{ type: 'tool-output-error', toolCallId: chunk.id, errorText: chunk.error.message }]\n : [{ type: 'tool-output-available', toolCallId: chunk.id, output: chunk.output }]\n case 'step_finish':\n return close_step_blocks(chunk.step_index, state)\n case 'finish':\n return close_open_blocks(state)\n default:\n return []\n }\n}\n\n/**\n * Narrow an untyped `TrajectoryEvent['chunk']` payload to a `StreamChunk`\n * when it looks like one (an object with a string `kind`), otherwise\n * return `undefined`.\n */\nfunction as_stream_chunk(value: unknown): StreamChunk | undefined {\n if (typeof value !== 'object' || value === null) return undefined\n const kind = Reflect.get(value, 'kind')\n if (typeof kind !== 'string') return undefined\n // The value rode a loose TrajectoryEvent bag; model_call only records real\n // StreamChunks under `chunk`, and map_chunk narrows on `kind`, so treating it\n // as a StreamChunk is sound. Unknown kinds fall through to `[]`.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return value as StreamChunk\n}\n\n/**\n * Map one run event to zero or more UI message chunks, advancing `state`.\n * Non-`model_chunk` events (spans, cost, user emits) yield nothing.\n */\nexport function to_ui_message_chunks(\n event: TrajectoryEvent,\n state: UiMapperState,\n): UIMessageChunk[] {\n if (event.kind !== 'model_chunk') return []\n const chunk = as_stream_chunk(event['chunk'])\n return chunk === undefined ? [] : map_chunk(chunk, state)\n}\n\n/**\n * Build the `ReadableStream<UIMessageChunk>` that drives a `run.stream(...)`\n * handle through `to_ui_message_chunks`, used by both the `Response` and\n * Node `ServerResponse` entry points below.\n */\nfunction build_stream(\n handle: RunStreamLike,\n options: ToUiStreamOptions,\n): ReadableStream<UIMessageChunk> {\n const on_error = options.on_error\n return createUIMessageStream({\n execute: async ({ writer }) => {\n const state = create_ui_mapper_state()\n for await (const event of handle.events) {\n for (const part of to_ui_message_chunks(event, state)) writer.write(part)\n }\n for (const part of close_open_blocks(state)) writer.write(part)\n await handle.result\n },\n ...(on_error !== undefined ? { onError: on_error } : {}),\n })\n}\n\n/**\n * Turn a `run.stream(...)` handle into an SSE `Response` a `useChat` endpoint\n * can return directly.\n */\nexport function to_ui_message_response(\n handle: RunStreamLike,\n options: ToUiStreamOptions = {},\n): Response {\n return createUIMessageStreamResponse({ stream: build_stream(handle, options) })\n}\n\n/**\n * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for\n * `node:http` servers that hold a `ServerResponse` rather than returning a\n * web `Response`. Resolves once the stream has ended the response, or stopped\n * because the client went away.\n */\nexport function pipe_ui_message_stream_to_response(\n handle: RunStreamLike,\n response: ServerResponse,\n options: ToUiStreamOptions = {},\n): Promise<void> {\n return pipeUIMessageStreamToResponse({ response, stream: build_stream(handle, options) })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,IAAI,IAAI;CAAE;AAClF;;;;AAKA,SAAS,QAAQ,YAA4B;CAC3C,OAAO,QAAQ;AACjB;;;;AAKA,SAAS,aAAa,YAA4B;CAChD,OAAO,aAAa;AACtB;;;;;;;;AASA,SAAS,kBAAkB,YAAoB,OAAwC;CACrF,MAAM,QAA0B,CAAC;CACjC,IAAI,MAAM,UAAU,OAAO,UAAU,GACnC,MAAM,KAAK;EAAE,MAAM;EAAY,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