@niadra/sdk 0.9.0 → 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 (87) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +40 -1
  3. package/dist/ai-sdk.d.cts +3 -3
  4. package/dist/ai-sdk.d.ts +3 -3
  5. package/dist/anthropic.d.cts +4 -4
  6. package/dist/anthropic.d.ts +4 -4
  7. package/dist/bedrock.d.cts +4 -4
  8. package/dist/bedrock.d.ts +4 -4
  9. package/dist/cli.js +368 -104
  10. package/dist/cli.js.map +1 -1
  11. package/dist/{client-B_ip8T2o.d.cts → client-rmWhZJOx.d.cts} +212 -21
  12. package/dist/{client-B_ip8T2o.d.ts → client-rmWhZJOx.d.ts} +212 -21
  13. package/dist/cloudflare-agents.d.cts +3 -3
  14. package/dist/cloudflare-agents.d.ts +3 -3
  15. package/dist/elevenlabs.cjs +7 -5
  16. package/dist/elevenlabs.cjs.map +1 -1
  17. package/dist/elevenlabs.d.cts +5 -5
  18. package/dist/elevenlabs.d.ts +5 -5
  19. package/dist/elevenlabs.js +7 -5
  20. package/dist/elevenlabs.js.map +1 -1
  21. package/dist/genkit.d.cts +3 -3
  22. package/dist/genkit.d.ts +3 -3
  23. package/dist/google-adk.cjs +7 -5
  24. package/dist/google-adk.cjs.map +1 -1
  25. package/dist/google-adk.d.cts +3 -3
  26. package/dist/google-adk.d.ts +3 -3
  27. package/dist/google-adk.js +7 -5
  28. package/dist/google-adk.js.map +1 -1
  29. package/dist/google-genai.d.cts +4 -4
  30. package/dist/google-genai.d.ts +4 -4
  31. package/dist/index.cjs +378 -106
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +13 -5
  34. package/dist/index.d.ts +13 -5
  35. package/dist/index.js +378 -106
  36. package/dist/index.js.map +1 -1
  37. package/dist/{intercept-CxmBLfoj.d.cts → intercept-C0XODsy9.d.cts} +1 -1
  38. package/dist/{intercept-CBaPK_-k.d.ts → intercept-veMDudKV.d.ts} +1 -1
  39. package/dist/langchain.cjs.map +1 -1
  40. package/dist/langchain.d.cts +3 -3
  41. package/dist/langchain.d.ts +3 -3
  42. package/dist/langchain.js.map +1 -1
  43. package/dist/livekit.cjs +10 -2
  44. package/dist/livekit.cjs.map +1 -1
  45. package/dist/livekit.d.cts +3 -3
  46. package/dist/livekit.d.ts +3 -3
  47. package/dist/livekit.js +10 -2
  48. package/dist/livekit.js.map +1 -1
  49. package/dist/llamaindex.d.cts +3 -3
  50. package/dist/llamaindex.d.ts +3 -3
  51. package/dist/mastra.d.cts +3 -3
  52. package/dist/mastra.d.ts +3 -3
  53. package/dist/openai-agents.d.cts +3 -3
  54. package/dist/openai-agents.d.ts +3 -3
  55. package/dist/retell.cjs +7 -5
  56. package/dist/retell.cjs.map +1 -1
  57. package/dist/retell.d.cts +5 -5
  58. package/dist/retell.d.ts +5 -5
  59. package/dist/retell.js +7 -5
  60. package/dist/retell.js.map +1 -1
  61. package/dist/{shared-BLkAbvuf.d.ts → shared-Cs7h5C4Y.d.ts} +1 -1
  62. package/dist/{shared-DEkF2Y_z.d.cts → shared-zaTBum17.d.cts} +1 -1
  63. package/dist/strands.d.cts +3 -3
  64. package/dist/strands.d.ts +3 -3
  65. package/dist/twilio.cjs +10 -2
  66. package/dist/twilio.cjs.map +1 -1
  67. package/dist/twilio.d.cts +4 -4
  68. package/dist/twilio.d.ts +4 -4
  69. package/dist/twilio.js +10 -2
  70. package/dist/twilio.js.map +1 -1
  71. package/dist/vapi.cjs +7 -5
  72. package/dist/vapi.cjs.map +1 -1
  73. package/dist/vapi.d.cts +5 -5
  74. package/dist/vapi.d.ts +5 -5
  75. package/dist/vapi.js +7 -5
  76. package/dist/vapi.js.map +1 -1
  77. package/dist/voltagent.d.cts +3 -3
  78. package/dist/voltagent.d.ts +3 -3
  79. package/dist/{webhook-BaraTaA9.d.ts → webhook-2V5QgnKI.d.ts} +1 -1
  80. package/dist/{webhook-CuR0Wckd.d.cts → webhook-CX7nvQig.d.cts} +1 -1
  81. package/dist/whatsapp.cjs +10 -2
  82. package/dist/whatsapp.cjs.map +1 -1
  83. package/dist/whatsapp.d.cts +2 -2
  84. package/dist/whatsapp.d.ts +2 -2
  85. package/dist/whatsapp.js +10 -2
  86. package/dist/whatsapp.js.map +1 -1
  87. package/package.json +3 -2
@@ -1,7 +1,7 @@
1
1
  import { Plugin, LocalAgent, InvokableTool, JSONValue } from '@strands-agents/sdk';
2
- import { f as ModelUsage } from './client-B_ip8T2o.cjs';
3
- import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-DEkF2Y_z.cjs';
4
- export { P as Proof, c as attestationProof } from './shared-DEkF2Y_z.cjs';
2
+ import { f as ModelUsage } from './client-rmWhZJOx.cjs';
3
+ import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-zaTBum17.cjs';
4
+ export { P as Proof, c as attestationProof } from './shared-zaTBum17.cjs';
5
5
 
6
6
  /**
7
7
  * Niadra for Strands Agents for TypeScript (`@strands-agents/sdk` 1.x, AWS): a plugin with the
package/dist/strands.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Plugin, LocalAgent, InvokableTool, JSONValue } from '@strands-agents/sdk';
2
- import { f as ModelUsage } from './client-B_ip8T2o.js';
3
- import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-BLkAbvuf.js';
4
- export { P as Proof, c as attestationProof } from './shared-BLkAbvuf.js';
2
+ import { f as ModelUsage } from './client-rmWhZJOx.js';
3
+ import { b as Session, a as ProofSource, A as AgentMemoryOption } from './shared-Cs7h5C4Y.js';
4
+ export { P as Proof, c as attestationProof } from './shared-Cs7h5C4Y.js';
5
5
 
6
6
  /**
7
7
  * Niadra for Strands Agents for TypeScript (`@strands-agents/sdk` 1.x, AWS): a plugin with the
package/dist/twilio.cjs CHANGED
@@ -21,9 +21,17 @@ var handles = {
21
21
  appUserId: (value, options) => build("app_user_id", value, void 0, options),
22
22
  /** The id of a person or organization in a system of record; `system` names that system, such as `crm`. */
23
23
  systemId: (value, system, options) => build("system_id", value, system, options),
24
- /** An HMAC of a national document number; `country` is its ISO 3166-1 alpha-2 code. */
24
+ /**
25
+ * A person's national document, such as a CPF: `govIdHmac("529.982.247-25", "BR")`. Send the number
26
+ * itself, never a hash of it: the server checks its check digits, then keeps only a keyed hash with your
27
+ * space's secret and an encrypted copy, and shows it masked. `country` is its ISO 3166-1 alpha-2 code.
28
+ */
25
29
  govIdHmac: (value, country, options) => build("gov_id_hmac", value, country, options),
26
- /** An HMAC of a company registry number. Identifies an organization. */
30
+ /**
31
+ * A company's registry number, such as a CNPJ: `orgRegistryHmac("11.222.333/0001-81", "BR")`. As with
32
+ * `govIdHmac`, send the number itself; the server checks it and keeps only a keyed hash. Identifies an
33
+ * organization.
34
+ */
27
35
  orgRegistryHmac: (value, country) => build("org_registry_hmac", value, country, { subjectKind: "account" }),
28
36
  /** An e-mail domain, such as `acme.com`. Identifies an organization. */
