fascicle 0.18.1 → 0.19.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 (51) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +27 -1
  3. package/dist/AGENTS.md +11 -10
  4. package/dist/a2a.d.ts +358 -0
  5. package/dist/a2a.js +2234 -0
  6. package/dist/a2a.js.map +1 -0
  7. package/dist/acp.d.ts +120 -9
  8. package/dist/acp.js +927 -154
  9. package/dist/acp.js.map +1 -1
  10. package/dist/adapters-DYFauXE1.js +1147 -0
  11. package/dist/adapters-DYFauXE1.js.map +1 -0
  12. package/dist/adapters.d.ts +124 -36
  13. package/dist/adapters.js +1 -1
  14. package/dist/agents.d.ts +2 -2
  15. package/dist/agents.js +1 -1
  16. package/dist/{core-BH7sWpEG.js → core-xTtRZqdb.js} +217 -99
  17. package/dist/core-xTtRZqdb.js.map +1 -0
  18. package/dist/diagram_bin.js +1 -1
  19. package/dist/durable-CgU0kO2H.d.ts +144 -0
  20. package/dist/{engine-fOjYHcv6.js → engine-B_Yl7acj.js} +128 -42
  21. package/dist/engine-B_Yl7acj.js.map +1 -0
  22. package/dist/index.d.ts +9 -136
  23. package/dist/index.js +6 -5
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-7iu8db6V.js → invoke-Bbk0RuVL.js} +3 -3
  26. package/dist/{invoke-7iu8db6V.js.map → invoke-Bbk0RuVL.js.map} +1 -1
  27. package/dist/{leading_system-BeQUSAim.js → leading_system-m-x7HzbQ.js} +16 -4
  28. package/dist/leading_system-m-x7HzbQ.js.map +1 -0
  29. package/dist/mcp-D1hN5ywq.js +662 -0
  30. package/dist/mcp-D1hN5ywq.js.map +1 -0
  31. package/dist/mcp.d.ts +115 -5
  32. package/dist/mcp.js +2 -2
  33. package/dist/otel.d.ts +1 -1
  34. package/dist/stdio.d.ts +1 -1
  35. package/dist/stdio.js +2 -2
  36. package/dist/testing.d.ts +7 -5
  37. package/dist/testing.js +618 -318
  38. package/dist/testing.js.map +1 -1
  39. package/dist/{types-BUXt_zgJ.d.ts → types-BtRpSctv.d.ts} +38 -5
  40. package/dist/{types-Dk9tLpUq.d.ts → types-CDTW7XWB.d.ts} +2 -2
  41. package/dist/ui.d.ts +2 -2
  42. package/dist/viewer.js +2 -2
  43. package/dist/web.d.ts +1 -1
  44. package/package.json +17 -5
  45. package/dist/adapters-CpKpDk7r.js +0 -461
  46. package/dist/adapters-CpKpDk7r.js.map +0 -1
  47. package/dist/core-BH7sWpEG.js.map +0 -1
  48. package/dist/engine-fOjYHcv6.js.map +0 -1
  49. package/dist/leading_system-BeQUSAim.js.map +0 -1
  50. package/dist/mcp-CHJ88HiG.js +0 -262
  51. package/dist/mcp-CHJ88HiG.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/assert_prefix_stable.ts","../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_loop_engine.ts","../src/testing/make_script_engine.ts","../src/testing/make_stub_engine.ts","../src/testing/text_of.ts"],"sourcesContent":["/**\n * assert_prefix_stable: a check that each turn of a tool loop only appends.\n *\n * A provider's prompt cache matches a request by its prefix: the system\n * prompt, the tools, and the messages, as the wire sends them. A loop whose\n * every turn sends the turn before it whole, with new messages after it,\n * keeps that prefix, so each turn can read the last one from the cache. A\n * loop that rewrites the prefix (a `prepare_step` sliding window, a tool\n * list rebuilt in another order, a system prompt that changes) misses the\n * cache on every turn, and nothing else fails to say so. This check reads\n * the requests that a double such as make_loop_engine recorded and throws\n * at the first turn that changed what an earlier turn sent.\n *\n * Requests carry no call id, so the check splits them into calls wherever a\n * `step_index` doesn't increase. It reads calls that ran one at a time:\n * calls that ran at once interleave on one engine, so a `parallel` flow\n * takes one double per branch. A retried turn repeats its `step_index`, so\n * it starts a new call in the check.\n */\n\nimport type { Message, Tool, TurnRequest } from '#engine'\nimport { to_json_schema } from '#schema'\n\nconst ONE_AT_A_TIME = 'the check reads calls that ran one at a time, so a parallel flow takes one double per branch'\n\n/** A tool list as its names, in order, the way a message prints it. */\nfunction listed(tools: ReadonlyArray<Tool>): string {\n return `[${tools.map((tool) => tool.name).join(', ')}]`\n}\n\n/**\n * How a tool's schema changed since the earlier turn: nothing when both\n * turns hold the same object or the same JSON Schema, and a difference that\n * names the tool when they don't, or when a new object can't be converted.\n */\nfunction schema_difference(before: Tool, after: Tool, step: number): string | undefined {\n if (after.input_schema === before.input_schema) return undefined\n try {\n const same =\n JSON.stringify(to_json_schema(after.input_schema)) === JSON.stringify(to_json_schema(before.input_schema))\n return same ? undefined : `the input schema of tool ${after.name} differs from step ${step}`\n } catch {\n return `the input schema of tool ${after.name} is a new object since step ${step}, and it has no JSON Schema to compare`\n }\n}\n\n/** The first way the later turn's tools differ from the earlier turn's: their names in order, a description, or a schema. */\nfunction tool_difference(earlier: ReadonlyArray<Tool>, later: ReadonlyArray<Tool>, step: number): string | undefined {\n const renamed = `the tools are ${listed(later)} where step ${step} sent ${listed(earlier)}`\n for (const [i, before] of earlier.entries()) {\n const after = later[i]\n if (after === undefined || after.name !== before.name) return renamed\n if (after.description !== before.description) {\n return `the description of tool ${after.name} differs from step ${step}`\n }\n const schema = schema_difference(before, after, step)\n if (schema !== undefined) return schema\n }\n return later.length > earlier.length ? renamed : undefined\n}\n\n/** The first message of the earlier turn that the later turn doesn't send again as the same JSON text. */\nfunction message_difference(\n earlier: ReadonlyArray<Message>,\n later: ReadonlyArray<Message>,\n step: number,\n): string | undefined {\n for (const [i, before] of earlier.entries()) {\n if (JSON.stringify(later[i]) !== JSON.stringify(before)) {\n return later.length > i ? `message ${i} differs from step ${step}` : `message ${i} from step ${step} is missing`\n }\n }\n return undefined\n}\n\n/** The first way the later turn changed what the earlier turn of its call sent. */\nfunction first_difference(earlier: TurnRequest, later: TurnRequest): string | undefined {\n const step = earlier.step_index\n if (later.system !== earlier.system) return `the system prompt differs from step ${step}`\n return tool_difference(earlier.tools, later.tools, step) ?? message_difference(earlier.messages, later.messages, step)\n}\n\n/**\n * Check that every turn of every call in `requests` sends the turn before it\n * unchanged: the same system prompt, the same tools in the same order\n * (names, descriptions, and input schemas), and every earlier message again,\n * as the same JSON text, before any new one.\n *\n * Throws a plain `Error` at the first difference, naming the call (counted\n * from 1), the step (its `step_index`), and the difference, with message and\n * tool positions as the request's arrays hold them, from 0. A new call\n * starts wherever a `step_index` doesn't increase, so the check reads calls\n * that ran one at a time, and a `parallel` flow takes one double per branch.\n */\nexport function assert_prefix_stable(requests: ReadonlyArray<TurnRequest>): void {\n let call = 0\n let earlier: TurnRequest | undefined\n for (const later of requests) {\n if (earlier === undefined || later.step_index <= earlier.step_index) {\n call += 1\n } else {\n const difference = first_difference(earlier, later)\n if (difference !== undefined) {\n throw new Error(\n `assert_prefix_stable: call ${call}, step ${later.step_index}: ${difference} (${ONE_AT_A_TIME})`,\n )\n }\n }\n earlier = later\n }\n}\n","/**\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 const second = await claims.claim(KEY, SECOND, HELD_MS)\n // A machine slow enough to reach the end of the renewed lifetime before\n // the second claim returns, oversleeping or stalling inside the claim,\n // can't tell a renewal from none, so the check judges only a claim that\n // finished inside it.\n if (Date.now() >= renewed + env.ttl_ms) return\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'\nimport { format_schema_issues, validate_schema } from '#schema'\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\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. The issues are normalized and rendered by the same\n * `#schema` helpers the engine uses. Absent a schema, the content passes\n * 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 validate_schema(schema, content)\n if (!checked.ok) {\n throw new schema_validation_error(\n `${described} failed the caller's schema: ${format_schema_issues(checked.issues)}`,\n checked.issues,\n render_text(content),\n )\n }\n return checked.value\n}\n","/**\n * make_loop_engine: a scripted model under the engine's own tool loop.\n *\n * make_stub_engine, make_script_engine, and make_capture_engine replace the\n * whole engine, so no tool runs under them. This double registers a native\n * provider through `create_engine` instead, and the real engine runs its\n * loop around a script: each time the loop asks the model for a turn, the\n * script plays its next entry, and the engine runs the tools, asks for the\n * approvals, and feeds the results back as it would around a real model.\n * Every request the model was sent lands in `requests` before its turn\n * plays, so a test reads what the loop sent, tool results included.\n *\n * A turn is a string (a final answer), an array of calls (a tool-calling\n * turn), or an object that spells the turn out field by field or throws\n * instead of answering. The engine classifies a thrown error as it would a\n * provider's, so a retryable one uses up the next turn on its retry, while\n * a plain `Error` never retries. A turn past the end of the script throws,\n * naming how many turns were scripted.\n *\n * The engine registers no pricing, so a call with a trajectory records\n * `pricing_missing`.\n */\n\nimport { create_engine } from '#engine'\nimport type {\n AssistantContentPart,\n Engine,\n FinishReason,\n NativeProviderAdapter,\n TurnRequest,\n TurnResult,\n UsageTotals,\n} from '#engine'\nimport { DEFAULT_USAGE } from './canned.js'\n\nconst PROVIDER = 'loop'\n\n/** One tool call a scripted turn makes. A call without an `id` gets `call_<turn>_<n>`. */\nexport type LoopCall = {\n readonly id?: string\n readonly name: string\n readonly input: unknown\n}\n\n/** A turn spelled out field by field. */\ntype LoopTurnFields = {\n /** The turn's text (default: its `content`'s text parts, joined). */\n readonly text?: string\n /** The calls the turn makes (default: its `content`'s tool_call parts). */\n readonly tool_calls?: ReadonlyArray<LoopCall>\n /** The turn's parts, which the loop sends back as the assistant message. */\n readonly content?: ReadonlyArray<AssistantContentPart>\n /** Default: `'tool_calls'` when the turn makes calls, `'stop'` otherwise. */\n readonly finish_reason?: FinishReason\n /** Default: the engine's `usage` option. */\n readonly usage?: UsageTotals\n /**\n * True to play a turn the provider paused partway through (Anthropic's\n * `pause_turn`), which the loop sends back and continues with another turn.\n */\n readonly paused?: boolean\n /** An error to throw for this turn instead of answering. */\n readonly throw?: Error\n}\n\n/**\n * One model turn: a string is a final answer, an array is the calls the turn\n * makes, and an object spells the turn out field by field.\n */\nexport type LoopTurn = string | ReadonlyArray<LoopCall> | LoopTurnFields\n\nexport type LoopEngineOptions = {\n /** The model every call resolves to unless it names one (default `'loop'`). */\n readonly model_id?: string\n /** The usage a turn reports when it sets none (default `{ input_tokens: 40, output_tokens: 20 }`). */\n readonly usage?: UsageTotals\n /**\n * The caching the double's provider declares, which decides the `cache`\n * each request carries (default: none, so no request carries one).\n */\n readonly prompt_cache?: NativeProviderAdapter['prompt_cache']\n}\n\nexport type LoopEngine = {\n readonly engine: Engine\n /** Every request the model was sent, in order, growing as the script plays. */\n readonly requests: TurnRequest[]\n}\n\ntype NamedCall = { readonly id: string; readonly name: string; readonly input: unknown }\n\n/** Narrow a turn to its array form. */\nfunction is_call_list(turn: LoopTurn): turn is ReadonlyArray<LoopCall> {\n return Array.isArray(turn)\n}\n\n/** Read any turn as its object form. */\nfunction as_fields(turn: LoopTurn): LoopTurnFields {\n if (typeof turn === 'string') return { text: turn }\n if (is_call_list(turn)) return { tool_calls: turn }\n return turn\n}\n\n/** The turn's text: its own, or its content's text parts joined, or none. */\nfunction text_of_turn(fields: LoopTurnFields): string {\n if (fields.text !== undefined) return fields.text\n return fields.content?.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('') ?? ''\n}\n\n/** The turn's calls, its own or its content's, each given an id it lacks. */\nfunction calls_of_turn(fields: LoopTurnFields, position: number): NamedCall[] {\n const calls =\n fields.tool_calls ?? fields.content?.flatMap((part) => (part.type === 'tool_call' ? [part] : [])) ?? []\n return calls.map((call, n) => ({ id: call.id ?? `call_${position}_${n}`, name: call.name, input: call.input }))\n}\n\n/**\n * Play one scripted turn the way a native provider streams it: a throw\n * before anything streams, else its text as one chunk and each call's start\n * and then its whole input, and then the aggregated result.\n */\nasync function play(\n req: TurnRequest,\n fields: LoopTurnFields,\n position: number,\n default_usage: UsageTotals,\n): Promise<TurnResult> {\n if (fields.throw !== undefined) throw fields.throw\n const text = text_of_turn(fields)\n const tool_calls = calls_of_turn(fields, position)\n const step_index = req.step_index\n // Stryker disable OptionalChaining: this provider supports streaming, so the engine hands every turn a dispatch_chunk and the guard can't be seen through the engine; it covers a request that carries none.\n if (text !== '') await req.dispatch_chunk?.({ kind: 'text', text, step_index })\n for (const call of tool_calls) {\n await req.dispatch_chunk?.({ kind: 'tool_call_start', id: call.id, name: call.name, step_index })\n await req.dispatch_chunk?.({ kind: 'tool_call_end', id: call.id, input: call.input, step_index })\n }\n // Stryker restore OptionalChaining\n const result: TurnResult = {\n text,\n tool_calls,\n finish_reason: fields.finish_reason ?? (tool_calls.length > 0 ? 'tool_calls' : 'stop'),\n usage: fields.usage ?? default_usage,\n ...(fields.paused === true ? { paused: true } : {}),\n }\n // Stryker disable next-line ConditionalExpression: the loop reads `content: undefined` as no content (`tool_loop.ts` checks `!== undefined`), so always spreading it is unobservable.\n return fields.content === undefined ? result : { ...result, content: fields.content }\n}\n\n/**\n * Build an engine whose one provider, `'loop'`, plays `turns` in order, a\n * turn each time any call through the engine asks the model for one, and\n * the array that records every request it was sent.\n *\n * `options.model_id` sets the default model (default `'loop'`),\n * `options.usage` the usage a turn reports when it sets none (default\n * `{ input_tokens: 40, output_tokens: 20 }`), and `options.prompt_cache` the\n * caching its provider declares (default: none).\n */\nexport function make_loop_engine(\n turns: ReadonlyArray<LoopTurn>,\n options: LoopEngineOptions = {},\n): LoopEngine {\n const default_usage = options.usage ?? DEFAULT_USAGE\n const requests: TurnRequest[] = []\n let played = 0\n const engine = create_engine({\n providers: { [PROVIDER]: {} },\n custom_providers: {\n [PROVIDER]: () => ({\n // Stryker disable next-line StringLiteral: generate branches only on 'external' and 'ai_sdk', so any other kind runs as native.\n kind: 'native',\n name: PROVIDER,\n supports: () => true,\n // Stryker disable next-line ConditionalExpression: the engine reads `prompt_cache` as a value, so a key set to undefined reads the same as no key.\n ...(options.prompt_cache !== undefined ? { prompt_cache: options.prompt_cache } : {}),\n invoke_turn: async (req) => {\n requests.push(req)\n const position = played\n played += 1\n const turn = turns[position]\n if (turn === undefined) {\n throw new Error(\n `make_loop_engine: script exhausted: ${turns.length} turn(s) scripted, turn ${played} requested`,\n )\n }\n return await play(req, as_fields(turn), position, default_usage)\n },\n }),\n },\n defaults: { provider: PROVIDER, model: options.model_id ?? PROVIDER },\n })\n return { engine, requests }\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\n/**\n * Canned content: a value to answer with as it is, or a `StubContentFn` to call\n * on each matched call.\n *\n * Spelled out as a union rather than `unknown`, which would absorb the function\n * type, so that a function written inline takes its parameter types from\n * `StubContentFn` instead of failing strict mode as implicitly `any`. The\n * empty object type that the lint rule below objects to is the point, since\n * with `null` and `undefined` it reads as any value, so a value typed `unknown`\n * stays assignable while the function type stays visible.\n */\n// oxlint-disable-next-line typescript/no-generated-empty-object-type\nexport type StubContent = StubContentFn | NonNullable<unknown> | null | undefined\n\nexport type StubResponse = {\n readonly prefix: string\n /** Static content, or a `StubContentFn` invoked per matched call. */\n readonly content: StubContent\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":";;;;AAuBA,MAAM,gBAAgB;;AAGtB,SAAS,OAAO,OAAoC;CAClD,OAAO,IAAI,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE;AACvD;;;;;;AAOA,SAAS,kBAAkB,QAAc,OAAa,MAAkC;CACtF,IAAI,MAAM,iBAAiB,OAAO,c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KAAA,GACZ,MAAM,IAAI,MAAM,oDAAoD,UAAU,UAAU;EAE1F,MAAM,aAAa,aAAa,IAAI,KAAK,KAAK;EAC9C,aAAa,IAAI,OAAO,aAAa,CAAC;EAEtC,MAAM,QAAQ;EACd,MAAM,WACJ,OAAO,MAAM,YAAY,aAErB,MAAO,MAAM,QAA0B,OAAO,UAAU,IACxD,MAAM;EAGZ,MAAM,YAAY,KAAK,UAAU,UAAU,QAAQ,KAAK;EAMxD,OAAO;GAEL,SAAS,MAPW,gBACpB,KAAK,QACL,UACA,iDAAiD,MAAM,OAAO,EAChE;GAIE,YAAY,CAAC;GACb,OAAO,CAAC;GACR;GACA,eAAe;GACf,gBAAgB;IAAE,UAAU;IAAQ;GAAS;EAC/C;CACF,CACF;AACF;;;;;;;;AClGA,SAAgB,QAAqB,MAAkC;CACrE,IAAI,OAAO,KAAK,WAAW,UAAU,OAAO,KAAK;CACjD,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,WAAW,KAAK,QAAQ;EACjC,IAAI,QAAQ,SAAS,QAAQ;EAC7B,IAAI,OAAO,QAAQ,YAAY,UAAU;GACvC,MAAM,KAAK,QAAQ,OAAO;GAC1B;EACF;EACA,KAAK,MAAM,QAAQ,QAAQ,SACzB,IAAI,KAAK,SAAS,QAAQ,MAAM,KAAK,KAAK,IAAI;CAElD;CACA,OAAO,MAAM,KAAK,IAAI;AACxB"}
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/assert_prefix_stable.ts","../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_loop_engine.ts","../src/testing/make_script_engine.ts","../src/testing/make_stub_engine.ts","../src/testing/text_of.ts"],"sourcesContent":["/**\n * assert_prefix_stable: a check that each turn of a tool loop only appends.\n *\n * A provider's prompt cache matches a request by its prefix: the system\n * prompt, the tools, and the messages, as the wire sends them. A loop whose\n * every turn sends the turn before it whole, with new messages after it,\n * keeps that prefix, so each turn can read the last one from the cache. A\n * loop that rewrites the prefix (a `prepare_step` sliding window, a tool\n * list rebuilt in another order, a system prompt that changes) misses the\n * cache on every turn, and nothing else fails to say so. This check reads\n * the requests that a double such as make_loop_engine recorded and throws\n * at the first turn that changed what an earlier turn sent.\n *\n * Requests carry no call id, so the check splits them into calls wherever a\n * `step_index` doesn't increase. It reads calls that ran one at a time:\n * calls that ran at once interleave on one engine, so a `parallel` flow\n * takes one double per branch. A retried turn repeats its `step_index`, so\n * it starts a new call in the check.\n */\n\nimport type { Message, Tool, TurnRequest } from '#engine'\nimport { to_json_schema } from '#schema'\n\nconst ONE_AT_A_TIME = 'the check reads calls that ran one at a time, so a parallel flow takes one double per branch'\n\n/** A tool list as its names, in order, the way a message prints it. */\nfunction listed(tools: ReadonlyArray<Tool>): string {\n return `[${tools.map((tool) => tool.name).join(', ')}]`\n}\n\n/**\n * How a tool's schema changed since the earlier turn: nothing when both\n * turns hold the same object or the same JSON Schema, and a difference that\n * names the tool when they don't, or when a new object can't be converted.\n */\nfunction schema_difference(before: Tool, after: Tool, step: number): string | undefined {\n if (after.input_schema === before.input_schema) return undefined\n try {\n const same =\n JSON.stringify(to_json_schema(after.input_schema)) === JSON.stringify(to_json_schema(before.input_schema))\n return same ? undefined : `the input schema of tool ${after.name} differs from step ${step}`\n } catch {\n return `the input schema of tool ${after.name} is a new object since step ${step}, and it has no JSON Schema to compare`\n }\n}\n\n/** The first way the later turn's tools differ from the earlier turn's: their names in order, a description, or a schema. */\nfunction tool_difference(earlier: ReadonlyArray<Tool>, later: ReadonlyArray<Tool>, step: number): string | undefined {\n const renamed = `the tools are ${listed(later)} where step ${step} sent ${listed(earlier)}`\n for (const [i, before] of earlier.entries()) {\n const after = later[i]\n if (after === undefined || after.name !== before.name) return renamed\n if (after.description !== before.description) {\n return `the description of tool ${after.name} differs from step ${step}`\n }\n const schema = schema_difference(before, after, step)\n if (schema !== undefined) return schema\n }\n return later.length > earlier.length ? renamed : undefined\n}\n\n/** The first message of the earlier turn that the later turn doesn't send again as the same JSON text. */\nfunction message_difference(\n earlier: ReadonlyArray<Message>,\n later: ReadonlyArray<Message>,\n step: number,\n): string | undefined {\n for (const [i, before] of earlier.entries()) {\n if (JSON.stringify(later[i]) !== JSON.stringify(before)) {\n return later.length > i ? `message ${i} differs from step ${step}` : `message ${i} from step ${step} is missing`\n }\n }\n return undefined\n}\n\n/** The first way the later turn changed what the earlier turn of its call sent. */\nfunction first_difference(earlier: TurnRequest, later: TurnRequest): string | undefined {\n const step = earlier.step_index\n if (later.system !== earlier.system) return `the system prompt differs from step ${step}`\n return tool_difference(earlier.tools, later.tools, step) ?? message_difference(earlier.messages, later.messages, step)\n}\n\n/**\n * Check that every turn of every call in `requests` sends the turn before it\n * unchanged: the same system prompt, the same tools in the same order\n * (names, descriptions, and input schemas), and every earlier message again,\n * as the same JSON text, before any new one.\n *\n * Throws a plain `Error` at the first difference, naming the call (counted\n * from 1), the step (its `step_index`), and the difference, with message and\n * tool positions as the request's arrays hold them, from 0. A new call\n * starts wherever a `step_index` doesn't increase, so the check reads calls\n * that ran one at a time, and a `parallel` flow takes one double per branch.\n */\nexport function assert_prefix_stable(requests: ReadonlyArray<TurnRequest>): void {\n let call = 0\n let earlier: TurnRequest | undefined\n for (const later of requests) {\n if (earlier === undefined || later.step_index <= earlier.step_index) {\n call += 1\n } else {\n const difference = first_difference(earlier, later)\n if (difference !== undefined) {\n throw new Error(\n `assert_prefix_stable: call ${call}, step ${later.step_index}: ${difference} (${ONE_AT_A_TIME})`,\n )\n }\n }\n earlier = later\n }\n}\n","/**\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. A conditional write\n * has to let exactly one of several racing writers through. The suite runs\n * every check against a fresh store from `make_store`, adds the scope,\n * claim, and compare-and-set checks when the store offers those\n * capabilities, and reports what passed, what failed, and what it skipped.\n * It returns that report instead of registering tests, so it works under any\n * test runner: assert that `failed` is empty.\n */\n\nimport type { CheckpointStore, ScopedCheckpointStore, Versioned } 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, and\n * that `get_versioned` still reads it with a version.\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\ntype Cas = {\n readonly get_versioned: (key: string) => Promise<Versioned | undefined>\n readonly set_if: (key: string, value: unknown, expected: string | null) => Promise<boolean>\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// How many times a conditional write races an unconditional one. The two\n// start in the other order every round, and a store that checks its\n// condition and then writes in a second step loses the race within a few.\nconst RACE_ROUNDS = 16\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'\nconst CREATE_REFUSED = 'a create on a key that holds nothing was refused'\nconst FRESH_SCOPE_CREATE_REFUSED = 'a create inside a fresh scope was refused'\nconst FRESH_WRITE_REFUSED = 'a write on the version just read was refused'\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\n/**\n * The store's compare-and-set pair, or a failure naming the half that's\n * missing. Both are called on the store itself, as `claims_of` does.\n */\nfunction cas_of(store: CheckpointStore): Cas {\n const { get_versioned, set_if } = store\n if (get_versioned === undefined && set_if === undefined) {\n throw new Error('the store has neither get_versioned nor set_if')\n }\n if (get_versioned === undefined) throw new Error('the store offers set_if without get_versioned')\n if (set_if === undefined) throw new Error('the store offers get_versioned without set_if')\n return {\n get_versioned: (key) => get_versioned.call(store, key),\n set_if: (key, value, expected) => set_if.call(store, key, value, expected),\n }\n}\n\n/**\n * Read `key` with its version, failing the check when the store reports a\n * key that holds something as absent, or hands back a version that isn't a\n * string.\n */\nasync function held_version(cas: Cas, key: string): Promise<Versioned> {\n const read = await cas.get_versioned(key)\n if (read === undefined) throw new Error('get_versioned read a key that holds something as absent')\n ensure(typeof read.version === 'string', `get_versioned returned the version ${show(read.version)}`)\n return read\n}\n\n/**\n * The value that racer `writer` writes, which no other racer does.\n */\nfunction racer_value(writer: number | undefined): unknown {\n return { writer }\n}\n\n/**\n * Write `RACE_KEY` on `expected` from many writers at the same moment, and\n * fail the check unless the store accepted exactly one of them and holds\n * what that one wrote. `kind` names the write (a create, or a write) and\n * `raced` says what the writers raced for, both for the failure message.\n */\nasync function ensure_one_winner(\n store: CheckpointStore,\n expected: string | null,\n kind: string,\n raced: string,\n): Promise<void> {\n const cas = cas_of(store)\n const writers = Array.from({ length: RACERS }, (_, i) => i)\n const won = await Promise.all(writers.map((i) => cas.set_if(RACE_KEY, racer_value(i), expected)))\n const winners = writers.filter((i) => won[i])\n ensure(winners.length === 1, `${RACERS} ${kind}s raced ${raced} and ${winners.length} won`)\n const value = await store.get(RACE_KEY)\n ensure(\n canonical(value) === canonical(racer_value(winners[0])),\n `the key holds ${show(value)}, which the ${kind} that won never wrote`,\n )\n}\n\n/**\n * Race a write on the version `RACE_KEY` was just read at against `plain`,\n * an unconditional write to the same key, and resolve what the key holds\n * afterwards, or `undefined` when it holds nothing.\n *\n * Whichever of the two the store runs first, the unconditional write decides\n * what's left. Run second, it lands over the conditional write. Run first,\n * it moves the version, and the conditional write is refused. So the\n * conditional write may report either answer, and its value may never be\n * what the key ends up holding. Even rounds start the conditional write\n * first and odd rounds start the unconditional one first, since a store\n * that isn't atomic tends to lose only one of the two orders.\n */\nasync function race_unconditional(\n store: CheckpointStore,\n round: number,\n plain: () => Promise<void>,\n): Promise<Versioned | undefined> {\n const cas = cas_of(store)\n await store.set(RACE_KEY, { round, by: 'before' })\n const read = await held_version(cas, RACE_KEY)\n const conditional = (): Promise<boolean> => cas.set_if(RACE_KEY, raced_value(round), read.version)\n await (round % 2 === 0 ? Promise.all([conditional(), plain()]) : Promise.all([plain(), conditional()]))\n return cas.get_versioned(RACE_KEY)\n}\n\n/**\n * The value the conditional write of one round writes.\n */\nfunction raced_value(round: number): unknown {\n return { round, by: 'set_if' }\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 const second = await claims.claim(KEY, SECOND, HELD_MS)\n // A machine slow enough to reach the end of the renewed lifetime before\n // the second claim returns, oversleeping or stalling inside the claim,\n // can't tell a renewal from none, so the check judges only a claim that\n // finished inside it.\n if (Date.now() >= renewed + env.ttl_ms) return\n ensure(!second, 'a renewed claim expired on its original schedule')\n },\n },\n]\n\nconst CAS_CHECKS: ReadonlyArray<Check> = [\n {\n name: 'get_versioned comes with set_if',\n run: async (store) => {\n cas_of(store)\n },\n },\n {\n name: 'a missing key has no version',\n run: async (store) => {\n const read = await cas_of(store).get_versioned(MISSING)\n ensure(read === undefined, `get_versioned on a key nobody set returned ${show(read)}`)\n },\n },\n {\n name: 'a stored null reads with a version',\n run: async (store) => {\n const cas = cas_of(store)\n await store.set(NULL_KEY, null)\n const read = await held_version(cas, NULL_KEY)\n ensure(is_miss(read.value), `a stored null read back as ${show(read.value)}`)\n const replaced = await cas.set_if(NULL_KEY, { v: 1 }, read.version)\n ensure(replaced, 'a write on the version of a stored null was refused')\n const value = await store.get(NULL_KEY)\n ensure(canonical(value) === canonical({ v: 1 }), `the write over a null left ${show(value)}`)\n },\n },\n {\n name: 'a create lands on an absent key',\n run: async (store) => {\n ensure(await cas_of(store).set_if(KEY, { v: 1 }, null), CREATE_REFUSED)\n const value = await store.get(KEY)\n ensure(canonical(value) === canonical({ v: 1 }), `a create that won left ${show(value)}`)\n },\n },\n {\n name: 'a create refuses a key that holds anything',\n run: async (store) => {\n const cas = cas_of(store)\n await store.set(KEY, { v: 1 })\n const over_value = await cas.set_if(KEY, { v: 2 }, null)\n ensure(!over_value, 'a create landed on a key that holds a value')\n const value = await store.get(KEY)\n ensure(canonical(value) === canonical({ v: 1 }), `a refused create left ${show(value)}`)\n await store.set(NULL_KEY, null)\n const over_null = await cas.set_if(NULL_KEY, { v: 2 }, null)\n ensure(!over_null, 'a create landed on a key that holds a stored null')\n },\n },\n {\n name: 'exactly one racing create wins',\n run: (store) => ensure_one_winner(store, null, 'create', 'for an absent key'),\n },\n {\n name: 'a write on the version it read lands and moves the version',\n run: async (store) => {\n const cas = cas_of(store)\n await store.set(KEY, { v: 1 })\n const before = await held_version(cas, KEY)\n ensure(canonical(before.value) === canonical({ v: 1 }), `get_versioned read ${show(before.value)}`)\n ensure(await cas.set_if(KEY, { v: 2 }, before.version), FRESH_WRITE_REFUSED)\n const after = await held_version(cas, KEY)\n ensure(canonical(after.value) === canonical({ v: 2 }), `the write left ${show(after.value)}`)\n ensure(after.version !== before.version, 'a write that landed left the version where it was')\n },\n },\n {\n name: 'a write on a stale version is refused and changes nothing',\n run: async (store) => {\n const cas = cas_of(store)\n await store.set(KEY, { v: 1 })\n const stale = await held_version(cas, KEY)\n ensure(await cas.set_if(KEY, { v: 2 }, stale.version), FRESH_WRITE_REFUSED)\n const current = await held_version(cas, KEY)\n const late = await cas.set_if(KEY, { v: 3 }, stale.version)\n ensure(!late, 'a write landed on a version another write had already replaced')\n const after = await held_version(cas, KEY)\n ensure(canonical(after.value) === canonical({ v: 2 }), `a refused write left ${show(after.value)}`)\n ensure(after.version === current.version, 'a refused write moved the version')\n },\n },\n {\n name: 'exactly one racing write on one version wins',\n run: async (store) => {\n await store.set(RACE_KEY, { v: 0 })\n const read = await held_version(cas_of(store), RACE_KEY)\n await ensure_one_winner(store, read.version, 'write', 'on one version')\n },\n },\n {\n name: 'set and delete move the version',\n run: async (store) => {\n const cas = cas_of(store)\n await store.set(KEY, { v: 1 })\n const first = await held_version(cas, KEY)\n await store.set(KEY, { v: 2 })\n const second = await held_version(cas, KEY)\n ensure(second.version !== first.version, 'a set left the version where it was')\n const over_set = await cas.set_if(KEY, { v: 3 }, first.version)\n ensure(!over_set, 'a write landed on a version a set had already replaced')\n await store.delete(KEY)\n const gone = await cas.get_versioned(KEY)\n ensure(gone === undefined, `get_versioned after delete returned ${show(gone)}`)\n const over_delete = await cas.set_if(KEY, { v: 3 }, second.version)\n ensure(!over_delete, 'a write landed on the version of a value that was deleted')\n ensure(is_miss(await store.get(KEY)), 'a refused write brought a deleted value back')\n },\n },\n {\n name: 'a set that races a write on a version is the one that lasts',\n run: async (store) => {\n for (let round = 0; round < RACE_ROUNDS; round += 1) {\n const written = { round, by: 'set' }\n const left = await race_unconditional(store, round, () => store.set(RACE_KEY, written))\n ensure(\n canonical(left?.value) === canonical(written),\n `a set raced a write on a version and the key holds ${show(left?.value)}, not what the set wrote`,\n )\n }\n },\n },\n {\n name: 'a delete that races a write on a version leaves the key absent',\n run: async (store) => {\n for (let round = 0; round < RACE_ROUNDS; round += 1) {\n const left = await race_unconditional(store, round, () => store.delete(RACE_KEY))\n ensure(\n left === undefined,\n `a delete raced a write on a version and the key holds ${show(left?.value)}`,\n )\n }\n },\n },\n {\n name: 'a create works again after a delete',\n run: async (store) => {\n const cas = cas_of(store)\n ensure(await cas.set_if(KEY, { v: 1 }, null), CREATE_REFUSED)\n await store.delete(KEY)\n ensure(await cas.set_if(KEY, { v: 2 }, null), 'a create was refused on a key that was deleted')\n const value = await store.get(KEY)\n ensure(canonical(value) === canonical({ v: 2 }), `the second create left ${show(value)}`)\n },\n },\n]\n\nconst CAS_DAMAGE_CHECK: Check = {\n name: 'a damaged value reads with a version',\n run: async (store, env) => {\n const cas = cas_of(store)\n await store.set(DAMAGED_KEY, { ok: true })\n await env.corrupt(store, DAMAGED_KEY)\n let read: Versioned | undefined\n try {\n read = await cas.get_versioned(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_versioned threw on a damaged value: ${String(err)}`, { cause: err })\n }\n if (read === undefined) throw new Error('get_versioned read a damaged value as an absent key')\n ensure(is_miss(read.value), `get_versioned on a damaged value returned ${show(read.value)}`)\n const replaced = await cas.set_if(DAMAGED_KEY, { ok: false }, read.version)\n ensure(replaced, 'a write on the version of a damaged value was refused')\n const value = await store.get(DAMAGED_KEY)\n ensure(canonical(value) === canonical({ ok: false }), `the write over the damage left ${show(value)}`)\n },\n}\n\nconst SCOPED_CAS_CHECKS: ReadonlyArray<Check> = [\n {\n name: 'scopes keep the compare-and-set capability',\n run: async (store) => {\n const cas = cas_of(scope_of(store, A))\n ensure(await cas.set_if(KEY, { v: 1 }, null), FRESH_SCOPE_CREATE_REFUSED)\n const read = await held_version(cas, KEY)\n ensure(canonical(read.value) === canonical({ v: 1 }), `a scope read back ${show(read.value)}`)\n const parent = await cas_of(store).get_versioned(KEY)\n ensure(parent === undefined, \"a create in a scope showed up under its parent's key\")\n },\n },\n {\n name: 'a version from one scope satisfies nothing in another',\n run: async (store) => {\n const a = scope_of(store, A)\n const b = scope_of(store, B)\n await a.set(KEY, { v: 1 })\n await b.set(KEY, { v: 2 })\n const in_a = await held_version(cas_of(a), KEY)\n const crossed = await cas_of(b).set_if(KEY, { v: 3 }, in_a.version)\n ensure(!crossed, \"a write in scope 'b' landed on a version read in scope 'a'\")\n const value = await b.get(KEY)\n ensure(canonical(value) === canonical({ v: 2 }), `the refused write left ${show(value)} in scope 'b'`)\n const beside = await cas_of(scope_of(store, CHILD)).set_if(KEY, { v: 4 }, null)\n ensure(beside, 'a create was refused because another scope holds the key')\n },\n },\n {\n name: 'a create works again after a clear',\n run: async (store) => {\n const a = scope_of(store, A)\n const cas = cas_of(a)\n ensure(await cas.set_if(KEY, { v: 1 }, null), FRESH_SCOPE_CREATE_REFUSED)\n await a.clear()\n const gone = await cas.get_versioned(KEY)\n ensure(gone === undefined, `get_versioned after clear returned ${show(gone)}`)\n ensure(await cas.set_if(KEY, { v: 2 }, null), 'a create was refused on a key that was cleared')\n },\n },\n]\n\n/**\n * True when the store offers either half of the compare-and-set, which is\n * when its checks run. A store with only one half fails the first of them.\n */\nfunction has_cas(store: CheckpointStore): boolean {\n return store.get_versioned !== undefined || store.set_if !== undefined\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 { checks: CAS_CHECKS, applies: has_cas },\n {\n checks: [CAS_DAMAGE_CHECK],\n applies: (store, options) => has_cas(store) && options.corrupt !== undefined,\n },\n { checks: SCOPED_CAS_CHECKS, applies: (store) => store.scope !== undefined && has_cas(store) },\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`, compare-and-set checks when it has `get_versioned` or `set_if`,\n * and the damage checks when `options.corrupt` is given. Every other check\n * 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'\nimport { format_schema_issues, validate_schema } from '#schema'\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\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. The issues are normalized and rendered by the same\n * `#schema` helpers the engine uses. Absent a schema, the content passes\n * 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 validate_schema(schema, content)\n if (!checked.ok) {\n throw new schema_validation_error(\n `${described} failed the caller's schema: ${format_schema_issues(checked.issues)}`,\n checked.issues,\n render_text(content),\n )\n }\n return checked.value\n}\n","/**\n * make_loop_engine: a scripted model under the engine's own tool loop.\n *\n * make_stub_engine, make_script_engine, and make_capture_engine replace the\n * whole engine, so no tool runs under them. This double registers a native\n * provider through `create_engine` instead, and the real engine runs its\n * loop around a script: each time the loop asks the model for a turn, the\n * script plays its next entry, and the engine runs the tools, asks for the\n * approvals, and feeds the results back as it would around a real model.\n * Every request the model was sent lands in `requests` before its turn\n * plays, so a test reads what the loop sent, tool results included.\n *\n * A turn is a string (a final answer), an array of calls (a tool-calling\n * turn), or an object that spells the turn out field by field or throws\n * instead of answering. The engine classifies a thrown error as it would a\n * provider's, so a retryable one uses up the next turn on its retry, while\n * a plain `Error` never retries. A turn past the end of the script throws,\n * naming how many turns were scripted.\n *\n * The engine registers no pricing, so a call with a trajectory records\n * `pricing_missing`.\n */\n\nimport { create_engine } from '#engine'\nimport type {\n AssistantContentPart,\n Engine,\n FinishReason,\n NativeProviderAdapter,\n TurnRequest,\n TurnResult,\n UsageTotals,\n} from '#engine'\nimport { DEFAULT_USAGE } from './canned.js'\n\nconst PROVIDER = 'loop'\n\n/** One tool call a scripted turn makes. A call without an `id` gets `call_<turn>_<n>`. */\nexport type LoopCall = {\n readonly id?: string\n readonly name: string\n readonly input: unknown\n}\n\n/** A turn spelled out field by field. */\ntype LoopTurnFields = {\n /** The turn's text (default: its `content`'s text parts, joined). */\n readonly text?: string\n /** The calls the turn makes (default: its `content`'s tool_call parts). */\n readonly tool_calls?: ReadonlyArray<LoopCall>\n /** The turn's parts, which the loop sends back as the assistant message. */\n readonly content?: ReadonlyArray<AssistantContentPart>\n /** Default: `'tool_calls'` when the turn makes calls, `'stop'` otherwise. */\n readonly finish_reason?: FinishReason\n /** Default: the engine's `usage` option. */\n readonly usage?: UsageTotals\n /**\n * True to play a turn the provider paused partway through (Anthropic's\n * `pause_turn`), which the loop sends back and continues with another turn.\n */\n readonly paused?: boolean\n /** An error to throw for this turn instead of answering. */\n readonly throw?: Error\n}\n\n/**\n * One model turn: a string is a final answer, an array is the calls the turn\n * makes, and an object spells the turn out field by field.\n */\nexport type LoopTurn = string | ReadonlyArray<LoopCall> | LoopTurnFields\n\nexport type LoopEngineOptions = {\n /** The model every call resolves to unless it names one (default `'loop'`). */\n readonly model_id?: string\n /** The usage a turn reports when it sets none (default `{ input_tokens: 40, output_tokens: 20 }`). */\n readonly usage?: UsageTotals\n /**\n * The caching the double's provider declares, which decides the `cache`\n * each request carries (default: none, so no request carries one).\n */\n readonly prompt_cache?: NativeProviderAdapter['prompt_cache']\n}\n\nexport type LoopEngine = {\n readonly engine: Engine\n /** Every request the model was sent, in order, growing as the script plays. */\n readonly requests: TurnRequest[]\n}\n\ntype NamedCall = { readonly id: string; readonly name: string; readonly input: unknown }\n\n/** Narrow a turn to its array form. */\nfunction is_call_list(turn: LoopTurn): turn is ReadonlyArray<LoopCall> {\n return Array.isArray(turn)\n}\n\n/** Read any turn as its object form. */\nfunction as_fields(turn: LoopTurn): LoopTurnFields {\n if (typeof turn === 'string') return { text: turn }\n if (is_call_list(turn)) return { tool_calls: turn }\n return turn\n}\n\n/** The turn's text: its own, or its content's text parts joined, or none. */\nfunction text_of_turn(fields: LoopTurnFields): string {\n if (fields.text !== undefined) return fields.text\n return fields.content?.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('') ?? ''\n}\n\n/** The turn's calls, its own or its content's, each given an id it lacks. */\nfunction calls_of_turn(fields: LoopTurnFields, position: number): NamedCall[] {\n const calls =\n fields.tool_calls ?? fields.content?.flatMap((part) => (part.type === 'tool_call' ? [part] : [])) ?? []\n return calls.map((call, n) => ({ id: call.id ?? `call_${position}_${n}`, name: call.name, input: call.input }))\n}\n\n/**\n * Play one scripted turn the way a native provider streams it: a throw\n * before anything streams, else its text as one chunk and each call's start\n * and then its whole input, and then the aggregated result.\n */\nasync function play(\n req: TurnRequest,\n fields: LoopTurnFields,\n position: number,\n default_usage: UsageTotals,\n): Promise<TurnResult> {\n if (fields.throw !== undefined) throw fields.throw\n const text = text_of_turn(fields)\n const tool_calls = calls_of_turn(fields, position)\n const step_index = req.step_index\n // Stryker disable OptionalChaining: this provider supports streaming, so the engine hands every turn a dispatch_chunk and the guard can't be seen through the engine; it covers a request that carries none.\n if (text !== '') await req.dispatch_chunk?.({ kind: 'text', text, step_index })\n for (const call of tool_calls) {\n await req.dispatch_chunk?.({ kind: 'tool_call_start', id: call.id, name: call.name, step_index })\n await req.dispatch_chunk?.({ kind: 'tool_call_end', id: call.id, input: call.input, step_index })\n }\n // Stryker restore OptionalChaining\n const result: TurnResult = {\n text,\n tool_calls,\n finish_reason: fields.finish_reason ?? (tool_calls.length > 0 ? 'tool_calls' : 'stop'),\n usage: fields.usage ?? default_usage,\n ...(fields.paused === true ? { paused: true } : {}),\n }\n // Stryker disable next-line ConditionalExpression: the loop reads `content: undefined` as no content (`tool_loop.ts` checks `!== undefined`), so always spreading it is unobservable.\n return fields.content === undefined ? result : { ...result, content: fields.content }\n}\n\n/**\n * Build an engine whose one provider, `'loop'`, plays `turns` in order, a\n * turn each time any call through the engine asks the model for one, and\n * the array that records every request it was sent.\n *\n * `options.model_id` sets the default model (default `'loop'`),\n * `options.usage` the usage a turn reports when it sets none (default\n * `{ input_tokens: 40, output_tokens: 20 }`), and `options.prompt_cache` the\n * caching its provider declares (default: none).\n */\nexport function make_loop_engine(\n turns: ReadonlyArray<LoopTurn>,\n options: LoopEngineOptions = {},\n): LoopEngine {\n const default_usage = options.usage ?? DEFAULT_USAGE\n const requests: TurnRequest[] = []\n let played = 0\n const engine = create_engine({\n providers: { [PROVIDER]: {} },\n custom_providers: {\n [PROVIDER]: () => ({\n // Stryker disable next-line StringLiteral: generate branches only on 'external' and 'ai_sdk', so any other kind runs as native.\n kind: 'native',\n name: PROVIDER,\n supports: () => true,\n // Stryker disable next-line ConditionalExpression: the engine reads `prompt_cache` as a value, so a key set to undefined reads the same as no key.\n ...(options.prompt_cache !== undefined ? { prompt_cache: options.prompt_cache } : {}),\n invoke_turn: async (req) => {\n requests.push(req)\n const position = played\n played += 1\n const turn = turns[position]\n if (turn === undefined) {\n throw new Error(\n `make_loop_engine: script exhausted: ${turns.length} turn(s) scripted, turn ${played} requested`,\n )\n }\n return await play(req, as_fields(turn), position, default_usage)\n },\n }),\n },\n defaults: { provider: PROVIDER, model: options.model_id ?? PROVIDER },\n })\n return { engine, requests }\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\n/**\n * Canned content: a value to answer with as it is, or a `StubContentFn` to call\n * on each matched call.\n *\n * Spelled out as a union rather than `unknown`, which would absorb the function\n * type, so that a function written inline takes its parameter types from\n * `StubContentFn` instead of failing strict mode as implicitly `any`. The\n * empty object type that the lint rule below objects to is the point, since\n * with `null` and `undefined` it reads as any value, so a value typed `unknown`\n * stays assignable while the function type stays visible.\n */\n// oxlint-disable-next-line typescript/no-generated-empty-object-type\nexport type StubContent = StubContentFn | NonNullable<unknown> | null | undefined\n\nexport type StubResponse = {\n readonly prefix: string\n /** Static content, or a `StubContentFn` invoked per matched call. */\n readonly content: StubContent\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":";;;;AAuBA,MAAM,gBAAgB;;AAGtB,SAAS,OAAO,OAAoC;CAClD,OAAO,IAAI,MAAM,KAAK,SAAS,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE;AACvD;;;;;;AAOA,SAAS,kBAAkB,QAAc,OAAa,MAAkC;CACtF,IAAI,MAAM,iBAAiB,OAAO,cAAc,OAAO,KAAA;CACvD,IAAI;EAGF,OADE,KAAK,UAAU,eAAe,MAAM,YAAY,CAAC,MAAM,KAA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the
29
29
  * store can't read back whole.
30
30
  *
31
- * The rest are optional capabilities, and `durable` needs all three. `scope`
31
+ * The rest are optional capabilities, and `durable` needs all five. `scope`
32
32
  * hands out a store whose keys, claims, and nested scopes are disjoint from
33
33
  * this one's, and the same prefix always reaches the same data. `claim` takes
34
34
  * `key` for `owner` until `ttl_ms` passes and resolves true when the caller
@@ -37,8 +37,18 @@ type TrajectoryLogger = {
37
37
  * It resolves false while another owner holds the key. `release` frees a
38
38
  * claim `owner` holds and does nothing otherwise. Claims live apart from
39
39
  * values, so a claim never changes what `get` returns and `set` or `delete`
40
- * never touch a claim. `checkpoint_store_conformance` in `fascicle/testing`
41
- * checks a store against all of this.
40
+ * never touch a claim.
41
+ *
42
+ * `get_versioned` and `set_if` are the store's compare-and-set. A version is
43
+ * opaque, and a store may derive it from the content, as an S3 ETag is, so
44
+ * writing the same bytes twice can leave it where it was. `set_if` is atomic
45
+ * against every write to the key, `set` and `delete` included. Of several
46
+ * writers that race on one version exactly one wins, and of several that race
47
+ * to create an absent key exactly one creates it. `delete`, and a scope's
48
+ * `clear`, make a key absent, so a create lands on it again. A version read
49
+ * in one scope never satisfies a condition in another.
50
+ * `checkpoint_store_conformance` in `fascicle/testing` checks a store against
51
+ * all of this.
42
52
  */
43
53
  type CheckpointStore = {
44
54
  readonly get: (key: string) => Promise<unknown>;
@@ -47,6 +57,29 @@ type CheckpointStore = {
47
57
  readonly scope?: (prefix: string) => ScopedCheckpointStore;
48
58
  readonly claim?: (key: string, owner: string, ttl_ms: number) => Promise<boolean>;
49
59
  readonly release?: (key: string, owner: string) => Promise<void>;
60
+ /**
61
+ * The value at `key` and the version it was read at, or `undefined` when
62
+ * nothing is stored there. A stored `null`, or a value that can't be read
63
+ * back whole, reads as `{ value: undefined, version }`, so a writer can still
64
+ * replace it on that version.
65
+ */
66
+ readonly get_versioned?: (key: string) => Promise<Versioned | undefined>;
67
+ /**
68
+ * Write `value` only while the key is still at `expected`, or only while
69
+ * nothing is stored there when `expected` is `null`. Resolves true when it
70
+ * wrote and false on a conflict. A conflict never throws, and a failure to
71
+ * reach the store does.
72
+ */
73
+ readonly set_if?: (key: string, value: unknown, expected: string | null) => Promise<boolean>;
74
+ };
75
+ /**
76
+ * A stored value and the version it was read at. The version changes
77
+ * whenever the stored value changes, and `set_if` takes it back as the
78
+ * condition on a write.
79
+ */
80
+ type Versioned = {
81
+ readonly value: unknown;
82
+ readonly version: string;
50
83
  };
51
84
  /**
52
85
  * A store reached through `scope(prefix)`. It can scope again, and `clear`
@@ -162,5 +195,5 @@ type StepInput<s> = s extends Step<infer i, unknown> ? i : never;
162
195
  * plumbing over `AnyStep` degrades to the safe top type instead of lying.
163
196
  */
164
197
  type StepOutput<s> = s extends Step<never, infer o> ? o : unknown;
165
- export { FlowValue as a, Step as c, StepMetadata as d, StepOptions as f, TrajectoryLogger as h, FlowNode as i, StepFn as l, TrajectoryEvent as m, CheckpointStore as n, RunContext as o, StepOutput as p, CleanupFn as r, ScopedCheckpointStore as s, AnyStep as t, StepInput as u };
166
- //# sourceMappingURL=types-BUXt_zgJ.d.ts.map
198
+ export { FlowValue as a, Step as c, StepMetadata as d, StepOptions as f, Versioned as g, TrajectoryLogger as h, FlowNode as i, StepFn as l, TrajectoryEvent as m, CheckpointStore as n, RunContext as o, StepOutput as p, CleanupFn as r, ScopedCheckpointStore as s, AnyStep as t, StepInput as u };
199
+ //# sourceMappingURL=types-BtRpSctv.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { r as ToolSchema } from "./types-CvghbZ0x.js";
2
- import { h as TrajectoryLogger } from "./types-BUXt_zgJ.js";
2
+ import { h as TrajectoryLogger } from "./types-BtRpSctv.js";
3
3
  /**
4
4
  * Public types for the claude_cli subprocess provider.
5
5
  *
@@ -984,4 +984,4 @@ type Engine = {
984
984
  dispose: () => Promise<void>;
985
985
  };
986
986
  export { StepTiming as A, UsageTotals as B, ProviderConfigMap as C, RetryFailureKind as D, ResolvedModel as E, ToolCallRecord as F, NativeProviderAdapter as G, AiSdkProviderAdapter as H, ToolExecContext as I, ProviderFactory as J, ProviderAdapter as K, TruncatedTurnPolicy as L, Tool as M, ToolApprovalHandler as N, RetryPolicy as O, ToolApprovalRequest as P, ClaudeCliProviderReported as Q, TurnRequest as R, PricingTable as S, ProviderOptions as T, EffortTranslation as U, UserContentPart as V, ExternalAgentAdapter as W, RawProviderUsage as X, ProviderTransport as Y, default_normalize_usage as Z, Message as _, CacheSetting as a, PrepareStepResult as b, CostBreakdown as c, EngineConfig as d, EngineDefaults as f, GenerateTiming as g, GenerateResult as h, BedrockCredentials as i, StreamChunk as j, StepRecord as k, EffortLevel as l, GenerateOptions as m, AssistantContentPart as n, CaptureLevel as o, FinishReason as p, ProviderCapability as q, BedrockCredentialProvider as r, CapturePayload as s, AiSdkTelemetrySettings as t, Engine as u, PrepareStepContext as v, ProviderInit as w, Pricing as x, PrepareStepHook as y, TurnResult as z };
987
- //# sourceMappingURL=types-Dk9tLpUq.d.ts.map
987
+ //# sourceMappingURL=types-CDTW7XWB.d.ts.map
package/dist/ui.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { m as TrajectoryEvent } from "./types-BUXt_zgJ.js";
2
- import { UIMessageChunk } from "ai";
1
+ import { m as TrajectoryEvent } from "./types-BtRpSctv.js";
3
2
  import { ServerResponse } from "node:http";
3
+ import { UIMessageChunk } from "ai";
4
4
  /**
5
5
  * The structural shape of a `run.stream(...)` handle. Typed structurally rather
6
6
  * than importing the core `StreamingRunHandle` so this module depends on no
package/dist/viewer.js CHANGED
@@ -1,12 +1,12 @@
1
- import "./core-BH7sWpEG.js";
1
+ import "./core-xTtRZqdb.js";
2
2
  import { l as parse_trajectory_event } from "./trajectory-CkCFZWNR.js";
3
3
  import { open, stat } from "node:fs/promises";
4
4
  import { basename, dirname, extname, relative, resolve, sep } from "node:path";
5
5
  import { constants, createReadStream, existsSync, statSync, watch } from "node:fs";
6
6
  import { spawn } from "node:child_process";
7
+ import { createServer } from "node:http";
7
8
  import { pipeline } from "node:stream";
8
9
  import { fileURLToPath } from "node:url";
9
- import { createServer } from "node:http";
10
10
  import { isIPv6 } from "node:net";
11
11
  import { parseArgs } from "node:util";
12
12
  // src/viewer/broadcast.ts
package/dist/web.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { M as Tool } from "./types-Dk9tLpUq.js";
1
+ import { M as Tool } from "./types-CDTW7XWB.js";
2
2
  /** One search: the query as the model wrote it, and the most results wanted. */
3
3
  type WebSearchRequest = {
4
4
  readonly query: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fascicle",
3
- "version": "0.18.1",
3
+ "version": "0.19.0",
4
4
  "description": "Compose agents like plain values. A TypeScript toolkit that wires LLM calls, tools, and functions into typed steps over eight providers. No framework, no ambient state.",
5
5
  "keywords": [
6
6
  "agents",
@@ -47,6 +47,11 @@
47
47
  "import": "./dist/index.js",
48
48
  "default": "./dist/index.js"
49
49
  },
50
+ "./a2a": {
51
+ "types": "./dist/a2a.d.ts",
52
+ "import": "./dist/a2a.js",
53
+ "default": "./dist/a2a.js"
54
+ },
50
55
  "./acp": {
51
56
  "types": "./dist/acp.d.ts",
52
57
  "import": "./dist/acp.js",
@@ -107,6 +112,7 @@
107
112
  "#agents": "./src/agents/index.ts",
108
113
  "#stdio": "./src/stdio/index.ts",
109
114
  "#acp": "./src/acp/index.ts",
115
+ "#a2a": "./src/a2a/index.ts",
110
116
  "#mcp": "./src/mcp/index.ts",
111
117
  "#ui": "./src/ui/index.ts",
112
118
  "#policy": "./src/policy/index.ts",
@@ -158,6 +164,7 @@
158
164
  "viewer:app:watch": "vite build --watch --config vite.viewer.config.ts"
159
165
  },
160
166
  "peerDependencies": {
167
+ "@a2a-js/sdk": "^1.3.0",
161
168
  "@agentclientprotocol/sdk": "^1.8.0 || ^2.0.0",
162
169
  "@ai-sdk/amazon-bedrock": "^5.0.0",
163
170
  "@ai-sdk/anthropic": "^4.0.0",
@@ -174,6 +181,9 @@
174
181
  "zod": "^4.2.0"
175
182
  },
176
183
  "peerDependenciesMeta": {
184
+ "@a2a-js/sdk": {
185
+ "optional": true
186
+ },
177
187
  "@ai-sdk/amazon-bedrock": {
178
188
  "optional": true
179
189
  },
@@ -218,13 +228,15 @@
218
228
  }
219
229
  },
220
230
  "devDependencies": {
231
+ "@a2a-js/sdk": "1.3.0",
221
232
  "@agentclientprotocol/sdk": "2.4.0",
222
233
  "@arethetypeswrong/cli": "0.18.5",
223
234
  "@ast-grep/cli": "0.51.1",
224
- "@modelcontextprotocol/sdk": "^1.32.2",
225
- "@opentelemetry/exporter-metrics-otlp-http": "^0.300.0",
226
- "@opentelemetry/exporter-trace-otlp-http": "^0.300.0",
227
- "@opentelemetry/resources": "^3.0.0",
235
+ "@aws-sdk/client-s3": "3.1167.0",
236
+ "@modelcontextprotocol/sdk": "1.32.2",
237
+ "@opentelemetry/exporter-metrics-otlp-http": "0.300.0",
238
+ "@opentelemetry/exporter-trace-otlp-http": "0.300.0",
239
+ "@opentelemetry/resources": "3.0.0",
228
240
  "@opentelemetry/sdk-metrics": "3.0.0",
229
241
  "@opentelemetry/sdk-trace": "3.0.0",
230
242
  "@playwright/test": "1.64.1",