@niadra/sdk 0.9.1 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/dist/ai-sdk.d.cts +3 -3
  3. package/dist/ai-sdk.d.ts +3 -3
  4. package/dist/anthropic.d.cts +4 -4
  5. package/dist/anthropic.d.ts +4 -4
  6. package/dist/bedrock.d.cts +4 -4
  7. package/dist/bedrock.d.ts +4 -4
  8. package/dist/cli.js +319 -96
  9. package/dist/cli.js.map +1 -1
  10. package/dist/{client-CWMxmJHs.d.cts → client-rmWhZJOx.d.cts} +190 -7
  11. package/dist/{client-CWMxmJHs.d.ts → client-rmWhZJOx.d.ts} +190 -7
  12. package/dist/cloudflare-agents.d.cts +3 -3
  13. package/dist/cloudflare-agents.d.ts +3 -3
  14. package/dist/elevenlabs.cjs +7 -5
  15. package/dist/elevenlabs.cjs.map +1 -1
  16. package/dist/elevenlabs.d.cts +5 -5
  17. package/dist/elevenlabs.d.ts +5 -5
  18. package/dist/elevenlabs.js +7 -5
  19. package/dist/elevenlabs.js.map +1 -1
  20. package/dist/genkit.d.cts +3 -3
  21. package/dist/genkit.d.ts +3 -3
  22. package/dist/google-adk.cjs +7 -5
  23. package/dist/google-adk.cjs.map +1 -1
  24. package/dist/google-adk.d.cts +3 -3
  25. package/dist/google-adk.d.ts +3 -3
  26. package/dist/google-adk.js +7 -5
  27. package/dist/google-adk.js.map +1 -1
  28. package/dist/google-genai.d.cts +4 -4
  29. package/dist/google-genai.d.ts +4 -4
  30. package/dist/index.cjs +329 -98
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +13 -5
  33. package/dist/index.d.ts +13 -5
  34. package/dist/index.js +329 -98
  35. package/dist/index.js.map +1 -1
  36. package/dist/{intercept-CGngQI8B.d.cts → intercept-C0XODsy9.d.cts} +1 -1
  37. package/dist/{intercept-Bv0nLpSw.d.ts → intercept-veMDudKV.d.ts} +1 -1
  38. package/dist/langchain.cjs.map +1 -1
  39. package/dist/langchain.d.cts +3 -3
  40. package/dist/langchain.d.ts +3 -3
  41. package/dist/langchain.js.map +1 -1
  42. package/dist/livekit.cjs +10 -2
  43. package/dist/livekit.cjs.map +1 -1
  44. package/dist/livekit.d.cts +3 -3
  45. package/dist/livekit.d.ts +3 -3
  46. package/dist/livekit.js +10 -2
  47. package/dist/livekit.js.map +1 -1
  48. package/dist/llamaindex.d.cts +3 -3
  49. package/dist/llamaindex.d.ts +3 -3
  50. package/dist/mastra.d.cts +3 -3
  51. package/dist/mastra.d.ts +3 -3
  52. package/dist/openai-agents.d.cts +3 -3
  53. package/dist/openai-agents.d.ts +3 -3
  54. package/dist/retell.cjs +7 -5
  55. package/dist/retell.cjs.map +1 -1
  56. package/dist/retell.d.cts +5 -5
  57. package/dist/retell.d.ts +5 -5
  58. package/dist/retell.js +7 -5
  59. package/dist/retell.js.map +1 -1
  60. package/dist/{shared-B4Ef2Wpg.d.ts → shared-Cs7h5C4Y.d.ts} +1 -1
  61. package/dist/{shared-Cq8mz-7m.d.cts → shared-zaTBum17.d.cts} +1 -1
  62. package/dist/strands.d.cts +3 -3
  63. package/dist/strands.d.ts +3 -3
  64. package/dist/twilio.cjs +10 -2
  65. package/dist/twilio.cjs.map +1 -1
  66. package/dist/twilio.d.cts +4 -4
  67. package/dist/twilio.d.ts +4 -4
  68. package/dist/twilio.js +10 -2
  69. package/dist/twilio.js.map +1 -1
  70. package/dist/vapi.cjs +7 -5
  71. package/dist/vapi.cjs.map +1 -1
  72. package/dist/vapi.d.cts +5 -5
  73. package/dist/vapi.d.ts +5 -5
  74. package/dist/vapi.js +7 -5
  75. package/dist/vapi.js.map +1 -1
  76. package/dist/voltagent.d.cts +3 -3
  77. package/dist/voltagent.d.ts +3 -3
  78. package/dist/{webhook-z2TjUzjv.d.ts → webhook-2V5QgnKI.d.ts} +1 -1
  79. package/dist/{webhook-jTx_SegV.d.cts → webhook-CX7nvQig.d.cts} +1 -1
  80. package/dist/whatsapp.cjs +10 -2
  81. package/dist/whatsapp.cjs.map +1 -1
  82. package/dist/whatsapp.d.cts +2 -2
  83. package/dist/whatsapp.d.ts +2 -2
  84. package/dist/whatsapp.js +10 -2
  85. package/dist/whatsapp.js.map +1 -1
  86. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tools.ts","../src/usage.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/elevenlabs.ts"],"names":[],"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;AAC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iadraValidationError } 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","import { NiadraValidationError } from \"./errors.js\";\nimport { includeText } from \"./constraints/text.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport { toObjectRef } from \"./handles.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type {\n ContextFormat,\n ContextPack,\n ContextRequest,\n ContextResponse,\n CoordinationBlock,\n Include,\n LiveTurn,\n PrefetchRequest,\n TargetModel,\n} from \"./types/context.js\";\nimport type { ConstraintsBlock } from \"./types/signals.js\";\nimport type { StateView } from \"./types/state.js\";\nimport type { Verification, View } from \"./types/vocabulary.js\";\n\n/** Arguments of `context()`. Pass exactly one of `subject` or `object`. */\nexport interface ContextParams {\n /** The customer, by any handle the server knows. */\n subject?: Handle;\n /** A business object, such as an invoice, when the task is about the object rather than a person. */\n object?: ObjectRef | string;\n /** The account or partner the person acts for. Requires an active link between the two. */\n about?: Handle;\n /** Defaults to `chat`. */\n view?: View;\n /**\n * The level proven in this conversation. The server may answer with a lower effective level\n * when the source's ceiling is lower; see `response.verification`.\n */\n verification?: Verification;\n /** Enables the per-conversation cache and the server's pinning of the pack. */\n conversation_id?: string;\n /** For internal agents: the task plays the role of the conversation. */\n task_id?: string;\n /**\n * Other words than the turn to pick this read's slots by. Up to 2,000 characters. Wins over\n * `turn`, and like it never changes the pack.\n */\n query?: string;\n /**\n * The customer's last turn; a conversation passes it for you. It goes as `query` and the answer\n * adds `slots`, what the turn selected from memory, in `suffix`, while the pack stays the\n * conversation's pinned one (and is cached as without it).\n */\n turn?: string | null;\n /** Ask only for what changed since this source last read the subject. */\n delta?: boolean;\n /** The model that will read the pack, so the server can size it for that model's prompt cache. */\n target?: TargetModel;\n /** `json` also returns the pack as typed sections in `pack` (`context-pack.v1`). Defaults to `text`. */\n format?: ContextFormat;\n /**\n * Adds `why` to each of `pack.slots`, naming the retrieval channels that\n * ranked it, the fused score, the weights version and, for a derived line, the rule behind it.\n * Requires `format: \"json\"`. It changes nothing else: the pinned text, the slots chosen and the\n * receipt are the same bytes with or without it.\n */\n explain?: boolean;\n /**\n * Blocks read in the same round trip: `[\"constraints\"]` returns the subject's constraints block, `[\"state\"]`\n * the state of their objects. Each only where the space turned its feature on; a block the space does not\n * serve is left out and not asked again for a while, and the read goes on. The blocks are cached with the\n * pack, so a read that fails serves the last good ones too.\n */\n include?: Include[];\n}\n\n/** Arguments of `prefetch()`: who the turn is about, as in `context()`, and the turn so far. */\nexport interface PrefetchParams {\n subject?: Handle;\n object?: ObjectRef | string;\n about?: Handle;\n /** Defaults to `voice`, where partial transcripts come from. */\n view?: View;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** The partial transcript of the customer's turn. */\n text: string;\n}\n\n/** Per-call options shared by every read method. */\nexport interface RequestOptions {\n /** Overrides the method's default time budget, in milliseconds. */\n timeout?: number | undefined;\n /** Cancels the wait. A request shared with other callers keeps running for them. */\n signal?: AbortSignal | undefined;\n /** Extra headers, such as a W3C `traceparent`. */\n headers?: Record<string, string> | undefined;\n}\n\nexport interface ContextOptions extends RequestOptions {\n /** Pass `false` to skip the per-conversation cache for this call. */\n cache?: boolean | undefined;\n /** For `conversation.context()` and `task.context()`: blocks read in the same round trip. */\n include?: Include[] | undefined;\n /** For `conversation.context()` and `task.context()`: `json` also returns `pack`. */\n format?: ContextFormat | undefined;\n /**\n * For `conversation.context()` and `task.context()`: adds `why` to each of `pack.slots`.\n * Requires `format: \"json\"`.\n */\n explain?: boolean | undefined;\n}\n\n/**\n * Where a `context()` result came from.\n *\n * - `network`: a response the server just sent (or confirmed unchanged).\n * - `cache`: a pack younger than the cache TTL; no request was made.\n * - `stale`: an older pack returned at once while a background request refreshes it.\n * - `fallback`: the request failed and this is the last good pack for the conversation.\n * - `none`: nothing was available; `text` is empty and `error` says why.\n */\nexport type ContextSource = \"network\" | \"cache\" | \"stale\" | \"fallback\" | \"none\";\n\n/** What `context()` resolves to. Always usable: on failure `text` is an empty string. */\nexport interface ContextResult {\n /** The pack, ready for the system prompt. Empty when there is nothing to inject. */\n text: string;\n /**\n * The parts that change turn by turn and belong at the end of the prompt, after the\n * conversation: the live turns from other channels, this turn's slots (what the customer's last\n * turn selected from memory), the blocks asked for by `include` (the state view, the constraints) and the\n * delta, in that order, as the API places them. Empty when there are none.\n */\n suffix: string;\n /** Named values from the pack, for templates that place them individually. */\n variables: Record<string, string>;\n /** The pack as typed sections, when read with `format: \"json\"`; otherwise `null`. */\n pack: ContextPack | null;\n source: ContextSource;\n /**\n * How long ago Niadra sent or confirmed the pack served, in milliseconds: 0 for an answer just received,\n * growing while a cached pack is served (`cache`, `stale`, or `fallback` with Niadra down), and `null` when\n * there is no pack.\n */\n ageMs: number | null;\n /** The response this result was built from; `null` when `source` is `none`. */\n response: ContextResponse | null;\n /** What went wrong, when `source` is `fallback` or `none`. */\n error: NiadraError | null;\n /** With `include: [\"constraints\"]`: the subject's constraints block. */\n constraints?: ConstraintsBlock | null;\n /** With `include: [\"state\"]`: the state of the subject's objects. */\n state?: StateView | null;\n /** With `include: [\"coordination\"]`: what coordination knows of the subject. */\n coordination?: CoordinationBlock | null;\n}\n\nconst VIEW = /^(voice|chat|brief|full|custom|account|partner|task:[a-z0-9_]{1,40})$/;\nconst MAX_QUERY = 2000;\n\n/** Validates the arguments and builds the wire request, without `known_etag`. */\nexport function buildContextRequest(params: ContextParams): ContextRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n if (params.query !== undefined && params.query.length > MAX_QUERY) {\n throw new NiadraValidationError(`query is longer than ${MAX_QUERY} characters`);\n }\n\n const request: ContextRequest = { view: params.view ?? \"chat\" };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n if (params.query) request.query = params.query;\n if (params.delta) request.delta = true;\n if (params.target) request.target = params.target;\n const format: string = params.format ?? \"text\";\n if (format !== \"text\" && format !== \"json\") throw new NiadraValidationError(\"format is `text` or `json`\");\n if (format === \"json\") request.format = \"json\";\n if (params.explain) {\n if (format !== \"json\") throw new NiadraValidationError('explain requires format: \"json\"');\n request.explain = true;\n }\n if (params.include?.length) request.include = [...new Set(params.include)];\n return request;\n}\n\n/** Validates the arguments of `prefetch()` and builds the wire request. */\nexport function buildPrefetchRequest(params: PrefetchParams): PrefetchRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n const text = params.text.trim();\n if (!text || text.length > MAX_QUERY) throw new NiadraValidationError(`text must be 1 to ${MAX_QUERY} characters`);\n const request: PrefetchRequest = { view: params.view ?? \"voice\", query: text };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n return request;\n}\n\n/** Packs are only cached inside a conversation or task, the unit the server pins them to. */\nexport function cacheScope(request: Pick<ContextRequest, \"conversation_id\" | \"task_id\">): string | null {\n if (request.conversation_id) return `conversation:${request.conversation_id}`;\n if (request.task_id) return `task:${request.task_id}`;\n return null;\n}\n\n/**\n * Every field that changes what the server would compile goes into the key, in a fixed order.\n * `delta` does not: a plain read and a delta read of one conversation get the same pinned\n * bytes, so they share one entry.\n */\nexport function cacheKey(request: ContextRequest): string {\n return JSON.stringify([\n request.subject ?? null,\n request.object ?? null,\n request.about ?? null,\n request.view ?? \"chat\",\n request.verification ?? \"V0\",\n request.conversation_id ?? null,\n request.task_id ?? null,\n request.query ?? null,\n request.target ?? null,\n request.format ?? \"text\",\n request.explain ?? false,\n request.include ?? null,\n ]);\n}\n\n/**\n * Applies a `not_modified` answer to the cached pack: the pinned text and its metadata stay,\n * while the parts outside the pin (live turns, delta, coverage, timing) come from the new answer.\n */\nexport function mergeNotModified(cached: ContextResponse, fresh: ContextResponse): ContextResponse {\n return {\n ...fresh,\n not_modified: false,\n text: cached.text ?? null,\n variables: cached.variables,\n version: cached.version,\n etag: cached.etag,\n manifest_hash: cached.manifest_hash ?? null,\n withheld: cached.withheld,\n cache: cached.cache ?? null,\n pack: cached.pack ?? null,\n // The blocks sit outside the pinned pack: a fresh block wins, and a missing one keeps the cached.\n constraints: fresh.constraints ?? cached.constraints ?? null,\n state: fresh.state ?? cached.state ?? null,\n coordination: fresh.coordination ?? cached.coordination ?? null,\n };\n}\n\nexport function resultFrom(\n response: ContextResponse,\n source: ContextSource,\n error: NiadraError | null = null,\n ageMs: number | null = 0,\n): ContextResult {\n // A conversation in the control group gets an empty pack on purpose; it is not an error.\n const holdout = response.path === \"holdout\";\n const text = holdout ? \"\" : (response.text ?? \"\");\n const pack = holdout ? null : (response.pack ?? null);\n const blocks = {\n constraints: response.constraints ?? null,\n state: response.state ?? null,\n coordination: response.coordination ?? null,\n };\n return { text, suffix: renderSuffix(response), variables: response.variables, pack, source, ageMs, response, error, ...blocks };\n}\n\nexport function emptyResult(error: NiadraError | null): ContextResult {\n return { text: \"\", suffix: \"\", variables: {}, pack: null, source: \"none\", ageMs: null, response: null, error, constraints: null, state: null, coordination: null };\n}\n\n/**\n * Renders the live turns, the slots and the delta for the end of the prompt, in that order. Kept\n * outside the pinned pack so that the prompt prefix stays byte-identical across turns and the\n * model provider's prompt cache keeps hitting. Returns an empty string when there is nothing to add.\n */\nexport function renderSuffix(response: ContextResponse): string {\n if (response.path === \"holdout\") return \"\";\n const included = includeText(response.text, response.state, response.constraints);\n return [renderLive(response), response.slots ?? \"\", included, response.delta ?? \"\"].filter(Boolean).join(\"\\n\\n\");\n}\n\n/**\n * Renders the live turns (recent turns from other channels that the pack has not absorbed\n * yet) as one tagged block, or an empty string when there are none. `complete=\"false\"` tells\n * the model the list may be missing turns because the server could not read all of them.\n */\nexport function renderLive(response: ContextResponse): string {\n if (response.path === \"holdout\" || response.live.length === 0) return \"\";\n const complete = response.live_complete ? \"\" : ' complete=\"false\"';\n const lines = response.live.map(renderLiveTurn).join(\"\\n\");\n return `<live_turns source=\"niadra\"${complete}>\\n${lines}\\n</live_turns>`;\n}\n\nfunction renderLiveTurn(turn: LiveTurn): string {\n return `[${utcSeconds(turn.at)}] ${turn.channel} · ${turn.speaker}: ${turn.text}`;\n}\n\n/** The same timestamp form in every SDK, whatever precision or offset the server sent. */\nfunction utcSeconds(at: string): string {\n const ms = Date.parse(at);\n return Number.isNaN(ms) ? at : `${new Date(ms).toISOString().slice(0, 19)}Z`;\n}\n","/**\n * What every framework adapter shares: the five primitives (context before the model call, the\n * turns, the tools, the verification and the handoff) wired the same way, and fail-open.\n *\n * Nothing here throws into the framework: a failed read gives an empty context, a failed write\n * is logged without content, and the agent keeps working without memory.\n */\n\nimport { recordedTool } from \"../capture/tool.js\";\nimport type { Played } from \"../replay/playback.js\";\nimport type { AgentMemoryParams } from \"../agent-memory.js\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { CallCapture, TurnFrame } from \"../capture/frame.js\";\nimport type { ContextOptions, ContextResult } from \"../context.js\";\nimport { emptyResult } from \"../context.js\";\nimport type { Conversation, TurnOptions } from \"../conversation.js\";\nimport type { Logger } from \"../logger.js\";\nimport type { Task } from \"../task.js\";\nimport type { BoundTools } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { Verification, VerifyMethod } from \"../types/vocabulary.js\";\n\n/** A customer conversation or an internal agent's task. */\nexport type Session = Conversation | Task;\n\n/** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */\nexport type SessionResolver<S extends Session = Session> = S | (() => S | null | undefined);\n\n/** What the framework proved about the person, recorded with `verify()` before the first context read. */\nexport interface Proof {\n method: VerifyMethod;\n level: Verification;\n /** Defaults to the session's subject. */\n handle?: Handle;\n}\n\n/** A proof, or a function that reads it from the framework when the first context is needed. */\nexport type ProofSource =\n | Proof\n | null\n | undefined\n | (() => Proof | null | undefined | PromiseLike<Proof | null | undefined>);\n\n/**\n * The agent's own working notes: `true` puts the block before the customer's context and offers\n * `search_agent_memory`; `{ write: true }` also offers `remember` (for a key with the\n * `agent_memory:write` scope); the other fields go to `agentMemory()`.\n */\nexport type AgentMemoryOption = boolean | (AgentMemoryParams & { write?: boolean });\n\n/** What goes into the prompt for one model call. */\nexport interface Read {\n context: ContextResult;\n /** The agent's own notes, or an empty string. */\n memory: string;\n /** What goes after the instructions: the notes, then the customer's pack. */\n prefix: string;\n /** What goes at the end: live turns, the turn's slots and deltas. */\n suffix: string;\n}\n\n/** A tool as every framework needs it: the name, the text for the model, the JSON Schema and the call. */\ninterface ToolSpec {\n name: string;\n description: string;\n /** JSON Schema of the arguments. None of them names the customer. */\n parameters: Record<string, unknown>;\n /** Runs the call and returns the text for the model. Never rejects in fail-open mode. */\n execute(args: string | Record<string, unknown>): Promise<string>;\n}\n\nconst ATTESTED: Record<string, Verification> = { A: \"V2\", B: \"V1\", C: \"V1\" };\n\n/**\n * The proof a carrier's STIR/SHAKEN attestation gives a phone call: `A` proves V2, `B` and `C`\n * prove V1, anything else proves nothing (`null`). Accepts the bare letter or the forms carriers\n * and platforms send, such as Twilio's `TN-Validation-Passed-A`.\n */\nexport function attestationProof(attestation: string | null | undefined): Proof | null {\n if (!attestation) return null;\n const value = attestation.trim().toUpperCase();\n if (value.includes(\"FAILED\") || value.startsWith(\"NO-\")) return null;\n const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];\n const level = letter ? ATTESTED[letter] : undefined;\n return level ? { method: \"network_attestation\", level } : null;\n}\n\nexport function resolveSession<S extends Session>(source: SessionResolver<S>): S | null {\n if (typeof source !== \"function\") return source;\n try {\n return source() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction isConversation(session: Session): session is Conversation {\n return \"customer\" in session && typeof session.customer === \"function\";\n}\n\n/** A phone number as an E.164 handle, or `null` when it does not look like one. */\nexport function phoneHandle(value: string | null | undefined): Handle | null {\n const raw = value?.trim().replace(/^tel:/i, \"\").replace(/[\\s().-]/g, \"\");\n if (!raw) return null;\n const e164 = raw.startsWith(\"+\") ? raw : `+${raw}`;\n return /^\\+[1-9]\\d{6,14}$/.test(e164) ? { type: \"phone_e164\", value: e164 } : null;\n}\n\nexport function errorName(error: unknown): string {\n return error instanceof Error ? error.name : typeof error;\n}\n\n/**\n * One session as an adapter drives it. Keeps the verification to a single call made before the\n * first context read, and turns every failure into a log line.\n */\nexport class Bridge {\n private proving: Promise<void> | null = null;\n /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */\n private begun = false;\n private opened = false;\n\n constructor(\n readonly session: Session,\n private readonly proof?: ProofSource,\n private readonly memory: AgentMemoryOption = false,\n ) {}\n\n /**\n * The context and, when enabled, the agent's notes, read side by side within the same budget.\n * Never rejects.\n */\n async read(options: ContextOptions = {}): Promise<Read> {\n const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);\n const [context, memory] = await Promise.all([\n this.context(options),\n memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve(\"\"),\n ]);\n return { context, memory, prefix: [memory, context.text].filter(Boolean).join(\"\\n\\n\"), suffix: context.suffix };\n }\n\n get logger(): Logger {\n return this.session.logger;\n }\n\n /**\n * Starts the first read of a call now, in the background, after the proof when one was given (the\n * pack depends on the level it proves): at call start, so the read runs while the call is set up.\n * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.\n */\n begin(): void {\n const session = this.session;\n if (!isConversation(session)) return;\n const start = (): void => {\n this.safe(\"start the first read\", () => {\n // False off the voice read path (a chat view, the cache off): reads go on as before.\n this.begun = session.begin();\n });\n };\n if (this.proof === undefined || this.proof === null) start();\n else void this.verifyOnce().then(start);\n }\n\n /** Verifies once (when a proof was given), then reads the context. Never rejects. */\n async context(options: ContextOptions = {}): Promise<ContextResult> {\n await this.verifyOnce();\n try {\n const session = this.session;\n if (this.begun && !this.opened && isConversation(session)) {\n this.opened = true;\n // The call's first read, begun at call start: waited for within its own, longer budget.\n await session.ready(options.timeout === undefined ? {} : { timeout: options.timeout });\n }\n return await this.session.context(options);\n } catch (error) {\n this.logger.warn(`could not read context (${errorName(error)})`);\n return emptyResult(null);\n }\n }\n\n /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */\n injected(context: ContextResult): void {\n if (!context.text && !context.suffix && context.response?.path !== \"holdout\") return;\n this.safe(\"mark the injection\", () => {\n this.session.markInjected(context);\n });\n }\n\n customer(text: string, options: TurnOptions = {}): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"record the customer's turn\", () => session.customer(text, options));\n }\n\n /** Sends the customer's turn so far, while they speak. In the background; never throws. */\n prefetch(text: string): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"prefetch the turn\", () => session.prefetch(text));\n }\n\n agent(text: string, options: TurnOptions = {}): void {\n if (!text.trim()) return;\n this.safe(\"record the agent's turn\", () => this.session.agent(text, options));\n }\n\n /** Records a transfer. Tasks have no transfer; the call is ignored for them. */\n async handoff(target: \"agent\" | \"human\", reason?: string): Promise<void> {\n const session = this.session;\n if (!isConversation(session)) return;\n try {\n await session.handoff(reason ? { target, reason } : { target });\n } catch (error) {\n this.logger.warn(`could not record the handoff (${errorName(error)})`);\n }\n }\n\n async end(): Promise<void> {\n try {\n await this.session.end();\n } catch (error) {\n this.logger.warn(`could not end the session (${errorName(error)})`);\n }\n }\n\n /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */\n tools(): ToolSpec[] {\n let bound: BoundTools | null;\n try {\n const memory = this.memory;\n bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });\n } catch (error) {\n this.logger.warn(`could not build the tools (${errorName(error)})`);\n return [];\n }\n return bound ? toolSpecs(bound) : [];\n }\n\n private async agentMemory(params: AgentMemoryParams, options: ContextOptions): Promise<string> {\n try {\n const result = await this.session.agentMemory(params, options.timeout === undefined ? {} : { timeout: options.timeout });\n return result.text;\n } catch (error) {\n this.logger.warn(`could not read the agent's memory (${errorName(error)})`);\n return \"\";\n }\n }\n\n private async verifyOnce(): Promise<void> {\n if (this.proof === undefined || this.proof === null) return;\n this.proving ??= this.runVerify();\n await this.proving;\n }\n\n private async runVerify(): Promise<void> {\n try {\n const source = this.proof;\n const proof = typeof source === \"function\" ? await source() : source;\n if (!proof) return;\n await this.session.verify(proof);\n } catch (error) {\n this.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n\n private safe(what: string, run: () => unknown): void {\n try {\n run();\n } catch (error) {\n this.logger.warn(`could not ${what} (${errorName(error)})`);\n }\n }\n}\n\nfunction withoutWrite(option: AgentMemoryParams & { write?: boolean }): AgentMemoryParams {\n const { write: _, ...params } = option;\n return params;\n}\n\n/** The bound kit as specs. The customer stays inside `bound`; no parameter names them. */\nfunction toolSpecs(bound: BoundTools): ToolSpec[] {\n return bound.definitions.map(({ function: definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n execute: (args) => bound.call(definition.name, args),\n }));\n}\n\n/** The text of a message content in the shapes model APIs use: a string, or a list of text parts. */\nexport function textOf(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content as unknown[]) {\n if (typeof part === \"string\") parts.push(part);\n else if (isRecord(part) && typeof part.text === \"string\" && (part.type === undefined || part.type === \"text\")) {\n parts.push(part.text);\n }\n }\n return parts.join(\"\");\n}\n\nexport function isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** A non-negative integer, or `null`. */\nexport function count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/**\n * The turn records an adapter keeps from its framework's callbacks, keyed by the framework's own ids (a\n * run, a request, a tool call id). A run starting while the session has a turn in progress (yours, from\n * `conversation.turn()`, or a replay's) records into it; otherwise the adapter opens its own turn and closes\n * it when the run ends. A tool call recorded here is taken over by a `tool()` wrapper running inside it, so\n * the call is recorded once. Every method does nothing when turns are off and never throws.\n */\nexport class TurnHooks {\n /** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */\n static readonly MAX_OPEN = 100;\n private readonly frames = new Map<string, { frame: TurnFrame; own: boolean }>();\n private readonly calls = new Map<string, CallCapture>();\n\n constructor(\n readonly adapter: string,\n readonly enabled: boolean,\n ) {}\n\n /** The turn of the run `key`: the session's turn in progress, or a new one of its own. */\n open(session: Session, key: string, params: TurnParams = {}): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = this.frames.get(key);\n if (held !== undefined) return held.frame;\n try {\n const active = session.activeTurn();\n if (active !== undefined && !this.owns(active)) {\n this.frames.set(key, { frame: active, own: false });\n return active;\n }\n const frame = session.openTurn({ ...params, adapter: this.adapter });\n this.frames.set(key, { frame, own: true });\n if (this.frames.size > TurnHooks.MAX_OPEN) {\n const [oldest] = this.frames.keys();\n if (oldest !== undefined) {\n this.frames.get(oldest)?.frame.incomplete();\n this.close(oldest);\n }\n }\n return frame;\n } catch (error) {\n session.logger.warn(`could not open the turn (${errorName(error)})`);\n return undefined;\n }\n }\n\n /** The turn of `key`, else the session's turn in progress. */\n frame(session: Session, key?: string): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = key === undefined ? undefined : this.frames.get(key);\n const frame = held?.frame ?? session.activeTurn();\n return frame === undefined || frame.closed ? undefined : frame;\n }\n\n has(key: string): boolean {\n return this.frames.has(key);\n }\n\n private owns(frame: TurnFrame): boolean {\n for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;\n return false;\n }\n\n /** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */\n close(key: string, error?: unknown): void {\n const held = this.frames.get(key);\n if (held === undefined) return;\n this.frames.delete(key);\n for (const [callKey, call] of this.calls) {\n if (call.frame !== held.frame) continue;\n this.calls.delete(callKey);\n if (held.own) call.failed(error ?? \"error\");\n }\n if (held.own) held.frame.close(error);\n }\n\n /** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */\n toolStart(session: Session, callKey: string, name: string, args: unknown, options: { frameKey?: string; callId?: string | null } = {}): void {\n const frame = this.frame(session, options.frameKey);\n if (frame === undefined) return;\n try {\n this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));\n } catch {\n frame.incomplete();\n }\n }\n\n /**\n * In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the\n * same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function\n * wrapped with `tool()`, which answers itself.\n */\n replayed(session: Session, name: string, args: unknown, fn?: unknown, frameKey?: string): Played | null {\n const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();\n if (frame?.playback == null || (fn !== undefined && recordedTool(fn) !== null)) return null;\n return frame.playback.answer(name, args, false);\n }\n\n toolEnd(callKey: string, result?: unknown, error?: unknown): void {\n const call = this.calls.get(callKey);\n if (call === undefined) return;\n this.calls.delete(callKey);\n try {\n if (error !== undefined) call.failed(error);\n else call.result(result);\n } catch {\n call.frame.incomplete();\n }\n }\n\n /** A model call that ended, with its tokens when the framework reported them. */\n model(\n session: Session,\n model: string | null | undefined,\n tokens: { in?: number | null; out?: number | null; cached?: number | null } = {},\n frameKey?: string,\n ): void {\n const frame = this.frame(session, frameKey);\n if (frame === undefined) return;\n try {\n frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });\n } catch {\n frame.incomplete();\n }\n }\n}\n","/**\n * Helpers for the webhook adapters (ElevenLabs, Vapi, WhatsApp, Twilio): signatures with Web\n * Crypto and header lookup. Only web APIs, so the handlers run on Node 20+, Deno, Bun, Cloudflare\n * Workers and the Vercel Edge Runtime alike.\n */\n\nimport type { Handle } from \"../types/common.js\";\nimport type { ContextStamp } from \"../types/events.js\";\nimport type { Verification } from \"../types/vocabulary.js\";\n\n/**\n * What a call's first webhook learned, for the webhooks that come later in the same call (tool\n * calls, the end-of-call report): who the caller is, the level they proved and the context stamp.\n */\nexport interface CallRecord {\n subject: Handle;\n verification: Verification;\n stamp?: ContextStamp | null;\n}\n\n/**\n * Where the webhook adapters keep a `CallRecord` between requests, by the platform's call id.\n * The default lives in this process's memory; on serverless or several instances, pass one backed\n * by your key-value store.\n */\nexport interface CallStore {\n get(id: string): CallRecord | undefined | PromiseLike<CallRecord | undefined>;\n set(id: string, record: CallRecord): void | PromiseLike<void>;\n}\n\n/** An in-memory `CallStore` that keeps the most recent `max` calls. */\nexport function memoryCallStore(max = 10_000): CallStore {\n const calls = new Map<string, CallRecord>();\n return {\n get: (id) => calls.get(id),\n set: (id, record) => {\n calls.delete(id);\n calls.set(id, record);\n if (calls.size > max) {\n const oldest = calls.keys().next().value;\n if (oldest !== undefined) calls.delete(oldest);\n }\n },\n };\n}\n\n/** Request headers as a `Headers` object or a plain record (any case). */\nexport type HeadersLike = Headers | Record<string, string | string[] | undefined>;\n\n/** What a handler answers: the HTTP status and a JSON-serializable body (`null` for no body). */\nexport interface WebhookResponse<B = unknown> {\n status: number;\n body: B;\n}\n\nexport function header(headers: HeadersLike, name: string): string | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers as Record<string, string | string[] | undefined>)) {\n if (key.toLowerCase() !== wanted) continue;\n return Array.isArray(value) ? value[0] : value;\n }\n return undefined;\n}\n\nfunction subtle(): SubtleCrypto {\n const crypto = (globalThis as { crypto?: Crypto }).crypto;\n if (!crypto?.subtle) throw new Error(\"Web Crypto is not available on this runtime\");\n return crypto.subtle;\n}\n\nconst encoder = new TextEncoder();\n\nexport async function hmac(hash: \"SHA-1\" | \"SHA-256\", secret: string, message: string): Promise<Uint8Array> {\n const key = await subtle().importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash }, false, [\"sign\"]);\n return new Uint8Array(await subtle().sign(\"HMAC\", key, encoder.encode(message)));\n}\n\nexport function hex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) out += byte.toString(16).padStart(2, \"0\");\n return out;\n}\n\nexport function base64(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\n/** Compares two strings in time that depends only on their length. */\nexport function safeEqual(a: string, b: string): boolean {\n const left = encoder.encode(a);\n const right = encoder.encode(b);\n if (left.length !== right.length) return false;\n let diff = 0;\n for (let i = 0; i < left.length; i++) diff |= (left[i] ?? 0) ^ (right[i] ?? 0);\n return diff === 0;\n}\n\n/** The raw body as text, whatever form the framework hands it in. */\nexport function bodyText(body: string | Uint8Array | ArrayBuffer): string {\n if (typeof body === \"string\") return body;\n return new TextDecoder().decode(body instanceof Uint8Array ? body : new Uint8Array(body));\n}\n\nexport function parseJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n","/**\n * Niadra for the ElevenLabs Agents Platform, on the server side: a phone call reaches ElevenLabs,\n * ElevenLabs calls your webhooks, and these handlers answer them. No ElevenLabs package is needed.\n *\n * - `initiation`: the \"conversation initiation client data\" webhook. Opens the conversation by\n * ElevenLabs' `conversation_id`, records what the call proved, reads the context and answers it\n * as dynamic variables: put `{{niadra_context}}` in the agent's system prompt (and\n * `{{niadra_turn}}` where the live turns from other channels should go).\n * - `tool`: server tools (`type: \"webhook\"`) for the navigation kit. `toolConfigs()` writes their\n * configuration: the conversation id and the caller come from ElevenLabs' system variables,\n * never from the model, so no tool parameter names a customer.\n * - `postCall`: the `post_call_transcription` webhook. Checks `ElevenLabs-Signature`, records every\n * turn of the transcript, the transfers (`transfer_to_agent`, `transfer_to_number`) as handoffs,\n * and ends the conversation.\n *\n * Each handler takes the body and the headers and resolves to `{ status, body }`; the example in\n * `examples/elevenlabs-hono.ts` mounts them on Hono. They only use web APIs, so they run on Node,\n * Deno, Bun, Cloudflare Workers and the Vercel Edge Runtime.\n */\n\nimport type { Niadra } from \"../client.js\";\nimport type { Conversation } from \"../conversation.js\";\nimport { AGENT_MEMORY_TOOL_DEFINITIONS, TOOL_DEFINITIONS } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport { providerOf } from \"../usage.js\";\nimport { Bridge, count, errorName, isRecord, phoneHandle } from \"./shared.js\";\nimport type { AgentMemoryOption, Proof } from \"./shared.js\";\nimport { bodyText, header, hmac, hex, memoryCallStore, parseJson, safeEqual } from \"./webhook.js\";\nimport type { CallRecord, CallStore, HeadersLike, WebhookResponse } from \"./webhook.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof } from \"./shared.js\";\nexport { memoryCallStore } from \"./webhook.js\";\nexport type { CallRecord, CallStore, HeadersLike, WebhookResponse } from \"./webhook.js\";\n\n/** The fields ElevenLabs sends to the initiation webhook, and the system variables it passes to tools. */\nexport interface ElevenLabsCall {\n conversationId: string;\n callerId?: string | undefined;\n calledNumber?: string | undefined;\n agentId?: string | undefined;\n callSid?: string | undefined;\n}\n\nexport interface ElevenLabsOptions {\n niadra: Niadra;\n /**\n * A secret only you and ElevenLabs know, sent by ElevenLabs in `secretHeader` on the initiation\n * webhook and on every tool call (store it as a workspace secret and reference it in the\n * request headers). Required: these endpoints return customer context.\n */\n secret: string;\n /** Defaults to `x-niadra-secret`. */\n secretHeader?: string;\n /** The post-call webhook's HMAC secret, from the ElevenLabs webhook settings. */\n webhookSecret?: string;\n /** Who is calling. Defaults to the caller id as an E.164 phone number. */\n subject?: (call: ElevenLabsCall) => Handle | null | undefined;\n /** What the call proved, such as the carrier's attestation you read from your telephony provider. */\n verify?: (call: ElevenLabsCall) => Proof | null | undefined | PromiseLike<Proof | null | undefined>;\n /** Keeps the caller and level between the webhooks of one call. Defaults to an in-memory store. */\n store?: CallStore;\n /** More dynamic variables for the agent, next to `niadra_context` and `niadra_turn`. */\n dynamicVariables?: (call: ElevenLabsCall) => Record<string, string | number | boolean>;\n /** Time budget of the context read in the initiation webhook, in milliseconds. Defaults to the voice budget. */\n contextTimeout?: number;\n /** The clock for the signature's 30-minute window, in milliseconds. */\n now?: () => number;\n /**\n * The agent's own notes as the dynamic variable `niadra_agent_memory` (put it before\n * `{{niadra_context}}`), and its memory tools among the server tools.\n */\n agentMemory?: AgentMemoryOption;\n}\n\nexport interface ElevenLabsToolConfigOptions {\n /** Where your `tool` handler is served, such as `https://api.acme.com/elevenlabs/tools`. */\n url: string;\n /** The id of the ElevenLabs workspace secret that holds `secret`. */\n secretId: string;\n /** Defaults to `x-niadra-secret`. */\n secretHeader?: string;\n}\n\nexport interface ElevenLabsHandlers {\n initiation(body: unknown, headers: HeadersLike): Promise<WebhookResponse>;\n tool(body: unknown, headers: HeadersLike): Promise<WebhookResponse>;\n /** Takes the raw body: the signature is computed over the exact bytes ElevenLabs sent. */\n postCall(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersLike): Promise<WebhookResponse>;\n /** The server tool configurations for the ElevenLabs API (`tool_config`) or its dashboard. */\n toolConfigs(options: ElevenLabsToolConfigOptions): Record<string, unknown>[];\n}\n\nconst TOOL_FIELD = \"niadra_tool\";\nconst CONVERSATION_FIELD = \"niadra_conversation_id\";\nconst CALLER_FIELD = \"niadra_caller_id\";\nconst SIGNATURE_WINDOW_MS = 30 * 60 * 1000;\nconst TRANSFERS: Record<string, \"agent\" | \"human\"> = { transfer_to_agent: \"agent\", transfer_to_number: \"human\" };\n\n/** The webhook handlers for one ElevenLabs agent. */\nexport function elevenLabs(options: ElevenLabsOptions): ElevenLabsHandlers {\n const store = options.store ?? memoryCallStore();\n const secretHeader = options.secretHeader ?? \"x-niadra-secret\";\n const now = options.now ?? Date.now;\n const logger = options.niadra.logger;\n\n const authorized = (headers: HeadersLike): boolean => {\n const given = header(headers, secretHeader);\n return Boolean(options.secret) && given !== undefined && safeEqual(given, options.secret);\n };\n\n const subjectOf = (call: ElevenLabsCall): Handle | null => {\n try {\n return (options.subject ? options.subject(call) : phoneHandle(call.callerId)) ?? null;\n } catch {\n return null;\n }\n };\n\n const open = (conversationId: string, record: CallRecord): Conversation =>\n options.niadra.conversation({\n subject: record.subject,\n channel: \"voice\",\n conversation_id: conversationId,\n verification: record.verification,\n });\n\n /** The call's record from the store, or rebuilt from what this webhook carries (without verifying again). */\n const recall = async (call: ElevenLabsCall): Promise<CallRecord | null> => {\n try {\n const stored = await store.get(call.conversationId);\n if (stored) return stored;\n } catch (error) {\n logger.warn(`could not read the call store (${errorName(error)})`);\n }\n const subject = subjectOf(call);\n return subject ? { subject, verification: \"V0\" } : null;\n };\n\n async function initiation(body: unknown, headers: HeadersLike): Promise<WebhookResponse> {\n if (!authorized(headers)) return { status: 401, body: { error: \"unauthorized\" } };\n const call = initiationCall(body);\n const variables: Record<string, string | number | boolean> = { niadra_context: \"\", niadra_turn: \"\" };\n if (options.agentMemory) variables.niadra_agent_memory = \"\";\n try {\n Object.assign(variables, call && options.dynamicVariables ? options.dynamicVariables(call) : {});\n } catch (error) {\n logger.warn(`could not build the dynamic variables (${errorName(error)})`);\n }\n const answer = (): WebhookResponse => ({\n status: 200,\n body: { type: \"conversation_initiation_client_data\", dynamic_variables: variables },\n });\n const subject = call ? subjectOf(call) : null;\n if (!call || !subject) return answer();\n\n const conversation = options.niadra.conversation({ subject, channel: \"voice\", conversation_id: call.conversationId });\n const bridge = new Bridge(conversation, options.verify ? () => options.verify?.(call) : undefined, options.agentMemory);\n bridge.begin(); // waited for within timeouts.contextVoiceStart: the agent has not spoken yet\n const read = await bridge.read(options.contextTimeout ? { timeout: options.contextTimeout } : {});\n bridge.injected(read.context);\n variables.niadra_context = read.context.text;\n variables.niadra_turn = read.suffix;\n if (options.agentMemory) variables.niadra_agent_memory = read.memory;\n try {\n await store.set(call.conversationId, {\n subject,\n verification: conversation.verification,\n stamp: conversation.contextStamp,\n });\n } catch (error) {\n logger.warn(`could not write the call store (${errorName(error)})`);\n }\n return answer();\n }\n\n async function tool(body: unknown, headers: HeadersLike): Promise<WebhookResponse> {\n if (!authorized(headers)) return { status: 401, body: { error: \"unauthorized\" } };\n if (!isRecord(body)) return { status: 400, body: { error: \"invalid_body\" } };\n const name = str(body[TOOL_FIELD]);\n const conversationId = str(body[CONVERSATION_FIELD]);\n if (!name || !conversationId) return { status: 400, body: { error: \"invalid_body\" } };\n const record = await recall({ conversationId, callerId: str(body[CALLER_FIELD]) });\n if (!record) return { status: 200, body: { error: \"unavailable\", detail: \"customer history is unavailable right now\" } };\n\n const args: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(body)) {\n if (key !== TOOL_FIELD && key !== CONVERSATION_FIELD && key !== CALLER_FIELD) args[key] = value;\n }\n const specs = new Bridge(open(conversationId, record), undefined, options.agentMemory).tools();\n const spec = specs.find((candidate) => candidate.name === name);\n if (!spec) return { status: 404, body: { error: \"unknown_tool\" } };\n return { status: 200, body: parseJson(await spec.execute(args)) ?? null };\n }\n\n async function postCall(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersLike): Promise<WebhookResponse> {\n const text = bodyText(rawBody);\n if (!options.webhookSecret) {\n logger.warn(\"the ElevenLabs post-call webhook needs `webhookSecret`\");\n return { status: 401, body: { error: \"unauthorized\" } };\n }\n if (!(await validSignature(text, header(headers, \"elevenlabs-signature\"), options.webhookSecret, now()))) {\n return { status: 401, body: { error: \"invalid_signature\" } };\n }\n const event = parseJson(text);\n if (!isRecord(event) || event.type !== \"post_call_transcription\" || !isRecord(event.data)) {\n return { status: 200, body: { ignored: true } };\n }\n const data = event.data;\n const conversationId = str(data.conversation_id);\n if (!conversationId) return { status: 400, body: { error: \"invalid_body\" } };\n const record = await recall({ conversationId, callerId: callerOf(data) });\n if (!record) return { status: 200, body: { recorded: 0 } };\n\n const bridge = new Bridge(open(conversationId, record));\n const started = count(isRecord(data.metadata) ? data.metadata.start_time_unix_secs : undefined);\n const transcript = Array.isArray(data.transcript) ? (data.transcript as unknown[]) : [];\n let recorded = 0;\n for (const [index, turn] of transcript.entries()) {\n if (!isRecord(turn)) continue;\n const message = str(turn.message);\n const at = typeof turn.time_in_call_secs === \"number\" && started !== null ? new Date((started + turn.time_in_call_secs) * 1000) : undefined;\n const base = { idempotency_key: `elevenlabs:${conversationId}:${index}`, ...(at ? { occurred_at: at } : {}) };\n if (message && turn.role === \"user\") {\n bridge.customer(message, base);\n recorded++;\n } else if (message && turn.role === \"agent\") {\n const usage = usageOf(turn.llm_usage);\n bridge.agent(message, { ...base, ...(usage ? { usage } : {}), ...(record.stamp ? { context_stamp: record.stamp } : {}) });\n recorded++;\n }\n for (const result of Array.isArray(turn.tool_results) ? (turn.tool_results as unknown[]) : []) {\n if (!isRecord(result) || result.is_error === true) continue;\n const target = TRANSFERS[str(result.tool_name) ?? \"\"];\n if (target) await bridge.handoff(target, transferReason(result));\n }\n }\n await bridge.end();\n await options.niadra.flush();\n return { status: 200, body: { recorded } };\n }\n\n function toolConfigs(config: ElevenLabsToolConfigOptions): Record<string, unknown>[] {\n const headerName = config.secretHeader ?? secretHeader;\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 return definitions.map(({ function: definition }) => {\n const parameters = definition.parameters as { properties?: Record<string, unknown>; required?: string[] };\n const properties: Record<string, unknown> = {};\n for (const [key, schema] of Object.entries(parameters.properties ?? {})) properties[key] = literal(schema);\n properties[TOOL_FIELD] = { type: \"string\", constant_value: definition.name };\n properties[CONVERSATION_FIELD] = { type: \"string\", dynamic_variable: \"system__conversation_id\" };\n properties[CALLER_FIELD] = { type: \"string\", dynamic_variable: \"system__caller_id\" };\n return {\n type: \"webhook\",\n name: definition.name,\n description: definition.description,\n api_schema: {\n url: config.url,\n method: \"POST\",\n request_headers: { [headerName]: { secret_id: config.secretId } },\n request_body_schema: {\n type: \"object\",\n properties,\n required: [...(parameters.required ?? []), TOOL_FIELD, CONVERSATION_FIELD, CALLER_FIELD],\n },\n },\n };\n });\n }\n\n return { initiation, tool, postCall, toolConfigs };\n}\n\n/** Checks `ElevenLabs-Signature: t=<seconds>,v0=<hex HMAC-SHA256 of \"<t>.<body>\">` within 30 minutes. */\nexport async function validSignature(body: string, signature: string | undefined, secret: string, now = Date.now()): Promise<boolean> {\n if (!signature || !secret) return false;\n const parts = signature.split(\",\").map((part) => part.trim());\n const timestamp = parts.find((part) => part.startsWith(\"t=\"))?.slice(2);\n const given = parts.find((part) => part.startsWith(\"v0=\"));\n if (!timestamp || !given || !/^\\d+$/.test(timestamp)) return false;\n const at = Number(timestamp) * 1000;\n if (at < now - SIGNATURE_WINDOW_MS || at > now + SIGNATURE_WINDOW_MS) return false;\n const expected = `v0=${hex(await hmac(\"SHA-256\", secret, `${timestamp}.${body}`))}`;\n return safeEqual(given, expected);\n}\n\nfunction initiationCall(body: unknown): ElevenLabsCall | null {\n if (!isRecord(body)) return null;\n const conversationId = str(body.conversation_id);\n if (!conversationId) return null;\n return {\n conversationId,\n callerId: str(body.caller_id),\n calledNumber: str(body.called_number),\n agentId: str(body.agent_id),\n callSid: str(body.call_sid),\n };\n}\n\nfunction callerOf(data: Record<PropertyKey, unknown>): string | undefined {\n const phone = isRecord(data.metadata) && isRecord(data.metadata.phone_call) ? data.metadata.phone_call : null;\n const external = phone ? str(phone.external_number) : undefined;\n if (external) return external;\n const client = isRecord(data.conversation_initiation_client_data) ? data.conversation_initiation_client_data : null;\n const variables = client && isRecord(client.dynamic_variables) ? client.dynamic_variables : null;\n return variables ? str(variables.system__caller_id) : undefined;\n}\n\nfunction transferReason(result: Record<PropertyKey, unknown>): string | undefined {\n const detail = isRecord(result.result) ? result.result : null;\n if (!detail) return undefined;\n return str(detail.reason) ?? str(detail.condition) ?? undefined;\n}\n\n/** ElevenLabs reports the tokens of each model the turn used; the first model is the agent's. */\nfunction usageOf(value: unknown): ModelUsage | null {\n if (!isRecord(value) || !isRecord(value.model_usage)) return null;\n for (const [model, usage] of Object.entries(value.model_usage)) {\n if (!isRecord(usage)) continue;\n const tokens = (key: string): number => {\n const category = usage[key];\n return isRecord(category) ? (count(category.tokens) ?? 0) : 0;\n };\n const input = tokens(\"input\");\n const read = tokens(\"input_cache_read\");\n const written = tokens(\"input_cache_write\");\n if (input + read + written === 0) continue;\n return { provider: providerOf(model), model, prompt_tokens: input + read + written, cached_tokens: read, cache_write_tokens: written };\n }\n return null;\n}\n\n/** A JSON Schema property in the subset ElevenLabs accepts, with the same descriptions. */\nfunction literal(schema: unknown): Record<string, unknown> {\n if (!isRecord(schema)) return { type: \"string\" };\n const type = typeof schema.type === \"string\" ? schema.type : \"string\";\n const out: Record<string, unknown> = { type };\n if (typeof schema.description === \"string\") out.description = schema.description;\n if (Array.isArray(schema.enum)) out.enum = schema.enum;\n if (type === \"array\") out.items = literal(isRecord(schema.items) ? schema.items : {});\n if (type === \"object\" && isRecord(schema.properties)) {\n const properties: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(schema.properties)) properties[key] = literal(value);\n out.properties = properties;\n if (Array.isArray(schema.required)) out.required = schema.required;\n }\n return out;\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n"]}
