@niadra/sdk 0.7.0 → 0.9.1

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 (125) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +55 -7
  3. package/dist/ai-sdk.cjs +3 -4
  4. package/dist/ai-sdk.cjs.map +1 -1
  5. package/dist/ai-sdk.d.cts +3 -3
  6. package/dist/ai-sdk.d.ts +3 -3
  7. package/dist/ai-sdk.js +3 -4
  8. package/dist/ai-sdk.js.map +1 -1
  9. package/dist/anthropic.cjs +1 -1
  10. package/dist/anthropic.cjs.map +1 -1
  11. package/dist/anthropic.d.cts +4 -4
  12. package/dist/anthropic.d.ts +4 -4
  13. package/dist/anthropic.js +1 -1
  14. package/dist/anthropic.js.map +1 -1
  15. package/dist/bedrock.cjs +1 -1
  16. package/dist/bedrock.cjs.map +1 -1
  17. package/dist/bedrock.d.cts +4 -4
  18. package/dist/bedrock.d.ts +4 -4
  19. package/dist/bedrock.js +1 -1
  20. package/dist/bedrock.js.map +1 -1
  21. package/dist/cli.js +157 -60
  22. package/dist/cli.js.map +1 -1
  23. package/dist/{client-DsIxZxZk.d.cts → client-CWMxmJHs.d.cts} +91 -28
  24. package/dist/{client-DsIxZxZk.d.ts → client-CWMxmJHs.d.ts} +91 -28
  25. package/dist/cloudflare-agents.cjs +1 -1
  26. package/dist/cloudflare-agents.cjs.map +1 -1
  27. package/dist/cloudflare-agents.d.cts +3 -3
  28. package/dist/cloudflare-agents.d.ts +3 -3
  29. package/dist/cloudflare-agents.js +1 -1
  30. package/dist/cloudflare-agents.js.map +1 -1
  31. package/dist/elevenlabs.cjs +1 -1
  32. package/dist/elevenlabs.cjs.map +1 -1
  33. package/dist/elevenlabs.d.cts +5 -5
  34. package/dist/elevenlabs.d.ts +5 -5
  35. package/dist/elevenlabs.js +1 -1
  36. package/dist/elevenlabs.js.map +1 -1
  37. package/dist/genkit.cjs +1 -1
  38. package/dist/genkit.cjs.map +1 -1
  39. package/dist/genkit.d.cts +3 -3
  40. package/dist/genkit.d.ts +3 -3
  41. package/dist/genkit.js +1 -1
  42. package/dist/genkit.js.map +1 -1
  43. package/dist/google-adk.cjs +1 -1
  44. package/dist/google-adk.cjs.map +1 -1
  45. package/dist/google-adk.d.cts +3 -3
  46. package/dist/google-adk.d.ts +3 -3
  47. package/dist/google-adk.js +1 -1
  48. package/dist/google-adk.js.map +1 -1
  49. package/dist/google-genai.cjs +1 -1
  50. package/dist/google-genai.cjs.map +1 -1
  51. package/dist/google-genai.d.cts +4 -4
  52. package/dist/google-genai.d.ts +4 -4
  53. package/dist/google-genai.js +1 -1
  54. package/dist/google-genai.js.map +1 -1
  55. package/dist/index.cjs +156 -57
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +6 -8
  58. package/dist/index.d.ts +6 -8
  59. package/dist/index.js +156 -57
  60. package/dist/index.js.map +1 -1
  61. package/dist/{intercept-D7qFCaRb.d.ts → intercept-Bv0nLpSw.d.ts} +1 -1
  62. package/dist/{intercept-0_lJE6k1.d.cts → intercept-CGngQI8B.d.cts} +1 -1
  63. package/dist/langchain.cjs +3 -4
  64. package/dist/langchain.cjs.map +1 -1
  65. package/dist/langchain.d.cts +3 -3
  66. package/dist/langchain.d.ts +3 -3
  67. package/dist/langchain.js +3 -4
  68. package/dist/langchain.js.map +1 -1
  69. package/dist/livekit.cjs +1 -1
  70. package/dist/livekit.cjs.map +1 -1
  71. package/dist/livekit.d.cts +3 -3
  72. package/dist/livekit.d.ts +3 -3
  73. package/dist/livekit.js +1 -1
  74. package/dist/livekit.js.map +1 -1
  75. package/dist/llamaindex.cjs +1 -1
  76. package/dist/llamaindex.cjs.map +1 -1
  77. package/dist/llamaindex.d.cts +3 -3
  78. package/dist/llamaindex.d.ts +3 -3
  79. package/dist/llamaindex.js +1 -1
  80. package/dist/llamaindex.js.map +1 -1
  81. package/dist/mastra.cjs +3 -4
  82. package/dist/mastra.cjs.map +1 -1
  83. package/dist/mastra.d.cts +3 -3
  84. package/dist/mastra.d.ts +3 -3
  85. package/dist/mastra.js +3 -4
  86. package/dist/mastra.js.map +1 -1
  87. package/dist/openai-agents.cjs +1 -1
  88. package/dist/openai-agents.cjs.map +1 -1
  89. package/dist/openai-agents.d.cts +3 -3
  90. package/dist/openai-agents.d.ts +3 -3
  91. package/dist/openai-agents.js +1 -1
  92. package/dist/openai-agents.js.map +1 -1
  93. package/dist/retell.cjs +1 -1
  94. package/dist/retell.cjs.map +1 -1
  95. package/dist/retell.d.cts +5 -5
  96. package/dist/retell.d.ts +5 -5
  97. package/dist/retell.js +1 -1
  98. package/dist/retell.js.map +1 -1
  99. package/dist/{shared-Bb5B59Bu.d.ts → shared-B4Ef2Wpg.d.ts} +1 -1
  100. package/dist/{shared-DTPWVlWm.d.cts → shared-Cq8mz-7m.d.cts} +1 -1
  101. package/dist/strands.cjs +1 -1
  102. package/dist/strands.cjs.map +1 -1
  103. package/dist/strands.d.cts +3 -3
  104. package/dist/strands.d.ts +3 -3
  105. package/dist/strands.js +1 -1
  106. package/dist/strands.js.map +1 -1
  107. package/dist/twilio.d.cts +4 -4
  108. package/dist/twilio.d.ts +4 -4
  109. package/dist/vapi.cjs +1 -1
  110. package/dist/vapi.cjs.map +1 -1
  111. package/dist/vapi.d.cts +5 -5
  112. package/dist/vapi.d.ts +5 -5
  113. package/dist/vapi.js +1 -1
  114. package/dist/vapi.js.map +1 -1
  115. package/dist/voltagent.cjs +1 -1
  116. package/dist/voltagent.cjs.map +1 -1
  117. package/dist/voltagent.d.cts +3 -3
  118. package/dist/voltagent.d.ts +3 -3
  119. package/dist/voltagent.js +1 -1
  120. package/dist/voltagent.js.map +1 -1
  121. package/dist/{webhook-CG4om_DK.d.cts → webhook-jTx_SegV.d.cts} +1 -1
  122. package/dist/{webhook-1ozGyksG.d.ts → webhook-z2TjUzjv.d.ts} +1 -1
  123. package/dist/whatsapp.d.cts +2 -2
  124. package/dist/whatsapp.d.ts +2 -2
  125. package/package.json +3 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constraints/binding.ts","../src/claims/text.ts","../src/constraints/render.ts","../src/ids.ts","../src/capture/context.ts","../src/capture/frame.ts","../src/capture/mask.ts","../src/capture/tool.ts","../src/replay/playback.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/prompt.ts","../src/integrations/mastra.ts"],"names":["found","folded","args","shown"],"mappings":";;;AA+BO,SAAS,YAAA,CAAa,GAAA,EAAiB,QAAA,GAA6C,EAAC,EAAY;AACtG,EAAA,OAAO;AAAA,IACL,MAAM,GAAA,CAAI,IAAA;AAAA,IACV,OAAO,GAAA,CAAI,IAAA,IAAQ,EAAC,EAAG,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,MACjC,MAAM,CAAA,CAAE,IAAA;AAAA,MACR,OAAO,CAAA,CAAE,KAAA;AAAA,MACT,SAAA,EAAW,EAAE,SAAA,IAAa,IAAA;AAAA,MAC1B,QAAA,EAAU,CAAA,CAAE,QAAA,EAAU,KAAA,IAAS,IAAA;AAAA,MAC/B,KAAK,CAAC,GAAI,CAAA,CAAE,GAAA,IAAO,EAAG,CAAA;AAAA,MACtB,MAAA,EAAQ,QAAA,CAAS,CAAA,CAAE,IAAI,CAAA,IAAK;AAAA,KAC9B,CAAE,CAAA;AAAA,IACF,SAAA,EAAW,GAAA,CAAI,SAAA,IAAa,GAAA,CAAI,cAAc,SAAA,IAAa;AAAA,GAC7D;AACF;AAGO,SAAS,WAAA,CAAY,KAAiB,MAAA,EAAyB;AACpE,EAAA,MAAM,MAAc,EAAC;AACrB,EAAA,KAAA,MAAW,IAAA,IAAQ,GAAA,CAAI,OAAA,IAAW,EAAC,EAAG;AACpC,IAAA,KAAA,MAAWA,UAAS,QAAA,CAAS,MAAA,EAAQ,IAAA,CAAK,IAAA,IAAQ,GAAG,CAAA,EAAG;AACtD,MAAA,IAAI,OAAOA,WAAU,QAAA,IAAYA,MAAAA,KAAU,QAAQ,KAAA,CAAM,OAAA,CAAQA,M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U,MAAA;AAChD,IAAA,IAAI,OAAO,OAAA,KAAY,UAAA,IAAc,YAAA,CAAa,OAAO,CAAA,EAAG;AAC1D,MAAA,GAAA,CAAI,IAAI,CAAA,GAAI,IAAA;AACZ,MAAA;AAAA,IACF;AACA,IAAA,MAAM,OAAA,GAAU,IAAA,CAAuC,IAAA,EAAM,OAAA,EAA2D;AAAA,MACtH,IAAA,EAAM,CAAC,KAAA,KAAU,KAAA;AAAA,MACjB,MAAA,EAAQ,CAAC,MAAA,EAAiB,OAAA,KAAuB,QAAA,CAAS,OAAO,CAAA,IAAK,OAAO,OAAA,CAAQ,UAAA,KAAe,QAAA,GAAW,OAAA,CAAQ,UAAA,GAAa;AAAA,KACrI,CAAA;AACD,IAAA,GAAA,CAAI,IAAI,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,OAAO,MAAA,CAAO,MAAA,CAAO,cAAA,CAAe,IAAI,CAAW,CAAA,EAAa,IAAA,EAAM,EAAE,OAAA,EAAS,SAAS,CAAA;AAAA,EACtH;AACA,EAAA,OAAO,GAAA;AACT;AAEA,SAAS,UAAU,KAAA,EAA6C;AAC9D,EAAA,OAAO,QAAA,CAAS,KAAK,CAAA,IAAK,OAAO,MAAM,GAAA,KAAQ,UAAA;AACjD;AAEA,SAAS,UAAU,KAAA,EAAgC;AACjD,EAAA,OAAO,QAAA,CAAS,KAAK,CAAA,IAAK,OAAO,KAAA,CAAM,OAAA,KAAY,UAAA,IAAc,OAAO,KAAA,CAAM,KAAA,KAAU,UAAA,GAAc,KAAA,GAA+B,IAAA;AACvI;AAEA,SAAS,OAAO,IAAA,EAAuB;AACrC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"mastra.js","sourcesContent":["/**\n * A tool's binding (`tool-bindings`, as the object type registry writes it): which argument carries which field,\n * how to read the objects out of a result, and what the tool can do.\n *\n * ```ts\n * const SEARCH = {\n * tool: \"search_products\",\n * args: [{ attr: \"item_variant.color\", param: \"color\", negation: { param: \"not_color\" } }],\n * results: [{ path: \"ui.cards[*]\", type: \"item_variant\", namespace: \"store\", id: \"variant_id\", fields: { color: \"color\" } }],\n * capabilities: { overfetch: false, relax_flag: \"$.meta.relaxed\", dry_run_param: \"dry_run\" },\n * };\n * ```\n *\n * `parseBinding()` gives the renderer its `Binding`; `resultItems()` reads a result's objects keyed `type.field`,\n * with their `ref` (`type:namespace:id`), which is what the SDK measures the hard constraints sent against and\n * what the tool counterfactual compares. The Python SDK reads bindings the same way.\n */\n\nimport type { Binding } from \"./render.js\";\n\nexport interface RawBinding {\n tool: string;\n args?: readonly { attr: string; param: string; transform?: \"lower\" | \"upper\" | null; negation?: { param?: string } | null; ops?: readonly string[] }[];\n results?: readonly { path?: string; type?: string; namespace?: string; id?: string; fields?: Readonly<Record<string, string>> }[];\n capabilities?: { overfetch?: boolean; relax_flag?: string | null; dry_run_param?: string | null; mask_output?: boolean };\n overfetch?: boolean;\n}\n\ntype Json = Record<string, unknown>;\n\n/** The binding the renderer takes. `families` maps a field (`type.field`) to its attribute family. */\nexport function parseBinding(raw: RawBinding, families: Readonly<Record<string, string>> = {}): Binding {\n return {\n tool: raw.tool,\n args: (raw.args ?? []).map((a) => ({\n attr: a.attr,\n param: a.param,\n transform: a.transform ?? null,\n negation: a.negation?.param ?? null,\n ops: [...(a.ops ?? [])],\n family: families[a.attr] ?? null,\n })),\n overfetch: raw.overfetch ?? raw.capabilities?.overfetch ?? false,\n };\n}\n\n/** The objects a result shows, in order: each `{ref, \"<type>.<field>\": value}`. */\nexport function resultItems(raw: RawBinding, result: unknown): Json[] {\n const out: Json[] = [];\n for (const spec of raw.results ?? []) {\n for (const found of readPath(result, spec.path ?? \"$\")) {\n if (typeof found !== \"object\" || found === null || Array.isArray(found)) continue;\n const entry = found as Json;\n const item: Json = {};\n for (const [field, key] of Object.entries(spec.fields ?? {})) if (key in entry) item[`${String(spec.type)}.${field}`] = entry[key];\n const ident = entry[spec.id ?? \"id\"];\n if (typeof ident === \"string\" || typeof ident === \"number\") item.ref = `${String(spec.type)}:${spec.namespace ?? \"default\"}:${String(ident)}`;\n out.push(item);\n }\n }\n return out;\n}\n\n/** Whether the result says the tool relaxed what it was asked (the binding's `relax_flag`). */\nexport function relaxed(raw: RawBinding, result: unknown): boolean {\n const path = raw.capabilities?.relax_flag;\n return typeof path === \"string\" && readPath(result, path).some((v) => v === true);\n}\n\n/** What a small path reads out of a JSON value: `$` the value, `a.b` a key, `a[*]` each item of a list. */\nfunction readPath(value: unknown, path: string): unknown[] {\n let found: unknown[] = [value];\n const trimmed = path.replace(/^\\$/, \"\").replace(/^\\.+|\\.+$/g, \"\");\n if (!trimmed) return found;\n for (const part of trimmed.split(\".\")) {\n const many = part.endsWith(\"[*]\");\n const key = many ? part.slice(0, -3) : part;\n const step: unknown[] = [];\n for (const current of found) {\n const got = key ? (typeof current === \"object\" && current !== null ? (current as Json)[key] : undefined) : current;\n if (many) {\n if (Array.isArray(got)) step.push(...(got as unknown[]));\n } else if (got !== undefined && got !== null) step.push(got);\n }\n found = step;\n }\n return found;\n}\n","/**\n * Offsets, words and sentences of an output, as every part of the claim checker reads them.\n *\n * Offsets are Unicode code points (the claim contract spec, section 2). The checker reads a text as one\n * UTF-16 unit per code point (`units`), so every index a regular expression returns is a code point offset.\n * Its patterns read `\\w`, `\\d`, `\\s` and `\\b` as Python's `re` does on text (`pattern`): the SDKs and the\n * server's reference checker find the same numbers in the same places.\n */\n\n/** A start and an end, in code points, end excluded. */\nexport type Span = readonly [number, number];\n\nconst WORD_CHARS = String.raw`\\p{L}\\p{N}_`;\n/** What Python's `str.isspace` counts as a space. */\nconst SPACE_CHARS = String.raw`\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000`;\nconst CLASSES: Partial<Record<string, string>> = { w: WORD_CHARS, d: String.raw`\\p{Nd}`, s: SPACE_CHARS };\nconst BOUNDARY = `(?:(?<=[${WORD_CHARS}])(?![${WORD_CHARS}])|(?<![${WORD_CHARS}])(?=[${WORD_CHARS}]))`;\n\n/**\n * A pattern written for Python's `re` on text, as a regular expression that matches the same: `\\w` is a\n * letter, a number or `_` of any script, `\\d` a decimal digit of any script, `\\s` any space, `\\b` the edge\n * of a run of `\\w`, `$` the end or a line break that ends the text, and `\\Z` the end only.\n */\nexport function pattern(source: string, flags = \"\"): RegExp {\n let out = \"\";\n let inClass = false;\n for (let i = 0; i < source.length; i++) {\n const ch = source.charAt(i);\n if (ch === \"\\\\\") {\n const next = source.charAt(++i);\n const chars = CLASSES[next];\n if (chars !== undefined) out += inClass ? chars : `[${chars}]`;\n else if (next === \"b\" && !inClass) out += BOUNDARY;\n else out += next === \"Z\" && !inClass ? \"$\" : `\\\\${next}`;\n continue;\n }\n if (ch === \"[\") inClass = true;\n else if (ch === \"]\") inClass = false;\n out += ch === \"$\" && !inClass ? String.raw`(?=\\n?$)` : ch;\n }\n return new RegExp(out, `${flags}u`);\n}\n\n/** `re.search(text, pos, endpos)`: the first match at `pos` or after, reading nothing past `endpos`. */\nexport function search(re: RegExp, text: string, pos: number, endpos = text.length): RegExpExecArray | null {\n re.lastIndex = pos;\n return re.exec(text.slice(0, endpos));\n}\n\n/** `re.match(text, pos)`, for a sticky pattern: a match starting at `pos` exactly. */\nexport function matchAt(re: RegExp, text: string, pos: number): RegExpExecArray | null {\n re.lastIndex = pos;\n return re.exec(text);\n}\n\n/** `compute`, remembered for the last texts it read: a check reads one output many times. */\nexport function memo<T>(compute: (text: string) => T, size = 256): (text: string) => T {\n const cache = new Map<string, T>();\n return (text) => {\n const hit = cache.get(text);\n if (hit !== undefined) return hit;\n const value = compute(text);\n const oldest = cache.keys().next();\n if (cache.size >= size && !oldest.done) cache.delete(oldest.value);\n cache.set(text, value);\n return value;\n };\n}\n\nconst ASCII = /^\\p{ASCII}*$/u;\nconst SURROGATE = /[\\ud800-\\udfff]/;\nconst DIGIT = /^\\p{Nd}$/u;\nconst WORD_CHAR = /^[\\p{L}\\p{N}]$/u;\nconst MARK = /^[\\p{Mn}\\p{Mc}]$/u;\n\n/** The value of a decimal digit of any script: Unicode encodes each script's digits in one run, 0 to 9. */\nexport function digitValue(ch: string): number {\n let cp = ch.codePointAt(0) ?? 0;\n if (cp >= 0x30 && cp <= 0x39) return cp - 0x30;\n let value = 0;\n while (DIGIT.test(String.fromCodePoint(cp - 1))) {\n cp -= 1;\n value += 1;\n }\n return value % 10;\n}\n\n/** The integer that decimal digits of any script write, as Python's `int` reads it. */\nexport function integer(digits: string): number {\n let value = 0;\n for (const ch of digits) value = value * 10 + digitValue(ch);\n return value;\n}\n\n/**\n * `text` as one UTF-16 unit per code point, so an index is a code point offset. A character past the Basic\n * Multilingual Plane stands in as one unit that every pattern reads alike: a decimal digit of the same value,\n * a letter, or a symbol.\n */\nexport const units = memo((text: string): string => {\n if (!SURROGATE.test(text)) return text;\n let out = \"\";\n for (const ch of text) {\n if (ch.length === 1) out += ch;\n else if (DIGIT.test(ch)) out += String.fromCharCode(0x0660 + digitValue(ch));\n else out += WORD_CHAR.test(ch) ? \"\\u3400\" : \"\\ufffc\";\n }\n return out;\n});\n\n/** The code points of `text` from `start` to `end`. */\nexport function slice(text: string, start: number, end: number): string {\n return Array.from(text).slice(start, end).join(\"\");\n}\n\n/**\n * Whether `c`, a code point of a decomposed text, is a combining mark (a canonical combining class other\n * than 0, what Python's `unicodedata.combining` reads): canonical ordering moves a mark between two marks\n * out of order, and never moves a starter.\n */\nfunction combining(c: string): boolean {\n if (!MARK.test(c)) return false;\n const run = `\\u0301${c}\\u0316`;\n return run.normalize(\"NFD\") !== run;\n}\n\n/** `text` in compatibility form (NFKD), without its combining marks. */\nexport function plain(text: string): string {\n let out = \"\";\n for (const c of text.normalize(\"NFKD\")) if (!combining(c)) out += c;\n return out;\n}\n\n/**\n * Lower case without accents, one code point for each code point, so an offset in the folded text is an\n * offset in the text: a character that folds to more than one (`fi`, `½`) becomes `?`.\n */\nexport const fold = memo((text: string): string => {\n if (ASCII.test(text)) return text.toLowerCase();\n let out = \"\";\n for (const ch of text) {\n const folded = plain(ch).toLowerCase();\n out += Array.from(folded).length === 1 ? folded : \"?\";\n }\n return out;\n});\n\n/** The folded text as the checker's patterns read it, one unit per code point (`units`). */\nexport function folded(text: string): string {\n return units(fold(text));\n}\n\n/** A folded word or number of a text, and where it is. */\nexport interface Word {\n readonly text: string;\n readonly start: number;\n readonly end: number;\n}\n\nconst WORD = /[a-z0-9]+(?:['’][a-z]+)?/g;\n\n/** The folded words and numbers of a text, with their offsets; punctuation separates them. */\nexport const words = memo((text: string): readonly Word[] =>\n Array.from(folded(text).matchAll(WORD), (m) => ({ text: m[0], start: m.index, end: m.index + m[0].length })),\n);\n\nexport function phraseAt(found: readonly Word[], i: number, phrase: readonly string[]): boolean {\n return phrase.every((word, k) => found[i + k]?.text === word);\n}\n\n/** The distinct word sequences of `terms`, leaving out a term without words. */\nexport function phrases(terms: readonly string[]): string[][] {\n const out = new Map<string, string[]>();\n for (const term of terms) {\n const phrase = words(term).map((w) => w.text);\n if (phrase.length > 0) out.set(phrase.join(\" \"), phrase);\n }\n return [...out.values()];\n}\n\n// A sentence ends at `!`, `?` or `;` before a space, at a period before a space and a capital letter (so\n// \"art. 5\" and \"R$ 1.234,56\" never end one), and at a line break.\nconst SENTENCE_END = pattern(String.raw`[!?;](?=\\s|$)|\\.(?=\\s+[A-ZÀ-Ý]|\\s*$)|\\n`, \"g\");\n\nexport const sentences = memo((text: string): readonly Span[] => {\n const all = units(text);\n const spans: Span[] = [];\n let start = 0;\n for (const m of all.matchAll(SENTENCE_END)) {\n const end = m.index + m[0].length;\n if (end > start) spans.push([start, end]);\n start = end;\n }\n if (start < all.length) spans.push([start, all.length]);\n return spans;\n});\n\nexport function sentenceOf(text: string, offset: number): Span {\n return sentences(text).find(([start, end]) => start <= offset && offset < end) ?? [0, units(text).length];\n}\n\nconst QUOTES: Partial<Record<string, string>> = { '\"': '\"', \"“\": \"”\", \"«\": \"»\", \"„\": \"“\" };\n\n/**\n * The spans between quotation marks, marks excluded: straight double quotes pair in order, and the curly\n * and angle quotes pair with their closing mark. A mark left open quotes nothing.\n */\nexport const quotations = memo((text: string): readonly Span[] => {\n const all = units(text);\n const spans: Span[] = [];\n let i = 0;\n while (i < all.length) {\n const close = QUOTES[all.charAt(i)];\n const end = close === undefined ? -1 : all.indexOf(close, i + 1);\n if (end > i + 1) {\n spans.push([i + 1, end]);\n i = end + 1;\n } else i += 1;\n }\n return spans;\n});\n","/**\n * The constraints block rendered for one tool call (`spec/constraints.md`, sections 6 and 7): what the\n * call's arguments can carry through the tool's binding, what they cannot (the residual), and, after the\n * call, how much of what was sent the results honored. The server runs the same rules for\n * `POST /v1/constraints` with a tool.\n *\n * - A hard constraint renders through the binding argument of its field: `in` and `eq` to the argument,\n * `not_in` and `ne` to its negation parameter, a comparison or `between` only to an argument that\n * declares it in `ops`. One value renders as itself, several as a list; `transform` changes the case of\n * text.\n * - A hard constraint that lost a conflict of the block is not rendered at all.\n * - A constraint of a category holds only for a call of that category.\n * - An attribute renders through the argument of its family (`size` for `size.pants`) when it applies:\n * `always`, or `when_asked` and the person asked for it this turn.\n * - What no argument can express is residual: the SDK filters it from the results when the tool\n * overfetches, and it is otherwise unenforced. `exclude` is always residual.\n * - Advisory mode (the default) changes nothing and suggests. Apply mode adds only what the call left out,\n * and only a hard constraint said in this turn or this session, or an attribute the person said; it never\n * overrides an argument the call set (the current utterance wins, and the clash is reported as a\n * conflict), and never adds an inferred size.\n * - A block for another beneficiary than the call's does not apply at all.\n *\n * The same rules as the Python SDK's `niadra.constraints.render`.\n */\n\nimport { fold } from \"../claims/text.js\";\nimport type { ConstraintsBlock, HardConstraint } from \"../types/signals.js\";\n\ntype Op = HardConstraint[\"op\"];\n\nconst SAID = new Set<string>([\"stated\", \"tool_args\", \"correction\"]);\nconst NEGATED = new Set<Op>([\"not_in\", \"ne\"]);\nconst POSITIVE = new Set<Op>([\"in\", \"eq\"]);\n\n/** One argument of a tool's binding (`tool-bindings`): the field it carries and how. */\nexport interface BindingArg {\n /** The field, `type.field`. */\n attr: string;\n param: string;\n transform?: \"lower\" | \"upper\" | null;\n /** The parameter that carries the field's negation (`not_in`, `ne`). */\n negation?: string | null;\n /** The comparisons the parameter accepts besides `in` and `eq`. */\n ops?: readonly string[];\n /** The attribute family of the field (`size`), from the type registry. */\n family?: string | null;\n}\n\nexport interface Binding {\n tool: string;\n args: readonly BindingArg[];\n /** The tool returns more than asked, so the SDK can filter the residual from its results. */\n overfetch?: boolean;\n}\n\n/** The call the model made. */\nexport interface Call {\n args: Readonly<Record<string, unknown>>;\n /** Whose call it is: `self` (the default), `beneficiary:<id>` or `gift`. */\n for?: string;\n category?: string | null;\n /** The attributes the person asked to use this turn (\"in my size\": `size`). */\n asked?: readonly string[];\n}\n\nexport interface Rendering {\n applies: boolean;\n /** What the call sends: its own arguments, plus what apply mode added. */\n args: Record<string, unknown>;\n suggested: Record<string, unknown>;\n injected: string[];\n hardSent: string[];\n residual: string[];\n postFilter: string[];\n /** A hard constraint and the argument the call set against it. */\n conflicts: { id: string; param: string }[];\n}\n\n/** What the results show of the hard constraints sent: \"sent, verifiable, violated\", never only sent. */\nexport interface Honored {\n resultsChecked: number;\n violations: number;\n /** Results without the constrained field: without this count, conformance lies upward. */\n unverifiable: number;\n}\n\n/** The block for one call of the tool `binding` describes. */\nexport function render(\n block: ConstraintsBlock,\n binding: Binding,\n call: Call,\n mode: \"advisory\" | \"apply\" = \"advisory\",\n): Rendering {\n if ((block.subject?.for ?? \"self\") !== (call.for ?? \"self\")) {\n const args = { ...call.args };\n return { applies: false, args, suggested: {}, injected: [], hardSent: [], residual: [], postFilter: [], conflicts: [] };\n }\n const hard = block.hard ?? [];\n const attributes = block.attributes ?? [];\n const lost = new Set((block.conflicts ?? []).flatMap((c) => c.ids.filter((id) => id !== c.kept)));\n const category = call.category ?? null;\n const suggested = new Map<string, unknown>();\n const sources = new Map<string, string[]>();\n const residual: string[] = [];\n const conflicts: { id: string; param: string }[] = [];\n const routed: [HardConstraint, string][] = [];\n for (const h of hard) {\n if (lost.has(h.id) || (h.category != null && h.category !== category)) continue;\n const route = routeOf(h, binding);\n if (!route) {\n residual.push(h.id);\n continue;\n }\n const [arg, param] = route;\n let value = shape(h.values, arg.transform);\n if (suggested.has(param)) {\n if (!POSITIVE.has(h.op) && !NEGATED.has(h.op)) {\n residual.push(h.id);\n continue;\n }\n const before = asList(suggested.get(param));\n const merged = [...before, ...asList(value).filter((v) => !before.includes(v))];\n value = merged.length === 1 ? merged[0] : merged;\n }\n suggested.set(param, value);\n sources.set(param, [...(sources.get(param) ?? []), h.id]);\n routed.push([h, param]);\n if (against(h, arg, call.args)) conflicts.push({ id: h.id, param: arg.param });\n }\n const asked = new Set(call.asked ?? []);\n for (const a of attributes) {\n const family = a.name.split(\".\")[0] ?? a.name;\n if (a.category != null && a.category !== category) continue;\n if (a.apply !== \"always\" && !asked.has(family) && !asked.has(a.name)) continue;\n const carrier = binding.args.find((b) => b.family === family);\n if (carrier && !suggested.has(carrier.param)) {\n suggested.set(carrier.param, shape([a.value], carrier.transform));\n sources.set(carrier.param, [a.id]);\n }\n }\n if ((block.exclude ?? []).length > 0) residual.push(\"exclude\");\n const args = new Map(Object.entries(call.args));\n const injected: string[] = [];\n if (mode === \"apply\") {\n const disputed = new Set(conflicts.map((c) => c.id));\n const allowed = new Set([\n ...hard\n .filter((h) => SAID.has(h.source) && (h.scope === \"turn\" || h.scope === \"session\") && !disputed.has(h.id))\n .map((h) => h.id),\n ...attributes.filter((a) => a.source === \"stated\" || a.source === \"correction\").map((a) => a.id),\n ]);\n for (const [param, value] of suggested) {\n const ids = sources.get(param) ?? [];\n if (!args.has(param) && ids.every((id) => allowed.has(id))) {\n args.set(param, value);\n injected.push(...ids);\n }\n }\n }\n const hardSent = routed.filter(([h, param]) => sent(h, param, args)).map(([h]) => h.id);\n return {\n applies: true,\n args: Object.fromEntries(args),\n suggested: Object.fromEntries(suggested),\n injected,\n hardSent,\n residual,\n postFilter: binding.overfetch ? [...residual] : [],\n conflicts,\n };\n}\n\n/**\n * Each result item, keyed by `type.field`, is a violation when it breaks a hard constraint that was sent,\n * and unverifiable when it breaks none but lacks the field of one.\n */\nexport function honored(\n block: ConstraintsBlock,\n sentIds: readonly string[],\n results: readonly Readonly<Record<string, unknown>>[],\n): Honored {\n const checks = (block.hard ?? []).filter((h) => sentIds.includes(h.id));\n let violations = 0;\n let unverifiable = 0;\n for (const item of results) {\n if (checks.some((h) => item[h.attr] != null && !satisfies(h.op, h.values, item[h.attr]))) violations++;\n else if (checks.some((h) => item[h.attr] == null)) unverifiable++;\n }\n return { resultsChecked: results.length, violations, unverifiable };\n}\n\n/** Whether `value` honors `op` over `values`; text is compared folded, numbers as exact decimals. */\nexport function satisfies(op: Op, values: readonly unknown[], value: unknown): boolean {\n const got = keyOf(value);\n const want = values.map(keyOf);\n const first = want[0];\n switch (op) {\n case \"in\":\n case \"eq\":\n return want.some((w) => same(got, w));\n case \"not_in\":\n case \"ne\":\n return !want.some((w) => same(got, w));\n case \"lt\":\n return holds(compare(got, first), (c) => c < 0);\n case \"lte\":\n return holds(compare(got, first), (c) => c <= 0);\n case \"gt\":\n return holds(compare(got, first), (c) => c > 0);\n case \"gte\":\n return holds(compare(got, first), (c) => c >= 0);\n case \"between\":\n return holds(compare(first, got), (c) => c <= 0) && holds(compare(got, want[1]), (c) => c <= 0);\n }\n}\n\nfunction shape(values: readonly unknown[], transform: BindingArg[\"transform\"]): unknown {\n const out = values.map((v) => {\n if (typeof v !== \"string\") return v;\n return transform === \"lower\" ? v.toLowerCase() : transform === \"upper\" ? v.toUpperCase() : v;\n });\n return out.length === 1 ? out[0] : out;\n}\n\nfunction asList(value: unknown): unknown[] {\n return Array.isArray(value) ? [...(value as unknown[])] : [value];\n}\n\n/** The argument and parameter a hard constraint renders through, if any can express it. */\nfunction routeOf(h: HardConstraint, binding: Binding): [BindingArg, string] | null {\n for (const arg of binding.args) {\n if (arg.attr !== h.attr) continue;\n const ops = arg.ops ?? [];\n if (POSITIVE.has(h.op) && (ops.length === 0 || ops.includes(h.op) || ops.includes(\"in\"))) return [arg, arg.param];\n if (NEGATED.has(h.op) && arg.negation != null) return [arg, arg.negation];\n if (!POSITIVE.has(h.op) && !NEGATED.has(h.op) && ops.includes(h.op)) return [arg, arg.param];\n }\n return null;\n}\n\nfunction sent(h: HardConstraint, param: string, args: ReadonlyMap<string, unknown>): boolean {\n if (!args.has(param)) return false;\n const given = asList(args.get(param));\n if (NEGATED.has(h.op)) return h.values.every((v) => satisfies(\"in\", given, v));\n if (POSITIVE.has(h.op)) return given.every((v) => satisfies(\"in\", h.values, v));\n return given.every((v) => satisfies(h.op, h.values, v));\n}\n\n/** The call set the field's own argument to something the constraint refuses. */\nfunction against(h: HardConstraint, arg: BindingArg, args: Readonly<Record<string, unknown>>): boolean {\n if (!Object.hasOwn(args, arg.param)) return false;\n return asList(args[arg.param]).some((v) => !satisfies(h.op, h.values, v));\n}\n\n/**\n * A value as the comparisons read it: a number (or text that reads as one, or a boolean as 1 or 0) as an\n * exact decimal, `sign * digits * 10^exponent` without leading or trailing zeros; other text folded and\n * trimmed; anything else compares with nothing.\n */\ntype Key =\n | { kind: \"number\"; sign: -1 | 0 | 1; digits: string; exponent: number }\n | { kind: \"text\"; text: string }\n | { kind: \"other\" };\n\nconst DECIMAL = /^([+-]?)(?:(\\d+)(?:\\.(\\d*))?|\\.(\\d+))(?:e([+-]?\\d+))?$/i;\n\nconst OTHER: Key = { kind: \"other\" };\n\nfunction keyOf(value: unknown): Key {\n if (typeof value === \"string\") {\n return decimal(value.trim().replace(/_/g, \"\")) ?? { kind: \"text\", text: fold(value).trim() };\n }\n const number = typeof value === \"boolean\" ? Number(value) : value;\n return typeof number === \"number\" && Number.isFinite(number) ? (decimal(String(number)) ?? OTHER) : OTHER;\n}\n\nfunction decimal(text: string): Key | null {\n const m = DECIMAL.exec(text);\n if (!m) return null;\n const fraction = m[3] ?? m[4] ?? \"\";\n const all = `${m[2] ?? \"\"}${fraction}`.replace(/^0+/, \"\");\n const digits = all.replace(/0+$/, \"\");\n if (!digits) return { kind: \"number\", sign: 0, digits: \"\", exponent: 0 };\n const exponent = Number(m[5] ?? 0) - fraction.length + (all.length - digits.length);\n return { kind: \"number\", sign: m[1] === \"-\" ? -1 : 1, digits, exponent };\n}\n\nfunction same(a: Key, b: Key | undefined): boolean {\n if (a.kind === \"number\" && b?.kind === \"number\") {\n return a.sign === b.sign && a.digits === b.digits && a.exponent === b.exponent;\n }\n return a.kind === \"text\" && b?.kind === \"text\" && a.text === b.text;\n}\n\n/** The order of two keys, or null when they do not compare (text with a number, a missing bound). */\nfunction compare(a: Key | undefined, b: Key | undefined): number | null {\n if (a?.kind === \"text\" && b?.kind === \"text\") return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;\n if (a?.kind !== \"number\" || b?.kind !== \"number\") return null;\n if (a.sign !== b.sign) return a.sign < b.sign ? -1 : 1;\n if (a.sign === 0) return 0;\n // The magnitude: first the place of the leading digit, then the digits from it.\n const lead = a.digits.length + a.exponent - (b.digits.length + b.exponent);\n if (lead !== 0) return lead * a.sign < 0 ? -1 : 1;\n const width = Math.max(a.digits.length, b.digits.length);\n const left = a.digits.padEnd(width, \"0\");\n const right = b.digits.padEnd(width, \"0\");\n return left === right ? 0 : (left < right ? -1 : 1) * a.sign;\n}\n\nfunction holds(order: number | null, test: (order: number) => boolean): boolean {\n return order !== null && test(order);\n}\n","let lastMs = -1;\nlet counter = 0;\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n const webCrypto = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } })\n .crypto;\n if (webCrypto?.getRandomValues) {\n webCrypto.getRandomValues(bytes);\n } else {\n // Node 18 hides Web Crypto behind a flag; idempotency keys need uniqueness, not secrecy.\n for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n return bytes;\n}\n\n/**\n * A UUIDv7 (RFC 9562): time-ordered, so keys minted by one process sort in the order the\n * events happened. A 12-bit counter keeps keys monotonic within the same millisecond.\n */\nexport function uuidv7(now: number = Date.now()): string {\n let ms = now;\n if (ms <= lastMs) {\n ms = lastMs;\n counter = (counter + 1) & 0xfff;\n if (counter === 0) ms += 1;\n } else {\n counter = (randomBytes(2)[0] ?? 0) & 0x7f;\n }\n lastMs = ms;\n\n const bytes = randomBytes(16);\n const high = Math.floor(ms / 2 ** 16);\n const low = ms % 2 ** 16;\n bytes[0] = (high >>> 24) & 0xff;\n bytes[1] = (high >>> 16) & 0xff;\n bytes[2] = (high >>> 8) & 0xff;\n bytes[3] = high & 0xff;\n bytes[4] = (low >>> 8) & 0xff;\n bytes[5] = low & 0xff;\n bytes[6] = 0x70 | ((counter >>> 8) & 0x0f);\n bytes[7] = counter & 0xff;\n bytes[8] = 0x80 | ((bytes[8] ?? 0) & 0x3f);\n\n let hex = \"\";\n for (const byte of bytes) hex += byte.toString(16).padStart(2, \"0\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * Where the turn in progress lives: an `AsyncLocalStorage`, which follows promises, `await` and timers, so a\n * tool called anywhere inside a turn lands in it, and two sub-agents started with `Promise.all` each keep\n * their own.\n *\n * The SDK builds for every runtime and never imports `node:async_hooks` itself. It takes the class from\n * `process.getBuiltinModule(\"node:async_hooks\")` where that exists (Node 20.16 and later, Bun, Deno); a\n * runtime without it passes the class to `useAsyncLocalStorage()`, as Cloudflare Workers do with the\n * `nodejs_als` flag. Where there is none, `currentTurn()` is `undefined` and adapters pass the turn they\n * opened explicitly: capture keeps working, only the implicit lookup is missing.\n */\n\nexport interface AsyncStore<T> {\n getStore(): T | undefined;\n run<R>(store: T, fn: () => R): R;\n enterWith(store: T): void;\n}\n\ntype StoreClass = new <T>() => AsyncStore<T>;\n\nlet chosen: StoreClass | null | undefined;\nconst stores = new Map<string, AsyncStore<unknown>>();\n\n/** The `AsyncLocalStorage` class to hold turns with, on a runtime where the SDK cannot find one itself. */\nexport function useAsyncLocalStorage(storage: StoreClass): void {\n chosen = storage;\n stores.clear();\n}\n\nfunction storeClass(): StoreClass | null {\n if (chosen !== undefined) return chosen;\n try {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n const hooks = proc?.getBuiltinModule?.(\"node:async_hooks\") as { AsyncLocalStorage?: StoreClass } | undefined;\n chosen = hooks?.AsyncLocalStorage ?? null;\n } catch {\n chosen = null;\n }\n return chosen;\n}\n\n/** The store named `name`, or `null` on a runtime without async context. */\nexport function store<T>(name: string): AsyncStore<T> | null {\n const existing = stores.get(name);\n if (existing) return existing as AsyncStore<T>;\n const Class = storeClass();\n if (!Class) return null;\n const created = new Class<unknown>();\n stores.set(name, created);\n return created as AsyncStore<T>;\n}\n","/**\n * A turn in the agent's process: the frame that collects what one turn read, called, said and decided\n * (the Turn Record spec, `turn-record.v0`).\n *\n * Capture never delays the agent and never fails it. At the moment something happens the frame copies it:\n * arguments and results become JSON text right away (`JSON.stringify`, a deep copy by construction), so a\n * later change to the agent's objects never reaches the record. Digests, the claim check and sending happen\n * later, on the sender. When the capture itself fails, the turn goes on and its record says\n * `completeness: incomplete`.\n *\n * The frame in progress is held by an `AsyncLocalStorage` (`capture/context.ts`): `frame.run(fn)` makes it\n * current for `fn` and everything `fn` awaits. A frame opened while another is current is a sub-turn of it:\n * its own `turn_id`, with `agent.parent_turn_id` naming the outer one. A second store holds the call in\n * progress, so a call made inside a tool names it as `parent_call_id`.\n */\n\nimport type { RawBinding } from \"../constraints/binding.js\";\nimport type { ConstraintsBlock } from \"../types/signals.js\";\nimport { uuidv7 } from \"../ids.js\";\nimport type { Playback, Played } from \"../replay/playback.js\";\nimport type { ClaimRecord, TurnPins } from \"../types/turns.js\";\nimport { store } from \"./context.js\";\n\nexport type TurnKind = \"message\" | \"action\" | \"event\" | \"timer\";\nexport type CallStatus = \"ok\" | \"error\" | \"timeout\" | \"cancelled\";\nexport type Flag =\n | \"error\"\n | \"guard_acted\"\n | \"guard_budget_exceeded\"\n | \"handoff\"\n | \"assertion_failed\"\n | \"synthetic\"\n | \"incomplete\"\n | \"negative_feedback\"\n | \"truncated\";\nexport type ContentMode = \"stored\" | \"pointer\" | \"hash_only\";\n\n/** The size the queue counts for a frame besides its blobs, and for each of its calls. */\nconst FRAME_BYTES = 512;\nconst CALL_BYTES = 256;\n\n/** A value of the record, copied at the moment: its JSON text until the queue drops it, then its digest. */\nexport interface Blob {\n data: string | null;\n size: number;\n sha256?: string;\n canonicalSize?: number;\n /** Where the company's store keeps it, once written (`pointer` mode). */\n pointer?: string;\n}\n\n/** An output of the turn, kept for the claim check that runs on the sender. */\nexport interface Said {\n text: string;\n context: string;\n immutable: boolean;\n agent: string | null;\n}\n\n/**\n * A value a read's include blocks served the turn: the claim check's evidence, with whether it may back a\n * claim now (`claimSafe`) and the gaps its object declares. A constraint has no `ref`.\n */\nexport interface StateValue {\n ref: string | null;\n field: string;\n value: unknown;\n claimSafe: boolean;\n role?: string | null;\n declaredGaps?: readonly string[];\n}\n\n/** A call's entry in the record, as the frame keeps it. */\nexport type CallEntry = Record<string, unknown> & { call_id: string; kind: \"tool\" | \"model\" };\n\nexport interface Observation {\n ref: string;\n fields: Record<string, unknown>;\n provenance?: { source: \"live\" | \"snapshot\" | \"cache\"; source_observed_at: string; scope?: string };\n}\n\n/** Takes a closed turn; what `TurnRecorder` does. */\nexport interface Submit {\n submit(frame: TurnFrame): void;\n /** Each field's attribute family, for the tools' bindings (the SDK profile). */\n families?: () => Readonly<Record<string, string>>;\n /** The fields each type hides from this key, for a tool's masked output (the SDK profile). */\n fieldAccess?: () => Readonly<Record<string, Readonly<Record<string, string>>>> | null;\n /** The binding the space serves for a tool, by its name (the SDK profile). */\n bindings?: (tool: string) => RawBinding | null;\n}\n\nconst turns = (): ReturnType<typeof store<TurnFrame>> => store<TurnFrame>(\"niadra_turn\");\nconst callStore = (): ReturnType<typeof store<CallCapture>> => store<CallCapture>(\"niadra_call\");\n\n/** The turn open in this async context, if any. */\nexport function currentTurn(): TurnFrame | undefined {\n return turns()?.getStore();\n}\n\n/** The call in progress in this async context, if any. */\nexport function currentCall(): CallCapture | undefined {\n return callStore()?.getStore();\n}\n\n/** `value` as JSON text, now: the copy a record keeps. Throws when it has no JSON form at all. */\nexport function snapshot(value: unknown): string {\n const text = JSON.stringify(value, (_key, v: unknown) => (typeof v === \"bigint\" ? v.toString() : v)) as string | undefined;\n return text ?? \"null\";\n}\n\nfunction statusOf(error: unknown): CallStatus {\n const name = error instanceof Error ? error.name : \"\";\n if (name === \"AbortError\") return \"cancelled\";\n if (name === \"TimeoutError\" || name === \"NiadraTimeoutError\") return \"timeout\";\n return \"error\";\n}\n\n/**\n * One tool or model call of a turn, open until `result()` or `failed()`. `run(fn)` makes it the call in\n * progress for `fn`, so calls made inside it name it as their parent, and a throw fails it.\n */\nexport class CallCapture {\n readonly callId: string;\n /** In a replay: how the call answers (`replay/playback.ts`). */\n played: Played | null = null;\n /** What the call's result honored of the constraints block, when the tool has a binding. */\n measure: ((result: unknown) => Record<string, unknown> | null) | null = null;\n private readonly started = performance.now();\n private finished = false;\n\n constructor(\n readonly frame: TurnFrame,\n readonly entry: CallEntry,\n ) {\n this.callId = entry.call_id;\n }\n\n get done(): boolean {\n return this.finished;\n }\n\n /**\n * The call returned `value`, as the model saw it. `ui` is the form the interface got, when it differs.\n * `observations` are the objects the result showed, each `{ref, fields, provenance}`.\n */\n result(\n value: unknown,\n options: { ui?: unknown; observations?: readonly Observation[]; costUnits?: Record<string, number>; cacheHit?: boolean } = {},\n ): void {\n if (this.finished) return;\n const extra: Record<string, unknown> = { result_model: this.frame.blob(value) };\n if (this.measure !== null) {\n try {\n extra.applied = this.measure(value);\n } catch {\n this.frame.incomplete();\n }\n }\n if (options.ui !== undefined) extra.result_ui = this.frame.blob(options.ui);\n if (options.observations?.length) extra.observations = options.observations.map((o) => ({ ...o }));\n if (options.costUnits) extra.cost_units = { ...options.costUnits };\n if (options.cacheHit !== undefined) extra.cache_hit = options.cacheHit;\n this.finish(\"ok\", extra);\n }\n\n /** The call ended without a result: a throw, or `timeout` or `cancelled`. */\n failed(error: unknown = \"error\"): void {\n if (this.finished) return;\n const status = typeof error === \"string\" ? (error as CallStatus) : statusOf(error);\n this.finish(status, {});\n if (status === \"error\") this.frame.flag(\"error\");\n }\n\n /** Runs `fn` as the call in progress. */\n run<R>(fn: () => R): R {\n const calls = callStore();\n return calls ? calls.run(this, fn) : fn();\n }\n\n private finish(status: CallStatus, extra: Record<string, unknown>): void {\n this.finished = true;\n for (const [key, value] of Object.entries(extra)) if (value !== undefined && value !== null) this.entry[key] = value;\n this.entry.status = status;\n this.entry.latency_ms = Math.round(performance.now() - this.started);\n }\n}\n\nexport interface FrameOptions {\n agent: string;\n role?: string | null;\n kind?: TurnKind;\n conversationId?: string | null;\n taskId?: string | null;\n pins?: TurnPins;\n adapter?: string | null;\n turnId?: string;\n parent?: TurnFrame;\n}\n\n/**\n * The record of one turn while it runs. `close()` ends it and hands it to the turn queue; nothing else\n * happens on the agent's path. Every method never throws for a failure of the capture itself, and does\n * nothing once the frame is closed.\n */\nexport class TurnFrame {\n readonly turnId: string;\n readonly parentTurnId: string | null;\n readonly agent: string;\n readonly role: string | null;\n readonly kind: TurnKind;\n readonly conversationId: string | null;\n readonly taskId: string | null;\n readonly pins: TurnPins & Record<string, unknown>;\n readonly adapter: string | null;\n readonly startedAt = new Date();\n endedAt: Date | null = null;\n latencyMs: number | null = null;\n readonly calls: CallEntry[] = [];\n readonly blobs = new Map<string, Blob>();\n readonly reads: Record<string, unknown>[] = [];\n readonly said: Said[] = [];\n readonly claims: ClaimRecord[] = [];\n /** What the person was shown or did in the turn, as the interaction spec writes it. */\n readonly interactions: Record<string, unknown>[] = [];\n readonly coordination: { decision_id: string; decision: string }[] = [];\n readonly effects = new Map<string, string>();\n readonly eventKeys: string[] = [];\n readonly flags = new Set<Flag>();\n /** Values the turn's reads placed in the turn block, for the claim check: each with its freshness. */\n readonly state: StateValue[] = [];\n completeness: \"complete\" | \"partial\" | \"incomplete\" = \"complete\";\n handoffId: string | null = null;\n /** The content mode this turn must leave in, when the server refused the recorder's. */\n mode: ContentMode | null = null;\n /** The constraints block the turn read last: what its tools' calls are measured against. */\n constraints: ConstraintsBlock | null = null;\n /**\n * Set in a replay: recorded answers for the tools, and where what the turn says goes. A sub-turn of a\n * replayed turn (a framework's run inside it) is replayed with it, and never sent.\n */\n playback: Playback | null = null;\n closed = false;\n private readonly guardedTexts = new Set<string>();\n private readonly adoptable: CallCapture[] = [];\n private readonly counters = { b: 0, k: 0, m: 0 };\n private readonly started = performance.now();\n\n constructor(\n private readonly recorder: Submit | null,\n options: FrameOptions,\n ) {\n const parent = options.parent;\n this.turnId = options.turnId ?? uuidv7();\n this.parentTurnId = parent?.turnId ?? null;\n this.agent = options.agent;\n this.role = options.role ?? null;\n this.kind = options.kind ?? \"message\";\n this.conversationId = options.conversationId ?? parent?.conversationId ?? null;\n this.taskId = options.taskId ?? (parent && !options.conversationId ? parent.taskId : null);\n this.pins = { ...(options.pins ?? {}) };\n this.adapter = options.adapter ?? null;\n this.playback = parent?.playback ?? null;\n }\n\n /** Whether the frame keeps what the turn says for the claim check on the sender. */\n get recording(): boolean {\n return this.recorder !== null;\n }\n\n // Capture\n\n /**\n * Opens a tool call, copying its arguments now. `callId` is the provider's id when there is one; otherwise\n * the frame names it `k1`, `k2`, ... Call the capture's `result()` or `failed()` when it ends.\n */\n toolCall(\n name: string,\n args?: unknown,\n options: { callId?: string | null; attempt?: number; synthetic?: boolean; cacheHit?: boolean; effectKey?: string; adoptable?: boolean } = {},\n ): CallCapture {\n const entry: CallEntry = {\n call_id: options.callId ?? `k${++this.counters.k}`,\n kind: \"tool\",\n name,\n attempt: options.attempt ?? 1,\n synthetic: options.synthetic ?? false,\n cache_hit: options.cacheHit ?? false,\n };\n if (options.effectKey !== undefined) entry.effect_key = options.effectKey;\n const parent = currentCall();\n if (parent?.frame === this) entry.parent_call_id = parent.callId;\n if (args !== undefined) entry.args = this.blob(args);\n if (options.synthetic) this.flag(\"synthetic\");\n const call = this.add(entry);\n if (options.adoptable) this.adoptable.push(call);\n return call;\n }\n\n /**\n * The open call of `name` an adapter recorded from its framework's callbacks, taken over by the `tool()`\n * wrapper running inside it, so the call is recorded once, with the wrapper's arguments.\n */\n adopt(name: string, args: unknown): CallCapture | undefined {\n for (let i = 0; i < this.adoptable.length; i++) {\n const call = this.adoptable[i];\n if (call === undefined || call.done || call.entry.name !== name) continue;\n this.adoptable.splice(i, 1);\n const before = call.entry.args;\n if (typeof before === \"string\") this.blobs.delete(before);\n const key = args === undefined ? undefined : this.blob(args);\n if (key === undefined) delete call.entry.args;\n else call.entry.args = key;\n return call;\n }\n return undefined;\n }\n\n /**\n * Records a model call that already ended, with its tokens when the provider reported them. The first\n * model named becomes the turn's `model` pin unless the build set one.\n */\n modelCall(\n model: string | null | undefined,\n options: { tokensIn?: number | null; tokensOut?: number | null; tokensCached?: number; latencyMs?: number; callId?: string; status?: CallStatus } = {},\n ): void {\n const entry: CallEntry = { call_id: options.callId ?? `m${++this.counters.m}`, kind: \"model\", status: options.status ?? \"ok\" };\n if (model) {\n entry.name = model;\n this.pinModel(model);\n }\n if (options.tokensIn != null && options.tokensOut != null) {\n entry.tokens = { in: options.tokensIn, cached: options.tokensCached ?? 0, out: options.tokensOut };\n }\n if (options.latencyMs !== undefined) entry.latency_ms = options.latencyMs;\n const parent = currentCall();\n if (parent?.frame === this) entry.parent_call_id = parent.callId;\n this.add(entry);\n }\n\n /** The SDK profile of the client that opened this turn, as far as the tools need it. */\n get profile(): Pick<Submit, \"families\" | \"fieldAccess\" | \"bindings\"> {\n return this.recorder ?? {};\n }\n\n /** The model the turn called, as its `model` pin, unless the build named one. */\n pinModel(model: string): void {\n this.pins.model ??= model;\n }\n\n /**\n * A read the turn made from Niadra, by its version: the pack by ETag, a block by its version. `value` is what\n * the read served, kept as a blob of the record so a replay and the tool counterfactual have it.\n */\n read(surface: string, options: { etag?: string | null; version?: string | null; receiptId?: string | null; value?: unknown } = {}): void {\n if (this.closed) return;\n const entry: Record<string, unknown> = { surface };\n if (options.etag) entry.etag = options.etag;\n if (options.version) entry.version = options.version;\n if (options.receiptId) entry.receipt_id = options.receiptId;\n if (options.value !== undefined && options.value !== null) {\n const key = this.blob(options.value);\n if (key !== undefined) entry.blob = key;\n }\n this.reads.push(entry);\n }\n\n /**\n * What the person was shown or did in the turn, as the interaction spec writes it: a `presented` list (with its\n * `exposure_id` and positions), a `seen`, an `engaged` item of it, a preference. A replay and the tool\n * counterfactual read where the person engaged from here.\n */\n interact(item: Record<string, unknown>): void {\n if (this.closed) return;\n this.interactions.push(JSON.parse(JSON.stringify(item)) as Record<string, unknown>);\n }\n\n /** The pack this turn read: its compiler's version and hash become the turn's `niadra` pins. */\n pack(compiler: string | null | undefined, packHash: string | null | undefined): void {\n const pins: Record<string, string> = {};\n if (compiler) pins.compiler = compiler;\n if (packHash) pins.pack_hash = packHash;\n if (Object.keys(pins).length > 0) this.pins.niadra = pins;\n }\n\n /** Fields of objects a read served the turn, kept for the claim check. */\n observeState(values: readonly StateValue[]): void {\n if (!this.closed) this.state.push(...values);\n }\n\n /**\n * Something the turn emitted: `eventKey` names the event `track()` sent for it (the text itself is never\n * repeated in the record), and the text is kept for the claim check the sender runs.\n */\n say(text: string, options: { eventKey?: string | null; context?: string; immutable?: boolean; agent?: string | null } = {}): void {\n if (this.closed) return;\n if (options.eventKey) this.eventKeys.push(options.eventKey);\n if (this.recorder !== null && !this.guardedTexts.has(text)) {\n this.said.push({ text, context: options.context ?? \"chat\", immutable: options.immutable ?? false, agent: options.agent ?? this.agent });\n }\n }\n\n /** A coordination decision the turn acted on. */\n coordinate(decisionId: string, decision: string): void {\n if (!this.closed) this.coordination.push({ decision_id: decisionId, decision });\n }\n\n /** What the turn saw of an effect: its last state by key. */\n effect(key: string, state: string): void {\n if (!this.closed) this.effects.set(key, state);\n }\n\n /** The claim guard checked `text` and recorded its claims: saying it later adds none. */\n guarded(text: string): void {\n this.guardedTexts.add(text);\n }\n\n addClaims(records: readonly ClaimRecord[]): void {\n this.claims.push(...records);\n }\n\n /** Marks the turn: a flagged turn keeps its values longest in the queue and goes to the kept tier. */\n flag(name: Flag): void {\n this.flags.add(name);\n }\n\n /** The capture failed during the turn: its record says so. */\n incomplete(): void {\n this.completeness = \"incomplete\";\n this.flags.add(\"incomplete\");\n }\n\n // Lifecycle\n\n /** Runs `fn` with this turn current; the turn stays open. */\n run<R>(fn: () => R): R {\n const frames = turns();\n return frames ? frames.run(this, fn) : fn();\n }\n\n /** Makes this the current turn of the running async context, for adapters that open a turn in one callback. */\n enter(): this {\n turns()?.enterWith(this);\n return this;\n }\n\n /** Ends the turn and hands its record to the queue. Later calls do nothing. */\n close(error?: unknown): void {\n if (this.closed) return;\n this.closed = true;\n this.endedAt = new Date();\n this.latencyMs = Math.round(performance.now() - this.started);\n if (error !== undefined && error !== null) this.flags.add(\"error\");\n for (const entry of this.calls) entry.status ??= \"cancelled\"; // a call the turn left open never returned in it\n if (this.recorder !== null && this.playback === null) this.recorder.submit(this);\n }\n\n // For the queue and the sender\n\n /** The value of a blob the frame still holds, read back from its copy; `undefined` otherwise. */\n valueOf(key: unknown): unknown {\n const data = typeof key === \"string\" ? this.blobs.get(key)?.data : null;\n if (data == null) return undefined;\n try {\n return JSON.parse(data) as unknown;\n } catch {\n return undefined;\n }\n }\n\n get flagged(): boolean {\n return this.flags.size > 0;\n }\n\n /** Bytes the queue counts for this turn: its blobs' values and an estimate of the frame. */\n get size(): number {\n let values = 0;\n for (const blob of this.blobs.values()) if (blob.data !== null) values += blob.size;\n return this.sizeWithoutValues + values;\n }\n\n get sizeWithoutValues(): number {\n return FRAME_BYTES + CALL_BYTES * this.calls.length;\n }\n\n /**\n * Drops the values of the blobs to make room. A blob whose digest is known stays as its digest; the\n * others leave the record, with the call fields that named them. Returns the bytes freed.\n */\n dropBlobs(): number {\n let freed = 0;\n for (const [key, blob] of [...this.blobs]) {\n if (blob.data === null) continue;\n freed += blob.size;\n blob.data = null;\n if (blob.sha256 === undefined) {\n this.blobs.delete(key);\n for (const entry of this.calls) {\n if (entry.args === key) delete entry.args;\n if (entry.result_model === key) delete entry.result_model;\n if (entry.result_ui === key) delete entry.result_ui;\n }\n }\n }\n if (freed > 0 && this.completeness === \"complete\") this.completeness = \"partial\";\n return freed;\n }\n\n /** Copies `value` as a blob of the record; `undefined` when it has no copy, and the turn says so. */\n blob(value: unknown): string | undefined {\n let data: string;\n try {\n data = snapshot(value);\n } catch {\n this.incomplete();\n return undefined;\n }\n const key = `b:${++this.counters.b}`;\n this.blobs.set(key, { data, size: data.length });\n return key;\n }\n\n private add(entry: CallEntry): CallCapture {\n if (!this.closed) this.calls.push(entry);\n return new CallCapture(this, entry);\n }\n}\n","/**\n * Field access at the tool's output (`tool(..., { maskOutput: true })`): a field the calling key may not read\n * never reaches the model.\n *\n * The SDK profile says, for each type, the fields this key may not read (`field_access`: `mask` or `deny`).\n * After the tool returns, the result the model gets loses every `deny` field and has every `mask` field's value\n * replaced with `[masked]`, wherever the field appears in it, for the types of the objects the result showed (its\n * `provenance`; every declared type when the tool has none).\n *\n * When Niadra does not answer, the last profile read keeps applying. With no profile ever read, the result\n * passes as it is, unless the tool says `onUnknown: \"block\"`: then the model gets only a marker that the result\n * was withheld, for a company that needs the check to fail closed.\n */\n\nexport const MASKED = \"[masked]\";\nexport const WITHHELD = \"[withheld: the fields this agent may read are not known yet]\";\n\n/** The fields each type hides from this key, by type: `null` while no profile was ever read. */\nexport type Access = () => Readonly<Record<string, Readonly<Record<string, string>>>> | null;\nexport type OnUnknown = \"pass\" | \"block\";\n\n/** `result` as the model may get it. */\nexport function protect(result: unknown, access: ReturnType<Access>, types: readonly string[] | null, onUnknown: OnUnknown): unknown {\n if (access === null) return onUnknown === \"block\" ? WITHHELD : result;\n const rules = new Map<string, string>();\n for (const name of types ?? Object.keys(access)) {\n for (const [field, effect] of Object.entries(access[name] ?? {})) rules.set(field, effect === \"deny\" || rules.get(field) === \"deny\" ? \"deny\" : effect);\n }\n if (rules.size === 0) return result;\n if (typeof result === \"string\" && /^\\s*[[{]/.test(result)) {\n try {\n return JSON.stringify(walk(JSON.parse(result) as unknown, rules));\n } catch {\n return result;\n }\n }\n return walk(result, rules);\n}\n\nfunction walk(value: unknown, rules: ReadonlyMap<string, string>): unknown {\n if (Array.isArray(value)) return value.map((v) => walk(v, rules));\n if (typeof value !== \"object\" || value === null) return value;\n const out: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n const effect = rules.get(key);\n if (effect === \"deny\") continue;\n out[key] = effect === \"mask\" ? MASKED : walk(v, rules);\n }\n return out;\n}\n","/**\n * `tool()`: records each call of a function tool in the turn it runs in, whatever the framework.\n *\n * ```ts\n * const quote = niadra.tool(\"quote\", async (plan: string) => pricing.quote(plan), {\n * provenance: (r) => [{ ref: `health_quote:op:${r.id}`, fields: r.prices }],\n * });\n * ```\n *\n * Inside a turn, a call records its arguments when it starts (the single argument, or the list of them),\n * its result or its failure when it ends, its latency, and the call it was made in. `provenance` turns a\n * result into the objects it showed, each `{ref, fields, provenance}`: without provenance an observation is\n * for display only. `ui` gives the form of the result the interface got, when it differs from the one the\n * model saw. Outside a turn, the tool runs untouched and nothing is recorded. The recording never fails the\n * tool: a provenance function that throws marks the turn incomplete, and the tool's own result and errors\n * pass through unchanged. An async generator is recorded piece by piece, and its result is the list of\n * pieces once it is consumed.\n *\n * With a binding (the tool's binding, as `constraints/binding.ts` reads it: `binding`, else the one the SDK\n * profile serves for the tool's name), a call in a turn that read the constraints block records what it did\n * with the block: the hard constraints its arguments sent, and over the\n * objects its result shows, how many were checked, broke one, or lacked the field. Nothing is changed.\n *\n * With `maskOutput: true`, the fields the key may not read never reach the model (`capture/mask.ts`); the record\n * keeps what the model saw. Left unset, the binding's `capabilities.mask_output` decides.\n *\n * In a replay (`replay/`) the call answers from the record when its arguments match a recorded call of the\n * tool; otherwise it runs only when `dryRun: true` says running it again is safe, and answers `undefined` (a\n * divergence) when not.\n */\n\nimport { parseBinding, relaxed, resultItems } from \"../constraints/binding.js\";\nimport type { RawBinding } from \"../constraints/binding.js\";\nimport { honored, render } from \"../constraints/render.js\";\nimport type { CallCapture, Observation, TurnFrame } from \"./frame.js\";\nimport { currentTurn } from \"./frame.js\";\nimport { protect } from \"./mask.js\";\nimport type { Access, OnUnknown } from \"./mask.js\";\n\nexport interface ToolOptions<A extends unknown[], R> {\n /** The objects a result showed, each `{ref, fields, provenance}`. */\n provenance?: (result: Awaited<R>) => Observation | readonly Observation[] | null | undefined;\n /** The form of the result the interface got, when it differs from the model's. */\n ui?: (result: Awaited<R>) => unknown;\n /** What the record keeps as the arguments; by default the single argument, or the list of them. */\n args?: (...args: A) => unknown;\n /** A replay may run the tool for real when the record has no answer for it. */\n dryRun?: boolean;\n /** The provider's id of the call, when the framework passes it to the tool. */\n callId?: (...args: A) => string | null | undefined;\n /** The turn to record in when the async context does not carry one (a framework that runs tools elsewhere). */\n frame?: () => TurnFrame | null | undefined;\n /** The tool's binding, to measure the constraints block against its calls; wins over the one the profile serves. */\n binding?: RawBinding;\n /** The bindings the SDK profile serves, by tool name; by default the client's (`niadra.tool`) or the turn's. */\n served?: (tool: string) => RawBinding | null;\n /** Keeps the fields this key may not read from the model; left unset, the binding's capability decides. */\n maskOutput?: boolean;\n /** With no profile ever read: `pass` (the default) lets the result through, `block` withholds it. */\n onUnknown?: OnUnknown;\n /** The fields each type hides; by default the SDK profile of the client (`niadra.tool`) or of the turn. */\n access?: Access;\n}\n\n/** What `tool()` knows of the function it wraps, for the runners that call it again. */\nexport interface RecordedTool {\n name: string;\n dryRun: boolean;\n provenance: ((result: never) => Observation | readonly Observation[] | null | undefined) | null;\n binding: RawBinding | null;\n}\n\nconst RECORDED = Symbol.for(\"niadra.tool\");\n\n/** The `tool()` of `fn`, if it is one. */\nexport function recordedTool(fn: unknown): RecordedTool | null {\n return typeof fn === \"function\" ? ((fn as unknown as Record<symbol, RecordedTool | undefined>)[RECORDED] ?? null) : null;\n}\n\nconst isAsyncFunction = (fn: unknown): boolean => Object.prototype.toString.call(fn) === \"[object AsyncFunction]\";\n\nfunction isAsyncIterator(value: unknown): value is AsyncGenerator {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { next?: unknown }).next === \"function\" &&\n Symbol.asyncIterator in value\n );\n}\n\nfunction found(frame: (() => TurnFrame | null | undefined) | undefined): TurnFrame | undefined {\n try {\n return frame?.() ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction thenable(value: unknown): value is PromiseLike<unknown> {\n return typeof value === \"object\" && value !== null && typeof (value as { then?: unknown }).then === \"function\";\n}\n\n/** Records the calls of `fn` as the tool `name`. See the module. */\nexport function tool<A extends unknown[], R>(\n name: string,\n fn: (...args: A) => R,\n options: ToolOptions<A, R> = {},\n): (...args: A) => R {\n const isAsync = isAsyncFunction(fn);\n\n /** The tool's binding: the one the code gives, else the one the SDK profile serves for its name. */\n function bindingOf(frame: TurnFrame | undefined): RawBinding | null {\n return options.binding ?? (options.served ?? frame?.profile.bindings)?.(name) ?? null;\n }\n\n /** Whether the output is masked: `maskOutput` when the code says it, else the binding's capability. */\n function masks(frame: TurnFrame | undefined): boolean {\n return options.maskOutput ?? bindingOf(frame)?.capabilities?.mask_output ?? false;\n }\n\n /** The result as the model may get it. */\n function shield(result: unknown, frame: TurnFrame | undefined): unknown {\n if (!masks(frame)) return result;\n const access = options.access ?? frame?.profile.fieldAccess ?? ((): null => null);\n return protect(result, access(), typesOf(result), options.onUnknown ?? \"pass\");\n }\n\n function typesOf(result: unknown): string[] | null {\n if (!options.provenance) return null;\n try {\n const found = options.provenance(result as Awaited<R>);\n const items = found == null ? [] : Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.map((o) => o.ref.split(\":\")[0] ?? \"\");\n } catch {\n return null;\n }\n }\n\n function end(call: CallCapture, result: unknown, model: unknown = result): void {\n const observations = observed(call, result);\n let shown: unknown;\n if (options.ui) {\n try {\n shown = options.ui(result as Awaited<R>);\n } catch {\n call.frame.incomplete();\n }\n }\n call.result(model, { ui: shown, observations });\n }\n\n function observed(call: CallCapture, result: unknown): Observation[] {\n if (!options.provenance) return [];\n try {\n const found = options.provenance(result as Awaited<R>);\n if (found == null) return [];\n const items = Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.filter((o) => typeof o.ref === \"string\" && typeof o.fields === \"object\");\n } catch {\n call.frame.incomplete();\n return [];\n }\n }\n\n async function* pieces(call: CallCapture, source: AsyncGenerator): AsyncGenerator {\n const kept: unknown[] = [];\n try {\n for await (const piece of source) {\n const shown = shield(piece, call.frame);\n kept.push(shown);\n yield shown;\n }\n } catch (error) {\n call.failed(error);\n throw error;\n }\n end(call, kept);\n }\n\n const wrapped = function (this: unknown, ...args: A): R {\n const frame = currentTurn() ?? found(options.frame);\n if (frame === undefined || frame.closed) {\n if (!masks(frame)) return fn.apply(this, args);\n const out = fn.apply(this, args);\n if (isAsyncIterator(out)) return maskedPieces(out, frame) as R;\n return (thenable(out) ? Promise.resolve(out).then((v) => shield(v, frame)) : shield(out, frame)) as R;\n }\n let recorded: unknown;\n let callId: string | null | undefined;\n try {\n recorded = options.args ? options.args(...args) : args.length === 1 ? args[0] : args;\n callId = options.callId?.(...args);\n } catch {\n recorded = args;\n }\n const call = frame.adopt(name, recorded) ?? frame.toolCall(name, recorded, typeof callId === \"string\" && callId ? { callId } : {});\n const binding = bindingOf(frame);\n if (binding !== null && frame.constraints !== null) call.measure = measure(frame, binding, recorded);\n if (frame.playback !== null) call.played = frame.playback.answer(name, recorded, options.dryRun ?? false);\n if (call.played !== null && !call.played.live) {\n const value = call.played.value;\n end(call, value);\n return (isAsync ? Promise.resolve(value) : value) as R;\n }\n let result: R;\n try {\n result = call.run(() => fn.apply(this, args));\n } catch (error) {\n call.failed(error);\n throw error;\n }\n if (isAsyncIterator(result)) return pieces(call, result) as R;\n if (thenable(result)) {\n return Promise.resolve(result).then(\n (value) => {\n const shown = shield(value, frame);\n end(call, value, shown);\n return shown;\n },\n (error: unknown) => {\n call.failed(error);\n throw error;\n },\n ) as R;\n }\n const shown = shield(result, frame);\n end(call, result, shown);\n return shown as R;\n };\n\n async function* maskedPieces(source: AsyncGenerator, frame: TurnFrame | undefined): AsyncGenerator {\n for await (const piece of source) yield shield(piece, frame);\n }\n\n Object.defineProperty(wrapped, \"name\", { value: fn.name || name });\n const marker: RecordedTool = {\n name,\n dryRun: options.dryRun ?? false,\n provenance: (options.provenance ?? null),\n binding: options.binding ?? null,\n };\n Object.defineProperty(wrapped, RECORDED, { value: marker });\n return wrapped;\n}\n\n/** How the call's result honored the block its arguments were rendered against; `null` when it does not apply. */\nfunction measure(frame: TurnFrame, raw: RawBinding, args: unknown): ((result: unknown) => Record<string, unknown> | null) | null {\n const block = frame.constraints;\n if (block === null) return null;\n const given = typeof args === \"object\" && args !== null && !Array.isArray(args) ? (args as Record<string, unknown>) : {};\n const rendering = render(block, parseBinding(raw, frame.profile.families?.() ?? {}), { args: given });\n if (!rendering.applies) return null;\n return (result) => {\n const seen = honored(block, rendering.hardSent, resultItems(raw, result));\n return {\n constraints: block.version,\n hard_sent: [...rendering.hardSent],\n results_checked: seen.resultsChecked,\n violations: seen.violations,\n unverifiable: seen.unverifiable,\n ...(relaxed(raw, result) ? { relaxed: \"declared\" } : {}),\n };\n };\n}\n","/**\n * What a replayed turn answers with: the recorded tool results, matched by the digest of their arguments, the\n * pack of the time, and where what the agent says and declares goes instead of Niadra (the replay spec, 6).\n */\n\nimport { canonicalJson, jsonDigest } from \"../digest.js\";\nimport { sha256Hex } from \"../sha256.js\";\nimport { currentTurn, snapshot } from \"../capture/frame.js\";\nimport type { TurnFrame } from \"../capture/frame.js\";\nimport type { CheckRequest, CheckResult } from \"../types/coordination.js\";\nimport type { ContextResponse } from \"../types/context.js\";\nimport { uuidv7 } from \"../ids.js\";\n\nexport type Mode = \"hermetic_turn\" | \"hermetic_conversation\" | \"era_memory\";\n\n/** A recorded value that could not be read, or is not the value its digest names. */\nexport class BlobError extends Error {\n override readonly name = \"BlobError\";\n}\n\n/** How one tool call answers: `live` runs the tool; otherwise `value` is the answer, recorded or empty. */\nexport interface Played {\n live: boolean;\n value: unknown;\n recorded: boolean;\n}\n\ninterface Recorded {\n argsHash: string | null;\n value: unknown;\n used: boolean;\n}\n\n/** One execution's answers and what it collected. */\nexport class Playback {\n divergent = 0;\n readonly said: string[] = [];\n /** Effect keys the agent declared done, and how many times. */\n readonly done = new Map<string, number>();\n handoff = false;\n /**\n * The working state in this execution, by scope and agent: what the recorded turn read first, then what the\n * replayed agent wrote. It stays here.\n */\n readonly states = new Map<string, { body: Record<string, unknown>; version: number }>();\n\n constructor(\n private readonly calls: Map<string, Recorded[]>,\n readonly mode: Mode = \"hermetic_turn\",\n readonly context: ContextResponse | null = null,\n ) {}\n\n /** An item the replayed agent tried to send: it never leaves, and a handoff is noted. */\n muted(item: unknown): true {\n if ((item as { type?: unknown } | null)?.type === \"handoff\") this.handoff = true;\n return true;\n }\n\n /** What the replayed agent said: the text its assertions read, and its claims. */\n say(frame: TurnFrame, text: string): void {\n this.said.push(text);\n frame.said.push({ text, context: \"chat\", immutable: false, agent: frame.agent });\n }\n\n /** A declaration the replayed agent made: kept here, never sent. */\n declared(kind: string, detail: Record<string, unknown>): void {\n if (kind === \"effect\" && detail.state === \"done\") {\n const key = String(detail.effect_key);\n this.done.set(key, (this.done.get(key) ?? 0) + 1);\n }\n if (kind === \"handoff\") this.handoff = true;\n }\n\n /** A check the replayed agent made, answered here: an effect it already declared done is denied, anything else goes. */\n checked(request: CheckRequest): CheckResult {\n const done = request.effect_key != null && (this.done.get(request.effect_key) ?? 0) > 0;\n const result: CheckResult = { decision: done ? \"deny\" : \"allow\", decision_id: uuidv7(), reasons: done ? [\"effect_done\"] : [], valid_for_s: 0 };\n if (request.effect_key != null) result.effect = { state: done ? \"done\" : \"none\", attempt: 1 };\n return result;\n }\n\n /**\n * A recorded call of `tool` with the same arguments, the recorded ones of one tool taken in order; else the\n * tool runs when it is safe to run dry (in `era_memory`, first), or answers empty.\n */\n answer(tool: string, args: unknown, dryRun: boolean): Played {\n if (this.mode === \"era_memory\" && dryRun) return { live: true, value: undefined, recorded: false };\n const wanted = this.hash(args);\n for (const recorded of this.calls.get(tool) ?? []) {\n if (!recorded.used && recorded.argsHash === wanted) {\n recorded.used = true;\n return { live: false, value: recorded.value, recorded: true };\n }\n }\n this.divergent++;\n return { live: dryRun, value: undefined, recorded: false };\n }\n\n /** The digest of the arguments as a record names them: SHA-256 over their canonical JSON, computed now. */\n private hash(args: unknown): string | null {\n try {\n const canonical = canonicalJson(JSON.parse(snapshot(args)) as unknown);\n return `sha256:${sha256Hex(new TextEncoder().encode(canonical))}`;\n } catch {\n return null;\n }\n }\n}\n\n/** The playback of the turn replayed in this async context, if any. */\nexport function replaying(): Playback | null {\n return currentTurn()?.playback ?? null;\n}\n\n/**\n * The answers of a recorded turn. Every value used is fetched (by pointer, inside the company's boundary) and\n * must match its digest; rejects with `BlobError` otherwise.\n */\nexport async function playback(\n record: Record<string, unknown>,\n read: ((pointer: string) => Promise<string>) | null,\n mode: Mode = \"hermetic_turn\",\n): Promise<Playback> {\n const blobs = (record.blobs ?? {}) as Record<string, Record<string, unknown>>;\n const values = new Map<string, unknown>();\n const value = async (key: unknown): Promise<unknown> => {\n const blob = typeof key === \"string\" ? blobs[key] : undefined;\n if (typeof key !== \"string\" || blob === undefined) return undefined;\n if (!values.has(key)) values.set(key, await materialized(blob, read));\n return values.get(key);\n };\n const calls = new Map<string, Recorded[]>();\n for (const call of (record.calls ?? []) as Record<string, unknown>[]) {\n if (call.kind !== \"tool\" || (call.status ?? \"ok\") !== \"ok\" || !(\"result_model\" in call)) continue;\n const recorded: Recorded = { argsHash: (call.args_hash as string | undefined) ?? null, value: await value(call.result_model), used: false };\n const name = String(call.name);\n calls.set(name, [...(calls.get(name) ?? []), recorded]);\n }\n const pack = ((record.reads ?? []) as Record<string, unknown>[]).find((r) => r.surface === \"pack\");\n let context: ContextResponse | null = null;\n if (pack !== undefined && typeof pack.blob === \"string\" && pack.blob in blobs) {\n const found = await value(pack.blob);\n if (typeof found === \"object\" && found !== null) context = found as ContextResponse;\n }\n const played = new Playback(calls, mode, context);\n for (const read of (record.reads ?? []) as Record<string, unknown>[]) {\n if (read.surface !== \"agent_state\" || typeof read.blob !== \"string\") continue;\n const held = (await value(read.blob)) as { scope?: { kind?: unknown; id?: unknown }; agent?: unknown; version?: unknown; body?: unknown } | undefined;\n if (typeof held !== \"object\") continue;\n const id = JSON.stringify([String(held.scope?.kind), String(held.scope?.id), String(held.agent)]);\n if (!played.states.has(id)) played.states.set(id, { body: { ...((held.body ?? {}) as Record<string, unknown>) }, version: Number(held.version ?? 0) });\n }\n return played;\n}\n\nexport async function materialized(blob: Record<string, unknown>, read: ((pointer: string) => Promise<string>) | null): Promise<unknown> {\n let found: unknown;\n if (\"content\" in blob) found = blob.content;\n else if (typeof blob.pointer === \"string\") {\n if (read === null) throw new BlobError(\"a value kept by pointer needs a reader: niadra.content.register(), or read\");\n try {\n found = JSON.parse(await read(blob.pointer)) as unknown;\n } catch (error) {\n throw new BlobError(\"a value kept by pointer could not be read\", { cause: error });\n }\n } else throw new BlobError(\"the record keeps only the digest of a value the replay needs\");\n if ((await jsonDigest(found)).sha256 !== blob.sha256) throw new BlobError(\"a recorded value does not match its digest\");\n return found;\n}\n","import { NiadraValidationError } from \"./errors.js\";\nimport { includeText } from \"./constraints/text.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport { toObjectRef } from \"./handles.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type {\n ContextFormat,\n ContextPack,\n ContextRequest,\n ContextResponse,\n CoordinationBlock,\n Include,\n LiveTurn,\n PrefetchRequest,\n TargetModel,\n} from \"./types/context.js\";\nimport type { ConstraintsBlock } from \"./types/signals.js\";\nimport type { StateView } from \"./types/state.js\";\nimport type { Verification, View } from \"./types/vocabulary.js\";\n\n/** Arguments of `context()`. Pass exactly one of `subject` or `object`. */\nexport interface ContextParams {\n /** The customer, by any handle the server knows. */\n subject?: Handle;\n /** A business object, such as an invoice, when the task is about the object rather than a person. */\n object?: ObjectRef | string;\n /** The account or partner the person acts for. Requires an active link between the two. */\n about?: Handle;\n /** Defaults to `chat`. */\n view?: View;\n /**\n * The level proven in this conversation. The server may answer with a lower effective level\n * when the source's ceiling is lower; see `response.verification`.\n */\n verification?: Verification;\n /** Enables the per-conversation cache and the server's pinning of the pack. */\n conversation_id?: string;\n /** For internal agents: the task plays the role of the conversation. */\n task_id?: string;\n /**\n * Other words than the turn to pick this read's slots by. Up to 2,000 characters. Wins over\n * `turn`, and like it never changes the pack.\n */\n query?: string;\n /**\n * The customer's last turn; a conversation passes it for you. It goes as `query` and the answer\n * adds `slots`, what the turn selected from memory, in `suffix`, while the pack stays the\n * conversation's pinned one (and is cached as without it).\n */\n turn?: string | null;\n /** Ask only for what changed since this source last read the subject. */\n delta?: boolean;\n /** The model that will read the pack, so the server can size it for that model's prompt cache. */\n target?: TargetModel;\n /** `json` also returns the pack as typed sections in `pack` (`context-pack.v1`). Defaults to `text`. */\n format?: ContextFormat;\n /**\n * Adds `why` to each of `pack.slots`, naming the retrieval channels that\n * ranked it, the fused score, the weights version and, for a derived line, the rule behind it.\n * Requires `format: \"json\"`. It changes nothing else: the pinned text, the slots chosen and the\n * receipt are the same bytes with or without it.\n */\n explain?: boolean;\n /**\n * Blocks read in the same round trip: `[\"constraints\"]` returns the subject's constraints block, `[\"state\"]`\n * the state of their objects. Each only where the space turned its feature on; a block the space does not\n * serve is left out and not asked again for a while, and the read goes on. The blocks are cached with the\n * pack, so a read that fails serves the last good ones too.\n */\n include?: Include[];\n}\n\n/** Arguments of `prefetch()`: who the turn is about, as in `context()`, and the turn so far. */\nexport interface PrefetchParams {\n subject?: Handle;\n object?: ObjectRef | string;\n about?: Handle;\n /** Defaults to `voice`, where partial transcripts come from. */\n view?: View;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** The partial transcript of the customer's turn. */\n text: string;\n}\n\n/** Per-call options shared by every read method. */\nexport interface RequestOptions {\n /** Overrides the method's default time budget, in milliseconds. */\n timeout?: number | undefined;\n /** Cancels the wait. A request shared with other callers keeps running for them. */\n signal?: AbortSignal | undefined;\n /** Extra headers, such as a W3C `traceparent`. */\n headers?: Record<string, string> | undefined;\n}\n\nexport interface ContextOptions extends RequestOptions {\n /** Pass `false` to skip the per-conversation cache for this call. */\n cache?: boolean | undefined;\n /** For `conversation.context()` and `task.context()`: blocks read in the same round trip. */\n include?: Include[] | undefined;\n /** For `conversation.context()` and `task.context()`: `json` also returns `pack`. */\n format?: ContextFormat | undefined;\n /**\n * For `conversation.context()` and `task.context()`: adds `why` to each of `pack.slots`.\n * Requires `format: \"json\"`.\n */\n explain?: boolean | undefined;\n}\n\n/**\n * Where a `context()` result came from.\n *\n * - `network`: a response the server just sent (or confirmed unchanged).\n * - `cache`: a pack younger than the cache TTL; no request was made.\n * - `stale`: an older pack returned at once while a background request refreshes it.\n * - `fallback`: the request failed and this is the last good pack for the conversation.\n * - `none`: nothing was available; `text` is empty and `error` says why.\n */\nexport type ContextSource = \"network\" | \"cache\" | \"stale\" | \"fallback\" | \"none\";\n\n/** What `context()` resolves to. Always usable: on failure `text` is an empty string. */\nexport interface ContextResult {\n /** The pack, ready for the system prompt. Empty when there is nothing to inject. */\n text: string;\n /**\n * The parts that change turn by turn and belong at the end of the prompt, after the\n * conversation: the live turns from other channels, this turn's slots (what the customer's last\n * turn selected from memory), the blocks asked for by `include` (the state view, the constraints) and the\n * delta, in that order, as the API places them. Empty when there are none.\n */\n suffix: string;\n /** Named values from the pack, for templates that place them individually. */\n variables: Record<string, string>;\n /** The pack as typed sections, when read with `format: \"json\"`; otherwise `null`. */\n pack: ContextPack | null;\n source: ContextSource;\n /** The response this result was built from; `null` when `source` is `none`. */\n response: ContextResponse | null;\n /** What went wrong, when `source` is `fallback` or `none`. */\n error: NiadraError | null;\n /** With `include: [\"constraints\"]`: the subject's constraints block. */\n constraints?: ConstraintsBlock | null;\n /** With `include: [\"state\"]`: the state of the subject's objects. */\n state?: StateView | null;\n /** With `include: [\"coordination\"]`: what coordination knows of the subject. */\n coordination?: CoordinationBlock | null;\n}\n\nconst VIEW = /^(voice|chat|brief|full|custom|account|partner|task:[a-z0-9_]{1,40})$/;\nconst MAX_QUERY = 2000;\n\n/** Validates the arguments and builds the wire request, without `known_etag`. */\nexport function buildContextRequest(params: ContextParams): ContextRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n if (params.query !== undefined && params.query.length > MAX_QUERY) {\n throw new NiadraValidationError(`query is longer than ${MAX_QUERY} characters`);\n }\n\n const request: ContextRequest = { view: params.view ?? \"chat\" };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n if (params.query) request.query = params.query;\n if (params.delta) request.delta = true;\n if (params.target) request.target = params.target;\n const format: string = params.format ?? \"text\";\n if (format !== \"text\" && format !== \"json\") throw new NiadraValidationError(\"format is `text` or `json`\");\n if (format === \"json\") request.format = \"json\";\n if (params.explain) {\n if (format !== \"json\") throw new NiadraValidationError('explain requires format: \"json\"');\n request.explain = true;\n }\n if (params.include?.length) request.include = [...new Set(params.include)];\n return request;\n}\n\n/** Validates the arguments of `prefetch()` and builds the wire request. */\nexport function buildPrefetchRequest(params: PrefetchParams): PrefetchRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n const text = params.text.trim();\n if (!text || text.length > MAX_QUERY) throw new NiadraValidationError(`text must be 1 to ${MAX_QUERY} characters`);\n const request: PrefetchRequest = { view: params.view ?? \"voice\", query: text };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n return request;\n}\n\n/** Packs are only cached inside a conversation or task, the unit the server pins them to. */\nexport function cacheScope(request: Pick<ContextRequest, \"conversation_id\" | \"task_id\">): string | null {\n if (request.conversation_id) return `conversation:${request.conversation_id}`;\n if (request.task_id) return `task:${request.task_id}`;\n return null;\n}\n\n/**\n * Every field that changes what the server would compile goes into the key, in a fixed order.\n * `delta` does not: a plain read and a delta read of one conversation get the same pinned\n * bytes, so they share one entry.\n */\nexport function cacheKey(request: ContextRequest): string {\n return JSON.stringify([\n request.subject ?? null,\n request.object ?? null,\n request.about ?? null,\n request.view ?? \"chat\",\n request.verification ?? \"V0\",\n request.conversation_id ?? null,\n request.task_id ?? null,\n request.query ?? null,\n request.target ?? null,\n request.format ?? \"text\",\n request.explain ?? false,\n request.include ?? null,\n ]);\n}\n\n/**\n * Applies a `not_modified` answer to the cached pack: the pinned text and its metadata stay,\n * while the parts outside the pin (live turns, delta, coverage, timing) come from the new answer.\n */\nexport function mergeNotModified(cached: ContextResponse, fresh: ContextResponse): ContextResponse {\n return {\n ...fresh,\n not_modified: false,\n text: cached.text ?? null,\n variables: cached.variables,\n version: cached.version,\n etag: cached.etag,\n manifest_hash: cached.manifest_hash ?? null,\n withheld: cached.withheld,\n cache: cached.cache ?? null,\n pack: cached.pack ?? null,\n // The blocks sit outside the pinned pack: a fresh block wins, and a missing one keeps the cached.\n constraints: fresh.constraints ?? cached.constraints ?? null,\n state: fresh.state ?? cached.state ?? null,\n coordination: fresh.coordination ?? cached.coordination ?? null,\n };\n}\n\nexport function resultFrom(\n response: ContextResponse,\n source: ContextSource,\n error: NiadraError | null = null,\n): ContextResult {\n // A conversation in the control group gets an empty pack on purpose; it is not an error.\n const holdout = response.path === \"holdout\";\n const text = holdout ? \"\" : (response.text ?? \"\");\n const pack = holdout ? null : (response.pack ?? null);\n const blocks = {\n constraints: response.constraints ?? null,\n state: response.state ?? null,\n coordination: response.coordination ?? null,\n };\n return { text, suffix: renderSuffix(response), variables: response.variables, pack, source, response, error, ...blocks };\n}\n\nexport function emptyResult(error: NiadraError | null): ContextResult {\n return { text: \"\", suffix: \"\", variables: {}, pack: null, source: \"none\", response: null, error, constraints: null, state: null, coordination: null };\n}\n\n/**\n * Renders the live turns, the slots and the delta for the end of the prompt, in that order. Kept\n * outside the pinned pack so that the prompt prefix stays byte-identical across turns and the\n * model provider's prompt cache keeps hitting. Returns an empty string when there is nothing to add.\n */\nexport function renderSuffix(response: ContextResponse): string {\n if (response.path === \"holdout\") return \"\";\n const included = includeText(response.text, response.state, response.constraints);\n return [renderLive(response), response.slots ?? \"\", included, response.delta ?? \"\"].filter(Boolean).join(\"\\n\\n\");\n}\n\n/**\n * Renders the live turns (recent turns from other channels that the pack has not absorbed\n * yet) as one tagged block, or an empty string when there are none. `complete=\"false\"` tells\n * the model the list may be missing turns because the server could not read all of them.\n */\nexport function renderLive(response: ContextResponse): string {\n if (response.path === \"holdout\" || response.live.length === 0) return \"\";\n const complete = response.live_complete ? \"\" : ' complete=\"false\"';\n const lines = response.live.map(renderLiveTurn).join(\"\\n\");\n return `<live_turns source=\"niadra\"${complete}>\\n${lines}\\n</live_turns>`;\n}\n\nfunction renderLiveTurn(turn: LiveTurn): string {\n return `[${utcSeconds(turn.at)}] ${turn.channel} · ${turn.speaker}: ${turn.text}`;\n}\n\n/** The same timestamp form in every SDK, whatever precision or offset the server sent. */\nfunction utcSeconds(at: string): string {\n const ms = Date.parse(at);\n return Number.isNaN(ms) ? at : `${new Date(ms).toISOString().slice(0, 19)}Z`;\n}\n","/**\n * What every framework adapter shares: the five primitives (context before the model call, the\n * turns, the tools, the verification and the handoff) wired the same way, and fail-open.\n *\n * Nothing here throws into the framework: a failed read gives an empty context, a failed write\n * is logged without content, and the agent keeps working without memory.\n */\n\nimport { recordedTool } from \"../capture/tool.js\";\nimport type { Played } from \"../replay/playback.js\";\nimport type { AgentMemoryParams } from \"../agent-memory.js\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { CallCapture, TurnFrame } from \"../capture/frame.js\";\nimport type { ContextOptions, ContextResult } from \"../context.js\";\nimport { emptyResult } from \"../context.js\";\nimport type { Conversation, TurnOptions } from \"../conversation.js\";\nimport type { Logger } from \"../logger.js\";\nimport type { Task } from \"../task.js\";\nimport type { BoundTools } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { Verification, VerifyMethod } from \"../types/vocabulary.js\";\n\n/** A customer conversation or an internal agent's task. */\nexport type Session = Conversation | Task;\n\n/** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */\nexport type SessionResolver<S extends Session = Session> = S | (() => S | null | undefined);\n\n/** What the framework proved about the person, recorded with `verify()` before the first context read. */\nexport interface Proof {\n method: VerifyMethod;\n level: Verification;\n /** Defaults to the session's subject. */\n handle?: Handle;\n}\n\n/** A proof, or a function that reads it from the framework when the first context is needed. */\nexport type ProofSource =\n | Proof\n | null\n | undefined\n | (() => Proof | null | undefined | PromiseLike<Proof | null | undefined>);\n\n/**\n * The agent's own working notes: `true` puts the block before the customer's context and offers\n * `search_agent_memory`; `{ write: true }` also offers `remember` (for a key with the\n * `agent_memory:write` scope); the other fields go to `agentMemory()`.\n */\nexport type AgentMemoryOption = boolean | (AgentMemoryParams & { write?: boolean });\n\n/** What goes into the prompt for one model call. */\nexport interface Read {\n context: ContextResult;\n /** The agent's own notes, or an empty string. */\n memory: string;\n /** What goes after the instructions: the notes, then the customer's pack. */\n prefix: string;\n /** What goes at the end: live turns, the turn's slots and deltas. */\n suffix: string;\n}\n\n/** A tool as every framework needs it: the name, the text for the model, the JSON Schema and the call. */\ninterface ToolSpec {\n name: string;\n description: string;\n /** JSON Schema of the arguments. None of them names the customer. */\n parameters: Record<string, unknown>;\n /** Runs the call and returns the text for the model. Never rejects in fail-open mode. */\n execute(args: string | Record<string, unknown>): Promise<string>;\n}\n\nconst ATTESTED: Record<string, Verification> = { A: \"V2\", B: \"V1\", C: \"V1\" };\n\n/**\n * The proof a carrier's STIR/SHAKEN attestation gives a phone call: `A` proves V2, `B` and `C`\n * prove V1, anything else proves nothing (`null`). Accepts the bare letter or the forms carriers\n * and platforms send, such as Twilio's `TN-Validation-Passed-A`.\n */\nexport function attestationProof(attestation: string | null | undefined): Proof | null {\n if (!attestation) return null;\n const value = attestation.trim().toUpperCase();\n if (value.includes(\"FAILED\") || value.startsWith(\"NO-\")) return null;\n const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];\n const level = letter ? ATTESTED[letter] : undefined;\n return level ? { method: \"network_attestation\", level } : null;\n}\n\nexport function resolveSession<S extends Session>(source: SessionResolver<S>): S | null {\n if (typeof source !== \"function\") return source;\n try {\n return source() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction isConversation(session: Session): session is Conversation {\n return \"customer\" in session && typeof session.customer === \"function\";\n}\n\n/** A phone number as an E.164 handle, or `null` when it does not look like one. */\nexport function phoneHandle(value: string | null | undefined): Handle | null {\n const raw = value?.trim().replace(/^tel:/i, \"\").replace(/[\\s().-]/g, \"\");\n if (!raw) return null;\n const e164 = raw.startsWith(\"+\") ? raw : `+${raw}`;\n return /^\\+[1-9]\\d{6,14}$/.test(e164) ? { type: \"phone_e164\", value: e164 } : null;\n}\n\nexport function errorName(error: unknown): string {\n return error instanceof Error ? error.name : typeof error;\n}\n\n/**\n * One session as an adapter drives it. Keeps the verification to a single call made before the\n * first context read, and turns every failure into a log line.\n */\nexport class Bridge {\n private proving: Promise<void> | null = null;\n /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */\n private begun = false;\n private opened = false;\n\n constructor(\n readonly session: Session,\n private readonly proof?: ProofSource,\n private readonly memory: AgentMemoryOption = false,\n ) {}\n\n /**\n * The context and, when enabled, the agent's notes, read side by side within the same budget.\n * Never rejects.\n */\n async read(options: ContextOptions = {}): Promise<Read> {\n const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);\n const [context, memory] = await Promise.all([\n this.context(options),\n memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve(\"\"),\n ]);\n return { context, memory, prefix: [memory, context.text].filter(Boolean).join(\"\\n\\n\"), suffix: context.suffix };\n }\n\n get logger(): Logger {\n return this.session.logger;\n }\n\n /**\n * Starts the first read of a call now, in the background, after the proof when one was given (the\n * pack depends on the level it proves): at call start, so the read runs while the call is set up.\n * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.\n */\n begin(): void {\n const session = this.session;\n if (!isConversation(session)) return;\n const start = (): void => {\n this.safe(\"start the first read\", () => {\n // False off the voice read path (a chat view, the cache off): reads go on as before.\n this.begun = session.begin();\n });\n };\n if (this.proof === undefined || this.proof === null) start();\n else void this.verifyOnce().then(start);\n }\n\n /** Verifies once (when a proof was given), then reads the context. Never rejects. */\n async context(options: ContextOptions = {}): Promise<ContextResult> {\n await this.verifyOnce();\n try {\n const session = this.session;\n if (this.begun && !this.opened && isConversation(session)) {\n this.opened = true;\n // The call's first read, begun at call start: waited for within its own, longer budget.\n await session.ready(options.timeout === undefined ? {} : { timeout: options.timeout });\n }\n return await this.session.context(options);\n } catch (error) {\n this.logger.warn(`could not read context (${errorName(error)})`);\n return emptyResult(null);\n }\n }\n\n /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */\n injected(context: ContextResult): void {\n if (!context.text && !context.suffix && context.response?.path !== \"holdout\") return;\n this.safe(\"mark the injection\", () => {\n this.session.markInjected(context);\n });\n }\n\n customer(text: string, options: TurnOptions = {}): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"record the customer's turn\", () => session.customer(text, options));\n }\n\n /** Sends the customer's turn so far, while they speak. In the background; never throws. */\n prefetch(text: string): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"prefetch the turn\", () => session.prefetch(text));\n }\n\n agent(text: string, options: TurnOptions = {}): void {\n if (!text.trim()) return;\n this.safe(\"record the agent's turn\", () => this.session.agent(text, options));\n }\n\n /** Records a transfer. Tasks have no transfer; the call is ignored for them. */\n async handoff(target: \"agent\" | \"human\", reason?: string): Promise<void> {\n const session = this.session;\n if (!isConversation(session)) return;\n try {\n await session.handoff(reason ? { target, reason } : { target });\n } catch (error) {\n this.logger.warn(`could not record the handoff (${errorName(error)})`);\n }\n }\n\n async end(): Promise<void> {\n try {\n await this.session.end();\n } catch (error) {\n this.logger.warn(`could not end the session (${errorName(error)})`);\n }\n }\n\n /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */\n tools(): ToolSpec[] {\n let bound: BoundTools | null;\n try {\n const memory = this.memory;\n bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });\n } catch (error) {\n this.logger.warn(`could not build the tools (${errorName(error)})`);\n return [];\n }\n return bound ? toolSpecs(bound) : [];\n }\n\n private async agentMemory(params: AgentMemoryParams, options: ContextOptions): Promise<string> {\n try {\n const result = await this.session.agentMemory(params, options.timeout === undefined ? {} : { timeout: options.timeout });\n return result.text;\n } catch (error) {\n this.logger.warn(`could not read the agent's memory (${errorName(error)})`);\n return \"\";\n }\n }\n\n private async verifyOnce(): Promise<void> {\n if (this.proof === undefined || this.proof === null) return;\n this.proving ??= this.runVerify();\n await this.proving;\n }\n\n private async runVerify(): Promise<void> {\n try {\n const source = this.proof;\n const proof = typeof source === \"function\" ? await source() : source;\n if (!proof) return;\n await this.session.verify(proof);\n } catch (error) {\n this.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n\n private safe(what: string, run: () => unknown): void {\n try {\n run();\n } catch (error) {\n this.logger.warn(`could not ${what} (${errorName(error)})`);\n }\n }\n}\n\nfunction withoutWrite(option: AgentMemoryParams & { write?: boolean }): AgentMemoryParams {\n const { write: _, ...params } = option;\n return params;\n}\n\n/** The bound kit as specs. The customer stays inside `bound`; no parameter names them. */\nfunction toolSpecs(bound: BoundTools): ToolSpec[] {\n return bound.definitions.map(({ function: definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n execute: (args) => bound.call(definition.name, args),\n }));\n}\n\n/** The text of a message content in the shapes model APIs use: a string, or a list of text parts. */\nexport function textOf(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content as unknown[]) {\n if (typeof part === \"string\") parts.push(part);\n else if (isRecord(part) && typeof part.text === \"string\" && (part.type === undefined || part.type === \"text\")) {\n parts.push(part.text);\n }\n }\n return parts.join(\"\");\n}\n\nexport function isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** A non-negative integer, or `null`. */\nexport function count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/**\n * The turn records an adapter keeps from its framework's callbacks, keyed by the framework's own ids (a\n * run, a request, a tool call id). A run starting while the session has a turn in progress (yours, from\n * `conversation.turn()`, or a replay's) records into it; otherwise the adapter opens its own turn and closes\n * it when the run ends. A tool call recorded here is taken over by a `tool()` wrapper running inside it, so\n * the call is recorded once. Every method does nothing when turns are off and never throws.\n */\nexport class TurnHooks {\n /** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */\n static readonly MAX_OPEN = 100;\n private readonly frames = new Map<string, { frame: TurnFrame; own: boolean }>();\n private readonly calls = new Map<string, CallCapture>();\n\n constructor(\n readonly adapter: string,\n readonly enabled: boolean,\n ) {}\n\n /** The turn of the run `key`: the session's turn in progress, or a new one of its own. */\n open(session: Session, key: string, params: TurnParams = {}): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = this.frames.get(key);\n if (held !== undefined) return held.frame;\n try {\n const active = session.activeTurn();\n if (active !== undefined && !this.owns(active)) {\n this.frames.set(key, { frame: active, own: false });\n return active;\n }\n const frame = session.openTurn({ ...params, adapter: this.adapter });\n this.frames.set(key, { frame, own: true });\n if (this.frames.size > TurnHooks.MAX_OPEN) {\n const [oldest] = this.frames.keys();\n if (oldest !== undefined) {\n this.frames.get(oldest)?.frame.incomplete();\n this.close(oldest);\n }\n }\n return frame;\n } catch (error) {\n session.logger.warn(`could not open the turn (${errorName(error)})`);\n return undefined;\n }\n }\n\n /** The turn of `key`, else the session's turn in progress. */\n frame(session: Session, key?: string): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = key === undefined ? undefined : this.frames.get(key);\n const frame = held?.frame ?? session.activeTurn();\n return frame === undefined || frame.closed ? undefined : frame;\n }\n\n has(key: string): boolean {\n return this.frames.has(key);\n }\n\n private owns(frame: TurnFrame): boolean {\n for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;\n return false;\n }\n\n /** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */\n close(key: string, error?: unknown): void {\n const held = this.frames.get(key);\n if (held === undefined) return;\n this.frames.delete(key);\n for (const [callKey, call] of this.calls) {\n if (call.frame !== held.frame) continue;\n this.calls.delete(callKey);\n if (held.own) call.failed(error ?? \"error\");\n }\n if (held.own) held.frame.close(error);\n }\n\n /** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */\n toolStart(session: Session, callKey: string, name: string, args: unknown, options: { frameKey?: string; callId?: string | null } = {}): void {\n const frame = this.frame(session, options.frameKey);\n if (frame === undefined) return;\n try {\n this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));\n } catch {\n frame.incomplete();\n }\n }\n\n /**\n * In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the\n * same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function\n * wrapped with `tool()`, which answers itself.\n */\n replayed(session: Session, name: string, args: unknown, fn?: unknown, frameKey?: string): Played | null {\n const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();\n if (frame?.playback == null || (fn !== undefined && recordedTool(fn) !== null)) return null;\n return frame.playback.answer(name, args, false);\n }\n\n toolEnd(callKey: string, result?: unknown, error?: unknown): void {\n const call = this.calls.get(callKey);\n if (call === undefined) return;\n this.calls.delete(callKey);\n try {\n if (error !== undefined) call.failed(error);\n else call.result(result);\n } catch {\n call.frame.incomplete();\n }\n }\n\n /** A model call that ended, with its tokens when the framework reported them. */\n model(\n session: Session,\n model: string | null | undefined,\n tokens: { in?: number | null; out?: number | null; cached?: number | null } = {},\n frameKey?: string,\n ): void {\n const frame = this.frame(session, frameKey);\n if (frame === undefined) return;\n try {\n frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });\n } catch {\n frame.incomplete();\n }\n }\n}\n","/**\n * The AI SDK's language model prompt (`LanguageModelV2Prompt` and later), shared by the adapters\n * that see it: the AI SDK middleware and Mastra's processor.\n */\n\nimport type { Bridge, Read } from \"./shared.js\";\nimport { isRecord } from \"./shared.js\";\n\n/**\n * The prefix (the agent's notes and the customer's pack) as a system message right after the leading system messages, and the suffix as a text\n * part at the end of the last user message, where every provider accepts it. Returns a new array.\n */\nexport function injectPrompt(prompt: readonly unknown[], read: Pick<Read, \"prefix\" | \"suffix\">): unknown[] {\n const injected = [...prompt];\n if (read.suffix) {\n const last = lastUserIndex(injected);\n const message = injected[last];\n if (isRecord(message) && Array.isArray(message.content)) {\n injected[last] = { ...message, content: [...(message.content as unknown[]), { type: \"text\", text: read.suffix }] };\n }\n }\n if (read.prefix) {\n let position = 0;\n while (position < injected.length && roleOf(injected[position]) === \"system\") position++;\n injected.splice(position, 0, { role: \"system\", content: read.prefix });\n }\n return injected;\n}\n\n/**\n * Records the last user message as the customer's turn once, however many steps of a tool loop\n * send the same prompt again. `seen` keeps what was recorded for this session.\n */\nexport function recordNewest(bridge: Bridge, seen: Set<string>, prompt: readonly unknown[]): void {\n const index = lastUserIndex(prompt);\n if (index < 0) return;\n const message = prompt[index];\n const text = isRecord(message) ? textParts(message.content) : \"\";\n const key = `${String(index)}:${text}`;\n if (!text || seen.has(key)) return;\n seen.add(key);\n bridge.customer(text);\n}\n\nfunction textParts(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return (content as unknown[])\n .map((part) => (isRecord(part) && part.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction lastUserIndex(prompt: readonly unknown[]): number {\n for (let index = prompt.length - 1; index >= 0; index--) if (roleOf(prompt[index]) === \"user\") return index;\n return -1;\n}\n\nfunction roleOf(message: unknown): string {\n return isRecord(message) && typeof message.role === \"string\" ? message.role : \"\";\n}\n","/**\n * Niadra for Mastra (`@mastra/core` 1.x): a processor for the agent and the navigation kit as\n * Mastra tools. Mastra's own `Memory` (threads, working memory) stays Mastra's; Niadra is the\n * customer's memory shared with the company's other agents.\n *\n * - `processLLMRequest` rewrites the prompt of each model call without touching the message list:\n * the pack goes after the system messages and the suffix at the end of the last user message,\n * so nothing of it lands in Mastra's memory. The customer's newest message is recorded once.\n * - `processOutputResult` records the final answer with the usage Mastra summed for the run.\n * - With `turns: true`, each request is a turn record, closed with the final answer: each model\n * call with its tokens, each tool call with Mastra's call id and its result. A request inside a\n * turn in progress (`conversation.turn()` around `agent.generate`) records into it. A function\n * wrapped with `tool()` inside a tool takes over its call, which is how a replay answers it.\n * - In a replay the processor wraps every tool of each step with `tool()` (`processInputStep`), so a\n * call answers from the record and never runs live, unless the tool is marked safe to run again.\n *\n * The session comes from the request context (`requestContext.set(\"niadra\", convo)`), or is fixed\n * when the processor is built for one conversation.\n *\n * @example\n * const niadraContext = niadraProcessor();\n * const agent = new Agent({\n * id: \"support\", name: \"Support\", model: openai(\"gpt-4.1\"),\n * instructions: \"You are Acme's support agent.\",\n * tools: ({ requestContext }) => niadraTools(requestContext.get(\"niadra\")),\n * inputProcessors: [niadraContext],\n * outputProcessors: [niadraContext],\n * });\n * const requestContext = new RequestContext([[\"niadra\", convo]]);\n * await agent.generate(messages, { requestContext });\n */\n\nimport type {\n Processor,\n ProcessInputStepArgs,\n ProcessLLMRequestArgs,\n ProcessLLMRequestResult,\n ProcessLLMResponseArgs,\n ProcessOutputResultArgs,\n ProcessOutputStepArgs,\n ProcessToolResultArgs,\n} from \"@mastra/core/processors\";\nimport { tool as recorded, recordedTool } from \"../capture/tool.js\";\nimport { uuidv7 } from \"../ids.js\";\nimport { replaying } from \"../replay/playback.js\";\nimport { createTool } from \"@mastra/core/tools\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport { injectPrompt, recordNewest } from \"./prompt.js\";\nimport { Bridge, TurnHooks, count, errorName, isRecord, resolveSession } from \"./shared.js\";\nimport type { AgentMemoryOption, ProofSource, Session } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session } from \"./shared.js\";\n\n/** The request context key the processor and `niadraTools` read by default. */\nexport const NIADRA_CONTEXT_KEY = \"niadra\";\n\ninterface RequestContextLike {\n get(key: string): unknown;\n}\n\nexport interface NiadraProcessorOptions {\n /** A fixed session, or a function of the request context; defaults to `requestContext.get(\"niadra\")`. */\n session?: Session | ((requestContext: RequestContextLike | undefined) => Session | null | undefined);\n /** What your app proved about the user, recorded once before the first context read. */\n verify?: ProofSource;\n /** Records the newest user message as the customer's turn. Defaults to `true`. */\n recordCustomer?: boolean;\n /** Records the final answer as the agent's turn. Defaults to `true`. */\n recordAgent?: boolean;\n /** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */\n agentMemory?: AgentMemoryOption;\n /** Records each request as a turn, with its model and tool calls. Defaults to `false`. */\n turns?: boolean;\n}\n\n/** The key of the request's run in the processor's state. */\nconst RUN = \"niadraRun\";\n\ninterface State {\n bridge: Bridge;\n seen: Set<string>;\n model: { provider?: string; modelId?: string } | null;\n}\n\n/** A Mastra processor that is both an input processor (the request) and an output processor (the result). */\nexport type NiadraProcessor = Processor<\"niadra\"> &\n Required<Pick<Processor<\"niadra\">, \"processLLMRequest\" | \"processOutputResult\" | \"processLLMResponse\" | \"processOutputStep\" | \"processToolResult\" | \"processInputStep\">>;\n\n/** One processor serves both lists: put the same instance in `inputProcessors` and `outputProcessors`. */\nexport function niadraProcessor(options: NiadraProcessorOptions = {}): NiadraProcessor {\n const states = new WeakMap<Session, State>();\n const hooks = new TurnHooks(\"mastra\", options.turns ?? false);\n /** The request's run: its turn opened on first use, keyed in the processor's per-request state. */\n const runOf = (state: Record<string, unknown>, session: Session): string | undefined => {\n if (!hooks.enabled) return undefined;\n let key = state[RUN];\n if (typeof key !== \"string\") {\n key = uuidv7();\n state[RUN] = key;\n }\n hooks.open(session, key as string);\n return key as string;\n };\n const stateOf = (requestContext: unknown): State | null => {\n const context = isContext(requestContext) ? requestContext : undefined;\n const choice = options.session;\n const session =\n typeof choice === \"function\"\n ? resolveSession(() => choice(context))\n : (choice ?? asSession(context?.get(NIADRA_CONTEXT_KEY)));\n if (!session) return null;\n let state = states.get(session);\n if (!state) {\n state = { bridge: new Bridge(session, options.verify, options.agentMemory), seen: new Set(), model: null };\n states.set(session, state);\n }\n return state;\n };\n\n return {\n id: \"niadra\",\n name: \"Niadra customer context\",\n\n async processLLMRequest({ prompt, model, requestContext, state: kept }: ProcessLLMRequestArgs): Promise<ProcessLLMRequestResult> {\n const state = stateOf(requestContext);\n if (!state) return undefined;\n runOf(kept, state.bridge.session);\n try {\n if (isRecord(model)) {\n state.model = {\n ...(typeof model.provider === \"string\" ? { provider: model.provider } : {}),\n ...(typeof model.modelId === \"string\" ? { modelId: model.modelId } : {}),\n };\n }\n if (options.recordCustomer ?? true) recordNewest(state.bridge, state.seen, prompt);\n const read = await state.bridge.read();\n state.bridge.injected(read.context);\n return { prompt: injectPrompt(prompt, read) as typeof prompt };\n } catch (error) {\n state.bridge.logger.warn(`could not inject context (${errorName(error)})`);\n return undefined;\n }\n },\n\n processLLMResponse({ model, chunks, requestContext, state: kept, fromCache }: ProcessLLMResponseArgs) {\n const state = hooks.enabled && !fromCache ? stateOf(requestContext) : null; // a cached answer called no model\n if (!state) return;\n const key = runOf(kept, state.bridge.session);\n // This step's usage is on its `finish` chunk; `steps` holds the ones before it.\n const finished: unknown = chunks.find((chunk) => chunk.type === \"finish\");\n const payload = isRecord(finished) && isRecord(finished.payload) ? finished.payload : {};\n const usage = isRecord(payload.output) ? payload.output.usage : undefined;\n const name = isRecord(model) && typeof model.modelId === \"string\" ? model.modelId : state.model?.modelId;\n const reported = mastraUsage(usage, state.model);\n const out = isRecord(usage) ? (count(usage.outputTokens) ?? (isRecord(usage.outputTokens) ? count(usage.outputTokens.total) : null)) : null;\n hooks.model(state.bridge.session, name, reported ? { in: reported.prompt_tokens, out, cached: reported.cached_tokens ?? 0 } : {}, key);\n },\n\n processInputStep({ tools }: ProcessInputStepArgs) {\n if (replaying() === null || tools === undefined) return undefined;\n return { tools: replayed(tools) };\n },\n\n processOutputStep({ messageList, toolCalls, requestContext, state: kept }: ProcessOutputStepArgs) {\n const state = hooks.enabled ? stateOf(requestContext) : null;\n if (!state) return messageList;\n const key = runOf(kept, state.bridge.session);\n for (const call of toolCalls ?? []) {\n hooks.toolStart(state.bridge.session, call.toolCallId, call.toolName, call.args, { ...(key ? { frameKey: key } : {}), callId: call.toolCallId });\n }\n return messageList;\n },\n\n processToolResult({ toolCallId, result }: ProcessToolResultArgs) {\n hooks.toolEnd(toolCallId, result);\n },\n\n processOutputResult({ messageList, result, requestContext, state: kept }: ProcessOutputResultArgs) {\n const state = stateOf(requestContext);\n const key = kept[RUN];\n try {\n if (!(options.recordAgent ?? true) || !state || typeof result.text !== \"string\") return messageList;\n try {\n const usage = mastraUsage(result.usage, state.model);\n state.bridge.agent(result.text, usage ? { usage } : {});\n } catch (error) {\n state.bridge.logger.warn(`could not record the agent's answer (${errorName(error)})`);\n }\n return messageList;\n } finally {\n if (typeof key === \"string\") hooks.close(key);\n }\n },\n };\n}\n\n/**\n * The navigation kit as Mastra tools, bound to the session's customer. Pass the session, or\n * nothing inside `tools: ({ requestContext }) => niadraTools(requestContext.get(\"niadra\"))`;\n * without a session it returns no tools.\n */\nexport function niadraTools(session: unknown, options: { agentMemory?: AgentMemoryOption } = {}): Record<string, ReturnType<typeof createTool>> {\n const resolved = asSession(session);\n if (!resolved) return {};\n const tools: Record<string, ReturnType<typeof createTool>> = {};\n for (const spec of new Bridge(resolved, undefined, options.agentMemory).tools()) {\n tools[spec.name] = createTool({\n id: spec.name,\n description: spec.description,\n inputSchema: spec.parameters as Parameters<typeof createTool>[0][\"inputSchema\"],\n execute: async (input: unknown) => parsed(await spec.execute(isRecord(input) ? (input as Record<string, unknown>) : {})),\n });\n }\n return tools;\n}\n\n/**\n * Instructions that carry the context, for agents that cannot take a processor: pass as\n * `instructions`. The pack follows your instructions; turns are not recorded this way.\n */\nexport function niadraInstructions(base: string, options: { session?: Session; agentMemory?: AgentMemoryOption } = {}) {\n return async ({ requestContext }: { requestContext: RequestContextLike }): Promise<string> => {\n const session = options.session ?? asSession(requestContext.get(NIADRA_CONTEXT_KEY));\n if (!session) return base;\n const bridge = new Bridge(session, undefined, options.agentMemory);\n const read = await bridge.read();\n bridge.injected(read.context);\n return [base, read.prefix, read.suffix].filter(Boolean).join(\"\\n\\n\");\n };\n}\n\n/** Mastra's usage (AI SDK 5 numbers, or the split input of later versions) as a `ModelUsage`. */\nexport function mastraUsage(usage: unknown, model: { provider?: string; modelId?: string } | null): ModelUsage | null {\n const provider = model?.provider?.split(\".\")[0]?.toLowerCase();\n const name = model?.modelId;\n if (!isRecord(usage) || !provider || !name) return null;\n let prompt: number | null;\n let cached: number;\n let written = 0;\n if (isRecord(usage.inputTokens)) {\n cached = count(usage.inputTokens.cacheRead) ?? 0;\n written = count(usage.inputTokens.cacheWrite) ?? 0;\n prompt = count(usage.inputTokens.total);\n } else {\n prompt = count(usage.inputTokens) ?? count(usage.promptTokens);\n cached = count(usage.cachedInputTokens) ?? 0;\n }\n if (prompt === null) return null;\n return { provider, model: name, prompt_tokens: Math.max(prompt, cached + written), cached_tokens: cached, cache_write_tokens: written };\n}\n\n/** The step's tools with each `execute` wrapped with `tool()`: in a replay, a call answers from the record. */\nfunction replayed(tools: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [name, spec] of Object.entries(tools)) {\n const execute = isRecord(spec) ? spec.execute : undefined;\n if (typeof execute !== \"function\" || recordedTool(execute)) {\n out[name] = spec;\n continue;\n }\n const wrapped = recorded<[unknown, unknown?], unknown>(name, execute as (input: unknown, context?: unknown) => unknown, {\n args: (input) => input,\n callId: (_input: unknown, context?: unknown) => (isRecord(context) && typeof context.toolCallId === \"string\" ? context.toolCallId : null),\n });\n out[name] = Object.assign(Object.create(Object.getPrototypeOf(spec) as object) as object, spec, { execute: wrapped });\n }\n return out;\n}\n\nfunction isContext(value: unknown): value is RequestContextLike {\n return isRecord(value) && typeof value.get === \"function\";\n}\n\nfunction asSession(value: unknown): Session | null {\n return isRecord(value) && typeof value.context === \"function\" && typeof value.agent === \"function\" ? (value as unknown as Session) : null;\n}\n\nfunction parsed(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/constraints/binding.ts","../src/claims/text.ts","../src/constraints/render.ts","../src/ids.ts","../src/capture/context.ts","../src/capture/frame.ts","../src/capture/mask.ts","../src/capture/tool.ts","../src/replay/playback.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/prompt.ts","../src/integrations/mast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EAAM,CAAC,KAAA,KAAU,KAAA;AAAA,MACjB,MAAA,EAAQ,CAAC,MAAA,EAAiB,OAAA,KAAuB,QAAA,CAAS,OAAO,CAAA,IAAK,OAAO,OAAA,CAAQ,UAAA,KAAe,QAAA,GAAW,OAAA,CAAQ,UAAA,GAAa;AAAA,KACrI,CAAA;AACD,IAAA,GAAA,CAAI,IAAI,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,OAAO,MAAA,CAAO,MAAA,CAAO,cAAA,CAAe,IAAI,CAAW,CAAA,EAAa,IAAA,EAAM,EAAE,OAAA,EAAS,SAAS,CAAA;AAAA,EACtH;AACA,EAAA,OAAO,GAAA;AACT;AAEA,SAAS,UAAU,KAAA,EAA6C;AAC9D,EAAA,OAAO,QAAA,CAAS,KAAK,CAAA,IAAK,OAAO,MAAM,GAAA,KAAQ,UAAA;AACjD;AAEA,SAAS,UAAU,KAAA,EAAgC;AACjD,EAAA,OAAO,QAAA,CAAS,KAAK,CAAA,IAAK,OAAO,KAAA,CAAM,OAAA,KAAY,UAAA,IAAc,OAAO,KAAA,CAAM,KAAA,KAAU,UAAA,GAAc,KAAA,GAA+B,IAAA;AACvI;AAEA,SAAS,OAAO,IAAA,EAAuB;AACrC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"mastra.js","sourcesContent":["/**\n * A tool's binding (`tool-bindings`, as the object type registry writes it): which argument carries which field,\n * how to read the objects out of a result, and what the tool can do.\n *\n * ```ts\n * const SEARCH = {\n * tool: \"search_products\",\n * args: [{ attr: \"item_variant.color\", param: \"color\", negation: { param: \"not_color\" } }],\n * results: [{ path: \"ui.cards[*]\", type: \"item_variant\", namespace: \"store\", id: \"variant_id\", fields: { color: \"color\" } }],\n * capabilities: { overfetch: false, relax_flag: \"$.meta.relaxed\", dry_run_param: \"dry_run\" },\n * };\n * ```\n *\n * `parseBinding()` gives the renderer its `Binding`; `resultItems()` reads a result's objects keyed `type.field`,\n * with their `ref` (`type:namespace:id`), which is what the SDK measures the hard constraints sent against and\n * what the tool counterfactual compares. The Python SDK reads bindings the same way.\n */\n\nimport type { Binding } from \"./render.js\";\n\nexport interface RawBinding {\n tool: string;\n args?: readonly { attr: string; param: string; transform?: \"lower\" | \"upper\" | null; negation?: { param?: string } | null; ops?: readonly string[] }[];\n results?: readonly { path?: string; type?: string; namespace?: string; id?: string; fields?: Readonly<Record<string, string>> }[];\n capabilities?: { overfetch?: boolean; relax_flag?: string | null; dry_run_param?: string | null; mask_output?: boolean };\n overfetch?: boolean;\n}\n\ntype Json = Record<string, unknown>;\n\n/** The binding the renderer takes. `families` maps a field (`type.field`) to its attribute family. */\nexport function parseBinding(raw: RawBinding, families: Readonly<Record<string, string>> = {}): Binding {\n return {\n tool: raw.tool,\n args: (raw.args ?? []).map((a) => ({\n attr: a.attr,\n param: a.param,\n transform: a.transform ?? null,\n negation: a.negation?.param ?? null,\n ops: [...(a.ops ?? [])],\n family: families[a.attr] ?? null,\n })),\n overfetch: raw.overfetch ?? raw.capabilities?.overfetch ?? false,\n };\n}\n\n/** The objects a result shows, in order: each `{ref, \"<type>.<field>\": value}`. */\nexport function resultItems(raw: RawBinding, result: unknown): Json[] {\n const out: Json[] = [];\n for (const spec of raw.results ?? []) {\n for (const found of readPath(result, spec.path ?? \"$\")) {\n if (typeof found !== \"object\" || found === null || Array.isArray(found)) continue;\n const entry = found as Json;\n const item: Json = {};\n for (const [field, key] of Object.entries(spec.fields ?? {})) if (key in entry) item[`${String(spec.type)}.${field}`] = entry[key];\n const ident = entry[spec.id ?? \"id\"];\n if (typeof ident === \"string\" || typeof ident === \"number\") item.ref = `${String(spec.type)}:${spec.namespace ?? \"default\"}:${String(ident)}`;\n out.push(item);\n }\n }\n return out;\n}\n\n/** Whether the result says the tool relaxed what it was asked (the binding's `relax_flag`). */\nexport function relaxed(raw: RawBinding, result: unknown): boolean {\n const path = raw.capabilities?.relax_flag;\n return typeof path === \"string\" && readPath(result, path).some((v) => v === true);\n}\n\n/** What a small path reads out of a JSON value: `$` the value, `a.b` a key, `a[*]` each item of a list. */\nfunction readPath(value: unknown, path: string): unknown[] {\n let found: unknown[] = [value];\n const trimmed = path.replace(/^\\$/, \"\").replace(/^\\.+|\\.+$/g, \"\");\n if (!trimmed) return found;\n for (const part of trimmed.split(\".\")) {\n const many = part.endsWith(\"[*]\");\n const key = many ? part.slice(0, -3) : part;\n const step: unknown[] = [];\n for (const current of found) {\n const got = key ? (typeof current === \"object\" && current !== null ? (current as Json)[key] : undefined) : current;\n if (many) {\n if (Array.isArray(got)) step.push(...(got as unknown[]));\n } else if (got !== undefined && got !== null) step.push(got);\n }\n found = step;\n }\n return found;\n}\n","/**\n * Offsets, words and sentences of an output, as every part of the claim checker reads them.\n *\n * Offsets are Unicode code points (the claim contract spec, section 2). The checker reads a text as one\n * UTF-16 unit per code point (`units`), so every index a regular expression returns is a code point offset.\n * Its patterns read `\\w`, `\\d`, `\\s` and `\\b` as Python's `re` does on text (`pattern`): the SDKs and the\n * server's reference checker find the same numbers in the same places.\n */\n\n/** A start and an end, in code points, end excluded. */\nexport type Span = readonly [number, number];\n\nconst WORD_CHARS = String.raw`\\p{L}\\p{N}_`;\n/** What Python's `str.isspace` counts as a space. */\nconst SPACE_CHARS = String.raw`\\t-\\r\\x1c-\\x20\\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000`;\nconst CLASSES: Partial<Record<string, string>> = { w: WORD_CHARS, d: String.raw`\\p{Nd}`, s: SPACE_CHARS };\nconst BOUNDARY = `(?:(?<=[${WORD_CHARS}])(?![${WORD_CHARS}])|(?<![${WORD_CHARS}])(?=[${WORD_CHARS}]))`;\n\n/**\n * A pattern written for Python's `re` on text, as a regular expression that matches the same: `\\w` is a\n * letter, a number or `_` of any script, `\\d` a decimal digit of any script, `\\s` any space, `\\b` the edge\n * of a run of `\\w`, `$` the end or a line break that ends the text, and `\\Z` the end only.\n */\nexport function pattern(source: string, flags = \"\"): RegExp {\n let out = \"\";\n let inClass = false;\n for (let i = 0; i < source.length; i++) {\n const ch = source.charAt(i);\n if (ch === \"\\\\\") {\n const next = source.charAt(++i);\n const chars = CLASSES[next];\n if (chars !== undefined) out += inClass ? chars : `[${chars}]`;\n else if (next === \"b\" && !inClass) out += BOUNDARY;\n else out += next === \"Z\" && !inClass ? \"$\" : `\\\\${next}`;\n continue;\n }\n if (ch === \"[\") inClass = true;\n else if (ch === \"]\") inClass = false;\n out += ch === \"$\" && !inClass ? String.raw`(?=\\n?$)` : ch;\n }\n return new RegExp(out, `${flags}u`);\n}\n\n/** `re.search(text, pos, endpos)`: the first match at `pos` or after, reading nothing past `endpos`. */\nexport function search(re: RegExp, text: string, pos: number, endpos = text.length): RegExpExecArray | null {\n re.lastIndex = pos;\n return re.exec(text.slice(0, endpos));\n}\n\n/** `re.match(text, pos)`, for a sticky pattern: a match starting at `pos` exactly. */\nexport function matchAt(re: RegExp, text: string, pos: number): RegExpExecArray | null {\n re.lastIndex = pos;\n return re.exec(text);\n}\n\n/** `compute`, remembered for the last texts it read: a check reads one output many times. */\nexport function memo<T>(compute: (text: string) => T, size = 256): (text: string) => T {\n const cache = new Map<string, T>();\n return (text) => {\n const hit = cache.get(text);\n if (hit !== undefined) return hit;\n const value = compute(text);\n const oldest = cache.keys().next();\n if (cache.size >= size && !oldest.done) cache.delete(oldest.value);\n cache.set(text, value);\n return value;\n };\n}\n\nconst ASCII = /^\\p{ASCII}*$/u;\nconst SURROGATE = /[\\ud800-\\udfff]/;\nconst DIGIT = /^\\p{Nd}$/u;\nconst WORD_CHAR = /^[\\p{L}\\p{N}]$/u;\nconst MARK = /^[\\p{Mn}\\p{Mc}]$/u;\n\n/** The value of a decimal digit of any script: Unicode encodes each script's digits in one run, 0 to 9. */\nexport function digitValue(ch: string): number {\n let cp = ch.codePointAt(0) ?? 0;\n if (cp >= 0x30 && cp <= 0x39) return cp - 0x30;\n let value = 0;\n while (DIGIT.test(String.fromCodePoint(cp - 1))) {\n cp -= 1;\n value += 1;\n }\n return value % 10;\n}\n\n/** The integer that decimal digits of any script write, as Python's `int` reads it. */\nexport function integer(digits: string): number {\n let value = 0;\n for (const ch of digits) value = value * 10 + digitValue(ch);\n return value;\n}\n\n/**\n * `text` as one UTF-16 unit per code point, so an index is a code point offset. A character past the Basic\n * Multilingual Plane stands in as one unit that every pattern reads alike: a decimal digit of the same value,\n * a letter, or a symbol.\n */\nexport const units = memo((text: string): string => {\n if (!SURROGATE.test(text)) return text;\n let out = \"\";\n for (const ch of text) {\n if (ch.length === 1) out += ch;\n else if (DIGIT.test(ch)) out += String.fromCharCode(0x0660 + digitValue(ch));\n else out += WORD_CHAR.test(ch) ? \"\\u3400\" : \"\\ufffc\";\n }\n return out;\n});\n\n/** The code points of `text` from `start` to `end`. */\nexport function slice(text: string, start: number, end: number): string {\n return Array.from(text).slice(start, end).join(\"\");\n}\n\n/**\n * Whether `c`, a code point of a decomposed text, is a combining mark (a canonical combining class other\n * than 0, what Python's `unicodedata.combining` reads): canonical ordering moves a mark between two marks\n * out of order, and never moves a starter.\n */\nfunction combining(c: string): boolean {\n if (!MARK.test(c)) return false;\n const run = `\\u0301${c}\\u0316`;\n return run.normalize(\"NFD\") !== run;\n}\n\n/** `text` in compatibility form (NFKD), without its combining marks. */\nexport function plain(text: string): string {\n let out = \"\";\n for (const c of text.normalize(\"NFKD\")) if (!combining(c)) out += c;\n return out;\n}\n\n/**\n * Lower case without accents, one code point for each code point, so an offset in the folded text is an\n * offset in the text: a character that folds to more than one (`fi`, `½`) becomes `?`.\n */\nexport const fold = memo((text: string): string => {\n if (ASCII.test(text)) return text.toLowerCase();\n let out = \"\";\n for (const ch of text) {\n const folded = plain(ch).toLowerCase();\n out += Array.from(folded).length === 1 ? folded : \"?\";\n }\n return out;\n});\n\n/** The folded text as the checker's patterns read it, one unit per code point (`units`). */\nexport function folded(text: string): string {\n return units(fold(text));\n}\n\n/** A folded word or number of a text, and where it is. */\nexport interface Word {\n readonly text: string;\n readonly start: number;\n readonly end: number;\n}\n\nconst WORD = /[a-z0-9]+(?:['’][a-z]+)?/g;\n\n/** The folded words and numbers of a text, with their offsets; punctuation separates them. */\nexport const words = memo((text: string): readonly Word[] =>\n Array.from(folded(text).matchAll(WORD), (m) => ({ text: m[0], start: m.index, end: m.index + m[0].length })),\n);\n\nexport function phraseAt(found: readonly Word[], i: number, phrase: readonly string[]): boolean {\n return phrase.every((word, k) => found[i + k]?.text === word);\n}\n\n/** The distinct word sequences of `terms`, leaving out a term without words. */\nexport function phrases(terms: readonly string[]): string[][] {\n const out = new Map<string, string[]>();\n for (const term of terms) {\n const phrase = words(term).map((w) => w.text);\n if (phrase.length > 0) out.set(phrase.join(\" \"), phrase);\n }\n return [...out.values()];\n}\n\n// A sentence ends at `!`, `?` or `;` before a space, at a period before a space and a capital letter (so\n// \"art. 5\" and \"R$ 1.234,56\" never end one), and at a line break.\nconst SENTENCE_END = pattern(String.raw`[!?;](?=\\s|$)|\\.(?=\\s+[A-ZÀ-Ý]|\\s*$)|\\n`, \"g\");\n\nexport const sentences = memo((text: string): readonly Span[] => {\n const all = units(text);\n const spans: Span[] = [];\n let start = 0;\n for (const m of all.matchAll(SENTENCE_END)) {\n const end = m.index + m[0].length;\n if (end > start) spans.push([start, end]);\n start = end;\n }\n if (start < all.length) spans.push([start, all.length]);\n return spans;\n});\n\nexport function sentenceOf(text: string, offset: number): Span {\n return sentences(text).find(([start, end]) => start <= offset && offset < end) ?? [0, units(text).length];\n}\n\nconst QUOTES: Partial<Record<string, string>> = { '\"': '\"', \"“\": \"”\", \"«\": \"»\", \"„\": \"“\" };\n\n/**\n * The spans between quotation marks, marks excluded: straight double quotes pair in order, and the curly\n * and angle quotes pair with their closing mark. A mark left open quotes nothing.\n */\nexport const quotations = memo((text: string): readonly Span[] => {\n const all = units(text);\n const spans: Span[] = [];\n let i = 0;\n while (i < all.length) {\n const close = QUOTES[all.charAt(i)];\n const end = close === undefined ? -1 : all.indexOf(close, i + 1);\n if (end > i + 1) {\n spans.push([i + 1, end]);\n i = end + 1;\n } else i += 1;\n }\n return spans;\n});\n","/**\n * The constraints block rendered for one tool call (`spec/constraints.md`, sections 6 and 7): what the\n * call's arguments can carry through the tool's binding, what they cannot (the residual), and, after the\n * call, how much of what was sent the results honored. The server runs the same rules for\n * `POST /v1/constraints` with a tool.\n *\n * - A hard constraint renders through the binding argument of its field: `in` and `eq` to the argument,\n * `not_in` and `ne` to its negation parameter, a comparison or `between` only to an argument that\n * declares it in `ops`. One value renders as itself, several as a list; `transform` changes the case of\n * text.\n * - A hard constraint that lost a conflict of the block is not rendered at all.\n * - A constraint of a category holds only for a call of that category.\n * - An attribute renders through the argument of its family (`size` for `size.pants`) when it applies:\n * `always`, or `when_asked` and the person asked for it this turn.\n * - What no argument can express is residual: the SDK filters it from the results when the tool\n * overfetches, and it is otherwise unenforced. `exclude` is always residual.\n * - Advisory mode (the default) changes nothing and suggests. Apply mode adds only what the call left out,\n * and only a hard constraint said in this turn or this session, or an attribute the person said; it never\n * overrides an argument the call set (the current utterance wins, and the clash is reported as a\n * conflict), and never adds an inferred size.\n * - A block for another beneficiary than the call's does not apply at all.\n *\n * The same rules as the Python SDK's `niadra.constraints.render`.\n */\n\nimport { fold } from \"../claims/text.js\";\nimport type { ConstraintsBlock, HardConstraint } from \"../types/signals.js\";\n\ntype Op = HardConstraint[\"op\"];\n\nconst SAID = new Set<string>([\"stated\", \"tool_args\", \"correction\"]);\nconst NEGATED = new Set<Op>([\"not_in\", \"ne\"]);\nconst POSITIVE = new Set<Op>([\"in\", \"eq\"]);\n\n/** One argument of a tool's binding (`tool-bindings`): the field it carries and how. */\nexport interface BindingArg {\n /** The field, `type.field`. */\n attr: string;\n param: string;\n transform?: \"lower\" | \"upper\" | null;\n /** The parameter that carries the field's negation (`not_in`, `ne`). */\n negation?: string | null;\n /** The comparisons the parameter accepts besides `in` and `eq`. */\n ops?: readonly string[];\n /** The attribute family of the field (`size`), from the type registry. */\n family?: string | null;\n}\n\nexport interface Binding {\n tool: string;\n args: readonly BindingArg[];\n /** The tool returns more than asked, so the SDK can filter the residual from its results. */\n overfetch?: boolean;\n}\n\n/** The call the model made. */\nexport interface Call {\n args: Readonly<Record<string, unknown>>;\n /** Whose call it is: `self` (the default), `beneficiary:<id>` or `gift`. */\n for?: string;\n category?: string | null;\n /** The attributes the person asked to use this turn (\"in my size\": `size`). */\n asked?: readonly string[];\n}\n\nexport interface Rendering {\n applies: boolean;\n /** What the call sends: its own arguments, plus what apply mode added. */\n args: Record<string, unknown>;\n suggested: Record<string, unknown>;\n injected: string[];\n hardSent: string[];\n residual: string[];\n postFilter: string[];\n /** A hard constraint and the argument the call set against it. */\n conflicts: { id: string; param: string }[];\n}\n\n/** What the results show of the hard constraints sent: \"sent, verifiable, violated\", never only sent. */\nexport interface Honored {\n resultsChecked: number;\n violations: number;\n /** Results without the constrained field: without this count, conformance lies upward. */\n unverifiable: number;\n}\n\n/** The block for one call of the tool `binding` describes. */\nexport function render(\n block: ConstraintsBlock,\n binding: Binding,\n call: Call,\n mode: \"advisory\" | \"apply\" = \"advisory\",\n): Rendering {\n if ((block.subject?.for ?? \"self\") !== (call.for ?? \"self\")) {\n const args = { ...call.args };\n return { applies: false, args, suggested: {}, injected: [], hardSent: [], residual: [], postFilter: [], conflicts: [] };\n }\n const hard = block.hard ?? [];\n const attributes = block.attributes ?? [];\n const lost = new Set((block.conflicts ?? []).flatMap((c) => c.ids.filter((id) => id !== c.kept)));\n const category = call.category ?? null;\n const suggested = new Map<string, unknown>();\n const sources = new Map<string, string[]>();\n const residual: string[] = [];\n const conflicts: { id: string; param: string }[] = [];\n const routed: [HardConstraint, string][] = [];\n for (const h of hard) {\n if (lost.has(h.id) || (h.category != null && h.category !== category)) continue;\n const route = routeOf(h, binding);\n if (!route) {\n residual.push(h.id);\n continue;\n }\n const [arg, param] = route;\n let value = shape(h.values, arg.transform);\n if (suggested.has(param)) {\n if (!POSITIVE.has(h.op) && !NEGATED.has(h.op)) {\n residual.push(h.id);\n continue;\n }\n const before = asList(suggested.get(param));\n const merged = [...before, ...asList(value).filter((v) => !before.includes(v))];\n value = merged.length === 1 ? merged[0] : merged;\n }\n suggested.set(param, value);\n sources.set(param, [...(sources.get(param) ?? []), h.id]);\n routed.push([h, param]);\n if (against(h, arg, call.args)) conflicts.push({ id: h.id, param: arg.param });\n }\n const asked = new Set(call.asked ?? []);\n for (const a of attributes) {\n const family = a.name.split(\".\")[0] ?? a.name;\n if (a.category != null && a.category !== category) continue;\n if (a.apply !== \"always\" && !asked.has(family) && !asked.has(a.name)) continue;\n const carrier = binding.args.find((b) => b.family === family);\n if (carrier && !suggested.has(carrier.param)) {\n suggested.set(carrier.param, shape([a.value], carrier.transform));\n sources.set(carrier.param, [a.id]);\n }\n }\n if ((block.exclude ?? []).length > 0) residual.push(\"exclude\");\n const args = new Map(Object.entries(call.args));\n const injected: string[] = [];\n if (mode === \"apply\") {\n const disputed = new Set(conflicts.map((c) => c.id));\n const allowed = new Set([\n ...hard\n .filter((h) => SAID.has(h.source) && (h.scope === \"turn\" || h.scope === \"session\") && !disputed.has(h.id))\n .map((h) => h.id),\n ...attributes.filter((a) => a.source === \"stated\" || a.source === \"correction\").map((a) => a.id),\n ]);\n for (const [param, value] of suggested) {\n const ids = sources.get(param) ?? [];\n if (!args.has(param) && ids.every((id) => allowed.has(id))) {\n args.set(param, value);\n injected.push(...ids);\n }\n }\n }\n const hardSent = routed.filter(([h, param]) => sent(h, param, args)).map(([h]) => h.id);\n return {\n applies: true,\n args: Object.fromEntries(args),\n suggested: Object.fromEntries(suggested),\n injected,\n hardSent,\n residual,\n postFilter: binding.overfetch ? [...residual] : [],\n conflicts,\n };\n}\n\n/**\n * Each result item, keyed by `type.field`, is a violation when it breaks a hard constraint that was sent,\n * and unverifiable when it breaks none but lacks the field of one.\n */\nexport function honored(\n block: ConstraintsBlock,\n sentIds: readonly string[],\n results: readonly Readonly<Record<string, unknown>>[],\n): Honored {\n const checks = (block.hard ?? []).filter((h) => sentIds.includes(h.id));\n let violations = 0;\n let unverifiable = 0;\n for (const item of results) {\n if (checks.some((h) => item[h.attr] != null && !satisfies(h.op, h.values, item[h.attr]))) violations++;\n else if (checks.some((h) => item[h.attr] == null)) unverifiable++;\n }\n return { resultsChecked: results.length, violations, unverifiable };\n}\n\n/** Whether `value` honors `op` over `values`; text is compared folded, numbers as exact decimals. */\nexport function satisfies(op: Op, values: readonly unknown[], value: unknown): boolean {\n const got = keyOf(value);\n const want = values.map(keyOf);\n const first = want[0];\n switch (op) {\n case \"in\":\n case \"eq\":\n return want.some((w) => same(got, w));\n case \"not_in\":\n case \"ne\":\n return !want.some((w) => same(got, w));\n case \"lt\":\n return holds(compare(got, first), (c) => c < 0);\n case \"lte\":\n return holds(compare(got, first), (c) => c <= 0);\n case \"gt\":\n return holds(compare(got, first), (c) => c > 0);\n case \"gte\":\n return holds(compare(got, first), (c) => c >= 0);\n case \"between\":\n return holds(compare(first, got), (c) => c <= 0) && holds(compare(got, want[1]), (c) => c <= 0);\n }\n}\n\nfunction shape(values: readonly unknown[], transform: BindingArg[\"transform\"]): unknown {\n const out = values.map((v) => {\n if (typeof v !== \"string\") return v;\n return transform === \"lower\" ? v.toLowerCase() : transform === \"upper\" ? v.toUpperCase() : v;\n });\n return out.length === 1 ? out[0] : out;\n}\n\nfunction asList(value: unknown): unknown[] {\n return Array.isArray(value) ? [...(value as unknown[])] : [value];\n}\n\n/** The argument and parameter a hard constraint renders through, if any can express it. */\nfunction routeOf(h: HardConstraint, binding: Binding): [BindingArg, string] | null {\n for (const arg of binding.args) {\n if (arg.attr !== h.attr) continue;\n const ops = arg.ops ?? [];\n if (POSITIVE.has(h.op) && (ops.length === 0 || ops.includes(h.op) || ops.includes(\"in\"))) return [arg, arg.param];\n if (NEGATED.has(h.op) && arg.negation != null) return [arg, arg.negation];\n if (!POSITIVE.has(h.op) && !NEGATED.has(h.op) && ops.includes(h.op)) return [arg, arg.param];\n }\n return null;\n}\n\nfunction sent(h: HardConstraint, param: string, args: ReadonlyMap<string, unknown>): boolean {\n if (!args.has(param)) return false;\n const given = asList(args.get(param));\n if (NEGATED.has(h.op)) return h.values.every((v) => satisfies(\"in\", given, v));\n if (POSITIVE.has(h.op)) return given.every((v) => satisfies(\"in\", h.values, v));\n return given.every((v) => satisfies(h.op, h.values, v));\n}\n\n/** The call set the field's own argument to something the constraint refuses. */\nfunction against(h: HardConstraint, arg: BindingArg, args: Readonly<Record<string, unknown>>): boolean {\n if (!Object.hasOwn(args, arg.param)) return false;\n return asList(args[arg.param]).some((v) => !satisfies(h.op, h.values, v));\n}\n\n/**\n * A value as the comparisons read it: a number (or text that reads as one, or a boolean as 1 or 0) as an\n * exact decimal, `sign * digits * 10^exponent` without leading or trailing zeros; other text folded and\n * trimmed; anything else compares with nothing.\n */\ntype Key =\n | { kind: \"number\"; sign: -1 | 0 | 1; digits: string; exponent: number }\n | { kind: \"text\"; text: string }\n | { kind: \"other\" };\n\nconst DECIMAL = /^([+-]?)(?:(\\d+)(?:\\.(\\d*))?|\\.(\\d+))(?:e([+-]?\\d+))?$/i;\n\nconst OTHER: Key = { kind: \"other\" };\n\nfunction keyOf(value: unknown): Key {\n if (typeof value === \"string\") {\n return decimal(value.trim().replace(/_/g, \"\")) ?? { kind: \"text\", text: fold(value).trim() };\n }\n const number = typeof value === \"boolean\" ? Number(value) : value;\n return typeof number === \"number\" && Number.isFinite(number) ? (decimal(String(number)) ?? OTHER) : OTHER;\n}\n\nfunction decimal(text: string): Key | null {\n const m = DECIMAL.exec(text);\n if (!m) return null;\n const fraction = m[3] ?? m[4] ?? \"\";\n const all = `${m[2] ?? \"\"}${fraction}`.replace(/^0+/, \"\");\n const digits = all.replace(/0+$/, \"\");\n if (!digits) return { kind: \"number\", sign: 0, digits: \"\", exponent: 0 };\n const exponent = Number(m[5] ?? 0) - fraction.length + (all.length - digits.length);\n return { kind: \"number\", sign: m[1] === \"-\" ? -1 : 1, digits, exponent };\n}\n\nfunction same(a: Key, b: Key | undefined): boolean {\n if (a.kind === \"number\" && b?.kind === \"number\") {\n return a.sign === b.sign && a.digits === b.digits && a.exponent === b.exponent;\n }\n return a.kind === \"text\" && b?.kind === \"text\" && a.text === b.text;\n}\n\n/** The order of two keys, or null when they do not compare (text with a number, a missing bound). */\nfunction compare(a: Key | undefined, b: Key | undefined): number | null {\n if (a?.kind === \"text\" && b?.kind === \"text\") return a.text < b.text ? -1 : a.text > b.text ? 1 : 0;\n if (a?.kind !== \"number\" || b?.kind !== \"number\") return null;\n if (a.sign !== b.sign) return a.sign < b.sign ? -1 : 1;\n if (a.sign === 0) return 0;\n // The magnitude: first the place of the leading digit, then the digits from it.\n const lead = a.digits.length + a.exponent - (b.digits.length + b.exponent);\n if (lead !== 0) return lead * a.sign < 0 ? -1 : 1;\n const width = Math.max(a.digits.length, b.digits.length);\n const left = a.digits.padEnd(width, \"0\");\n const right = b.digits.padEnd(width, \"0\");\n return left === right ? 0 : (left < right ? -1 : 1) * a.sign;\n}\n\nfunction holds(order: number | null, test: (order: number) => boolean): boolean {\n return order !== null && test(order);\n}\n","let lastMs = -1;\nlet counter = 0;\n\nfunction randomBytes(length: number): Uint8Array {\n const bytes = new Uint8Array(length);\n const webCrypto = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } })\n .crypto;\n if (webCrypto?.getRandomValues) {\n webCrypto.getRandomValues(bytes);\n } else {\n // Node 18 hides Web Crypto behind a flag; idempotency keys need uniqueness, not secrecy.\n for (let i = 0; i < length; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n return bytes;\n}\n\n/**\n * A UUIDv7 (RFC 9562): time-ordered, so keys minted by one process sort in the order the\n * events happened. A 12-bit counter keeps keys monotonic within the same millisecond.\n */\nexport function uuidv7(now: number = Date.now()): string {\n let ms = now;\n if (ms <= lastMs) {\n ms = lastMs;\n counter = (counter + 1) & 0xfff;\n if (counter === 0) ms += 1;\n } else {\n counter = (randomBytes(2)[0] ?? 0) & 0x7f;\n }\n lastMs = ms;\n\n const bytes = randomBytes(16);\n const high = Math.floor(ms / 2 ** 16);\n const low = ms % 2 ** 16;\n bytes[0] = (high >>> 24) & 0xff;\n bytes[1] = (high >>> 16) & 0xff;\n bytes[2] = (high >>> 8) & 0xff;\n bytes[3] = high & 0xff;\n bytes[4] = (low >>> 8) & 0xff;\n bytes[5] = low & 0xff;\n bytes[6] = 0x70 | ((counter >>> 8) & 0x0f);\n bytes[7] = counter & 0xff;\n bytes[8] = 0x80 | ((bytes[8] ?? 0) & 0x3f);\n\n let hex = \"\";\n for (const byte of bytes) hex += byte.toString(16).padStart(2, \"0\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * Where the turn in progress lives: an `AsyncLocalStorage`, which follows promises, `await` and timers, so a\n * tool called anywhere inside a turn lands in it, and two sub-agents started with `Promise.all` each keep\n * their own.\n *\n * The SDK builds for every runtime and never imports `node:async_hooks` itself. It takes the class from\n * `process.getBuiltinModule(\"node:async_hooks\")` where that exists (Node 20.16 and later, Bun, Deno); a\n * runtime without it passes the class to `useAsyncLocalStorage()`, as Cloudflare Workers do with the\n * `nodejs_als` flag. Where there is none, `currentTurn()` is `undefined` and adapters pass the turn they\n * opened explicitly: capture keeps working, only the implicit lookup is missing.\n */\n\nexport interface AsyncStore<T> {\n getStore(): T | undefined;\n run<R>(store: T, fn: () => R): R;\n enterWith(store: T): void;\n}\n\ntype StoreClass = new <T>() => AsyncStore<T>;\n\nlet chosen: StoreClass | null | undefined;\nconst stores = new Map<string, AsyncStore<unknown>>();\n\n/** The `AsyncLocalStorage` class to hold turns with, on a runtime where the SDK cannot find one itself. */\nexport function useAsyncLocalStorage(storage: StoreClass): void {\n chosen = storage;\n stores.clear();\n}\n\nfunction storeClass(): StoreClass | null {\n if (chosen !== undefined) return chosen;\n try {\n const proc = (globalThis as { process?: { getBuiltinModule?: (id: string) => unknown } }).process;\n const hooks = proc?.getBuiltinModule?.(\"node:async_hooks\") as { AsyncLocalStorage?: StoreClass } | undefined;\n chosen = hooks?.AsyncLocalStorage ?? null;\n } catch {\n chosen = null;\n }\n return chosen;\n}\n\n/** The store named `name`, or `null` on a runtime without async context. */\nexport function store<T>(name: string): AsyncStore<T> | null {\n const existing = stores.get(name);\n if (existing) return existing as AsyncStore<T>;\n const Class = storeClass();\n if (!Class) return null;\n const created = new Class<unknown>();\n stores.set(name, created);\n return created as AsyncStore<T>;\n}\n","/**\n * A turn in the agent's process: the frame that collects what one turn read, called, said and decided\n * (the Turn Record spec, `turn-record.v0`).\n *\n * Capture never delays the agent and never fails it. At the moment something happens the frame copies it:\n * arguments and results become JSON text right away (`JSON.stringify`, a deep copy by construction), so a\n * later change to the agent's objects never reaches the record. Digests, the claim check and sending happen\n * later, on the sender. When the capture itself fails, the turn goes on and its record says\n * `completeness: incomplete`.\n *\n * The frame in progress is held by an `AsyncLocalStorage` (`capture/context.ts`): `frame.run(fn)` makes it\n * current for `fn` and everything `fn` awaits. A frame opened while another is current is a sub-turn of it:\n * its own `turn_id`, with `agent.parent_turn_id` naming the outer one. A second store holds the call in\n * progress, so a call made inside a tool names it as `parent_call_id`.\n */\n\nimport type { RawBinding } from \"../constraints/binding.js\";\nimport type { ConstraintsBlock } from \"../types/signals.js\";\nimport { uuidv7 } from \"../ids.js\";\nimport type { Playback, Played } from \"../replay/playback.js\";\nimport type { ClaimRecord, TurnPins } from \"../types/turns.js\";\nimport { store } from \"./context.js\";\n\nexport type TurnKind = \"message\" | \"action\" | \"event\" | \"timer\";\nexport type CallStatus = \"ok\" | \"error\" | \"timeout\" | \"cancelled\";\nexport type Flag =\n | \"error\"\n | \"guard_acted\"\n | \"guard_budget_exceeded\"\n | \"handoff\"\n | \"assertion_failed\"\n | \"synthetic\"\n | \"incomplete\"\n | \"negative_feedback\"\n | \"truncated\";\nexport type ContentMode = \"stored\" | \"pointer\" | \"hash_only\";\n\n/** The size the queue counts for a frame besides its blobs, and for each of its calls. */\nconst FRAME_BYTES = 512;\nconst CALL_BYTES = 256;\n\n/** A value of the record, copied at the moment: its JSON text until the queue drops it, then its digest. */\nexport interface Blob {\n data: string | null;\n size: number;\n sha256?: string;\n canonicalSize?: number;\n /** Where the company's store keeps it, once written (`pointer` mode). */\n pointer?: string;\n}\n\n/** An output of the turn, kept for the claim check that runs on the sender. */\nexport interface Said {\n text: string;\n context: string;\n immutable: boolean;\n agent: string | null;\n}\n\n/**\n * A value a read's include blocks served the turn: the claim check's evidence, with whether it may back a\n * claim now (`claimSafe`) and the gaps its object declares. A constraint has no `ref`.\n */\nexport interface StateValue {\n ref: string | null;\n field: string;\n value: unknown;\n claimSafe: boolean;\n role?: string | null;\n declaredGaps?: readonly string[];\n}\n\n/** A call's entry in the record, as the frame keeps it. */\nexport type CallEntry = Record<string, unknown> & { call_id: string; kind: \"tool\" | \"model\" };\n\nexport interface Observation {\n ref: string;\n fields: Record<string, unknown>;\n provenance?: { source: \"live\" | \"snapshot\" | \"cache\"; source_observed_at: string; scope?: string };\n}\n\n/** Takes a closed turn; what `TurnRecorder` does. */\nexport interface Submit {\n submit(frame: TurnFrame): void;\n /** Each field's attribute family, for the tools' bindings (the SDK profile). */\n families?: () => Readonly<Record<string, string>>;\n /** The fields each type hides from this key, for a tool's masked output (the SDK profile). */\n fieldAccess?: () => Readonly<Record<string, Readonly<Record<string, string>>>> | null;\n /** The binding the space serves for a tool, by its name (the SDK profile). */\n bindings?: (tool: string) => RawBinding | null;\n}\n\nconst turns = (): ReturnType<typeof store<TurnFrame>> => store<TurnFrame>(\"niadra_turn\");\nconst callStore = (): ReturnType<typeof store<CallCapture>> => store<CallCapture>(\"niadra_call\");\n\n/** The turn open in this async context, if any. */\nexport function currentTurn(): TurnFrame | undefined {\n return turns()?.getStore();\n}\n\n/** The call in progress in this async context, if any. */\nexport function currentCall(): CallCapture | undefined {\n return callStore()?.getStore();\n}\n\n/** `value` as JSON text, now: the copy a record keeps. Throws when it has no JSON form at all. */\nexport function snapshot(value: unknown): string {\n const text = JSON.stringify(value, (_key, v: unknown) => (typeof v === \"bigint\" ? v.toString() : v)) as string | undefined;\n return text ?? \"null\";\n}\n\nfunction statusOf(error: unknown): CallStatus {\n const name = error instanceof Error ? error.name : \"\";\n if (name === \"AbortError\") return \"cancelled\";\n if (name === \"TimeoutError\" || name === \"NiadraTimeoutError\") return \"timeout\";\n return \"error\";\n}\n\n/**\n * One tool or model call of a turn, open until `result()` or `failed()`. `run(fn)` makes it the call in\n * progress for `fn`, so calls made inside it name it as their parent, and a throw fails it.\n */\nexport class CallCapture {\n readonly callId: string;\n /** In a replay: how the call answers (`replay/playback.ts`). */\n played: Played | null = null;\n /** What the call's result honored of the constraints block, when the tool has a binding. */\n measure: ((result: unknown) => Record<string, unknown> | null) | null = null;\n private readonly started = performance.now();\n private finished = false;\n\n constructor(\n readonly frame: TurnFrame,\n readonly entry: CallEntry,\n ) {\n this.callId = entry.call_id;\n }\n\n get done(): boolean {\n return this.finished;\n }\n\n /**\n * The call returned `value`, as the model saw it. `ui` is the form the interface got, when it differs.\n * `observations` are the objects the result showed, each `{ref, fields, provenance}`.\n */\n result(\n value: unknown,\n options: { ui?: unknown; observations?: readonly Observation[]; costUnits?: Record<string, number>; cacheHit?: boolean } = {},\n ): void {\n if (this.finished) return;\n const extra: Record<string, unknown> = { result_model: this.frame.blob(value) };\n if (this.measure !== null) {\n try {\n extra.applied = this.measure(value);\n } catch {\n this.frame.incomplete();\n }\n }\n if (options.ui !== undefined) extra.result_ui = this.frame.blob(options.ui);\n if (options.observations?.length) extra.observations = options.observations.map((o) => ({ ...o }));\n if (options.costUnits) extra.cost_units = { ...options.costUnits };\n if (options.cacheHit !== undefined) extra.cache_hit = options.cacheHit;\n this.finish(\"ok\", extra);\n }\n\n /** The call ended without a result: a throw, or `timeout` or `cancelled`. */\n failed(error: unknown = \"error\"): void {\n if (this.finished) return;\n const status = typeof error === \"string\" ? (error as CallStatus) : statusOf(error);\n this.finish(status, {});\n if (status === \"error\") this.frame.flag(\"error\");\n }\n\n /** Runs `fn` as the call in progress. */\n run<R>(fn: () => R): R {\n const calls = callStore();\n return calls ? calls.run(this, fn) : fn();\n }\n\n private finish(status: CallStatus, extra: Record<string, unknown>): void {\n this.finished = true;\n for (const [key, value] of Object.entries(extra)) if (value !== undefined && value !== null) this.entry[key] = value;\n this.entry.status = status;\n this.entry.latency_ms = Math.round(performance.now() - this.started);\n }\n}\n\nexport interface FrameOptions {\n agent: string;\n role?: string | null;\n kind?: TurnKind;\n conversationId?: string | null;\n taskId?: string | null;\n pins?: TurnPins;\n adapter?: string | null;\n turnId?: string;\n parent?: TurnFrame;\n}\n\n/**\n * The record of one turn while it runs. `close()` ends it and hands it to the turn queue; nothing else\n * happens on the agent's path. Every method never throws for a failure of the capture itself, and does\n * nothing once the frame is closed.\n */\nexport class TurnFrame {\n readonly turnId: string;\n readonly parentTurnId: string | null;\n readonly agent: string;\n readonly role: string | null;\n readonly kind: TurnKind;\n readonly conversationId: string | null;\n readonly taskId: string | null;\n readonly pins: TurnPins & Record<string, unknown>;\n readonly adapter: string | null;\n readonly startedAt = new Date();\n endedAt: Date | null = null;\n latencyMs: number | null = null;\n readonly calls: CallEntry[] = [];\n readonly blobs = new Map<string, Blob>();\n readonly reads: Record<string, unknown>[] = [];\n readonly said: Said[] = [];\n readonly claims: ClaimRecord[] = [];\n /** What the person was shown or did in the turn, as the interaction spec writes it. */\n readonly interactions: Record<string, unknown>[] = [];\n readonly coordination: { decision_id: string; decision: string }[] = [];\n readonly effects = new Map<string, string>();\n readonly eventKeys: string[] = [];\n readonly flags = new Set<Flag>();\n /** Values the turn's reads placed in the turn block, for the claim check: each with its freshness. */\n readonly state: StateValue[] = [];\n completeness: \"complete\" | \"partial\" | \"incomplete\" = \"complete\";\n handoffId: string | null = null;\n /** The content mode this turn must leave in, when the server refused the recorder's. */\n mode: ContentMode | null = null;\n /** The constraints block the turn read last: what its tools' calls are measured against. */\n constraints: ConstraintsBlock | null = null;\n /**\n * Set in a replay: recorded answers for the tools, and where what the turn says goes. A sub-turn of a\n * replayed turn (a framework's run inside it) is replayed with it, and never sent.\n */\n playback: Playback | null = null;\n closed = false;\n private readonly guardedTexts = new Set<string>();\n private readonly adoptable: CallCapture[] = [];\n private readonly counters = { b: 0, k: 0, m: 0 };\n private readonly started = performance.now();\n\n constructor(\n private readonly recorder: Submit | null,\n options: FrameOptions,\n ) {\n const parent = options.parent;\n this.turnId = options.turnId ?? uuidv7();\n this.parentTurnId = parent?.turnId ?? null;\n this.agent = options.agent;\n this.role = options.role ?? null;\n this.kind = options.kind ?? \"message\";\n this.conversationId = options.conversationId ?? parent?.conversationId ?? null;\n this.taskId = options.taskId ?? (parent && !options.conversationId ? parent.taskId : null);\n this.pins = { ...(options.pins ?? {}) };\n this.adapter = options.adapter ?? null;\n this.playback = parent?.playback ?? null;\n }\n\n /** Whether the frame keeps what the turn says for the claim check on the sender. */\n get recording(): boolean {\n return this.recorder !== null;\n }\n\n // Capture\n\n /**\n * Opens a tool call, copying its arguments now. `callId` is the provider's id when there is one; otherwise\n * the frame names it `k1`, `k2`, ... Call the capture's `result()` or `failed()` when it ends.\n */\n toolCall(\n name: string,\n args?: unknown,\n options: { callId?: string | null; attempt?: number; synthetic?: boolean; cacheHit?: boolean; effectKey?: string; adoptable?: boolean } = {},\n ): CallCapture {\n const entry: CallEntry = {\n call_id: options.callId ?? `k${++this.counters.k}`,\n kind: \"tool\",\n name,\n attempt: options.attempt ?? 1,\n synthetic: options.synthetic ?? false,\n cache_hit: options.cacheHit ?? false,\n };\n if (options.effectKey !== undefined) entry.effect_key = options.effectKey;\n const parent = currentCall();\n if (parent?.frame === this) entry.parent_call_id = parent.callId;\n if (args !== undefined) entry.args = this.blob(args);\n if (options.synthetic) this.flag(\"synthetic\");\n const call = this.add(entry);\n if (options.adoptable) this.adoptable.push(call);\n return call;\n }\n\n /**\n * The open call of `name` an adapter recorded from its framework's callbacks, taken over by the `tool()`\n * wrapper running inside it, so the call is recorded once, with the wrapper's arguments.\n */\n adopt(name: string, args: unknown): CallCapture | undefined {\n for (let i = 0; i < this.adoptable.length; i++) {\n const call = this.adoptable[i];\n if (call === undefined || call.done || call.entry.name !== name) continue;\n this.adoptable.splice(i, 1);\n const before = call.entry.args;\n if (typeof before === \"string\") this.blobs.delete(before);\n const key = args === undefined ? undefined : this.blob(args);\n if (key === undefined) delete call.entry.args;\n else call.entry.args = key;\n return call;\n }\n return undefined;\n }\n\n /**\n * Records a model call that already ended, with its tokens when the provider reported them. The first\n * model named becomes the turn's `model` pin unless the build set one.\n */\n modelCall(\n model: string | null | undefined,\n options: { tokensIn?: number | null; tokensOut?: number | null; tokensCached?: number; latencyMs?: number; callId?: string; status?: CallStatus } = {},\n ): void {\n const entry: CallEntry = { call_id: options.callId ?? `m${++this.counters.m}`, kind: \"model\", status: options.status ?? \"ok\" };\n if (model) {\n entry.name = model;\n this.pinModel(model);\n }\n if (options.tokensIn != null && options.tokensOut != null) {\n entry.tokens = { in: options.tokensIn, cached: options.tokensCached ?? 0, out: options.tokensOut };\n }\n if (options.latencyMs !== undefined) entry.latency_ms = options.latencyMs;\n const parent = currentCall();\n if (parent?.frame === this) entry.parent_call_id = parent.callId;\n this.add(entry);\n }\n\n /** The SDK profile of the client that opened this turn, as far as the tools need it. */\n get profile(): Pick<Submit, \"families\" | \"fieldAccess\" | \"bindings\"> {\n return this.recorder ?? {};\n }\n\n /** The model the turn called, as its `model` pin, unless the build named one. */\n pinModel(model: string): void {\n this.pins.model ??= model;\n }\n\n /**\n * A read the turn made from Niadra, by its version: the pack by ETag, a block by its version. `value` is what\n * the read served, kept as a blob of the record so a replay and the tool counterfactual have it.\n */\n read(surface: string, options: { etag?: string | null; version?: string | null; receiptId?: string | null; value?: unknown } = {}): void {\n if (this.closed) return;\n const entry: Record<string, unknown> = { surface };\n if (options.etag) entry.etag = options.etag;\n if (options.version) entry.version = options.version;\n if (options.receiptId) entry.receipt_id = options.receiptId;\n if (options.value !== undefined && options.value !== null) {\n const key = this.blob(options.value);\n if (key !== undefined) entry.blob = key;\n }\n this.reads.push(entry);\n }\n\n /**\n * What the person was shown or did in the turn, as the interaction spec writes it: a `presented` list (with its\n * `exposure_id` and positions), a `seen`, an `engaged` item of it, a preference. A replay and the tool\n * counterfactual read where the person engaged from here.\n */\n interact(item: Record<string, unknown>): void {\n if (this.closed) return;\n this.interactions.push(JSON.parse(JSON.stringify(item)) as Record<string, unknown>);\n }\n\n /** The pack this turn read: its compiler's version and hash become the turn's `niadra` pins. */\n pack(compiler: string | null | undefined, packHash: string | null | undefined): void {\n const pins: Record<string, string> = {};\n if (compiler) pins.compiler = compiler;\n if (packHash) pins.pack_hash = packHash;\n if (Object.keys(pins).length > 0) this.pins.niadra = pins;\n }\n\n /** Fields of objects a read served the turn, kept for the claim check. */\n observeState(values: readonly StateValue[]): void {\n if (!this.closed) this.state.push(...values);\n }\n\n /**\n * Something the turn emitted: `eventKey` names the event `track()` sent for it (the text itself is never\n * repeated in the record), and the text is kept for the claim check the sender runs.\n */\n say(text: string, options: { eventKey?: string | null; context?: string; immutable?: boolean; agent?: string | null } = {}): void {\n if (this.closed) return;\n if (options.eventKey) this.eventKeys.push(options.eventKey);\n if (this.recorder !== null && !this.guardedTexts.has(text)) {\n this.said.push({ text, context: options.context ?? \"chat\", immutable: options.immutable ?? false, agent: options.agent ?? this.agent });\n }\n }\n\n /** A coordination decision the turn acted on. */\n coordinate(decisionId: string, decision: string): void {\n if (!this.closed) this.coordination.push({ decision_id: decisionId, decision });\n }\n\n /** What the turn saw of an effect: its last state by key. */\n effect(key: string, state: string): void {\n if (!this.closed) this.effects.set(key, state);\n }\n\n /** The claim guard checked `text` and recorded its claims: saying it later adds none. */\n guarded(text: string): void {\n this.guardedTexts.add(text);\n }\n\n addClaims(records: readonly ClaimRecord[]): void {\n this.claims.push(...records);\n }\n\n /** Marks the turn: a flagged turn keeps its values longest in the queue and goes to the kept tier. */\n flag(name: Flag): void {\n this.flags.add(name);\n }\n\n /** The capture failed during the turn: its record says so. */\n incomplete(): void {\n this.completeness = \"incomplete\";\n this.flags.add(\"incomplete\");\n }\n\n // Lifecycle\n\n /** Runs `fn` with this turn current; the turn stays open. */\n run<R>(fn: () => R): R {\n const frames = turns();\n return frames ? frames.run(this, fn) : fn();\n }\n\n /** Makes this the current turn of the running async context, for adapters that open a turn in one callback. */\n enter(): this {\n turns()?.enterWith(this);\n return this;\n }\n\n /** Ends the turn and hands its record to the queue. Later calls do nothing. */\n close(error?: unknown): void {\n if (this.closed) return;\n this.closed = true;\n this.endedAt = new Date();\n this.latencyMs = Math.round(performance.now() - this.started);\n if (error !== undefined && error !== null) this.flags.add(\"error\");\n for (const entry of this.calls) entry.status ??= \"cancelled\"; // a call the turn left open never returned in it\n if (this.recorder !== null && this.playback === null) this.recorder.submit(this);\n }\n\n // For the queue and the sender\n\n /** The value of a blob the frame still holds, read back from its copy; `undefined` otherwise. */\n valueOf(key: unknown): unknown {\n const data = typeof key === \"string\" ? this.blobs.get(key)?.data : null;\n if (data == null) return undefined;\n try {\n return JSON.parse(data) as unknown;\n } catch {\n return undefined;\n }\n }\n\n get flagged(): boolean {\n return this.flags.size > 0;\n }\n\n /** Bytes the queue counts for this turn: its blobs' values and an estimate of the frame. */\n get size(): number {\n let values = 0;\n for (const blob of this.blobs.values()) if (blob.data !== null) values += blob.size;\n return this.sizeWithoutValues + values;\n }\n\n get sizeWithoutValues(): number {\n return FRAME_BYTES + CALL_BYTES * this.calls.length;\n }\n\n /**\n * Drops the values of the blobs to make room. A blob whose digest is known stays as its digest; the\n * others leave the record, with the call fields that named them. Returns the bytes freed.\n */\n dropBlobs(): number {\n let freed = 0;\n for (const [key, blob] of [...this.blobs]) {\n if (blob.data === null) continue;\n freed += blob.size;\n blob.data = null;\n if (blob.sha256 === undefined) {\n this.blobs.delete(key);\n for (const entry of this.calls) {\n if (entry.args === key) delete entry.args;\n if (entry.result_model === key) delete entry.result_model;\n if (entry.result_ui === key) delete entry.result_ui;\n }\n }\n }\n if (freed > 0 && this.completeness === \"complete\") this.completeness = \"partial\";\n return freed;\n }\n\n /** Copies `value` as a blob of the record; `undefined` when it has no copy, and the turn says so. */\n blob(value: unknown): string | undefined {\n let data: string;\n try {\n data = snapshot(value);\n } catch {\n this.incomplete();\n return undefined;\n }\n const key = `b:${++this.counters.b}`;\n this.blobs.set(key, { data, size: data.length });\n return key;\n }\n\n private add(entry: CallEntry): CallCapture {\n if (!this.closed) this.calls.push(entry);\n return new CallCapture(this, entry);\n }\n}\n","/**\n * Field access at the tool's output (`tool(..., { maskOutput: true })`): a field the calling key may not read\n * never reaches the model.\n *\n * The SDK profile says, for each type, the fields this key may not read (`field_access`: `mask` or `deny`).\n * After the tool returns, the result the model gets loses every `deny` field and has every `mask` field's value\n * replaced with `[masked]`, wherever the field appears in it, for the types of the objects the result showed (its\n * `provenance`; every declared type when the tool has none).\n *\n * When Niadra does not answer, the last profile read keeps applying. With no profile ever read, the result\n * passes as it is, unless the tool says `onUnknown: \"block\"`: then the model gets only a marker that the result\n * was withheld, for a company that needs the check to fail closed.\n */\n\nexport const MASKED = \"[masked]\";\nexport const WITHHELD = \"[withheld: the fields this agent may read are not known yet]\";\n\n/** The fields each type hides from this key, by type: `null` while no profile was ever read. */\nexport type Access = () => Readonly<Record<string, Readonly<Record<string, string>>>> | null;\nexport type OnUnknown = \"pass\" | \"block\";\n\n/** `result` as the model may get it. */\nexport function protect(result: unknown, access: ReturnType<Access>, types: readonly string[] | null, onUnknown: OnUnknown): unknown {\n if (access === null) return onUnknown === \"block\" ? WITHHELD : result;\n const rules = new Map<string, string>();\n for (const name of types ?? Object.keys(access)) {\n for (const [field, effect] of Object.entries(access[name] ?? {})) rules.set(field, effect === \"deny\" || rules.get(field) === \"deny\" ? \"deny\" : effect);\n }\n if (rules.size === 0) return result;\n if (typeof result === \"string\" && /^\\s*[[{]/.test(result)) {\n try {\n return JSON.stringify(walk(JSON.parse(result) as unknown, rules));\n } catch {\n return result;\n }\n }\n return walk(result, rules);\n}\n\nfunction walk(value: unknown, rules: ReadonlyMap<string, string>): unknown {\n if (Array.isArray(value)) return value.map((v) => walk(v, rules));\n if (typeof value !== \"object\" || value === null) return value;\n const out: Record<string, unknown> = {};\n for (const [key, v] of Object.entries(value)) {\n const effect = rules.get(key);\n if (effect === \"deny\") continue;\n out[key] = effect === \"mask\" ? MASKED : walk(v, rules);\n }\n return out;\n}\n","/**\n * `tool()`: records each call of a function tool in the turn it runs in, whatever the framework.\n *\n * ```ts\n * const quote = niadra.tool(\"quote\", async (plan: string) => pricing.quote(plan), {\n * provenance: (r) => [{ ref: `health_quote:op:${r.id}`, fields: r.prices }],\n * });\n * ```\n *\n * Inside a turn, a call records its arguments when it starts (the single argument, or the list of them),\n * its result or its failure when it ends, its latency, and the call it was made in. `provenance` turns a\n * result into the objects it showed, each `{ref, fields, provenance}`: without provenance an observation is\n * for display only. `ui` gives the form of the result the interface got, when it differs from the one the\n * model saw. Outside a turn, the tool runs untouched and nothing is recorded. The recording never fails the\n * tool: a provenance function that throws marks the turn incomplete, and the tool's own result and errors\n * pass through unchanged. An async generator is recorded piece by piece, and its result is the list of\n * pieces once it is consumed.\n *\n * When the space binds the tool (its `tool-bindings` document, which the SDK profile serves this source by the\n * tool's name), a call in a turn that read the constraints block records what it did with the block: the hard\n * constraints its arguments sent, and over the objects its result shows, how many were checked, broke one, or\n * lacked the field. Nothing is changed. A binding lives in the space's configuration, never in code.\n *\n * With `maskOutput: true`, the fields the key may not read never reach the model (`capture/mask.ts`); the record\n * keeps what the model saw. Left unset, the binding's `capabilities.mask_output` decides.\n *\n * In a replay (`replay/`) the call answers from the record when its arguments match a recorded call of the\n * tool; otherwise it runs only when `dryRun: true` says running it again is safe, and answers `undefined` (a\n * divergence) when not.\n */\n\nimport { parseBinding, relaxed, resultItems } from \"../constraints/binding.js\";\nimport type { RawBinding } from \"../constraints/binding.js\";\nimport { honored, render } from \"../constraints/render.js\";\nimport type { CallCapture, Observation, TurnFrame } from \"./frame.js\";\nimport { currentTurn } from \"./frame.js\";\nimport { protect } from \"./mask.js\";\nimport type { Access, OnUnknown } from \"./mask.js\";\n\nexport interface ToolOptions<A extends unknown[], R> {\n /** The objects a result showed, each `{ref, fields, provenance}`. */\n provenance?: (result: Awaited<R>) => Observation | readonly Observation[] | null | undefined;\n /** The form of the result the interface got, when it differs from the model's. */\n ui?: (result: Awaited<R>) => unknown;\n /** What the record keeps as the arguments; by default the single argument, or the list of them. */\n args?: (...args: A) => unknown;\n /** A replay may run the tool for real when the record has no answer for it. */\n dryRun?: boolean;\n /** The provider's id of the call, when the framework passes it to the tool. */\n callId?: (...args: A) => string | null | undefined;\n /** The turn to record in when the async context does not carry one (a framework that runs tools elsewhere). */\n frame?: () => TurnFrame | null | undefined;\n /** The bindings the SDK profile serves, by tool name; by default the client's (`niadra.tool`) or the turn's. */\n served?: (tool: string) => RawBinding | null;\n /** Keeps the fields this key may not read from the model; left unset, the binding's capability decides. */\n maskOutput?: boolean;\n /** With no profile ever read: `pass` (the default) lets the result through, `block` withholds it. */\n onUnknown?: OnUnknown;\n /** The fields each type hides; by default the SDK profile of the client (`niadra.tool`) or of the turn. */\n access?: Access;\n}\n\n/** What `tool()` knows of the function it wraps, for the runners that call it again. */\nexport interface RecordedTool {\n name: string;\n dryRun: boolean;\n provenance: ((result: never) => Observation | readonly Observation[] | null | undefined) | null;\n}\n\nconst RECORDED = Symbol.for(\"niadra.tool\");\n\n/** The `tool()` of `fn`, if it is one. */\nexport function recordedTool(fn: unknown): RecordedTool | null {\n return typeof fn === \"function\" ? ((fn as unknown as Record<symbol, RecordedTool | undefined>)[RECORDED] ?? null) : null;\n}\n\nconst isAsyncFunction = (fn: unknown): boolean => Object.prototype.toString.call(fn) === \"[object AsyncFunction]\";\n\nfunction isAsyncIterator(value: unknown): value is AsyncGenerator {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { next?: unknown }).next === \"function\" &&\n Symbol.asyncIterator in value\n );\n}\n\nfunction found(frame: (() => TurnFrame | null | undefined) | undefined): TurnFrame | undefined {\n try {\n return frame?.() ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction thenable(value: unknown): value is PromiseLike<unknown> {\n return typeof value === \"object\" && value !== null && typeof (value as { then?: unknown }).then === \"function\";\n}\n\n/** Records the calls of `fn` as the tool `name`. See the module. */\nexport function tool<A extends unknown[], R>(\n name: string,\n fn: (...args: A) => R,\n options: ToolOptions<A, R> = {},\n): (...args: A) => R {\n const isAsync = isAsyncFunction(fn);\n\n /** The binding the SDK profile serves for the tool's name. */\n function bindingOf(frame: TurnFrame | undefined): RawBinding | null {\n return (options.served ?? frame?.profile.bindings)?.(name) ?? null;\n }\n\n /** Whether the output is masked: `maskOutput` when the code says it, else the binding's capability. */\n function masks(frame: TurnFrame | undefined): boolean {\n return options.maskOutput ?? bindingOf(frame)?.capabilities?.mask_output ?? false;\n }\n\n /** The result as the model may get it. */\n function shield(result: unknown, frame: TurnFrame | undefined): unknown {\n if (!masks(frame)) return result;\n const access = options.access ?? frame?.profile.fieldAccess ?? ((): null => null);\n return protect(result, access(), typesOf(result), options.onUnknown ?? \"pass\");\n }\n\n function typesOf(result: unknown): string[] | null {\n if (!options.provenance) return null;\n try {\n const found = options.provenance(result as Awaited<R>);\n const items = found == null ? [] : Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.map((o) => o.ref.split(\":\")[0] ?? \"\");\n } catch {\n return null;\n }\n }\n\n function end(call: CallCapture, result: unknown, model: unknown = result): void {\n const observations = observed(call, result);\n let shown: unknown;\n if (options.ui) {\n try {\n shown = options.ui(result as Awaited<R>);\n } catch {\n call.frame.incomplete();\n }\n }\n call.result(model, { ui: shown, observations });\n }\n\n function observed(call: CallCapture, result: unknown): Observation[] {\n if (!options.provenance) return [];\n try {\n const found = options.provenance(result as Awaited<R>);\n if (found == null) return [];\n const items = Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.filter((o) => typeof o.ref === \"string\" && typeof o.fields === \"object\");\n } catch {\n call.frame.incomplete();\n return [];\n }\n }\n\n async function* pieces(call: CallCapture, source: AsyncGenerator): AsyncGenerator {\n const kept: unknown[] = [];\n try {\n for await (const piece of source) {\n const shown = shield(piece, call.frame);\n kept.push(shown);\n yield shown;\n }\n } catch (error) {\n call.failed(error);\n throw error;\n }\n end(call, kept);\n }\n\n const wrapped = function (this: unknown, ...args: A): R {\n const frame = currentTurn() ?? found(options.frame);\n if (frame === undefined || frame.closed) {\n if (!masks(frame)) return fn.apply(this, args);\n const out = fn.apply(this, args);\n if (isAsyncIterator(out)) return maskedPieces(out, frame) as R;\n return (thenable(out) ? Promise.resolve(out).then((v) => shield(v, frame)) : shield(out, frame)) as R;\n }\n let recorded: unknown;\n let callId: string | null | undefined;\n try {\n recorded = options.args ? options.args(...args) : args.length === 1 ? args[0] : args;\n callId = options.callId?.(...args);\n } catch {\n recorded = args;\n }\n const call = frame.adopt(name, recorded) ?? frame.toolCall(name, recorded, typeof callId === \"string\" && callId ? { callId } : {});\n const binding = bindingOf(frame);\n if (binding !== null && frame.constraints !== null) call.measure = measure(frame, binding, recorded);\n if (frame.playback !== null) call.played = frame.playback.answer(name, recorded, options.dryRun ?? false);\n if (call.played !== null && !call.played.live) {\n const value = call.played.value;\n end(call, value);\n return (isAsync ? Promise.resolve(value) : value) as R;\n }\n let result: R;\n try {\n result = call.run(() => fn.apply(this, args));\n } catch (error) {\n call.failed(error);\n throw error;\n }\n if (isAsyncIterator(result)) return pieces(call, result) as R;\n if (thenable(result)) {\n return Promise.resolve(result).then(\n (value) => {\n const shown = shield(value, frame);\n end(call, value, shown);\n return shown;\n },\n (error: unknown) => {\n call.failed(error);\n throw error;\n },\n ) as R;\n }\n const shown = shield(result, frame);\n end(call, result, shown);\n return shown as R;\n };\n\n async function* maskedPieces(source: AsyncGenerator, frame: TurnFrame | undefined): AsyncGenerator {\n for await (const piece of source) yield shield(piece, frame);\n }\n\n Object.defineProperty(wrapped, \"name\", { value: fn.name || name });\n const marker: RecordedTool = {\n name,\n dryRun: options.dryRun ?? false,\n provenance: (options.provenance ?? null),\n };\n Object.defineProperty(wrapped, RECORDED, { value: marker });\n return wrapped;\n}\n\n/** How the call's result honored the block its arguments were rendered against; `null` when it does not apply. */\nfunction measure(frame: TurnFrame, raw: RawBinding, args: unknown): ((result: unknown) => Record<string, unknown> | null) | null {\n const block = frame.constraints;\n if (block === null) return null;\n const given = typeof args === \"object\" && args !== null && !Array.isArray(args) ? (args as Record<string, unknown>) : {};\n const rendering = render(block, parseBinding(raw, frame.profile.families?.() ?? {}), { args: given });\n if (!rendering.applies) return null;\n return (result) => {\n const seen = honored(block, rendering.hardSent, resultItems(raw, result));\n return {\n constraints: block.version,\n hard_sent: [...rendering.hardSent],\n results_checked: seen.resultsChecked,\n violations: seen.violations,\n unverifiable: seen.unverifiable,\n ...(relaxed(raw, result) ? { relaxed: \"declared\" } : {}),\n };\n };\n}\n","/**\n * What a replayed turn answers with: the recorded tool results, matched by the digest of their arguments, the\n * pack of the time, and where what the agent says and declares goes instead of Niadra (the replay spec, 6).\n */\n\nimport { canonicalJson, jsonDigest } from \"../digest.js\";\nimport { sha256Hex } from \"../sha256.js\";\nimport { currentTurn, snapshot } from \"../capture/frame.js\";\nimport type { TurnFrame } from \"../capture/frame.js\";\nimport type { CheckRequest, CheckResult } from \"../types/coordination.js\";\nimport type { ContextResponse } from \"../types/context.js\";\nimport { uuidv7 } from \"../ids.js\";\n\nexport type Mode = \"hermetic_turn\" | \"hermetic_conversation\" | \"era_memory\";\n\n/** A recorded value that could not be read, or is not the value its digest names. */\nexport class BlobError extends Error {\n override readonly name = \"BlobError\";\n}\n\n/** How one tool call answers: `live` runs the tool; otherwise `value` is the answer, recorded or empty. */\nexport interface Played {\n live: boolean;\n value: unknown;\n recorded: boolean;\n}\n\ninterface Recorded {\n argsHash: string | null;\n value: unknown;\n used: boolean;\n}\n\n/** One execution's answers and what it collected. */\nexport class Playback {\n divergent = 0;\n readonly said: string[] = [];\n /** Effect keys the agent declared done, and how many times. */\n readonly done = new Map<string, number>();\n handoff = false;\n /**\n * The working state in this execution, by scope and agent: what the recorded turn read first, then what the\n * replayed agent wrote. It stays here.\n */\n readonly states = new Map<string, { body: Record<string, unknown>; version: number }>();\n\n constructor(\n private readonly calls: Map<string, Recorded[]>,\n readonly mode: Mode = \"hermetic_turn\",\n readonly context: ContextResponse | null = null,\n ) {}\n\n /** An item the replayed agent tried to send: it never leaves, and a handoff is noted. */\n muted(item: unknown): true {\n if ((item as { type?: unknown } | null)?.type === \"handoff\") this.handoff = true;\n return true;\n }\n\n /** What the replayed agent said: the text its assertions read, and its claims. */\n say(frame: TurnFrame, text: string): void {\n this.said.push(text);\n frame.said.push({ text, context: \"chat\", immutable: false, agent: frame.agent });\n }\n\n /** A declaration the replayed agent made: kept here, never sent. */\n declared(kind: string, detail: Record<string, unknown>): void {\n if (kind === \"effect\" && detail.state === \"done\") {\n const key = String(detail.effect_key);\n this.done.set(key, (this.done.get(key) ?? 0) + 1);\n }\n if (kind === \"handoff\") this.handoff = true;\n }\n\n /** A check the replayed agent made, answered here: an effect it already declared done is denied, anything else goes. */\n checked(request: CheckRequest): CheckResult {\n const done = request.effect_key != null && (this.done.get(request.effect_key) ?? 0) > 0;\n const result: CheckResult = { decision: done ? \"deny\" : \"allow\", decision_id: uuidv7(), reasons: done ? [\"effect_done\"] : [], valid_for_s: 0 };\n if (request.effect_key != null) result.effect = { state: done ? \"done\" : \"none\", attempt: 1 };\n return result;\n }\n\n /**\n * A recorded call of `tool` with the same arguments, the recorded ones of one tool taken in order; else the\n * tool runs when it is safe to run dry (in `era_memory`, first), or answers empty.\n */\n answer(tool: string, args: unknown, dryRun: boolean): Played {\n if (this.mode === \"era_memory\" && dryRun) return { live: true, value: undefined, recorded: false };\n const wanted = this.hash(args);\n for (const recorded of this.calls.get(tool) ?? []) {\n if (!recorded.used && recorded.argsHash === wanted) {\n recorded.used = true;\n return { live: false, value: recorded.value, recorded: true };\n }\n }\n this.divergent++;\n return { live: dryRun, value: undefined, recorded: false };\n }\n\n /** The digest of the arguments as a record names them: SHA-256 over their canonical JSON, computed now. */\n private hash(args: unknown): string | null {\n try {\n const canonical = canonicalJson(JSON.parse(snapshot(args)) as unknown);\n return `sha256:${sha256Hex(new TextEncoder().encode(canonical))}`;\n } catch {\n return null;\n }\n }\n}\n\n/** The playback of the turn replayed in this async context, if any. */\nexport function replaying(): Playback | null {\n return currentTurn()?.playback ?? null;\n}\n\n/**\n * The answers of a recorded turn. Every value used is fetched (by pointer, inside the company's boundary) and\n * must match its digest; rejects with `BlobError` otherwise.\n */\nexport async function playback(\n record: Record<string, unknown>,\n read: ((pointer: string) => Promise<string>) | null,\n mode: Mode = \"hermetic_turn\",\n): Promise<Playback> {\n const blobs = (record.blobs ?? {}) as Record<string, Record<string, unknown>>;\n const values = new Map<string, unknown>();\n const value = async (key: unknown): Promise<unknown> => {\n const blob = typeof key === \"string\" ? blobs[key] : undefined;\n if (typeof key !== \"string\" || blob === undefined) return undefined;\n if (!values.has(key)) values.set(key, await materialized(blob, read));\n return values.get(key);\n };\n const calls = new Map<string, Recorded[]>();\n for (const call of (record.calls ?? []) as Record<string, unknown>[]) {\n if (call.kind !== \"tool\" || (call.status ?? \"ok\") !== \"ok\" || !(\"result_model\" in call)) continue;\n const recorded: Recorded = { argsHash: (call.args_hash as string | undefined) ?? null, value: await value(call.result_model), used: false };\n const name = String(call.name);\n calls.set(name, [...(calls.get(name) ?? []), recorded]);\n }\n const pack = ((record.reads ?? []) as Record<string, unknown>[]).find((r) => r.surface === \"pack\");\n let context: ContextResponse | null = null;\n if (pack !== undefined && typeof pack.blob === \"string\" && pack.blob in blobs) {\n const found = await value(pack.blob);\n if (typeof found === \"object\" && found !== null) context = found as ContextResponse;\n }\n const played = new Playback(calls, mode, context);\n for (const read of (record.reads ?? []) as Record<string, unknown>[]) {\n if (read.surface !== \"agent_state\" || typeof read.blob !== \"string\") continue;\n const held = (await value(read.blob)) as { scope?: { kind?: unknown; id?: unknown }; agent?: unknown; version?: unknown; body?: unknown } | undefined;\n if (typeof held !== \"object\") continue;\n const id = JSON.stringify([String(held.scope?.kind), String(held.scope?.id), String(held.agent)]);\n if (!played.states.has(id)) played.states.set(id, { body: { ...((held.body ?? {}) as Record<string, unknown>) }, version: Number(held.version ?? 0) });\n }\n return played;\n}\n\nexport async function materialized(blob: Record<string, unknown>, read: ((pointer: string) => Promise<string>) | null): Promise<unknown> {\n let found: unknown;\n if (\"content\" in blob) found = blob.content;\n else if (typeof blob.pointer === \"string\") {\n if (read === null) throw new BlobError(\"a value kept by pointer needs a reader: niadra.content.register(), or read\");\n try {\n found = JSON.parse(await read(blob.pointer)) as unknown;\n } catch (error) {\n throw new BlobError(\"a value kept by pointer could not be read\", { cause: error });\n }\n } else throw new BlobError(\"the record keeps only the digest of a value the replay needs\");\n if ((await jsonDigest(found)).sha256 !== blob.sha256) throw new BlobError(\"a recorded value does not match its digest\");\n return found;\n}\n","import { NiadraValidationError } from \"./errors.js\";\nimport { includeText } from \"./constraints/text.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport { toObjectRef } from \"./handles.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type {\n ContextFormat,\n ContextPack,\n ContextRequest,\n ContextResponse,\n CoordinationBlock,\n Include,\n LiveTurn,\n PrefetchRequest,\n TargetModel,\n} from \"./types/context.js\";\nimport type { ConstraintsBlock } from \"./types/signals.js\";\nimport type { StateView } from \"./types/state.js\";\nimport type { Verification, View } from \"./types/vocabulary.js\";\n\n/** Arguments of `context()`. Pass exactly one of `subject` or `object`. */\nexport interface ContextParams {\n /** The customer, by any handle the server knows. */\n subject?: Handle;\n /** A business object, such as an invoice, when the task is about the object rather than a person. */\n object?: ObjectRef | string;\n /** The account or partner the person acts for. Requires an active link between the two. */\n about?: Handle;\n /** Defaults to `chat`. */\n view?: View;\n /**\n * The level proven in this conversation. The server may answer with a lower effective level\n * when the source's ceiling is lower; see `response.verification`.\n */\n verification?: Verification;\n /** Enables the per-conversation cache and the server's pinning of the pack. */\n conversation_id?: string;\n /** For internal agents: the task plays the role of the conversation. */\n task_id?: string;\n /**\n * Other words than the turn to pick this read's slots by. Up to 2,000 characters. Wins over\n * `turn`, and like it never changes the pack.\n */\n query?: string;\n /**\n * The customer's last turn; a conversation passes it for you. It goes as `query` and the answer\n * adds `slots`, what the turn selected from memory, in `suffix`, while the pack stays the\n * conversation's pinned one (and is cached as without it).\n */\n turn?: string | null;\n /** Ask only for what changed since this source last read the subject. */\n delta?: boolean;\n /** The model that will read the pack, so the server can size it for that model's prompt cache. */\n target?: TargetModel;\n /** `json` also returns the pack as typed sections in `pack` (`context-pack.v1`). Defaults to `text`. */\n format?: ContextFormat;\n /**\n * Adds `why` to each of `pack.slots`, naming the retrieval channels that\n * ranked it, the fused score, the weights version and, for a derived line, the rule behind it.\n * Requires `format: \"json\"`. It changes nothing else: the pinned text, the slots chosen and the\n * receipt are the same bytes with or without it.\n */\n explain?: boolean;\n /**\n * Blocks read in the same round trip: `[\"constraints\"]` returns the subject's constraints block, `[\"state\"]`\n * the state of their objects. Each only where the space turned its feature on; a block the space does not\n * serve is left out and not asked again for a while, and the read goes on. The blocks are cached with the\n * pack, so a read that fails serves the last good ones too.\n */\n include?: Include[];\n}\n\n/** Arguments of `prefetch()`: who the turn is about, as in `context()`, and the turn so far. */\nexport interface PrefetchParams {\n subject?: Handle;\n object?: ObjectRef | string;\n about?: Handle;\n /** Defaults to `voice`, where partial transcripts come from. */\n view?: View;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** The partial transcript of the customer's turn. */\n text: string;\n}\n\n/** Per-call options shared by every read method. */\nexport interface RequestOptions {\n /** Overrides the method's default time budget, in milliseconds. */\n timeout?: number | undefined;\n /** Cancels the wait. A request shared with other callers keeps running for them. */\n signal?: AbortSignal | undefined;\n /** Extra headers, such as a W3C `traceparent`. */\n headers?: Record<string, string> | undefined;\n}\n\nexport interface ContextOptions extends RequestOptions {\n /** Pass `false` to skip the per-conversation cache for this call. */\n cache?: boolean | undefined;\n /** For `conversation.context()` and `task.context()`: blocks read in the same round trip. */\n include?: Include[] | undefined;\n /** For `conversation.context()` and `task.context()`: `json` also returns `pack`. */\n format?: ContextFormat | undefined;\n /**\n * For `conversation.context()` and `task.context()`: adds `why` to each of `pack.slots`.\n * Requires `format: \"json\"`.\n */\n explain?: boolean | undefined;\n}\n\n/**\n * Where a `context()` result came from.\n *\n * - `network`: a response the server just sent (or confirmed unchanged).\n * - `cache`: a pack younger than the cache TTL; no request was made.\n * - `stale`: an older pack returned at once while a background request refreshes it.\n * - `fallback`: the request failed and this is the last good pack for the conversation.\n * - `none`: nothing was available; `text` is empty and `error` says why.\n */\nexport type ContextSource = \"network\" | \"cache\" | \"stale\" | \"fallback\" | \"none\";\n\n/** What `context()` resolves to. Always usable: on failure `text` is an empty string. */\nexport interface ContextResult {\n /** The pack, ready for the system prompt. Empty when there is nothing to inject. */\n text: string;\n /**\n * The parts that change turn by turn and belong at the end of the prompt, after the\n * conversation: the live turns from other channels, this turn's slots (what the customer's last\n * turn selected from memory), the blocks asked for by `include` (the state view, the constraints) and the\n * delta, in that order, as the API places them. Empty when there are none.\n */\n suffix: string;\n /** Named values from the pack, for templates that place them individually. */\n variables: Record<string, string>;\n /** The pack as typed sections, when read with `format: \"json\"`; otherwise `null`. */\n pack: ContextPack | null;\n source: ContextSource;\n /**\n * How long ago Niadra sent or confirmed the pack served, in milliseconds: 0 for an answer just received,\n * growing while a cached pack is served (`cache`, `stale`, or `fallback` with Niadra down), and `null` when\n * there is no pack.\n */\n ageMs: number | null;\n /** The response this result was built from; `null` when `source` is `none`. */\n response: ContextResponse | null;\n /** What went wrong, when `source` is `fallback` or `none`. */\n error: NiadraError | null;\n /** With `include: [\"constraints\"]`: the subject's constraints block. */\n constraints?: ConstraintsBlock | null;\n /** With `include: [\"state\"]`: the state of the subject's objects. */\n state?: StateView | null;\n /** With `include: [\"coordination\"]`: what coordination knows of the subject. */\n coordination?: CoordinationBlock | null;\n}\n\nconst VIEW = /^(voice|chat|brief|full|custom|account|partner|task:[a-z0-9_]{1,40})$/;\nconst MAX_QUERY = 2000;\n\n/** Validates the arguments and builds the wire request, without `known_etag`. */\nexport function buildContextRequest(params: ContextParams): ContextRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n if (params.query !== undefined && params.query.length > MAX_QUERY) {\n throw new NiadraValidationError(`query is longer than ${MAX_QUERY} characters`);\n }\n\n const request: ContextRequest = { view: params.view ?? \"chat\" };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n if (params.query) request.query = params.query;\n if (params.delta) request.delta = true;\n if (params.target) request.target = params.target;\n const format: string = params.format ?? \"text\";\n if (format !== \"text\" && format !== \"json\") throw new NiadraValidationError(\"format is `text` or `json`\");\n if (format === \"json\") request.format = \"json\";\n if (params.explain) {\n if (format !== \"json\") throw new NiadraValidationError('explain requires format: \"json\"');\n request.explain = true;\n }\n if (params.include?.length) request.include = [...new Set(params.include)];\n return request;\n}\n\n/** Validates the arguments of `prefetch()` and builds the wire request. */\nexport function buildPrefetchRequest(params: PrefetchParams): PrefetchRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n const text = params.text.trim();\n if (!text || text.length > MAX_QUERY) throw new NiadraValidationError(`text must be 1 to ${MAX_QUERY} characters`);\n const request: PrefetchRequest = { view: params.view ?? \"voice\", query: text };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n return request;\n}\n\n/** Packs are only cached inside a conversation or task, the unit the server pins them to. */\nexport function cacheScope(request: Pick<ContextRequest, \"conversation_id\" | \"task_id\">): string | null {\n if (request.conversation_id) return `conversation:${request.conversation_id}`;\n if (request.task_id) return `task:${request.task_id}`;\n return null;\n}\n\n/**\n * Every field that changes what the server would compile goes into the key, in a fixed order.\n * `delta` does not: a plain read and a delta read of one conversation get the same pinned\n * bytes, so they share one entry.\n */\nexport function cacheKey(request: ContextRequest): string {\n return JSON.stringify([\n request.subject ?? null,\n request.object ?? null,\n request.about ?? null,\n request.view ?? \"chat\",\n request.verification ?? \"V0\",\n request.conversation_id ?? null,\n request.task_id ?? null,\n request.query ?? null,\n request.target ?? null,\n request.format ?? \"text\",\n request.explain ?? false,\n request.include ?? null,\n ]);\n}\n\n/**\n * Applies a `not_modified` answer to the cached pack: the pinned text and its metadata stay,\n * while the parts outside the pin (live turns, delta, coverage, timing) come from the new answer.\n */\nexport function mergeNotModified(cached: ContextResponse, fresh: ContextResponse): ContextResponse {\n return {\n ...fresh,\n not_modified: false,\n text: cached.text ?? null,\n variables: cached.variables,\n version: cached.version,\n etag: cached.etag,\n manifest_hash: cached.manifest_hash ?? null,\n withheld: cached.withheld,\n cache: cached.cache ?? null,\n pack: cached.pack ?? null,\n // The blocks sit outside the pinned pack: a fresh block wins, and a missing one keeps the cached.\n constraints: fresh.constraints ?? cached.constraints ?? null,\n state: fresh.state ?? cached.state ?? null,\n coordination: fresh.coordination ?? cached.coordination ?? null,\n };\n}\n\nexport function resultFrom(\n response: ContextResponse,\n source: ContextSource,\n error: NiadraError | null = null,\n ageMs: number | null = 0,\n): ContextResult {\n // A conversation in the control group gets an empty pack on purpose; it is not an error.\n const holdout = response.path === \"holdout\";\n const text = holdout ? \"\" : (response.text ?? \"\");\n const pack = holdout ? null : (response.pack ?? null);\n const blocks = {\n constraints: response.constraints ?? null,\n state: response.state ?? null,\n coordination: response.coordination ?? null,\n };\n return { text, suffix: renderSuffix(response), variables: response.variables, pack, source, ageMs, response, error, ...blocks };\n}\n\nexport function emptyResult(error: NiadraError | null): ContextResult {\n return { text: \"\", suffix: \"\", variables: {}, pack: null, source: \"none\", ageMs: null, response: null, error, constraints: null, state: null, coordination: null };\n}\n\n/**\n * Renders the live turns, the slots and the delta for the end of the prompt, in that order. Kept\n * outside the pinned pack so that the prompt prefix stays byte-identical across turns and the\n * model provider's prompt cache keeps hitting. Returns an empty string when there is nothing to add.\n */\nexport function renderSuffix(response: ContextResponse): string {\n if (response.path === \"holdout\") return \"\";\n const included = includeText(response.text, response.state, response.constraints);\n return [renderLive(response), response.slots ?? \"\", included, response.delta ?? \"\"].filter(Boolean).join(\"\\n\\n\");\n}\n\n/**\n * Renders the live turns (recent turns from other channels that the pack has not absorbed\n * yet) as one tagged block, or an empty string when there are none. `complete=\"false\"` tells\n * the model the list may be missing turns because the server could not read all of them.\n */\nexport function renderLive(response: ContextResponse): string {\n if (response.path === \"holdout\" || response.live.length === 0) return \"\";\n const complete = response.live_complete ? \"\" : ' complete=\"false\"';\n const lines = response.live.map(renderLiveTurn).join(\"\\n\");\n return `<live_turns source=\"niadra\"${complete}>\\n${lines}\\n</live_turns>`;\n}\n\nfunction renderLiveTurn(turn: LiveTurn): string {\n return `[${utcSeconds(turn.at)}] ${turn.channel} · ${turn.speaker}: ${turn.text}`;\n}\n\n/** The same timestamp form in every SDK, whatever precision or offset the server sent. */\nfunction utcSeconds(at: string): string {\n const ms = Date.parse(at);\n return Number.isNaN(ms) ? at : `${new Date(ms).toISOString().slice(0, 19)}Z`;\n}\n","/**\n * What every framework adapter shares: the five primitives (context before the model call, the\n * turns, the tools, the verification and the handoff) wired the same way, and fail-open.\n *\n * Nothing here throws into the framework: a failed read gives an empty context, a failed write\n * is logged without content, and the agent keeps working without memory.\n */\n\nimport { recordedTool } from \"../capture/tool.js\";\nimport type { Played } from \"../replay/playback.js\";\nimport type { AgentMemoryParams } from \"../agent-memory.js\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { CallCapture, TurnFrame } from \"../capture/frame.js\";\nimport type { ContextOptions, ContextResult } from \"../context.js\";\nimport { emptyResult } from \"../context.js\";\nimport type { Conversation, TurnOptions } from \"../conversation.js\";\nimport type { Logger } from \"../logger.js\";\nimport type { Task } from \"../task.js\";\nimport type { BoundTools } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { Verification, VerifyMethod } from \"../types/vocabulary.js\";\n\n/** A customer conversation or an internal agent's task. */\nexport type Session = Conversation | Task;\n\n/** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */\nexport type SessionResolver<S extends Session = Session> = S | (() => S | null | undefined);\n\n/** What the framework proved about the person, recorded with `verify()` before the first context read. */\nexport interface Proof {\n method: VerifyMethod;\n level: Verification;\n /** Defaults to the session's subject. */\n handle?: Handle;\n}\n\n/** A proof, or a function that reads it from the framework when the first context is needed. */\nexport type ProofSource =\n | Proof\n | null\n | undefined\n | (() => Proof | null | undefined | PromiseLike<Proof | null | undefined>);\n\n/**\n * The agent's own working notes: `true` puts the block before the customer's context and offers\n * `search_agent_memory`; `{ write: true }` also offers `remember` (for a key with the\n * `agent_memory:write` scope); the other fields go to `agentMemory()`.\n */\nexport type AgentMemoryOption = boolean | (AgentMemoryParams & { write?: boolean });\n\n/** What goes into the prompt for one model call. */\nexport interface Read {\n context: ContextResult;\n /** The agent's own notes, or an empty string. */\n memory: string;\n /** What goes after the instructions: the notes, then the customer's pack. */\n prefix: string;\n /** What goes at the end: live turns, the turn's slots and deltas. */\n suffix: string;\n}\n\n/** A tool as every framework needs it: the name, the text for the model, the JSON Schema and the call. */\ninterface ToolSpec {\n name: string;\n description: string;\n /** JSON Schema of the arguments. None of them names the customer. */\n parameters: Record<string, unknown>;\n /** Runs the call and returns the text for the model. Never rejects in fail-open mode. */\n execute(args: string | Record<string, unknown>): Promise<string>;\n}\n\nconst ATTESTED: Record<string, Verification> = { A: \"V2\", B: \"V1\", C: \"V1\" };\n\n/**\n * The proof a carrier's STIR/SHAKEN attestation gives a phone call: `A` proves V2, `B` and `C`\n * prove V1, anything else proves nothing (`null`). Accepts the bare letter or the forms carriers\n * and platforms send, such as Twilio's `TN-Validation-Passed-A`.\n */\nexport function attestationProof(attestation: string | null | undefined): Proof | null {\n if (!attestation) return null;\n const value = attestation.trim().toUpperCase();\n if (value.includes(\"FAILED\") || value.startsWith(\"NO-\")) return null;\n const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];\n const level = letter ? ATTESTED[letter] : undefined;\n return level ? { method: \"network_attestation\", level } : null;\n}\n\nexport function resolveSession<S extends Session>(source: SessionResolver<S>): S | null {\n if (typeof source !== \"function\") return source;\n try {\n return source() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction isConversation(session: Session): session is Conversation {\n return \"customer\" in session && typeof session.customer === \"function\";\n}\n\n/** A phone number as an E.164 handle, or `null` when it does not look like one. */\nexport function phoneHandle(value: string | null | undefined): Handle | null {\n const raw = value?.trim().replace(/^tel:/i, \"\").replace(/[\\s().-]/g, \"\");\n if (!raw) return null;\n const e164 = raw.startsWith(\"+\") ? raw : `+${raw}`;\n return /^\\+[1-9]\\d{6,14}$/.test(e164) ? { type: \"phone_e164\", value: e164 } : null;\n}\n\nexport function errorName(error: unknown): string {\n return error instanceof Error ? error.name : typeof error;\n}\n\n/**\n * One session as an adapter drives it. Keeps the verification to a single call made before the\n * first context read, and turns every failure into a log line.\n */\nexport class Bridge {\n private proving: Promise<void> | null = null;\n /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */\n private begun = false;\n private opened = false;\n\n constructor(\n readonly session: Session,\n private readonly proof?: ProofSource,\n private readonly memory: AgentMemoryOption = false,\n ) {}\n\n /**\n * The context and, when enabled, the agent's notes, read side by side within the same budget.\n * Never rejects.\n */\n async read(options: ContextOptions = {}): Promise<Read> {\n const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);\n const [context, memory] = await Promise.all([\n this.context(options),\n memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve(\"\"),\n ]);\n return { context, memory, prefix: [memory, context.text].filter(Boolean).join(\"\\n\\n\"), suffix: context.suffix };\n }\n\n get logger(): Logger {\n return this.session.logger;\n }\n\n /**\n * Starts the first read of a call now, in the background, after the proof when one was given (the\n * pack depends on the level it proves): at call start, so the read runs while the call is set up.\n * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.\n */\n begin(): void {\n const session = this.session;\n if (!isConversation(session)) return;\n const start = (): void => {\n this.safe(\"start the first read\", () => {\n // False off the voice read path (a chat view, the cache off): reads go on as before.\n this.begun = session.begin();\n });\n };\n if (this.proof === undefined || this.proof === null) start();\n else void this.verifyOnce().then(start);\n }\n\n /** Verifies once (when a proof was given), then reads the context. Never rejects. */\n async context(options: ContextOptions = {}): Promise<ContextResult> {\n await this.verifyOnce();\n try {\n const session = this.session;\n if (this.begun && !this.opened && isConversation(session)) {\n this.opened = true;\n // The call's first read, begun at call start: waited for within its own, longer budget.\n await session.ready(options.timeout === undefined ? {} : { timeout: options.timeout });\n }\n return await this.session.context(options);\n } catch (error) {\n this.logger.warn(`could not read context (${errorName(error)})`);\n return emptyResult(null);\n }\n }\n\n /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */\n injected(context: ContextResult): void {\n if (!context.text && !context.suffix && context.response?.path !== \"holdout\") return;\n this.safe(\"mark the injection\", () => {\n this.session.markInjected(context);\n });\n }\n\n customer(text: string, options: TurnOptions = {}): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"record the customer's turn\", () => session.customer(text, options));\n }\n\n /** Sends the customer's turn so far, while they speak. In the background; never throws. */\n prefetch(text: string): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"prefetch the turn\", () => session.prefetch(text));\n }\n\n agent(text: string, options: TurnOptions = {}): void {\n if (!text.trim()) return;\n this.safe(\"record the agent's turn\", () => this.session.agent(text, options));\n }\n\n /** Records a transfer. Tasks have no transfer; the call is ignored for them. */\n async handoff(target: \"agent\" | \"human\", reason?: string): Promise<void> {\n const session = this.session;\n if (!isConversation(session)) return;\n try {\n await session.handoff(reason ? { target, reason } : { target });\n } catch (error) {\n this.logger.warn(`could not record the handoff (${errorName(error)})`);\n }\n }\n\n async end(): Promise<void> {\n try {\n await this.session.end();\n } catch (error) {\n this.logger.warn(`could not end the session (${errorName(error)})`);\n }\n }\n\n /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */\n tools(): ToolSpec[] {\n let bound: BoundTools | null;\n try {\n const memory = this.memory;\n bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });\n } catch (error) {\n this.logger.warn(`could not build the tools (${errorName(error)})`);\n return [];\n }\n return bound ? toolSpecs(bound) : [];\n }\n\n private async agentMemory(params: AgentMemoryParams, options: ContextOptions): Promise<string> {\n try {\n const result = await this.session.agentMemory(params, options.timeout === undefined ? {} : { timeout: options.timeout });\n return result.text;\n } catch (error) {\n this.logger.warn(`could not read the agent's memory (${errorName(error)})`);\n return \"\";\n }\n }\n\n private async verifyOnce(): Promise<void> {\n if (this.proof === undefined || this.proof === null) return;\n this.proving ??= this.runVerify();\n await this.proving;\n }\n\n private async runVerify(): Promise<void> {\n try {\n const source = this.proof;\n const proof = typeof source === \"function\" ? await source() : source;\n if (!proof) return;\n await this.session.verify(proof);\n } catch (error) {\n this.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n\n private safe(what: string, run: () => unknown): void {\n try {\n run();\n } catch (error) {\n this.logger.warn(`could not ${what} (${errorName(error)})`);\n }\n }\n}\n\nfunction withoutWrite(option: AgentMemoryParams & { write?: boolean }): AgentMemoryParams {\n const { write: _, ...params } = option;\n return params;\n}\n\n/** The bound kit as specs. The customer stays inside `bound`; no parameter names them. */\nfunction toolSpecs(bound: BoundTools): ToolSpec[] {\n return bound.definitions.map(({ function: definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n execute: (args) => bound.call(definition.name, args),\n }));\n}\n\n/** The text of a message content in the shapes model APIs use: a string, or a list of text parts. */\nexport function textOf(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content as unknown[]) {\n if (typeof part === \"string\") parts.push(part);\n else if (isRecord(part) && typeof part.text === \"string\" && (part.type === undefined || part.type === \"text\")) {\n parts.push(part.text);\n }\n }\n return parts.join(\"\");\n}\n\nexport function isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** A non-negative integer, or `null`. */\nexport function count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/**\n * The turn records an adapter keeps from its framework's callbacks, keyed by the framework's own ids (a\n * run, a request, a tool call id). A run starting while the session has a turn in progress (yours, from\n * `conversation.turn()`, or a replay's) records into it; otherwise the adapter opens its own turn and closes\n * it when the run ends. A tool call recorded here is taken over by a `tool()` wrapper running inside it, so\n * the call is recorded once. Every method does nothing when turns are off and never throws.\n */\nexport class TurnHooks {\n /** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */\n static readonly MAX_OPEN = 100;\n private readonly frames = new Map<string, { frame: TurnFrame; own: boolean }>();\n private readonly calls = new Map<string, CallCapture>();\n\n constructor(\n readonly adapter: string,\n readonly enabled: boolean,\n ) {}\n\n /** The turn of the run `key`: the session's turn in progress, or a new one of its own. */\n open(session: Session, key: string, params: TurnParams = {}): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = this.frames.get(key);\n if (held !== undefined) return held.frame;\n try {\n const active = session.activeTurn();\n if (active !== undefined && !this.owns(active)) {\n this.frames.set(key, { frame: active, own: false });\n return active;\n }\n const frame = session.openTurn({ ...params, adapter: this.adapter });\n this.frames.set(key, { frame, own: true });\n if (this.frames.size > TurnHooks.MAX_OPEN) {\n const [oldest] = this.frames.keys();\n if (oldest !== undefined) {\n this.frames.get(oldest)?.frame.incomplete();\n this.close(oldest);\n }\n }\n return frame;\n } catch (error) {\n session.logger.warn(`could not open the turn (${errorName(error)})`);\n return undefined;\n }\n }\n\n /** The turn of `key`, else the session's turn in progress. */\n frame(session: Session, key?: string): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = key === undefined ? undefined : this.frames.get(key);\n const frame = held?.frame ?? session.activeTurn();\n return frame === undefined || frame.closed ? undefined : frame;\n }\n\n has(key: string): boolean {\n return this.frames.has(key);\n }\n\n private owns(frame: TurnFrame): boolean {\n for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;\n return false;\n }\n\n /** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */\n close(key: string, error?: unknown): void {\n const held = this.frames.get(key);\n if (held === undefined) return;\n this.frames.delete(key);\n for (const [callKey, call] of this.calls) {\n if (call.frame !== held.frame) continue;\n this.calls.delete(callKey);\n if (held.own) call.failed(error ?? \"error\");\n }\n if (held.own) held.frame.close(error);\n }\n\n /** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */\n toolStart(session: Session, callKey: string, name: string, args: unknown, options: { frameKey?: string; callId?: string | null } = {}): void {\n const frame = this.frame(session, options.frameKey);\n if (frame === undefined) return;\n try {\n this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));\n } catch {\n frame.incomplete();\n }\n }\n\n /**\n * In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the\n * same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function\n * wrapped with `tool()`, which answers itself.\n */\n replayed(session: Session, name: string, args: unknown, fn?: unknown, frameKey?: string): Played | null {\n const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();\n if (frame?.playback == null || (fn !== undefined && recordedTool(fn) !== null)) return null;\n return frame.playback.answer(name, args, false);\n }\n\n toolEnd(callKey: string, result?: unknown, error?: unknown): void {\n const call = this.calls.get(callKey);\n if (call === undefined) return;\n this.calls.delete(callKey);\n try {\n if (error !== undefined) call.failed(error);\n else call.result(result);\n } catch {\n call.frame.incomplete();\n }\n }\n\n /** A model call that ended, with its tokens when the framework reported them. */\n model(\n session: Session,\n model: string | null | undefined,\n tokens: { in?: number | null; out?: number | null; cached?: number | null } = {},\n frameKey?: string,\n ): void {\n const frame = this.frame(session, frameKey);\n if (frame === undefined) return;\n try {\n frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });\n } catch {\n frame.incomplete();\n }\n }\n}\n","/**\n * The AI SDK's language model prompt (`LanguageModelV2Prompt` and later), shared by the adapters\n * that see it: the AI SDK middleware and Mastra's processor.\n */\n\nimport type { Bridge, Read } from \"./shared.js\";\nimport { isRecord } from \"./shared.js\";\n\n/**\n * The prefix (the agent's notes and the customer's pack) as a system message right after the leading system messages, and the suffix as a text\n * part at the end of the last user message, where every provider accepts it. Returns a new array.\n */\nexport function injectPrompt(prompt: readonly unknown[], read: Pick<Read, \"prefix\" | \"suffix\">): unknown[] {\n const injected = [...prompt];\n if (read.suffix) {\n const last = lastUserIndex(injected);\n const message = injected[last];\n if (isRecord(message) && Array.isArray(message.content)) {\n injected[last] = { ...message, content: [...(message.content as unknown[]), { type: \"text\", text: read.suffix }] };\n }\n }\n if (read.prefix) {\n let position = 0;\n while (position < injected.length && roleOf(injected[position]) === \"system\") position++;\n injected.splice(position, 0, { role: \"system\", content: read.prefix });\n }\n return injected;\n}\n\n/**\n * Records the last user message as the customer's turn once, however many steps of a tool loop\n * send the same prompt again. `seen` keeps what was recorded for this session.\n */\nexport function recordNewest(bridge: Bridge, seen: Set<string>, prompt: readonly unknown[]): void {\n const index = lastUserIndex(prompt);\n if (index < 0) return;\n const message = prompt[index];\n const text = isRecord(message) ? textParts(message.content) : \"\";\n const key = `${String(index)}:${text}`;\n if (!text || seen.has(key)) return;\n seen.add(key);\n bridge.customer(text);\n}\n\nfunction textParts(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return (content as unknown[])\n .map((part) => (isRecord(part) && part.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction lastUserIndex(prompt: readonly unknown[]): number {\n for (let index = prompt.length - 1; index >= 0; index--) if (roleOf(prompt[index]) === \"user\") return index;\n return -1;\n}\n\nfunction roleOf(message: unknown): string {\n return isRecord(message) && typeof message.role === \"string\" ? message.role : \"\";\n}\n","/**\n * Niadra for Mastra (`@mastra/core` 1.x): a processor for the agent and the navigation kit as\n * Mastra tools. Mastra's own `Memory` (threads, working memory) stays Mastra's; Niadra is the\n * customer's memory shared with the company's other agents.\n *\n * - `processLLMRequest` rewrites the prompt of each model call without touching the message list:\n * the pack goes after the system messages and the suffix at the end of the last user message,\n * so nothing of it lands in Mastra's memory. The customer's newest message is recorded once.\n * - `processOutputResult` records the final answer with the usage Mastra summed for the run.\n * - With `turns: true`, each request is a turn record, closed with the final answer: each model\n * call with its tokens, each tool call with Mastra's call id and its result. A request inside a\n * turn in progress (`conversation.turn()` around `agent.generate`) records into it. A function\n * wrapped with `tool()` inside a tool takes over its call, which is how a replay answers it.\n * - In a replay the processor wraps every tool of each step with `tool()` (`processInputStep`), so a\n * call answers from the record and never runs live, unless the tool is marked safe to run again.\n *\n * The session comes from the request context (`requestContext.set(\"niadra\", convo)`), or is fixed\n * when the processor is built for one conversation.\n *\n * @example\n * const niadraContext = niadraProcessor();\n * const agent = new Agent({\n * id: \"support\", name: \"Support\", model: openai(\"gpt-4.1\"),\n * instructions: \"You are Acme's support agent.\",\n * tools: ({ requestContext }) => niadraTools(requestContext.get(\"niadra\")),\n * inputProcessors: [niadraContext],\n * outputProcessors: [niadraContext],\n * });\n * const requestContext = new RequestContext([[\"niadra\", convo]]);\n * await agent.generate(messages, { requestContext });\n */\n\nimport type {\n Processor,\n ProcessInputStepArgs,\n ProcessLLMRequestArgs,\n ProcessLLMRequestResult,\n ProcessLLMResponseArgs,\n ProcessOutputResultArgs,\n ProcessOutputStepArgs,\n ProcessToolResultArgs,\n} from \"@mastra/core/processors\";\nimport { tool as recorded, recordedTool } from \"../capture/tool.js\";\nimport { uuidv7 } from \"../ids.js\";\nimport { replaying } from \"../replay/playback.js\";\nimport { createTool } from \"@mastra/core/tools\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport { injectPrompt, recordNewest } from \"./prompt.js\";\nimport { Bridge, TurnHooks, count, errorName, isRecord, resolveSession } from \"./shared.js\";\nimport type { AgentMemoryOption, ProofSource, Session } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session } from \"./shared.js\";\n\n/** The request context key the processor and `niadraTools` read by default. */\nexport const NIADRA_CONTEXT_KEY = \"niadra\";\n\ninterface RequestContextLike {\n get(key: string): unknown;\n}\n\nexport interface NiadraProcessorOptions {\n /** A fixed session, or a function of the request context; defaults to `requestContext.get(\"niadra\")`. */\n session?: Session | ((requestContext: RequestContextLike | undefined) => Session | null | undefined);\n /** What your app proved about the user, recorded once before the first context read. */\n verify?: ProofSource;\n /** Records the newest user message as the customer's turn. Defaults to `true`. */\n recordCustomer?: boolean;\n /** Records the final answer as the agent's turn. Defaults to `true`. */\n recordAgent?: boolean;\n /** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */\n agentMemory?: AgentMemoryOption;\n /** Records each request as a turn, with its model and tool calls. Defaults to `false`. */\n turns?: boolean;\n}\n\n/** The key of the request's run in the processor's state. */\nconst RUN = \"niadraRun\";\n\ninterface State {\n bridge: Bridge;\n seen: Set<string>;\n model: { provider?: string; modelId?: string } | null;\n}\n\n/** A Mastra processor that is both an input processor (the request) and an output processor (the result). */\nexport type NiadraProcessor = Processor<\"niadra\"> &\n Required<Pick<Processor<\"niadra\">, \"processLLMRequest\" | \"processOutputResult\" | \"processLLMResponse\" | \"processOutputStep\" | \"processToolResult\" | \"processInputStep\">>;\n\n/** One processor serves both lists: put the same instance in `inputProcessors` and `outputProcessors`. */\nexport function niadraProcessor(options: NiadraProcessorOptions = {}): NiadraProcessor {\n const states = new WeakMap<Session, State>();\n const hooks = new TurnHooks(\"mastra\", options.turns ?? false);\n /** The request's run: its turn opened on first use, keyed in the processor's per-request state. */\n const runOf = (state: Record<string, unknown>, session: Session): string | undefined => {\n if (!hooks.enabled) return undefined;\n let key = state[RUN];\n if (typeof key !== \"string\") {\n key = uuidv7();\n state[RUN] = key;\n }\n hooks.open(session, key as string);\n return key as string;\n };\n const stateOf = (requestContext: unknown): State | null => {\n const context = isContext(requestContext) ? requestContext : undefined;\n const choice = options.session;\n const session =\n typeof choice === \"function\"\n ? resolveSession(() => choice(context))\n : (choice ?? asSession(context?.get(NIADRA_CONTEXT_KEY)));\n if (!session) return null;\n let state = states.get(session);\n if (!state) {\n state = { bridge: new Bridge(session, options.verify, options.agentMemory), seen: new Set(), model: null };\n states.set(session, state);\n }\n return state;\n };\n\n return {\n id: \"niadra\",\n name: \"Niadra customer context\",\n\n async processLLMRequest({ prompt, model, requestContext, state: kept }: ProcessLLMRequestArgs): Promise<ProcessLLMRequestResult> {\n const state = stateOf(requestContext);\n if (!state) return undefined;\n runOf(kept, state.bridge.session);\n try {\n if (isRecord(model)) {\n state.model = {\n ...(typeof model.provider === \"string\" ? { provider: model.provider } : {}),\n ...(typeof model.modelId === \"string\" ? { modelId: model.modelId } : {}),\n };\n }\n if (options.recordCustomer ?? true) recordNewest(state.bridge, state.seen, prompt);\n const read = await state.bridge.read();\n state.bridge.injected(read.context);\n return { prompt: injectPrompt(prompt, read) as typeof prompt };\n } catch (error) {\n state.bridge.logger.warn(`could not inject context (${errorName(error)})`);\n return undefined;\n }\n },\n\n processLLMResponse({ model, chunks, requestContext, state: kept, fromCache }: ProcessLLMResponseArgs) {\n const state = hooks.enabled && !fromCache ? stateOf(requestContext) : null; // a cached answer called no model\n if (!state) return;\n const key = runOf(kept, state.bridge.session);\n // This step's usage is on its `finish` chunk; `steps` holds the ones before it.\n const finished: unknown = chunks.find((chunk) => chunk.type === \"finish\");\n const payload = isRecord(finished) && isRecord(finished.payload) ? finished.payload : {};\n const usage = isRecord(payload.output) ? payload.output.usage : undefined;\n const name = isRecord(model) && typeof model.modelId === \"string\" ? model.modelId : state.model?.modelId;\n const reported = mastraUsage(usage, state.model);\n const out = isRecord(usage) ? (count(usage.outputTokens) ?? (isRecord(usage.outputTokens) ? count(usage.outputTokens.total) : null)) : null;\n hooks.model(state.bridge.session, name, reported ? { in: reported.prompt_tokens, out, cached: reported.cached_tokens ?? 0 } : {}, key);\n },\n\n processInputStep({ tools }: ProcessInputStepArgs) {\n if (replaying() === null || tools === undefined) return undefined;\n return { tools: replayed(tools) };\n },\n\n processOutputStep({ messageList, toolCalls, requestContext, state: kept }: ProcessOutputStepArgs) {\n const state = hooks.enabled ? stateOf(requestContext) : null;\n if (!state) return messageList;\n const key = runOf(kept, state.bridge.session);\n for (const call of toolCalls ?? []) {\n hooks.toolStart(state.bridge.session, call.toolCallId, call.toolName, call.args, { ...(key ? { frameKey: key } : {}), callId: call.toolCallId });\n }\n return messageList;\n },\n\n processToolResult({ toolCallId, result }: ProcessToolResultArgs) {\n hooks.toolEnd(toolCallId, result);\n },\n\n processOutputResult({ messageList, result, requestContext, state: kept }: ProcessOutputResultArgs) {\n const state = stateOf(requestContext);\n const key = kept[RUN];\n try {\n if (!(options.recordAgent ?? true) || !state || typeof result.text !== \"string\") return messageList;\n try {\n const usage = mastraUsage(result.usage, state.model);\n state.bridge.agent(result.text, usage ? { usage } : {});\n } catch (error) {\n state.bridge.logger.warn(`could not record the agent's answer (${errorName(error)})`);\n }\n return messageList;\n } finally {\n if (typeof key === \"string\") hooks.close(key);\n }\n },\n };\n}\n\n/**\n * The navigation kit as Mastra tools, bound to the session's customer. Pass the session, or\n * nothing inside `tools: ({ requestContext }) => niadraTools(requestContext.get(\"niadra\"))`;\n * without a session it returns no tools.\n */\nexport function niadraTools(session: unknown, options: { agentMemory?: AgentMemoryOption } = {}): Record<string, ReturnType<typeof createTool>> {\n const resolved = asSession(session);\n if (!resolved) return {};\n const tools: Record<string, ReturnType<typeof createTool>> = {};\n for (const spec of new Bridge(resolved, undefined, options.agentMemory).tools()) {\n tools[spec.name] = createTool({\n id: spec.name,\n description: spec.description,\n inputSchema: spec.parameters as Parameters<typeof createTool>[0][\"inputSchema\"],\n execute: async (input: unknown) => parsed(await spec.execute(isRecord(input) ? (input as Record<string, unknown>) : {})),\n });\n }\n return tools;\n}\n\n/**\n * Instructions that carry the context, for agents that cannot take a processor: pass as\n * `instructions`. The pack follows your instructions; turns are not recorded this way.\n */\nexport function niadraInstructions(base: string, options: { session?: Session; agentMemory?: AgentMemoryOption } = {}) {\n return async ({ requestContext }: { requestContext: RequestContextLike }): Promise<string> => {\n const session = options.session ?? asSession(requestContext.get(NIADRA_CONTEXT_KEY));\n if (!session) return base;\n const bridge = new Bridge(session, undefined, options.agentMemory);\n const read = await bridge.read();\n bridge.injected(read.context);\n return [base, read.prefix, read.suffix].filter(Boolean).join(\"\\n\\n\");\n };\n}\n\n/** Mastra's usage (AI SDK 5 numbers, or the split input of later versions) as a `ModelUsage`. */\nexport function mastraUsage(usage: unknown, model: { provider?: string; modelId?: string } | null): ModelUsage | null {\n const provider = model?.provider?.split(\".\")[0]?.toLowerCase();\n const name = model?.modelId;\n if (!isRecord(usage) || !provider || !name) return null;\n let prompt: number | null;\n let cached: number;\n let written = 0;\n if (isRecord(usage.inputTokens)) {\n cached = count(usage.inputTokens.cacheRead) ?? 0;\n written = count(usage.inputTokens.cacheWrite) ?? 0;\n prompt = count(usage.inputTokens.total);\n } else {\n prompt = count(usage.inputTokens) ?? count(usage.promptTokens);\n cached = count(usage.cachedInputTokens) ?? 0;\n }\n if (prompt === null) return null;\n return { provider, model: name, prompt_tokens: Math.max(prompt, cached + written), cached_tokens: cached, cache_write_tokens: written };\n}\n\n/** The step's tools with each `execute` wrapped with `tool()`: in a replay, a call answers from the record. */\nfunction replayed(tools: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [name, spec] of Object.entries(tools)) {\n const execute = isRecord(spec) ? spec.execute : undefined;\n if (typeof execute !== \"function\" || recordedTool(execute)) {\n out[name] = spec;\n continue;\n }\n const wrapped = recorded<[unknown, unknown?], unknown>(name, execute as (input: unknown, context?: unknown) => unknown, {\n args: (input) => input,\n callId: (_input: unknown, context?: unknown) => (isRecord(context) && typeof context.toolCallId === \"string\" ? context.toolCallId : null),\n });\n out[name] = Object.assign(Object.create(Object.getPrototypeOf(spec) as object) as object, spec, { execute: wrapped });\n }\n return out;\n}\n\nfunction isContext(value: unknown): value is RequestContextLike {\n return isRecord(value) && typeof value.get === \"function\";\n}\n\nfunction asSession(value: unknown): Session | null {\n return isRecord(value) && typeof value.context === \"function\" && typeof value.agent === \"function\" ? (value as unknown as Session) : null;\n}\n\nfunction parsed(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n}\n"]}