@niadra/sdk 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/README.md +15 -6
- package/dist/ai-sdk.cjs +3 -4
- package/dist/ai-sdk.cjs.map +1 -1
- package/dist/ai-sdk.d.cts +3 -3
- package/dist/ai-sdk.d.ts +3 -3
- package/dist/ai-sdk.js +3 -4
- package/dist/ai-sdk.js.map +1 -1
- package/dist/anthropic.cjs +1 -1
- package/dist/anthropic.cjs.map +1 -1
- package/dist/anthropic.d.cts +4 -4
- package/dist/anthropic.d.ts +4 -4
- package/dist/anthropic.js +1 -1
- package/dist/anthropic.js.map +1 -1
- package/dist/bedrock.cjs +1 -1
- package/dist/bedrock.cjs.map +1 -1
- package/dist/bedrock.d.cts +4 -4
- package/dist/bedrock.d.ts +4 -4
- package/dist/bedrock.js +1 -1
- package/dist/bedrock.js.map +1 -1
- package/dist/cli.js +107 -51
- package/dist/cli.js.map +1 -1
- package/dist/{client-DsIxZxZk.d.cts → client-B_ip8T2o.d.cts} +69 -14
- package/dist/{client-DsIxZxZk.d.ts → client-B_ip8T2o.d.ts} +69 -14
- package/dist/cloudflare-agents.cjs +1 -1
- package/dist/cloudflare-agents.cjs.map +1 -1
- package/dist/cloudflare-agents.d.cts +3 -3
- package/dist/cloudflare-agents.d.ts +3 -3
- package/dist/cloudflare-agents.js +1 -1
- package/dist/cloudflare-agents.js.map +1 -1
- package/dist/elevenlabs.cjs +1 -1
- package/dist/elevenlabs.cjs.map +1 -1
- package/dist/elevenlabs.d.cts +5 -5
- package/dist/elevenlabs.d.ts +5 -5
- package/dist/elevenlabs.js +1 -1
- package/dist/elevenlabs.js.map +1 -1
- package/dist/genkit.cjs +1 -1
- package/dist/genkit.cjs.map +1 -1
- package/dist/genkit.d.cts +3 -3
- package/dist/genkit.d.ts +3 -3
- package/dist/genkit.js +1 -1
- package/dist/genkit.js.map +1 -1
- package/dist/google-adk.cjs +1 -1
- package/dist/google-adk.cjs.map +1 -1
- package/dist/google-adk.d.cts +3 -3
- package/dist/google-adk.d.ts +3 -3
- package/dist/google-adk.js +1 -1
- package/dist/google-adk.js.map +1 -1
- package/dist/google-genai.cjs +1 -1
- package/dist/google-genai.cjs.map +1 -1
- package/dist/google-genai.d.cts +4 -4
- package/dist/google-genai.d.ts +4 -4
- package/dist/google-genai.js +1 -1
- package/dist/google-genai.js.map +1 -1
- package/dist/index.cjs +106 -48
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -8
- package/dist/index.d.ts +6 -8
- package/dist/index.js +106 -48
- package/dist/index.js.map +1 -1
- package/dist/{intercept-D7qFCaRb.d.ts → intercept-CBaPK_-k.d.ts} +1 -1
- package/dist/{intercept-0_lJE6k1.d.cts → intercept-CxmBLfoj.d.cts} +1 -1
- package/dist/langchain.cjs +3 -4
- package/dist/langchain.cjs.map +1 -1
- package/dist/langchain.d.cts +3 -3
- package/dist/langchain.d.ts +3 -3
- package/dist/langchain.js +3 -4
- package/dist/langchain.js.map +1 -1
- package/dist/livekit.cjs +1 -1
- package/dist/livekit.cjs.map +1 -1
- package/dist/livekit.d.cts +3 -3
- package/dist/livekit.d.ts +3 -3
- package/dist/livekit.js +1 -1
- package/dist/livekit.js.map +1 -1
- package/dist/llamaindex.cjs +1 -1
- package/dist/llamaindex.cjs.map +1 -1
- package/dist/llamaindex.d.cts +3 -3
- package/dist/llamaindex.d.ts +3 -3
- package/dist/llamaindex.js +1 -1
- package/dist/llamaindex.js.map +1 -1
- package/dist/mastra.cjs +3 -4
- package/dist/mastra.cjs.map +1 -1
- package/dist/mastra.d.cts +3 -3
- package/dist/mastra.d.ts +3 -3
- package/dist/mastra.js +3 -4
- package/dist/mastra.js.map +1 -1
- package/dist/openai-agents.cjs +1 -1
- package/dist/openai-agents.cjs.map +1 -1
- package/dist/openai-agents.d.cts +3 -3
- package/dist/openai-agents.d.ts +3 -3
- package/dist/openai-agents.js +1 -1
- package/dist/openai-agents.js.map +1 -1
- package/dist/retell.cjs +1 -1
- package/dist/retell.cjs.map +1 -1
- package/dist/retell.d.cts +5 -5
- package/dist/retell.d.ts +5 -5
- package/dist/retell.js +1 -1
- package/dist/retell.js.map +1 -1
- package/dist/{shared-Bb5B59Bu.d.ts → shared-BLkAbvuf.d.ts} +1 -1
- package/dist/{shared-DTPWVlWm.d.cts → shared-DEkF2Y_z.d.cts} +1 -1
- package/dist/strands.cjs +1 -1
- package/dist/strands.cjs.map +1 -1
- package/dist/strands.d.cts +3 -3
- package/dist/strands.d.ts +3 -3
- package/dist/strands.js +1 -1
- package/dist/strands.js.map +1 -1
- package/dist/twilio.d.cts +4 -4
- package/dist/twilio.d.ts +4 -4
- package/dist/vapi.cjs +1 -1
- package/dist/vapi.cjs.map +1 -1
- package/dist/vapi.d.cts +5 -5
- package/dist/vapi.d.ts +5 -5
- package/dist/vapi.js +1 -1
- package/dist/vapi.js.map +1 -1
- package/dist/voltagent.cjs +1 -1
- package/dist/voltagent.cjs.map +1 -1
- package/dist/voltagent.d.cts +3 -3
- package/dist/voltagent.d.ts +3 -3
- package/dist/voltagent.js +1 -1
- package/dist/voltagent.js.map +1 -1
- package/dist/{webhook-1ozGyksG.d.ts → webhook-BaraTaA9.d.ts} +1 -1
- package/dist/{webhook-CG4om_DK.d.cts → webhook-CuR0Wckd.d.cts} +1 -1
- package/dist/whatsapp.d.cts +2 -2
- package/dist/whatsapp.d.ts +2 -2
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/capture/tool.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/prompt.ts","../src/integrations/ai-sdk.ts","../src/integrations/cloudflare-agents.ts"],"names":["tool","jsonSchema"],"mappings":";;;;;;;AAwEA,IAAM,QAAA,mBAAW,MAAA,CAAO,GAAA,CAAI,aAAa,CAAA;AAGlC,SAAS,aAAa,EAAA,EAAkC;AAC7D,EAAA,OAAO,OAAO,EAAA,KAAO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AAgB,MAAA,EAAqB;AAClG,EAAA,MAAM,MAAA,GAAS,CAAC,GAAG,QAAQ,CAAA;AAC3B,EAAA,MAAM,KAAA,GAAQ,SAAS,MAAM,CAAA;AAC7B,EAAA,MAAM,IAAA,GAAO,OAAO,KAAK,CAAA;AACzB,EAAA,IAAI,UAAU,IAAA,EAAM;AAClB,IAAA,MAAM,UAAU,IAAA,CAAK,OAAA;AACrB,IAAA,MAAM,IAAA,GAAO,OAAO,OAAA,KAAY,QAAA,GAAW,GAAG,OAAO;;AAAA,EAAO,MAAM,CAAA,CAAA,GAAK,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAAI,CAAC,GAAI,OAAA,EAAuB,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,MAAA,EAAQ,CAAA,GAAI,OAAA;AAC9J,IAAA,MAAA,CAAO,KAAK,CAAA,GAAI,EAAE,GAAG,IAAA,EAAM,SAAS,IAAA,EAAK;AAAA,EAC3C;AACA,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,IAAI,QAAA,GAAW,CAAA;AACf,IAAA,OAAO,WAAW,MAAA,CAAO,MAAA,IAAU,OAAO,QAAQ,CAAA,EAAG,SAAS,QAAA,EAAU,QAAA,EAAA;AACxE,IAAA,MAAA,CAAO,MAAA,CAAO,UAAU,CAAA,EAAG,EAAE,MAAM,QAAA,EAAU,OAAA,EAAS,QAAa,CAAA;AAAA,EACrE;AACA,EAAA,OAAO,MAAA;AACT","file":"cloudflare-agents.cjs","sourcesContent":["/**\n * `tool()`: records each call of a function tool in the turn it runs in, whatever the framework.\n *\n * ```ts\n * const quote = niadra.tool(\"quote\", async (plan: string) => pricing.quote(plan), {\n * provenance: (r) => [{ ref: `health_quote:op:${r.id}`, fields: r.prices }],\n * });\n * ```\n *\n * Inside a turn, a call records its arguments when it starts (the single argument, or the list of them),\n * its result or its failure when it ends, its latency, and the call it was made in. `provenance` turns a\n * result into the objects it showed, each `{ref, fields, provenance}`: without provenance an observation is\n * for display only. `ui` gives the form of the result the interface got, when it differs from the one the\n * model saw. Outside a turn, the tool runs untouched and nothing is recorded. The recording never fails the\n * tool: a provenance function that throws marks the turn incomplete, and the tool's own result and errors\n * pass through unchanged. An async generator is recorded piece by piece, and its result is the list of\n * pieces once it is consumed.\n *\n * With a binding (the tool's binding, as `constraints/binding.ts` reads it: `binding`, else the one the SDK\n * profile serves for the tool's name), a call in a turn that read the constraints block records what it did\n * with the block: the hard constraints its arguments sent, and over the\n * objects its result shows, how many were checked, broke one, or lacked the field. Nothing is changed.\n *\n * With `maskOutput: true`, the fields the key may not read never reach the model (`capture/mask.ts`); the record\n * keeps what the model saw. Left unset, the binding's `capabilities.mask_output` decides.\n *\n * In a replay (`replay/`) the call answers from the record when its arguments match a recorded call of the\n * tool; otherwise it runs only when `dryRun: true` says running it again is safe, and answers `undefined` (a\n * divergence) when not.\n */\n\nimport { parseBinding, relaxed, resultItems } from \"../constraints/binding.js\";\nimport type { RawBinding } from \"../constraints/binding.js\";\nimport { honored, render } from \"../constraints/render.js\";\nimport type { CallCapture, Observation, TurnFrame } from \"./frame.js\";\nimport { currentTurn } from \"./frame.js\";\nimport { protect } from \"./mask.js\";\nimport type { Access, OnUnknown } from \"./mask.js\";\n\nexport interface ToolOptions<A extends unknown[], R> {\n /** The objects a result showed, each `{ref, fields, provenance}`. */\n provenance?: (result: Awaited<R>) => Observation | readonly Observation[] | null | undefined;\n /** The form of the result the interface got, when it differs from the model's. */\n ui?: (result: Awaited<R>) => unknown;\n /** What the record keeps as the arguments; by default the single argument, or the list of them. */\n args?: (...args: A) => unknown;\n /** A replay may run the tool for real when the record has no answer for it. */\n dryRun?: boolean;\n /** The provider's id of the call, when the framework passes it to the tool. */\n callId?: (...args: A) => string | null | undefined;\n /** The turn to record in when the async context does not carry one (a framework that runs tools elsewhere). */\n frame?: () => TurnFrame | null | undefined;\n /** The tool's binding, to measure the constraints block against its calls; wins over the one the profile serves. */\n binding?: RawBinding;\n /** The bindings the SDK profile serves, by tool name; by default the client's (`niadra.tool`) or the turn's. */\n served?: (tool: string) => RawBinding | null;\n /** Keeps the fields this key may not read from the model; left unset, the binding's capability decides. */\n maskOutput?: boolean;\n /** With no profile ever read: `pass` (the default) lets the result through, `block` withholds it. */\n onUnknown?: OnUnknown;\n /** The fields each type hides; by default the SDK profile of the client (`niadra.tool`) or of the turn. */\n access?: Access;\n}\n\n/** What `tool()` knows of the function it wraps, for the runners that call it again. */\nexport interface RecordedTool {\n name: string;\n dryRun: boolean;\n provenance: ((result: never) => Observation | readonly Observation[] | null | undefined) | null;\n binding: RawBinding | null;\n}\n\nconst RECORDED = Symbol.for(\"niadra.tool\");\n\n/** The `tool()` of `fn`, if it is one. */\nexport function recordedTool(fn: unknown): RecordedTool | null {\n return typeof fn === \"function\" ? ((fn as unknown as Record<symbol, RecordedTool | undefined>)[RECORDED] ?? null) : null;\n}\n\nconst isAsyncFunction = (fn: unknown): boolean => Object.prototype.toString.call(fn) === \"[object AsyncFunction]\";\n\nfunction isAsyncIterator(value: unknown): value is AsyncGenerator {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { next?: unknown }).next === \"function\" &&\n Symbol.asyncIterator in value\n );\n}\n\nfunction found(frame: (() => TurnFrame | null | undefined) | undefined): TurnFrame | undefined {\n try {\n return frame?.() ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction thenable(value: unknown): value is PromiseLike<unknown> {\n return typeof value === \"object\" && value !== null && typeof (value as { then?: unknown }).then === \"function\";\n}\n\n/** Records the calls of `fn` as the tool `name`. See the module. */\nexport function tool<A extends unknown[], R>(\n name: string,\n fn: (...args: A) => R,\n options: ToolOptions<A, R> = {},\n): (...args: A) => R {\n const isAsync = isAsyncFunction(fn);\n\n /** The tool's binding: the one the code gives, else the one the SDK profile serves for its name. */\n function bindingOf(frame: TurnFrame | undefined): RawBinding | null {\n return options.binding ?? (options.served ?? frame?.profile.bindings)?.(name) ?? null;\n }\n\n /** Whether the output is masked: `maskOutput` when the code says it, else the binding's capability. */\n function masks(frame: TurnFrame | undefined): boolean {\n return options.maskOutput ?? bindingOf(frame)?.capabilities?.mask_output ?? false;\n }\n\n /** The result as the model may get it. */\n function shield(result: unknown, frame: TurnFrame | undefined): unknown {\n if (!masks(frame)) return result;\n const access = options.access ?? frame?.profile.fieldAccess ?? ((): null => null);\n return protect(result, access(), typesOf(result), options.onUnknown ?? \"pass\");\n }\n\n function typesOf(result: unknown): string[] | null {\n if (!options.provenance) return null;\n try {\n const found = options.provenance(result as Awaited<R>);\n const items = found == null ? [] : Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.map((o) => o.ref.split(\":\")[0] ?? \"\");\n } catch {\n return null;\n }\n }\n\n function end(call: CallCapture, result: unknown, model: unknown = result): void {\n const observations = observed(call, result);\n let shown: unknown;\n if (options.ui) {\n try {\n shown = options.ui(result as Awaited<R>);\n } catch {\n call.frame.incomplete();\n }\n }\n call.result(model, { ui: shown, observations });\n }\n\n function observed(call: CallCapture, result: unknown): Observation[] {\n if (!options.provenance) return [];\n try {\n const found = options.provenance(result as Awaited<R>);\n if (found == null) return [];\n const items = Array.isArray(found) ? (found as Observation[]) : [found as Observation];\n return items.filter((o) => typeof o.ref === \"string\" && typeof o.fields === \"object\");\n } catch {\n call.frame.incomplete();\n return [];\n }\n }\n\n async function* pieces(call: CallCapture, source: AsyncGenerator): AsyncGenerator {\n const kept: unknown[] = [];\n try {\n for await (const piece of source) {\n const shown = shield(piece, call.frame);\n kept.push(shown);\n yield shown;\n }\n } catch (error) {\n call.failed(error);\n throw error;\n }\n end(call, kept);\n }\n\n const wrapped = function (this: unknown, ...args: A): R {\n const frame = currentTurn() ?? found(options.frame);\n if (frame === undefined || frame.closed) {\n if (!masks(frame)) return fn.apply(this, args);\n const out = fn.apply(this, args);\n if (isAsyncIterator(out)) return maskedPieces(out, frame) as R;\n return (thenable(out) ? Promise.resolve(out).then((v) => shield(v, frame)) : shield(out, frame)) as R;\n }\n let recorded: unknown;\n let callId: string | null | undefined;\n try {\n recorded = options.args ? options.args(...args) : args.length === 1 ? args[0] : args;\n callId = options.callId?.(...args);\n } catch {\n recorded = args;\n }\n const call = frame.adopt(name, recorded) ?? frame.toolCall(name, recorded, typeof callId === \"string\" && callId ? { callId } : {});\n const binding = bindingOf(frame);\n if (binding !== null && frame.constraints !== null) call.measure = measure(frame, binding, recorded);\n if (frame.playback !== null) call.played = frame.playback.answer(name, recorded, options.dryRun ?? false);\n if (call.played !== null && !call.played.live) {\n const value = call.played.value;\n end(call, value);\n return (isAsync ? Promise.resolve(value) : value) as R;\n }\n let result: R;\n try {\n result = call.run(() => fn.apply(this, args));\n } catch (error) {\n call.failed(error);\n throw error;\n }\n if (isAsyncIterator(result)) return pieces(call, result) as R;\n if (thenable(result)) {\n return Promise.resolve(result).then(\n (value) => {\n const shown = shield(value, frame);\n end(call, value, shown);\n return shown;\n },\n (error: unknown) => {\n call.failed(error);\n throw error;\n },\n ) as R;\n }\n const shown = shield(result, frame);\n end(call, result, shown);\n return shown as R;\n };\n\n async function* maskedPieces(source: AsyncGenerator, frame: TurnFrame | undefined): AsyncGenerator {\n for await (const piece of source) yield shield(piece, frame);\n }\n\n Object.defineProperty(wrapped, \"name\", { value: fn.name || name });\n const marker: RecordedTool = {\n name,\n dryRun: options.dryRun ?? false,\n provenance: (options.provenance ?? null),\n binding: options.binding ?? null,\n };\n Object.defineProperty(wrapped, RECORDED, { value: marker });\n return wrapped;\n}\n\n/** How the call's result honored the block its arguments were rendered against; `null` when it does not apply. */\nfunction measure(frame: TurnFrame, raw: RawBinding, args: unknown): ((result: unknown) => Record<string, unknown> | null) | null {\n const block = frame.constraints;\n if (block === null) return null;\n const given = typeof args === \"object\" && args !== null && !Array.isArray(args) ? (args as Record<string, unknown>) : {};\n const rendering = render(block, parseBinding(raw, frame.profile.families?.() ?? {}), { args: given });\n if (!rendering.applies) return null;\n return (result) => {\n const seen = honored(block, rendering.hardSent, resultItems(raw, result));\n return {\n constraints: block.version,\n hard_sent: [...rendering.hardSent],\n results_checked: seen.resultsChecked,\n violations: seen.violations,\n unverifiable: seen.unverifiable,\n ...(relaxed(raw, result) ? { relaxed: \"declared\" } : {}),\n };\n };\n}\n","import { NiadraValidationError } from \"./errors.js\";\nimport { includeText } from \"./constraints/text.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport { toObjectRef } from \"./handles.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type {\n ContextFormat,\n ContextPack,\n ContextRequest,\n ContextResponse,\n CoordinationBlock,\n Include,\n LiveTurn,\n PrefetchRequest,\n TargetModel,\n} from \"./types/context.js\";\nimport type { ConstraintsBlock } from \"./types/signals.js\";\nimport type { StateView } from \"./types/state.js\";\nimport type { Verification, View } from \"./types/vocabulary.js\";\n\n/** Arguments of `context()`. Pass exactly one of `subject` or `object`. */\nexport interface ContextParams {\n /** The customer, by any handle the server knows. */\n subject?: Handle;\n /** A business object, such as an invoice, when the task is about the object rather than a person. */\n object?: ObjectRef | string;\n /** The account or partner the person acts for. Requires an active link between the two. */\n about?: Handle;\n /** Defaults to `chat`. */\n view?: View;\n /**\n * The level proven in this conversation. The server may answer with a lower effective level\n * when the source's ceiling is lower; see `response.verification`.\n */\n verification?: Verification;\n /** Enables the per-conversation cache and the server's pinning of the pack. */\n conversation_id?: string;\n /** For internal agents: the task plays the role of the conversation. */\n task_id?: string;\n /**\n * Other words than the turn to pick this read's slots by. Up to 2,000 characters. Wins over\n * `turn`, and like it never changes the pack.\n */\n query?: string;\n /**\n * The customer's last turn; a conversation passes it for you. It goes as `query` and the answer\n * adds `slots`, what the turn selected from memory, in `suffix`, while the pack stays the\n * conversation's pinned one (and is cached as without it).\n */\n turn?: string | null;\n /** Ask only for what changed since this source last read the subject. */\n delta?: boolean;\n /** The model that will read the pack, so the server can size it for that model's prompt cache. */\n target?: TargetModel;\n /** `json` also returns the pack as typed sections in `pack` (`context-pack.v1`). Defaults to `text`. */\n format?: ContextFormat;\n /**\n * Adds `why` to each of `pack.slots`, naming the retrieval channels that\n * ranked it, the fused score, the weights version and, for a derived line, the rule behind it.\n * Requires `format: \"json\"`. It changes nothing else: the pinned text, the slots chosen and the\n * receipt are the same bytes with or without it.\n */\n explain?: boolean;\n /**\n * Blocks read in the same round trip: `[\"constraints\"]` returns the subject's constraints block, `[\"state\"]`\n * the state of their objects. Each only where the space turned its feature on; a block the space does not\n * serve is left out and not asked again for a while, and the read goes on. The blocks are cached with the\n * pack, so a read that fails serves the last good ones too.\n */\n include?: Include[];\n}\n\n/** Arguments of `prefetch()`: who the turn is about, as in `context()`, and the turn so far. */\nexport interface PrefetchParams {\n subject?: Handle;\n object?: ObjectRef | string;\n about?: Handle;\n /** Defaults to `voice`, where partial transcripts come from. */\n view?: View;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** The partial transcript of the customer's turn. */\n text: string;\n}\n\n/** Per-call options shared by every read method. */\nexport interface RequestOptions {\n /** Overrides the method's default time budget, in milliseconds. */\n timeout?: number | undefined;\n /** Cancels the wait. A request shared with other callers keeps running for them. */\n signal?: AbortSignal | undefined;\n /** Extra headers, such as a W3C `traceparent`. */\n headers?: Record<string, string> | undefined;\n}\n\nexport interface ContextOptions extends RequestOptions {\n /** Pass `false` to skip the per-conversation cache for this call. */\n cache?: boolean | undefined;\n /** For `conversation.context()` and `task.context()`: blocks read in the same round trip. */\n include?: Include[] | undefined;\n /** For `conversation.context()` and `task.context()`: `json` also returns `pack`. */\n format?: ContextFormat | undefined;\n /**\n * For `conversation.context()` and `task.context()`: adds `why` to each of `pack.slots`.\n * Requires `format: \"json\"`.\n */\n explain?: boolean | undefined;\n}\n\n/**\n * Where a `context()` result came from.\n *\n * - `network`: a response the server just sent (or confirmed unchanged).\n * - `cache`: a pack younger than the cache TTL; no request was made.\n * - `stale`: an older pack returned at once while a background request refreshes it.\n * - `fallback`: the request failed and this is the last good pack for the conversation.\n * - `none`: nothing was available; `text` is empty and `error` says why.\n */\nexport type ContextSource = \"network\" | \"cache\" | \"stale\" | \"fallback\" | \"none\";\n\n/** What `context()` resolves to. Always usable: on failure `text` is an empty string. */\nexport interface ContextResult {\n /** The pack, ready for the system prompt. Empty when there is nothing to inject. */\n text: string;\n /**\n * The parts that change turn by turn and belong at the end of the prompt, after the\n * conversation: the live turns from other channels, this turn's slots (what the customer's last\n * turn selected from memory), the blocks asked for by `include` (the state view, the constraints) and the\n * delta, in that order, as the API places them. Empty when there are none.\n */\n suffix: string;\n /** Named values from the pack, for templates that place them individually. */\n variables: Record<string, string>;\n /** The pack as typed sections, when read with `format: \"json\"`; otherwise `null`. */\n pack: ContextPack | null;\n source: ContextSource;\n /** The response this result was built from; `null` when `source` is `none`. */\n response: ContextResponse | null;\n /** What went wrong, when `source` is `fallback` or `none`. */\n error: NiadraError | null;\n /** With `include: [\"constraints\"]`: the subject's constraints block. */\n constraints?: ConstraintsBlock | null;\n /** With `include: [\"state\"]`: the state of the subject's objects. */\n state?: StateView | null;\n /** With `include: [\"coordination\"]`: what coordination knows of the subject. */\n coordination?: CoordinationBlock | null;\n}\n\nconst VIEW = /^(voice|chat|brief|full|custom|account|partner|task:[a-z0-9_]{1,40})$/;\nconst MAX_QUERY = 2000;\n\n/** Validates the arguments and builds the wire request, without `known_etag`. */\nexport function buildContextRequest(params: ContextParams): ContextRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n if (params.query !== undefined && params.query.length > MAX_QUERY) {\n throw new NiadraValidationError(`query is longer than ${MAX_QUERY} characters`);\n }\n\n const request: ContextRequest = { view: params.view ?? \"chat\" };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n if (params.query) request.query = params.query;\n if (params.delta) request.delta = true;\n if (params.target) request.target = params.target;\n const format: string = params.format ?? \"text\";\n if (format !== \"text\" && format !== \"json\") throw new NiadraValidationError(\"format is `text` or `json`\");\n if (format === \"json\") request.format = \"json\";\n if (params.explain) {\n if (format !== \"json\") throw new NiadraValidationError('explain requires format: \"json\"');\n request.explain = true;\n }\n if (params.include?.length) request.include = [...new Set(params.include)];\n return request;\n}\n\n/** Validates the arguments of `prefetch()` and builds the wire request. */\nexport function buildPrefetchRequest(params: PrefetchParams): PrefetchRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n const text = params.text.trim();\n if (!text || text.length > MAX_QUERY) throw new NiadraValidationError(`text must be 1 to ${MAX_QUERY} characters`);\n const request: PrefetchRequest = { view: params.view ?? \"voice\", query: text };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n return request;\n}\n\n/** Packs are only cached inside a conversation or task, the unit the server pins them to. */\nexport function cacheScope(request: Pick<ContextRequest, \"conversation_id\" | \"task_id\">): string | null {\n if (request.conversation_id) return `conversation:${request.conversation_id}`;\n if (request.task_id) return `task:${request.task_id}`;\n return null;\n}\n\n/**\n * Every field that changes what the server would compile goes into the key, in a fixed order.\n * `delta` does not: a plain read and a delta read of one conversation get the same pinned\n * bytes, so they share one entry.\n */\nexport function cacheKey(request: ContextRequest): string {\n return JSON.stringify([\n request.subject ?? null,\n request.object ?? null,\n request.about ?? null,\n request.view ?? \"chat\",\n request.verification ?? \"V0\",\n request.conversation_id ?? null,\n request.task_id ?? null,\n request.query ?? null,\n request.target ?? null,\n request.format ?? \"text\",\n request.explain ?? false,\n request.include ?? null,\n ]);\n}\n\n/**\n * Applies a `not_modified` answer to the cached pack: the pinned text and its metadata stay,\n * while the parts outside the pin (live turns, delta, coverage, timing) come from the new answer.\n */\nexport function mergeNotModified(cached: ContextResponse, fresh: ContextResponse): ContextResponse {\n return {\n ...fresh,\n not_modified: false,\n text: cached.text ?? null,\n variables: cached.variables,\n version: cached.version,\n etag: cached.etag,\n manifest_hash: cached.manifest_hash ?? null,\n withheld: cached.withheld,\n cache: cached.cache ?? null,\n pack: cached.pack ?? null,\n // The blocks sit outside the pinned pack: a fresh block wins, and a missing one keeps the cached.\n constraints: fresh.constraints ?? cached.constraints ?? null,\n state: fresh.state ?? cached.state ?? null,\n coordination: fresh.coordination ?? cached.coordination ?? null,\n };\n}\n\nexport function resultFrom(\n response: ContextResponse,\n source: ContextSource,\n error: NiadraError | null = null,\n): ContextResult {\n // A conversation in the control group gets an empty pack on purpose; it is not an error.\n const holdout = response.path === \"holdout\";\n const text = holdout ? \"\" : (response.text ?? \"\");\n const pack = holdout ? null : (response.pack ?? null);\n const blocks = {\n constraints: response.constraints ?? null,\n state: response.state ?? null,\n coordination: response.coordination ?? null,\n };\n return { text, suffix: renderSuffix(response), variables: response.variables, pack, source, response, error, ...blocks };\n}\n\nexport function emptyResult(error: NiadraError | null): ContextResult {\n return { text: \"\", suffix: \"\", variables: {}, pack: null, source: \"none\", response: null, error, constraints: null, state: null, coordination: null };\n}\n\n/**\n * Renders the live turns, the slots and the delta for the end of the prompt, in that order. Kept\n * outside the pinned pack so that the prompt prefix stays byte-identical across turns and the\n * model provider's prompt cache keeps hitting. Returns an empty string when there is nothing to add.\n */\nexport function renderSuffix(response: ContextResponse): string {\n if (response.path === \"holdout\") return \"\";\n const included = includeText(response.text, response.state, response.constraints);\n return [renderLive(response), response.slots ?? \"\", included, response.delta ?? \"\"].filter(Boolean).join(\"\\n\\n\");\n}\n\n/**\n * Renders the live turns (recent turns from other channels that the pack has not absorbed\n * yet) as one tagged block, or an empty string when there are none. `complete=\"false\"` tells\n * the model the list may be missing turns because the server could not read all of them.\n */\nexport function renderLive(response: ContextResponse): string {\n if (response.path === \"holdout\" || response.live.length === 0) return \"\";\n const complete = response.live_complete ? \"\" : ' complete=\"false\"';\n const lines = response.live.map(renderLiveTurn).join(\"\\n\");\n return `<live_turns source=\"niadra\"${complete}>\\n${lines}\\n</live_turns>`;\n}\n\nfunction renderLiveTurn(turn: LiveTurn): string {\n return `[${utcSeconds(turn.at)}] ${turn.channel} · ${turn.speaker}: ${turn.text}`;\n}\n\n/** The same timestamp form in every SDK, whatever precision or offset the server sent. */\nfunction utcSeconds(at: string): string {\n const ms = Date.parse(at);\n return Number.isNaN(ms) ? at : `${new Date(ms).toISOString().slice(0, 19)}Z`;\n}\n","/**\n * What every framework adapter shares: the five primitives (context before the model call, the\n * turns, the tools, the verification and the handoff) wired the same way, and fail-open.\n *\n * Nothing here throws into the framework: a failed read gives an empty context, a failed write\n * is logged without content, and the agent keeps working without memory.\n */\n\nimport { recordedTool } from \"../capture/tool.js\";\nimport type { Played } from \"../replay/playback.js\";\nimport type { AgentMemoryParams } from \"../agent-memory.js\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { CallCapture, TurnFrame } from \"../capture/frame.js\";\nimport type { ContextOptions, ContextResult } from \"../context.js\";\nimport { emptyResult } from \"../context.js\";\nimport type { Conversation, TurnOptions } from \"../conversation.js\";\nimport type { Logger } from \"../logger.js\";\nimport type { Task } from \"../task.js\";\nimport type { BoundTools } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { Verification, VerifyMethod } from \"../types/vocabulary.js\";\n\n/** A customer conversation or an internal agent's task. */\nexport type Session = Conversation | Task;\n\n/** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */\nexport type SessionResolver<S extends Session = Session> = S | (() => S | null | undefined);\n\n/** What the framework proved about the person, recorded with `verify()` before the first context read. */\nexport interface Proof {\n method: VerifyMethod;\n level: Verification;\n /** Defaults to the session's subject. */\n handle?: Handle;\n}\n\n/** A proof, or a function that reads it from the framework when the first context is needed. */\nexport type ProofSource =\n | Proof\n | null\n | undefined\n | (() => Proof | null | undefined | PromiseLike<Proof | null | undefined>);\n\n/**\n * The agent's own working notes: `true` puts the block before the customer's context and offers\n * `search_agent_memory`; `{ write: true }` also offers `remember` (for a key with the\n * `agent_memory:write` scope); the other fields go to `agentMemory()`.\n */\nexport type AgentMemoryOption = boolean | (AgentMemoryParams & { write?: boolean });\n\n/** What goes into the prompt for one model call. */\nexport interface Read {\n context: ContextResult;\n /** The agent's own notes, or an empty string. */\n memory: string;\n /** What goes after the instructions: the notes, then the customer's pack. */\n prefix: string;\n /** What goes at the end: live turns, the turn's slots and deltas. */\n suffix: string;\n}\n\n/** A tool as every framework needs it: the name, the text for the model, the JSON Schema and the call. */\ninterface ToolSpec {\n name: string;\n description: string;\n /** JSON Schema of the arguments. None of them names the customer. */\n parameters: Record<string, unknown>;\n /** Runs the call and returns the text for the model. Never rejects in fail-open mode. */\n execute(args: string | Record<string, unknown>): Promise<string>;\n}\n\nconst ATTESTED: Record<string, Verification> = { A: \"V2\", B: \"V1\", C: \"V1\" };\n\n/**\n * The proof a carrier's STIR/SHAKEN attestation gives a phone call: `A` proves V2, `B` and `C`\n * prove V1, anything else proves nothing (`null`). Accepts the bare letter or the forms carriers\n * and platforms send, such as Twilio's `TN-Validation-Passed-A`.\n */\nexport function attestationProof(attestation: string | null | undefined): Proof | null {\n if (!attestation) return null;\n const value = attestation.trim().toUpperCase();\n if (value.includes(\"FAILED\") || value.startsWith(\"NO-\")) return null;\n const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];\n const level = letter ? ATTESTED[letter] : undefined;\n return level ? { method: \"network_attestation\", level } : null;\n}\n\nexport function resolveSession<S extends Session>(source: SessionResolver<S>): S | null {\n if (typeof source !== \"function\") return source;\n try {\n return source() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction isConversation(session: Session): session is Conversation {\n return \"customer\" in session && typeof session.customer === \"function\";\n}\n\n/** A phone number as an E.164 handle, or `null` when it does not look like one. */\nexport function phoneHandle(value: string | null | undefined): Handle | null {\n const raw = value?.trim().replace(/^tel:/i, \"\").replace(/[\\s().-]/g, \"\");\n if (!raw) return null;\n const e164 = raw.startsWith(\"+\") ? raw : `+${raw}`;\n return /^\\+[1-9]\\d{6,14}$/.test(e164) ? { type: \"phone_e164\", value: e164 } : null;\n}\n\nexport function errorName(error: unknown): string {\n return error instanceof Error ? error.name : typeof error;\n}\n\n/**\n * One session as an adapter drives it. Keeps the verification to a single call made before the\n * first context read, and turns every failure into a log line.\n */\nexport class Bridge {\n private proving: Promise<void> | null = null;\n /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */\n private begun = false;\n private opened = false;\n\n constructor(\n readonly session: Session,\n private readonly proof?: ProofSource,\n private readonly memory: AgentMemoryOption = false,\n ) {}\n\n /**\n * The context and, when enabled, the agent's notes, read side by side within the same budget.\n * Never rejects.\n */\n async read(options: ContextOptions = {}): Promise<Read> {\n const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);\n const [context, memory] = await Promise.all([\n this.context(options),\n memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve(\"\"),\n ]);\n return { context, memory, prefix: [memory, context.text].filter(Boolean).join(\"\\n\\n\"), suffix: context.suffix };\n }\n\n get logger(): Logger {\n return this.session.logger;\n }\n\n /**\n * Starts the first read of a call now, in the background, after the proof when one was given (the\n * pack depends on the level it proves): at call start, so the read runs while the call is set up.\n * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.\n */\n begin(): void {\n const session = this.session;\n if (!isConversation(session)) return;\n const start = (): void => {\n this.safe(\"start the first read\", () => {\n // False off the voice read path (a chat view, the cache off): reads go on as before.\n this.begun = session.begin();\n });\n };\n if (this.proof === undefined || this.proof === null) start();\n else void this.verifyOnce().then(start);\n }\n\n /** Verifies once (when a proof was given), then reads the context. Never rejects. */\n async context(options: ContextOptions = {}): Promise<ContextResult> {\n await this.verifyOnce();\n try {\n const session = this.session;\n if (this.begun && !this.opened && isConversation(session)) {\n this.opened = true;\n // The call's first read, begun at call start: waited for within its own, longer budget.\n await session.ready(options.timeout === undefined ? {} : { timeout: options.timeout });\n }\n return await this.session.context(options);\n } catch (error) {\n this.logger.warn(`could not read context (${errorName(error)})`);\n return emptyResult(null);\n }\n }\n\n /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */\n injected(context: ContextResult): void {\n if (!context.text && !context.suffix && context.response?.path !== \"holdout\") return;\n this.safe(\"mark the injection\", () => {\n this.session.markInjected(context);\n });\n }\n\n customer(text: string, options: TurnOptions = {}): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"record the customer's turn\", () => session.customer(text, options));\n }\n\n /** Sends the customer's turn so far, while they speak. In the background; never throws. */\n prefetch(text: string): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"prefetch the turn\", () => session.prefetch(text));\n }\n\n agent(text: string, options: TurnOptions = {}): void {\n if (!text.trim()) return;\n this.safe(\"record the agent's turn\", () => this.session.agent(text, options));\n }\n\n /** Records a transfer. Tasks have no transfer; the call is ignored for them. */\n async handoff(target: \"agent\" | \"human\", reason?: string): Promise<void> {\n const session = this.session;\n if (!isConversation(session)) return;\n try {\n await session.handoff(reason ? { target, reason } : { target });\n } catch (error) {\n this.logger.warn(`could not record the handoff (${errorName(error)})`);\n }\n }\n\n async end(): Promise<void> {\n try {\n await this.session.end();\n } catch (error) {\n this.logger.warn(`could not end the session (${errorName(error)})`);\n }\n }\n\n /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */\n tools(): ToolSpec[] {\n let bound: BoundTools | null;\n try {\n const memory = this.memory;\n bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });\n } catch (error) {\n this.logger.warn(`could not build the tools (${errorName(error)})`);\n return [];\n }\n return bound ? toolSpecs(bound) : [];\n }\n\n private async agentMemory(params: AgentMemoryParams, options: ContextOptions): Promise<string> {\n try {\n const result = await this.session.agentMemory(params, options.timeout === undefined ? {} : { timeout: options.timeout });\n return result.text;\n } catch (error) {\n this.logger.warn(`could not read the agent's memory (${errorName(error)})`);\n return \"\";\n }\n }\n\n private async verifyOnce(): Promise<void> {\n if (this.proof === undefined || this.proof === null) return;\n this.proving ??= this.runVerify();\n await this.proving;\n }\n\n private async runVerify(): Promise<void> {\n try {\n const source = this.proof;\n const proof = typeof source === \"function\" ? await source() : source;\n if (!proof) return;\n await this.session.verify(proof);\n } catch (error) {\n this.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n\n private safe(what: string, run: () => unknown): void {\n try {\n run();\n } catch (error) {\n this.logger.warn(`could not ${what} (${errorName(error)})`);\n }\n }\n}\n\nfunction withoutWrite(option: AgentMemoryParams & { write?: boolean }): AgentMemoryParams {\n const { write: _, ...params } = option;\n return params;\n}\n\n/** The bound kit as specs. The customer stays inside `bound`; no parameter names them. */\nfunction toolSpecs(bound: BoundTools): ToolSpec[] {\n return bound.definitions.map(({ function: definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n execute: (args) => bound.call(definition.name, args),\n }));\n}\n\n/** The text of a message content in the shapes model APIs use: a string, or a list of text parts. */\nexport function textOf(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content as unknown[]) {\n if (typeof part === \"string\") parts.push(part);\n else if (isRecord(part) && typeof part.text === \"string\" && (part.type === undefined || part.type === \"text\")) {\n parts.push(part.text);\n }\n }\n return parts.join(\"\");\n}\n\nexport function isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** A non-negative integer, or `null`. */\nexport function count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/**\n * The turn records an adapter keeps from its framework's callbacks, keyed by the framework's own ids (a\n * run, a request, a tool call id). A run starting while the session has a turn in progress (yours, from\n * `conversation.turn()`, or a replay's) records into it; otherwise the adapter opens its own turn and closes\n * it when the run ends. A tool call recorded here is taken over by a `tool()` wrapper running inside it, so\n * the call is recorded once. Every method does nothing when turns are off and never throws.\n */\nexport class TurnHooks {\n /** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */\n static readonly MAX_OPEN = 100;\n private readonly frames = new Map<string, { frame: TurnFrame; own: boolean }>();\n private readonly calls = new Map<string, CallCapture>();\n\n constructor(\n readonly adapter: string,\n readonly enabled: boolean,\n ) {}\n\n /** The turn of the run `key`: the session's turn in progress, or a new one of its own. */\n open(session: Session, key: string, params: TurnParams = {}): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = this.frames.get(key);\n if (held !== undefined) return held.frame;\n try {\n const active = session.activeTurn();\n if (active !== undefined && !this.owns(active)) {\n this.frames.set(key, { frame: active, own: false });\n return active;\n }\n const frame = session.openTurn({ ...params, adapter: this.adapter });\n this.frames.set(key, { frame, own: true });\n if (this.frames.size > TurnHooks.MAX_OPEN) {\n const [oldest] = this.frames.keys();\n if (oldest !== undefined) {\n this.frames.get(oldest)?.frame.incomplete();\n this.close(oldest);\n }\n }\n return frame;\n } catch (error) {\n session.logger.warn(`could not open the turn (${errorName(error)})`);\n return undefined;\n }\n }\n\n /** The turn of `key`, else the session's turn in progress. */\n frame(session: Session, key?: string): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = key === undefined ? undefined : this.frames.get(key);\n const frame = held?.frame ?? session.activeTurn();\n return frame === undefined || frame.closed ? undefined : frame;\n }\n\n has(key: string): boolean {\n return this.frames.has(key);\n }\n\n private owns(frame: TurnFrame): boolean {\n for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;\n return false;\n }\n\n /** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */\n close(key: string, error?: unknown): void {\n const held = this.frames.get(key);\n if (held === undefined) return;\n this.frames.delete(key);\n for (const [callKey, call] of this.calls) {\n if (call.frame !== held.frame) continue;\n this.calls.delete(callKey);\n if (held.own) call.failed(error ?? \"error\");\n }\n if (held.own) held.frame.close(error);\n }\n\n /** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */\n toolStart(session: Session, callKey: string, name: string, args: unknown, options: { frameKey?: string; callId?: string | null } = {}): void {\n const frame = this.frame(session, options.frameKey);\n if (frame === undefined) return;\n try {\n this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));\n } catch {\n frame.incomplete();\n }\n }\n\n /**\n * In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the\n * same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function\n * wrapped with `tool()`, which answers itself.\n */\n replayed(session: Session, name: string, args: unknown, fn?: unknown, frameKey?: string): Played | null {\n const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();\n if (frame?.playback == null || (fn !== undefined && recordedTool(fn) !== null)) return null;\n return frame.playback.answer(name, args, false);\n }\n\n toolEnd(callKey: string, result?: unknown, error?: unknown): void {\n const call = this.calls.get(callKey);\n if (call === undefined) return;\n this.calls.delete(callKey);\n try {\n if (error !== undefined) call.failed(error);\n else call.result(result);\n } catch {\n call.frame.incomplete();\n }\n }\n\n /** A model call that ended, with its tokens when the framework reported them. */\n model(\n session: Session,\n model: string | null | undefined,\n tokens: { in?: number | null; out?: number | null; cached?: number | null } = {},\n frameKey?: string,\n ): void {\n const frame = this.frame(session, frameKey);\n if (frame === undefined) return;\n try {\n frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });\n } catch {\n frame.incomplete();\n }\n }\n}\n","/**\n * The AI SDK's language model prompt (`LanguageModelV2Prompt` and later), shared by the adapters\n * that see it: the AI SDK middleware and Mastra's processor.\n */\n\nimport type { Bridge, Read } from \"./shared.js\";\nimport { isRecord } from \"./shared.js\";\n\n/**\n * The prefix (the agent's notes and the customer's pack) as a system message right after the leading system messages, and the suffix as a text\n * part at the end of the last user message, where every provider accepts it. Returns a new array.\n */\nexport function injectPrompt(prompt: readonly unknown[], read: Pick<Read, \"prefix\" | \"suffix\">): unknown[] {\n const injected = [...prompt];\n if (read.suffix) {\n const last = lastUserIndex(injected);\n const message = injected[last];\n if (isRecord(message) && Array.isArray(message.content)) {\n injected[last] = { ...message, content: [...(message.content as unknown[]), { type: \"text\", text: read.suffix }] };\n }\n }\n if (read.prefix) {\n let position = 0;\n while (position < injected.length && roleOf(injected[position]) === \"system\") position++;\n injected.splice(position, 0, { role: \"system\", content: read.prefix });\n }\n return injected;\n}\n\n/**\n * Records the last user message as the customer's turn once, however many steps of a tool loop\n * send the same prompt again. `seen` keeps what was recorded for this session.\n */\nexport function recordNewest(bridge: Bridge, seen: Set<string>, prompt: readonly unknown[]): void {\n const index = lastUserIndex(prompt);\n if (index < 0) return;\n const message = prompt[index];\n const text = isRecord(message) ? textParts(message.content) : \"\";\n const key = `${String(index)}:${text}`;\n if (!text || seen.has(key)) return;\n seen.add(key);\n bridge.customer(text);\n}\n\nfunction textParts(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n return (content as unknown[])\n .map((part) => (isRecord(part) && part.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction lastUserIndex(prompt: readonly unknown[]): number {\n for (let index = prompt.length - 1; index >= 0; index--) if (roleOf(prompt[index]) === \"user\") return index;\n return -1;\n}\n\nfunction roleOf(message: unknown): string {\n return isRecord(message) && typeof message.role === \"string\" ? message.role : \"\";\n}\n","/**\n * Niadra for 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","/**\n * Niadra for the Cloudflare Agents SDK (`agents` 0.x): one helper per `Agent` instance (a Durable\n * Object), with the customer's context before every model call and the navigation kit as tools.\n * Only web APIs and the AI SDK (which `agents` already requires), so it runs on Workers as it is.\n *\n * `niadraAgent(this, { niadra, subject })` returns the same helper for the life of the instance,\n * bound to one conversation whose id is the agent's name (the id you route to, such as a chat or\n * a user) unless you give another:\n *\n * - `middleware`: the `@niadra/sdk/ai-sdk` middleware for `wrapLanguageModel()`, the way agents call\n * models (`AIChatAgent.onChatMessage`, `streamText`, `generateText`): the pack after your system\n * prompt, the suffix at the end of the last user message, the customer's newest message and the\n * answer recorded with the provider's usage. After each answer it hands the queued writes to\n * `ctx.waitUntil()`, so the instance does not go idle before Niadra has them.\n * - `tools()`: the kit as AI SDK tools bound to the customer.\n * - `prepare(messages)` and `record(text)`: the same for a model called without the AI SDK, such\n * as the Workers AI binding (`env.AI.run(model, { messages })`, whose usage `workersAiUsage()`\n * reads) or a voice agent's `onTurn()` (pass `channel: \"voice\"` for the voice budget).\n *\n * Fail-open: when Niadra is slow or down, the model gets the messages as they came.\n *\n * @example\n * import { AIChatAgent } from \"@cloudflare/ai-chat\";\n * import { convertToModelMessages, streamText, wrapLanguageModel } from \"ai\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n * import { Niadra, handles } from \"@niadra/sdk\";\n * import { niadraAgent } from \"@niadra/sdk/cloudflare-agents\";\n *\n * let niadra: Niadra | undefined; // one client per isolate\n *\n * export class Support extends AIChatAgent<Env> {\n * async onChatMessage() {\n * niadra ??= new Niadra({ apiKey: this.env.NIADRA_API_KEY });\n * const memory = niadraAgent(this, { niadra, subject: handles.appUserId(this.name) });\n * const result = streamText({\n * model: wrapLanguageModel({ model: createWorkersAI({ binding: this.env.AI })(\"@cf/openai/gpt-oss-120b\"), middleware: memory.middleware }),\n * system: \"You are Acme's support agent.\",\n * messages: await convertToModelMessages(this.messages),\n * tools: { ...memory.tools(), ...yourTools },\n * });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n */\n\nimport type { ToolSet } from \"ai\";\nimport type { Niadra } from \"../client.js\";\nimport type { TurnOptions } from \"../conversation.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport type { NiadraMiddleware } from \"./ai-sdk.js\";\nimport { niadraMiddleware, niadraTools } from \"./ai-sdk.js\";\nimport { Bridge, count, errorName, isRecord, textOf } from \"./shared.js\";\nimport type { AgentMemoryOption, ProofSource, Session } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { NiadraMiddleware } from \"./ai-sdk.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session } from \"./shared.js\";\n\n/** What the helper reads from an `Agent`: its name (and, at run time, `ctx.waitUntil` when there). */\nexport interface AgentLike {\n readonly name: string;\n}\n\nexport interface NiadraAgentOptions {\n niadra: Niadra;\n /**\n * Who the customer is: a handle, or a function of the agent (its name is often your user or chat\n * id). Never from the model. Leave it out when you pass `session`.\n */\n subject?: Handle | ((agent: AgentLike) => Handle | null | undefined);\n /** Defaults to `web_chat`; `voice` gives the voice budget and view. */\n channel?: string;\n /** Defaults to the agent's name. */\n conversationId?: string;\n /** A conversation or an internal agent's task you opened yourself, in place of `subject`. */\n session?: Session;\n /** What your app proved about the user, recorded once before the first context read. */\n verify?: ProofSource;\n /** Records the newest user message as the customer's turn. Defaults to `true`. */\n recordCustomer?: boolean;\n /** Records the model's answer as the agent's turn. Defaults to `true`. */\n recordAgent?: boolean;\n /** Puts the agent's own notes before the customer's context, and adds its memory tools. */\n agentMemory?: AgentMemoryOption;\n /** Keeps the instance alive until a promise settles. Defaults to the agent's `ctx.waitUntil`. */\n waitUntil?: (promise: Promise<unknown>) => void;\n}\n\n/** A chat message in the `{ role, content }` shape the Workers AI binding and most chat APIs take. */\nexport interface ChatMessage {\n role: string;\n content: unknown;\n [key: string]: unknown;\n}\n\nexport interface NiadraForAgent {\n /** The conversation or task, or `null` when no customer could be found (everything then passes through). */\n readonly session: Session | null;\n /** For `wrapLanguageModel({ model, middleware })`. */\n readonly middleware: NiadraMiddleware;\n /** The navigation kit as AI SDK tools; none without a session. */\n tools(): ToolSet;\n /** The messages with the context in place, for a model called without the AI SDK. Never rejects. */\n prepare<M extends ChatMessage>(messages: readonly M[]): Promise<M[]>;\n /** Records an answer given without the AI SDK middleware, with the provider's response or usage when you have it. */\n record(text: string, options?: TurnOptions): void;\n /** Hands the queued writes to `ctx.waitUntil()` (the middleware and `record` do it for you). */\n flush(): void;\n /** Ends the conversation (or task) and sends what is queued. */\n end(): Promise<void>;\n}\n\nconst helpers = new WeakMap<object, NiadraForAgent>();\n\n/**\n * The helper for one agent instance. The first call builds it; later calls on the same instance\n * return the same helper, so the conversation keeps its pinned pack and its deltas across turns.\n */\nexport function niadraAgent(agent: AgentLike, options: NiadraAgentOptions): NiadraForAgent {\n const existing = helpers.get(agent);\n if (existing) return existing;\n const helper = build(agent, options);\n helpers.set(agent, helper);\n return helper;\n}\n\nfunction build(agent: AgentLike, options: NiadraAgentOptions): NiadraForAgent {\n const logger = options.niadra.logger;\n const session = options.session ?? open(agent, options);\n const waitUntil = options.waitUntil ?? waitUntilOf(agent);\n const flush = (): void => {\n try {\n const sending = options.niadra.flush().catch((error: unknown) => {\n logger.warn(`could not send to Niadra (${errorName(error)})`);\n });\n waitUntil?.(sending);\n } catch (error) {\n logger.warn(`could not schedule the flush (${errorName(error)})`);\n }\n };\n const base = niadraMiddleware(session ?? (() => null), {\n ...(options.verify === undefined ? {} : { verify: options.verify }),\n ...(options.recordCustomer === undefined ? {} : { recordCustomer: options.recordCustomer }),\n ...(options.recordAgent === undefined ? {} : { recordAgent: options.recordAgent }),\n ...(options.agentMemory === undefined ? {} : { agentMemory: options.agentMemory }),\n });\n const middleware: NiadraMiddleware = {\n specificationVersion: base.specificationVersion,\n transformParams: (call) => base.transformParams(call),\n async wrapGenerate(call) {\n const result: unknown = await base.wrapGenerate(call);\n flush();\n return result;\n },\n async wrapStream(call) {\n const result: unknown = await base.wrapStream(call);\n if (!isRecord(result) || !(result.stream instanceof ReadableStream)) return result;\n // Runs after the middleware's own capture has recorded the answer.\n const after = new TransformStream<unknown, unknown>({ flush });\n return { ...result, stream: (result.stream as ReadableStream<unknown>).pipeThrough(after) };\n },\n };\n const bridge = session ? new Bridge(session, options.verify, options.agentMemory) : null;\n const seen = new Set<string>();\n\n return {\n session,\n middleware,\n tools: () => (session ? niadraTools(session, options.agentMemory === undefined ? {} : { agentMemory: options.agentMemory }) : {}),\n async prepare(messages) {\n if (!bridge) return [...messages];\n try {\n if (options.recordCustomer ?? true) {\n const index = lastUser(messages);\n const text = index >= 0 ? textOf(messages[index]?.content) : \"\";\n const key = `${String(index)}:${text}`;\n if (text && !seen.has(key)) {\n seen.add(key);\n bridge.customer(text);\n }\n }\n const read = await bridge.read();\n bridge.injected(read.context);\n return inject(messages, read.prefix, read.suffix);\n } catch (error) {\n logger.warn(`could not inject context (${errorName(error)})`);\n return [...messages];\n }\n },\n record(text, turn = {}) {\n if (!bridge || !(options.recordAgent ?? true)) return;\n bridge.agent(text, turn);\n flush();\n },\n flush,\n async end() {\n if (bridge) await bridge.end();\n flush();\n },\n };\n}\n\nfunction open(agent: AgentLike, options: NiadraAgentOptions): Session | null {\n let subject: Handle | null | undefined;\n try {\n subject = typeof options.subject === \"function\" ? options.subject(agent) : options.subject;\n } catch (error) {\n options.niadra.logger.warn(`could not find the customer (${errorName(error)})`);\n return null;\n }\n if (!subject) return null;\n return options.niadra.conversation({ subject, channel: options.channel ?? \"web_chat\", conversation_id: options.conversationId ?? agent.name });\n}\n\n/**\n * The usage of a Workers AI binding answer (`{ usage: { prompt_tokens } }`) as a `ModelUsage`, for\n * `record(text, { usage: workersAiUsage(answer, model) })`. The model id loses its leading `@`.\n */\nexport function workersAiUsage(answer: unknown, model: string): ModelUsage | null {\n const usage = isRecord(answer) && isRecord(answer.usage) ? answer.usage : null;\n const prompt = usage ? count(usage.prompt_tokens) : null;\n const name = model.replace(/^@/, \"\");\n if (prompt === null || !name) return null;\n const details = usage && isRecord(usage.prompt_tokens_details) ? usage.prompt_tokens_details : {};\n const cached = Math.min(count(details.cached_tokens) ?? 0, prompt);\n return { provider: \"workers-ai\", model: name, prompt_tokens: prompt, cached_tokens: cached, cache_write_tokens: 0 };\n}\n\n/** The Durable Object's `ctx.waitUntil`, which the class keeps protected. */\nfunction waitUntilOf(agent: AgentLike): ((promise: Promise<unknown>) => void) | undefined {\n const ctx = (agent as { ctx?: unknown }).ctx;\n if (!isRecord(ctx) || typeof ctx.waitUntil !== \"function\") return undefined;\n const waitUntil = ctx.waitUntil as (promise: Promise<unknown>) => void;\n return (promise) => {\n waitUntil.call(ctx, promise);\n };\n}\n\nfunction lastUser(messages: readonly ChatMessage[]): number {\n for (let index = messages.length - 1; index >= 0; index--) if (messages[index]?.role === \"user\") return index;\n return -1;\n}\n\n/** A copy: the prefix as a system message after the leading ones, the suffix at the end of the last user message. */\nfunction inject<M extends ChatMessage>(messages: readonly M[], prefix: string, suffix: string): M[] {\n const result = [...messages];\n const index = lastUser(result);\n const last = result[index];\n if (suffix && last) {\n const content = last.content;\n const next = typeof content === \"string\" ? `${content}\\n\\n${suffix}` : Array.isArray(content) ? [...(content as unknown[]), { type: \"text\", text: suffix }] : content;\n result[index] = { ...last, content: next };\n }\n if (prefix) {\n let position = 0;\n while (position < result.length && result[position]?.role === \"system\") position++;\n result.splice(position, 0, { role: \"system\", content: prefix } as M);\n }\n return result;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/capture/tool.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/prompt.ts","../src/integrations/ai-sdk.ts","../src/integrations/cloudflare-agents.ts"],"names":["tool","jsonSchema"],"mappings":";;;;;;;AAqEA,IAAM,QAAA,mBAAW,MAAA,CAAO,GAAA,CAAI,aAAa,CAAA;AAGlC,SAAS,aAAa,EAAA,EAAkC;AAC7D,EAAA,OAAO,OAAO,EAAA,KAAO,UAAA,GAAe,EAAA,CAA2D,QAAQ,KAAK,IAAA,GAAQ,IAAA;AACtH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A,MAAM,MAAA,GAAS,CAAC,GAAG,QAAQ,CAAA;AAC3B,EAAA,MAAM,KAAA,GAAQ,SAAS,MAAM,CAAA;AAC7B,EAAA,MAAM,IAAA,GAAO,OAAO,KAAK,CAAA;AACzB,EAAA,IAAI,UAAU,IAAA,EAAM;AAClB,IAAA,MAAM,UAAU,IAAA,CAAK,OAAA;AACrB,IAAA,MAAM,IAAA,GAAO,OAAO,OAAA,KAAY,QAAA,GAAW,GAAG,OAAO;;AAAA,EAAO,MAAM,CAAA,CAAA,GAAK,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAAI,CAAC,GAAI,OAAA,EAAuB,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,MAAA,EAAQ,CAAA,GAAI,OAAA;AAC9J,IAAA,MAAA,CAAO,KAAK,CAAA,GAAI,EAAE,GAAG,IAAA,EAAM,SAAS,IAAA,EAAK;AAAA,EAC3C;AACA,EAAA,IAAI,MAAA,EAAQ;AACV,IAAA,IAAI,QAAA,GAAW,CAAA;AACf,IAAA,OAAO,WAAW,MAAA,CAAO,MAAA,IAAU,OAAO,QAAQ,CAAA,EAAG,SAAS,QAAA,EAAU,QAAA,EAAA;AACxE,IAAA,MAAA,CAAO,MAAA,CAAO,UAAU,CAAA,EAAG,EAAE,MAAM,QAAA,EAAU,OAAA,EAAS,QAAa,CAAA;AAAA,EACrE;AACA,EAAA,OAAO,MAAA;AACT","file":"cloudflare-agents.cjs","sourcesContent":["/**\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","/**\n * Niadra for the Cloudflare Agents SDK (`agents` 0.x): one helper per `Agent` instance (a Durable\n * Object), with the customer's context before every model call and the navigation kit as tools.\n * Only web APIs and the AI SDK (which `agents` already requires), so it runs on Workers as it is.\n *\n * `niadraAgent(this, { niadra, subject })` returns the same helper for the life of the instance,\n * bound to one conversation whose id is the agent's name (the id you route to, such as a chat or\n * a user) unless you give another:\n *\n * - `middleware`: the `@niadra/sdk/ai-sdk` middleware for `wrapLanguageModel()`, the way agents call\n * models (`AIChatAgent.onChatMessage`, `streamText`, `generateText`): the pack after your system\n * prompt, the suffix at the end of the last user message, the customer's newest message and the\n * answer recorded with the provider's usage. After each answer it hands the queued writes to\n * `ctx.waitUntil()`, so the instance does not go idle before Niadra has them.\n * - `tools()`: the kit as AI SDK tools bound to the customer.\n * - `prepare(messages)` and `record(text)`: the same for a model called without the AI SDK, such\n * as the Workers AI binding (`env.AI.run(model, { messages })`, whose usage `workersAiUsage()`\n * reads) or a voice agent's `onTurn()` (pass `channel: \"voice\"` for the voice budget).\n *\n * Fail-open: when Niadra is slow or down, the model gets the messages as they came.\n *\n * @example\n * import { AIChatAgent } from \"@cloudflare/ai-chat\";\n * import { convertToModelMessages, streamText, wrapLanguageModel } from \"ai\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n * import { Niadra, handles } from \"@niadra/sdk\";\n * import { niadraAgent } from \"@niadra/sdk/cloudflare-agents\";\n *\n * let niadra: Niadra | undefined; // one client per isolate\n *\n * export class Support extends AIChatAgent<Env> {\n * async onChatMessage() {\n * niadra ??= new Niadra({ apiKey: this.env.NIADRA_API_KEY });\n * const memory = niadraAgent(this, { niadra, subject: handles.appUserId(this.name) });\n * const result = streamText({\n * model: wrapLanguageModel({ model: createWorkersAI({ binding: this.env.AI })(\"@cf/openai/gpt-oss-120b\"), middleware: memory.middleware }),\n * system: \"You are Acme's support agent.\",\n * messages: await convertToModelMessages(this.messages),\n * tools: { ...memory.tools(), ...yourTools },\n * });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n */\n\nimport type { ToolSet } from \"ai\";\nimport type { Niadra } from \"../client.js\";\nimport type { TurnOptions } from \"../conversation.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport type { NiadraMiddleware } from \"./ai-sdk.js\";\nimport { niadraMiddleware, niadraTools } from \"./ai-sdk.js\";\nimport { Bridge, count, errorName, isRecord, textOf } from \"./shared.js\";\nimport type { AgentMemoryOption, ProofSource, Session } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { NiadraMiddleware } from \"./ai-sdk.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session } from \"./shared.js\";\n\n/** What the helper reads from an `Agent`: its name (and, at run time, `ctx.waitUntil` when there). */\nexport interface AgentLike {\n readonly name: string;\n}\n\nexport interface NiadraAgentOptions {\n niadra: Niadra;\n /**\n * Who the customer is: a handle, or a function of the agent (its name is often your user or chat\n * id). Never from the model. Leave it out when you pass `session`.\n */\n subject?: Handle | ((agent: AgentLike) => Handle | null | undefined);\n /** Defaults to `web_chat`; `voice` gives the voice budget and view. */\n channel?: string;\n /** Defaults to the agent's name. */\n conversationId?: string;\n /** A conversation or an internal agent's task you opened yourself, in place of `subject`. */\n session?: Session;\n /** What your app proved about the user, recorded once before the first context read. */\n verify?: ProofSource;\n /** Records the newest user message as the customer's turn. Defaults to `true`. */\n recordCustomer?: boolean;\n /** Records the model's answer as the agent's turn. Defaults to `true`. */\n recordAgent?: boolean;\n /** Puts the agent's own notes before the customer's context, and adds its memory tools. */\n agentMemory?: AgentMemoryOption;\n /** Keeps the instance alive until a promise settles. Defaults to the agent's `ctx.waitUntil`. */\n waitUntil?: (promise: Promise<unknown>) => void;\n}\n\n/** A chat message in the `{ role, content }` shape the Workers AI binding and most chat APIs take. */\nexport interface ChatMessage {\n role: string;\n content: unknown;\n [key: string]: unknown;\n}\n\nexport interface NiadraForAgent {\n /** The conversation or task, or `null` when no customer could be found (everything then passes through). */\n readonly session: Session | null;\n /** For `wrapLanguageModel({ model, middleware })`. */\n readonly middleware: NiadraMiddleware;\n /** The navigation kit as AI SDK tools; none without a session. */\n tools(): ToolSet;\n /** The messages with the context in place, for a model called without the AI SDK. Never rejects. */\n prepare<M extends ChatMessage>(messages: readonly M[]): Promise<M[]>;\n /** Records an answer given without the AI SDK middleware, with the provider's response or usage when you have it. */\n record(text: string, options?: TurnOptions): void;\n /** Hands the queued writes to `ctx.waitUntil()` (the middleware and `record` do it for you). */\n flush(): void;\n /** Ends the conversation (or task) and sends what is queued. */\n end(): Promise<void>;\n}\n\nconst helpers = new WeakMap<object, NiadraForAgent>();\n\n/**\n * The helper for one agent instance. The first call builds it; later calls on the same instance\n * return the same helper, so the conversation keeps its pinned pack and its deltas across turns.\n */\nexport function niadraAgent(agent: AgentLike, options: NiadraAgentOptions): NiadraForAgent {\n const existing = helpers.get(agent);\n if (existing) return existing;\n const helper = build(agent, options);\n helpers.set(agent, helper);\n return helper;\n}\n\nfunction build(agent: AgentLike, options: NiadraAgentOptions): NiadraForAgent {\n const logger = options.niadra.logger;\n const session = options.session ?? open(agent, options);\n const waitUntil = options.waitUntil ?? waitUntilOf(agent);\n const flush = (): void => {\n try {\n const sending = options.niadra.flush().catch((error: unknown) => {\n logger.warn(`could not send to Niadra (${errorName(error)})`);\n });\n waitUntil?.(sending);\n } catch (error) {\n logger.warn(`could not schedule the flush (${errorName(error)})`);\n }\n };\n const base = niadraMiddleware(session ?? (() => null), {\n ...(options.verify === undefined ? {} : { verify: options.verify }),\n ...(options.recordCustomer === undefined ? {} : { recordCustomer: options.recordCustomer }),\n ...(options.recordAgent === undefined ? {} : { recordAgent: options.recordAgent }),\n ...(options.agentMemory === undefined ? {} : { agentMemory: options.agentMemory }),\n });\n const middleware: NiadraMiddleware = {\n specificationVersion: base.specificationVersion,\n transformParams: (call) => base.transformParams(call),\n async wrapGenerate(call) {\n const result: unknown = await base.wrapGenerate(call);\n flush();\n return result;\n },\n async wrapStream(call) {\n const result: unknown = await base.wrapStream(call);\n if (!isRecord(result) || !(result.stream instanceof ReadableStream)) return result;\n // Runs after the middleware's own capture has recorded the answer.\n const after = new TransformStream<unknown, unknown>({ flush });\n return { ...result, stream: (result.stream as ReadableStream<unknown>).pipeThrough(after) };\n },\n };\n const bridge = session ? new Bridge(session, options.verify, options.agentMemory) : null;\n const seen = new Set<string>();\n\n return {\n session,\n middleware,\n tools: () => (session ? niadraTools(session, options.agentMemory === undefined ? {} : { agentMemory: options.agentMemory }) : {}),\n async prepare(messages) {\n if (!bridge) return [...messages];\n try {\n if (options.recordCustomer ?? true) {\n const index = lastUser(messages);\n const text = index >= 0 ? textOf(messages[index]?.content) : \"\";\n const key = `${String(index)}:${text}`;\n if (text && !seen.has(key)) {\n seen.add(key);\n bridge.customer(text);\n }\n }\n const read = await bridge.read();\n bridge.injected(read.context);\n return inject(messages, read.prefix, read.suffix);\n } catch (error) {\n logger.warn(`could not inject context (${errorName(error)})`);\n return [...messages];\n }\n },\n record(text, turn = {}) {\n if (!bridge || !(options.recordAgent ?? true)) return;\n bridge.agent(text, turn);\n flush();\n },\n flush,\n async end() {\n if (bridge) await bridge.end();\n flush();\n },\n };\n}\n\nfunction open(agent: AgentLike, options: NiadraAgentOptions): Session | null {\n let subject: Handle | null | undefined;\n try {\n subject = typeof options.subject === \"function\" ? options.subject(agent) : options.subject;\n } catch (error) {\n options.niadra.logger.warn(`could not find the customer (${errorName(error)})`);\n return null;\n }\n if (!subject) return null;\n return options.niadra.conversation({ subject, channel: options.channel ?? \"web_chat\", conversation_id: options.conversationId ?? agent.name });\n}\n\n/**\n * The usage of a Workers AI binding answer (`{ usage: { prompt_tokens } }`) as a `ModelUsage`, for\n * `record(text, { usage: workersAiUsage(answer, model) })`. The model id loses its leading `@`.\n */\nexport function workersAiUsage(answer: unknown, model: string): ModelUsage | null {\n const usage = isRecord(answer) && isRecord(answer.usage) ? answer.usage : null;\n const prompt = usage ? count(usage.prompt_tokens) : null;\n const name = model.replace(/^@/, \"\");\n if (prompt === null || !name) return null;\n const details = usage && isRecord(usage.prompt_tokens_details) ? usage.prompt_tokens_details : {};\n const cached = Math.min(count(details.cached_tokens) ?? 0, prompt);\n return { provider: \"workers-ai\", model: name, prompt_tokens: prompt, cached_tokens: cached, cache_write_tokens: 0 };\n}\n\n/** The Durable Object's `ctx.waitUntil`, which the class keeps protected. */\nfunction waitUntilOf(agent: AgentLike): ((promise: Promise<unknown>) => void) | undefined {\n const ctx = (agent as { ctx?: unknown }).ctx;\n if (!isRecord(ctx) || typeof ctx.waitUntil !== \"function\") return undefined;\n const waitUntil = ctx.waitUntil as (promise: Promise<unknown>) => void;\n return (promise) => {\n waitUntil.call(ctx, promise);\n };\n}\n\nfunction lastUser(messages: readonly ChatMessage[]): number {\n for (let index = messages.length - 1; index >= 0; index--) if (messages[index]?.role === \"user\") return index;\n return -1;\n}\n\n/** A copy: the prefix as a system message after the leading ones, the suffix at the end of the last user message. */\nfunction inject<M extends ChatMessage>(messages: readonly M[], prefix: string, suffix: string): M[] {\n const result = [...messages];\n const index = lastUser(result);\n const last = result[index];\n if (suffix && last) {\n const content = last.content;\n const next = typeof content === \"string\" ? `${content}\\n\\n${suffix}` : Array.isArray(content) ? [...(content as unknown[]), { type: \"text\", text: suffix }] : content;\n result[index] = { ...last, content: next };\n }\n if (prefix) {\n let position = 0;\n while (position < result.length && result[position]?.role === \"system\") position++;\n result.splice(position, 0, { role: \"system\", content: prefix } as M);\n }\n return result;\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { ToolSet } from 'ai';
|
|
2
|
-
import { c as Niadra,
|
|
2
|
+
import { c as Niadra, g as Handle, fX as TurnOptions, f as ModelUsage } from './client-B_ip8T2o.cjs';
|
|
3
3
|
import { NiadraMiddleware } from './ai-sdk.cjs';
|
|
4
|
-
import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-
|
|
5
|
-
export { P as Proof, c as attestationProof } from './shared-
|
|
4
|
+
import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-DEkF2Y_z.cjs';
|
|
5
|
+
export { P as Proof, c as attestationProof } from './shared-DEkF2Y_z.cjs';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Niadra for the Cloudflare Agents SDK (`agents` 0.x): one helper per `Agent` instance (a Durable
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { ToolSet } from 'ai';
|
|
2
|
-
import { c as Niadra,
|
|
2
|
+
import { c as Niadra, g as Handle, fX as TurnOptions, f as ModelUsage } from './client-B_ip8T2o.js';
|
|
3
3
|
import { NiadraMiddleware } from './ai-sdk.js';
|
|
4
|
-
import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-
|
|
5
|
-
export { P as Proof, c as attestationProof } from './shared-
|
|
4
|
+
import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-BLkAbvuf.js';
|
|
5
|
+
export { P as Proof, c as attestationProof } from './shared-BLkAbvuf.js';
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* Niadra for the Cloudflare Agents SDK (`agents` 0.x): one helper per `Agent` instance (a Durable
|
|
@@ -10,7 +10,7 @@ function recordedTool(fn) {
|
|
|
10
10
|
|
|
11
11
|
// src/context.ts
|
|
12
12
|
function emptyResult(error) {
|
|
13
|
-
return { text: "", suffix: "", variables: {}, pack: null, source: "none", response: null, error, constraints: null, state: null, coordination: null };
|
|
13
|
+
return { text: "", suffix: "", variables: {}, pack: null, source: "none", ageMs: null, response: null, error, constraints: null, state: null, coordination: null };
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
// src/integrations/shared.ts
|