@niadra/sdk 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +160 -68
  2. package/README.md +451 -22
  3. package/dist/ai-sdk.cjs +1037 -0
  4. package/dist/ai-sdk.cjs.map +1 -0
  5. package/dist/ai-sdk.d.cts +118 -0
  6. package/dist/ai-sdk.d.ts +118 -0
  7. package/dist/ai-sdk.js +1030 -0
  8. package/dist/ai-sdk.js.map +1 -0
  9. package/dist/anthropic.cjs +528 -0
  10. package/dist/anthropic.cjs.map +1 -0
  11. package/dist/anthropic.d.cts +35 -0
  12. package/dist/anthropic.d.ts +35 -0
  13. package/dist/anthropic.js +523 -0
  14. package/dist/anthropic.js.map +1 -0
  15. package/dist/bedrock.cjs +392 -0
  16. package/dist/bedrock.cjs.map +1 -0
  17. package/dist/bedrock.d.cts +25 -0
  18. package/dist/bedrock.d.ts +25 -0
  19. package/dist/bedrock.js +388 -0
  20. package/dist/bedrock.js.map +1 -0
  21. package/dist/cli.js +11045 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/client-DsIxZxZk.d.cts +6905 -0
  24. package/dist/client-DsIxZxZk.d.ts +6905 -0
  25. package/dist/cloudflare-agents.cjs +626 -0
  26. package/dist/cloudflare-agents.cjs.map +1 -0
  27. package/dist/cloudflare-agents.d.cts +113 -0
  28. package/dist/cloudflare-agents.d.ts +113 -0
  29. package/dist/cloudflare-agents.js +622 -0
  30. package/dist/cloudflare-agents.js.map +1 -0
  31. package/dist/elevenlabs.cjs +738 -0
  32. package/dist/elevenlabs.cjs.map +1 -0
  33. package/dist/elevenlabs.d.cts +86 -0
  34. package/dist/elevenlabs.d.ts +86 -0
  35. package/dist/elevenlabs.js +733 -0
  36. package/dist/elevenlabs.js.map +1 -0
  37. package/dist/genkit.cjs +323 -0
  38. package/dist/genkit.cjs.map +1 -0
  39. package/dist/genkit.d.cts +67 -0
  40. package/dist/genkit.d.ts +67 -0
  41. package/dist/genkit.js +318 -0
  42. package/dist/genkit.js.map +1 -0
  43. package/dist/google-adk.cjs +705 -0
  44. package/dist/google-adk.cjs.map +1 -0
  45. package/dist/google-adk.d.cts +91 -0
  46. package/dist/google-adk.d.ts +91 -0
  47. package/dist/google-adk.js +701 -0
  48. package/dist/google-adk.js.map +1 -0
  49. package/dist/google-genai.cjs +422 -0
  50. package/dist/google-genai.cjs.map +1 -0
  51. package/dist/google-genai.d.cts +26 -0
  52. package/dist/google-genai.d.ts +26 -0
  53. package/dist/google-genai.js +418 -0
  54. package/dist/google-genai.js.map +1 -0
  55. package/dist/index.cjs +11421 -1895
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +959 -1294
  58. package/dist/index.d.ts +959 -1294
  59. package/dist/index.js +11368 -1896
  60. package/dist/index.js.map +1 -1
  61. package/dist/intercept-0_lJE6k1.d.cts +20 -0
  62. package/dist/intercept-D7qFCaRb.d.ts +20 -0
  63. package/dist/langchain.cjs +1077 -0
  64. package/dist/langchain.cjs.map +1 -0
  65. package/dist/langchain.d.cts +102 -0
  66. package/dist/langchain.d.ts +102 -0
  67. package/dist/langchain.js +1068 -0
  68. package/dist/langchain.js.map +1 -0
  69. package/dist/livekit.cjs +404 -0
  70. package/dist/livekit.cjs.map +1 -0
  71. package/dist/livekit.d.cts +113 -0
  72. package/dist/livekit.d.ts +113 -0
  73. package/dist/livekit.js +398 -0
  74. package/dist/livekit.js.map +1 -0
  75. package/dist/llamaindex.cjs +349 -0
  76. package/dist/llamaindex.cjs.map +1 -0
  77. package/dist/llamaindex.d.cts +92 -0
  78. package/dist/llamaindex.d.ts +92 -0
  79. package/dist/llamaindex.js +344 -0
  80. package/dist/llamaindex.js.map +1 -0
  81. package/dist/mastra.cjs +1082 -0
  82. package/dist/mastra.cjs.map +1 -0
  83. package/dist/mastra.d.cts +86 -0
  84. package/dist/mastra.d.ts +86 -0
  85. package/dist/mastra.js +1075 -0
  86. package/dist/mastra.js.map +1 -0
  87. package/dist/openai-agents.cjs +465 -0
  88. package/dist/openai-agents.cjs.map +1 -0
  89. package/dist/openai-agents.d.cts +75 -0
  90. package/dist/openai-agents.d.ts +75 -0
  91. package/dist/openai-agents.js +459 -0
  92. package/dist/openai-agents.js.map +1 -0
  93. package/dist/retell.cjs +846 -0
  94. package/dist/retell.cjs.map +1 -0
  95. package/dist/retell.d.cts +161 -0
  96. package/dist/retell.d.ts +161 -0
  97. package/dist/retell.js +841 -0
  98. package/dist/retell.js.map +1 -0
  99. package/dist/shared-Bb5B59Bu.d.ts +39 -0
  100. package/dist/shared-DTPWVlWm.d.cts +39 -0
  101. package/dist/strands.cjs +352 -0
  102. package/dist/strands.cjs.map +1 -0
  103. package/dist/strands.d.cts +72 -0
  104. package/dist/strands.d.ts +72 -0
  105. package/dist/strands.js +347 -0
  106. package/dist/strands.js.map +1 -0
  107. package/dist/twilio.cjs +174 -0
  108. package/dist/twilio.cjs.map +1 -0
  109. package/dist/twilio.d.cts +64 -0
  110. package/dist/twilio.d.ts +64 -0
  111. package/dist/twilio.js +167 -0
  112. package/dist/twilio.js.map +1 -0
  113. package/dist/vapi.cjs +661 -0
  114. package/dist/vapi.cjs.map +1 -0
  115. package/dist/vapi.d.cts +78 -0
  116. package/dist/vapi.d.ts +78 -0
  117. package/dist/vapi.js +656 -0
  118. package/dist/vapi.js.map +1 -0
  119. package/dist/voltagent.cjs +509 -0
  120. package/dist/voltagent.cjs.map +1 -0
  121. package/dist/voltagent.d.cts +70 -0
  122. package/dist/voltagent.d.ts +70 -0
  123. package/dist/voltagent.js +503 -0
  124. package/dist/voltagent.js.map +1 -0
  125. package/dist/webhook-1ozGyksG.d.ts +37 -0
  126. package/dist/webhook-CG4om_DK.d.cts +37 -0
  127. package/dist/whatsapp.cjs +214 -0
  128. package/dist/whatsapp.cjs.map +1 -0
  129. package/dist/whatsapp.d.cts +81 -0
  130. package/dist/whatsapp.d.ts +81 -0
  131. package/dist/whatsapp.js +207 -0
  132. package/dist/whatsapp.js.map +1 -0
  133. package/package.json +351 -6
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools.ts","../src/usage.ts","../src/capture/tool.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/google-adk.ts"],"names":["BaseTool"],"mappings":";;;;;;;AAmGO,IAAM,gBAAA,GAA8C;AAAA,EACzD;AAAA,IACE,MAAA,EAAQ,UAAA;AAAA,IACR,UAAA,EAAY;AAAA,MACV,MAAA,EAAQ,yBAAA;AAAA,MACR,aAAA,EAAe,qdAAA;AAAA,MACf,YAAA,EAAc;AAAA,QACZ,MAAA,EAAQ,QAAA;AAAA,QACR,YAAA,EAAc;AAAA,UACZ,OAAA,EAAS;AAAA,YACP,MAAA,EAAQ,QAAA;AAAA,YACR,aAAA,EAAe;AAAA,WACjB;AAAA,UACA,SAAA,EAAW;AAAA,YACT,MAAA,EAAQ,QAAA;AAAA,YACR,YAAA,EAAc;AAAA,cACZ,OAAA,EAAS;AAAA,gBACP,MAAA,EAAQ,QAAA;AAAA,gBACR,QAAA,EAAU;AAAA,eACZ;AAAA,cACA,OAAA,EAAS;AAAA,gBACP,MAAA,EAAQ,QAAA;AAAA,gBACR,QAAA,EAAU;AAAA,eACZ;AAAA,cACA,MAAA,EAAQ;AAAA,gBACN,MAAA,EAAQ,QAAA;AAAA,gBACR,aAAA,EAAe;AAAA,eACjB;AAAA,cACA,UAAA,EAAY;AAAA,gBACV,MAAA,EAAQ,OAAA;AAAA,gBACR,OAAA,EAAS;AAAA,kBACP,MAAA,EAAQ;AAAA;AACV,eACF;AAAA,cACA,YAAA,EAAc;AAAA,gBACZ,MAAA,EAAQ,OAAA;AAAA,gBACR,OAAA,EAAS;AAAA,kBACP,MAAA,EAAQ;AAAA;AACV,eACF;AAAA,cACA,YAAA,EAAc;AAAA,gBACZ,MAAA,EAAQ,OAAA;AAAA,gBACR,OAAA,EAAS;AAAA,kBACP,MAAA,EAAQ;AAAA,oBACN,SAAA;AAAA,oB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AEA,SAAS,WAAA,CAAY,KAAA,EAAgB,SAAA,GAAY,IAAA,EAAc;AAC7D,EAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,GAAG,OAAO,EAAA;AAClC,EAAA,OAAQ,KAAA,CACL,IAAI,CAAC,IAAA,KAAU,SAAS,IAAI,CAAA,IAAK,OAAO,IAAA,CAAK,IAAA,KAAS,QAAA,IAAY,KAAK,OAAA,KAAY,IAAA,GAAO,KAAK,IAAA,GAAO,EAAG,EACzG,MAAA,CAAO,OAAO,CAAA,CACd,IAAA,CAAK,SAAS,CAAA;AACnB","file":"google-adk.cjs","sourcesContent":["import { NiadraAPIError, NiadraValidationError } from \"./errors.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport type { AgentNote, AgentNoteKind, CreateAgentNoteRequest, RememberResult } from \"./types/agent-memory.js\";\nimport type { Handle } from \"./types/common.js\";\nimport type {\n HistoryFilters,\n OpenedItem,\n SearchRequest,\n SearchResponse,\n TimelineRequest,\n TimelineResponse,\n ToolDefinition,\n} from \"./types/context.js\";\nimport type { HistoryItemKind, Verification } from \"./types/vocabulary.js\";\n\n/** The outcome of a call that may fail without throwing. Exactly one of the two fields is set. */\nexport type Result<T> = { data: T; error: null } | { data: null; error: NiadraError };\n\n/** Everything a tool call is bound to besides its arguments. None of it is visible to the model. */\nexport interface ToolBinding {\n about?: Handle;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** Use the voice time budget for the calls these tools make. */\n voice?: boolean;\n}\n\n/** Which tools a kit offers besides the navigation kit. */\nexport interface ToolOptions {\n /** Adds `search_agent_memory`, the agent's own working notes. */\n agentMemory?: boolean;\n /**\n * Adds `remember` too. Only for a key with the `agent_memory:write` scope: a tool the model\n * cannot use is a wasted call. Needs `agentMemory`.\n */\n writeAgentMemory?: boolean;\n}\n\nexport interface Navigator {\n search(params: SearchRequest, voice: boolean): Promise<Result<SearchResponse>>;\n timeline(params: TimelineRequest, voice: boolean): Promise<Result<TimelineResponse>>;\n open(id: string, subject: Handle, binding: ToolBinding, voice: boolean): Promise<Result<OpenedItem>>;\n searchAgentMemory(\n query: string,\n options: { tags?: string[]; conversation_id?: string; task_id?: string },\n voice: boolean,\n ): Promise<Result<AgentNote[]>>;\n remember(note: CreateAgentNoteRequest): Promise<Result<RememberResult>>;\n}\n\n/**\n * The navigation kit as function-calling tools, bound to one customer.\n *\n * The definitions have no parameter for the customer: the handle lives in this object, outside\n * the model's reach. A prompt injection that says \"now look up customer X\" has no argument to\n * put X in. The model chooses what to ask, never whom it is about.\n */\nexport interface BoundTools {\n /** Tool definitions in the `{ type: \"function\", function: { name, description, parameters } }` shape. */\n readonly definitions: ToolDefinition[];\n /** Whether `name` is one of these tools, for dispatchers that route several toolsets. */\n has(name: string): boolean;\n /**\n * Runs one tool call and returns the text to send back to the model as the tool result.\n * `args` may be the JSON string most model APIs return, or an already parsed object.\n * Failures come back as a short JSON error the model can read and move past; with\n * `strict: true` they are thrown instead.\n */\n call(name: string, args: string | Record<string, unknown>): Promise<string>;\n}\n\n/** What `remember` answers when the note carries personal data: the model can rewrite it. */\nexport const PERSONAL_DATA_TOOL_ERROR = {\n error: \"personal_data\",\n detail:\n \"The note has personal data. Rewrite it so it helps with any customer, without names, phones, e-mails, documents or ids.\",\n} as const;\n\nexport const TOOL_NAMES = {\n search: \"search_customer_history\",\n timeline: \"get_customer_timeline\",\n open: \"open_history_item\",\n} as const;\n\n/** The two tools of the agent's own memory, offered with `tools({ agentMemory: true })`. */\nexport const AGENT_MEMORY_TOOL_NAMES = {\n search: \"search_agent_memory\",\n remember: \"remember\",\n} as const;\n\nconst ITEM_KINDS: HistoryItemKind[] = [\"episode\", \"fact\", \"open_item\", \"action\", \"object\", \"trait\"];\nconst NOTE_KINDS: AgentNoteKind[] = [\"procedure\", \"tool_note\", \"process_note\", \"pitfall\"];\n\n/**\n * The navigation kit, word for word the server's canonical definitions (`GET /v1/history/tools`)\n * and the Python SDK's: a model sees one toolset whatever language the agent is written in. The\n * server names the context's history line in the space's language; the SDKs ship its default.\n */\nexport const TOOL_DEFINITIONS: readonly ToolDefinition[] = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"search_customer_history\",\n \"description\": \"Search everything that already happened with this customer: past conversations, promises, agent actions, orders and invoices. Use it when the customer refers to something earlier or asks whether a problem happened before. Do not call it when the answer is already in the context block, including its 'Do histórico' line, which already counts recurrences. Returns short items with date, channel and outcome, plus a recurrence count. Open one with open_history_item.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"query\": {\n \"type\": \"string\",\n \"description\": \"What to look for, in the customer's words.\"\n },\n \"filters\": {\n \"type\": \"object\",\n \"properties\": {\n \"since\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"until\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"when\": {\n \"type\": \"string\",\n \"description\": \"The period in the customer's own words, as they said it: 'last week', 'semana passada', 'en marzo'.\"\n },\n \"channels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"categories\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"item_kinds\": {\n \"type\": \"array\",\n \"items\": {\n \"enum\": [\n \"episode\",\n \"fact\",\n \"open_item\",\n \"action\",\n \"object\",\n \"trait\"\n ]\n }\n },\n \"outcome\": {\n \"type\": \"string\"\n }\n },\n \"additionalProperties\": false\n },\n \"max_tokens\": {\n \"type\": \"integer\",\n \"minimum\": 50,\n \"maximum\": 4000\n }\n },\n \"required\": [\n \"query\"\n ],\n \"additionalProperties\": false\n }\n }\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_customer_timeline\",\n \"description\": \"List this customer's conversations and agent actions in order, newest first, one line each. Use it to leaf through the history when you do not know what to search for. Pass next_cursor to continue. Prefer search_customer_history for a specific question.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"cursor\": {\n \"type\": \"string\"\n },\n \"limit\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 100\n },\n \"filters\": {\n \"type\": \"object\",\n \"properties\": {\n \"since\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"until\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"when\": {\n \"type\": \"string\",\n \"description\": \"The period in the customer's own words, as they said it: 'last week', 'semana passada', 'en marzo'.\"\n },\n \"channels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"categories\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"item_kinds\": {\n \"type\": \"array\",\n \"items\": {\n \"enum\": [\n \"episode\",\n \"fact\",\n \"open_item\",\n \"action\",\n \"object\",\n \"trait\"\n ]\n }\n },\n \"outcome\": {\n \"type\": \"string\"\n }\n },\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n }\n }\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"open_history_item\",\n \"description\": \"Open one conversation or business object returned by search_customer_history or get_customer_timeline: what was asked, what was promised and by whom, the outcome and what memory came from it. Use it only after a search or timeline pointed to the item.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"The item id, e.g. `episode:...`.\"\n }\n },\n \"required\": [\n \"id\"\n ],\n \"additionalProperties\": false\n }\n }\n }\n] as ToolDefinition[];\n\n/**\n * `search_agent_memory` and `remember`, word for word the server's canonical definitions. They\n * read and write the agent's working notes, never anything about a customer.\n */\nexport const AGENT_MEMORY_TOOL_DEFINITIONS: readonly ToolDefinition[] = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"search_agent_memory\",\n \"description\": \"Search your own working notes: procedures, how the company's tools and processes behave, and known pitfalls. Use it before a task or a tool call you are unsure how to do. It holds nothing about customers; for the customer's history use search_customer_history.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"query\": {\n \"type\": \"string\",\n \"description\": \"What you need to know how to do.\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"maxItems\": 8,\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9][a-z0-9_.:-]{0,63}$\"\n },\n \"description\": \"Object types, operations or systems, e.g. `invoice`, `credit`, `erp`.\"\n }\n },\n \"required\": [\n \"query\"\n ],\n \"additionalProperties\": false\n }\n }\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"remember\",\n \"description\": \"Save a working note for yourself and future runs: a procedure that worked, how a tool or process behaves, or a pitfall to avoid. Never write anything about a customer here: no names, phones, e-mails, documents, ids or words from the conversation. A note with personal data is refused. Write it so it helps with any customer.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"kind\": {\n \"enum\": [\n \"procedure\",\n \"tool_note\",\n \"process_note\",\n \"pitfall\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"maxLength\": 120\n },\n \"body\": {\n \"type\": \"string\",\n \"maxLength\": 2000\n },\n \"tags\": {\n \"type\": \"array\",\n \"maxItems\": 8,\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9][a-z0-9_.:-]{0,63}$\"\n },\n \"description\": \"Object types, operations or systems, e.g. `invoice`, `credit`, `erp`.\"\n }\n },\n \"required\": [\n \"kind\",\n \"title\",\n \"body\"\n ],\n \"additionalProperties\": false\n }\n }\n }\n] as ToolDefinition[];\n\nfunction parseArgs(args: string | Record<string, unknown>): Record<string, unknown> {\n if (typeof args !== \"string\") return args;\n if (args.trim() === \"\") return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(args);\n } catch {\n throw new NiadraValidationError(\"tool arguments are not valid JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new NiadraValidationError(\"tool arguments must be a JSON object\");\n }\n return parsed as Record<string, unknown>;\n}\n\nfunction str(args: Record<string, unknown>, name: string): string | undefined {\n const value = args[name];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction strings(args: Record<string, unknown>, name: string): string[] | undefined {\n const value = args[name];\n if (!Array.isArray(value)) return undefined;\n const list = value.filter((entry): entry is string => typeof entry === \"string\");\n return list.length > 0 ? list : undefined;\n}\n\nfunction int(args: Record<string, unknown>, name: string): number | undefined {\n const value = args[name];\n return typeof value === \"number\" && Number.isInteger(value) ? value : undefined;\n}\n\n/** The filters of a call: the `filters` object of the canonical definitions. */\nfunction filtersFrom(args: Record<string, unknown>): HistoryFilters {\n const nested = args.filters;\n const source: Record<string, unknown> =\n typeof nested === \"object\" && nested !== null && !Array.isArray(nested) ? (nested as Record<string, unknown>) : {};\n const filters: HistoryFilters = {};\n const since = str(source, \"since\");\n const until = str(source, \"until\");\n const when = str(source, \"when\");\n const channels = strings(source, \"channels\");\n const categories = strings(source, \"categories\");\n const kinds = strings(source, \"item_kinds\")\n ?.filter((kind): kind is HistoryItemKind => (ITEM_KINDS as string[]).includes(kind));\n const outcome = str(source, \"outcome\");\n if (since) filters.since = since;\n if (until) filters.until = until;\n if (when) filters.when = when.slice(0, 100);\n if (channels) filters.channels = channels;\n if (categories) filters.categories = categories;\n if (kinds?.length) filters.item_kinds = [...new Set(kinds)];\n if (outcome) filters.outcome = outcome;\n return filters;\n}\n\nfunction tagsFrom(args: Record<string, unknown>): string[] | undefined {\n return strings(args, \"tags\")?.slice(0, 8);\n}\n\n/** Builds the bound toolset. `strict` decides whether failures are thrown or described to the model. */\nexport function bindTools(\n subject: Handle,\n binding: ToolBinding,\n navigator: Navigator,\n strict: boolean,\n options: ToolOptions = {},\n): BoundTools {\n const voice = binding.voice ?? false;\n const memory = options.agentMemory ? AGENT_MEMORY_TOOL_DEFINITIONS.slice(0, options.writeAgentMemory ? 2 : 1) : [];\n const definitions: ToolDefinition[] = [...TOOL_DEFINITIONS, ...memory];\n const names = new Set(definitions.map((definition) => definition.function.name));\n\n async function run(name: string, args: Record<string, unknown>): Promise<Result<unknown>> {\n switch (name) {\n case TOOL_NAMES.search: {\n const query = str(args, \"query\");\n if (!query) throw new NiadraValidationError(\"search_customer_history needs a query\");\n const request: SearchRequest = { subject, query, filters: filtersFrom(args) };\n applyBinding(request, binding);\n if (binding.task_id) request.task_id = binding.task_id;\n const maxTokens = int(args, \"max_tokens\");\n if (maxTokens !== undefined) request.max_tokens = Math.min(4000, Math.max(50, maxTokens));\n const result = await navigator.search(request, voice);\n return result.error ? result : { data: compactSearch(result.data), error: null };\n }\n case TOOL_NAMES.timeline: {\n const request: TimelineRequest = { subject, filters: filtersFrom(args) };\n applyBinding(request, binding);\n const cursor = str(args, \"cursor\");\n if (cursor) request.cursor = cursor;\n const limit = int(args, \"limit\");\n if (limit !== undefined) request.limit = Math.min(100, Math.max(1, limit));\n return navigator.timeline(request, voice);\n }\n case TOOL_NAMES.open: {\n const id = str(args, \"id\");\n if (!id) throw new NiadraValidationError(\"open_history_item needs an id\");\n return navigator.open(id, subject, binding, voice);\n }\n case AGENT_MEMORY_TOOL_NAMES.search: {\n const query = str(args, \"query\");\n if (!query) throw new NiadraValidationError(\"search_agent_memory needs a query\");\n const scope: { tags?: string[]; conversation_id?: string; task_id?: string } = {};\n const tags = tagsFrom(args);\n if (tags) scope.tags = tags;\n if (binding.conversation_id) scope.conversation_id = binding.conversation_id;\n else if (binding.task_id) scope.task_id = binding.task_id;\n const result = await navigator.searchAgentMemory(query, scope, voice);\n return result.error ? result : { data: { notes: result.data.map(compactNote) }, error: null };\n }\n case AGENT_MEMORY_TOOL_NAMES.remember: {\n const kind = str(args, \"kind\");\n const title = str(args, \"title\");\n const body = str(args, \"body\");\n if (!kind || !(NOTE_KINDS as string[]).includes(kind) || !title || !body) {\n throw new NiadraValidationError(\"remember needs a kind, a title and a body\");\n }\n const note: CreateAgentNoteRequest = { kind: kind as AgentNoteKind, title, body };\n const tags = tagsFrom(args);\n if (tags) note.tags = tags;\n if (binding.conversation_id) note.evidence = { conversation_id: binding.conversation_id };\n else if (binding.task_id) note.evidence = { task_id: binding.task_id };\n const result = await navigator.remember(note);\n return result.error ? result : { data: remembered(result.data), error: null };\n }\n default:\n throw new NiadraValidationError(`unknown tool: ${name}`);\n }\n }\n\n return {\n definitions: definitions.map((definition) => cloneDefinition(definition)),\n has: (name) => names.has(name),\n async call(name, rawArgs) {\n let result: Result<unknown>;\n try {\n if (!names.has(name)) throw new NiadraValidationError(`unknown tool: ${name}`);\n result = await run(name, parseArgs(rawArgs));\n } catch (error) {\n // Even a strict client hands this one to the model: rewriting the note is the answer.\n if (error instanceof NiadraAPIError && isPersonalData(error)) return JSON.stringify(PERSONAL_DATA_TOOL_ERROR);\n if (strict) throw error;\n return JSON.stringify({ error: \"invalid_call\", detail: (error as Error).message });\n }\n if (result.error) {\n if (isPersonalData(result.error)) return JSON.stringify(PERSONAL_DATA_TOOL_ERROR);\n if (strict) throw result.error;\n const memory = name === AGENT_MEMORY_TOOL_NAMES.search || name === AGENT_MEMORY_TOOL_NAMES.remember;\n const detail = memory ? \"agent memory is unavailable right now\" : \"customer history is unavailable right now\";\n return JSON.stringify({ error: \"unavailable\", detail });\n }\n return JSON.stringify(result.data);\n },\n };\n}\n\n/** What the model needs of a note: the id, the kind, the title, the body and the tags. */\nfunction compactNote(note: AgentNote): Partial<AgentNote> {\n const { note_id, kind, title, body, tags } = note;\n return tags === undefined ? { note_id, kind, title, body } : { note_id, kind, title, body, tags };\n}\n\n/** A saved note, or a proposal a person still has to approve, as the model reads it. */\nfunction remembered(result: RememberResult): Record<string, unknown> {\n if (result.note) return { saved: true, note_id: result.note.note_id, version: result.note.version };\n return { saved: false, proposal_id: result.proposal_id ?? null, status: \"waiting for review\" };\n}\n\n/** The server refused a note with personal data: an answer for the model, not a failure. */\nfunction isPersonalData(error: NiadraError): boolean {\n return error instanceof NiadraAPIError && error.code === \"personal_data_in_agent_memory\";\n}\n\nfunction applyBinding(request: SearchRequest | TimelineRequest, binding: ToolBinding): void {\n if (binding.about) request.about = binding.about;\n if (binding.verification) request.verification = binding.verification;\n if (binding.conversation_id) request.conversation_id = binding.conversation_id;\n}\n\n/** Token accounting is for the caller, not the model; everything else the model can use. */\nfunction compactSearch(response: SearchResponse): Omit<SearchResponse, \"tokens_used\"> {\n const { tokens_used: _, ...rest } = response;\n return rest;\n}\n\nfunction cloneDefinition(definition: ToolDefinition): ToolDefinition {\n return JSON.parse(JSON.stringify(definition)) as ToolDefinition;\n}\n","/**\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","/**\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 * Niadra for the Agent Development Kit for TypeScript (`@google/adk` 2.x): model callbacks and the\n * navigation kit as ADK tools, for one agent definition that serves every ADK session.\n *\n * `niadraAdk({ session })` finds the Niadra session of each ADK session once (by its session id)\n * and returns:\n *\n * - `beforeModelCallback`: records the user's message of each invocation once, adds the agent's notes and\n * the customer's pack after your instruction in `config.systemInstruction`, and the suffix\n * (deltas and live turns) as a text part of the last user content. ADK builds the request from\n * the session's events on every call, so nothing of it lands in the session.\n * - `afterModelCallback`: records the final answer with `usageMetadata`, and `transfer_to_agent`\n * as a handoff between agents. Partial (streamed) responses and tool calls record nothing.\n * - `tools`: the kit as ADK tools with the canonical JSON Schemas. Each call finds its customer from\n * the tool's context, never from the model's arguments.\n * - With `turns: true`, `beforeAgentCallback`, `afterAgentCallback`, `beforeToolCallback` and\n * `afterToolCallback` record each agent's run in an invocation as a turn: each tool call with its\n * arguments and result, each model call with its tokens. In a replay a tool not wrapped with `tool()`\n * answers from the record and never runs.\n *\n * Fail-open: when Niadra is slow or down, the request goes to the model as ADK built it.\n *\n * @example\n * import { LlmAgent, InMemoryRunner } from \"@google/adk\";\n * import { niadraAdk } from \"@niadra/sdk/google-adk\";\n *\n * const memory = niadraAdk({\n * session: (context) => niadra.conversation({ subject: handles.appUserId(context.userId), channel: \"web_chat\", conversation_id: context.sessionId }),\n * });\n * // `...memory` sets `tools`, `beforeModelCallback` and `afterModelCallback`; give the same to sub-agents.\n * const support = new LlmAgent({ name: \"support\", model: \"gemini-2.5-flash\", instruction: \"You are Acme's support agent.\", ...memory });\n */\n\nimport { BaseTool } from \"@google/adk\";\nimport type { Context, LlmRequest, LlmResponse, ReadonlyContext, RunAsyncToolRequest } from \"@google/adk\";\nimport { AGENT_MEMORY_TOOL_DEFINITIONS, TOOL_DEFINITIONS } from \"../tools.js\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport { providerOf } from \"../usage.js\";\nimport { Bridge, TurnHooks, count, errorName, isRecord } from \"./shared.js\";\nimport type { AgentMemoryOption, ProofSource, Session } from \"./shared.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof, ProofSource, Session } from \"./shared.js\";\n\nexport interface NiadraAdkOptions {\n /**\n * The Niadra session of an ADK session: a fixed conversation or task, or a function of the\n * callback context (`userId`, `sessionId`, `state`), called once per ADK session id.\n */\n session: Session | ((context: ReadonlyContext) => Session | null | undefined);\n /** What your app proved about the user, recorded once per session before the first context read. */\n verify?: ProofSource;\n /** Records the newest user message as the customer's turn. Defaults to `true`. */\n recordCustomer?: boolean;\n /** Records the final answer as the agent's turn. Defaults to `true`. */\n recordAgent?: boolean;\n /** Puts the agent's own notes before the customer's context, and adds its memory tools. */\n agentMemory?: AgentMemoryOption;\n /** Records each agent's run as a turn, with its tool and model calls. Defaults to `false`. */\n turns?: boolean;\n}\n\ntype BeforeModel = (params: { context: Context; request: LlmRequest }) => Promise<LlmResponse | undefined>;\ntype AfterModel = (params: { context: Context; response: LlmResponse }) => Promise<LlmResponse | undefined>;\ntype AgentCallback = (context: Context) => undefined;\ntype BeforeTool = (params: { tool: BaseTool; args: Record<string, unknown>; context: Context }) => Record<string, unknown> | undefined;\ntype AfterTool = (params: { tool: BaseTool; args: Record<string, unknown>; context: Context; response: Record<string, unknown> }) => undefined;\n\nexport interface NiadraAdk {\n beforeModelCallback: BeforeModel;\n afterModelCallback: AfterModel;\n beforeAgentCallback: AgentCallback;\n afterAgentCallback: AgentCallback;\n beforeToolCallback: BeforeTool;\n afterToolCallback: AfterTool;\n /** The navigation kit as ADK tools. */\n tools: BaseTool[];\n}\n\ninterface State {\n bridge: Bridge;\n seen: Set<string>;\n model: string;\n}\n\nconst MAX_SESSIONS = 10_000;\n\n/** The callbacks and tools for one ADK agent, sharing one Niadra session per ADK session. */\nexport function niadraAdk(options: NiadraAdkOptions): NiadraAdk {\n const bySession = new Map<string, State | null>();\n const hooks = new TurnHooks(\"google-adk\", options.turns ?? false);\n /** One agent's run in one invocation: what its turn is keyed by. */\n const runKey = (context: Context): string => `${context.invocationId}:${context.agentName}`;\n const fixed = typeof options.session === \"function\" ? null : newState(options.session, options);\n\n const stateOf = (context: ReadonlyContext): State | null => {\n if (fixed) return fixed;\n const resolve = options.session as (context: ReadonlyContext) => Session | null | undefined;\n const key = context.sessionId;\n if (bySession.has(key)) return bySession.get(key) ?? null;\n let state: State | null;\n try {\n const session = resolve(context);\n state = session ? newState(session, options) : null;\n } catch {\n state = null;\n }\n bySession.set(key, state);\n if (bySession.size > MAX_SESSIONS) {\n const oldest = bySession.keys().next().value;\n if (oldest !== undefined) bySession.delete(oldest);\n }\n return state;\n };\n\n const beforeModelCallback: BeforeModel = async ({ context, request }) => {\n const state = stateOf(context);\n if (!state) return undefined;\n state.model = request.model ?? state.model;\n try {\n const contents = request.contents;\n // One customer turn per invocation: the user's message that started it, whatever agent answers.\n const said = textOfParts(context.userContent?.parts);\n if ((options.recordCustomer ?? true) && said && !state.seen.has(context.invocationId)) {\n state.seen.add(context.invocationId);\n if (state.seen.size > MAX_SESSIONS) state.seen.clear();\n state.bridge.customer(said);\n }\n const read = await state.bridge.read();\n state.bridge.injected(read.context);\n if (read.prefix) {\n const config = (request.config ??= {});\n const system = config.systemInstruction;\n if (system === undefined || system === \"\") config.systemInstruction = read.prefix;\n else if (typeof system === \"string\") config.systemInstruction = `${system}\\n\\n${read.prefix}`;\n else if (isRecord(system) && Array.isArray(system.parts)) config.systemInstruction = { ...system, parts: [...(system.parts as unknown[]), { text: read.prefix }] } as typeof system;\n else if (Array.isArray(system)) config.systemInstruction = [...(system as unknown[]), { text: read.prefix }] as typeof system;\n }\n if (read.suffix) {\n for (let index = contents.length - 1; index >= 0; index--) {\n const content = contents[index];\n if (!content || (content.role ?? \"user\") !== \"user\" || !textOfParts(content.parts)) continue;\n contents[index] = { ...content, parts: [...(content.parts ?? []), { text: read.suffix }] };\n break;\n }\n }\n } catch (error) {\n state.bridge.logger.warn(`could not inject context (${errorName(error)})`);\n }\n return undefined;\n };\n\n const afterModelCallback: AfterModel = async ({ context, response }) => {\n const state = stateOf(context);\n if (!state || response.partial === true) return undefined;\n const tokens = response.usageMetadata;\n hooks.model(state.bridge.session, state.model || null, { in: count(tokens?.promptTokenCount), out: count(tokens?.candidatesTokenCount), cached: count(tokens?.cachedContentTokenCount) ?? 0 }, runKey(context));\n try {\n const parts = response.content?.parts ?? [];\n const transfer = parts.find((part) => part.functionCall?.name === \"transfer_to_agent\")?.functionCall;\n if (transfer) {\n const target = isRecord(transfer.args) && typeof transfer.args.agent_name === \"string\" ? transfer.args.agent_name : undefined;\n await state.bridge.handoff(\"agent\", target ? `${context.agentName} to ${target}` : undefined);\n return undefined;\n }\n if (!(options.recordAgent ?? true) || parts.some((part) => part.functionCall)) return undefined;\n const text = textOfParts(parts, \"\");\n if (!text) return undefined;\n const usage = adkUsage(response, state.model);\n state.bridge.agent(text, usage ? { usage } : {});\n } catch (error) {\n state.bridge.logger.warn(`could not record the agent's answer (${errorName(error)})`);\n }\n return undefined;\n };\n\n const memory = options.agentMemory;\n const definitions = [\n ...TOOL_DEFINITIONS,\n ...(memory ? AGENT_MEMORY_TOOL_DEFINITIONS.slice(0, memory !== true && memory.write ? 2 : 1) : []),\n ];\n const tools = definitions.map(({ function: definition }) => new NiadraTool(definition, (context) => stateOf(context)));\n const beforeAgentCallback: AgentCallback = (context) => {\n const state = stateOf(context);\n if (state) hooks.open(state.bridge.session, runKey(context), { agent: context.agentName });\n return undefined;\n };\n\n const afterAgentCallback: AgentCallback = (context) => {\n hooks.close(runKey(context));\n return undefined;\n };\n\n const beforeToolCallback: BeforeTool = ({ tool, args, context }) => {\n const state = stateOf(context);\n if (!state) return undefined;\n const key = context.functionCallId ?? `${tool.name}:${context.invocationId}`;\n hooks.toolStart(state.bridge.session, key, tool.name, args, { frameKey: runKey(context), callId: context.functionCallId ?? null });\n const played = hooks.replayed(state.bridge.session, tool.name, args, (tool as { execute?: unknown }).execute, runKey(context));\n if (played === null) return undefined;\n const answer = played.recorded && isRecord(played.value) ? played.value : {};\n hooks.toolEnd(key, answer);\n return answer;\n };\n\n const afterToolCallback: AfterTool = ({ tool, context, response }) => {\n hooks.toolEnd(context.functionCallId ?? `${tool.name}:${context.invocationId}`, response);\n return undefined;\n };\n\n return { beforeModelCallback, afterModelCallback, beforeAgentCallback, afterAgentCallback, beforeToolCallback, afterToolCallback, tools };\n}\n\n/** `usageMetadata` of an ADK response as a `ModelUsage`: the prompt count includes the cached tokens. */\nexport function adkUsage(response: LlmResponse, model: string): ModelUsage | null {\n const usage = response.usageMetadata;\n const prompt = count(usage?.promptTokenCount);\n const name = (response.modelVersion ?? model).replace(/^models\\//, \"\");\n if (prompt === null || !name) return null;\n const cached = count(usage?.cachedContentTokenCount) ?? 0;\n return { provider: providerOf(name), model: name, prompt_tokens: Math.max(prompt, cached), cached_tokens: cached, cache_write_tokens: 0 };\n}\n\n/** One tool of the kit. The declaration is the canonical one; the customer comes from the tool's context. */\nclass NiadraTool extends BaseTool {\n constructor(\n private readonly definition: (typeof TOOL_DEFINITIONS)[number][\"function\"],\n private readonly stateOf: (context: ReadonlyContext) => State | null,\n ) {\n super({ name: definition.name, description: definition.description });\n }\n\n override _getDeclaration() {\n return { name: this.definition.name, description: this.definition.description, parametersJsonSchema: this.definition.parameters };\n }\n\n async runAsync({ args, toolContext }: RunAsyncToolRequest): Promise<unknown> {\n const state = this.stateOf(toolContext);\n const spec = state?.bridge.tools().find((candidate) => candidate.name === this.name);\n if (!spec) return { error: \"unavailable\", detail: \"customer history is unavailable right now\" };\n const text = await spec.execute(args);\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return { result: text };\n }\n }\n}\n\nfunction newState(session: Session, options: NiadraAdkOptions): State {\n return { bridge: new Bridge(session, options.verify, options.agentMemory), seen: new Set(), model: \"\" };\n}\n\nfunction textOfParts(parts: unknown, separator = \"\\n\"): string {\n if (!Array.isArray(parts)) return \"\";\n return (parts as unknown[])\n .map((part) => (isRecord(part) && typeof part.text === \"string\" && part.thought !== true ? part.text : \"\"))\n .filter(Boolean)\n .join(separator);\n}\n"]}
@@ -0,0 +1,91 @@
1
+ import { Context, LlmRequest, LlmResponse, BaseTool, ReadonlyContext } from '@google/adk';
2
+ import { g as ModelUsage } from './client-DsIxZxZk.cjs';
3
+ import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-DTPWVlWm.cjs';
4
+ export { P as Proof, c as attestationProof } from './shared-DTPWVlWm.cjs';
5
+
6
+ /**
7
+ * Niadra for the Agent Development Kit for TypeScript (`@google/adk` 2.x): model callbacks and the
8
+ * navigation kit as ADK tools, for one agent definition that serves every ADK session.
9
+ *
10
+ * `niadraAdk({ session })` finds the Niadra session of each ADK session once (by its session id)
11
+ * and returns:
12
+ *
13
+ * - `beforeModelCallback`: records the user's message of each invocation once, adds the agent's notes and
14
+ * the customer's pack after your instruction in `config.systemInstruction`, and the suffix
15
+ * (deltas and live turns) as a text part of the last user content. ADK builds the request from
16
+ * the session's events on every call, so nothing of it lands in the session.
17
+ * - `afterModelCallback`: records the final answer with `usageMetadata`, and `transfer_to_agent`
18
+ * as a handoff between agents. Partial (streamed) responses and tool calls record nothing.
19
+ * - `tools`: the kit as ADK tools with the canonical JSON Schemas. Each call finds its customer from
20
+ * the tool's context, never from the model's arguments.
21
+ * - With `turns: true`, `beforeAgentCallback`, `afterAgentCallback`, `beforeToolCallback` and
22
+ * `afterToolCallback` record each agent's run in an invocation as a turn: each tool call with its
23
+ * arguments and result, each model call with its tokens. In a replay a tool not wrapped with `tool()`
24
+ * answers from the record and never runs.
25
+ *
26
+ * Fail-open: when Niadra is slow or down, the request goes to the model as ADK built it.
27
+ *
28
+ * @example
29
+ * import { LlmAgent, InMemoryRunner } from "@google/adk";
30
+ * import { niadraAdk } from "@niadra/sdk/google-adk";
31
+ *
32
+ * const memory = niadraAdk({
33
+ * session: (context) => niadra.conversation({ subject: handles.appUserId(context.userId), channel: "web_chat", conversation_id: context.sessionId }),
34
+ * });
35
+ * // `...memory` sets `tools`, `beforeModelCallback` and `afterModelCallback`; give the same to sub-agents.
36
+ * const support = new LlmAgent({ name: "support", model: "gemini-2.5-flash", instruction: "You are Acme's support agent.", ...memory });
37
+ */
38
+
39
+ interface NiadraAdkOptions {
40
+ /**
41
+ * The Niadra session of an ADK session: a fixed conversation or task, or a function of the
42
+ * callback context (`userId`, `sessionId`, `state`), called once per ADK session id.
43
+ */
44
+ session: Session | ((context: ReadonlyContext) => Session | null | undefined);
45
+ /** What your app proved about the user, recorded once per session before the first context read. */
46
+ verify?: ProofSource;
47
+ /** Records the newest user message as the customer's turn. Defaults to `true`. */
48
+ recordCustomer?: boolean;
49
+ /** Records the final answer as the agent's turn. Defaults to `true`. */
50
+ recordAgent?: boolean;
51
+ /** Puts the agent's own notes before the customer's context, and adds its memory tools. */
52
+ agentMemory?: AgentMemoryOption;
53
+ /** Records each agent's run as a turn, with its tool and model calls. Defaults to `false`. */
54
+ turns?: boolean;
55
+ }
56
+ type BeforeModel = (params: {
57
+ context: Context;
58
+ request: LlmRequest;
59
+ }) => Promise<LlmResponse | undefined>;
60
+ type AfterModel = (params: {
61
+ context: Context;
62
+ response: LlmResponse;
63
+ }) => Promise<LlmResponse | undefined>;
64
+ type AgentCallback = (context: Context) => undefined;
65
+ type BeforeTool = (params: {
66
+ tool: BaseTool;
67
+ args: Record<string, unknown>;
68
+ context: Context;
69
+ }) => Record<string, unknown> | undefined;
70
+ type AfterTool = (params: {
71
+ tool: BaseTool;
72
+ args: Record<string, unknown>;
73
+ context: Context;
74
+ response: Record<string, unknown>;
75
+ }) => undefined;
76
+ interface NiadraAdk {
77
+ beforeModelCallback: BeforeModel;
78
+ afterModelCallback: AfterModel;
79
+ beforeAgentCallback: AgentCallback;
80
+ afterAgentCallback: AgentCallback;
81
+ beforeToolCallback: BeforeTool;
82
+ afterToolCallback: AfterTool;
83
+ /** The navigation kit as ADK tools. */
84
+ tools: BaseTool[];
85
+ }
86
+ /** The callbacks and tools for one ADK agent, sharing one Niadra session per ADK session. */
87
+ declare function niadraAdk(options: NiadraAdkOptions): NiadraAdk;
88
+ /** `usageMetadata` of an ADK response as a `ModelUsage`: the prompt count includes the cached tokens. */
89
+ declare function adkUsage(response: LlmResponse, model: string): ModelUsage | null;
90
+
91
+ export { AgentMemoryOption, type NiadraAdk, type NiadraAdkOptions, ProofSource, Session, adkUsage, niadraAdk };
@@ -0,0 +1,91 @@
1
+ import { Context, LlmRequest, LlmResponse, BaseTool, ReadonlyContext } from '@google/adk';
2
+ import { g as ModelUsage } from './client-DsIxZxZk.js';
3
+ import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-Bb5B59Bu.js';
4
+ export { P as Proof, c as attestationProof } from './shared-Bb5B59Bu.js';
5
+
6
+ /**
7
+ * Niadra for the Agent Development Kit for TypeScript (`@google/adk` 2.x): model callbacks and the
8
+ * navigation kit as ADK tools, for one agent definition that serves every ADK session.
9
+ *
10
+ * `niadraAdk({ session })` finds the Niadra session of each ADK session once (by its session id)
11
+ * and returns:
12
+ *
13
+ * - `beforeModelCallback`: records the user's message of each invocation once, adds the agent's notes and
14
+ * the customer's pack after your instruction in `config.systemInstruction`, and the suffix
15
+ * (deltas and live turns) as a text part of the last user content. ADK builds the request from
16
+ * the session's events on every call, so nothing of it lands in the session.
17
+ * - `afterModelCallback`: records the final answer with `usageMetadata`, and `transfer_to_agent`
18
+ * as a handoff between agents. Partial (streamed) responses and tool calls record nothing.
19
+ * - `tools`: the kit as ADK tools with the canonical JSON Schemas. Each call finds its customer from
20
+ * the tool's context, never from the model's arguments.
21
+ * - With `turns: true`, `beforeAgentCallback`, `afterAgentCallback`, `beforeToolCallback` and
22
+ * `afterToolCallback` record each agent's run in an invocation as a turn: each tool call with its
23
+ * arguments and result, each model call with its tokens. In a replay a tool not wrapped with `tool()`
24
+ * answers from the record and never runs.
25
+ *
26
+ * Fail-open: when Niadra is slow or down, the request goes to the model as ADK built it.
27
+ *
28
+ * @example
29
+ * import { LlmAgent, InMemoryRunner } from "@google/adk";
30
+ * import { niadraAdk } from "@niadra/sdk/google-adk";
31
+ *
32
+ * const memory = niadraAdk({
33
+ * session: (context) => niadra.conversation({ subject: handles.appUserId(context.userId), channel: "web_chat", conversation_id: context.sessionId }),
34
+ * });
35
+ * // `...memory` sets `tools`, `beforeModelCallback` and `afterModelCallback`; give the same to sub-agents.
36
+ * const support = new LlmAgent({ name: "support", model: "gemini-2.5-flash", instruction: "You are Acme's support agent.", ...memory });
37
+ */
38
+
39
+ interface NiadraAdkOptions {
40
+ /**
41
+ * The Niadra session of an ADK session: a fixed conversation or task, or a function of the
42
+ * callback context (`userId`, `sessionId`, `state`), called once per ADK session id.
43
+ */
44
+ session: Session | ((context: ReadonlyContext) => Session | null | undefined);
45
+ /** What your app proved about the user, recorded once per session before the first context read. */
46
+ verify?: ProofSource;
47
+ /** Records the newest user message as the customer's turn. Defaults to `true`. */
48
+ recordCustomer?: boolean;
49
+ /** Records the final answer as the agent's turn. Defaults to `true`. */
50
+ recordAgent?: boolean;
51
+ /** Puts the agent's own notes before the customer's context, and adds its memory tools. */
52
+ agentMemory?: AgentMemoryOption;
53
+ /** Records each agent's run as a turn, with its tool and model calls. Defaults to `false`. */
54
+ turns?: boolean;
55
+ }
56
+ type BeforeModel = (params: {
57
+ context: Context;
58
+ request: LlmRequest;
59
+ }) => Promise<LlmResponse | undefined>;
60
+ type AfterModel = (params: {
61
+ context: Context;
62
+ response: LlmResponse;
63
+ }) => Promise<LlmResponse | undefined>;
64
+ type AgentCallback = (context: Context) => undefined;
65
+ type BeforeTool = (params: {
66
+ tool: BaseTool;
67
+ args: Record<string, unknown>;
68
+ context: Context;
69
+ }) => Record<string, unknown> | undefined;
70
+ type AfterTool = (params: {
71
+ tool: BaseTool;
72
+ args: Record<string, unknown>;
73
+ context: Context;
74
+ response: Record<string, unknown>;
75
+ }) => undefined;
76
+ interface NiadraAdk {
77
+ beforeModelCallback: BeforeModel;
78
+ afterModelCallback: AfterModel;
79
+ beforeAgentCallback: AgentCallback;
80
+ afterAgentCallback: AgentCallback;
81
+ beforeToolCallback: BeforeTool;
82
+ afterToolCallback: AfterTool;
83
+ /** The navigation kit as ADK tools. */
84
+ tools: BaseTool[];
85
+ }
86
+ /** The callbacks and tools for one ADK agent, sharing one Niadra session per ADK session. */
87
+ declare function niadraAdk(options: NiadraAdkOptions): NiadraAdk;
88
+ /** `usageMetadata` of an ADK response as a `ModelUsage`: the prompt count includes the cached tokens. */
89
+ declare function adkUsage(response: LlmResponse, model: string): ModelUsage | null;
90
+
91
+ export { AgentMemoryOption, type NiadraAdk, type NiadraAdkOptions, ProofSource, Session, adkUsage, niadraAdk };