29
37
  emailDomain: (domain) => build("email_domain", domain, void 0, { subjectKind: "account" }),
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/handles.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/twilio.ts"],"names":["subject"],"mappings":";;;AASA,SAAS,KAAA,CAAM,IAAA,EAAsB,KAAA,EAAe,KAAA,EAAgB,OAAA,EAAiC;AACnG,EAAA,MAAM,MAAA,GAAiB,EAAE,IAAA,EAAM,KAAA,EAAM;AACrC,EAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAA,CAAO,KAAA,GAAQ,KAAA;AACxC,EAAA,IAAI,OAAA,EAAS,WAAA,KAAgB,MAAA,EAAW,MAAA,CAAO,eAAe,OAAA,CAAQ,WAAA;AACtE,EAAA,OAAO,MAAA;AACT;AASO,IAAM,OAAA,GAAU;AAAA;AAAA,EAErB,KAAA,EAAO,CAAC,IAAA,EAAc,OAAA,KAAoC,MAAM,YAAA,EAAc,IAAA,EAAM,QAAW,OAAO,CAAA;AAAA,EACtG,KAAA,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OAAO,IAAA,CAAK,CAAA,gCAAA,EAAmC,SAAA,CAAU,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA;AAAA,EACjF;AACF;AAGO,SAAS,mBAAA,CAAoB,cAA4B,OAAA,EAAuC;AACrG,EAAA,IAAI,CAAC,OAAA,CAAQ,IAAA,EAAM,OAAO,IAAA;AAC1B,EAAA,IAAI;AACF,IAAA,OAAO,YAAA,CAAa,QAAA,CAAS,OAAA,CAAQ,IAAA,EAAM;AAAA,MACzC,GAAI,QAAQ,SAAA,GAAY,EAAE,iBAAiB,OAAA,CAAQ,SAAA,KAAc,EAAC;AAAA,MAClE,GAAI,QAAQ,UAAA,KAAe,KAAA,CAAA,GAAY,EAAE,cAAA,EAAgB,OAAA,CAAQ,UAAA,EAAW,GAAI;AAAC,KAClF,CAAA;AAAA,EACH,SAAS,KAAA,EAAO;AACd,IAAA,YAAA,CAAa,OAAO,IAAA,CAAK,CAAA,qCAAA,EAAwC,SAAA,CAAU,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA;AACpF,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"twilio.cjs","sourcesContent":["import { NiadraValidationError } from \"./errors.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type { SubjectKind } from \"./types/vocabulary.js\";\n\ninterface HandleOptions {\n /** Overrides the subject kind the server would infer from the handle type. */\n subjectKind?: SubjectKind;\n}\n\nfunction build(type: Handle[\"type\"], value: string, scope?: string, options?: HandleOptions): Handle {\n const handle: Handle = { type, value };\n if (scope !== undefined) handle.scope = scope;\n if (options?.subjectKind !== undefined) handle.subject_kind = options.subjectKind;\n return handle;\n}\n\n/**\n * Builders for the handle types the API accepts. They only assemble the object; the value is\n * normalized and validated on the server, which is the single source of truth for matching.\n *\n * @example\n * niadra.context({ subject: handles.phone(\"+5511987654321\"), conversation_id: \"wa-8812\" })\n */\nexport const handles = {\n /** A phone number in E.164 form, such as `+5511987654321`. */\n phone: (e164: string, options?: HandleOptions): Handle => build(\"phone_e164\", e164, undefined, options),\n email: (address: string, options?: HandleOptions): Handle => build(\"email\", address, undefined, options),\n /** The WhatsApp id (`wa_id`) the Cloud API reports for a contact. */\n waId: (value: string, options?: HandleOptions): Handle => build(\"wa_id\", value, undefined, options),\n waJid: (value: string, options?: HandleOptions): Handle => build(\"wa_jid\", value, undefined, options),\n waLid: (value: string, options?: HandleOptions): Handle => build(\"wa_lid\", value, undefined, options),\n /** A business-scoped WhatsApp user id; `businessAccount` is the WhatsApp Business account it belongs to. */\n waBsuid: (value: string, businessAccount: string, options?: HandleOptions): Handle =>\n build(\"wa_bsuid\", value, businessAccount, options),\n /** The user id in your own app or site. */\n appUserId: (value: string, options?: HandleOptions): Handle => build(\"app_user_id\", value, undefined, options),\n /** The id of a person or organization in a system of record; `system` names that system, such as `crm`. */\n systemId: (value: string, system: string, options?: HandleOptions): Handle =>\n build(\"system_id\", value, system, options),\n /** An HMAC of a national document number; `country` is its ISO 3166-1 alpha-2 code. */\n govIdHmac: (value: string, country: string, options?: HandleOptions): Handle =>\n build(\"gov_id_hmac\", value, country, options),\n /** An HMAC of a company registry number. Identifies an organization. */\n orgRegistryHmac: (value: string, country: string): Handle =>\n build(\"org_registry_hmac\", value, country, { subjectKind: \"account\" }),\n /** An e-mail domain, such as `acme.com`. Identifies an organization. */\n emailDomain: (domain: string): Handle => build(\"email_domain\", domain, undefined, { subjectKind: \"account\" }),\n /** An anonymous visitor or device id, before the person is known. */\n anonId: (value: string, options?: HandleOptions): Handle => build(\"anon_id\", value, undefined, options),\n} as const;\n\n/**\n * Accepts an `ObjectRef` or the `type:namespace:id` shorthand. The id may itself contain\n * colons (`invoice:erp:2026:0823`); only the first two separate the parts.\n */\nexport function toObjectRef(object: ObjectRef | string): ObjectRef {\n if (typeof object !== \"string\") return object;\n const first = object.indexOf(\":\");\n const second = first < 0 ? -1 : object.indexOf(\":\", first + 1);\n if (first <= 0 || second <= first + 1 || second === object.length - 1) {\n throw new NiadraValidationError(\"object must look like `type:namespace:id`\");\n }\n return { type: object.slice(0, first), namespace: object.slice(first + 1, second), id: object.slice(second + 1) };\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 Twilio webhooks: Programmable Voice, Messaging (SMS and WhatsApp) and Conversations.\n * Translates only: it checks `X-Twilio-Signature`, finds the customer's handle, the call or thread\n * id and what the carrier attested, and records the inbound turn. It never answers with TwiML.\n *\n * @example\n * const { status, request } = await readTwilio(publicUrl, await req.text(), req.headers, { authToken });\n * const convo = niadra.conversation({ subject: request.subject, channel: request.channel, conversation_id: request.conversationId });\n * await verifyTwilio(convo, request); // StirVerstat on voice; then the first read starts while it rings\n * recordTwilioInbound(convo, request);\n * const ctx = await convo.ready(); // the call's first read, within timeouts.contextVoiceStart\n */\n\nimport type { Conversation } from \"../conversation.js\";\nimport { handles } from \"../handles.js\";\nimport type { Handle } from \"../types/common.js\";\nimport { attestationProof, errorName, phoneHandle } from \"./shared.js\";\nimport type { Proof } from \"./shared.js\";\nimport { base64, bodyText, header, hmac, safeEqual } from \"./webhook.js\";\nimport type { HeadersLike } from \"./webhook.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { Proof } from \"./shared.js\";\nexport type { HeadersLike } from \"./webhook.js\";\n\n/** One Twilio webhook request, read. */\nexport interface TwilioRequest {\n /** `voice`, `whatsapp`, `sms` or `conversations`, usable as the Niadra channel. */\n channel: \"voice\" | \"whatsapp\" | \"sms\" | \"conversations\";\n /** The customer: `WaId` on WhatsApp, else the phone number on the customer's side of the call or message. */\n subject: Handle;\n /** `CallSid` on voice, `ConversationSid` on Conversations; messages leave the thread id to you. */\n conversationId?: string | undefined;\n /** `MessageSid`: the idempotency key of the turn. */\n messageId?: string | undefined;\n /** The message body, or the speech recognized by `<Gather input=\"speech\">`. */\n text?: string | undefined;\n /** Speech confidence from `<Gather>`, between 0 and 1. */\n confidence?: number | undefined;\n /** What the carrier attested (`StirVerstat`), as a proof for `verify()`; `null` when nothing was proven. */\n proof: Proof | null;\n /** Every parameter Twilio sent. */\n params: Record<string, string>;\n}\n\n/**\n * Checks `X-Twilio-Signature`: base64 HMAC-SHA1, with the auth token, of the full URL Twilio called\n * followed by every POST parameter, sorted by name, as name and value.\n */\nexport async function validTwilioSignature(\n url: string,\n params: URLSearchParams | Record<string, string>,\n signature: string | undefined,\n authToken: string,\n): Promise<boolean> {\n if (!signature || !authToken) return false;\n const pairs = params instanceof URLSearchParams ? [...params.entries()] : Object.entries(params);\n pairs.sort(([a, x], [b, y]) => (a === b ? (x < y ? -1 : x > y ? 1 : 0) : a < b ? -1 : 1));\n const data = url + pairs.map(([key, value]) => key + value).join(\"\");\n return safeEqual(signature, base64(await hmac(\"SHA-1\", authToken, data)));\n}\n\n/**\n * Checks the signature of a form-encoded Twilio webhook and reads it. `url` is the exact public URL\n * Twilio called, query string included (behind a proxy, not the one your server sees).\n */\nexport async function readTwilio(\n url: string,\n rawBody: string | Uint8Array | ArrayBuffer,\n headers: HeadersLike,\n options: { authToken: string },\n): Promise<{ status: number; request: TwilioRequest | null }> {\n const params = new URLSearchParams(bodyText(rawBody));\n if (!(await validTwilioSignature(url, params, header(headers, \"x-twilio-signature\"), options.authToken))) {\n return { status: 403, request: null };\n }\n return { status: 200, request: parseTwilio(params) };\n}\n\n/** Reads the parameters of an already verified request; `null` when no customer can be found. */\nexport function parseTwilio(params: URLSearchParams | Record<string, string>): TwilioRequest | null {\n const all: Record<string, string> = params instanceof URLSearchParams ? Object.fromEntries(params.entries()) : { ...params };\n const get = (name: string): string | undefined => {\n const value = all[name];\n return value === \"\" ? undefined : value;\n };\n const outbound = get(\"Direction\")?.startsWith(\"outbound\") ?? false;\n const other = outbound ? get(\"To\") : get(\"From\");\n const text = get(\"Body\") ?? get(\"SpeechResult\");\n const confidence = Number(get(\"Confidence\"));\n const base = {\n messageId: get(\"MessageSid\"),\n text,\n confidence: Number.isFinite(confidence) && confidence >= 0 && confidence <= 1 && get(\"SpeechResult\") ? confidence : undefined,\n proof: attestationProof(get(\"StirVerstat\")),\n params: all,\n };\n\n if (get(\"ConversationSid\")) {\n const author = get(\"Author\");\n const subject = author ? (phoneHandle(author.replace(/^whatsapp:/, \"\")) ?? handles.appUserId(author)) : null;\n return subject ? { ...base, channel: \"conversations\", subject, conversationId: get(\"ConversationSid\") } : null;\n }\n if (other?.startsWith(\"whatsapp:\")) {\n const waId = get(\"WaId\");\n const subject = waId ? handles.waId(waId) : phoneHandle(other.slice(\"whatsapp:\".length));\n return subject ? { ...base, channel: \"whatsapp\", subject } : null;\n }\n const subject = phoneHandle(other);\n if (!subject) return null;\n if (get(\"CallSid\") && !get(\"MessageSid\")) return { ...base, channel: \"voice\", subject, conversationId: get(\"CallSid\") };\n return { ...base, channel: \"sms\", subject };\n}\n\n/**\n * Records what the carrier attested for the call, before the first context read, and on the\n * incoming call webhook (`CallStatus` `ringing`) starts the conversation's first read at the level\n * it proved, so it runs while the phone rings; `conversation.ready()` waits for it. Never rejects.\n */\nexport async function verifyTwilio(conversation: Conversation, request: TwilioRequest): Promise<void> {\n if (request.proof) {\n try {\n await conversation.verify(request.proof);\n } catch (error) {\n conversation.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n if (request.channel !== \"voice\" || request.params.CallStatus !== \"ringing\") return;\n try {\n conversation.begin();\n } catch (error) {\n conversation.logger.warn(`could not start the first read (${errorName(error)})`);\n }\n}\n\n/** Records the inbound text or speech as the customer's turn, keyed by `MessageSid` when there is one. */\nexport function recordTwilioInbound(conversation: Conversation, request: TwilioRequest): string | null {\n if (!request.text) return null;\n try {\n return conversation.customer(request.text, {\n ...(request.messageId ? { idempotency_key: request.messageId } : {}),\n ...(request.confidence !== undefined ? { stt_confidence: request.confidence } : {}),\n });\n } catch (error) {\n conversation.logger.warn(`could not record the Twilio message (${errorName(error)})`);\n return null;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/handles.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/twilio.ts"],"names":["subject"],"mappings":";;;AASA,SAAS,KAAA,CAAM,IAAA,EAAsB,KAAA,EAAe,KAAA,EAAgB,OAAA,EAAiC;AACnG,EAAA,MAAM,MAAA,GAAiB,EAAE,IAAA,EAAM,KAAA,EAAM;AACrC,EAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAA,CAAO,KAAA,GAAQ,KAAA;AACxC,EAAA,IAAI,OAAA,EAAS,WAAA,KAAgB,MAAA,EAAW,MAAA,CAAO,eAAe,OAAA,CAAQ,WAAA;AACtE,EAAA,OAAO,MAAA;AACT;AASO,IAAM,OAAA,GAAU;AAAA;AAAA,EAErB,KAAA,EAAO,CAAC,IAAA,EAAc,OAAA,KAAoC,MAAM,YAAA,EAAc,IAAA,EAAM,QAAW,OAAO,CAAA;AAAA,EACtG,KAAA,EAAO,CAAC,OAAA,EAAiB,OAAA,KAAoC,MAAM,OAAA,EAAS,OAAA,EAAS,QAAW,OAAO,CAAA;AAAA;AAAA,EAEvG,IAAA,EAAM,CAAC,KAAA,EAAe,OAAA,KAAoC,MAAM,OAAA,EAAS,KAAA,EAAO,QAAW,OAAO,CAAA;AAAA,EAClG,KAAA,EAAO,CAAC,KAAA,EAAe,OAAA,KAAoC,MAAM,QAAA,EAAU,KAAA,EAAO,QAAW,OAAO,CAAA;AAAA,EACpG,KAAA,EAAO,CAAC,KAAA,EAAe,OAAA,KAAoC,MAAM,QAAA,EAAU,KAAA,EAAO,QAAW,OAAO,CAAA;AAAA;AAAA,EAEpG,OAAA,EAAS,CAAC,KAAA,EAAe,eAAA,EAAyB,YAChD,KAAA,CAAM,UAAA,EAAY,KAAA,EAAO,eAAA,EAAiB,OAAO,CAAA;AAAA;AAAA,EAEnD,SAAA,EAAW,CAAC,KAAA,EAAe,OAAA,KA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AAA,CAAa,OAAO,IAAA,CAAK,CAAA,qCAAA,EAAwC,SAAA,CAAU,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA;AACpF,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"twilio.cjs","sourcesContent":["import { NiadraValidationError } from \"./errors.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type { SubjectKind } from \"./types/vocabulary.js\";\n\ninterface HandleOptions {\n /** Overrides the subject kind the server would infer from the handle type. */\n subjectKind?: SubjectKind;\n}\n\nfunction build(type: Handle[\"type\"], value: string, scope?: string, options?: HandleOptions): Handle {\n const handle: Handle = { type, value };\n if (scope !== undefined) handle.scope = scope;\n if (options?.subjectKind !== undefined) handle.subject_kind = options.subjectKind;\n return handle;\n}\n\n/**\n * Builders for the handle types the API accepts. They only assemble the object; the value is\n * normalized and validated on the server, which is the single source of truth for matching.\n *\n * @example\n * niadra.context({ subject: handles.phone(\"+5511987654321\"), conversation_id: \"wa-8812\" })\n */\nexport const handles = {\n /** A phone number in E.164 form, such as `+5511987654321`. */\n phone: (e164: string, options?: HandleOptions): Handle => build(\"phone_e164\", e164, undefined, options),\n email: (address: string, options?: HandleOptions): Handle => build(\"email\", address, undefined, options),\n /** The WhatsApp id (`wa_id`) the Cloud API reports for a contact. */\n waId: (value: string, options?: HandleOptions): Handle => build(\"wa_id\", value, undefined, options),\n waJid: (value: string, options?: HandleOptions): Handle => build(\"wa_jid\", value, undefined, options),\n waLid: (value: string, options?: HandleOptions): Handle => build(\"wa_lid\", value, undefined, options),\n /** A business-scoped WhatsApp user id; `businessAccount` is the WhatsApp Business account it belongs to. */\n waBsuid: (value: string, businessAccount: string, options?: HandleOptions): Handle =>\n build(\"wa_bsuid\", value, businessAccount, options),\n /** The user id in your own app or site. */\n appUserId: (value: string, options?: HandleOptions): Handle => build(\"app_user_id\", value, undefined, options),\n /** The id of a person or organization in a system of record; `system` names that system, such as `crm`. */\n systemId: (value: string, system: string, options?: HandleOptions): Handle =>\n build(\"system_id\", value, system, options),\n /**\n * A person's national document, such as a CPF: `govIdHmac(\"529.982.247-25\", \"BR\")`. Send the number\n * itself, never a hash of it: the server checks its check digits, then keeps only a keyed hash with your\n * space's secret and an encrypted copy, and shows it masked. `country` is its ISO 3166-1 alpha-2 code.\n */\n govIdHmac: (value: string, country: string, options?: HandleOptions): Handle =>\n build(\"gov_id_hmac\", value, country, options),\n /**\n * A company's registry number, such as a CNPJ: `orgRegistryHmac(\"11.222.333/0001-81\", \"BR\")`. As with\n * `govIdHmac`, send the number itself; the server checks it and keeps only a keyed hash. Identifies an\n * organization.\n */\n orgRegistryHmac: (value: string, country: string): Handle =>\n build(\"org_registry_hmac\", value, country, { subjectKind: \"account\" }),\n /** An e-mail domain, such as `acme.com`. Identifies an organization. */\n emailDomain: (domain: string): Handle => build(\"email_domain\", domain, undefined, { subjectKind: \"account\" }),\n /** An anonymous visitor or device id, before the person is known. */\n anonId: (value: string, options?: HandleOptions): Handle => build(\"anon_id\", value, undefined, options),\n} as const;\n\n/**\n * Accepts an `ObjectRef` or the `type:namespace:id` shorthand. The id may itself contain\n * colons (`invoice:erp:2026:0823`); only the first two separate the parts.\n */\nexport function toObjectRef(object: ObjectRef | string): ObjectRef {\n if (typeof object !== \"string\") return object;\n const first = object.indexOf(\":\");\n const second = first < 0 ? -1 : object.indexOf(\":\", first + 1);\n if (first <= 0 || second <= first + 1 || second === object.length - 1) {\n throw new NiadraValidationError(\"object must look like `type:namespace:id`\");\n }\n return { type: object.slice(0, first), namespace: object.slice(first + 1, second), id: object.slice(second + 1) };\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 Twilio webhooks: Programmable Voice, Messaging (SMS and WhatsApp) and Conversations.\n * Translates only: it checks `X-Twilio-Signature`, finds the customer's handle, the call or thread\n * id and what the carrier attested, and records the inbound turn. It never answers with TwiML.\n *\n * @example\n * const { status, request } = await readTwilio(publicUrl, await req.text(), req.headers, { authToken });\n * const convo = niadra.conversation({ subject: request.subject, channel: request.channel, conversation_id: request.conversationId });\n * await verifyTwilio(convo, request); // StirVerstat on voice; then the first read starts while it rings\n * recordTwilioInbound(convo, request);\n * const ctx = await convo.ready(); // the call's first read, within timeouts.contextVoiceStart\n */\n\nimport type { Conversation } from \"../conversation.js\";\nimport { handles } from \"../handles.js\";\nimport type { Handle } from \"../types/common.js\";\nimport { attestationProof, errorName, phoneHandle } from \"./shared.js\";\nimport type { Proof } from \"./shared.js\";\nimport { base64, bodyText, header, hmac, safeEqual } from \"./webhook.js\";\nimport type { HeadersLike } from \"./webhook.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { Proof } from \"./shared.js\";\nexport type { HeadersLike } from \"./webhook.js\";\n\n/** One Twilio webhook request, read. */\nexport interface TwilioRequest {\n /** `voice`, `whatsapp`, `sms` or `conversations`, usable as the Niadra channel. */\n channel: \"voice\" | \"whatsapp\" | \"sms\" | \"conversations\";\n /** The customer: `WaId` on WhatsApp, else the phone number on the customer's side of the call or message. */\n subject: Handle;\n /** `CallSid` on voice, `ConversationSid` on Conversations; messages leave the thread id to you. */\n conversationId?: string | undefined;\n /** `MessageSid`: the idempotency key of the turn. */\n messageId?: string | undefined;\n /** The message body, or the speech recognized by `<Gather input=\"speech\">`. */\n text?: string | undefined;\n /** Speech confidence from `<Gather>`, between 0 and 1. */\n confidence?: number | undefined;\n /** What the carrier attested (`StirVerstat`), as a proof for `verify()`; `null` when nothing was proven. */\n proof: Proof | null;\n /** Every parameter Twilio sent. */\n params: Record<string, string>;\n}\n\n/**\n * Checks `X-Twilio-Signature`: base64 HMAC-SHA1, with the auth token, of the full URL Twilio called\n * followed by every POST parameter, sorted by name, as name and value.\n */\nexport async function validTwilioSignature(\n url: string,\n params: URLSearchParams | Record<string, string>,\n signature: string | undefined,\n authToken: string,\n): Promise<boolean> {\n if (!signature || !authToken) return false;\n const pairs = params instanceof URLSearchParams ? [...params.entries()] : Object.entries(params);\n pairs.sort(([a, x], [b, y]) => (a === b ? (x < y ? -1 : x > y ? 1 : 0) : a < b ? -1 : 1));\n const data = url + pairs.map(([key, value]) => key + value).join(\"\");\n return safeEqual(signature, base64(await hmac(\"SHA-1\", authToken, data)));\n}\n\n/**\n * Checks the signature of a form-encoded Twilio webhook and reads it. `url` is the exact public URL\n * Twilio called, query string included (behind a proxy, not the one your server sees).\n */\nexport async function readTwilio(\n url: string,\n rawBody: string | Uint8Array | ArrayBuffer,\n headers: HeadersLike,\n options: { authToken: string },\n): Promise<{ status: number; request: TwilioRequest | null }> {\n const params = new URLSearchParams(bodyText(rawBody));\n if (!(await validTwilioSignature(url, params, header(headers, \"x-twilio-signature\"), options.authToken))) {\n return { status: 403, request: null };\n }\n return { status: 200, request: parseTwilio(params) };\n}\n\n/** Reads the parameters of an already verified request; `null` when no customer can be found. */\nexport function parseTwilio(params: URLSearchParams | Record<string, string>): TwilioRequest | null {\n const all: Record<string, string> = params instanceof URLSearchParams ? Object.fromEntries(params.entries()) : { ...params };\n const get = (name: string): string | undefined => {\n const value = all[name];\n return value === \"\" ? undefined : value;\n };\n const outbound = get(\"Direction\")?.startsWith(\"outbound\") ?? false;\n const other = outbound ? get(\"To\") : get(\"From\");\n const text = get(\"Body\") ?? get(\"SpeechResult\");\n const confidence = Number(get(\"Confidence\"));\n const base = {\n messageId: get(\"MessageSid\"),\n text,\n confidence: Number.isFinite(confidence) && confidence >= 0 && confidence <= 1 && get(\"SpeechResult\") ? confidence : undefined,\n proof: attestationProof(get(\"StirVerstat\")),\n params: all,\n };\n\n if (get(\"ConversationSid\")) {\n const author = get(\"Author\");\n const subject = author ? (phoneHandle(author.replace(/^whatsapp:/, \"\")) ?? handles.appUserId(author)) : null;\n return subject ? { ...base, channel: \"conversations\", subject, conversationId: get(\"ConversationSid\") } : null;\n }\n if (other?.startsWith(\"whatsapp:\")) {\n const waId = get(\"WaId\");\n const subject = waId ? handles.waId(waId) : phoneHandle(other.slice(\"whatsapp:\".length));\n return subject ? { ...base, channel: \"whatsapp\", subject } : null;\n }\n const subject = phoneHandle(other);\n if (!subject) return null;\n if (get(\"CallSid\") && !get(\"MessageSid\")) return { ...base, channel: \"voice\", subject, conversationId: get(\"CallSid\") };\n return { ...base, channel: \"sms\", subject };\n}\n\n/**\n * Records what the carrier attested for the call, before the first context read, and on the\n * incoming call webhook (`CallStatus` `ringing`) starts the conversation's first read at the level\n * it proved, so it runs while the phone rings; `conversation.ready()` waits for it. Never rejects.\n */\nexport async function verifyTwilio(conversation: Conversation, request: TwilioRequest): Promise<void> {\n if (request.proof) {\n try {\n await conversation.verify(request.proof);\n } catch (error) {\n conversation.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n if (request.channel !== \"voice\" || request.params.CallStatus !== \"ringing\") return;\n try {\n conversation.begin();\n } catch (error) {\n conversation.logger.warn(`could not start the first read (${errorName(error)})`);\n }\n}\n\n/** Records the inbound text or speech as the customer's turn, keyed by `MessageSid` when there is one. */\nexport function recordTwilioInbound(conversation: Conversation, request: TwilioRequest): string | null {\n if (!request.text) return null;\n try {\n return conversation.customer(request.text, {\n ...(request.messageId ? { idempotency_key: request.messageId } : {}),\n ...(request.confidence !== undefined ? { stt_confidence: request.confidence } : {}),\n });\n } catch (error) {\n conversation.logger.warn(`could not record the Twilio message (${errorName(error)})`);\n return null;\n }\n}\n"]}
package/dist/twilio.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { g as Handle, bs as Conversation } from './client-B_ip8T2o.cjs';
2
- import { P as Proof } from './shared-DEkF2Y_z.cjs';
3
- export { c as attestationProof } from './shared-DEkF2Y_z.cjs';
4
- import { H as HeadersLike } from './webhook-CuR0Wckd.cjs';
1
+ import { g as Handle, bx as Conversation } from './client-rmWhZJOx.cjs';
2
+ import { P as Proof } from './shared-zaTBum17.cjs';
3
+ export { c as attestationProof } from './shared-zaTBum17.cjs';
4
+ import { H as HeadersLike } from './webhook-CX7nvQig.cjs';
5
5
 
