fascicle 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/README.md +8 -8
  3. package/dist/acp.d.ts +9 -2
  4. package/dist/acp.js +1538 -1472
  5. package/dist/acp.js.map +1 -1
  6. package/dist/{adapters-DNnzeLxr.js → adapters-CDUzZlby.js} +35 -13
  7. package/dist/adapters-CDUzZlby.js.map +1 -0
  8. package/dist/adapters.d.ts +8 -1
  9. package/dist/adapters.js +1 -1
  10. package/dist/agents.d.ts +1 -1
  11. package/dist/agents.js +15 -8
  12. package/dist/agents.js.map +1 -1
  13. package/dist/bin/fascicle-viewer.js +4 -1
  14. package/dist/console-CdB4pcFO.js +37 -0
  15. package/dist/console-CdB4pcFO.js.map +1 -0
  16. package/dist/{core-CDrz0NM1.js → core-CErsxGF6.js} +246 -147
  17. package/dist/core-CErsxGF6.js.map +1 -0
  18. package/dist/diagram_bin.js +2 -2
  19. package/dist/diagram_bin.js.map +1 -1
  20. package/dist/{engine-ha9xmgwE.js → engine-CR8q2IqV.js} +173 -67
  21. package/dist/engine-CR8q2IqV.js.map +1 -0
  22. package/dist/index.d.ts +529 -73
  23. package/dist/index.js +440 -137
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-px31fffH.js → invoke-COaeZ-vy.js} +6 -5
  26. package/dist/invoke-COaeZ-vy.js.map +1 -0
  27. package/dist/{json_schema_to_standard-BTWD0J6p.js → json_schema_to_standard-C4F4lXHE.js} +9 -12
  28. package/dist/json_schema_to_standard-C4F4lXHE.js.map +1 -0
  29. package/dist/{leading_system-DfJLqpGi.js → leading_system-PoHzNHuV.js} +28 -8
  30. package/dist/leading_system-PoHzNHuV.js.map +1 -0
  31. package/dist/mcp.d.ts +3 -2
  32. package/dist/mcp.js +8 -4
  33. package/dist/mcp.js.map +1 -1
  34. package/dist/otel.js +10 -10
  35. package/dist/otel.js.map +1 -1
  36. package/dist/{search-CA_OqFeW.js → search-CpCJYMUm.js} +53 -6
  37. package/dist/search-CpCJYMUm.js.map +1 -0
  38. package/dist/search_worker.js +1 -1
  39. package/dist/stdio.js +7 -3
  40. package/dist/stdio.js.map +1 -1
  41. package/dist/testing.d.ts +1 -1
  42. package/dist/testing.js +3 -3
  43. package/dist/testing.js.map +1 -1
  44. package/dist/{trajectory-Bm-mOtqw.d.ts → trajectory-BKGNxi7u.d.ts} +10 -9
  45. package/dist/{trajectory-BI-mrVFT.js → trajectory-DeURWIhj.js} +6 -5
  46. package/dist/trajectory-DeURWIhj.js.map +1 -0
  47. package/dist/{types-De-TVQxS.d.ts → types-Sw0oHW-_.d.ts} +6 -7
  48. package/dist/ui.d.ts +2 -1
  49. package/dist/ui.js +8 -1
  50. package/dist/ui.js.map +1 -1
  51. package/dist/viewer-app/assets/index-BYF5Dp7d.js +2 -0
  52. package/dist/viewer-app/index.html +2 -1
  53. package/dist/viewer.d.ts +26 -12
  54. package/dist/viewer.js +282 -63
  55. package/dist/viewer.js.map +1 -1
  56. package/package.json +4 -4
  57. package/dist/adapters-DNnzeLxr.js.map +0 -1
  58. package/dist/core-CDrz0NM1.js.map +0 -1
  59. package/dist/engine-ha9xmgwE.js.map +0 -1
  60. package/dist/invoke-px31fffH.js.map +0 -1
  61. package/dist/json_schema_to_standard-BTWD0J6p.js.map +0 -1
  62. package/dist/leading_system-DfJLqpGi.js.map +0 -1
  63. package/dist/search-CA_OqFeW.js.map +0 -1
  64. package/dist/trajectory-BI-mrVFT.js.map +0 -1
  65. package/dist/viewer-app/assets/index-Fnh5HKSU.js +0 -2
