@niadra/sdk 0.11.2 → 0.11.3

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 (62) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/ai-sdk.cjs.map +1 -1
  3. package/dist/ai-sdk.d.cts +3 -3
  4. package/dist/ai-sdk.d.ts +3 -3
  5. package/dist/ai-sdk.js.map +1 -1
  6. package/dist/anthropic.d.cts +4 -4
  7. package/dist/anthropic.d.ts +4 -4
  8. package/dist/bedrock.d.cts +4 -4
  9. package/dist/bedrock.d.ts +4 -4
  10. package/dist/cli.js +1 -1
  11. package/dist/cli.js.map +1 -1
  12. package/dist/{client-C0FxHZgk.d.cts → client-CUbAjxus.d.cts} +15 -3
  13. package/dist/{client-C0FxHZgk.d.ts → client-CUbAjxus.d.ts} +15 -3
  14. package/dist/cloudflare-agents.d.cts +3 -3
  15. package/dist/cloudflare-agents.d.ts +3 -3
  16. package/dist/elevenlabs.d.cts +5 -5
  17. package/dist/elevenlabs.d.ts +5 -5
  18. package/dist/genkit.d.cts +3 -3
  19. package/dist/genkit.d.ts +3 -3
  20. package/dist/google-adk.d.cts +3 -3
  21. package/dist/google-adk.d.ts +3 -3
  22. package/dist/google-genai.d.cts +4 -4
  23. package/dist/google-genai.d.ts +4 -4
  24. package/dist/index.cjs +1 -1
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +3 -3
  27. package/dist/index.d.ts +3 -3
  28. package/dist/index.js +1 -1
  29. package/dist/index.js.map +1 -1
  30. package/dist/{intercept-BTSgDwBp.d.ts → intercept-Dkzcel9G.d.ts} +1 -1
  31. package/dist/{intercept--jszljK3.d.cts → intercept-Ue3ovmWl.d.cts} +1 -1
  32. package/dist/langchain.cjs.map +1 -1
  33. package/dist/langchain.d.cts +3 -3
  34. package/dist/langchain.d.ts +3 -3
  35. package/dist/langchain.js.map +1 -1
  36. package/dist/livekit.d.cts +3 -3
  37. package/dist/livekit.d.ts +3 -3
  38. package/dist/llamaindex.d.cts +3 -3
  39. package/dist/llamaindex.d.ts +3 -3
  40. package/dist/mastra.cjs.map +1 -1
  41. package/dist/mastra.d.cts +3 -3
  42. package/dist/mastra.d.ts +3 -3
  43. package/dist/mastra.js.map +1 -1
  44. package/dist/openai-agents.d.cts +3 -3
  45. package/dist/openai-agents.d.ts +3 -3
  46. package/dist/retell.d.cts +5 -5
  47. package/dist/retell.d.ts +5 -5
  48. package/dist/{shared-BgH4GypR.d.cts → shared-Bo7qdYgi.d.cts} +1 -1
  49. package/dist/{shared-DNEUVdMh.d.ts → shared-PDIMXzXx.d.ts} +1 -1
  50. package/dist/strands.d.cts +3 -3
  51. package/dist/strands.d.ts +3 -3
  52. package/dist/twilio.d.cts +4 -4
  53. package/dist/twilio.d.ts +4 -4
  54. package/dist/vapi.d.cts +5 -5
  55. package/dist/vapi.d.ts +5 -5
  56. package/dist/voltagent.d.cts +3 -3
  57. package/dist/voltagent.d.ts +3 -3
  58. package/dist/{webhook-CmjN8aRy.d.ts → webhook-BXzrUf4z.d.ts} +1 -1
  59. package/dist/{webhook-JVLjLq-R.d.cts → webhook-CS2V4I6e.d.cts} +1 -1
  60. package/dist/whatsapp.d.cts +2 -2
  61. package/dist/whatsapp.d.ts +2 -2
  62. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/constraints/binding.ts","../src/claims/text.ts","../src/constraints/render.ts","../src/capture/context.ts","../src/capture/frame.ts","../src/capture/mask.ts","../src/capture/tool.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/prompt.ts","../src/integrations/ai-sdk.ts"],"names":["found","folded","args","shown","tool","jsonSchema"],"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,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9D;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":"ai-sdk.cjs","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 // An instruction about an object is in the block only while the read is about that object.\n .filter((h) => SAID.has(h.source) && (h.scope === \"turn\" || h.scope === \"session\" || h.scope === \"object\") && !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","/**\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","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 the Vercel AI SDK (`ai` 5, 6 and 7), the idiomatic way: a language model middleware\n * for `wrapLanguageModel({ model, middleware })`, which works with every provider, and the\n * navigation kit as AI SDK tools.\n *\n * - `transformParams` records the customer's newest message, puts the pack as a system message\n * right after your system messages and the suffix (deltas and live turns) as a text part at the\n * end of the last user message, where every provider accepts it.\n * - `wrapGenerate` and `wrapStream` record the model's text as the agent's turn, with the usage the\n * provider reported (prompt tokens, cache reads and writes). Tool-only steps record nothing.\n * - Turn records: inside a turn of the session (`conversation.turn()` around `generateText`, or\n * `niadraTurn()` for `streamText`, whose steps run after the call returns), each model call is\n * recorded with its tokens, and `recordTools(tools)` records each tool call with the provider's\n * call id; in a replay those tools answer from the record.\n *\n * Nothing here can fail the model call: a context that cannot be read is left out, and a failure\n * to record is logged without content.\n *\n * @example\n * const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: \"web_chat\", conversation_id: chatId });\n * const result = streamText({\n * model: wrapLanguageModel({ model: openai(\"gpt-4.1\"), middleware: niadraMiddleware(convo) }),\n * system: \"You are Acme's support agent.\",\n * messages,\n * tools: { ...niadraTools(convo), ...yourTools },\n * });\n *\n * @example\n * const turn = niadraTurn(convo);\n * const result = turn.run(() =>\n * streamText({ model, messages, tools: recordTools(yourTools, { session: convo }), onFinish: turn.onFinish, onError: turn.onError }),\n * );\n */\n\nimport { jsonSchema, tool } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { TurnFrame } from \"../capture/frame.js\";\nimport { tool as recorded } from \"../capture/tool.js\";\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, SessionResolver } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session, SessionResolver } from \"./shared.js\";\n\nexport interface NiadraMiddlewareOptions {\n /** What your app proved about the user (a login, say), 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 model's text 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}\n\ntype Params = Record<string, unknown> & { prompt?: unknown };\ninterface ModelInfo {\n provider?: string;\n modelId?: string;\n}\n\n/**\n * The middleware, in the shape `wrapLanguageModel` takes from AI SDK 5 on. `specificationVersion`\n * is the one AI SDK 6 requires; AI SDK 5 and 7 do not read it.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any -- the AI SDK majors type these with their own\n call options and results; `any` keeps one middleware assignable to all three. */\nexport interface NiadraMiddleware {\n readonly specificationVersion: \"v3\";\n transformParams(options: { type: \"generate\" | \"stream\"; params: any; model: any }): PromiseLike<any>;\n wrapGenerate(options: { doGenerate: () => PromiseLike<any>; doStream: () => PromiseLike<any>; params: any; model: any }): PromiseLike<any>;\n wrapStream(options: { doGenerate: () => PromiseLike<any>; doStream: () => PromiseLike<any>; params: any; model: any }): PromiseLike<any>;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\ninterface State {\n bridge: Bridge;\n seen: Set<string>;\n}\n\n/**\n * A middleware bound to a conversation or task, or to a function that finds the one each call\n * belongs to (for a model wrapped once at startup). When the function returns `null`, the call\n * passes through untouched.\n */\nexport function niadraMiddleware(session: SessionResolver, options: NiadraMiddlewareOptions = {}): NiadraMiddleware {\n const states = new WeakMap<Session, State>();\n const hooks = new TurnHooks(\"ai-sdk\", true);\n const modelCall = (usage: unknown, model: ModelInfo, modelId: unknown): void => {\n const current = resolveSession(session);\n if (!current) return;\n const name = typeof modelId === \"string\" && modelId ? modelId : model.modelId;\n const reported = aiSdkUsage(usage, model, modelId);\n const out = isRecord(usage) ? (count(usage.outputTokens) ?? (isRecord(usage.outputTokens) ? count(usage.outputTokens.total) : null)) : null;\n hooks.model(current, name, reported ? { in: reported.prompt_tokens, out, cached: reported.cached_tokens ?? 0 } : {});\n };\n const stateOf = (): State | null => {\n const current = resolveSession(session);\n if (!current) return null;\n let state = states.get(current);\n if (!state) {\n state = { bridge: new Bridge(current, options.verify, options.agentMemory), seen: new Set() };\n states.set(current, state);\n }\n return state;\n };\n\n return {\n specificationVersion: \"v3\",\n\n async transformParams({ params }: { params: Params }) {\n const state = stateOf();\n if (!state || !Array.isArray(params.prompt)) return params;\n try {\n const prompt = params.prompt as unknown[];\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 { ...params, prompt: injectPrompt(prompt, read) };\n } catch (error) {\n state.bridge.logger.warn(`could not inject context (${errorName(error)})`);\n return params;\n }\n },\n\n async wrapGenerate({ doGenerate, model }: { doGenerate: () => PromiseLike<unknown>; model: ModelInfo }) {\n const result = await doGenerate();\n if (isRecord(result)) modelCall(result.usage, model, isRecord(result.response) ? result.response.modelId : undefined);\n if (options.recordAgent ?? true) {\n const state = stateOf();\n if (state) {\n try {\n const content = isRecord(result) && Array.isArray(result.content) ? (result.content as unknown[]) : [];\n const text = content.map((part) => (isRecord(part) && part.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\")).join(\"\");\n const response = isRecord(result) && isRecord(result.response) ? result.response : {};\n record(state, text, isRecord(result) ? result.usage : undefined, model, response.modelId);\n } catch (error) {\n state.bridge.logger.warn(`could not capture the model's answer (${errorName(error)})`);\n }\n }\n }\n return result;\n },\n\n async wrapStream({ doStream, model }: { doStream: () => PromiseLike<unknown>; model: ModelInfo }) {\n const result = await doStream();\n const state = (options.recordAgent ?? true) ? stateOf() : null;\n if (!state || !isRecord(result) || !(result.stream instanceof ReadableStream)) return result;\n const parts: string[] = [];\n let usage: unknown;\n let modelId: unknown;\n const capture = new TransformStream<unknown, unknown>({\n transform(chunk, controller) {\n if (isRecord(chunk)) {\n if (chunk.type === \"text-delta\") parts.push(typeof chunk.delta === \"string\" ? chunk.delta : typeof chunk.textDelta === \"string\" ? chunk.textDelta : \"\");\n else if (chunk.type === \"finish\") usage = chunk.usage;\n else if (chunk.type === \"response-metadata\") modelId = chunk.modelId;\n }\n controller.enqueue(chunk);\n },\n flush() {\n try {\n modelCall(usage, model, modelId);\n record(state, parts.join(\"\"), usage, model, modelId);\n } catch (error) {\n state.bridge.logger.warn(`could not capture the model's answer (${errorName(error)})`);\n }\n },\n });\n return { ...result, stream: (result.stream as ReadableStream<unknown>).pipeThrough(capture) };\n },\n };\n}\n\n/**\n * The navigation kit as AI SDK tools (`search_customer_history`, `get_customer_timeline`,\n * `open_history_item`), bound to the session's customer. Spread them next to your own tools.\n */\nexport function niadraTools(session: Session, options: { agentMemory?: AgentMemoryOption } = {}): ToolSet {\n const tools: ToolSet = {};\n for (const spec of new Bridge(session, undefined, options.agentMemory).tools()) {\n tools[spec.name] = tool({\n description: spec.description,\n inputSchema: jsonSchema<Record<string, unknown>>(spec.parameters as Parameters<typeof jsonSchema>[0]),\n execute: async (input: Record<string, unknown>) => parsed(await spec.execute(input)),\n });\n }\n return tools;\n}\n\n/**\n * A turn of the session for one `streamText` or `generateText` call: run the call inside `run()` and pass\n * `onFinish` and `onError` (call them from yours when you have your own), which close the turn.\n */\nexport function niadraTurn(\n session: Session,\n params: TurnParams = {},\n): { frame: TurnFrame; run<T>(fn: () => T): T; onFinish(): void; onError(event: { error: unknown }): void; onAbort(): void } {\n const frame = session.openTurn({ ...params, adapter: \"ai-sdk\" });\n return {\n frame,\n run: (fn) => frame.run(fn),\n onFinish: () => {\n frame.close();\n },\n onError: (event) => {\n frame.close(event.error);\n },\n onAbort: () => {\n frame.close();\n },\n };\n}\n\nexport interface RecordToolsOptions {\n /** The session whose turn in progress the calls go to when the async context does not carry it. */\n session?: Session;\n /** The tools a replay may run for real when the record has no answer: their names, or all. */\n dryRun?: boolean | readonly string[];\n}\n\n/**\n * Your tools with each call recorded in the turn it runs in, named by the tool's key, with the provider's\n * call id. In a replay a call answers from the record. Tools without `execute` pass as they are.\n */\nexport function recordTools<T extends ToolSet>(tools: T, options: RecordToolsOptions = {}): T {\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\") {\n out[name] = spec;\n continue;\n }\n const dryRun = Array.isArray(options.dryRun) ? options.dryRun.includes(name) : options.dryRun === true;\n const session = options.session;\n out[name] = {\n ...spec,\n execute: 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 ...(session ? { frame: () => session.activeTurn() } : {}),\n dryRun,\n }),\n };\n }\n return out as T;\n}\n\n/** What the AI SDK reports as usage, as a `ModelUsage`: v2 counts are numbers, v3 and v4 split the input. */\nexport function aiSdkUsage(usage: unknown, model: ModelInfo, modelId?: unknown): ModelUsage | null {\n if (!isRecord(usage)) return null;\n const name = typeof modelId === \"string\" && modelId ? modelId : model.modelId;\n const provider = model.provider?.split(\".\")[0]?.toLowerCase();\n if (!name || !provider) return null;\n let prompt: number | null;\n let cached: number;\n let written: number;\n if (isRecord(usage.inputTokens)) {\n const input = usage.inputTokens;\n cached = count(input.cacheRead) ?? 0;\n written = count(input.cacheWrite) ?? 0;\n prompt = count(input.total) ?? (count(input.noCache) === null ? null : (count(input.noCache) ?? 0) + cached + written);\n } else {\n prompt = count(usage.inputTokens);\n cached = count(usage.cachedInputTokens) ?? 0;\n written = 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\nfunction record(state: State, text: string, usage: unknown, model: ModelInfo, modelId: unknown): void {\n const reported = aiSdkUsage(usage, model, modelId);\n state.bridge.agent(text, reported ? { usage: reported } : {});\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/capture/context.ts","../src/capture/frame.ts","../src/capture/mask.ts","../src/capture/tool.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/prompt.ts","../src/integrations/ai-sdk.ts"],"names":["found","folded","args","shown","tool","jsonSchema"],"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,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,CAAA;AAAA,EACZ;AACA,EAAA,IAAI,MAAA,KAAW,MAAM,OAAO,IAAA;AAC5B,EAAA,OAAO,EAAE,QAAA,EAAU,KAAA,EAAO,IAAA,EAAM,eAAe,IAAA,CAAK,GAAA,CAAI,MAAA,EAAQ,MAAA,GAAS,OAAO,CAAA,EAAG,aAAA,EAAe,MAAA,EAAQ,oBAAoB,OAAA,EAAQ;AACxI;AAEA,SAAS,MAAA,CAAO,KAAA,EAAc,IAAA,EAAc,KAAA,EAAgB,OAAkB,OAAA,EAAwB;AACpG,EAAA,MAAM,QAAA,GAAW,UAAA,CAAW,KAAA,EAAO,KAAA,EAAO,OAAO,CAAA;AACjD,EAAA,KAAA,CAAM,MAAA,CAAO,MAAM,IAAA,EAAM,QAAA,GAAW,EAAE,KAAA,EAAO,QAAA,EAAS,GAAI,EAAE,CAAA;AAC9D;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":"ai-sdk.cjs","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 // An instruction about an object is in the block only while the read is about that object.\n .filter((h) => SAID.has(h.source) && (h.scope === \"turn\" || h.scope === \"session\" || h.scope === \"object\") && !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","/**\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\ninterface 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\";\ntype 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. */\ntype 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","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 the Vercel AI SDK (`ai` 5, 6 and 7), the idiomatic way: a language model middleware\n * for `wrapLanguageModel({ model, middleware })`, which works with every provider, and the\n * navigation kit as AI SDK tools.\n *\n * - `transformParams` records the customer's newest message, puts the pack as a system message\n * right after your system messages and the suffix (deltas and live turns) as a text part at the\n * end of the last user message, where every provider accepts it.\n * - `wrapGenerate` and `wrapStream` record the model's text as the agent's turn, with the usage the\n * provider reported (prompt tokens, cache reads and writes). Tool-only steps record nothing.\n * - Turn records: inside a turn of the session (`conversation.turn()` around `generateText`, or\n * `niadraTurn()` for `streamText`, whose steps run after the call returns), each model call is\n * recorded with its tokens, and `recordTools(tools)` records each tool call with the provider's\n * call id; in a replay those tools answer from the record.\n *\n * Nothing here can fail the model call: a context that cannot be read is left out, and a failure\n * to record is logged without content.\n *\n * @example\n * const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: \"web_chat\", conversation_id: chatId });\n * const result = streamText({\n * model: wrapLanguageModel({ model: openai(\"gpt-4.1\"), middleware: niadraMiddleware(convo) }),\n * system: \"You are Acme's support agent.\",\n * messages,\n * tools: { ...niadraTools(convo), ...yourTools },\n * });\n *\n * @example\n * const turn = niadraTurn(convo);\n * const result = turn.run(() =>\n * streamText({ model, messages, tools: recordTools(yourTools, { session: convo }), onFinish: turn.onFinish, onError: turn.onError }),\n * );\n */\n\nimport { jsonSchema, tool } from \"ai\";\nimport type { ToolSet } from \"ai\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { TurnFrame } from \"../capture/frame.js\";\nimport { tool as recorded } from \"../capture/tool.js\";\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, SessionResolver } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session, SessionResolver } from \"./shared.js\";\n\nexport interface NiadraMiddlewareOptions {\n /** What your app proved about the user (a login, say), 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 model's text 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}\n\ntype Params = Record<string, unknown> & { prompt?: unknown };\ninterface ModelInfo {\n provider?: string;\n modelId?: string;\n}\n\n/**\n * The middleware, in the shape `wrapLanguageModel` takes from AI SDK 5 on. `specificationVersion`\n * is the one AI SDK 6 requires; AI SDK 5 and 7 do not read it.\n */\n/* eslint-disable @typescript-eslint/no-explicit-any -- the AI SDK majors type these with their own\n call options and results; `any` keeps one middleware assignable to all three. */\nexport interface NiadraMiddleware {\n readonly specificationVersion: \"v3\";\n transformParams(options: { type: \"generate\" | \"stream\"; params: any; model: any }): PromiseLike<any>;\n wrapGenerate(options: { doGenerate: () => PromiseLike<any>; doStream: () => PromiseLike<any>; params: any; model: any }): PromiseLike<any>;\n wrapStream(options: { doGenerate: () => PromiseLike<any>; doStream: () => PromiseLike<any>; params: any; model: any }): PromiseLike<any>;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any */\n\ninterface State {\n bridge: Bridge;\n seen: Set<string>;\n}\n\n/**\n * A middleware bound to a conversation or task, or to a function that finds the one each call\n * belongs to (for a model wrapped once at startup). When the function returns `null`, the call\n * passes through untouched.\n */\nexport function niadraMiddleware(session: SessionResolver, options: NiadraMiddlewareOptions = {}): NiadraMiddleware {\n const states = new WeakMap<Session, State>();\n const hooks = new TurnHooks(\"ai-sdk\", true);\n const modelCall = (usage: unknown, model: ModelInfo, modelId: unknown): void => {\n const current = resolveSession(session);\n if (!current) return;\n const name = typeof modelId === \"string\" && modelId ? modelId : model.modelId;\n const reported = aiSdkUsage(usage, model, modelId);\n const out = isRecord(usage) ? (count(usage.outputTokens) ?? (isRecord(usage.outputTokens) ? count(usage.outputTokens.total) : null)) : null;\n hooks.model(current, name, reported ? { in: reported.prompt_tokens, out, cached: reported.cached_tokens ?? 0 } : {});\n };\n const stateOf = (): State | null => {\n const current = resolveSession(session);\n if (!current) return null;\n let state = states.get(current);\n if (!state) {\n state = { bridge: new Bridge(current, options.verify, options.agentMemory), seen: new Set() };\n states.set(current, state);\n }\n return state;\n };\n\n return {\n specificationVersion: \"v3\",\n\n async transformParams({ params }: { params: Params }) {\n const state = stateOf();\n if (!state || !Array.isArray(params.prompt)) return params;\n try {\n const prompt = params.prompt as unknown[];\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 { ...params, prompt: injectPrompt(prompt, read) };\n } catch (error) {\n state.bridge.logger.warn(`could not inject context (${errorName(error)})`);\n return params;\n }\n },\n\n async wrapGenerate({ doGenerate, model }: { doGenerate: () => PromiseLike<unknown>; model: ModelInfo }) {\n const result = await doGenerate();\n if (isRecord(result)) modelCall(result.usage, model, isRecord(result.response) ? result.response.modelId : undefined);\n if (options.recordAgent ?? true) {\n const state = stateOf();\n if (state) {\n try {\n const content = isRecord(result) && Array.isArray(result.content) ? (result.content as unknown[]) : [];\n const text = content.map((part) => (isRecord(part) && part.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\")).join(\"\");\n const response = isRecord(result) && isRecord(result.response) ? result.response : {};\n record(state, text, isRecord(result) ? result.usage : undefined, model, response.modelId);\n } catch (error) {\n state.bridge.logger.warn(`could not capture the model's answer (${errorName(error)})`);\n }\n }\n }\n return result;\n },\n\n async wrapStream({ doStream, model }: { doStream: () => PromiseLike<unknown>; model: ModelInfo }) {\n const result = await doStream();\n const state = (options.recordAgent ?? true) ? stateOf() : null;\n if (!state || !isRecord(result) || !(result.stream instanceof ReadableStream)) return result;\n const parts: string[] = [];\n let usage: unknown;\n let modelId: unknown;\n const capture = new TransformStream<unknown, unknown>({\n transform(chunk, controller) {\n if (isRecord(chunk)) {\n if (chunk.type === \"text-delta\") parts.push(typeof chunk.delta === \"string\" ? chunk.delta : typeof chunk.textDelta === \"string\" ? chunk.textDelta : \"\");\n else if (chunk.type === \"finish\") usage = chunk.usage;\n else if (chunk.type === \"response-metadata\") modelId = chunk.modelId;\n }\n controller.enqueue(chunk);\n },\n flush() {\n try {\n modelCall(usage, model, modelId);\n record(state, parts.join(\"\"), usage, model, modelId);\n } catch (error) {\n state.bridge.logger.warn(`could not capture the model's answer (${errorName(error)})`);\n }\n },\n });\n return { ...result, stream: (result.stream as ReadableStream<unknown>).pipeThrough(capture) };\n },\n };\n}\n\n/**\n * The navigation kit as AI SDK tools (`search_customer_history`, `get_customer_timeline`,\n * `open_history_item`), bound to the session's customer. Spread them next to your own tools.\n */\nexport function niadraTools(session: Session, options: { agentMemory?: AgentMemoryOption } = {}): ToolSet {\n const tools: ToolSet = {};\n for (const spec of new Bridge(session, undefined, options.agentMemory).tools()) {\n tools[spec.name] = tool({\n description: spec.description,\n inputSchema: jsonSchema<Record<string, unknown>>(spec.parameters as Parameters<typeof jsonSchema>[0]),\n execute: async (input: Record<string, unknown>) => parsed(await spec.execute(input)),\n });\n }\n return tools;\n}\n\n/**\n * A turn of the session for one `streamText` or `generateText` call: run the call inside `run()` and pass\n * `onFinish` and `onError` (call them from yours when you have your own), which close the turn.\n */\nexport function niadraTurn(\n session: Session,\n params: TurnParams = {},\n): { frame: TurnFrame; run<T>(fn: () => T): T; onFinish(): void; onError(event: { error: unknown }): void; onAbort(): void } {\n const frame = session.openTurn({ ...params, adapter: \"ai-sdk\" });\n return {\n frame,\n run: (fn) => frame.run(fn),\n onFinish: () => {\n frame.close();\n },\n onError: (event) => {\n frame.close(event.error);\n },\n onAbort: () => {\n frame.close();\n },\n };\n}\n\nexport interface RecordToolsOptions {\n /** The session whose turn in progress the calls go to when the async context does not carry it. */\n session?: Session;\n /** The tools a replay may run for real when the record has no answer: their names, or all. */\n dryRun?: boolean | readonly string[];\n}\n\n/**\n * Your tools with each call recorded in the turn it runs in, named by the tool's key, with the provider's\n * call id. In a replay a call answers from the record. Tools without `execute` pass as they are.\n */\nexport function recordTools<T extends ToolSet>(tools: T, options: RecordToolsOptions = {}): T {\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\") {\n out[name] = spec;\n continue;\n }\n const dryRun = Array.isArray(options.dryRun) ? options.dryRun.includes(name) : options.dryRun === true;\n const session = options.session;\n out[name] = {\n ...spec,\n execute: 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 ...(session ? { frame: () => session.activeTurn() } : {}),\n dryRun,\n }),\n };\n }\n return out as T;\n}\n\n/** What the AI SDK reports as usage, as a `ModelUsage`: v2 counts are numbers, v3 and v4 split the input. */\nexport function aiSdkUsage(usage: unknown, model: ModelInfo, modelId?: unknown): ModelUsage | null {\n if (!isRecord(usage)) return null;\n const name = typeof modelId === \"string\" && modelId ? modelId : model.modelId;\n const provider = model.provider?.split(\".\")[0]?.toLowerCase();\n if (!name || !provider) return null;\n let prompt: number | null;\n let cached: number;\n let written: number;\n if (isRecord(usage.inputTokens)) {\n const input = usage.inputTokens;\n cached = count(input.cacheRead) ?? 0;\n written = count(input.cacheWrite) ?? 0;\n prompt = count(input.total) ?? (count(input.noCache) === null ? null : (count(input.noCache) ?? 0) + cached + written);\n } else {\n prompt = count(usage.inputTokens);\n cached = count(usage.cachedInputTokens) ?? 0;\n written = 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\nfunction record(state: State, text: string, usage: unknown, model: ModelInfo, modelId: unknown): void {\n const reported = aiSdkUsage(usage, model, modelId);\n state.bridge.agent(text, reported ? { usage: reported } : {});\n}\n\nfunction parsed(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n}\n"]}