6
6
  /**
7
7
  * Niadra for Twilio webhooks: Programmable Voice, Messaging (SMS and WhatsApp) and Conversations.
package/dist/twilio.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { g as Handle, bs as Conversation } from './client-B_ip8T2o.js';
2
- import { P as Proof } from './shared-BLkAbvuf.js';
3
- export { c as attestationProof } from './shared-BLkAbvuf.js';
4
- import { H as HeadersLike } from './webhook-BaraTaA9.js';
1
+ import { g as Handle, bx as Conversation } from './client-rmWhZJOx.js';
2
+ import { P as Proof } from './shared-Cs7h5C4Y.js';
3
+ export { c as attestationProof } from './shared-Cs7h5C4Y.js';
4
+ import { H as HeadersLike } from './webhook-2V5QgnKI.js';
5
5
 
6
6
  /**
7
7
  * Niadra for Twilio webhooks: Programmable Voice, Messaging (SMS and WhatsApp) and Conversations.
package/dist/twilio.js CHANGED
@@ -19,9 +19,17 @@ var handles = {
19
19
  appUserId: (value, options) => build("app_user_id", value, void 0, options),
20
20
  /** The id of a person or organization in a system of record; `system` names that system, such as `crm`. */
21
21
  systemId: (value, system, options) => build("system_id", value, system, options),