@@ -1 +1 @@
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,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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. The stub,\n * script, and capture factories share this shell so a test double differs\n * from a real 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;A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9C,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"}
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * `TrajectoryEvent` (in `types.ts`) is the loose internal type — any code that
6
6
  * calls `trajectory.record(event)` or `start_span(name, meta)` produces values
7
- * conforming to it. This file defines the *narrower* shapes that the studio
7
+ * conforming to it. This file defines the *narrower* shapes that the viewer
8
8
  * (and any other downstream consumer) can recognize in the wire stream:
9
9
  *
10
10
  * span_start: composer span open
@@ -13,7 +13,8 @@
13
13
  * run_end: terminal run event carrying the run's status, so a consumer
14
14
  * distinguishes done / failed / aborted / suspended without
15
15
  * inferring from silence
16
- * checkpoint: checkpoint store lookup outcome (hit / miss / read_error)
16
+ * checkpoint: checkpoint store outcome (hit / miss / read_error /
17
+ * write_error)
17
18
  * step_replayed: a step marked `side_effect` re-running before a resumed
18
19
  * run reached the gates it was resumed at
19
20
  * map_item_failed: an item of a `map` that settles threw, and its slot
@@ -28,8 +29,8 @@
28
29
  * the wire, just not a `SpanStartEvent`. Anything stricter would have a viewer
29
30
  * drop lines a newer producer emits, which is the opposite of what a
30
31
  * forward-compatible wire format is for. `is_custom_trajectory_event` therefore
31
- * answers `true` for well-known kinds too: it is the fallback shape, not a
32
- * fifth disjoint case.
32
+ * answers `true` for well-known kinds too: it is the fallback shape, not
33
+ * another disjoint case.
33
34
  *
34
35
  * Extra fields (`run_id`, `id`, provider-specific metadata) are neither
35
36
  * required nor stripped: a successful parse hands the value straight back, so a
@@ -60,7 +61,7 @@ type RunEndEvent = {
60
61
  } & {
61
62
  readonly [key: string]: unknown;
62
63
  };
