@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
package/dist/vapi.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tools.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/vapi.ts"],"names":[],"mappings":";;;AA+EO,IAAM,UAAA,GAAa;AAAA,EACxB,MAAA,EAAQ,yBAAA;AAAA,EACR,QAAA,EAAU,uBAAA;AAAA,EACV,IAAA,EAAM;AACR,CAAA;AAGO,IAAM,uBAAA,GAA0B;AAAA,EACrC,MAAA,EAAQ,qBAAA;AAAA,EACR,QAAA,EAAU;AACZ,CAAA;AAUO,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,cAC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C,OAAA,CAAQ,WAAA,EAAa,OAAA,CAAQ,OAAO,CAAA,CAAE,MAAA,CAAO,OAAO,CAAA,CAAE,IAAA,CAAK,MAAM,CAAA;AACjF,EAAA,IAAI,SAAS,MAAA,EAAQ;AACnB,IAAA,IAAI,QAAA,GAAW,CAAA;AACf,IAAA,OAAO,QAAA,GAAW,QAAA,CAAS,MAAA,IAAU,QAAA,CAAS,QAAA,CAAS,QAAQ,CAAC,CAAA,IAAM,QAAA,CAAS,QAAQ,CAAA,CAAgB,IAAA,KAAS,QAAA,EAAU,QAAA,EAAA;AAC1H,IAAA,QAAA,CAAS,MAAA,CAAO,UAAU,CAAA,EAAG,EAAE,MAAM,QAAA,EAAU,OAAA,EAAS,QAAQ,CAAA;AAAA,EAClE;AACA,EAAA,MAAM,SAAA,GAAY,KAAA,GAAQ,EAAE,GAAG,MAAA,EAAQ,KAAA,EAAO,EAAE,GAAG,KAAA,EAAO,QAAA,EAAS,EAAE,GAAI,MAAA;AACzE,EAAA,OAAO,EAAE,SAAA,EAAW,kBAAA,EAAoB,EAAE,gBAAe,EAAE;AAC7D","file":"vapi.cjs","sourcesContent":["import { NiadraAPIError, NiadraValidationError } from \"./errors.js\";\nimport type { NiadraError } from \"./errors.js\";\nimport type { AgentNote, AgentNoteKind, CreateAgentNoteRequest, RememberResult } from \"./types/agent-memory.js\";\nimport type { Handle } from \"./types/common.js\";\nimport type {\n HistoryFilters,\n OpenedItem,\n SearchRequest,\n SearchResponse,\n TimelineRequest,\n TimelineResponse,\n ToolDefinition,\n} from \"./types/context.js\";\nimport type { HistoryItemKind, Verification } from \"./types/vocabulary.js\";\n\n/** The outcome of a call that may fail without throwing. Exactly one of the two fields is set. */\nexport type Result<T> = { data: T; error: null } | { data: null; error: NiadraError };\n\n/** Everything a tool call is bound to besides its arguments. None of it is visible to the model. */\nexport interface ToolBinding {\n about?: Handle;\n verification?: Verification;\n conversation_id?: string;\n task_id?: string;\n /** Use the voice time budget for the calls these tools make. */\n voice?: boolean;\n}\n\n/** Which tools a kit offers besides the navigation kit. */\nexport interface ToolOptions {\n /** Adds `search_agent_memory`, the agent's own working notes. */\n agentMemory?: boolean;\n /**\n * Adds `remember` too. Only for a key with the `agent_memory:write` scope: a tool the model\n * cannot use is a wasted call. Needs `agentMemory`.\n */\n writeAgentMemory?: boolean;\n}\n\nexport interface Navigator {\n search(params: SearchRequest, voice: boolean): Promise<Result<SearchResponse>>;\n timeline(params: TimelineRequest, voice: boolean): Promise<Result<TimelineResponse>>;\n open(id: string, subject: Handle, binding: ToolBinding, voice: boolean): Promise<Result<OpenedItem>>;\n searchAgentMemory(\n query: string,\n options: { tags?: string[]; conversation_id?: string; task_id?: string },\n voice: boolean,\n ): Promise<Result<AgentNote[]>>;\n remember(note: CreateAgentNoteRequest): Promise<Result<RememberResult>>;\n}\n\n/**\n * The navigation kit as function-calling tools, bound to one customer.\n *\n * The definitions have no parameter for the customer: the handle lives in this object, outside\n * the model's reach. A prompt injection that says \"now look up customer X\" has no argument to\n * put X in. The model chooses what to ask, never whom it is about.\n */\nexport interface BoundTools {\n /** Tool definitions in the `{ type: \"function\", function: { name, description, parameters } }` shape. */\n readonly definitions: ToolDefinition[];\n /** Whether `name` is one of these tools, for dispatchers that route several toolsets. */\n has(name: string): boolean;\n /**\n * Runs one tool call and returns the text to send back to the model as the tool result.\n * `args` may be the JSON string most model APIs return, or an already parsed object.\n * Failures come back as a short JSON error the model can read and move past; with\n * `strict: true` they are thrown instead.\n */\n call(name: string, args: string | Record<string, unknown>): Promise<string>;\n}\n\n/** What `remember` answers when the note carries personal data: the model can rewrite it. */\nexport const PERSONAL_DATA_TOOL_ERROR = {\n error: \"personal_data\",\n detail:\n \"The note has personal data. Rewrite it so it helps with any customer, without names, phones, e-mails, documents or ids.\",\n} as const;\n\nexport const TOOL_NAMES = {\n search: \"search_customer_history\",\n timeline: \"get_customer_timeline\",\n open: \"open_history_item\",\n} as const;\n\n/** The two tools of the agent's own memory, offered with `tools({ agentMemory: true })`. */\nexport const AGENT_MEMORY_TOOL_NAMES = {\n search: \"search_agent_memory\",\n remember: \"remember\",\n} as const;\n\nconst ITEM_KINDS: HistoryItemKind[] = [\"episode\", \"fact\", \"open_item\", \"action\", \"object\", \"trait\"];\nconst NOTE_KINDS: AgentNoteKind[] = [\"procedure\", \"tool_note\", \"process_note\", \"pitfall\"];\n\n/**\n * The navigation kit, word for word the server's canonical definitions (`GET /v1/history/tools`)\n * and the Python SDK's: a model sees one toolset whatever language the agent is written in. The\n * server names the context's history line in the space's language; the SDKs ship its default.\n */\nexport const TOOL_DEFINITIONS: readonly ToolDefinition[] = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"search_customer_history\",\n \"description\": \"Search everything that already happened with this customer: past conversations, promises, agent actions, orders and invoices. Use it when the customer refers to something earlier or asks whether a problem happened before. Do not call it when the answer is already in the context block, including its 'Do histórico' line, which already counts recurrences. Returns short items with date, channel and outcome, plus a recurrence count. Open one with open_history_item.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"query\": {\n \"type\": \"string\",\n \"description\": \"What to look for, in the customer's words.\"\n },\n \"filters\": {\n \"type\": \"object\",\n \"properties\": {\n \"since\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"until\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"when\": {\n \"type\": \"string\",\n \"description\": \"The period in the customer's own words, as they said it: 'last week', 'semana passada', 'en marzo'.\"\n },\n \"channels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"categories\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"item_kinds\": {\n \"type\": \"array\",\n \"items\": {\n \"enum\": [\n \"episode\",\n \"fact\",\n \"open_item\",\n \"action\",\n \"object\",\n \"trait\"\n ]\n }\n },\n \"outcome\": {\n \"type\": \"string\"\n }\n },\n \"additionalProperties\": false\n },\n \"max_tokens\": {\n \"type\": \"integer\",\n \"minimum\": 50,\n \"maximum\": 4000\n }\n },\n \"required\": [\n \"query\"\n ],\n \"additionalProperties\": false\n }\n }\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_customer_timeline\",\n \"description\": \"List this customer's conversations and agent actions in order, newest first, one line each. Use it to leaf through the history when you do not know what to search for. Pass next_cursor to continue. Prefer search_customer_history for a specific question.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"cursor\": {\n \"type\": \"string\"\n },\n \"limit\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 100\n },\n \"filters\": {\n \"type\": \"object\",\n \"properties\": {\n \"since\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"until\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"when\": {\n \"type\": \"string\",\n \"description\": \"The period in the customer's own words, as they said it: 'last week', 'semana passada', 'en marzo'.\"\n },\n \"channels\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"categories\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"item_kinds\": {\n \"type\": \"array\",\n \"items\": {\n \"enum\": [\n \"episode\",\n \"fact\",\n \"open_item\",\n \"action\",\n \"object\",\n \"trait\"\n ]\n }\n },\n \"outcome\": {\n \"type\": \"string\"\n }\n },\n \"additionalProperties\": false\n }\n },\n \"additionalProperties\": false\n }\n }\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"open_history_item\",\n \"description\": \"Open one conversation or business object returned by search_customer_history or get_customer_timeline: what was asked, what was promised and by whom, the outcome and what memory came from it. Use it only after a search or timeline pointed to the item.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"description\": \"The item id, e.g. `episode:...`.\"\n }\n },\n \"required\": [\n \"id\"\n ],\n \"additionalProperties\": false\n }\n }\n }\n] as ToolDefinition[];\n\n/**\n * `search_agent_memory` and `remember`, word for word the server's canonical definitions. They\n * read and write the agent's working notes, never anything about a customer.\n */\nexport const AGENT_MEMORY_TOOL_DEFINITIONS: readonly ToolDefinition[] = [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"search_agent_memory\",\n \"description\": \"Search your own working notes: procedures, how the company's tools and processes behave, and known pitfalls. Use it before a task or a tool call you are unsure how to do. It holds nothing about customers; for the customer's history use search_customer_history.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"query\": {\n \"type\": \"string\",\n \"description\": \"What you need to know how to do.\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"maxItems\": 8,\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9][a-z0-9_.:-]{0,63}$\"\n },\n \"description\": \"Object types, operations or systems, e.g. `invoice`, `credit`, `erp`.\"\n }\n },\n \"required\": [\n \"query\"\n ],\n \"additionalProperties\": false\n }\n }\n },\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"remember\",\n \"description\": \"Save a working note for yourself and future runs: a procedure that worked, how a tool or process behaves, or a pitfall to avoid. Never write anything about a customer here: no names, phones, e-mails, documents, ids or words from the conversation. A note with personal data is refused. Write it so it helps with any customer.\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"kind\": {\n \"enum\": [\n \"procedure\",\n \"tool_note\",\n \"process_note\",\n \"pitfall\"\n ]\n },\n \"title\": {\n \"type\": \"string\",\n \"maxLength\": 120\n },\n \"body\": {\n \"type\": \"string\",\n \"maxLength\": 2000\n },\n \"tags\": {\n \"type\": \"array\",\n \"maxItems\": 8,\n \"items\": {\n \"type\": \"string\",\n \"pattern\": \"^[a-z0-9][a-z0-9_.:-]{0,63}$\"\n },\n \"description\": \"Object types, operations or systems, e.g. `invoice`, `credit`, `erp`.\"\n }\n },\n \"required\": [\n \"kind\",\n \"title\",\n \"body\"\n ],\n \"additionalProperties\": false\n }\n }\n }\n] as ToolDefinition[];\n\nfunction parseArgs(args: string | Record<string, unknown>): Record<string, unknown> {\n if (typeof args !== \"string\") return args;\n if (args.trim() === \"\") return {};\n let parsed: unknown;\n try {\n parsed = JSON.parse(args);\n } catch {\n throw new NiadraValidationError(\"tool arguments are not valid JSON\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new NiadraValidationError(\"tool arguments must be a JSON object\");\n }\n return parsed as Record<string, unknown>;\n}\n\nfunction str(args: Record<string, unknown>, name: string): string | undefined {\n const value = args[name];\n return typeof value === \"string\" && value.length > 0 ? value : undefined;\n}\n\nfunction strings(args: Record<string, unknown>, name: string): string[] | undefined {\n const value = args[name];\n if (!Array.isArray(value)) return undefined;\n const list = value.filter((entry): entry is string => typeof entry === \"string\");\n return list.length > 0 ? list : undefined;\n}\n\nfunction int(args: Record<string, unknown>, name: string): number | undefined {\n const value = args[name];\n return typeof value === \"number\" && Number.isInteger(value) ? value : undefined;\n}\n\n/** The filters of a call: the `filters` object of the canonical definitions. */\nfunction filtersFrom(args: Record<string, unknown>): HistoryFilters {\n const nested = args.filters;\n const source: Record<string, unknown> =\n typeof nested === \"object\" && nested !== null && !Array.isArray(nested) ? (nested as Record<string, unknown>) : {};\n const filters: HistoryFilters = {};\n const since = str(source, \"since\");\n const until = str(source, \"until\");\n const when = str(source, \"when\");\n const channels = strings(source, \"channels\");\n const categories = strings(source, \"categories\");\n const kinds = strings(source, \"item_kinds\")\n ?.filter((kind): kind is HistoryItemKind => (ITEM_KINDS as string[]).includes(kind));\n const outcome = str(source, \"outcome\");\n if (since) filters.since = since;\n if (until) filters.until = until;\n if (when) filters.when = when.slice(0, 100);\n if (channels) filters.channels = channels;\n if (categories) filters.categories = categories;\n if (kinds?.length) filters.item_kinds = [...new Set(kinds)];\n if (outcome) filters.outcome = outcome;\n return filters;\n}\n\nfunction tagsFrom(args: Record<string, unknown>): string[] | undefined {\n return strings(args, \"tags\")?.slice(0, 8);\n}\n\n/** Builds the bound toolset. `strict` decides whether failures are thrown or described to the model. */\nexport function bindTools(\n subject: Handle,\n binding: ToolBinding,\n navigator: Navigator,\n strict: boolean,\n options: ToolOptions = {},\n): BoundTools {\n const voice = binding.voice ?? false;\n const memory = options.agentMemory ? AGENT_MEMORY_TOOL_DEFINITIONS.slice(0, options.writeAgentMemory ? 2 : 1) : [];\n const definitions: ToolDefinition[] = [...TOOL_DEFINITIONS, ...memory];\n const names = new Set(definitions.map((definition) => definition.function.name));\n\n async function run(name: string, args: Record<string, unknown>): Promise<Result<unknown>> {\n switch (name) {\n case TOOL_NAMES.search: {\n const query = str(args, \"query\");\n if (!query) throw new NiadraValidationError(\"search_customer_history needs a query\");\n const request: SearchRequest = { subject, query, filters: filtersFrom(args) };\n applyBinding(request, binding);\n if (binding.task_id) request.task_id = binding.task_id;\n const maxTokens = int(args, \"max_tokens\");\n if (maxTokens !== undefined) request.max_tokens = Math.min(4000, Math.max(50, maxTokens));\n const result = await navigator.search(request, voice);\n return result.error ? result : { data: compactSearch(result.data), error: null };\n }\n case TOOL_NAMES.timeline: {\n const request: TimelineRequest = { subject, filters: filtersFrom(args) };\n applyBinding(request, binding);\n const cursor = str(args, \"cursor\");\n if (cursor) request.cursor = cursor;\n const limit = int(args, \"limit\");\n if (limit !== undefined) request.limit = Math.min(100, Math.max(1, limit));\n return navigator.timeline(request, voice);\n }\n case TOOL_NAMES.open: {\n const id = str(args, \"id\");\n if (!id) throw new NiadraValidationError(\"open_history_item needs an id\");\n return navigator.open(id, subject, binding, voice);\n }\n case AGENT_MEMORY_TOOL_NAMES.search: {\n const query = str(args, \"query\");\n if (!query) throw new NiadraValidationError(\"search_agent_memory needs a query\");\n const scope: { tags?: string[]; conversation_id?: string; task_id?: string } = {};\n const tags = tagsFrom(args);\n if (tags) scope.tags = tags;\n if (binding.conversation_id) scope.conversation_id = binding.conversation_id;\n else if (binding.task_id) scope.task_id = binding.task_id;\n const result = await navigator.searchAgentMemory(query, scope, voice);\n return result.error ? result : { data: { notes: result.data.map(compactNote) }, error: null };\n }\n case AGENT_MEMORY_TOOL_NAMES.remember: {\n const kind = str(args, \"kind\");\n const title = str(args, \"title\");\n const body = str(args, \"body\");\n if (!kind || !(NOTE_KINDS as string[]).includes(kind) || !title || !body) {\n throw new NiadraValidationError(\"remember needs a kind, a title and a body\");\n }\n const note: CreateAgentNoteRequest = { kind: kind as AgentNoteKind, title, body };\n const tags = tagsFrom(args);\n if (tags) note.tags = tags;\n if (binding.conversation_id) note.evidence = { conversation_id: binding.conversation_id };\n else if (binding.task_id) note.evidence = { task_id: binding.task_id };\n const result = await navigator.remember(note);\n return result.error ? result : { data: remembered(result.data), error: null };\n }\n default:\n throw new NiadraValidationError(`unknown tool: ${name}`);\n }\n }\n\n return {\n definitions: definitions.map((definition) => cloneDefinition(definition)),\n has: (name) => names.has(name),\n async call(name, rawArgs) {\n let result: Result<unknown>;\n try {\n if (!names.has(name)) throw new NiadraValidationError(`unknown tool: ${name}`);\n result = await run(name, parseArgs(rawArgs));\n } catch (error) {\n // Even a strict client hands this one to the model: rewriting the note is the answer.\n if (error instanceof NiadraAPIError && isPersonalData(error)) return JSON.stringify(PERSONAL_DATA_TOOL_ERROR);\n if (strict) throw error;\n return JSON.stringify({ error: \"invalid_call\", detail: (error as Error).message });\n }\n if (result.error) {\n if (isPersonalData(result.error)) return JSON.stringify(PERSONAL_DATA_TOOL_ERROR);\n if (strict) throw result.error;\n const memory = name === AGENT_MEMORY_TOOL_NAMES.search || name === AGENT_MEMORY_TOOL_NAMES.remember;\n const detail = memory ? \"agent memory is unavailable right now\" : \"customer history is unavailable right now\";\n return JSON.stringify({ error: \"unavailable\", detail });\n }\n return JSON.stringify(result.data);\n },\n };\n}\n\n/** What the model needs of a note: the id, the kind, the title, the body and the tags. */\nfunction compactNote(note: AgentNote): Partial<AgentNote> {\n const { note_id, kind, title, body, tags } = note;\n return tags === undefined ? { note_id, kind, title, body } : { note_id, kind, title, body, tags };\n}\n\n/** A saved note, or a proposal a person still has to approve, as the model reads it. */\nfunction remembered(result: RememberResult): Record<string, unknown> {\n if (result.note) return { saved: true, note_id: result.note.note_id, version: result.note.version };\n return { saved: false, proposal_id: result.proposal_id ?? null, status: \"waiting for review\" };\n}\n\n/** The server refused a note with personal data: an answer for the model, not a failure. */\nfunction isPersonalData(error: NiadraError): boolean {\n return error instanceof NiadraAPIError && error.code === \"personal_data_in_agent_memory\";\n}\n\nfunction applyBinding(request: SearchRequest | TimelineRequest, binding: ToolBinding): void {\n if (binding.about) request.about = binding.about;\n if (binding.verification) request.verification = binding.verification;\n if (binding.conversation_id) request.conversation_id = binding.conversation_id;\n}\n\n/** Token accounting is for the caller, not the model; everything else the model can use. */\nfunction compactSearch(response: SearchResponse): Omit<SearchResponse, \"tokens_used\"> {\n const { tokens_used: _, ...rest } = response;\n return rest;\n}\n\nfunction cloneDefinition(definition: ToolDefinition): ToolDefinition {\n return JSON.parse(JSON.stringify(definition)) as ToolDefinition;\n}\n","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 Vapi, on your server URL. One handler takes every server message Vapi sends\n * (`{ message: { type, call, ... } }`) and answers the ones that matter:\n *\n * - `assistant-request`: opens the conversation by the call id, records what the call proved,\n * reads the voice context and answers with your assistant, the context in its variables\n * (`{{niadra_context}}`, `{{niadra_turn}}`) and, for a transient assistant, as a system message\n * right after its own.\n * - `tool-calls`: runs the navigation kit (define the tools in Vapi with `vapiTools()`); the\n * customer comes from the call, never from the model's arguments.\n * - `transfer-destination-request` and `transfer-update`: records the transfer to a person.\n * - `end-of-call-report`: records every turn of the call and ends the conversation.\n *\n * Requests are checked against the server secret (`x-vapi-secret`, or `Authorization: Bearer`).\n * Only web APIs: runs on Node, 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, AGENT_MEMORY_TOOL_NAMES, TOOL_DEFINITIONS, TOOL_NAMES } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport { Bridge, errorName, isRecord, phoneHandle } from \"./shared.js\";\nimport type { AgentMemoryOption, Proof } from \"./shared.js\";\nimport { header, memoryCallStore, 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/** What the handlers read from a Vapi server message. */\nexport interface VapiCall {\n /** Vapi's call id, used as the `conversation_id`. */\n id: string;\n /** The customer's number, when Vapi reports one. */\n customerNumber?: string | undefined;\n /** The whole server message, for anything else you need. */\n message: Record<string, unknown>;\n}\n\n/** The context of the call, for building the assistant. */\nexport interface VapiContext {\n /** The pack, for the system prompt. Empty when there is nothing to inject. */\n context: string;\n /** The agent's own notes, when `agentMemory` is on; they go before the pack. */\n agentMemory: string;\n /** Deltas and live turns from other channels. */\n turn: string;\n}\n\ntype Assistant = Record<string, unknown>;\n\nexport interface VapiOptions {\n niadra: Niadra;\n /** The secret configured on the server URL (sent in `x-vapi-secret`) or its bearer token. Required. */\n secret: string;\n /**\n * What `assistant-request` answers with: a saved assistant's id (the context goes in its\n * variables), a transient assistant (the context also goes into `model.messages`), or a\n * function of the call and its context that returns either, or a full response object.\n */\n assistant?: string | Assistant | ((call: VapiCall, context: VapiContext) => Assistant | string | PromiseLike<Assistant | string>);\n /** Who is calling. Defaults to the customer's number as E.164. */\n subject?: (call: VapiCall) => Handle | null | undefined;\n /** What the call proved, such as the carrier's attestation. */\n verify?: (call: VapiCall) => Proof | null | undefined | PromiseLike<Proof | null | undefined>;\n /** The answer to `transfer-destination-request`, such as `{ destination: { type: \"number\", number } }`. */\n transfer?: (call: VapiCall) => Record<string, unknown> | PromiseLike<Record<string, unknown>>;\n /** Runs tool calls that are not Niadra's, so one server URL can serve all of them. */\n otherTool?: (name: string, args: unknown, call: VapiCall) => string | PromiseLike<string>;\n /** Keeps the caller and level between the messages of one call. Defaults to an in-memory store. */\n store?: CallStore;\n /** Time budget of the context read in `assistant-request`, in milliseconds. Defaults to the voice budget. */\n contextTimeout?: number;\n /** The agent's own notes in `{{niadra_agent_memory}}` (and before the pack of a transient assistant), and its memory tools. */\n agentMemory?: AgentMemoryOption;\n}\n\nconst OURS = new Set<string>([...Object.values(TOOL_NAMES), ...Object.values(AGENT_MEMORY_TOOL_NAMES)]);\nconst AGENT_ROLES = new Set([\"bot\", \"assistant\"]);\n\n/** The navigation kit as Vapi `function` tools, pointing at your server URL, with the SDK's descriptions. */\nexport function vapiTools(server: { url: string; secret?: string }, options: { agentMemory?: AgentMemoryOption } = {}): Record<string, unknown>[] {\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 type: \"function\",\n function: { name: definition.name, description: definition.description, parameters: definition.parameters },\n server: server.secret ? { url: server.url, secret: server.secret } : { url: server.url },\n }));\n}\n\n/** The handler for your Vapi server URL. */\nexport function vapi(options: VapiOptions): (body: unknown, headers: HeadersLike) => Promise<WebhookResponse> {\n const store = options.store ?? memoryCallStore();\n const logger = options.niadra.logger;\n const transferred = new Set<string>();\n\n const authorized = (headers: HeadersLike): boolean => {\n if (!options.secret) return false;\n const given = header(headers, \"x-vapi-secret\") ?? header(headers, \"authorization\")?.replace(/^Bearer\\s+/i, \"\");\n return given !== undefined && safeEqual(given, options.secret);\n };\n\n const subjectOf = (call: VapiCall): Handle | null => {\n try {\n return (options.subject ? options.subject(call) : phoneHandle(call.customerNumber)) ?? null;\n } catch {\n return null;\n }\n };\n\n const recall = async (call: VapiCall): Promise<CallRecord | null> => {\n try {\n const stored = await store.get(call.id);\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 const open = (call: VapiCall, record: CallRecord): Conversation =>\n options.niadra.conversation({ subject: record.subject, channel: \"voice\", conversation_id: call.id, verification: record.verification });\n\n async function assistantRequest(call: VapiCall): Promise<WebhookResponse> {\n const context: VapiContext = { context: \"\", agentMemory: \"\", turn: \"\" };\n const subject = subjectOf(call);\n if (subject) {\n const conversation = options.niadra.conversation({ subject, channel: \"voice\", conversation_id: call.id });\n const bridge = new Bridge(conversation, options.verify ? () => options.verify?.(call) : undefined, options.agentMemory);\n bridge.begin(); // waited for within timeouts.contextVoiceStart: the assistant is not answering yet\n const read = await bridge.read(options.contextTimeout ? { timeout: options.contextTimeout } : {});\n bridge.injected(read.context);\n context.context = read.context.text;\n context.agentMemory = read.memory;\n context.turn = read.suffix;\n try {\n await store.set(call.id, { subject, verification: conversation.verification, stamp: conversation.contextStamp });\n } catch (error) {\n logger.warn(`could not write the call store (${errorName(error)})`);\n }\n }\n let chosen: Assistant | string | undefined;\n try {\n chosen = typeof options.assistant === \"function\" ? await options.assistant(call, context) : options.assistant;\n } catch (error) {\n logger.warn(`could not build the assistant (${errorName(error)})`);\n return { status: 200, body: { error: \"The assistant is not available right now.\" } };\n }\n return { status: 200, body: assistantResponse(chosen, context, Boolean(options.agentMemory)) };\n }\n\n async function toolCalls(call: VapiCall): Promise<WebhookResponse> {\n const list = Array.isArray(call.message.toolCallList) ? (call.message.toolCallList as unknown[]) : [];\n const record = await recall(call);\n const specs = record ? new Bridge(open(call, record), undefined, options.agentMemory).tools() : [];\n const results: Record<string, unknown>[] = [];\n for (const item of list) {\n if (!isRecord(item) || !isRecord(item.function)) continue;\n const id = typeof item.id === \"string\" ? item.id : \"\";\n const name = typeof item.function.name === \"string\" ? item.function.name : \"\";\n const args = item.function.arguments as string | Record<string, unknown> | undefined;\n let result: string;\n if (OURS.has(name)) {\n const spec = specs.find((candidate) => candidate.name === name);\n result = spec\n ? await spec.execute(args ?? {})\n : JSON.stringify({ error: \"unavailable\", detail: \"customer history is unavailable right now\" });\n } else if (options.otherTool) {\n try {\n result = await options.otherTool(name, args, call);\n } catch (error) {\n logger.warn(`a tool outside Niadra failed (${errorName(error)})`);\n results.push({ name, toolCallId: id, error: \"tool failed\" });\n continue;\n }\n } else {\n results.push({ name, toolCallId: id, error: `unknown tool: ${name}` });\n continue;\n }\n results.push({ name, toolCallId: id, result });\n }\n return { status: 200, body: { results } };\n }\n\n async function transfer(call: VapiCall, answer: boolean): Promise<WebhookResponse> {\n if (!transferred.has(call.id)) {\n transferred.add(call.id);\n if (transferred.size > 10_000) transferred.clear();\n const record = await recall(call);\n if (record) await new Bridge(open(call, record)).handoff(\"human\", \"transfer\");\n }\n if (!answer) return { status: 200, body: {} };\n try {\n return { status: 200, body: options.transfer ? await options.transfer(call) : {} };\n } catch (error) {\n logger.warn(`could not choose the transfer destination (${errorName(error)})`);\n return { status: 200, body: { error: \"The transfer is not available right now.\" } };\n }\n }\n\n async function endOfCall(call: VapiCall): Promise<WebhookResponse> {\n const record = await recall(call);\n if (!record) return { status: 200, body: { recorded: 0 } };\n const bridge = new Bridge(open(call, record));\n const artifact = isRecord(call.message.artifact) ? call.message.artifact : {};\n const messages = Array.isArray(artifact.messages) ? (artifact.messages as unknown[]) : [];\n let recorded = 0;\n for (const [index, message] of messages.entries()) {\n if (!isRecord(message) || typeof message.message !== \"string\" || !message.message.trim()) continue;\n const role = typeof message.role === \"string\" ? message.role : \"\";\n const at = typeof message.time === \"number\" ? new Date(message.time) : undefined;\n const base = { idempotency_key: `vapi:${call.id}:${index}`, ...(at ? { occurred_at: at } : {}) };\n if (role === \"user\") {\n bridge.customer(message.message, base);\n recorded++;\n } else if (AGENT_ROLES.has(role)) {\n bridge.agent(message.message, record.stamp ? { ...base, context_stamp: record.stamp } : base);\n recorded++;\n }\n }\n await bridge.end();\n await options.niadra.flush();\n return { status: 200, body: { recorded } };\n }\n\n return async (body, headers) => {\n if (!authorized(headers)) return { status: 401, body: { error: \"unauthorized\" } };\n const call = callOf(body);\n if (!call) return { status: 400, body: { error: \"invalid_body\" } };\n switch (call.message.type) {\n case \"assistant-request\":\n return assistantRequest(call);\n case \"tool-calls\":\n return toolCalls(call);\n case \"transfer-destination-request\":\n return transfer(call, true);\n case \"transfer-update\":\n return transfer(call, false);\n case \"end-of-call-report\":\n return endOfCall(call);\n default:\n return { status: 200, body: {} };\n }\n };\n}\n\nfunction callOf(body: unknown): VapiCall | null {\n const message = isRecord(body) && isRecord(body.message) ? body.message : null;\n if (!message || typeof message.type !== \"string\") return null;\n const call = isRecord(message.call) ? message.call : {};\n const id = typeof call.id === \"string\" ? call.id : undefined;\n if (!id) return null;\n const customer = isRecord(call.customer) ? call.customer : isRecord(message.customer) ? message.customer : {};\n return { id, customerNumber: typeof customer.number === \"string\" ? customer.number : undefined, message };\n}\n\nfunction assistantResponse(chosen: Assistant | string | undefined, context: VapiContext, memory: boolean): Record<string, unknown> {\n const variableValues: Record<string, string> = { niadra_context: context.context, niadra_turn: context.turn };\n if (memory) variableValues.niadra_agent_memory = context.agentMemory;\n if (typeof chosen === \"string\") return { assistantId: chosen, assistantOverrides: { variableValues } };\n if (!chosen) return { assistantOverrides: { variableValues } };\n // A full response, such as `{ assistantId, assistantOverrides }` or `{ squadId }`, gets the variables merged in.\n if (!(\"model\" in chosen) && (\"assistantId\" in chosen || \"squadId\" in chosen || \"assistant\" in chosen)) {\n const overrides = isRecord(chosen.assistantOverrides) ? chosen.assistantOverrides : {};\n const values = isRecord(overrides.variableValues) ? overrides.variableValues : {};\n return { ...chosen, assistantOverrides: { ...overrides, variableValues: { ...values, ...variableValues } } };\n }\n const model = isRecord(chosen.model) ? chosen.model : null;\n const messages = model && Array.isArray(model.messages) ? [...(model.messages as unknown[])] : [];\n const prefix = [context.agentMemory, context.context].filter(Boolean).join(\"\\n\\n\");\n if (model && prefix) {\n let position = 0;\n while (position < messages.length && isRecord(messages[position]) && (messages[position] as Assistant).role === \"system\") position++;\n messages.splice(position, 0, { role: \"system\", content: prefix });\n }\n const assistant = model ? { ...chosen, model: { ...model, messages } } : chosen;\n return { assistant, assistantOverrides: { variableValues } };\n}\n"]}
1
+ {"version":3,"sources":["../src/tools.ts","../src/context.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/vapi.ts"],"names":[],"mappings":";;;AA+EO,IAAM,UAAA,GAAa;AAAA,EACxB,MAAA,EAAQ,yBAAA;AAAA,EACR,QAAA,EAAU,uBAAA;AAAA,EACV,IAAA,EAAM;AACR,CAAA;AAGO,IAAM,uBAAA,GAA0B;AAAA,EACrC,MAAA,EAAQ,qBAAA;AAAA,EACR,QAAA,EAAU;AACZ,CAAA;AAUO,IAAM,gBAAA,GAA8C;AAAA,E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O,EAAE,GAAG,KAAA,EAAO,QAAA,EAAS,EAAE,GAAI,MAAA;AACzE,EAAA,OAAO,EAAE,SAAA,EAAW,kBAAA,EAAoB,EAAE,gBAAe,EAAE;AAC7D","file":"vapi.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","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 Vapi, on your server URL. One handler takes every server message Vapi sends\n * (`{ message: { type, call, ... } }`) and answers the ones that matter:\n *\n * - `assistant-request`: opens the conversation by the call id, records what the call proved,\n * reads the voice context and answers with your assistant, the context in its variables\n * (`{{niadra_context}}`, `{{niadra_turn}}`) and, for a transient assistant, as a system message\n * right after its own.\n * - `tool-calls`: runs the navigation kit (define the tools in Vapi with `vapiTools()`); the\n * customer comes from the call, never from the model's arguments.\n * - `transfer-destination-request` and `transfer-update`: records the transfer to a person.\n * - `end-of-call-report`: records every turn of the call and ends the conversation.\n *\n * Requests are checked against the server secret (`x-vapi-secret`, or `Authorization: Bearer`).\n * Only web APIs: runs on Node, 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, AGENT_MEMORY_TOOL_NAMES, TOOL_DEFINITIONS, TOOL_NAMES } from \"../tools.js\";\nimport type { Handle } from \"../types/common.js\";\nimport { Bridge, errorName, isRecord, phoneHandle } from \"./shared.js\";\nimport type { AgentMemoryOption, Proof } from \"./shared.js\";\nimport { header, memoryCallStore, 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/** What the handlers read from a Vapi server message. */\nexport interface VapiCall {\n /** Vapi's call id, used as the `conversation_id`. */\n id: string;\n /** The customer's number, when Vapi reports one. */\n customerNumber?: string | undefined;\n /** The whole server message, for anything else you need. */\n message: Record<string, unknown>;\n}\n\n/** The context of the call, for building the assistant. */\nexport interface VapiContext {\n /** The pack, for the system prompt. Empty when there is nothing to inject. */\n context: string;\n /** The agent's own notes, when `agentMemory` is on; they go before the pack. */\n agentMemory: string;\n /** Deltas and live turns from other channels. */\n turn: string;\n}\n\ntype Assistant = Record<string, unknown>;\n\nexport interface VapiOptions {\n niadra: Niadra;\n /** The secret configured on the server URL (sent in `x-vapi-secret`) or its bearer token. Required. */\n secret: string;\n /**\n * What `assistant-request` answers with: a saved assistant's id (the context goes in its\n * variables), a transient assistant (the context also goes into `model.messages`), or a\n * function of the call and its context that returns either, or a full response object.\n */\n assistant?: string | Assistant | ((call: VapiCall, context: VapiContext) => Assistant | string | PromiseLike<Assistant | string>);\n /** Who is calling. Defaults to the customer's number as E.164. */\n subject?: (call: VapiCall) => Handle | null | undefined;\n /** What the call proved, such as the carrier's attestation. */\n verify?: (call: VapiCall) => Proof | null | undefined | PromiseLike<Proof | null | undefined>;\n /** The answer to `transfer-destination-request`, such as `{ destination: { type: \"number\", number } }`. */\n transfer?: (call: VapiCall) => Record<string, unknown> | PromiseLike<Record<string, unknown>>;\n /** Runs tool calls that are not Niadra's, so one server URL can serve all of them. */\n otherTool?: (name: string, args: unknown, call: VapiCall) => string | PromiseLike<string>;\n /** Keeps the caller and level between the messages of one call. Defaults to an in-memory store. */\n store?: CallStore;\n /** Time budget of the context read in `assistant-request`, in milliseconds. Defaults to the voice budget. */\n contextTimeout?: number;\n /** The agent's own notes in `{{niadra_agent_memory}}` (and before the pack of a transient assistant), and its memory tools. */\n agentMemory?: AgentMemoryOption;\n}\n\nconst OURS = new Set<string>([...Object.values(TOOL_NAMES), ...Object.values(AGENT_MEMORY_TOOL_NAMES)]);\nconst AGENT_ROLES = new Set([\"bot\", \"assistant\"]);\n\n/** The navigation kit as Vapi `function` tools, pointing at your server URL, with the SDK's descriptions. */\nexport function vapiTools(server: { url: string; secret?: string }, options: { agentMemory?: AgentMemoryOption } = {}): Record<string, unknown>[] {\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 type: \"function\",\n function: { name: definition.name, description: definition.description, parameters: definition.parameters },\n server: server.secret ? { url: server.url, secret: server.secret } : { url: server.url },\n }));\n}\n\n/** The handler for your Vapi server URL. */\nexport function vapi(options: VapiOptions): (body: unknown, headers: HeadersLike) => Promise<WebhookResponse> {\n const store = options.store ?? memoryCallStore();\n const logger = options.niadra.logger;\n const transferred = new Set<string>();\n\n const authorized = (headers: HeadersLike): boolean => {\n if (!options.secret) return false;\n const given = header(headers, \"x-vapi-secret\") ?? header(headers, \"authorization\")?.replace(/^Bearer\\s+/i, \"\");\n return given !== undefined && safeEqual(given, options.secret);\n };\n\n const subjectOf = (call: VapiCall): Handle | null => {\n try {\n return (options.subject ? options.subject(call) : phoneHandle(call.customerNumber)) ?? null;\n } catch {\n return null;\n }\n };\n\n const recall = async (call: VapiCall): Promise<CallRecord | null> => {\n try {\n const stored = await store.get(call.id);\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 const open = (call: VapiCall, record: CallRecord): Conversation =>\n options.niadra.conversation({ subject: record.subject, channel: \"voice\", conversation_id: call.id, verification: record.verification });\n\n async function assistantRequest(call: VapiCall): Promise<WebhookResponse> {\n const context: VapiContext = { context: \"\", agentMemory: \"\", turn: \"\" };\n const subject = subjectOf(call);\n if (subject) {\n const conversation = options.niadra.conversation({ subject, channel: \"voice\", conversation_id: call.id });\n const bridge = new Bridge(conversation, options.verify ? () => options.verify?.(call) : undefined, options.agentMemory);\n bridge.begin(); // waited for within timeouts.contextVoiceStart: the assistant is not answering yet\n const read = await bridge.read(options.contextTimeout ? { timeout: options.contextTimeout } : {});\n bridge.injected(read.context);\n context.context = read.context.text;\n context.agentMemory = read.memory;\n context.turn = read.suffix;\n try {\n await store.set(call.id, { subject, verification: conversation.verification, stamp: conversation.contextStamp });\n } catch (error) {\n logger.warn(`could not write the call store (${errorName(error)})`);\n }\n }\n let chosen: Assistant | string | undefined;\n try {\n chosen = typeof options.assistant === \"function\" ? await options.assistant(call, context) : options.assistant;\n } catch (error) {\n logger.warn(`could not build the assistant (${errorName(error)})`);\n return { status: 200, body: { error: \"The assistant is not available right now.\" } };\n }\n return { status: 200, body: assistantResponse(chosen, context, Boolean(options.agentMemory)) };\n }\n\n async function toolCalls(call: VapiCall): Promise<WebhookResponse> {\n const list = Array.isArray(call.message.toolCallList) ? (call.message.toolCallList as unknown[]) : [];\n const record = await recall(call);\n const specs = record ? new Bridge(open(call, record), undefined, options.agentMemory).tools() : [];\n const results: Record<string, unknown>[] = [];\n for (const item of list) {\n if (!isRecord(item) || !isRecord(item.function)) continue;\n const id = typeof item.id === \"string\" ? item.id : \"\";\n const name = typeof item.function.name === \"string\" ? item.function.name : \"\";\n const args = item.function.arguments as string | Record<string, unknown> | undefined;\n let result: string;\n if (OURS.has(name)) {\n const spec = specs.find((candidate) => candidate.name === name);\n result = spec\n ? await spec.execute(args ?? {})\n : JSON.stringify({ error: \"unavailable\", detail: \"customer history is unavailable right now\" });\n } else if (options.otherTool) {\n try {\n result = await options.otherTool(name, args, call);\n } catch (error) {\n logger.warn(`a tool outside Niadra failed (${errorName(error)})`);\n results.push({ name, toolCallId: id, error: \"tool failed\" });\n continue;\n }\n } else {\n results.push({ name, toolCallId: id, error: `unknown tool: ${name}` });\n continue;\n }\n results.push({ name, toolCallId: id, result });\n }\n return { status: 200, body: { results } };\n }\n\n async function transfer(call: VapiCall, answer: boolean): Promise<WebhookResponse> {\n if (!transferred.has(call.id)) {\n transferred.add(call.id);\n if (transferred.size > 10_000) transferred.clear();\n const record = await recall(call);\n if (record) await new Bridge(open(call, record)).handoff(\"human\", \"transfer\");\n }\n if (!answer) return { status: 200, body: {} };\n try {\n return { status: 200, body: options.transfer ? await options.transfer(call) : {} };\n } catch (error) {\n logger.warn(`could not choose the transfer destination (${errorName(error)})`);\n return { status: 200, body: { error: \"The transfer is not available right now.\" } };\n }\n }\n\n async function endOfCall(call: VapiCall): Promise<WebhookResponse> {\n const record = await recall(call);\n if (!record) return { status: 200, body: { recorded: 0 } };\n const bridge = new Bridge(open(call, record));\n const artifact = isRecord(call.message.artifact) ? call.message.artifact : {};\n const messages = Array.isArray(artifact.messages) ? (artifact.messages as unknown[]) : [];\n let recorded = 0;\n for (const [index, message] of messages.entries()) {\n if (!isRecord(message) || typeof message.message !== \"string\" || !message.message.trim()) continue;\n const role = typeof message.role === \"string\" ? message.role : \"\";\n const at = typeof message.time === \"number\" ? new Date(message.time) : undefined;\n const base = { idempotency_key: `vapi:${call.id}:${index}`, ...(at ? { occurred_at: at } : {}) };\n if (role === \"user\") {\n bridge.customer(message.message, base);\n recorded++;\n } else if (AGENT_ROLES.has(role)) {\n bridge.agent(message.message, record.stamp ? { ...base, context_stamp: record.stamp } : base);\n recorded++;\n }\n }\n await bridge.end();\n await options.niadra.flush();\n return { status: 200, body: { recorded } };\n }\n\n return async (body, headers) => {\n if (!authorized(headers)) return { status: 401, body: { error: \"unauthorized\" } };\n const call = callOf(body);\n if (!call) return { status: 400, body: { error: \"invalid_body\" } };\n switch (call.message.type) {\n case \"assistant-request\":\n return assistantRequest(call);\n case \"tool-calls\":\n return toolCalls(call);\n case \"transfer-destination-request\":\n return transfer(call, true);\n case \"transfer-update\":\n return transfer(call, false);\n case \"end-of-call-report\":\n return endOfCall(call);\n default:\n return { status: 200, body: {} };\n }\n };\n}\n\nfunction callOf(body: unknown): VapiCall | null {\n const message = isRecord(body) && isRecord(body.message) ? body.message : null;\n if (!message || typeof message.type !== \"string\") return null;\n const call = isRecord(message.call) ? message.call : {};\n const id = typeof call.id === \"string\" ? call.id : undefined;\n if (!id) return null;\n const customer = isRecord(call.customer) ? call.customer : isRecord(message.customer) ? message.customer : {};\n return { id, customerNumber: typeof customer.number === \"string\" ? customer.number : undefined, message };\n}\n\nfunction assistantResponse(chosen: Assistant | string | undefined, context: VapiContext, memory: boolean): Record<string, unknown> {\n const variableValues: Record<string, string> = { niadra_context: context.context, niadra_turn: context.turn };\n if (memory) variableValues.niadra_agent_memory = context.agentMemory;\n if (typeof chosen === \"string\") return { assistantId: chosen, assistantOverrides: { variableValues } };\n if (!chosen) return { assistantOverrides: { variableValues } };\n // A full response, such as `{ assistantId, assistantOverrides }` or `{ squadId }`, gets the variables merged in.\n if (!(\"model\" in chosen) && (\"assistantId\" in chosen || \"squadId\" in chosen || \"assistant\" in chosen)) {\n const overrides = isRecord(chosen.assistantOverrides) ? chosen.assistantOverrides : {};\n const values = isRecord(overrides.variableValues) ? overrides.variableValues : {};\n return { ...chosen, assistantOverrides: { ...overrides, variableValues: { ...values, ...variableValues } } };\n }\n const model = isRecord(chosen.model) ? chosen.model : null;\n const messages = model && Array.isArray(model.messages) ? [...(model.messages as unknown[])] : [];\n const prefix = [context.agentMemory, context.context].filter(Boolean).join(\"\\n\\n\");\n if (model && prefix) {\n let position = 0;\n while (position < messages.length && isRecord(messages[position]) && (messages[position] as Assistant).role === \"system\") position++;\n messages.splice(position, 0, { role: \"system\", content: prefix });\n }\n const assistant = model ? { ...chosen, model: { ...model, messages } } : chosen;\n return { assistant, assistantOverrides: { variableValues } };\n}\n"]}
package/dist/vapi.d.cts CHANGED
@@ -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 { C as CallStore, H as HeadersLike, W as WebhookResponse } 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 { C as CallStore, H as HeadersLike, W as WebhookResponse } from './webhook-CX7nvQig.cjs';
5
+ export { a as CallRecord, m as memoryCallStore } from './webhook-CX7nvQig.cjs';
6
6
 