22
- /** An HMAC of a national document number; `country` is its ISO 3166-1 alpha-2 code. */
22
+ /**
23
+ * A person's national document, such as a CPF: `govIdHmac("529.982.247-25", "BR")`. Send the number
24
+ * itself, never a hash of it: the server checks its check digits, then keeps only a keyed hash with your
25
+ * space's secret and an encrypted copy, and shows it masked. `country` is its ISO 3166-1 alpha-2 code.
26
+ */
23
27
  govIdHmac: (value, country, options) => build("gov_id_hmac", value, country, options),
24
- /** An HMAC of a company registry number. Identifies an organization. */
28
+ /**
29
+ * A company's registry number, such as a CNPJ: `orgRegistryHmac("11.222.333/0001-81", "BR")`. As with
30
+ * `govIdHmac`, send the number itself; the server checks it and keeps only a keyed hash. Identifies an
31
+ * organization.
32
+ */
25
33
  orgRegistryHmac: (value, country) => build("org_registry_hmac", value, country, { subjectKind: "account" }),
26
34
  /** An e-mail domain, such as `acme.com`. Identifies an organization. */
27
35
  emailDomain: (domain) => build("email_domain", domain, void 0, { subjectKind: "account" }),
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/handles.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/twilio.ts"],"names":["subject"],"mappings":";AASA,SAAS,KAAA,CAAM,IAAA,EAAsB,KAAA,EAAe,KAAA,EAAgB,OAAA,EAAiC;AACnG,EAAA,MAAM,MAAA,GAAiB,EAAE,IAAA,EAAM,KAAA,EAAM;AACrC,EAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAA,CAAO,KAAA,GAAQ,KAAA;AACxC,EAAA,IAAI,OAAA,EAAS,WAAA,KAAgB,MAAA,EAAW,MAAA,CAAO,eAAe,OAAA,CAAQ,WAAA;AACtE,EAAA,OAAO,MAAA;AACT;AASO,IAAM,OAAA,GAAU;AAAA;AAAA,EAErB,KAAA,EAAO,CAAC,IAAA,EAAc,OAAA,KAAoC,MAAM,YAAA,EAAc,IAAA,EAAM,QAAW,OAAO,CAAA;AAAA,EACtG,KAAA,EAAO,CAAC,OAAA,EAAiB,OAAA,KAAoC,MAAM,OAAA,EAAS,OAAA,EAAS,QAAW,OAAO,CAAA;AAAA;AAAA,EAEvG,IAAA,EAAM,CAAC,KAAA,EAAe,OAAA,KAAoC,MAAM,OAAA,EAAS,KAAA,EAAO,QAAW,OAAO,CAAA;AAAA,EAClG,KAAA,EAAO,CAAC,KAAA,EAAe,OAAA,KAAoC,MAAM,QAAA,EAAU,KAAA,EAAO,QAAW,OAAO,CAAA;AAAA,EACpG,KAAA,EAAO,CAAC,KAAA,EAAe,OAAA,KAAoC,MAAM,QAAA,EAAU,KAAA,EAAO,QAAW,OAAO,CAAA;AAAA;AAAA,EAEpG,OAAA,EAAS,CAAC,KAAA,EAAe,eAAA,EAAyB,YAChD,KAAA,CAAM,UAAA,EAAY,KAAA,EAAO,eAAA,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SAAS,KAAA,EAAO;AACd,IAAA,YAAA,CAAa,OAAO,IAAA,CAAK,CAAA,qCAAA,EAAwC,SAAA,CAAU,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA;AACpF,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"twilio.js","sourcesContent":["import { NiadraValidationError } from \"./errors.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type { SubjectKind } from \"./types/vocabulary.js\";\n\ninterface HandleOptions {\n /** Overrides the subject kind the server would infer from the handle type. */\n subjectKind?: SubjectKind;\n}\n\nfunction build(type: Handle[\"type\"], value: string, scope?: string, options?: HandleOptions): Handle {\n const handle: Handle = { type, value };\n if (scope !== undefined) handle.scope = scope;\n if (options?.subjectKind !== undefined) handle.subject_kind = options.subjectKind;\n return handle;\n}\n\n/**\n * Builders for the handle types the API accepts. They only assemble the object; the value is\n * normalized and validated on the server, which is the single source of truth for matching.\n *\n * @example\n * niadra.context({ subject: handles.phone(\"+5511987654321\"), conversation_id: \"wa-8812\" })\n */\nexport const handles = {\n /** A phone number in E.164 form, such as `+5511987654321`. */\n phone: (e164: string, options?: HandleOptions): Handle => build(\"phone_e164\", e164, undefined, options),\n email: (address: string, options?: HandleOptions): Handle => build(\"email\", address, undefined, options),\n /** The WhatsApp id (`wa_id`) the Cloud API reports for a contact. */\n waId: (value: string, options?: HandleOptions): Handle => build(\"wa_id\", value, undefined, options),\n waJid: (value: string, options?: HandleOptions): Handle => build(\"wa_jid\", value, undefined, options),\n waLid: (value: string, options?: HandleOptions): Handle => build(\"wa_lid\", value, undefined, options),\n /** A business-scoped WhatsApp user id; `businessAccount` is the WhatsApp Business account it belongs to. */\n waBsuid: (value: string, businessAccount: string, options?: HandleOptions): Handle =>\n build(\"wa_bsuid\", value, businessAccount, options),\n /** The user id in your own app or site. */\n appUserId: (value: string, options?: HandleOptions): Handle => build(\"app_user_id\", value, undefined, options),\n /** The id of a person or organization in a system of record; `system` names that system, such as `crm`. */\n systemId: (value: string, system: string, options?: HandleOptions): Handle =>\n build(\"system_id\", value, system, options),\n /** An HMAC of a national document number; `country` is its ISO 3166-1 alpha-2 code. */\n govIdHmac: (value: string, country: string, options?: HandleOptions): Handle =>\n build(\"gov_id_hmac\", value, country, options),\n /** An HMAC of a company registry number. Identifies an organization. */\n orgRegistryHmac: (value: string, country: string): Handle =>\n build(\"org_registry_hmac\", value, country, { subjectKind: \"account\" }),\n /** An e-mail domain, such as `acme.com`. Identifies an organization. */\n emailDomain: (domain: string): Handle => build(\"email_domain\", domain, undefined, { subjectKind: \"account\" }),\n /** An anonymous visitor or device id, before the person is known. */\n anonId: (value: string, options?: HandleOptions): Handle => build(\"anon_id\", value, undefined, options),\n} as const;\n\n/**\n * Accepts an `ObjectRef` or the `type:namespace:id` shorthand. The id may itself contain\n * colons (`invoice:erp:2026:0823`); only the first two separate the parts.\n */\nexport function toObjectRef(object: ObjectRef | string): ObjectRef {\n if (typeof object !== \"string\") return object;\n const first = object.indexOf(\":\");\n const second = first < 0 ? -1 : object.indexOf(\":\", first + 1);\n if (first <= 0 || second <= first + 1 || second === object.length - 1) {\n throw new NiadraValidationError(\"object must look like `type:namespace:id`\");\n }\n return { type: object.slice(0, first), namespace: object.slice(first + 1, second), id: object.slice(second + 1) };\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 Twilio webhooks: Programmable Voice, Messaging (SMS and WhatsApp) and Conversations.\n * Translates only: it checks `X-Twilio-Signature`, finds the customer's handle, the call or thread\n * id and what the carrier attested, and records the inbound turn. It never answers with TwiML.\n *\n * @example\n * const { status, request } = await readTwilio(publicUrl, await req.text(), req.headers, { authToken });\n * const convo = niadra.conversation({ subject: request.subject, channel: request.channel, conversation_id: request.conversationId });\n * await verifyTwilio(convo, request); // StirVerstat on voice; then the first read starts while it rings\n * recordTwilioInbound(convo, request);\n * const ctx = await convo.ready(); // the call's first read, within timeouts.contextVoiceStart\n */\n\nimport type { Conversation } from \"../conversation.js\";\nimport { handles } from \"../handles.js\";\nimport type { Handle } from \"../types/common.js\";\nimport { attestationProof, errorName, phoneHandle } from \"./shared.js\";\nimport type { Proof } from \"./shared.js\";\nimport { base64, bodyText, header, hmac, safeEqual } from \"./webhook.js\";\nimport type { HeadersLike } from \"./webhook.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { Proof } from \"./shared.js\";\nexport type { HeadersLike } from \"./webhook.js\";\n\n/** One Twilio webhook request, read. */\nexport interface TwilioRequest {\n /** `voice`, `whatsapp`, `sms` or `conversations`, usable as the Niadra channel. */\n channel: \"voice\" | \"whatsapp\" | \"sms\" | \"conversations\";\n /** The customer: `WaId` on WhatsApp, else the phone number on the customer's side of the call or message. */\n subject: Handle;\n /** `CallSid` on voice, `ConversationSid` on Conversations; messages leave the thread id to you. */\n conversationId?: string | undefined;\n /** `MessageSid`: the idempotency key of the turn. */\n messageId?: string | undefined;\n /** The message body, or the speech recognized by `<Gather input=\"speech\">`. */\n text?: string | undefined;\n /** Speech confidence from `<Gather>`, between 0 and 1. */\n confidence?: number | undefined;\n /** What the carrier attested (`StirVerstat`), as a proof for `verify()`; `null` when nothing was proven. */\n proof: Proof | null;\n /** Every parameter Twilio sent. */\n params: Record<string, string>;\n}\n\n/**\n * Checks `X-Twilio-Signature`: base64 HMAC-SHA1, with the auth token, of the full URL Twilio called\n * followed by every POST parameter, sorted by name, as name and value.\n */\nexport async function validTwilioSignature(\n url: string,\n params: URLSearchParams | Record<string, string>,\n signature: string | undefined,\n authToken: string,\n): Promise<boolean> {\n if (!signature || !authToken) return false;\n const pairs = params instanceof URLSearchParams ? [...params.entries()] : Object.entries(params);\n pairs.sort(([a, x], [b, y]) => (a === b ? (x < y ? -1 : x > y ? 1 : 0) : a < b ? -1 : 1));\n const data = url + pairs.map(([key, value]) => key + value).join(\"\");\n return safeEqual(signature, base64(await hmac(\"SHA-1\", authToken, data)));\n}\n\n/**\n * Checks the signature of a form-encoded Twilio webhook and reads it. `url` is the exact public URL\n * Twilio called, query string included (behind a proxy, not the one your server sees).\n */\nexport async function readTwilio(\n url: string,\n rawBody: string | Uint8Array | ArrayBuffer,\n headers: HeadersLike,\n options: { authToken: string },\n): Promise<{ status: number; request: TwilioRequest | null }> {\n const params = new URLSearchParams(bodyText(rawBody));\n if (!(await validTwilioSignature(url, params, header(headers, \"x-twilio-signature\"), options.authToken))) {\n return { status: 403, request: null };\n }\n return { status: 200, request: parseTwilio(params) };\n}\n\n/** Reads the parameters of an already verified request; `null` when no customer can be found. */\nexport function parseTwilio(params: URLSearchParams | Record<string, string>): TwilioRequest | null {\n const all: Record<string, string> = params instanceof URLSearchParams ? Object.fromEntries(params.entries()) : { ...params };\n const get = (name: string): string | undefined => {\n const value = all[name];\n return value === \"\" ? undefined : value;\n };\n const outbound = get(\"Direction\")?.startsWith(\"outbound\") ?? false;\n const other = outbound ? get(\"To\") : get(\"From\");\n const text = get(\"Body\") ?? get(\"SpeechResult\");\n const confidence = Number(get(\"Confidence\"));\n const base = {\n messageId: get(\"MessageSid\"),\n text,\n confidence: Number.isFinite(confidence) && confidence >= 0 && confidence <= 1 && get(\"SpeechResult\") ? confidence : undefined,\n proof: attestationProof(get(\"StirVerstat\")),\n params: all,\n };\n\n if (get(\"ConversationSid\")) {\n const author = get(\"Author\");\n const subject = author ? (phoneHandle(author.replace(/^whatsapp:/, \"\")) ?? handles.appUserId(author)) : null;\n return subject ? { ...base, channel: \"conversations\", subject, conversationId: get(\"ConversationSid\") } : null;\n }\n if (other?.startsWith(\"whatsapp:\")) {\n const waId = get(\"WaId\");\n const subject = waId ? handles.waId(waId) : phoneHandle(other.slice(\"whatsapp:\".length));\n return subject ? { ...base, channel: \"whatsapp\", subject } : null;\n }\n const subject = phoneHandle(other);\n if (!subject) return null;\n if (get(\"CallSid\") && !get(\"MessageSid\")) return { ...base, channel: \"voice\", subject, conversationId: get(\"CallSid\") };\n return { ...base, channel: \"sms\", subject };\n}\n\n/**\n * Records what the carrier attested for the call, before the first context read, and on the\n * incoming call webhook (`CallStatus` `ringing`) starts the conversation's first read at the level\n * it proved, so it runs while the phone rings; `conversation.ready()` waits for it. Never rejects.\n */\nexport async function verifyTwilio(conversation: Conversation, request: TwilioRequest): Promise<void> {\n if (request.proof) {\n try {\n await conversation.verify(request.proof);\n } catch (error) {\n conversation.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n if (request.channel !== \"voice\" || request.params.CallStatus !== \"ringing\") return;\n try {\n conversation.begin();\n } catch (error) {\n conversation.logger.warn(`could not start the first read (${errorName(error)})`);\n }\n}\n\n/** Records the inbound text or speech as the customer's turn, keyed by `MessageSid` when there is one. */\nexport function recordTwilioInbound(conversation: Conversation, request: TwilioRequest): string | null {\n if (!request.text) return null;\n try {\n return conversation.customer(request.text, {\n ...(request.messageId ? { idempotency_key: request.messageId } : {}),\n ...(request.confidence !== undefined ? { stt_confidence: request.confidence } : {}),\n });\n } catch (error) {\n conversation.logger.warn(`could not record the Twilio message (${errorName(error)})`);\n return null;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/handles.ts","../src/integrations/shared.ts","../src/integrations/webhook.ts","../src/integrations/twilio.ts"],"names":["subject"],"mappings":";AASA,SAAS,KAAA,CAAM,IAAA,EAAsB,KAAA,EAAe,KAAA,EAAgB,OAAA,EAAiC;AACnG,EAAA,MAAM,MAAA,GAAiB,EAAE,IAAA,EAAM,KAAA,EAAM;AACrC,EAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAA,CAAO,KAAA,GAAQ,KAAA;AACxC,EAAA,IAAI,OAAA,EAAS,WAAA,KAAgB,MAAA,EAAW,MAAA,CAAO,eAAe,OAAA,CAAQ,WAAA;AACtE,EAAA,OAAO,MAAA;AACT;AASO,IAAM,OAAA,GAAU;AAAA;A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AAY,OAAA,IAAW,OAAA,CAAQ,MAAA,CAAO,eAAe,SAAA,EAAW;AAC5E,EAAA,IAAI;AACF,IAAA,YAAA,CAAa,KAAA,EAAM;AAAA,EACrB,SAAS,KAAA,EAAO;AACd,IAAA,YAAA,CAAa,OAAO,IAAA,CAAK,CAAA,gCAAA,EAAmC,SAAA,CAAU,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA;AAAA,EACjF;AACF;AAGO,SAAS,mBAAA,CAAoB,cAA4B,OAAA,EAAuC;AACrG,EAAA,IAAI,CAAC,OAAA,CAAQ,IAAA,EAAM,OAAO,IAAA;AAC1B,EAAA,IAAI;AACF,IAAA,OAAO,YAAA,CAAa,QAAA,CAAS,OAAA,CAAQ,IAAA,EAAM;AAAA,MACzC,GAAI,QAAQ,SAAA,GAAY,EAAE,iBAAiB,OAAA,CAAQ,SAAA,KAAc,EAAC;AAAA,MAClE,GAAI,QAAQ,UAAA,KAAe,KAAA,CAAA,GAAY,EAAE,cAAA,EAAgB,OAAA,CAAQ,UAAA,EAAW,GAAI;AAAC,KAClF,CAAA;AAAA,EACH,SAAS,KAAA,EAAO;AACd,IAAA,YAAA,CAAa,OAAO,IAAA,CAAK,CAAA,qCAAA,EAAwC,SAAA,CAAU,KAAK,CAAC,CAAA,CAAA,CAAG,CAAA;AACpF,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"twilio.js","sourcesContent":["import { NiadraValidationError } from \"./errors.js\";\nimport type { Handle, ObjectRef } from \"./types/common.js\";\nimport type { SubjectKind } from \"./types/vocabulary.js\";\n\ninterface HandleOptions {\n /** Overrides the subject kind the server would infer from the handle type. */\n subjectKind?: SubjectKind;\n}\n\nfunction build(type: Handle[\"type\"], value: string, scope?: string, options?: HandleOptions): Handle {\n const handle: Handle = { type, value };\n if (scope !== undefined) handle.scope = scope;\n if (options?.subjectKind !== undefined) handle.subject_kind = options.subjectKind;\n return handle;\n}\n\n/**\n * Builders for the handle types the API accepts. They only assemble the object; the value is\n * normalized and validated on the server, which is the single source of truth for matching.\n *\n * @example\n * niadra.context({ subject: handles.phone(\"+5511987654321\"), conversation_id: \"wa-8812\" })\n */\nexport const handles = {\n /** A phone number in E.164 form, such as `+5511987654321`. */\n phone: (e164: string, options?: HandleOptions): Handle => build(\"phone_e164\", e164, undefined, options),\n email: (address: string, options?: HandleOptions): Handle => build(\"email\", address, undefined, options),\n /** The WhatsApp id (`wa_id`) the Cloud API reports for a contact. */\n waId: (value: string, options?: HandleOptions): Handle => build(\"wa_id\", value, undefined, options),\n waJid: (value: string, options?: HandleOptions): Handle => build(\"wa_jid\", value, undefined, options),\n waLid: (value: string, options?: HandleOptions): Handle => build(\"wa_lid\", value, undefined, options),\n /** A business-scoped WhatsApp user id; `businessAccount` is the WhatsApp Business account it belongs to. */\n waBsuid: (value: string, businessAccount: string, options?: HandleOptions): Handle =>\n build(\"wa_bsuid\", value, businessAccount, options),\n /** The user id in your own app or site. */\n appUserId: (value: string, options?: HandleOptions): Handle => build(\"app_user_id\", value, undefined, options),\n /** The id of a person or organization in a system of record; `system` names that system, such as `crm`. */\n systemId: (value: string, system: string, options?: HandleOptions): Handle =>\n build(\"system_id\", value, system, options),\n /**\n * A person's national document, such as a CPF: `govIdHmac(\"529.982.247-25\", \"BR\")`. Send the number\n * itself, never a hash of it: the server checks its check digits, then keeps only a keyed hash with your\n * space's secret and an encrypted copy, and shows it masked. `country` is its ISO 3166-1 alpha-2 code.\n */\n govIdHmac: (value: string, country: string, options?: HandleOptions): Handle =>\n build(\"gov_id_hmac\", value, country, options),\n /**\n * A company's registry number, such as a CNPJ: `orgRegistryHmac(\"11.222.333/0001-81\", \"BR\")`. As with\n * `govIdHmac`, send the number itself; the server checks it and keeps only a keyed hash. Identifies an\n * organization.\n */\n orgRegistryHmac: (value: string, country: string): Handle =>\n build(\"org_registry_hmac\", value, country, { subjectKind: \"account\" }),\n /** An e-mail domain, such as `acme.com`. Identifies an organization. */\n emailDomain: (domain: string): Handle => build(\"email_domain\", domain, undefined, { subjectKind: \"account\" }),\n /** An anonymous visitor or device id, before the person is known. */\n anonId: (value: string, options?: HandleOptions): Handle => build(\"anon_id\", value, undefined, options),\n} as const;\n\n/**\n * Accepts an `ObjectRef` or the `type:namespace:id` shorthand. The id may itself contain\n * colons (`invoice:erp:2026:0823`); only the first two separate the parts.\n */\nexport function toObjectRef(object: ObjectRef | string): ObjectRef {\n if (typeof object !== \"string\") return object;\n const first = object.indexOf(\":\");\n const second = first < 0 ? -1 : object.indexOf(\":\", first + 1);\n if (first <= 0 || second <= first + 1 || second === object.length - 1) {\n throw new NiadraValidationError(\"object must look like `type:namespace:id`\");\n }\n return { type: object.slice(0, first), namespace: object.slice(first + 1, second), id: object.slice(second + 1) };\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 Twilio webhooks: Programmable Voice, Messaging (SMS and WhatsApp) and Conversations.\n * Translates only: it checks `X-Twilio-Signature`, finds the customer's handle, the call or thread\n * id and what the carrier attested, and records the inbound turn. It never answers with TwiML.\n *\n * @example\n * const { status, request } = await readTwilio(publicUrl, await req.text(), req.headers, { authToken });\n * const convo = niadra.conversation({ subject: request.subject, channel: request.channel, conversation_id: request.conversationId });\n * await verifyTwilio(convo, request); // StirVerstat on voice; then the first read starts while it rings\n * recordTwilioInbound(convo, request);\n * const ctx = await convo.ready(); // the call's first read, within timeouts.contextVoiceStart\n */\n\nimport type { Conversation } from \"../conversation.js\";\nimport { handles } from \"../handles.js\";\nimport type { Handle } from \"../types/common.js\";\nimport { attestationProof, errorName, phoneHandle } from \"./shared.js\";\nimport type { Proof } from \"./shared.js\";\nimport { base64, bodyText, header, hmac, safeEqual } from \"./webhook.js\";\nimport type { HeadersLike } from \"./webhook.js\";\n\nexport { attestationProof } from \"./shared.js\";\nexport type { Proof } from \"./shared.js\";\nexport type { HeadersLike } from \"./webhook.js\";\n\n/** One Twilio webhook request, read. */\nexport interface TwilioRequest {\n /** `voice`, `whatsapp`, `sms` or `conversations`, usable as the Niadra channel. */\n channel: \"voice\" | \"whatsapp\" | \"sms\" | \"conversations\";\n /** The customer: `WaId` on WhatsApp, else the phone number on the customer's side of the call or message. */\n subject: Handle;\n /** `CallSid` on voice, `ConversationSid` on Conversations; messages leave the thread id to you. */\n conversationId?: string | undefined;\n /** `MessageSid`: the idempotency key of the turn. */\n messageId?: string | undefined;\n /** The message body, or the speech recognized by `<Gather input=\"speech\">`. */\n text?: string | undefined;\n /** Speech confidence from `<Gather>`, between 0 and 1. */\n confidence?: number | undefined;\n /** What the carrier attested (`StirVerstat`), as a proof for `verify()`; `null` when nothing was proven. */\n proof: Proof | null;\n /** Every parameter Twilio sent. */\n params: Record<string, string>;\n}\n\n/**\n * Checks `X-Twilio-Signature`: base64 HMAC-SHA1, with the auth token, of the full URL Twilio called\n * followed by every POST parameter, sorted by name, as name and value.\n */\nexport async function validTwilioSignature(\n url: string,\n params: URLSearchParams | Record<string, string>,\n signature: string | undefined,\n authToken: string,\n): Promise<boolean> {\n if (!signature || !authToken) return false;\n const pairs = params instanceof URLSearchParams ? [...params.entries()] : Object.entries(params);\n pairs.sort(([a, x], [b, y]) => (a === b ? (x < y ? -1 : x > y ? 1 : 0) : a < b ? -1 : 1));\n const data = url + pairs.map(([key, value]) => key + value).join(\"\");\n return safeEqual(signature, base64(await hmac(\"SHA-1\", authToken, data)));\n}\n\n/**\n * Checks the signature of a form-encoded Twilio webhook and reads it. `url` is the exact public URL\n * Twilio called, query string included (behind a proxy, not the one your server sees).\n */\nexport async function readTwilio(\n url: string,\n rawBody: string | Uint8Array | ArrayBuffer,\n headers: HeadersLike,\n options: { authToken: string },\n): Promise<{ status: number; request: TwilioRequest | null }> {\n const params = new URLSearchParams(bodyText(rawBody));\n if (!(await validTwilioSignature(url, params, header(headers, \"x-twilio-signature\"), options.authToken))) {\n return { status: 403, request: null };\n }\n return { status: 200, request: parseTwilio(params) };\n}\n\n/** Reads the parameters of an already verified request; `null` when no customer can be found. */\nexport function parseTwilio(params: URLSearchParams | Record<string, string>): TwilioRequest | null {\n const all: Record<string, string> = params instanceof URLSearchParams ? Object.fromEntries(params.entries()) : { ...params };\n const get = (name: string): string | undefined => {\n const value = all[name];\n return value === \"\" ? undefined : value;\n };\n const outbound = get(\"Direction\")?.startsWith(\"outbound\") ?? false;\n const other = outbound ? get(\"To\") : get(\"From\");\n const text = get(\"Body\") ?? get(\"SpeechResult\");\n const confidence = Number(get(\"Confidence\"));\n const base = {\n messageId: get(\"MessageSid\"),\n text,\n confidence: Number.isFinite(confidence) && confidence >= 0 && confidence <= 1 && get(\"SpeechResult\") ? confidence : undefined,\n proof: attestationProof(get(\"StirVerstat\")),\n params: all,\n };\n\n if (get(\"ConversationSid\")) {\n const author = get(\"Author\");\n const subject = author ? (phoneHandle(author.replace(/^whatsapp:/, \"\")) ?? handles.appUserId(author)) : null;\n return subject ? { ...base, channel: \"conversations\", subject, conversationId: get(\"ConversationSid\") } : null;\n }\n if (other?.startsWith(\"whatsapp:\")) {\n const waId = get(\"WaId\");\n const subject = waId ? handles.waId(waId) : phoneHandle(other.slice(\"whatsapp:\".length));\n return subject ? { ...base, channel: \"whatsapp\", subject } : null;\n }\n const subject = phoneHandle(other);\n if (!subject) return null;\n if (get(\"CallSid\") && !get(\"MessageSid\")) return { ...base, channel: \"voice\", subject, conversationId: get(\"CallSid\") };\n return { ...base, channel: \"sms\", subject };\n}\n\n/**\n * Records what the carrier attested for the call, before the first context read, and on the\n * incoming call webhook (`CallStatus` `ringing`) starts the conversation's first read at the level\n * it proved, so it runs while the phone rings; `conversation.ready()` waits for it. Never rejects.\n */\nexport async function verifyTwilio(conversation: Conversation, request: TwilioRequest): Promise<void> {\n if (request.proof) {\n try {\n await conversation.verify(request.proof);\n } catch (error) {\n conversation.logger.warn(`could not record the verification (${errorName(error)})`);\n }\n }\n if (request.channel !== \"voice\" || request.params.CallStatus !== \"ringing\") return;\n try {\n conversation.begin();\n } catch (error) {\n conversation.logger.warn(`could not start the first read (${errorName(error)})`);\n }\n}\n\n/** Records the inbound text or speech as the customer's turn, keyed by `MessageSid` when there is one. */\nexport function recordTwilioInbound(conversation: Conversation, request: TwilioRequest): string | null {\n if (!request.text) return null;\n try {\n return conversation.customer(request.text, {\n ...(request.messageId ? { idempotency_key: request.messageId } : {}),\n ...(request.confidence !== undefined ? { stt_confidence: request.confidence } : {}),\n });\n } catch (error) {\n conversation.logger.warn(`could not record the Twilio message (${errorName(error)})`);\n return null;\n }\n}\n"]}
package/dist/vapi.cjs CHANGED
@@ -15,7 +15,7 @@ var TOOL_DEFINITIONS = [
15
15
  "type": "function",
16
16
  "function": {
17
17
  "name": "search_customer_history",
18
- "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.",
18
+ "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.",
19
19
  "parameters": {
20
20
  "type": "object",
21
21
  "properties": {
@@ -59,7 +59,8 @@ var TOOL_DEFINITIONS = [
59
59
  "open_item",
60
60
  "action",
61
61
  "object",
62
- "trait"
62
+ "trait",
63
+ "system_event"
63
64
  ]
64
65
  }
65
66
  },
@@ -86,7 +87,7 @@ var TOOL_DEFINITIONS = [
86
87
  "type": "function",
87
88
  "function": {
88
89
  "name": "get_customer_timeline",
89
- "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.",
90
+ "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.",
90
91
  "parameters": {
91
92
  "type": "object",
92
93
  "properties": {
@@ -134,7 +135,8 @@ var TOOL_DEFINITIONS = [
134
135
  "open_item",
135
136
  "action",
136
137
  "object",
137
- "trait"
138
+ "trait",
139
+ "system_event"
138
140
  ]
139
141
  }
140
142
  },
@@ -153,7 +155,7 @@ var TOOL_DEFINITIONS = [
153
155
  "type": "function",
154
156
  "function": {
155
157
  "name": "open_history_item",
156
- "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.",
158
+ "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.",
157
159
  "parameters": {
158
160
  "type": "object",
159
161
  "properties": {