63
- type CheckpointStatus = 'hit' | 'miss' | 'read_error';
64
+ type CheckpointStatus = 'hit' | 'miss' | 'read_error' | 'write_error';
64
65
  type CheckpointEvent = {
65
66
  readonly kind: 'checkpoint';
66
67
  readonly status: CheckpointStatus;
@@ -116,9 +117,9 @@ declare function is_emit_event(value: unknown): value is EmitEvent;
116
117
  */
117
118
  declare function is_run_end_event(value: unknown): value is RunEndEvent;
118
119
  /**
119
- * A checkpoint lookup event: `status` must be a known lookup outcome and `key`
120
- * the store key that was consulted, for the same truthful-narrowing reason as
121
- * `is_run_end_event`.
120
+ * A checkpoint event: `status` must be a known outcome of the store lookup or
121
+ * of the write after a miss, and `key` the store key that was consulted, for
122
+ * the same truthful-narrowing reason as `is_run_end_event`.
122
123
  */
123
124
  declare function is_checkpoint_event(value: unknown): value is CheckpointEvent;
124
125
  /**
@@ -142,4 +143,4 @@ declare function is_map_item_failed_event(value: unknown): value is MapItemFaile
142
143
  declare function parse_trajectory_event(value: unknown): TrajectoryParseResult;
143
144
  //#endregion
144
145
  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
146
+ //# sourceMappingURL=trajectory-BKGNxi7u.d.ts.map
@@ -45,12 +45,13 @@ function is_run_end_event(value) {
45
45
  const CHECKPOINT_STATUSES = /* @__PURE__ */ new Set([
46
46
  "hit",
47
47
  "miss",
48
- "read_error"
48
+ "read_error",
49
+ "write_error"
49
50
  ]);
50
51
  /**
51
- * A checkpoint lookup event: `status` must be a known lookup outcome and `key`
52
- * the store key that was consulted, for the same truthful-narrowing reason as
53
- * `is_run_end_event`.
52
+ * A checkpoint event: `status` must be a known outcome of the store lookup or
53
+ * of the write after a miss, and `key` the store key that was consulted, for
54
+ * the same truthful-narrowing reason as `is_run_end_event`.
54
55
  */
55
56
  function is_checkpoint_event(value) {
56
57
  if (!is_custom_trajectory_event(value)) return false;
@@ -101,4 +102,4 @@ function parse_trajectory_event(value) {
101
102
  //#endregion
102
103
  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 };
103
104
 
104
- //# sourceMappingURL=trajectory-BI-mrVFT.js.map
105
+ //# sourceMappingURL=trajectory-DeURWIhj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trajectory-DeURWIhj.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 viewer\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 outcome (hit / miss / read_error /\n * write_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\n * another 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' | 'write_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', 'write_error'])\n\n/**\n * A checkpoint event: `status` must be a known outcome of the store lookup or\n * of the write after a miss, and `key` the store key that was consulted, for\n * the same truthful-narrowing reason as `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: exp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,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"}
@@ -46,7 +46,6 @@ type ClaudeCliProviderConfig = {
46
46
  readonly setting_sources?: ReadonlyArray<'user' | 'project' | 'local'>;
47
47
  readonly plugin_dirs?: ReadonlyArray<string>;
48
48
  readonly sandbox?: SandboxProviderConfig;
49
- readonly skip_probe?: boolean;
50
49
  };
51
50
  /**
52
51
  * What the claude CLI's terminal `result` event reports about a run, found
@@ -139,7 +138,7 @@ declare function default_normalize_usage(raw: RawProviderUsage | undefined): Usa
139
138
  //#endregion
140
139
  //#region src/engine/types.d.ts
141
140
  type EffortLevel = 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
142
- type FinishReason = 'stop' | 'tool_calls' | 'length' | 'content_filter' | 'aborted' | 'max_steps';
141
+ type FinishReason = 'stop' | 'tool_calls' | 'length' | 'content_filter' | 'max_steps';
143
142
  type RetryFailureKind = 'rate_limit' | 'provider_5xx' | 'network' | 'timeout';
144
143
  type RetryPolicy = {
145
144
  max_attempts: number;
@@ -331,7 +330,7 @@ type Tool<i = unknown, o = unknown> = {
331
330
  * deterministically: the loop executes the call (recording its output and
332
331
  * trajectory events like any tool), then stops instead of running another
333
332
  * model turn. A denied, invalid, dropped, or throwing terminal call does NOT
334
- * end the loop. undefined (the default) preserves the prior loop exactly.
333
+ * end the loop. undefined (the default) never ends the loop early.
335
334
  */
336
335
  ends_turn?: boolean;
337
336
  };
@@ -628,7 +627,7 @@ type ProviderConfigMap = {
628
627
  [custom: string]: ProviderInit | undefined;
629
628
  };
630
629
  /**
631
- * Opt-in OpenTelemetry for the `ai_sdk` transport (D7, Layer 2). When `enabled`,
630
+ * Opt-in OpenTelemetry for the `ai_sdk` transport (Layer 2). When `enabled`,
632
631
  * the transport constructs an `@ai-sdk/otel` integration strictly below the turn
633
632
  * seam and hands it to the SDK's telemetry, so generateText / streamText emit
634
633
  * turn-internal spans on the ai_sdk transport only. Native transports ignore it;
@@ -676,7 +675,7 @@ type EngineDefaults = {
676
675
  readonly max_tool_calls_per_step?: number;
677
676
  readonly provider_options?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
678
677
  /**
679
- * Opt-in OpenTelemetry for the `ai_sdk` transport (D7, Layer 2). Enabling it
678
+ * Opt-in OpenTelemetry for the `ai_sdk` transport (Layer 2). Enabling it
680
679
  * makes every ai_sdk-transport generate call emit turn-internal spans via
681
680
  * `@ai-sdk/otel`; native transports ignore it. See AiSdkTelemetrySettings.
682
681
  */
@@ -721,5 +720,5 @@ type Engine = {
721
720
  dispose: () => Promise<void>;
722
721
  };
723
722
  //#endregion
724
- export { ToolCallRecord as A, ProviderAdapter as B, RetryPolicy as C, Tool as D, StreamChunk as E, UserContentPart as F, default_normalize_usage as G, ProviderFactory as H, AiSdkProviderAdapter as I, ClaudeCliProviderReported as K, EffortTranslation as L, TurnRequest as M, TurnResult as N, ToolApprovalHandler as O, UsageTotals as P, ExternalAgentAdapter as R, RetryFailureKind as S, StepTiming as T, ProviderTransport as U, ProviderCapability as V, RawProviderUsage as W, PricingTable as _, Engine as a, ProviderOptions as b, FinishReason as c, GenerateTiming as d, Message as f, Pricing as g, PrepareStepResult as h, EffortLevel as i, ToolExecContext as j, ToolApprovalRequest 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, StepRecord as w, ResolvedModel as x, ProviderInit as y, NativeProviderAdapter as z };
725
- //# sourceMappingURL=types-De-TVQxS.d.ts.map
723
+ export { ToolApprovalHandler as A, ExternalAgentAdapter as B, ResolvedModel as C, StepTiming as D, StepRecord as E, TurnResult as F, ProviderTransport as G, ProviderAdapter as H, UsageTotals as I, ClaudeCliProviderReported as J, RawProviderUsage as K, UserContentPart as L, ToolCallRecord as M, ToolExecContext as N, StreamChunk as O, TurnRequest as P, AiSdkProviderAdapter as R, ProviderOptions as S, RetryPolicy as T, ProviderCapability as U, NativeProviderAdapter as V, ProviderFactory as W, PrepareStepResult as _, CostBreakdown as a, ProviderConfigMap as b, EngineConfig as c, GenerateOptions as d, GenerateResult as f, PrepareStepHook as g, PrepareStepContext as h, BedrockCredentials as i, ToolApprovalRequest as j, Tool as k, EngineDefaults as l, Message as m, AssistantContentPart as n, EffortLevel as o, GenerateTiming as p, default_normalize_usage as q, BedrockCredentialProvider as r, Engine as s, AiSdkTelemetrySettings as t, FinishReason as u, Pricing as v, RetryFailureKind as w, ProviderInit as x, PricingTable as y, EffortTranslation as z };
724
+ //# sourceMappingURL=types-Sw0oHW-_.d.ts.map
package/dist/ui.d.ts CHANGED
@@ -51,7 +51,8 @@ export declare function to_ui_message_response(handle: RunStreamLike, options?:
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
53
  * web `Response`. Resolves once the stream has ended the response, or stopped
54
- * because the client went away.
54
+ * because the client went away, which leaves the run going unless its `abort`
55
+ * signal fires too.
55
56
  */
56
57
  export declare function pipe_ui_message_stream_to_response(handle: RunStreamLike, response: ServerResponse, options?: ToUiStreamOptions): Promise<void>;
57
58
  //#endregion
package/dist/ui.js CHANGED
@@ -14,6 +14,12 @@ import { createUIMessageStream, createUIMessageStreamResponse, pipeUIMessageStre
14
14
  * `x-vercel-ai-ui-message-stream` header) is owned by the `ai` builders; this
15
15
  * file only translates chunk shapes and manages open text/reasoning blocks.
16
16
  *
17
+ * The stream alone doesn't stop the run. A client that disconnects ends the
18
+ * response, but the run keeps calling the model until its flow finishes. To
19
+ * stop it with the client, pass `run.stream` an `abort` signal that fires on
20
+ * disconnect: the route handler's `request.signal`, or a controller that the
21
+ * Node response's `close` event aborts.
22
+ *
17
23
  * v7's `file`/`reasoning-file` UI parts are never emitted: the engine chunk
18
24
  * vocabulary has no generated-file kind (those provider parts drop at the
19
25
  * inbound mapping), so there is nothing here to translate them from.
@@ -199,7 +205,8 @@ function to_ui_message_response(handle, options = {}) {
199
205
  * Pipe a `run.stream(...)` handle to a Node `http.ServerResponse` as SSE, for
200
206
  * `node:http` servers that hold a `ServerResponse` rather than returning a
201
207
  * web `Response`. Resolves once the stream has ended the response, or stopped
202
- * because the client went away.
208
+ * because the client went away, which leaves the run going unless its `abort`
209
+ * signal fires too.
203
210
  */
204
211
  function pipe_ui_message_stream_to_response(handle, response, options = {}) {
205
212
  return pipeUIMessageStreamToResponse({
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`. 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,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,C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C,GACf;CACf,OAAO,8BAA8B;EAAE;EAAU,QAAQ,aAAa,QAAQ,OAAO;CAAE,CAAC;AAC1F"}
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 * The stream alone doesn't stop the run. A client that disconnects ends the\n * response, but the run keeps calling the model until its flow finishes. To\n * stop it with the client, pass `run.stream` an `abort` signal that fires on\n * disconnect: the route handler's `request.signal`, or a controller that the\n * Node response's `close` event aborts.\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, which leaves the run going unless its `abort`\n * signal fires too.\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,yBAAwC;CACtD,OAAO;EAAE,2BAAW,IAAI,IAAI;EAAG,gCAAgB,IAAI,IAAI;EAAG,4BAAY,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