7
7
  /**
8
8
  * Niadra for Vapi, on your server URL. One handler takes every server message Vapi sends
package/dist/vapi.d.ts CHANGED
@@ -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 { C as CallStore, H as HeadersLike, W as WebhookResponse } 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 { C as CallStore, H as HeadersLike, W as WebhookResponse } from './webhook-2V5QgnKI.js';
5
+ export { a as CallRecord, m as memoryCallStore } from './webhook-2V5QgnKI.js';
6
6
 
7
7
  /**
8
8
  * Niadra for Vapi, on your server URL. One handler takes every server message Vapi sends
package/dist/vapi.js CHANGED
@@ -13,7 +13,7 @@ var TOOL_DEFINITIONS = [
13
13
  "type": "function",
14
14
  "function": {
15
15
  "name": "search_customer_history",
16
- "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\xF3rico' line, which already counts recurrences. Returns short items with date, channel and outcome, plus a recurrence count. Open one with open_history_item.",
16
+ "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\xF3rico' 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.",
17
17
  "parameters": {
18
18
  "type": "object",
19
19
  "properties": {
@@ -57,7 +57,8 @@ var TOOL_DEFINITIONS = [
57
57
  "open_item",
58
58
  "action",
59
59
  "object",
60
- "trait"
60
+ "trait",
61
+ "system_event"
61
62
  ]
62
63
  }
63
64
  },
@@ -84,7 +85,7 @@ var TOOL_DEFINITIONS = [
84
85
  "type": "function",
85
86
  "function": {
86
87
  "name": "get_customer_timeline",
87
- "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.",
88
+ "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.",
88
89
  "parameters": {
89
90
  "type": "object",
90
91
  "properties": {
@@ -132,7 +133,8 @@ var TOOL_DEFINITIONS = [
132
133
  "open_item",
133
134
  "action",
134
135
  "object",
135
- "trait"
136
+ "trait",
137
+ "system_event"
136
138
  ]
137
139
  }
138
140
  },
@@ -151,7 +153,7 @@ var TOOL_DEFINITIONS = [
151
153
  "type": "function",
152
154
  "function": {
153
155
  "name": "open_history_item",
154
- "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.",
156
+ "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.",
155
157
  "parameters": {
156
158
  "type": "object",
157
159
  "properties": {