@niadra/sdk 0.1.1 → 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 +200 -62
- package/README.md +462 -24
- package/dist/ai-sdk.cjs +1036 -0
- package/dist/ai-sdk.cjs.map +1 -0
- package/dist/ai-sdk.d.cts +118 -0
- package/dist/ai-sdk.d.ts +118 -0
- package/dist/ai-sdk.js +1029 -0
- package/dist/ai-sdk.js.map +1 -0
- package/dist/anthropic.cjs +528 -0
- package/dist/anthropic.cjs.map +1 -0
- package/dist/anthropic.d.cts +35 -0
- package/dist/anthropic.d.ts +35 -0
- package/dist/anthropic.js +523 -0
- package/dist/anthropic.js.map +1 -0
- package/dist/bedrock.cjs +392 -0
- package/dist/bedrock.cjs.map +1 -0
- package/dist/bedrock.d.cts +25 -0
- package/dist/bedrock.d.ts +25 -0
- package/dist/bedrock.js +388 -0
- package/dist/bedrock.js.map +1 -0
- package/dist/cli.js +11101 -0
- package/dist/cli.js.map +1 -0
- package/dist/client-B_ip8T2o.d.cts +6960 -0
- package/dist/client-B_ip8T2o.d.ts +6960 -0
- package/dist/cloudflare-agents.cjs +626 -0
- package/dist/cloudflare-agents.cjs.map +1 -0
- package/dist/cloudflare-agents.d.cts +113 -0
- package/dist/cloudflare-agents.d.ts +113 -0
- package/dist/cloudflare-agents.js +622 -0
- package/dist/cloudflare-agents.js.map +1 -0
- package/dist/elevenlabs.cjs +738 -0
- package/dist/elevenlabs.cjs.map +1 -0
- package/dist/elevenlabs.d.cts +86 -0
- package/dist/elevenlabs.d.ts +86 -0
- package/dist/elevenlabs.js +733 -0
- package/dist/elevenlabs.js.map +1 -0
- package/dist/genkit.cjs +323 -0
- package/dist/genkit.cjs.map +1 -0
- package/dist/genkit.d.cts +67 -0
- package/dist/genkit.d.ts +67 -0
- package/dist/genkit.js +318 -0
- package/dist/genkit.js.map +1 -0
- package/dist/google-adk.cjs +705 -0
- package/dist/google-adk.cjs.map +1 -0
- package/dist/google-adk.d.cts +91 -0
- package/dist/google-adk.d.ts +91 -0
- package/dist/google-adk.js +701 -0
- package/dist/google-adk.js.map +1 -0
- package/dist/google-genai.cjs +422 -0
- package/dist/google-genai.cjs.map +1 -0
- package/dist/google-genai.d.cts +26 -0
- package/dist/google-genai.d.ts +26 -0
- package/dist/google-genai.js +418 -0
- package/dist/google-genai.js.map +1 -0
- package/dist/index.cjs +11494 -1910
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +957 -1294
- package/dist/index.d.ts +957 -1294
- package/dist/index.js +11441 -1911
- package/dist/index.js.map +1 -1
- package/dist/intercept-CBaPK_-k.d.ts +20 -0
- package/dist/intercept-CxmBLfoj.d.cts +20 -0
- package/dist/langchain.cjs +1076 -0
- package/dist/langchain.cjs.map +1 -0
- package/dist/langchain.d.cts +102 -0
- package/dist/langchain.d.ts +102 -0
- package/dist/langchain.js +1067 -0
- package/dist/langchain.js.map +1 -0
- package/dist/livekit.cjs +404 -0
- package/dist/livekit.cjs.map +1 -0
- package/dist/livekit.d.cts +113 -0
- package/dist/livekit.d.ts +113 -0
- package/dist/livekit.js +398 -0
- package/dist/livekit.js.map +1 -0
- package/dist/llamaindex.cjs +349 -0
- package/dist/llamaindex.cjs.map +1 -0
- package/dist/llamaindex.d.cts +92 -0
- package/dist/llamaindex.d.ts +92 -0
- package/dist/llamaindex.js +344 -0
- package/dist/llamaindex.js.map +1 -0
- package/dist/mastra.cjs +1081 -0
- package/dist/mastra.cjs.map +1 -0
- package/dist/mastra.d.cts +86 -0
- package/dist/mastra.d.ts +86 -0
- package/dist/mastra.js +1074 -0
- package/dist/mastra.js.map +1 -0
- package/dist/openai-agents.cjs +465 -0
- package/dist/openai-agents.cjs.map +1 -0
- package/dist/openai-agents.d.cts +75 -0
- package/dist/openai-agents.d.ts +75 -0
- package/dist/openai-agents.js +459 -0
- package/dist/openai-agents.js.map +1 -0
- package/dist/retell.cjs +846 -0
- package/dist/retell.cjs.map +1 -0
- package/dist/retell.d.cts +161 -0
- package/dist/retell.d.ts +161 -0
- package/dist/retell.js +841 -0
- package/dist/retell.js.map +1 -0
- package/dist/shared-BLkAbvuf.d.ts +39 -0
- package/dist/shared-DEkF2Y_z.d.cts +39 -0
- package/dist/strands.cjs +352 -0
- package/dist/strands.cjs.map +1 -0
- package/dist/strands.d.cts +72 -0
- package/dist/strands.d.ts +72 -0
- package/dist/strands.js +347 -0
- package/dist/strands.js.map +1 -0
- package/dist/twilio.cjs +174 -0
- package/dist/twilio.cjs.map +1 -0
- package/dist/twilio.d.cts +64 -0
- package/dist/twilio.d.ts +64 -0
- package/dist/twilio.js +167 -0
- package/dist/twilio.js.map +1 -0
- package/dist/vapi.cjs +661 -0
- package/dist/vapi.cjs.map +1 -0
- package/dist/vapi.d.cts +78 -0
- package/dist/vapi.d.ts +78 -0
- package/dist/vapi.js +656 -0
- package/dist/vapi.js.map +1 -0
- package/dist/voltagent.cjs +509 -0
- package/dist/voltagent.cjs.map +1 -0
- package/dist/voltagent.d.cts +70 -0
- package/dist/voltagent.d.ts +70 -0
- package/dist/voltagent.js +503 -0
- package/dist/voltagent.js.map +1 -0
- package/dist/webhook-BaraTaA9.d.ts +37 -0
- package/dist/webhook-CuR0Wckd.d.cts +37 -0
- package/dist/whatsapp.cjs +214 -0
- package/dist/whatsapp.cjs.map +1 -0
- package/dist/whatsapp.d.cts +81 -0
- package/dist/whatsapp.d.ts +81 -0
- package/dist/whatsapp.js +207 -0
- package/dist/whatsapp.js.map +1 -0
- package/package.json +351 -6
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/usage.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/genkit.ts"],"names":["tool"],"mappings":";;;;;;;AAuBA,SAAS,GAAA,CAAI,OAAgB,IAAA,EAAuB;AAClD,EAAA,OAAA,CAAQ,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,KAAA,KAAU,eAAe,KAAA,KAAU,IAAA,GAC1E,KAAA,C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S,QAAA,EAAU,QAAA,EAAA;AACxE,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,QAAA,GAAW,CAAC,CAAA;AAElC,IAAA,IAAI,QAAQ,MAAA,CAAO,QAAA,GAAW,CAAC,CAAA,GAAI,EAAE,GAAG,MAAA,EAAQ,OAAA,EAAS,CAAC,GAAG,MAAA,CAAO,OAAA,EAAS,EAAE,IAAA,EAAM,MAAA,EAAQ,CAAA,EAAE;AAAA,SAC1F,MAAA,CAAO,OAAA,CAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,CAAA,EAAG,CAAA;AAAA,EACrE;AACA,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,SAAS,QAAA,EAAwC;AACxD,EAAA,MAAM,UAAU,QAAA,CAAS,OAAA,IAAW,QAAA,CAAS,UAAA,GAAa,CAAC,CAAA,EAAG,OAAA;AAC9D,EAAA,IAAI,CAAC,OAAA,IAAW,OAAA,CAAQ,OAAA,CAAQ,IAAA,CAAK,CAAC,IAAA,KAAS,aAAA,IAAiB,IAAI,CAAA,EAAG,OAAO,EAAA;AAC9E,EAAA,OAAO,SAAA,CAAU,QAAQ,OAAO,CAAA;AAClC;AAEA,SAAS,UAAU,OAAA,EAAkC;AACnD,EAAA,OAAO,QACJ,GAAA,CAAI,CAAC,IAAA,KAAU,OAAO,KAAK,IAAA,KAAS,QAAA,GAAW,IAAA,CAAK,IAAA,GAAO,EAAG,CAAA,CAC9D,MAAA,CAAO,OAAO,CAAA,CACd,KAAK,IAAI,CAAA;AACd;AAEA,SAAS,OAAO,IAAA,EAAuB;AACrC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACxB,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"genkit.cjs","sourcesContent":["/**\n * Reads what a model provider reported for one call: every input token, the ones read from the\n * provider's prompt cache and the ones written to it.\n *\n * Two shapes are understood, from the response or its `usage` (plain objects or class instances):\n *\n * - OpenAI chat completions and compatible gateways: `usage.prompt_tokens` (cached tokens included)\n * and `usage.prompt_tokens_details.cached_tokens`; the Responses API's `input_tokens` with\n * `input_tokens_details.cached_tokens` too. Gateways that pass Anthropic's cache fields through\n * (`cache_read_input_tokens`, `cache_creation_input_tokens`) are read as well.\n * - Anthropic messages: `usage.input_tokens` counts only the uncached rest, so the prompt is\n * `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`.\n *\n * Nothing here throws: a response without usage gives `null`.\n */\n\nimport type { ModelUsage } from \"./types/events.js\";\n\ntype Bag = Record<PropertyKey, unknown>;\n\nconst PROVIDER = /^[a-z0-9][a-z0-9_.-]{0,63}$/;\nconst MODEL = /^[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,127}$/;\n\nfunction get(value: unknown, name: string): unknown {\n return (typeof value === \"object\" || typeof value === \"function\") && value !== null\n ? (value as Bag)[name]\n : undefined;\n}\n\nfunction count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/** `prompt_tokens`, `cached_tokens` and `cache_write_tokens` from a provider's usage, or `null`. */\nexport function tokenCounts(\n usage: unknown,\n): Pick<ModelUsage, \"prompt_tokens\" | \"cached_tokens\" | \"cache_write_tokens\"> | null {\n const read = count(get(usage, \"cache_read_input_tokens\")) ?? 0;\n const written = count(get(usage, \"cache_creation_input_tokens\")) ?? 0;\n let prompt = count(get(usage, \"prompt_tokens\"));\n let cached: number;\n if (prompt !== null) {\n const reported = count(get(get(usage, \"prompt_tokens_details\"), \"cached_tokens\"));\n cached = reported !== null && reported > 0 ? reported : read;\n } else {\n const inputs = count(get(usage, \"input_tokens\"));\n if (inputs === null) return null;\n const details = get(usage, \"input_tokens_details\");\n if (details !== undefined && details !== null) {\n // The Responses API counts cached tokens inside `input_tokens`, as chat completions do.\n prompt = inputs;\n cached = count(get(details, \"cached_tokens\")) ?? 0;\n } else {\n prompt = inputs + read + written;\n cached = read;\n }\n }\n // A gateway can report a cache that does not fit its own prompt count; the prompt is at least that.\n return { prompt_tokens: Math.max(prompt, cached + written), cached_tokens: cached, cache_write_tokens: written };\n}\n\n/**\n * Who served the call: the router prefix of `vendor/model` names, else what the name or the usage\n * shape says, else `openai` (the client `wrap()` takes).\n */\nexport function providerOf(model: string, usage?: unknown): string {\n const slash = model.indexOf(\"/\");\n if (slash > 0) return model.slice(0, slash).trim().toLowerCase();\n const name = model.trim().toLowerCase();\n if (name.startsWith(\"claude\") || `.${name}`.includes(\".anthropic.\")) return \"anthropic\";\n if (name.startsWith(\"gemini\")) return \"google\";\n if (get(usage, \"prompt_tokens\") === undefined && get(usage, \"cache_read_input_tokens\") !== undefined) {\n return \"anthropic\";\n }\n return \"openai\";\n}\n\n/**\n * The usage of an OpenAI or Anthropic response (or of its bare `usage`, with `options.model`), for\n * the agent's turn: `convo.agent(text, { usage: modelUsage(response) })`. `null` without usage.\n */\nexport function modelUsage(\n response: unknown,\n options: { provider?: string; model?: string } = {},\n): ModelUsage | null {\n try {\n let usage = get(response, \"usage\");\n if (usage === undefined || usage === null || typeof usage !== \"object\") usage = response;\n const counts = tokenCounts(usage);\n const name = options.model ?? get(response, \"model\");\n if (!counts || typeof name !== \"string\" || !MODEL.test(name)) return null;\n const provider = (options.provider ?? providerOf(name, usage)).toLowerCase();\n if (!PROVIDER.test(provider)) return null;\n return { provider, model: name, ...counts };\n } catch {\n return null;\n }\n}\n\n/** A `ModelUsage` as given, or read from a provider's response; `null` when neither works. */\nexport function asModelUsage(value: unknown): ModelUsage | null {\n if (value === undefined || value === null) return null;\n if (isModelUsage(value)) return value;\n return modelUsage(value);\n}\n\n/** A `ModelUsage` the server accepts as it is; anything else is read like a provider's usage. */\nfunction isModelUsage(value: unknown): value is ModelUsage {\n const provider = get(value, \"provider\");\n const model = get(value, \"model\");\n const prompt = count(get(value, \"prompt_tokens\"));\n const cached = get(value, \"cached_tokens\") === undefined ? 0 : count(get(value, \"cached_tokens\"));\n const written = get(value, \"cache_write_tokens\") === undefined ? 0 : count(get(value, \"cache_write_tokens\"));\n return (\n typeof provider === \"string\" &&\n PROVIDER.test(provider) &&\n typeof model === \"string\" &&\n MODEL.test(model) &&\n prompt !== null &&\n cached !== null &&\n written !== null &&\n cached + written <= prompt\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 * Niadra for Genkit (`genkit` 1.x, Firebase Genkit for JavaScript): a model middleware for\n * `generate({ use })` and the navigation kit as Genkit tools.\n *\n * - `niadraMiddleware(session)` runs around every model call, the steps of a tool loop included:\n * it records the customer's newest message once, adds the agent's notes and the customer's pack\n * as a text part of your system message (a new system message when there is none), and adds the\n * suffix (deltas and live turns) as a text part of the last user message. The answer is recorded\n * as the agent's turn with Genkit's usage (input tokens and cached content tokens) when you name\n * the model; steps that only request tools record nothing.\n * - `niadraTools(session)` is the kit as Genkit tools (not registered, so each request can carry\n * the tools bound to its own customer), with the canonical JSON Schemas.\n *\n * Fail-open: when Niadra is slow or down, the request goes to the model as it came.\n *\n * @example\n * import { genkit } from \"genkit\";\n * import { googleAI } from \"@genkit-ai/google-genai\";\n * import { niadraMiddleware, niadraTools } from \"@niadra/sdk/genkit\";\n *\n * const ai = genkit({ plugins: [googleAI()] });\n * const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: \"web_chat\", conversation_id: chatId });\n * const { text } = await ai.generate({\n * model: googleAI.model(\"gemini-2.5-flash\"),\n * system: \"You are Acme's support agent.\",\n * messages: history,\n * prompt: \"Where is my replacement?\",\n * tools: niadraTools(convo),\n * use: [niadraMiddleware(convo, { model: \"googleai/gemini-2.5-flash\" })],\n * });\n */\n\nimport type { GenerateRequest, GenerateResponseData, MessageData, ModelMiddleware, Part } from \"genkit/model\";\nimport { tool } from \"genkit/tool\";\nimport type { ToolAction } from \"genkit/tool\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport { providerOf } from \"../usage.js\";\nimport { Bridge, 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, 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 /**\n * The model the request goes to, as Genkit names it (`googleai/gemini-2.5-flash`), for the usage\n * of the agent's turn. A model middleware does not see the model's name; without it the turn is\n * recorded without usage.\n */\n model?: string;\n /** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */\n agentMemory?: AgentMemoryOption;\n}\n\ninterface State {\n bridge: Bridge;\n seen: Set<string>;\n}\n\n/**\n * A Genkit model middleware bound to a conversation or task, or to a function that finds the one\n * each call belongs to; when it returns `null`, the call passes through untouched.\n */\nexport function niadraMiddleware(session: SessionResolver, options: NiadraMiddlewareOptions = {}): ModelMiddleware {\n const states = new WeakMap<Session, State>();\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 async (request, next) => {\n const state = stateOf();\n if (!state) return next(request);\n let prepared: GenerateRequest = request;\n try {\n if (options.recordCustomer ?? true) recordNewest(state, request.messages);\n const read = await state.bridge.read();\n state.bridge.injected(read.context);\n prepared = { ...request, messages: inject(request.messages, read.prefix, read.suffix) };\n } catch (error) {\n state.bridge.logger.warn(`could not inject context (${errorName(error)})`);\n }\n const response = await next(prepared);\n if (options.recordAgent ?? true) {\n try {\n const answer = answerOf(response);\n if (answer) {\n const usage = options.model ? genkitUsage(response.usage, options.model) : null;\n state.bridge.agent(answer, usage ? { usage } : {});\n }\n } catch (error) {\n state.bridge.logger.warn(`could not record the agent's answer (${errorName(error)})`);\n }\n }\n return response;\n };\n}\n\n/** The navigation kit as Genkit tools, bound to the session's customer. */\nexport function niadraTools(session: Session, options: { agentMemory?: AgentMemoryOption } = {}): ToolAction[] {\n return new Bridge(session, undefined, options.agentMemory).tools().map(\n (spec) =>\n tool(\n { name: spec.name, description: spec.description, inputJsonSchema: spec.parameters, outputJsonSchema: {} },\n async (input: unknown) => parsed(await spec.execute(isRecord(input) ? input : {})),\n ) as unknown as ToolAction,\n );\n}\n\n/** Genkit's usage as a `ModelUsage`: `inputTokens` counts the cached content tokens too. */\nexport function genkitUsage(usage: unknown, model: string): ModelUsage | null {\n if (!isRecord(usage)) return null;\n const prompt = count(usage.inputTokens);\n if (prompt === null) return null;\n const cached = count(usage.cachedContentTokens) ?? 0;\n const slash = model.indexOf(\"/\");\n const name = slash > 0 ? model.slice(slash + 1) : model;\n return { provider: providerOf(model, usage), model: name, prompt_tokens: Math.max(prompt, cached), cached_tokens: cached, cache_write_tokens: 0 };\n}\n\nfunction recordNewest(state: State, messages: readonly MessageData[]): void {\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index];\n if (message?.role !== \"user\") continue;\n const text = textParts(message.content);\n const key = `${String(index)}:${text}`;\n if (text && !state.seen.has(key)) {\n state.seen.add(key);\n state.bridge.customer(text);\n }\n return;\n }\n}\n\n/** A copy of the messages: the prefix as a part of the leading system message, the suffix as a part of the last user message. */\nfunction inject(messages: readonly MessageData[], prefix: string, suffix: string): MessageData[] {\n const result = [...messages];\n if (suffix) {\n for (let index = result.length - 1; index >= 0; index--) {\n const message = result[index];\n if (message?.role !== \"user\") continue;\n result[index] = { ...message, content: [...message.content, { text: suffix }] };\n break;\n }\n }\n if (prefix) {\n let position = 0;\n while (position < result.length && result[position]?.role === \"system\") position++;\n const system = result[position - 1];\n // Several providers read one system message only, so the pack joins yours.\n if (system) result[position - 1] = { ...system, content: [...system.content, { text: prefix }] };\n else result.unshift({ role: \"system\", content: [{ text: prefix }] });\n }\n return result;\n}\n\nfunction answerOf(response: GenerateResponseData): string {\n const message = response.message ?? response.candidates?.[0]?.message;\n if (!message || message.content.some((part) => \"toolRequest\" in part)) return \"\";\n return textParts(message.content);\n}\n\nfunction textParts(content: readonly Part[]): string {\n return content\n .map((part) => (typeof part.text === \"string\" ? part.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction parsed(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n}\n"]}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { ModelMiddleware } from 'genkit/model';
|
|
2
|
+
import { ToolAction } from 'genkit/tool';
|
|
3
|
+
import { f as ModelUsage } from './client-B_ip8T2o.cjs';
|
|
4
|
+
import { a as ProofSource, A as AgentMemoryOption, S as SessionResolver, b as Session } from './shared-DEkF2Y_z.cjs';
|
|
5
|
+
export { P as Proof, c as attestationProof } from './shared-DEkF2Y_z.cjs';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Niadra for Genkit (`genkit` 1.x, Firebase Genkit for JavaScript): a model middleware for
|
|
9
|
+
* `generate({ use })` and the navigation kit as Genkit tools.
|
|
10
|
+
*
|
|
11
|
+
* - `niadraMiddleware(session)` runs around every model call, the steps of a tool loop included:
|
|
12
|
+
* it records the customer's newest message once, adds the agent's notes and the customer's pack
|
|
13
|
+
* as a text part of your system message (a new system message when there is none), and adds the
|
|
14
|
+
* suffix (deltas and live turns) as a text part of the last user message. The answer is recorded
|
|
15
|
+
* as the agent's turn with Genkit's usage (input tokens and cached content tokens) when you name
|
|
16
|
+
* the model; steps that only request tools record nothing.
|
|
17
|
+
* - `niadraTools(session)` is the kit as Genkit tools (not registered, so each request can carry
|
|
18
|
+
* the tools bound to its own customer), with the canonical JSON Schemas.
|
|
19
|
+
*
|
|
20
|
+
* Fail-open: when Niadra is slow or down, the request goes to the model as it came.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* import { genkit } from "genkit";
|
|
24
|
+
* import { googleAI } from "@genkit-ai/google-genai";
|
|
25
|
+
* import { niadraMiddleware, niadraTools } from "@niadra/sdk/genkit";
|
|
26
|
+
*
|
|
27
|
+
* const ai = genkit({ plugins: [googleAI()] });
|
|
28
|
+
* const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: "web_chat", conversation_id: chatId });
|
|
29
|
+
* const { text } = await ai.generate({
|
|
30
|
+
* model: googleAI.model("gemini-2.5-flash"),
|
|
31
|
+
* system: "You are Acme's support agent.",
|
|
32
|
+
* messages: history,
|
|
33
|
+
* prompt: "Where is my replacement?",
|
|
34
|
+
* tools: niadraTools(convo),
|
|
35
|
+
* use: [niadraMiddleware(convo, { model: "googleai/gemini-2.5-flash" })],
|
|
36
|
+
* });
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
interface NiadraMiddlewareOptions {
|
|
40
|
+
/** What your app proved about the user, recorded once before the first context read. */
|
|
41
|
+
verify?: ProofSource;
|
|
42
|
+
/** Records the newest user message as the customer's turn. Defaults to `true`. */
|
|
43
|
+
recordCustomer?: boolean;
|
|
44
|
+
/** Records the model's answer as the agent's turn. Defaults to `true`. */
|
|
45
|
+
recordAgent?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* The model the request goes to, as Genkit names it (`googleai/gemini-2.5-flash`), for the usage
|
|
48
|
+
* of the agent's turn. A model middleware does not see the model's name; without it the turn is
|
|
49
|
+
* recorded without usage.
|
|
50
|
+
*/
|
|
51
|
+
model?: string;
|
|
52
|
+
/** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */
|
|
53
|
+
agentMemory?: AgentMemoryOption;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A Genkit model middleware bound to a conversation or task, or to a function that finds the one
|
|
57
|
+
* each call belongs to; when it returns `null`, the call passes through untouched.
|
|
58
|
+
*/
|
|
59
|
+
declare function niadraMiddleware(session: SessionResolver, options?: NiadraMiddlewareOptions): ModelMiddleware;
|
|
60
|
+
/** The navigation kit as Genkit tools, bound to the session's customer. */
|
|
61
|
+
declare function niadraTools(session: Session, options?: {
|
|
62
|
+
agentMemory?: AgentMemoryOption;
|
|
63
|
+
}): ToolAction[];
|
|
64
|
+
/** Genkit's usage as a `ModelUsage`: `inputTokens` counts the cached content tokens too. */
|
|
65
|
+
declare function genkitUsage(usage: unknown, model: string): ModelUsage | null;
|
|
66
|
+
|
|
67
|
+
export { AgentMemoryOption, type NiadraMiddlewareOptions, ProofSource, Session, SessionResolver, genkitUsage, niadraMiddleware, niadraTools };
|
package/dist/genkit.d.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { ModelMiddleware } from 'genkit/model';
|
|
2
|
+
import { ToolAction } from 'genkit/tool';
|
|
3
|
+
import { f as ModelUsage } from './client-B_ip8T2o.js';
|
|
4
|
+
import { a as ProofSource, A as AgentMemoryOption, S as SessionResolver, b as Session } from './shared-BLkAbvuf.js';
|
|
5
|
+
export { P as Proof, c as attestationProof } from './shared-BLkAbvuf.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Niadra for Genkit (`genkit` 1.x, Firebase Genkit for JavaScript): a model middleware for
|
|
9
|
+
* `generate({ use })` and the navigation kit as Genkit tools.
|
|
10
|
+
*
|
|
11
|
+
* - `niadraMiddleware(session)` runs around every model call, the steps of a tool loop included:
|
|
12
|
+
* it records the customer's newest message once, adds the agent's notes and the customer's pack
|
|
13
|
+
* as a text part of your system message (a new system message when there is none), and adds the
|
|
14
|
+
* suffix (deltas and live turns) as a text part of the last user message. The answer is recorded
|
|
15
|
+
* as the agent's turn with Genkit's usage (input tokens and cached content tokens) when you name
|
|
16
|
+
* the model; steps that only request tools record nothing.
|
|
17
|
+
* - `niadraTools(session)` is the kit as Genkit tools (not registered, so each request can carry
|
|
18
|
+
* the tools bound to its own customer), with the canonical JSON Schemas.
|
|
19
|
+
*
|
|
20
|
+
* Fail-open: when Niadra is slow or down, the request goes to the model as it came.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* import { genkit } from "genkit";
|
|
24
|
+
* import { googleAI } from "@genkit-ai/google-genai";
|
|
25
|
+
* import { niadraMiddleware, niadraTools } from "@niadra/sdk/genkit";
|
|
26
|
+
*
|
|
27
|
+
* const ai = genkit({ plugins: [googleAI()] });
|
|
28
|
+
* const convo = niadra.conversation({ subject: handles.appUserId(user.id), channel: "web_chat", conversation_id: chatId });
|
|
29
|
+
* const { text } = await ai.generate({
|
|
30
|
+
* model: googleAI.model("gemini-2.5-flash"),
|
|
31
|
+
* system: "You are Acme's support agent.",
|
|
32
|
+
* messages: history,
|
|
33
|
+
* prompt: "Where is my replacement?",
|
|
34
|
+
* tools: niadraTools(convo),
|
|
35
|
+
* use: [niadraMiddleware(convo, { model: "googleai/gemini-2.5-flash" })],
|
|
36
|
+
* });
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
interface NiadraMiddlewareOptions {
|
|
40
|
+
/** What your app proved about the user, recorded once before the first context read. */
|
|
41
|
+
verify?: ProofSource;
|
|
42
|
+
/** Records the newest user message as the customer's turn. Defaults to `true`. */
|
|
43
|
+
recordCustomer?: boolean;
|
|
44
|
+
/** Records the model's answer as the agent's turn. Defaults to `true`. */
|
|
45
|
+
recordAgent?: boolean;
|
|
46
|
+
/**
|
|
47
|
+
* The model the request goes to, as Genkit names it (`googleai/gemini-2.5-flash`), for the usage
|
|
48
|
+
* of the agent's turn. A model middleware does not see the model's name; without it the turn is
|
|
49
|
+
* recorded without usage.
|
|
50
|
+
*/
|
|
51
|
+
model?: string;
|
|
52
|
+
/** Puts the agent's own notes before the customer's context. Pass the same to `niadraTools`. */
|
|
53
|
+
agentMemory?: AgentMemoryOption;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A Genkit model middleware bound to a conversation or task, or to a function that finds the one
|
|
57
|
+
* each call belongs to; when it returns `null`, the call passes through untouched.
|
|
58
|
+
*/
|
|
59
|
+
declare function niadraMiddleware(session: SessionResolver, options?: NiadraMiddlewareOptions): ModelMiddleware;
|
|
60
|
+
/** The navigation kit as Genkit tools, bound to the session's customer. */
|
|
61
|
+
declare function niadraTools(session: Session, options?: {
|
|
62
|
+
agentMemory?: AgentMemoryOption;
|
|
63
|
+
}): ToolAction[];
|
|
64
|
+
/** Genkit's usage as a `ModelUsage`: `inputTokens` counts the cached content tokens too. */
|
|
65
|
+
declare function genkitUsage(usage: unknown, model: string): ModelUsage | null;
|
|
66
|
+
|
|
67
|
+
export { AgentMemoryOption, type NiadraMiddlewareOptions, ProofSource, Session, SessionResolver, genkitUsage, niadraMiddleware, niadraTools };
|
package/dist/genkit.js
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { tool } from 'genkit/tool';
|
|
2
|
+
|
|
3
|
+
// src/integrations/genkit.ts
|
|
4
|
+
|
|
5
|
+
// src/usage.ts
|
|
6
|
+
function get(value, name) {
|
|
7
|
+
return (typeof value === "object" || typeof value === "function") && value !== null ? value[name] : void 0;
|
|
8
|
+
}
|
|
9
|
+
function providerOf(model, usage) {
|
|
10
|
+
const slash = model.indexOf("/");
|
|
11
|
+
if (slash > 0) return model.slice(0, slash).trim().toLowerCase();
|
|
12
|
+
const name = model.trim().toLowerCase();
|
|
13
|
+
if (name.startsWith("claude") || `.${name}`.includes(".anthropic.")) return "anthropic";
|
|
14
|
+
if (name.startsWith("gemini")) return "google";
|
|
15
|
+
if (get(usage, "prompt_tokens") === void 0 && get(usage, "cache_read_input_tokens") !== void 0) {
|
|
16
|
+
return "anthropic";
|
|
17
|
+
}
|
|
18
|
+
return "openai";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// src/context.ts
|
|
22
|
+
function emptyResult(error) {
|
|
23
|
+
return { text: "", suffix: "", variables: {}, pack: null, source: "none", ageMs: null, response: null, error, constraints: null, state: null, coordination: null };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/integrations/shared.ts
|
|
27
|
+
var ATTESTED = { A: "V2", B: "V1", C: "V1" };
|
|
28
|
+
function attestationProof(attestation) {
|
|
29
|
+
if (!attestation) return null;
|
|
30
|
+
const value = attestation.trim().toUpperCase();
|
|
31
|
+
if (value.includes("FAILED") || value.startsWith("NO-")) return null;
|
|
32
|
+
const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];
|
|
33
|
+
const level = letter ? ATTESTED[letter] : void 0;
|
|
34
|
+
return level ? { method: "network_attestation", level } : null;
|
|
35
|
+
}
|
|
36
|
+
function resolveSession(source) {
|
|
37
|
+
if (typeof source !== "function") return source;
|
|
38
|
+
try {
|
|
39
|
+
return source() ?? null;
|
|
40
|
+
} catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function isConversation(session) {
|
|
45
|
+
return "customer" in session && typeof session.customer === "function";
|
|
46
|
+
}
|
|
47
|
+
function errorName(error) {
|
|
48
|
+
return error instanceof Error ? error.name : typeof error;
|
|
49
|
+
}
|
|
50
|
+
var Bridge = class {
|
|
51
|
+
constructor(session, proof, memory = false) {
|
|
52
|
+
this.session = session;
|
|
53
|
+
this.proof = proof;
|
|
54
|
+
this.memory = memory;
|
|
55
|
+
}
|
|
56
|
+
session;
|
|
57
|
+
proof;
|
|
58
|
+
memory;
|
|
59
|
+
proving = null;
|
|
60
|
+
/** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */
|
|
61
|
+
begun = false;
|
|
62
|
+
opened = false;
|
|
63
|
+
/**
|
|
64
|
+
* The context and, when enabled, the agent's notes, read side by side within the same budget.
|
|
65
|
+
* Never rejects.
|
|
66
|
+
*/
|
|
67
|
+
async read(options = {}) {
|
|
68
|
+
const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);
|
|
69
|
+
const [context, memory] = await Promise.all([
|
|
70
|
+
this.context(options),
|
|
71
|
+
memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve("")
|
|
72
|
+
]);
|
|
73
|
+
return { context, memory, prefix: [memory, context.text].filter(Boolean).join("\n\n"), suffix: context.suffix };
|
|
74
|
+
}
|
|
75
|
+
get logger() {
|
|
76
|
+
return this.session.logger;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Starts the first read of a call now, in the background, after the proof when one was given (the
|
|
80
|
+
* pack depends on the level it proves): at call start, so the read runs while the call is set up.
|
|
81
|
+
* The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.
|
|
82
|
+
*/
|
|
83
|
+
begin() {
|
|
84
|
+
const session = this.session;
|
|
85
|
+
if (!isConversation(session)) return;
|
|
86
|
+
const start = () => {
|
|
87
|
+
this.safe("start the first read", () => {
|
|
88
|
+
this.begun = session.begin();
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
if (this.proof === void 0 || this.proof === null) start();
|
|
92
|
+
else void this.verifyOnce().then(start);
|
|
93
|
+
}
|
|
94
|
+
/** Verifies once (when a proof was given), then reads the context. Never rejects. */
|
|
95
|
+
async context(options = {}) {
|
|
96
|
+
await this.verifyOnce();
|
|
97
|
+
try {
|
|
98
|
+
const session = this.session;
|
|
99
|
+
if (this.begun && !this.opened && isConversation(session)) {
|
|
100
|
+
this.opened = true;
|
|
101
|
+
await session.ready(options.timeout === void 0 ? {} : { timeout: options.timeout });
|
|
102
|
+
}
|
|
103
|
+
return await this.session.context(options);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
this.logger.warn(`could not read context (${errorName(error)})`);
|
|
106
|
+
return emptyResult(null);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */
|
|
110
|
+
injected(context) {
|
|
111
|
+
if (!context.text && !context.suffix && context.response?.path !== "holdout") return;
|
|
112
|
+
this.safe("mark the injection", () => {
|
|
113
|
+
this.session.markInjected(context);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
customer(text, options = {}) {
|
|
117
|
+
const session = this.session;
|
|
118
|
+
if (!text.trim() || !isConversation(session)) return;
|
|
119
|
+
this.safe("record the customer's turn", () => session.customer(text, options));
|
|
120
|
+
}
|
|
121
|
+
/** Sends the customer's turn so far, while they speak. In the background; never throws. */
|
|
122
|
+
prefetch(text) {
|
|
123
|
+
const session = this.session;
|
|
124
|
+
if (!text.trim() || !isConversation(session)) return;
|
|
125
|
+
this.safe("prefetch the turn", () => session.prefetch(text));
|
|
126
|
+
}
|
|
127
|
+
agent(text, options = {}) {
|
|
128
|
+
if (!text.trim()) return;
|
|
129
|
+
this.safe("record the agent's turn", () => this.session.agent(text, options));
|
|
130
|
+
}
|
|
131
|
+
/** Records a transfer. Tasks have no transfer; the call is ignored for them. */
|
|
132
|
+
async handoff(target, reason) {
|
|
133
|
+
const session = this.session;
|
|
134
|
+
if (!isConversation(session)) return;
|
|
135
|
+
try {
|
|
136
|
+
await session.handoff(reason ? { target, reason } : { target });
|
|
137
|
+
} catch (error) {
|
|
138
|
+
this.logger.warn(`could not record the handoff (${errorName(error)})`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async end() {
|
|
142
|
+
try {
|
|
143
|
+
await this.session.end();
|
|
144
|
+
} catch (error) {
|
|
145
|
+
this.logger.warn(`could not end the session (${errorName(error)})`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */
|
|
149
|
+
tools() {
|
|
150
|
+
let bound;
|
|
151
|
+
try {
|
|
152
|
+
const memory = this.memory;
|
|
153
|
+
bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });
|
|
154
|
+
} catch (error) {
|
|
155
|
+
this.logger.warn(`could not build the tools (${errorName(error)})`);
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
return bound ? toolSpecs(bound) : [];
|
|
159
|
+
}
|
|
160
|
+
async agentMemory(params, options) {
|
|
161
|
+
try {
|
|
162
|
+
const result = await this.session.agentMemory(params, options.timeout === void 0 ? {} : { timeout: options.timeout });
|
|
163
|
+
return result.text;
|
|
164
|
+
} catch (error) {
|
|
165
|
+
this.logger.warn(`could not read the agent's memory (${errorName(error)})`);
|
|
166
|
+
return "";
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async verifyOnce() {
|
|
170
|
+
if (this.proof === void 0 || this.proof === null) return;
|
|
171
|
+
this.proving ??= this.runVerify();
|
|
172
|
+
await this.proving;
|
|
173
|
+
}
|
|
174
|
+
async runVerify() {
|
|
175
|
+
try {
|
|
176
|
+
const source = this.proof;
|
|
177
|
+
const proof = typeof source === "function" ? await source() : source;
|
|
178
|
+
if (!proof) return;
|
|
179
|
+
await this.session.verify(proof);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
this.logger.warn(`could not record the verification (${errorName(error)})`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
safe(what, run) {
|
|
185
|
+
try {
|
|
186
|
+
run();
|
|
187
|
+
} catch (error) {
|
|
188
|
+
this.logger.warn(`could not ${what} (${errorName(error)})`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
function withoutWrite(option) {
|
|
193
|
+
const { write: _, ...params } = option;
|
|
194
|
+
return params;
|
|
195
|
+
}
|
|
196
|
+
function toolSpecs(bound) {
|
|
197
|
+
return bound.definitions.map(({ function: definition }) => ({
|
|
198
|
+
name: definition.name,
|
|
199
|
+
description: definition.description,
|
|
200
|
+
parameters: definition.parameters,
|
|
201
|
+
execute: (args) => bound.call(definition.name, args)
|
|
202
|
+
}));
|
|
203
|
+
}
|
|
204
|
+
function isRecord(value) {
|
|
205
|
+
return typeof value === "object" && value !== null;
|
|
206
|
+
}
|
|
207
|
+
function count(value) {
|
|
208
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/integrations/genkit.ts
|
|
212
|
+
function niadraMiddleware(session, options = {}) {
|
|
213
|
+
const states = /* @__PURE__ */ new WeakMap();
|
|
214
|
+
const stateOf = () => {
|
|
215
|
+
const current = resolveSession(session);
|
|
216
|
+
if (!current) return null;
|
|
217
|
+
let state = states.get(current);
|
|
218
|
+
if (!state) {
|
|
219
|
+
state = { bridge: new Bridge(current, options.verify, options.agentMemory), seen: /* @__PURE__ */ new Set() };
|
|
220
|
+
states.set(current, state);
|
|
221
|
+
}
|
|
222
|
+
return state;
|
|
223
|
+
};
|
|
224
|
+
return async (request, next) => {
|
|
225
|
+
const state = stateOf();
|
|
226
|
+
if (!state) return next(request);
|
|
227
|
+
let prepared = request;
|
|
228
|
+
try {
|
|
229
|
+
if (options.recordCustomer ?? true) recordNewest(state, request.messages);
|
|
230
|
+
const read = await state.bridge.read();
|
|
231
|
+
state.bridge.injected(read.context);
|
|
232
|
+
prepared = { ...request, messages: inject(request.messages, read.prefix, read.suffix) };
|
|
233
|
+
} catch (error) {
|
|
234
|
+
state.bridge.logger.warn(`could not inject context (${errorName(error)})`);
|
|
235
|
+
}
|
|
236
|
+
const response = await next(prepared);
|
|
237
|
+
if (options.recordAgent ?? true) {
|
|
238
|
+
try {
|
|
239
|
+
const answer = answerOf(response);
|
|
240
|
+
if (answer) {
|
|
241
|
+
const usage = options.model ? genkitUsage(response.usage, options.model) : null;
|
|
242
|
+
state.bridge.agent(answer, usage ? { usage } : {});
|
|
243
|
+
}
|
|
244
|
+
} catch (error) {
|
|
245
|
+
state.bridge.logger.warn(`could not record the agent's answer (${errorName(error)})`);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return response;
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function niadraTools(session, options = {}) {
|
|
252
|
+
return new Bridge(session, void 0, options.agentMemory).tools().map(
|
|
253
|
+
(spec) => tool(
|
|
254
|
+
{ name: spec.name, description: spec.description, inputJsonSchema: spec.parameters, outputJsonSchema: {} },
|
|
255
|
+
async (input) => parsed(await spec.execute(isRecord(input) ? input : {}))
|
|
256
|
+
)
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
function genkitUsage(usage, model) {
|
|
260
|
+
if (!isRecord(usage)) return null;
|
|
261
|
+
const prompt = count(usage.inputTokens);
|
|
262
|
+
if (prompt === null) return null;
|
|
263
|
+
const cached = count(usage.cachedContentTokens) ?? 0;
|
|
264
|
+
const slash = model.indexOf("/");
|
|
265
|
+
const name = slash > 0 ? model.slice(slash + 1) : model;
|
|
266
|
+
return { provider: providerOf(model, usage), model: name, prompt_tokens: Math.max(prompt, cached), cached_tokens: cached, cache_write_tokens: 0 };
|
|
267
|
+
}
|
|
268
|
+
function recordNewest(state, messages) {
|
|
269
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
270
|
+
const message = messages[index];
|
|
271
|
+
if (message?.role !== "user") continue;
|
|
272
|
+
const text = textParts(message.content);
|
|
273
|
+
const key = `${String(index)}:${text}`;
|
|
274
|
+
if (text && !state.seen.has(key)) {
|
|
275
|
+
state.seen.add(key);
|
|
276
|
+
state.bridge.customer(text);
|
|
277
|
+
}
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
function inject(messages, prefix, suffix) {
|
|
282
|
+
const result = [...messages];
|
|
283
|
+
if (suffix) {
|
|
284
|
+
for (let index = result.length - 1; index >= 0; index--) {
|
|
285
|
+
const message = result[index];
|
|
286
|
+
if (message?.role !== "user") continue;
|
|
287
|
+
result[index] = { ...message, content: [...message.content, { text: suffix }] };
|
|
288
|
+
break;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (prefix) {
|
|
292
|
+
let position = 0;
|
|
293
|
+
while (position < result.length && result[position]?.role === "system") position++;
|
|
294
|
+
const system = result[position - 1];
|
|
295
|
+
if (system) result[position - 1] = { ...system, content: [...system.content, { text: prefix }] };
|
|
296
|
+
else result.unshift({ role: "system", content: [{ text: prefix }] });
|
|
297
|
+
}
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
function answerOf(response) {
|
|
301
|
+
const message = response.message ?? response.candidates?.[0]?.message;
|
|
302
|
+
if (!message || message.content.some((part) => "toolRequest" in part)) return "";
|
|
303
|
+
return textParts(message.content);
|
|
304
|
+
}
|
|
305
|
+
function textParts(content) {
|
|
306
|
+
return content.map((part) => typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
|
|
307
|
+
}
|
|
308
|
+
function parsed(text) {
|
|
309
|
+
try {
|
|
310
|
+
return JSON.parse(text);
|
|
311
|
+
} catch {
|
|
312
|
+
return text;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export { attestationProof, genkitUsage, niadraMiddleware, niadraTools };
|
|
317
|
+
//# sourceMappingURL=genkit.js.map
|
|
318
|
+
//# sourceMappingURL=genkit.js.map
|