1
+ {"version":3,"sources":["../src/tools.ts","../src/usage.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/elevenlabs.ts"],"names":[],"mappings":";;;AAmGO,IAAM,gBAAA,GAA8C;AAAA,EACzD;AAAA,IACE,MAA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AA,CAAQ,MAAA,CAAO,IAAI,CAAA,EAAG,GAAA,CAAI,OAAO,MAAA,CAAO,IAAA;AAClD,EAAA,IAAI,IAAA,KAAS,OAAA,EAAS,GAAA,CAAI,KAAA,GAAQ,OAAA,CAAQ,QAAA,CAAS,MAAA,CAAO,KAAK,CAAA,GAAI,MAAA,CAAO,KAAA,GAAQ,EAAE,CAAA;AACpF,EAAA,IAAI,IAAA,KAAS,QAAA,IAAY,QAAA,CAAS,MAAA,CAAO,UAAU,CAAA,EAAG;AACpD,IAAA,MAAM,aAAsC,EAAC;AAC7C,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,CAAA,IAAK,MAAA,CAAO,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA,EAAG,UAAA,CAAW,GAAG,CAAA,GAAI,QAAQ,KAAK,CAAA;AAC7F,IAAA,GAAA,CAAI,UAAA,GAAa,UAAA;AACjB,IAAA,IAAI,MAAM,OAAA,CAAQ,MAAA,CAAO,QAAQ,CAAA,EAAG,GAAA,CAAI,WAAW,MAAA,CAAO,QAAA;AAAA,EAC5D;AACA,EAAA,OAAO,GAAA;AACT;AAEA,SAAS,IAAI,KAAA,EAAoC;AAC/C,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,MAAA,GAAS,IAAI,KAAA,GAAQ,MAAA;AACjE","file":"elevenlabs.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\", \"system_event\"];\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 'Histórico' line, which already counts recurrences. Returns short items with date, channel and outcome, plus a recurrence count. Open a conversation (`episode:`) or an object (`object:`) with open_history_item; the other items are complete as listed.\",\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 \"system_event\"\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, agent actions and system events in order, newest first, one line each. Use it to leaf through the history when you do not know what to search for; filters.item_kinds also lists the open items, facts, patterns or objects it names. 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 \"system_event\"\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 (`episode:`) or business object (`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. Actions, events, facts and promises are complete as listed and do not open. 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","import { NiadraValidationError } from \"./errors.js\";\nimport { includeText } from \"./constraints/text.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport { toObjectRef } from \"./handles.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type {\n ContextFormat,\n ContextPack,\n ContextRequest,\n ContextResponse,\n CoordinationBlock,\n Include,\n LiveTurn,\n PrefetchRequest,\n TargetModel,\n} from \"./types/context.js\";\nimport type { ConstraintsBlock } from \"./types/signals.js\";\nimport type { StateView } from \"./types/state.js\";\nimport type { Verification, View } from \"./types/vocabulary.js\";\n\n/** Arguments of `context()`. Pass exactly one of `subject` or `object`. */\nexport interface ContextParams {\n /** The customer, by any handle the server knows. */\n subject?: Handle;\n /** A business object, such as an invoice, when the task is about the object rather than a person. */\n object?: ObjectRef | string;\n /** The account or partner the person acts for. Requires an active link between the two. */\n about?: Handle;\n /** Defaults to `chat`. */\n view?: View;\n /**\n * The level proven in this conversation. The server may answer with a lower effective level\n * when the source's ceiling is lower; see `response.verification`.\n */\n verification?: Verification;\n /** Enables the per-conversation cache and the server's pinning of the pack. */\n conversation_id?: string;\n /** For internal agents: the task plays the role of the conversation. */\n task_id?: string;\n /**\n * Other words than the turn to pick this read's slots by. Up to 2,000 characters. Wins over\n * `turn`, and like it never changes the pack.\n */\n query?: string;\n /**\n * The customer's last turn; a conversation passes it for you. It goes as `query` and the answer\n * adds `slots`, what the turn selected from memory, in `suffix`, while the pack stays the\n * conversation's pinned one (and is cached as without it).\n */\n turn?: string | null;\n /** Ask only for what changed since this source last read the subject. */\n delta?: boolean;\n /** The model that will read the pack, so the server can size it for that model's prompt cache. */\n target?: TargetModel;\n /** `json` also returns the pack as typed sections in `pack` (`context-pack.v1`). Defaults to `text`. */\n format?: ContextFormat;\n /**\n * Adds `why` to each of `pack.slots`, naming the retrieval channels that\n * ranked it, the fused score, the weights version and, for a derived line, the rule behind it.\n * Requires `format: \"json\"`. It changes nothing else: the pinned text, the slots chosen and the\n * receipt are the same bytes with or without it.\n */\n explain?: boolean;\n /**\n * Blocks read in the same round trip: `[\"constraints\"]` returns the subject's constraints block, `[\"state\"]`\n * the state of their objects. Each only where the space turned its feature on; a block the space does not\n * serve is left out and not asked again for a while, and the read goes on. The blocks are cached with the\n * pack, so a read that fails serves the last good ones too.\n */\n include?: Include[];\n}\n\n/** Arguments of `prefetch()`: who the turn is about, as in `context()`, and the turn so far. */\nexport interface PrefetchParams {\n subject?: Handle;\n object?: ObjectRef | string;\n about?: Handle;\n /** Defaults to `voice`, where partial transcripts come from. */\n view?: View;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** The partial transcript of the customer's turn. */\n text: string;\n}\n\n/** Per-call options shared by every read method. */\nexport interface RequestOptions {\n /** Overrides the method's default time budget, in milliseconds. */\n timeout?: number | undefined;\n /** Cancels the wait. A request shared with other callers keeps running for them. */\n signal?: AbortSignal | undefined;\n /** Extra headers, such as a W3C `traceparent`. */\n headers?: Record<string, string> | undefined;\n}\n\nexport interface ContextOptions extends RequestOptions {\n /** Pass `false` to skip the per-conversation cache for this call. */\n cache?: boolean | undefined;\n /** For `conversation.context()` and `task.context()`: blocks read in the same round trip. */\n include?: Include[] | undefined;\n /** For `conversation.context()` and `task.context()`: `json` also returns `pack`. */\n format?: ContextFormat | undefined;\n /**\n * For `conversation.context()` and `task.context()`: adds `why` to each of `pack.slots`.\n * Requires `format: \"json\"`.\n */\n explain?: boolean | undefined;\n}\n\n/**\n * Where a `context()` result came from.\n *\n * - `network`: a response the server just sent (or confirmed unchanged).\n * - `cache`: a pack younger than the cache TTL; no request was made.\n * - `stale`: an older pack returned at once while a background request refreshes it.\n * - `fallback`: the request failed and this is the last good pack for the conversation.\n * - `none`: nothing was available; `text` is empty and `error` says why.\n */\nexport type ContextSource = \"network\" | \"cache\" | \"stale\" | \"fallback\" | \"none\";\n\n/** What `context()` resolves to. Always usable: on failure `text` is an empty string. */\nexport interface ContextResult {\n /** The pack, ready for the system prompt. Empty when there is nothing to inject. */\n text: string;\n /**\n * The parts that change turn by turn and belong at the end of the prompt, after the\n * conversation: the live turns from other channels, this turn's slots (what the customer's last\n * turn selected from memory), the blocks asked for by `include` (the state view, the constraints) and the\n * delta, in that order, as the API places them. Empty when there are none.\n */\n suffix: string;\n /** Named values from the pack, for templates that place them individually. */\n variables: Record<string, string>;\n /** The pack as typed sections, when read with `format: \"json\"`; otherwise `null`. */\n pack: ContextPack | null;\n source: ContextSource;\n /**\n * How long ago Niadra sent or confirmed the pack served, in milliseconds: 0 for an answer just received,\n * growing while a cached pack is served (`cache`, `stale`, or `fallback` with Niadra down), and `null` when\n * there is no pack.\n */\n ageMs: number | null;\n /** The response this result was built from; `null` when `source` is `none`. */\n response: ContextResponse | null;\n /** What went wrong, when `source` is `fallback` or `none`. */\n error: NiadraError | null;\n /** With `include: [\"constraints\"]`: the subject's constraints block. */\n constraints?: ConstraintsBlock | null;\n /** With `include: [\"state\"]`: the state of the subject's objects. */\n state?: StateView | null;\n /** With `include: [\"coordination\"]`: what coordination knows of the subject. */\n coordination?: CoordinationBlock | null;\n}\n\nconst VIEW = /^(voice|chat|brief|full|custom|account|partner|task:[a-z0-9_]{1,40})$/;\nconst MAX_QUERY = 2000;\n\n/** Validates the arguments and builds the wire request, without `known_etag`. */\nexport function buildContextRequest(params: ContextParams): ContextRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n if (params.query !== undefined && params.query.length > MAX_QUERY) {\n throw new NiadraValidationError(`query is longer than ${MAX_QUERY} characters`);\n }\n\n const request: ContextRequest = { view: params.view ?? \"chat\" };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n if (params.query) request.query = params.query;\n if (params.delta) request.delta = true;\n if (params.target) request.target = params.target;\n const format: string = params.format ?? \"text\";\n if (format !== \"text\" && format !== \"json\") throw new NiadraValidationError(\"format is `text` or `json`\");\n if (format === \"json\") request.format = \"json\";\n if (params.explain) {\n if (format !== \"json\") throw new NiadraValidationError('explain requires format: \"json\"');\n request.explain = true;\n }\n if (params.include?.length) request.include = [...new Set(params.include)];\n return request;\n}\n\n/** Validates the arguments of `prefetch()` and builds the wire request. */\nexport function buildPrefetchRequest(params: PrefetchParams): PrefetchRequest {\n if ((params.subject === undefined) === (params.object === undefined)) {\n throw new NiadraValidationError(\"pass exactly one of `subject` or `object`\");\n }\n if (params.conversation_id && params.task_id) {\n throw new NiadraValidationError(\"pass `conversation_id` or `task_id`, not both\");\n }\n if (params.view !== undefined && !VIEW.test(params.view)) {\n throw new NiadraValidationError(\"unknown view; task views look like `task:billing`\");\n }\n const text = params.text.trim();\n if (!text || text.length > MAX_QUERY) throw new NiadraValidationError(`text must be 1 to ${MAX_QUERY} characters`);\n const request: PrefetchRequest = { view: params.view ?? \"voice\", query: text };\n if (params.subject) request.subject = params.subject;\n if (params.object !== undefined) request.object = toObjectRef(params.object);\n if (params.about) request.about = params.about;\n if (params.verification) request.verification = params.verification;\n if (params.conversation_id) request.conversation_id = params.conversation_id;\n if (params.task_id) request.task_id = params.task_id;\n return request;\n}\n\n/** Packs are only cached inside a conversation or task, the unit the server pins them to. */\nexport function cacheScope(request: Pick<ContextRequest, \"conversation_id\" | \"task_id\">): string | null {\n if (request.conversation_id) return `conversation:${request.conversation_id}`;\n if (request.task_id) return `task:${request.task_id}`;\n return null;\n}\n\n/**\n * Every field that changes what the server would compile goes into the key, in a fixed order.\n * `delta` does not: a plain read and a delta read of one conversation get the same pinned\n * bytes, so they share one entry.\n */\nexport function cacheKey(request: ContextRequest): string {\n return JSON.stringify([\n request.subject ?? null,\n request.object ?? null,\n request.about ?? null,\n request.view ?? \"chat\",\n request.verification ?? \"V0\",\n request.conversation_id ?? null,\n request.task_id ?? null,\n request.query ?? null,\n request.target ?? null,\n request.format ?? \"text\",\n request.explain ?? false,\n request.include ?? null,\n ]);\n}\n\n/**\n * Applies a `not_modified` answer to the cached pack: the pinned text and its metadata stay,\n * while the parts outside the pin (live turns, delta, coverage, timing) come from the new answer.\n */\nexport function mergeNotModified(cached: ContextResponse, fresh: ContextResponse): ContextResponse {\n return {\n ...fresh,\n not_modified: false,\n text: cached.text ?? null,\n variables: cached.variables,\n version: cached.version,\n etag: cached.etag,\n manifest_hash: cached.manifest_hash ?? null,\n withheld: cached.withheld,\n cache: cached.cache ?? null,\n pack: cached.pack ?? null,\n // The blocks sit outside the pinned pack: a fresh block wins, and a missing one keeps the cached.\n constraints: fresh.constraints ?? cached.constraints ?? null,\n state: fresh.state ?? cached.state ?? null,\n coordination: fresh.coordination ?? cached.coordination ?? null,\n };\n}\n\nexport function resultFrom(\n response: ContextResponse,\n source: ContextSource,\n error: NiadraError | null = null,\n ageMs: number | null = 0,\n): ContextResult {\n // A conversation in the control group gets an empty pack on purpose; it is not an error.\n const holdout = response.path === \"holdout\";\n const text = holdout ? \"\" : (response.text ?? \"\");\n const pack = holdout ? null : (response.pack ?? null);\n const blocks = {\n constraints: response.constraints ?? null,\n state: response.state ?? null,\n coordination: response.coordination ?? null,\n };\n return { text, suffix: renderSuffix(response), variables: response.variables, pack, source, ageMs, response, error, ...blocks };\n}\n\nexport function emptyResult(error: NiadraError | null): ContextResult {\n return { text: \"\", suffix: \"\", variables: {}, pack: null, source: \"none\", ageMs: null, response: null, error, constraints: null, state: null, coordination: null };\n}\n\n/**\n * Renders the live turns, the slots and the delta for the end of the prompt, in that order. Kept\n * outside the pinned pack so that the prompt prefix stays byte-identical across turns and the\n * model provider's prompt cache keeps hitting. Returns an empty string when there is nothing to add.\n */\nexport function renderSuffix(response: ContextResponse): string {\n if (response.path === \"holdout\") return \"\";\n const included = includeText(response.text, response.state, response.constraints);\n return [renderLive(response), response.slots ?? \"\", included, response.delta ?? \"\"].filter(Boolean).join(\"\\n\\n\");\n}\n\n/**\n * Renders the live turns (recent turns from other channels that the pack has not absorbed\n * yet) as one tagged block, or an empty string when there are none. `complete=\"false\"` tells\n * the model the list may be missing turns because the server could not read all of them.\n */\nexport function renderLive(response: ContextResponse): string {\n if (response.path === \"holdout\" || response.live.length === 0) return \"\";\n const complete = response.live_complete ? \"\" : ' complete=\"false\"';\n const lines = response.live.map(renderLiveTurn).join(\"\\n\");\n return `<live_turns source=\"niadra\"${complete}>\\n${lines}\\n</live_turns>`;\n}\n\nfunction renderLiveTurn(turn: LiveTurn): string {\n return `[${utcSeconds(turn.at)}] ${turn.channel} · ${turn.speaker}: ${turn.text}`;\n}\n\n/** The same timestamp form in every SDK, whatever precision or offset the server sent. */\nfunction utcSeconds(at: string): string {\n const ms = Date.parse(at);\n return Number.isNaN(ms) ? at : `${new Date(ms).toISOString().slice(0, 19)}Z`;\n}\n","/**\n * What every framework adapter shares: the five primitives (context before the model call, the\n * turns, the tools, the verification and the handoff) wired the same way, and fail-open.\n *\n * Nothing here throws into the framework: a failed read gives an empty context, a failed write\n * is logged without content, and the agent keeps working without memory.\n */\n\nimport { recordedTool } from \"../capture/tool.js\";\nimport type { Played } from \"../replay/playback.js\";\nimport type { AgentMemoryParams } from \"../agent-memory.js\";\nimport type { TurnParams } from \"../agent-session.js\";\nimport type { CallCapture, TurnFrame } from \"../capture/frame.js\";\nimport type { ContextOptions, ContextResult } from \"../context.js\";\nimport { emptyResult } from \"../context.js\";\nimport type { Conversation, TurnOptions } from \"../conversation.js\";\nimport type { Logger } from \"../logger.js\";\nimport type { Task } from \"../task.js\";\nimport type { BoundTools } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { Verification, VerifyMethod } from \"../types/vocabulary.js\";\n\n/** A customer conversation or an internal agent's task. */\nexport type Session = Conversation | Task;\n\n/** A session, or a function that finds the one the current call belongs to (`null` passes the call through). */\nexport type SessionResolver<S extends Session = Session> = S | (() => S | null | undefined);\n\n/** What the framework proved about the person, recorded with `verify()` before the first context read. */\nexport interface Proof {\n method: VerifyMethod;\n level: Verification;\n /** Defaults to the session's subject. */\n handle?: Handle;\n}\n\n/** A proof, or a function that reads it from the framework when the first context is needed. */\nexport type ProofSource =\n | Proof\n | null\n | undefined\n | (() => Proof | null | undefined | PromiseLike<Proof | null | undefined>);\n\n/**\n * The agent's own working notes: `true` puts the block before the customer's context and offers\n * `search_agent_memory`; `{ write: true }` also offers `remember` (for a key with the\n * `agent_memory:write` scope); the other fields go to `agentMemory()`.\n */\nexport type AgentMemoryOption = boolean | (AgentMemoryParams & { write?: boolean });\n\n/** What goes into the prompt for one model call. */\nexport interface Read {\n context: ContextResult;\n /** The agent's own notes, or an empty string. */\n memory: string;\n /** What goes after the instructions: the notes, then the customer's pack. */\n prefix: string;\n /** What goes at the end: live turns, the turn's slots and deltas. */\n suffix: string;\n}\n\n/** A tool as every framework needs it: the name, the text for the model, the JSON Schema and the call. */\ninterface ToolSpec {\n name: string;\n description: string;\n /** JSON Schema of the arguments. None of them names the customer. */\n parameters: Record<string, unknown>;\n /** Runs the call and returns the text for the model. Never rejects in fail-open mode. */\n execute(args: string | Record<string, unknown>): Promise<string>;\n}\n\nconst ATTESTED: Record<string, Verification> = { A: \"V2\", B: \"V1\", C: \"V1\" };\n\n/**\n * The proof a carrier's STIR/SHAKEN attestation gives a phone call: `A` proves V2, `B` and `C`\n * prove V1, anything else proves nothing (`null`). Accepts the bare letter or the forms carriers\n * and platforms send, such as Twilio's `TN-Validation-Passed-A`.\n */\nexport function attestationProof(attestation: string | null | undefined): Proof | null {\n if (!attestation) return null;\n const value = attestation.trim().toUpperCase();\n if (value.includes(\"FAILED\") || value.startsWith(\"NO-\")) return null;\n const letter = value.length === 1 ? value : /PASSED-([ABC])$/.exec(value)?.[1];\n const level = letter ? ATTESTED[letter] : undefined;\n return level ? { method: \"network_attestation\", level } : null;\n}\n\nexport function resolveSession<S extends Session>(source: SessionResolver<S>): S | null {\n if (typeof source !== \"function\") return source;\n try {\n return source() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction isConversation(session: Session): session is Conversation {\n return \"customer\" in session && typeof session.customer === \"function\";\n}\n\n/** A phone number as an E.164 handle, or `null` when it does not look like one. */\nexport function phoneHandle(value: string | null | undefined): Handle | null {\n const raw = value?.trim().replace(/^tel:/i, \"\").replace(/[\\s().-]/g, \"\");\n if (!raw) return null;\n const e164 = raw.startsWith(\"+\") ? raw : `+${raw}`;\n return /^\\+[1-9]\\d{6,14}$/.test(e164) ? { type: \"phone_e164\", value: e164 } : null;\n}\n\nexport function errorName(error: unknown): string {\n return error instanceof Error ? error.name : typeof error;\n}\n\n/**\n * One session as an adapter drives it. Keeps the verification to a single call made before the\n * first context read, and turns every failure into a log line.\n */\nexport class Bridge {\n private proving: Promise<void> | null = null;\n /** `begin()` started the first read of a call: the first `context()` waits for it with `ready()`. */\n private begun = false;\n private opened = false;\n\n constructor(\n readonly session: Session,\n private readonly proof?: ProofSource,\n private readonly memory: AgentMemoryOption = false,\n ) {}\n\n /**\n * The context and, when enabled, the agent's notes, read side by side within the same budget.\n * Never rejects.\n */\n async read(options: ContextOptions = {}): Promise<Read> {\n const memoryParams = this.memory === false ? null : this.memory === true ? {} : withoutWrite(this.memory);\n const [context, memory] = await Promise.all([\n this.context(options),\n memoryParams ? this.agentMemory(memoryParams, options) : Promise.resolve(\"\"),\n ]);\n return { context, memory, prefix: [memory, context.text].filter(Boolean).join(\"\\n\\n\"), suffix: context.suffix };\n }\n\n get logger(): Logger {\n return this.session.logger;\n }\n\n /**\n * Starts the first read of a call now, in the background, after the proof when one was given (the\n * pack depends on the level it proves): at call start, so the read runs while the call is set up.\n * The first `context()` then waits for it within `timeouts.contextVoiceStart`. Never throws.\n */\n begin(): void {\n const session = this.session;\n if (!isConversation(session)) return;\n const start = (): void => {\n this.safe(\"start the first read\", () => {\n // False off the voice read path (a chat view, the cache off): reads go on as before.\n this.begun = session.begin();\n });\n };\n if (this.proof === undefined || this.proof === null) start();\n else void this.verifyOnce().then(start);\n }\n\n /** Verifies once (when a proof was given), then reads the context. Never rejects. */\n async context(options: ContextOptions = {}): Promise<ContextResult> {\n await this.verifyOnce();\n try {\n const session = this.session;\n if (this.begun && !this.opened && isConversation(session)) {\n this.opened = true;\n // The call's first read, begun at call start: waited for within its own, longer budget.\n await session.ready(options.timeout === undefined ? {} : { timeout: options.timeout });\n }\n return await this.session.context(options);\n } catch (error) {\n this.logger.warn(`could not read context (${errorName(error)})`);\n return emptyResult(null);\n }\n }\n\n /** Records that `context` went into the prompt, unless it was empty for a reason other than the holdout. */\n injected(context: ContextResult): void {\n if (!context.text && !context.suffix && context.response?.path !== \"holdout\") return;\n this.safe(\"mark the injection\", () => {\n this.session.markInjected(context);\n });\n }\n\n customer(text: string, options: TurnOptions = {}): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"record the customer's turn\", () => session.customer(text, options));\n }\n\n /** Sends the customer's turn so far, while they speak. In the background; never throws. */\n prefetch(text: string): void {\n const session = this.session;\n if (!text.trim() || !isConversation(session)) return;\n this.safe(\"prefetch the turn\", () => session.prefetch(text));\n }\n\n agent(text: string, options: TurnOptions = {}): void {\n if (!text.trim()) return;\n this.safe(\"record the agent's turn\", () => this.session.agent(text, options));\n }\n\n /** Records a transfer. Tasks have no transfer; the call is ignored for them. */\n async handoff(target: \"agent\" | \"human\", reason?: string): Promise<void> {\n const session = this.session;\n if (!isConversation(session)) return;\n try {\n await session.handoff(reason ? { target, reason } : { target });\n } catch (error) {\n this.logger.warn(`could not record the handoff (${errorName(error)})`);\n }\n }\n\n async end(): Promise<void> {\n try {\n await this.session.end();\n } catch (error) {\n this.logger.warn(`could not end the session (${errorName(error)})`);\n }\n }\n\n /** The navigation kit as plain specs (with the agent's memory tools when enabled), or none for a task about an object only. */\n tools(): ToolSpec[] {\n let bound: BoundTools | null;\n try {\n const memory = this.memory;\n bound = this.session.tools(memory === false ? {} : { agentMemory: true, writeAgentMemory: memory !== true && memory.write === true });\n } catch (error) {\n this.logger.warn(`could not build the tools (${errorName(error)})`);\n return [];\n }\n return bound ? toolSpecs(bound) : [];\n }\n\n private async agentMemory(params: AgentMemoryParams, options: ContextOptions): Promise<string> {\n try {\n const result = await this.session.agentMemory(params, options.timeout === undefined ? {} : { timeout: options.timeout });\n return result.text;\n } catch (error) {\n this.logger.warn(`could not read the agent's memory (${errorName(error)})`);\n return \"\";\n }\n }\n\n private async verifyOnce(): Promise<void> {\n if (this.proof === undefined || this.proof === null) return;\n this.proving ??= this.runVerify();\n await this.proving;\n }\n\n private async runVerify(): Promise<void> {\n try {\n const source = this.proof;\n const proof = typeof source === \"function\" ? await source() : source;\n if (!proof) return;\n await this.session.verify(proof);\n } catch (error) {\n this.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n\n private safe(what: string, run: () => unknown): void {\n try {\n run();\n } catch (error) {\n this.logger.warn(`could not ${what} (${errorName(error)})`);\n }\n }\n}\n\nfunction withoutWrite(option: AgentMemoryParams & { write?: boolean }): AgentMemoryParams {\n const { write: _, ...params } = option;\n return params;\n}\n\n/** The bound kit as specs. The customer stays inside `bound`; no parameter names them. */\nfunction toolSpecs(bound: BoundTools): ToolSpec[] {\n return bound.definitions.map(({ function: definition }) => ({\n name: definition.name,\n description: definition.description,\n parameters: definition.parameters,\n execute: (args) => bound.call(definition.name, args),\n }));\n}\n\n/** The text of a message content in the shapes model APIs use: a string, or a list of text parts. */\nexport function textOf(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content as unknown[]) {\n if (typeof part === \"string\") parts.push(part);\n else if (isRecord(part) && typeof part.text === \"string\" && (part.type === undefined || part.type === \"text\")) {\n parts.push(part.text);\n }\n }\n return parts.join(\"\");\n}\n\nexport function isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/** A non-negative integer, or `null`. */\nexport function count(value: unknown): number | null {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : null;\n}\n\n/**\n * The turn records an adapter keeps from its framework's callbacks, keyed by the framework's own ids (a\n * run, a request, a tool call id). A run starting while the session has a turn in progress (yours, from\n * `conversation.turn()`, or a replay's) records into it; otherwise the adapter opens its own turn and closes\n * it when the run ends. A tool call recorded here is taken over by a `tool()` wrapper running inside it, so\n * the call is recorded once. Every method does nothing when turns are off and never throws.\n */\nexport class TurnHooks {\n /** Runs held open at most; past it the oldest run's turn closes, incomplete (a run whose end never came). */\n static readonly MAX_OPEN = 100;\n private readonly frames = new Map<string, { frame: TurnFrame; own: boolean }>();\n private readonly calls = new Map<string, CallCapture>();\n\n constructor(\n readonly adapter: string,\n readonly enabled: boolean,\n ) {}\n\n /** The turn of the run `key`: the session's turn in progress, or a new one of its own. */\n open(session: Session, key: string, params: TurnParams = {}): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = this.frames.get(key);\n if (held !== undefined) return held.frame;\n try {\n const active = session.activeTurn();\n if (active !== undefined && !this.owns(active)) {\n this.frames.set(key, { frame: active, own: false });\n return active;\n }\n const frame = session.openTurn({ ...params, adapter: this.adapter });\n this.frames.set(key, { frame, own: true });\n if (this.frames.size > TurnHooks.MAX_OPEN) {\n const [oldest] = this.frames.keys();\n if (oldest !== undefined) {\n this.frames.get(oldest)?.frame.incomplete();\n this.close(oldest);\n }\n }\n return frame;\n } catch (error) {\n session.logger.warn(`could not open the turn (${errorName(error)})`);\n return undefined;\n }\n }\n\n /** The turn of `key`, else the session's turn in progress. */\n frame(session: Session, key?: string): TurnFrame | undefined {\n if (!this.enabled) return undefined;\n const held = key === undefined ? undefined : this.frames.get(key);\n const frame = held?.frame ?? session.activeTurn();\n return frame === undefined || frame.closed ? undefined : frame;\n }\n\n has(key: string): boolean {\n return this.frames.has(key);\n }\n\n private owns(frame: TurnFrame): boolean {\n for (const held of this.frames.values()) if (held.own && held.frame === frame) return true;\n return false;\n }\n\n /** Ends the run `key`: a turn the adapter opened closes; the calls it left open failed. */\n close(key: string, error?: unknown): void {\n const held = this.frames.get(key);\n if (held === undefined) return;\n this.frames.delete(key);\n for (const [callKey, call] of this.calls) {\n if (call.frame !== held.frame) continue;\n this.calls.delete(callKey);\n if (held.own) call.failed(error ?? \"error\");\n }\n if (held.own) held.frame.close(error);\n }\n\n /** A tool call starting, keyed by `callKey`; `callId` is the provider's id of the call, when there is one. */\n toolStart(session: Session, callKey: string, name: string, args: unknown, options: { frameKey?: string; callId?: string | null } = {}): void {\n const frame = this.frame(session, options.frameKey);\n if (frame === undefined) return;\n try {\n this.calls.set(callKey, frame.toolCall(name, args, { callId: options.callId ?? null, adoptable: true }));\n } catch {\n frame.incomplete();\n }\n }\n\n /**\n * In a replay, how a framework tool the adapter stands in for answers: the recorded result of a call with the\n * same arguments, or empty (a divergence), never the live tool. `null` outside a replay, and for a function\n * wrapped with `tool()`, which answers itself.\n */\n replayed(session: Session, name: string, args: unknown, fn?: unknown, frameKey?: string): Played | null {\n const frame = this.enabled ? this.frame(session, frameKey) : session.activeTurn();\n if (frame?.playback == null || (fn !== undefined && recordedTool(fn) !== null)) return null;\n return frame.playback.answer(name, args, false);\n }\n\n toolEnd(callKey: string, result?: unknown, error?: unknown): void {\n const call = this.calls.get(callKey);\n if (call === undefined) return;\n this.calls.delete(callKey);\n try {\n if (error !== undefined) call.failed(error);\n else call.result(result);\n } catch {\n call.frame.incomplete();\n }\n }\n\n /** A model call that ended, with its tokens when the framework reported them. */\n model(\n session: Session,\n model: string | null | undefined,\n tokens: { in?: number | null; out?: number | null; cached?: number | null } = {},\n frameKey?: string,\n ): void {\n const frame = this.frame(session, frameKey);\n if (frame === undefined) return;\n try {\n frame.modelCall(model, { tokensIn: tokens.in ?? null, tokensOut: tokens.out ?? null, tokensCached: tokens.cached ?? 0 });\n } catch {\n frame.incomplete();\n }\n }\n}\n","/**\n * Helpers for the webhook adapters (ElevenLabs, Vapi, WhatsApp, Twilio): signatures with Web\n * Crypto and header lookup. Only web APIs, so the handlers run on Node 20+, Deno, Bun, Cloudflare\n * Workers and the Vercel Edge Runtime alike.\n */\n\nimport type { Handle } from \"../types/common.js\";\nimport type { ContextStamp } from \"../types/events.js\";\nimport type { Verification } from \"../types/vocabulary.js\";\n\n/**\n * What a call's first webhook learned, for the webhooks that come later in the same call (tool\n * calls, the end-of-call report): who the caller is, the level they proved and the context stamp.\n */\nexport interface CallRecord {\n subject: Handle;\n verification: Verification;\n stamp?: ContextStamp | null;\n}\n\n/**\n * Where the webhook adapters keep a `CallRecord` between requests, by the platform's call id.\n * The default lives in this process's memory; on serverless or several instances, pass one backed\n * by your key-value store.\n */\nexport interface CallStore {\n get(id: string): CallRecord | undefined | PromiseLike<CallRecord | undefined>;\n set(id: string, record: CallRecord): void | PromiseLike<void>;\n}\n\n/** An in-memory `CallStore` that keeps the most recent `max` calls. */\nexport function memoryCallStore(max = 10_000): CallStore {\n const calls = new Map<string, CallRecord>();\n return {\n get: (id) => calls.get(id),\n set: (id, record) => {\n calls.delete(id);\n calls.set(id, record);\n if (calls.size > max) {\n const oldest = calls.keys().next().value;\n if (oldest !== undefined) calls.delete(oldest);\n }\n },\n };\n}\n\n/** Request headers as a `Headers` object or a plain record (any case). */\nexport type HeadersLike = Headers | Record<string, string | string[] | undefined>;\n\n/** What a handler answers: the HTTP status and a JSON-serializable body (`null` for no body). */\nexport interface WebhookResponse<B = unknown> {\n status: number;\n body: B;\n}\n\nexport function header(headers: HeadersLike, name: string): string | undefined {\n if (typeof (headers as Headers).get === \"function\") return (headers as Headers).get(name) ?? undefined;\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(headers as Record<string, string | string[] | undefined>)) {\n if (key.toLowerCase() !== wanted) continue;\n return Array.isArray(value) ? value[0] : value;\n }\n return undefined;\n}\n\nfunction subtle(): SubtleCrypto {\n const crypto = (globalThis as { crypto?: Crypto }).crypto;\n if (!crypto?.subtle) throw new Error(\"Web Crypto is not available on this runtime\");\n return crypto.subtle;\n}\n\nconst encoder = new TextEncoder();\n\nexport async function hmac(hash: \"SHA-1\" | \"SHA-256\", secret: string, message: string): Promise<Uint8Array> {\n const key = await subtle().importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash }, false, [\"sign\"]);\n return new Uint8Array(await subtle().sign(\"HMAC\", key, encoder.encode(message)));\n}\n\nexport function hex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) out += byte.toString(16).padStart(2, \"0\");\n return out;\n}\n\nexport function base64(bytes: Uint8Array): string {\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n}\n\n/** Compares two strings in time that depends only on their length. */\nexport function safeEqual(a: string, b: string): boolean {\n const left = encoder.encode(a);\n const right = encoder.encode(b);\n if (left.length !== right.length) return false;\n let diff = 0;\n for (let i = 0; i < left.length; i++) diff |= (left[i] ?? 0) ^ (right[i] ?? 0);\n return diff === 0;\n}\n\n/** The raw body as text, whatever form the framework hands it in. */\nexport function bodyText(body: string | Uint8Array | ArrayBuffer): string {\n if (typeof body === \"string\") return body;\n return new TextDecoder().decode(body instanceof Uint8Array ? body : new Uint8Array(body));\n}\n\nexport function parseJson(text: string): unknown {\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return undefined;\n }\n}\n","/**\n * Niadra for the ElevenLabs Agents Platform, on the server side: a phone call reaches ElevenLabs,\n * ElevenLabs calls your webhooks, and these handlers answer them. No ElevenLabs package is needed.\n *\n * - `initiation`: the \"conversation initiation client data\" webhook. Opens the conversation by\n * ElevenLabs' `conversation_id`, records what the call proved, reads the context and answers it\n * as dynamic variables: put `{{niadra_context}}` in the agent's system prompt (and\n * `{{niadra_turn}}` where the live turns from other channels should go).\n * - `tool`: server tools (`type: \"webhook\"`) for the navigation kit. `toolConfigs()` writes their\n * configuration: the conversation id and the caller come from ElevenLabs' system variables,\n * never from the model, so no tool parameter names a customer.\n * - `postCall`: the `post_call_transcription` webhook. Checks `ElevenLabs-Signature`, records every\n * turn of the transcript, the transfers (`transfer_to_agent`, `transfer_to_number`) as handoffs,\n * and ends the conversation.\n *\n * Each handler takes the body and the headers and resolves to `{ status, body }`; the example in\n * `examples/elevenlabs-hono.ts` mounts them on Hono. They only use web APIs, so they run on Node,\n * Deno, Bun, Cloudflare Workers and the Vercel Edge Runtime.\n */\n\nimport type { Niadra } from \"../client.js\";\nimport type { Conversation } from \"../conversation.js\";\nimport { AGENT_MEMORY_TOOL_DEFINITIONS, TOOL_DEFINITIONS } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport type { ModelUsage } from \"../types/events.js\";\nimport { providerOf } from \"../usage.js\";\nimport { Bridge, count, errorName, isRecord, phoneHandle } from \"./shared.js\";\nimport type { AgentMemoryOption, Proof } from \"./shared.js\";\nimport { bodyText, header, hmac, hex, memoryCallStore, parseJson, safeEqual } from \"./webhook.js\";\nimport type { CallRecord, CallStore, HeadersLike, WebhookResponse } from \"./webhook.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { AgentMemoryOption, Proof } from \"./shared.js\";\nexport { memoryCallStore } from \"./webhook.js\";\nexport type { CallRecord, CallStore, HeadersLike, WebhookResponse } from \"./webhook.js\";\n\n/** The fields ElevenLabs sends to the initiation webhook, and the system variables it passes to tools. */\nexport interface ElevenLabsCall {\n conversationId: string;\n callerId?: string | undefined;\n calledNumber?: string | undefined;\n agentId?: string | undefined;\n callSid?: string | undefined;\n}\n\nexport interface ElevenLabsOptions {\n niadra: Niadra;\n /**\n * A secret only you and ElevenLabs know, sent by ElevenLabs in `secretHeader` on the initiation\n * webhook and on every tool call (store it as a workspace secret and reference it in the\n * request headers). Required: these endpoints return customer context.\n */\n secret: string;\n /** Defaults to `x-niadra-secret`. */\n secretHeader?: string;\n /** The post-call webhook's HMAC secret, from the ElevenLabs webhook settings. */\n webhookSecret?: string;\n /** Who is calling. Defaults to the caller id as an E.164 phone number. */\n subject?: (call: ElevenLabsCall) => Handle | null | undefined;\n /** What the call proved, such as the carrier's attestation you read from your telephony provider. */\n verify?: (call: ElevenLabsCall) => Proof | null | undefined | PromiseLike<Proof | null | undefined>;\n /** Keeps the caller and level between the webhooks of one call. Defaults to an in-memory store. */\n store?: CallStore;\n /** More dynamic variables for the agent, next to `niadra_context` and `niadra_turn`. */\n dynamicVariables?: (call: ElevenLabsCall) => Record<string, string | number | boolean>;\n /** Time budget of the context read in the initiation webhook, in milliseconds. Defaults to the voice budget. */\n contextTimeout?: number;\n /** The clock for the signature's 30-minute window, in milliseconds. */\n now?: () => number;\n /**\n * The agent's own notes as the dynamic variable `niadra_agent_memory` (put it before\n * `{{niadra_context}}`), and its memory tools among the server tools.\n */\n agentMemory?: AgentMemoryOption;\n}\n\nexport interface ElevenLabsToolConfigOptions {\n /** Where your `tool` handler is served, such as `https://api.acme.com/elevenlabs/tools`. */\n url: string;\n /** The id of the ElevenLabs workspace secret that holds `secret`. */\n secretId: string;\n /** Defaults to `x-niadra-secret`. */\n secretHeader?: string;\n}\n\nexport interface ElevenLabsHandlers {\n initiation(body: unknown, headers: HeadersLike): Promise<WebhookResponse>;\n tool(body: unknown, headers: HeadersLike): Promise<WebhookResponse>;\n /** Takes the raw body: the signature is computed over the exact bytes ElevenLabs sent. */\n postCall(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersLike): Promise<WebhookResponse>;\n /** The server tool configurations for the ElevenLabs API (`tool_config`) or its dashboard. */\n toolConfigs(options: ElevenLabsToolConfigOptions): Record<string, unknown>[];\n}\n\nconst TOOL_FIELD = \"niadra_tool\";\nconst CONVERSATION_FIELD = \"niadra_conversation_id\";\nconst CALLER_FIELD = \"niadra_caller_id\";\nconst SIGNATURE_WINDOW_MS = 30 * 60 * 1000;\nconst TRANSFERS: Record<string, \"agent\" | \"human\"> = { transfer_to_agent: \"agent\", transfer_to_number: \"human\" };\n\n/** The webhook handlers for one ElevenLabs agent. */\nexport function elevenLabs(options: ElevenLabsOptions): ElevenLabsHandlers {\n const store = options.store ?? memoryCallStore();\n const secretHeader = options.secretHeader ?? \"x-niadra-secret\";\n const now = options.now ?? Date.now;\n const logger = options.niadra.logger;\n\n const authorized = (headers: HeadersLike): boolean => {\n const given = header(headers, secretHeader);\n return Boolean(options.secret) && given !== undefined && safeEqual(given, options.secret);\n };\n\n const subjectOf = (call: ElevenLabsCall): Handle | null => {\n try {\n return (options.subject ? options.subject(call) : phoneHandle(call.callerId)) ?? null;\n } catch {\n return null;\n }\n };\n\n const open = (conversationId: string, record: CallRecord): Conversation =>\n options.niadra.conversation({\n subject: record.subject,\n channel: \"voice\",\n conversation_id: conversationId,\n verification: record.verification,\n });\n\n /** The call's record from the store, or rebuilt from what this webhook carries (without verifying again). */\n const recall = async (call: ElevenLabsCall): Promise<CallRecord | null> => {\n try {\n const stored = await store.get(call.conversationId);\n if (stored) return stored;\n } catch (error) {\n logger.warn(`could not read the call store (${errorName(error)})`);\n }\n const subject = subjectOf(call);\n return subject ? { subject, verification: \"V0\" } : null;\n };\n\n async function initiation(body: unknown, headers: HeadersLike): Promise<WebhookResponse> {\n if (!authorized(headers)) return { status: 401, body: { error: \"unauthorized\" } };\n const call = initiationCall(body);\n const variables: Record<string, string | number | boolean> = { niadra_context: \"\", niadra_turn: \"\" };\n if (options.agentMemory) variables.niadra_agent_memory = \"\";\n try {\n Object.assign(variables, call && options.dynamicVariables ? options.dynamicVariables(call) : {});\n } catch (error) {\n logger.warn(`could not build the dynamic variables (${errorName(error)})`);\n }\n const answer = (): WebhookResponse => ({\n status: 200,\n body: { type: \"conversation_initiation_client_data\", dynamic_variables: variables },\n });\n const subject = call ? subjectOf(call) : null;\n if (!call || !subject) return answer();\n\n const conversation = options.niadra.conversation({ subject, channel: \"voice\", conversation_id: call.conversationId });\n const bridge = new Bridge(conversation, options.verify ? () => options.verify?.(call) : undefined, options.agentMemory);\n bridge.begin(); // waited for within timeouts.contextVoiceStart: the agent has not spoken yet\n const read = await bridge.read(options.contextTimeout ? { timeout: options.contextTimeout } : {});\n bridge.injected(read.context);\n variables.niadra_context = read.context.text;\n variables.niadra_turn = read.suffix;\n if (options.agentMemory) variables.niadra_agent_memory = read.memory;\n try {\n await store.set(call.conversationId, {\n subject,\n verification: conversation.verification,\n stamp: conversation.contextStamp,\n });\n } catch (error) {\n logger.warn(`could not write the call store (${errorName(error)})`);\n }\n return answer();\n }\n\n async function tool(body: unknown, headers: HeadersLike): Promise<WebhookResponse> {\n if (!authorized(headers)) return { status: 401, body: { error: \"unauthorized\" } };\n if (!isRecord(body)) return { status: 400, body: { error: \"invalid_body\" } };\n const name = str(body[TOOL_FIELD]);\n const conversationId = str(body[CONVERSATION_FIELD]);\n if (!name || !conversationId) return { status: 400, body: { error: \"invalid_body\" } };\n const record = await recall({ conversationId, callerId: str(body[CALLER_FIELD]) });\n if (!record) return { status: 200, body: { error: \"unavailable\", detail: \"customer history is unavailable right now\" } };\n\n const args: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(body)) {\n if (key !== TOOL_FIELD && key !== CONVERSATION_FIELD && key !== CALLER_FIELD) args[key] = value;\n }\n const specs = new Bridge(open(conversationId, record), undefined, options.agentMemory).tools();\n const spec = specs.find((candidate) => candidate.name === name);\n if (!spec) return { status: 404, body: { error: \"unknown_tool\" } };\n return { status: 200, body: parseJson(await spec.execute(args)) ?? null };\n }\n\n async function postCall(rawBody: string | Uint8Array | ArrayBuffer, headers: HeadersLike): Promise<WebhookResponse> {\n const text = bodyText(rawBody);\n if (!options.webhookSecret) {\n logger.warn(\"the ElevenLabs post-call webhook needs `webhookSecret`\");\n return { status: 401, body: { error: \"unauthorized\" } };\n }\n if (!(await validSignature(text, header(headers, \"elevenlabs-signature\"), options.webhookSecret, now()))) {\n return { status: 401, body: { error: \"invalid_signature\" } };\n }\n const event = parseJson(text);\n if (!isRecord(event) || event.type !== \"post_call_transcription\" || !isRecord(event.data)) {\n return { status: 200, body: { ignored: true } };\n }\n const data = event.data;\n const conversationId = str(data.conversation_id);\n if (!conversationId) return { status: 400, body: { error: \"invalid_body\" } };\n const record = await recall({ conversationId, callerId: callerOf(data) });\n if (!record) return { status: 200, body: { recorded: 0 } };\n\n const bridge = new Bridge(open(conversationId, record));\n const started = count(isRecord(data.metadata) ? data.metadata.start_time_unix_secs : undefined);\n const transcript = Array.isArray(data.transcript) ? (data.transcript as unknown[]) : [];\n let recorded = 0;\n for (const [index, turn] of transcript.entries()) {\n if (!isRecord(turn)) continue;\n const message = str(turn.message);\n const at = typeof turn.time_in_call_secs === \"number\" && started !== null ? new Date((started + turn.time_in_call_secs) * 1000) : undefined;\n const base = { idempotency_key: `elevenlabs:${conversationId}:${index}`, ...(at ? { occurred_at: at } : {}) };\n if (message && turn.role === \"user\") {\n bridge.customer(message, base);\n recorded++;\n } else if (message && turn.role === \"agent\") {\n const usage = usageOf(turn.llm_usage);\n bridge.agent(message, { ...base, ...(usage ? { usage } : {}), ...(record.stamp ? { context_stamp: record.stamp } : {}) });\n recorded++;\n }\n for (const result of Array.isArray(turn.tool_results) ? (turn.tool_results as unknown[]) : []) {\n if (!isRecord(result) || result.is_error === true) continue;\n const target = TRANSFERS[str(result.tool_name) ?? \"\"];\n if (target) await bridge.handoff(target, transferReason(result));\n }\n }\n await bridge.end();\n await options.niadra.flush();\n return { status: 200, body: { recorded } };\n }\n\n function toolConfigs(config: ElevenLabsToolConfigOptions): Record<string, unknown>[] {\n const headerName = config.secretHeader ?? secretHeader;\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 return definitions.map(({ function: definition }) => {\n const parameters = definition.parameters as { properties?: Record<string, unknown>; required?: string[] };\n const properties: Record<string, unknown> = {};\n for (const [key, schema] of Object.entries(parameters.properties ?? {})) properties[key] = literal(schema);\n properties[TOOL_FIELD] = { type: \"string\", constant_value: definition.name };\n properties[CONVERSATION_FIELD] = { type: \"string\", dynamic_variable: \"system__conversation_id\" };\n properties[CALLER_FIELD] = { type: \"string\", dynamic_variable: \"system__caller_id\" };\n return {\n type: \"webhook\",\n name: definition.name,\n description: definition.description,\n api_schema: {\n url: config.url,\n method: \"POST\",\n request_headers: { [headerName]: { secret_id: config.secretId } },\n request_body_schema: {\n type: \"object\",\n properties,\n required: [...(parameters.required ?? []), TOOL_FIELD, CONVERSATION_FIELD, CALLER_FIELD],\n },\n },\n };\n });\n }\n\n return { initiation, tool, postCall, toolConfigs };\n}\n\n/** Checks `ElevenLabs-Signature: t=<seconds>,v0=<hex HMAC-SHA256 of \"<t>.<body>\">` within 30 minutes. */\nexport async function validSignature(body: string, signature: string | undefined, secret: string, now = Date.now()): Promise<boolean> {\n if (!signature || !secret) return false;\n const parts = signature.split(\",\").map((part) => part.trim());\n const timestamp = parts.find((part) => part.startsWith(\"t=\"))?.slice(2);\n const given = parts.find((part) => part.startsWith(\"v0=\"));\n if (!timestamp || !given || !/^\\d+$/.test(timestamp)) return false;\n const at = Number(timestamp) * 1000;\n if (at < now - SIGNATURE_WINDOW_MS || at > now + SIGNATURE_WINDOW_MS) return false;\n const expected = `v0=${hex(await hmac(\"SHA-256\", secret, `${timestamp}.${body}`))}`;\n return safeEqual(given, expected);\n}\n\nfunction initiationCall(body: unknown): ElevenLabsCall | null {\n if (!isRecord(body)) return null;\n const conversationId = str(body.conversation_id);\n if (!conversationId) return null;\n return {\n conversationId,\n callerId: str(body.caller_id),\n calledNumber: str(body.called_number),\n agentId: str(body.agent_id),\n callSid: str(body.call_sid),\n };\n}\n\nfunction callerOf(data: Record<PropertyKey, unknown>): string | undefined {\n const phone = isRecord(data.metadata) && isRecord(data.metadata.phone_call) ? data.metadata.phone_call : null;\n const external = phone ? str(phone.external_number) : undefined;\n if (external) return external;\n const client = isRecord(data.conversation_initiation_client_data) ? data.conversation_initiation_client_data : null;\n const variables = client && isRecord(client.dynamic_variables) ? client.dynamic_variables : null;\n return variables ? str(variables.system__caller_id) : undefined;\n}\n\nfunction transferReason(result: Record<PropertyKey, unknown>): string | undefined {\n const detail = isRecord(result.result) ? result.result : null;\n if (!detail) return undefined;\n return str(detail.reason) ?? str(detail.condition) ?? undefined;\n}\n\n/** ElevenLabs reports the tokens of each model the turn used; the first model is the agent's. */\nfunction usageOf(value: unknown): ModelUsage | null {\n if (!isRecord(value) || !isRecord(value.model_usage)) return null;\n for (const [model, usage] of Object.entries(value.model_usage)) {\n if (!isRecord(usage)) continue;\n const tokens = (key: string): number => {\n const category = usage[key];\n return isRecord(category) ? (count(category.tokens) ?? 0) : 0;\n };\n const input = tokens(\"input\");\n const read = tokens(\"input_cache_read\");\n const written = tokens(\"input_cache_write\");\n if (input + read + written === 0) continue;\n return { provider: providerOf(model), model, prompt_tokens: input + read + written, cached_tokens: read, cache_write_tokens: written };\n }\n return null;\n}\n\n/** A JSON Schema property in the subset ElevenLabs accepts, with the same descriptions. */\nfunction literal(schema: unknown): Record<string, unknown> {\n if (!isRecord(schema)) return { type: \"string\" };\n const type = typeof schema.type === \"string\" ? schema.type : \"string\";\n const out: Record<string, unknown> = { type };\n if (typeof schema.description === \"string\") out.description = schema.description;\n if (Array.isArray(schema.enum)) out.enum = schema.enum;\n if (type === \"array\") out.items = literal(isRecord(schema.items) ? schema.items : {});\n if (type === \"object\" && isRecord(schema.properties)) {\n const properties: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(schema.properties)) properties[key] = literal(value);\n out.properties = properties;\n if (Array.isArray(schema.required)) out.required = schema.required;\n }\n return out;\n}\n\nfunction str(value: unknown): string | undefined {\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { c as Niadra, g as Handle } from './client-CWMxmJHs.cjs';
2
- import { P as Proof, A as AgentMemoryOption } from './shared-Cq8mz-7m.cjs';
3
- export { c as attestationProof } from './shared-Cq8mz-7m.cjs';
4
- import { H as HeadersLike, W as WebhookResponse, C as CallStore } from './webhook-jTx_SegV.cjs';
5
- export { a as CallRecord, m as memoryCallStore } from './webhook-jTx_SegV.cjs';
1
+ import { c as Niadra, g as Handle } from './client-rmWhZJOx.cjs';
2
+ import { P as Proof, A as AgentMemoryOption } from './shared-zaTBum17.cjs';
3
+ export { c as attestationProof } from './shared-zaTBum17.cjs';
4
+ import { H as HeadersLike, W as WebhookResponse, C as CallStore } from './webhook-CX7nvQig.cjs';
5
+ export { a as CallRecord, m as memoryCallStore } from './webhook-CX7nvQig.cjs';
6
6
 
7
7
  /**
8
8
  * Niadra for the ElevenLabs Agents Platform, on the server side: a phone call reaches ElevenLabs,
@@ -1,8 +1,8 @@
1
- import { c as Niadra, g as Handle } from './client-CWMxmJHs.js';
2
- import { P as Proof, A as AgentMemoryOption } from './shared-B4Ef2Wpg.js';
3
- export { c as attestationProof } from './shared-B4Ef2Wpg.js';
4
- import { H as HeadersLike, W as WebhookResponse, C as CallStore } from './webhook-z2TjUzjv.js';
5
- export { a as CallRecord, m as memoryCallStore } from './webhook-z2TjUzjv.js';
1
+ import { c as Niadra, g as Handle } from './client-rmWhZJOx.js';
2
+ import { P as Proof, A as AgentMemoryOption } from './shared-Cs7h5C4Y.js';
3
+ export { c as attestationProof } from './shared-Cs7h5C4Y.js';
4
+ import { H as HeadersLike, W as WebhookResponse, C as CallStore } from './webhook-2V5QgnKI.js';
5
+ export { a as CallRecord, m as memoryCallStore } from './webhook-2V5QgnKI.js';
6
6
 
7
7
  /**
8
8
  * Niadra for the ElevenLabs Agents Platform, on the server side: a phone call reaches ElevenLabs,