signalwire-agents 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/CLAUDE.md +112 -0
  2. package/README.md +417 -0
  3. package/dist/AgentBase.d.ts +481 -0
  4. package/dist/AgentBase.js +1155 -0
  5. package/dist/AgentBase.js.map +1 -0
  6. package/dist/AgentServer.d.ts +60 -0
  7. package/dist/AgentServer.js +128 -0
  8. package/dist/AgentServer.js.map +1 -0
  9. package/dist/AuthHandler.d.ts +56 -0
  10. package/dist/AuthHandler.js +119 -0
  11. package/dist/AuthHandler.js.map +1 -0
  12. package/dist/ConfigLoader.d.ts +68 -0
  13. package/dist/ConfigLoader.js +150 -0
  14. package/dist/ConfigLoader.js.map +1 -0
  15. package/dist/ContextBuilder.d.ts +431 -0
  16. package/dist/ContextBuilder.js +751 -0
  17. package/dist/ContextBuilder.js.map +1 -0
  18. package/dist/DataMap.d.ts +179 -0
  19. package/dist/DataMap.js +321 -0
  20. package/dist/DataMap.js.map +1 -0
  21. package/dist/Logger.d.ts +91 -0
  22. package/dist/Logger.js +191 -0
  23. package/dist/Logger.js.map +1 -0
  24. package/dist/PomBuilder.d.ts +144 -0
  25. package/dist/PomBuilder.js +249 -0
  26. package/dist/PomBuilder.js.map +1 -0
  27. package/dist/PromptManager.d.ts +85 -0
  28. package/dist/PromptManager.js +108 -0
  29. package/dist/PromptManager.js.map +1 -0
  30. package/dist/SchemaUtils.d.ts +42 -0
  31. package/dist/SchemaUtils.js +148 -0
  32. package/dist/SchemaUtils.js.map +1 -0
  33. package/dist/ServerlessAdapter.d.ts +100 -0
  34. package/dist/ServerlessAdapter.js +166 -0
  35. package/dist/ServerlessAdapter.js.map +1 -0
  36. package/dist/SessionManager.d.ts +86 -0
  37. package/dist/SessionManager.js +155 -0
  38. package/dist/SessionManager.js.map +1 -0
  39. package/dist/SslConfig.d.ts +77 -0
  40. package/dist/SslConfig.js +100 -0
  41. package/dist/SslConfig.js.map +1 -0
  42. package/dist/SwaigFunction.d.ts +88 -0
  43. package/dist/SwaigFunction.js +125 -0
  44. package/dist/SwaigFunction.js.map +1 -0
  45. package/dist/SwaigFunctionResult.d.ts +442 -0
  46. package/dist/SwaigFunctionResult.js +735 -0
  47. package/dist/SwaigFunctionResult.js.map +1 -0
  48. package/dist/SwmlBuilder.d.ts +37 -0
  49. package/dist/SwmlBuilder.js +55 -0
  50. package/dist/SwmlBuilder.js.map +1 -0
  51. package/dist/cli/agent-loader.d.ts +22 -0
  52. package/dist/cli/agent-loader.js +106 -0
  53. package/dist/cli/agent-loader.js.map +1 -0
  54. package/dist/cli/mock-data.d.ts +37 -0
  55. package/dist/cli/mock-data.js +79 -0
  56. package/dist/cli/mock-data.js.map +1 -0
  57. package/dist/cli/swaig-test.d.ts +32 -0
  58. package/dist/cli/swaig-test.js +405 -0
  59. package/dist/cli/swaig-test.js.map +1 -0
  60. package/dist/index.d.ts +36 -0
  61. package/dist/index.js +44 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/prefabs/ConciergeAgent.d.ts +64 -0
  64. package/dist/prefabs/ConciergeAgent.js +188 -0
  65. package/dist/prefabs/ConciergeAgent.js.map +1 -0
  66. package/dist/prefabs/FAQBotAgent.d.ts +68 -0
  67. package/dist/prefabs/FAQBotAgent.js +206 -0
  68. package/dist/prefabs/FAQBotAgent.js.map +1 -0
  69. package/dist/prefabs/InfoGathererAgent.d.ts +73 -0
  70. package/dist/prefabs/InfoGathererAgent.js +202 -0
  71. package/dist/prefabs/InfoGathererAgent.js.map +1 -0
  72. package/dist/prefabs/ReceptionistAgent.d.ts +65 -0
  73. package/dist/prefabs/ReceptionistAgent.js +205 -0
  74. package/dist/prefabs/ReceptionistAgent.js.map +1 -0
  75. package/dist/prefabs/SurveyAgent.d.ts +84 -0
  76. package/dist/prefabs/SurveyAgent.js +324 -0
  77. package/dist/prefabs/SurveyAgent.js.map +1 -0
  78. package/dist/prefabs/index.d.ts +13 -0
  79. package/dist/prefabs/index.js +14 -0
  80. package/dist/prefabs/index.js.map +1 -0
  81. package/dist/skills/SkillBase.d.ts +134 -0
  82. package/dist/skills/SkillBase.js +105 -0
  83. package/dist/skills/SkillBase.js.map +1 -0
  84. package/dist/skills/SkillManager.d.ts +83 -0
  85. package/dist/skills/SkillManager.js +159 -0
  86. package/dist/skills/SkillManager.js.map +1 -0
  87. package/dist/skills/SkillRegistry.d.ts +105 -0
  88. package/dist/skills/SkillRegistry.js +195 -0
  89. package/dist/skills/SkillRegistry.js.map +1 -0
  90. package/dist/skills/builtin/api_ninjas_trivia.d.ts +35 -0
  91. package/dist/skills/builtin/api_ninjas_trivia.js +161 -0
  92. package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -0
  93. package/dist/skills/builtin/claude_skills.d.ts +34 -0
  94. package/dist/skills/builtin/claude_skills.js +156 -0
  95. package/dist/skills/builtin/claude_skills.js.map +1 -0
  96. package/dist/skills/builtin/custom_skills.d.ts +59 -0
  97. package/dist/skills/builtin/custom_skills.js +231 -0
  98. package/dist/skills/builtin/custom_skills.js.map +1 -0
  99. package/dist/skills/builtin/datasphere.d.ts +34 -0
  100. package/dist/skills/builtin/datasphere.js +163 -0
  101. package/dist/skills/builtin/datasphere.js.map +1 -0
  102. package/dist/skills/builtin/datasphere_serverless.d.ts +54 -0
  103. package/dist/skills/builtin/datasphere_serverless.js +155 -0
  104. package/dist/skills/builtin/datasphere_serverless.js.map +1 -0
  105. package/dist/skills/builtin/datetime.d.ts +31 -0
  106. package/dist/skills/builtin/datetime.js +95 -0
  107. package/dist/skills/builtin/datetime.js.map +1 -0
  108. package/dist/skills/builtin/google_maps.d.ts +33 -0
  109. package/dist/skills/builtin/google_maps.js +233 -0
  110. package/dist/skills/builtin/google_maps.js.map +1 -0
  111. package/dist/skills/builtin/index.d.ts +28 -0
  112. package/dist/skills/builtin/index.js +75 -0
  113. package/dist/skills/builtin/index.js.map +1 -0
  114. package/dist/skills/builtin/info_gatherer.d.ts +52 -0
  115. package/dist/skills/builtin/info_gatherer.js +237 -0
  116. package/dist/skills/builtin/info_gatherer.js.map +1 -0
  117. package/dist/skills/builtin/joke.d.ts +32 -0
  118. package/dist/skills/builtin/joke.js +142 -0
  119. package/dist/skills/builtin/joke.js.map +1 -0
  120. package/dist/skills/builtin/math.d.ts +33 -0
  121. package/dist/skills/builtin/math.js +120 -0
  122. package/dist/skills/builtin/math.js.map +1 -0
  123. package/dist/skills/builtin/mcp_gateway.d.ts +35 -0
  124. package/dist/skills/builtin/mcp_gateway.js +85 -0
  125. package/dist/skills/builtin/mcp_gateway.js.map +1 -0
  126. package/dist/skills/builtin/native_vector_search.d.ts +44 -0
  127. package/dist/skills/builtin/native_vector_search.js +248 -0
  128. package/dist/skills/builtin/native_vector_search.js.map +1 -0
  129. package/dist/skills/builtin/play_background_file.d.ts +34 -0
  130. package/dist/skills/builtin/play_background_file.js +135 -0
  131. package/dist/skills/builtin/play_background_file.js.map +1 -0
  132. package/dist/skills/builtin/spider.d.ts +34 -0
  133. package/dist/skills/builtin/spider.js +164 -0
  134. package/dist/skills/builtin/spider.js.map +1 -0
  135. package/dist/skills/builtin/swml_transfer.d.ts +44 -0
  136. package/dist/skills/builtin/swml_transfer.js +204 -0
  137. package/dist/skills/builtin/swml_transfer.js.map +1 -0
  138. package/dist/skills/builtin/weather_api.d.ts +34 -0
  139. package/dist/skills/builtin/weather_api.js +136 -0
  140. package/dist/skills/builtin/weather_api.js.map +1 -0
  141. package/dist/skills/builtin/web_search.d.ts +34 -0
  142. package/dist/skills/builtin/web_search.js +141 -0
  143. package/dist/skills/builtin/web_search.js.map +1 -0
  144. package/dist/skills/builtin/wikipedia_search.d.ts +34 -0
  145. package/dist/skills/builtin/wikipedia_search.js +166 -0
  146. package/dist/skills/builtin/wikipedia_search.js.map +1 -0
  147. package/dist/skills/index.d.ts +11 -0
  148. package/dist/skills/index.js +10 -0
  149. package/dist/skills/index.js.map +1 -0
  150. package/dist/types.d.ts +85 -0
  151. package/dist/types.js +5 -0
  152. package/dist/types.js.map +1 -0
  153. package/docs/agent-guide.md +869 -0
  154. package/docs/api-reference.md +2419 -0
  155. package/docs/architecture.md +843 -0
  156. package/docs/cli-guide.md +579 -0
  157. package/docs/configuration.md +422 -0
  158. package/docs/contexts-guide.md +787 -0
  159. package/docs/datamap-guide.md +1141 -0
  160. package/docs/prefabs-guide.md +830 -0
  161. package/docs/security.md +436 -0
  162. package/docs/serverless-guide.md +513 -0
  163. package/docs/skills-guide.md +845 -0
  164. package/docs/swaig-reference.md +1627 -0
  165. package/examples/call-flow.ts +60 -0
  166. package/examples/contexts-steps.ts +62 -0
  167. package/examples/datamap-tools.ts +52 -0
  168. package/examples/dynamic-config.ts +51 -0
  169. package/examples/multi-agent.ts +67 -0
  170. package/examples/pom-prompt.ts +68 -0
  171. package/examples/simple-agent.ts +33 -0
  172. package/package.json +35 -0
  173. package/src/AgentBase.ts +1279 -0
  174. package/src/AgentServer.ts +149 -0
  175. package/src/AuthHandler.ts +141 -0
  176. package/src/ConfigLoader.ts +165 -0
  177. package/src/ContextBuilder.ts +796 -0
  178. package/src/DataMap.ts +365 -0
  179. package/src/Logger.ts +197 -0
  180. package/src/PomBuilder.ts +298 -0
  181. package/src/PromptManager.ts +133 -0
  182. package/src/SchemaUtils.ts +170 -0
  183. package/src/ServerlessAdapter.ts +218 -0
  184. package/src/SessionManager.ts +161 -0
  185. package/src/SslConfig.ts +118 -0
  186. package/src/SwaigFunction.ts +168 -0
  187. package/src/SwaigFunctionResult.ts +864 -0
  188. package/src/SwmlBuilder.ts +62 -0
  189. package/src/cli/agent-loader.ts +122 -0
  190. package/src/cli/mock-data.ts +110 -0
  191. package/src/cli/swaig-test.ts +440 -0
  192. package/src/index.ts +99 -0
  193. package/src/prefabs/ConciergeAgent.ts +251 -0
  194. package/src/prefabs/FAQBotAgent.ts +263 -0
  195. package/src/prefabs/InfoGathererAgent.ts +276 -0
  196. package/src/prefabs/ReceptionistAgent.ts +277 -0
  197. package/src/prefabs/SurveyAgent.ts +413 -0
  198. package/src/prefabs/index.ts +23 -0
  199. package/src/skills/SkillBase.ts +184 -0
  200. package/src/skills/SkillManager.ts +177 -0
  201. package/src/skills/SkillRegistry.ts +231 -0
  202. package/src/skills/builtin/api_ninjas_trivia.ts +230 -0
  203. package/src/skills/builtin/claude_skills.ts +239 -0
  204. package/src/skills/builtin/custom_skills.ts +326 -0
  205. package/src/skills/builtin/datasphere.ts +225 -0
  206. package/src/skills/builtin/datasphere_serverless.ts +194 -0
  207. package/src/skills/builtin/datetime.ts +115 -0
  208. package/src/skills/builtin/google_maps.ts +347 -0
  209. package/src/skills/builtin/index.ts +79 -0
  210. package/src/skills/builtin/info_gatherer.ts +331 -0
  211. package/src/skills/builtin/joke.ts +180 -0
  212. package/src/skills/builtin/math.ts +150 -0
  213. package/src/skills/builtin/mcp_gateway.ts +99 -0
  214. package/src/skills/builtin/native_vector_search.ts +327 -0
  215. package/src/skills/builtin/play_background_file.ts +189 -0
  216. package/src/skills/builtin/spider.ts +232 -0
  217. package/src/skills/builtin/swml_transfer.ts +285 -0
  218. package/src/skills/builtin/weather_api.ts +193 -0
  219. package/src/skills/builtin/web_search.ts +212 -0
  220. package/src/skills/builtin/wikipedia_search.ts +248 -0
  221. package/src/skills/index.ts +12 -0
  222. package/src/types.ts +99 -0
  223. package/tests/AgentBase.test.ts +693 -0
  224. package/tests/AgentServer.test.ts +102 -0
  225. package/tests/AuthHandler.test.ts +121 -0
  226. package/tests/ConfigLoader.test.ts +121 -0
  227. package/tests/DataMap.test.ts +286 -0
  228. package/tests/Logger.test.ts +218 -0
  229. package/tests/PomBuilder.test.ts +164 -0
  230. package/tests/ProxyDetection.test.ts +185 -0
  231. package/tests/SchemaUtils.test.ts +106 -0
  232. package/tests/ServerlessAdapter.test.ts +200 -0
  233. package/tests/SessionManager.test.ts +139 -0
  234. package/tests/SslConfig.test.ts +97 -0
  235. package/tests/SwaigFunctionResult.test.ts +298 -0
  236. package/tests/cli/mock-data.test.ts +94 -0
  237. package/tests/cli/swaig-test.test.ts +96 -0
  238. package/tests/prefabs/prefabs.test.ts +854 -0
  239. package/tests/setup.ts +6 -0
  240. package/tests/skills/SkillBase.test.ts +118 -0
  241. package/tests/skills/SkillManager.test.ts +164 -0
  242. package/tests/skills/SkillRegistry.test.ts +124 -0
  243. package/tests/skills/builtin.test.ts +924 -0
  244. package/tsconfig.json +18 -0
  245. package/vitest.config.ts +9 -0
@@ -0,0 +1,2419 @@
1
+ # API Reference
2
+
3
+ Complete reference for every exported class, interface, type, and function in the SignalWire AI Agents TypeScript SDK.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ - [AgentBase](#agentbase)
10
+ - [Constructor](#agentbase-constructor)
11
+ - [Static Properties](#agentbase-static-properties)
12
+ - [Public Properties](#agentbase-public-properties)
13
+ - [Prompt Methods](#prompt-methods)
14
+ - [Tool Methods](#tool-methods)
15
+ - [Speech and Language Methods](#speech-and-language-methods)
16
+ - [AI Configuration Methods](#ai-configuration-methods)
17
+ - [Call Flow Methods](#call-flow-methods)
18
+ - [Context Methods](#context-methods)
19
+ - [Skill Methods](#skill-methods)
20
+ - [Dynamic Configuration Methods](#dynamic-configuration-methods)
21
+ - [URL and Proxy Methods](#url-and-proxy-methods)
22
+ - [Server Methods](#server-methods)
23
+ - [Utility Methods](#utility-methods)
24
+ - [Protected Hooks](#protected-hooks)
25
+ - [AgentServer](#agentserver)
26
+ - [SwaigFunctionResult](#swaigfunctionresult)
27
+ - [Constructor](#swaigfunctionresult-constructor)
28
+ - [Core Methods](#swaigfunctionresult-core-methods)
29
+ - [Call Control Actions](#call-control-actions)
30
+ - [Audio Actions](#audio-actions)
31
+ - [Speech Actions](#speech-actions)
32
+ - [Data Actions](#data-actions)
33
+ - [SWML Actions](#swml-actions)
34
+ - [Function Actions](#function-actions)
35
+ - [Communication Actions](#communication-actions)
36
+ - [Room and Conference Actions](#room-and-conference-actions)
37
+ - [RPC Actions](#rpc-actions)
38
+ - [Payment Actions](#payment-actions)
39
+ - [Static Helpers](#swaigfunctionresult-static-helpers)
40
+ - [Serialization](#swaigfunctionresult-serialization)
41
+ - [SwaigFunction](#swaigfunction)
42
+ - [DataMap](#datamap)
43
+ - [Constructor](#datamap-constructor)
44
+ - [Configuration Methods](#datamap-configuration-methods)
45
+ - [Webhook Methods](#datamap-webhook-methods)
46
+ - [Output Methods](#datamap-output-methods)
47
+ - [Registration and Serialization](#datamap-registration-and-serialization)
48
+ - [Factory Functions](#datamap-factory-functions)
49
+ - [ContextBuilder](#contextbuilder)
50
+ - [ContextBuilder Class](#contextbuilder-class)
51
+ - [Context Class](#context-class)
52
+ - [Step Class](#step-class)
53
+ - [GatherInfo Class](#gatherinfo-class)
54
+ - [GatherQuestion Class](#gatherquestion-class)
55
+ - [Helper Functions](#contextbuilder-helper-functions)
56
+ - [PomBuilder](#pombuilder)
57
+ - [PomSection Class](#pomsection-class)
58
+ - [PomBuilder Class](#pombuilder-class)
59
+ - [SwmlBuilder](#swmlbuilder)
60
+ - [PromptManager](#promptmanager)
61
+ - [SessionManager](#sessionmanager)
62
+ - [Skills](#skills)
63
+ - [SkillBase](#skillbase)
64
+ - [SkillManager](#skillmanager)
65
+ - [SkillRegistry](#skillregistry)
66
+ - [Prefab Agents](#prefab-agents)
67
+ - [InfoGathererAgent](#infogathereragent)
68
+ - [SurveyAgent](#surveyagent)
69
+ - [FAQBotAgent](#faqbotagent)
70
+ - [ConciergeAgent](#conciergeagent)
71
+ - [ReceptionistAgent](#receptionistagent)
72
+ - [Utility Classes](#utility-classes)
73
+ - [AuthHandler](#authhandler)
74
+ - [ConfigLoader](#configloader)
75
+ - [Logger](#logger)
76
+ - [SslConfig](#sslconfig)
77
+ - [SchemaUtils](#schemautils)
78
+ - [ServerlessAdapter](#serverlessadapter)
79
+ - [Types and Interfaces](#types-and-interfaces)
80
+ - [AgentOptions](#agentoptions)
81
+ - [LanguageConfig](#languageconfig)
82
+ - [PronunciationRule](#pronunciationrule)
83
+ - [FunctionInclude](#functioninclude)
84
+ - [DynamicConfigCallback](#dynamicconfigcallback)
85
+ - [SummaryCallback](#summarycallback)
86
+ - [SwaigHandler](#swaighandler)
87
+ - [SwaigFunctionOptions](#swaigfunctionoptions)
88
+ - [AuthConfig](#authconfig)
89
+ - [SslOptions](#ssloptions)
90
+ - [ValidationResult](#validationresult)
91
+ - [ServerlessEvent](#serverlessevent)
92
+ - [ServerlessResponse](#serverlessresponse)
93
+ - [PomSectionData](#pomsectiondata)
94
+
95
+ ---
96
+
97
+ ## AgentBase
98
+
99
+ ```ts
100
+ import { AgentBase } from '@anthropic/signalwire-agents';
101
+ ```
102
+
103
+ Core agent class that composes an HTTP server, prompt management, session handling, SWAIG tool registry, and 5-phase SWML rendering into a single deployable unit.
104
+
105
+ ### AgentBase Constructor
106
+
107
+ ```ts
108
+ constructor(opts: AgentOptions)
109
+ ```
110
+
111
+ Creates a new agent. See [AgentOptions](#agentoptions) for the full options table.
112
+
113
+ **Example:**
114
+ ```ts
115
+ const agent = new AgentBase({ name: 'MyAgent', route: '/agent' });
116
+ ```
117
+
118
+ ### AgentBase Static Properties
119
+
120
+ #### `PROMPT_SECTIONS`
121
+
122
+ ```ts
123
+ static PROMPT_SECTIONS?: { title: string; body?: string; bullets?: string[]; numbered?: boolean }[]
124
+ ```
125
+
126
+ Declarative prompt sections applied automatically by the constructor via `promptAddSection()`. Subclasses override this to define default prompt structure.
127
+
128
+ **Example:**
129
+ ```ts
130
+ class MyAgent extends AgentBase {
131
+ static override PROMPT_SECTIONS = [
132
+ { title: 'Role', body: 'You are a helpful assistant.' },
133
+ { title: 'Rules', bullets: ['Be concise.', 'Be polite.'] },
134
+ ];
135
+ }
136
+ ```
137
+
138
+ ### AgentBase Public Properties
139
+
140
+ | Property | Type | Description |
141
+ |----------|------|-------------|
142
+ | `name` | `string` | Display name of this agent |
143
+ | `route` | `string` | HTTP route path this agent listens on |
144
+ | `host` | `string` | Hostname the HTTP server binds to |
145
+ | `port` | `number` | Port number the HTTP server listens on |
146
+ | `agentId` | `string` | Unique identifier for this agent instance |
147
+
148
+ ### Prompt Methods
149
+
150
+ #### `setPromptText(text)`
151
+
152
+ ```ts
153
+ setPromptText(text: string): this
154
+ ```
155
+
156
+ Set the main system prompt text. Bypasses POM rendering when set.
157
+
158
+ #### `setPostPrompt(text)`
159
+
160
+ ```ts
161
+ setPostPrompt(text: string): this
162
+ ```
163
+
164
+ Set the post-prompt text evaluated after the call ends. Used for call summarization.
165
+
166
+ #### `promptAddSection(title, opts?)`
167
+
168
+ ```ts
169
+ promptAddSection(title: string, opts?: {
170
+ body?: string;
171
+ bullets?: string[];
172
+ numbered?: boolean;
173
+ numberedBullets?: boolean;
174
+ subsections?: { title: string; body?: string; bullets?: string[] }[];
175
+ }): this
176
+ ```
177
+
178
+ Add a new section to the POM prompt. Sections render as Markdown headings with body text, bullet points, and nested subsections.
179
+
180
+ #### `promptAddToSection(title, opts?)`
181
+
182
+ ```ts
183
+ promptAddToSection(title: string, opts?: {
184
+ body?: string;
185
+ bullet?: string;
186
+ bullets?: string[];
187
+ }): this
188
+ ```
189
+
190
+ Append content to an existing prompt section. Creates the section if it does not exist.
191
+
192
+ #### `promptAddSubsection(parentTitle, title, opts?)`
193
+
194
+ ```ts
195
+ promptAddSubsection(parentTitle: string, title: string, opts?: {
196
+ body?: string;
197
+ bullets?: string[];
198
+ }): this
199
+ ```
200
+
201
+ Add a subsection under an existing prompt section.
202
+
203
+ #### `promptHasSection(title)`
204
+
205
+ ```ts
206
+ promptHasSection(title: string): boolean
207
+ ```
208
+
209
+ Check whether a prompt section with the given title exists.
210
+
211
+ #### `getPrompt()`
212
+
213
+ ```ts
214
+ getPrompt(): string
215
+ ```
216
+
217
+ Get the fully rendered main prompt text.
218
+
219
+ #### `getPostPrompt()`
220
+
221
+ ```ts
222
+ getPostPrompt(): string | null
223
+ ```
224
+
225
+ Get the post-prompt text, or `null` if not configured.
226
+
227
+ ### Tool Methods
228
+
229
+ #### `defineTool(opts)`
230
+
231
+ ```ts
232
+ defineTool(opts: {
233
+ name: string;
234
+ description: string;
235
+ parameters?: Record<string, unknown>;
236
+ handler: SwaigHandler;
237
+ secure?: boolean;
238
+ fillers?: Record<string, string[]>;
239
+ waitFile?: string;
240
+ waitFileLoops?: number;
241
+ required?: string[];
242
+ }): this
243
+ ```
244
+
245
+ Register a SWAIG tool (function) the AI can invoke during a call.
246
+
247
+ | Parameter | Type | Default | Description |
248
+ |-----------|------|---------|-------------|
249
+ | `name` | `string` | -- | Unique tool name |
250
+ | `description` | `string` | -- | Description shown to the AI |
251
+ | `parameters` | `Record<string, unknown>` | `{}` | JSON Schema properties for the tool's parameters |
252
+ | `handler` | `SwaigHandler` | -- | Callback invoked when the tool is called |
253
+ | `secure` | `boolean` | `false` | Require session token authentication |
254
+ | `fillers` | `Record<string, string[]>` | -- | Language-keyed filler phrases spoken during execution |
255
+ | `waitFile` | `string` | -- | Audio file URL to play while waiting |
256
+ | `waitFileLoops` | `number` | -- | Number of times to loop the wait file |
257
+ | `required` | `string[]` | `[]` | List of required parameter names |
258
+
259
+ **Example:**
260
+ ```ts
261
+ agent.defineTool({
262
+ name: 'get_weather',
263
+ description: 'Get current weather for a city',
264
+ parameters: { city: { type: 'string', description: 'City name' } },
265
+ handler: async (args) => new SwaigFunctionResult(`Weather in ${args.city}: sunny`),
266
+ });
267
+ ```
268
+
269
+ #### `getRegisteredTools()`
270
+
271
+ ```ts
272
+ getRegisteredTools(): { name: string; description: string; parameters: Record<string, unknown> }[]
273
+ ```
274
+
275
+ Get a summary of all registered tools.
276
+
277
+ #### `getTool(name)`
278
+
279
+ ```ts
280
+ getTool(name: string): SwaigFunction | undefined
281
+ ```
282
+
283
+ Look up a registered SwaigFunction by name.
284
+
285
+ #### `registerSwaigFunction(fn)`
286
+
287
+ ```ts
288
+ registerSwaigFunction(fn: SwaigFunction | Record<string, unknown>): this
289
+ ```
290
+
291
+ Register a pre-built SwaigFunction instance or a raw function descriptor (e.g., from DataMap).
292
+
293
+ ### Speech and Language Methods
294
+
295
+ #### `addHint(hint)`
296
+
297
+ ```ts
298
+ addHint(hint: string): this
299
+ ```
300
+
301
+ Add a single speech-recognition hint word or phrase.
302
+
303
+ #### `addHints(hints)`
304
+
305
+ ```ts
306
+ addHints(hints: string[]): this
307
+ ```
308
+
309
+ Add multiple speech-recognition hints at once.
310
+
311
+ #### `addPatternHint(opts)`
312
+
313
+ ```ts
314
+ addPatternHint(opts: { pattern: string; replace: string; ignoreCase?: boolean }): this
315
+ ```
316
+
317
+ Add a pattern-based speech-recognition hint with find-and-replace behavior.
318
+
319
+ #### `addLanguage(config)`
320
+
321
+ ```ts
322
+ addLanguage(config: LanguageConfig): this
323
+ ```
324
+
325
+ Add a supported language to the AI configuration. See [LanguageConfig](#languageconfig).
326
+
327
+ #### `setLanguages(languages)`
328
+
329
+ ```ts
330
+ setLanguages(languages: LanguageConfig[]): this
331
+ ```
332
+
333
+ Replace all configured languages with a new list.
334
+
335
+ #### `addPronunciation(rule)`
336
+
337
+ ```ts
338
+ addPronunciation(rule: PronunciationRule): this
339
+ ```
340
+
341
+ Add a pronunciation override rule for the TTS engine. See [PronunciationRule](#pronunciationrule).
342
+
343
+ ### AI Configuration Methods
344
+
345
+ #### `setParam(key, value)`
346
+
347
+ ```ts
348
+ setParam(key: string, value: unknown): this
349
+ ```
350
+
351
+ Set a single AI parameter (e.g., `"temperature"`, `"top_p"`).
352
+
353
+ #### `setParams(params)`
354
+
355
+ ```ts
356
+ setParams(params: Record<string, unknown>): this
357
+ ```
358
+
359
+ Merge multiple AI parameters into the existing params object.
360
+
361
+ #### `setGlobalData(data)`
362
+
363
+ ```ts
364
+ setGlobalData(data: Record<string, unknown>): this
365
+ ```
366
+
367
+ Replace the entire `global_data` object passed into the AI configuration.
368
+
369
+ #### `updateGlobalData(data)`
370
+
371
+ ```ts
372
+ updateGlobalData(data: Record<string, unknown>): this
373
+ ```
374
+
375
+ Merge additional entries into the existing `global_data` object.
376
+
377
+ #### `setNativeFunctions(funcs)`
378
+
379
+ ```ts
380
+ setNativeFunctions(funcs: string[]): this
381
+ ```
382
+
383
+ Set the list of native SWAIG function names (built-in platform functions).
384
+
385
+ #### `addInternalFiller(functionName, languageCode, fillers)`
386
+
387
+ ```ts
388
+ addInternalFiller(functionName: string, languageCode: string, fillers: string[]): this
389
+ ```
390
+
391
+ Add filler phrases spoken while a specific function is executing.
392
+
393
+ #### `addFunctionInclude(url, functions, metaData?)`
394
+
395
+ ```ts
396
+ addFunctionInclude(url: string, functions: string[], metaData?: Record<string, unknown>): this
397
+ ```
398
+
399
+ Add a remote SWAIG function include reference.
400
+
401
+ #### `setPromptLlmParams(params)`
402
+
403
+ ```ts
404
+ setPromptLlmParams(params: Record<string, unknown>): this
405
+ ```
406
+
407
+ Merge LLM-specific parameters into the main prompt configuration (e.g., `model`, `temperature`).
408
+
409
+ #### `setPostPromptLlmParams(params)`
410
+
411
+ ```ts
412
+ setPostPromptLlmParams(params: Record<string, unknown>): this
413
+ ```
414
+
415
+ Merge LLM-specific parameters into the post-prompt configuration.
416
+
417
+ #### `enableDebugEvents(level?)`
418
+
419
+ ```ts
420
+ enableDebugEvents(level?: number): this
421
+ ```
422
+
423
+ Enable debug event webhooks. `level` defaults to `1`.
424
+
425
+ ### Call Flow Methods
426
+
427
+ The SWML document is rendered in 5 phases:
428
+
429
+ 1. **Pre-answer** verbs
430
+ 2. **Answer** verb
431
+ 3. **Post-answer** verbs (including optional `record_call`)
432
+ 4. **AI** verb
433
+ 5. **Post-AI** verbs
434
+
435
+ #### `addPreAnswerVerb(verbName, config)`
436
+
437
+ ```ts
438
+ addPreAnswerVerb(verbName: string, config: Record<string, unknown>): this
439
+ ```
440
+
441
+ Add a SWML verb to execute before the answer phase (phase 1).
442
+
443
+ #### `addAnswerVerb(config?)`
444
+
445
+ ```ts
446
+ addAnswerVerb(config?: Record<string, unknown>): this
447
+ ```
448
+
449
+ Configure the answer verb (phase 2).
450
+
451
+ #### `addPostAnswerVerb(verbName, config)`
452
+
453
+ ```ts
454
+ addPostAnswerVerb(verbName: string, config: Record<string, unknown>): this
455
+ ```
456
+
457
+ Add a verb after the answer but before the AI verb (phase 3).
458
+
459
+ #### `addPostAiVerb(verbName, config)`
460
+
461
+ ```ts
462
+ addPostAiVerb(verbName: string, config: Record<string, unknown>): this
463
+ ```
464
+
465
+ Add a verb after the AI verb (phase 5).
466
+
467
+ #### `clearPreAnswerVerbs()`
468
+
469
+ ```ts
470
+ clearPreAnswerVerbs(): this
471
+ ```
472
+
473
+ Remove all pre-answer verbs.
474
+
475
+ #### `clearPostAnswerVerbs()`
476
+
477
+ ```ts
478
+ clearPostAnswerVerbs(): this
479
+ ```
480
+
481
+ Remove all post-answer verbs.
482
+
483
+ #### `clearPostAiVerbs()`
484
+
485
+ ```ts
486
+ clearPostAiVerbs(): this
487
+ ```
488
+
489
+ Remove all post-AI verbs.
490
+
491
+ ### Context Methods
492
+
493
+ #### `defineContexts(contexts?)`
494
+
495
+ ```ts
496
+ defineContexts(contexts?: ContextBuilder | Record<string, unknown>): ContextBuilder
497
+ ```
498
+
499
+ Define or replace the contexts configuration for the AI verb. Returns the active ContextBuilder. See [ContextBuilder](#contextbuilder).
500
+
501
+ ### Skill Methods
502
+
503
+ #### `addSkill(skill)`
504
+
505
+ ```ts
506
+ async addSkill(skill: SkillBase): Promise<this>
507
+ ```
508
+
509
+ Add a skill to this agent, registering its tools, prompt sections, hints, and global data. See [SkillBase](#skillbase).
510
+
511
+ #### `removeSkill(instanceId)`
512
+
513
+ ```ts
514
+ async removeSkill(instanceId: string): Promise<boolean>
515
+ ```
516
+
517
+ Remove a previously added skill by its instance ID. Returns `true` if found and removed.
518
+
519
+ #### `listSkills()`
520
+
521
+ ```ts
522
+ listSkills(): { name: string; instanceId: string; initialized: boolean }[]
523
+ ```
524
+
525
+ List all registered skills.
526
+
527
+ #### `hasSkill(skillName)`
528
+
529
+ ```ts
530
+ hasSkill(skillName: string): boolean
531
+ ```
532
+
533
+ Check whether a skill with the given name is registered.
534
+
535
+ ### Dynamic Configuration Methods
536
+
537
+ #### `setDynamicConfigCallback(cb)`
538
+
539
+ ```ts
540
+ setDynamicConfigCallback(cb: DynamicConfigCallback): this
541
+ ```
542
+
543
+ Set a callback invoked on each SWML request to dynamically modify an ephemeral agent copy. The original agent is never mutated. See [DynamicConfigCallback](#dynamicconfigcallback).
544
+
545
+ #### `addSwaigQueryParams(params)`
546
+
547
+ ```ts
548
+ addSwaigQueryParams(params: Record<string, string>): this
549
+ ```
550
+
551
+ Add extra query parameters appended to all SWAIG webhook URLs.
552
+
553
+ ### URL and Proxy Methods
554
+
555
+ #### `manualSetProxyUrl(url)`
556
+
557
+ ```ts
558
+ manualSetProxyUrl(url: string): this
559
+ ```
560
+
561
+ Manually set the external-facing proxy base URL used for webhook URL generation. Overrides auto-detection but not the `SWML_PROXY_URL_BASE` environment variable.
562
+
563
+ #### `setWebHookUrl(url)`
564
+
565
+ ```ts
566
+ setWebHookUrl(url: string): this
567
+ ```
568
+
569
+ Override the default SWAIG webhook URL.
570
+
571
+ #### `setPostPromptUrl(url)`
572
+
573
+ ```ts
574
+ setPostPromptUrl(url: string): this
575
+ ```
576
+
577
+ Override the default post-prompt webhook URL.
578
+
579
+ #### `getFullUrl(includeAuth?)`
580
+
581
+ ```ts
582
+ getFullUrl(includeAuth?: boolean): string
583
+ ```
584
+
585
+ Get the full external URL of this agent. When `includeAuth` is `true`, basic-auth credentials are embedded in the URL.
586
+
587
+ ### Server Methods
588
+
589
+ #### `getApp()`
590
+
591
+ ```ts
592
+ getApp(): Hono
593
+ ```
594
+
595
+ Get or lazily create the Hono HTTP application with all routes, middleware, auth, and CORS. Routes created:
596
+
597
+ | Endpoint | Method | Description |
598
+ |----------|--------|-------------|
599
+ | `{route}` | GET/POST | Returns rendered SWML |
600
+ | `{route}/swaig` | GET/POST | SWAIG function dispatcher |
601
+ | `{route}/post_prompt` | GET/POST | Post-prompt handler |
602
+ | `{route}/debug_events` | POST | Debug event handler |
603
+ | `{route}/health` | GET | Health check (`{ status: 'ok' }`) |
604
+ | `{route}/ready` | GET | Readiness check (`{ status: 'ready' }`) |
605
+
606
+ #### `asRouter()`
607
+
608
+ ```ts
609
+ asRouter(): Hono
610
+ ```
611
+
612
+ Return this agent's Hono app for mounting as a sub-router in an AgentServer.
613
+
614
+ #### `serve()`
615
+
616
+ ```ts
617
+ async serve(): Promise<void>
618
+ ```
619
+
620
+ Start the HTTP server and begin listening for requests.
621
+
622
+ #### `run()`
623
+
624
+ ```ts
625
+ async run(): Promise<void>
626
+ ```
627
+
628
+ Alias for `serve()`.
629
+
630
+ #### `renderSwml(callId?)`
631
+
632
+ ```ts
633
+ renderSwml(callId?: string): string
634
+ ```
635
+
636
+ Render the complete SWML document as a JSON string. Assembles all 5 phases.
637
+
638
+ ### Utility Methods
639
+
640
+ #### `getName()`
641
+
642
+ ```ts
643
+ getName(): string
644
+ ```
645
+
646
+ Get the agent's display name.
647
+
648
+ #### `getBasicAuthCredentials(includeSource?)`
649
+
650
+ ```ts
651
+ getBasicAuthCredentials(): [string, string]
652
+ getBasicAuthCredentials(includeSource: true): [string, string, 'provided' | 'environment' | 'generated']
653
+ ```
654
+
655
+ Get the basic-auth credentials. When `includeSource` is `true`, appends the source as a third element.
656
+
657
+ ### Protected Hooks
658
+
659
+ Override these in subclasses to customize agent behavior.
660
+
661
+ #### `defineTools()`
662
+
663
+ ```ts
664
+ protected defineTools(): void
665
+ ```
666
+
667
+ Lifecycle method for subclasses to register tools. Called explicitly by subclass constructors (not automatic). Default is a no-op.
668
+
669
+ #### `onSummary(summary, rawData)`
670
+
671
+ ```ts
672
+ onSummary(summary: Record<string, unknown> | null, rawData: Record<string, unknown>): void | Promise<void>
673
+ ```
674
+
675
+ Called when a post-prompt summary is received at the end of a call.
676
+
677
+ #### `onSwmlRequest(rawData)`
678
+
679
+ ```ts
680
+ onSwmlRequest(rawData: Record<string, unknown>): void | Promise<void>
681
+ ```
682
+
683
+ Called on every SWML request before rendering.
684
+
685
+ #### `onDebugEvent(event)`
686
+
687
+ ```ts
688
+ onDebugEvent(event: Record<string, unknown>): void | Promise<void>
689
+ ```
690
+
691
+ Called when a debug event webhook is received.
692
+
693
+ #### `validateBasicAuth(username, password)`
694
+
695
+ ```ts
696
+ validateBasicAuth(username: string, password: string): boolean | Promise<boolean>
697
+ ```
698
+
699
+ Override to add custom basic-auth validation logic. Return `true` to allow, `false` to reject. Default returns `true`.
700
+
701
+ #### `onFunctionCall(name, args, rawData)`
702
+
703
+ ```ts
704
+ onFunctionCall(name: string, args: Record<string, unknown>, rawData: Record<string, unknown>): void | Promise<void>
705
+ ```
706
+
707
+ Pre-execution hook called before each SWAIG function.
708
+
709
+ ---
710
+
711
+ ## AgentServer
712
+
713
+ ```ts
714
+ import { AgentServer } from '@anthropic/signalwire-agents';
715
+ ```
716
+
717
+ Multi-agent HTTP server that hosts multiple AgentBase instances on distinct route prefixes.
718
+
719
+ ### Constructor
720
+
721
+ ```ts
722
+ constructor(opts?: { host?: string; port?: number })
723
+ ```
724
+
725
+ | Parameter | Type | Default | Description |
726
+ |-----------|------|---------|-------------|
727
+ | `host` | `string` | `'0.0.0.0'` | Hostname to bind to |
728
+ | `port` | `number` | `PORT` env or `3000` | Port to listen on |
729
+
730
+ ### Methods
731
+
732
+ #### `register(agent, route?)`
733
+
734
+ ```ts
735
+ register(agent: AgentBase, route?: string): void
736
+ ```
737
+
738
+ Register an agent at the given route prefix. Defaults to the agent's own route. Throws if the route is already occupied.
739
+
740
+ #### `unregister(route)`
741
+
742
+ ```ts
743
+ unregister(route: string): void
744
+ ```
745
+
746
+ Remove an agent registration by route.
747
+
748
+ #### `getAgents()`
749
+
750
+ ```ts
751
+ getAgents(): Map<string, AgentBase>
752
+ ```
753
+
754
+ Get all registered agents keyed by route prefix.
755
+
756
+ #### `getAgent(route)`
757
+
758
+ ```ts
759
+ getAgent(route: string): AgentBase | undefined
760
+ ```
761
+
762
+ Look up a registered agent by route prefix.
763
+
764
+ #### `getApp()`
765
+
766
+ ```ts
767
+ getApp(): Hono
768
+ ```
769
+
770
+ Build and return the Hono application with all registered agents and a root listing endpoint (unless an agent is mounted at `/`).
771
+
772
+ #### `run(host?, port?)`
773
+
774
+ ```ts
775
+ async run(host?: string, port?: number): Promise<void>
776
+ ```
777
+
778
+ Start the HTTP server. Optional host/port overrides the constructor values.
779
+
780
+ **Example:**
781
+ ```ts
782
+ const server = new AgentServer({ port: 8080 });
783
+ server.register(agent1, '/sales');
784
+ server.register(agent2, '/support');
785
+ await server.run();
786
+ ```
787
+
788
+ ---
789
+
790
+ ## SwaigFunctionResult
791
+
792
+ ```ts
793
+ import { SwaigFunctionResult } from '@anthropic/signalwire-agents';
794
+ ```
795
+
796
+ Builder for SWAIG function responses. Carries response text and an ordered list of structured actions. Every mutating method returns `this` for fluent chaining.
797
+
798
+ ### SwaigFunctionResult Constructor
799
+
800
+ ```ts
801
+ constructor(response?: string, postProcess?: boolean)
802
+ ```
803
+
804
+ | Parameter | Type | Default | Description |
805
+ |-----------|------|---------|-------------|
806
+ | `response` | `string` | `''` | Initial response text |
807
+ | `postProcess` | `boolean` | `false` | Whether actions are post-processed after the AI responds |
808
+
809
+ ### Public Properties
810
+
811
+ | Property | Type | Description |
812
+ |----------|------|-------------|
813
+ | `response` | `string` | The text response returned to the AI |
814
+ | `action` | `Record<string, unknown>[]` | Ordered list of actions |
815
+ | `postProcess` | `boolean` | Whether post-processing is enabled |
816
+
817
+ ### SwaigFunctionResult Core Methods
818
+
819
+ | Method | Signature | Description |
820
+ |--------|-----------|-------------|
821
+ | `setResponse` | `(response: string): this` | Set the response text |
822
+ | `setPostProcess` | `(postProcess: boolean): this` | Enable/disable post-processing |
823
+ | `addAction` | `(name: string, data: unknown): this` | Append a named action |
824
+ | `addActions` | `(actions: Record<string, unknown>[]): this` | Append multiple actions |
825
+
826
+ ### Call Control Actions
827
+
828
+ | Method | Signature | Description |
829
+ |--------|-----------|-------------|
830
+ | `connect` | `(destination: string, final?: boolean, fromAddr?: string): this` | Connect to another destination via SWML transfer |
831
+ | `swmlTransfer` | `(dest: string, aiResponse: string, final?: boolean): this` | Transfer with a custom AI response |
832
+ | `hangup` | `(): this` | Hang up the call |
833
+ | `hold` | `(timeout?: number): this` | Place on hold (0-900 seconds, default 300) |
834
+ | `waitForUser` | `(opts?: { enabled?: boolean; timeout?: number; answerFirst?: boolean }): this` | Wait for user input |
835
+ | `stop` | `(): this` | Stop the AI session |
836
+
837
+ ### Audio Actions
838
+
839
+ | Method | Signature | Description |
840
+ |--------|-----------|-------------|
841
+ | `say` | `(text: string): this` | Speak text via TTS |
842
+ | `playBackgroundFile` | `(filename: string, wait?: boolean): this` | Play background audio |
843
+ | `stopBackgroundFile` | `(): this` | Stop background audio |
844
+
845
+ ### Speech Actions
846
+
847
+ | Method | Signature | Description |
848
+ |--------|-----------|-------------|
849
+ | `addDynamicHints` | `(hints: (string \| { pattern: string; replace: string; ignore_case?: boolean })[]): this` | Add dynamic speech hints |
850
+ | `clearDynamicHints` | `(): this` | Remove all dynamic hints |
851
+ | `setEndOfSpeechTimeout` | `(milliseconds: number): this` | Set silence duration marking end of speech |
852
+ | `setSpeechEventTimeout` | `(milliseconds: number): this` | Set speech event detection timeout |
853
+
854
+ ### Data Actions
855
+
856
+ | Method | Signature | Description |
857
+ |--------|-----------|-------------|
858
+ | `updateGlobalData` | `(data: Record<string, unknown>): this` | Merge into global data store |
859
+ | `removeGlobalData` | `(keys: string \| string[]): this` | Remove keys from global data |
860
+ | `setMetadata` | `(data: Record<string, unknown>): this` | Set call metadata |
861
+ | `removeMetadata` | `(keys: string \| string[]): this` | Remove call metadata keys |
862
+
863
+ ### SWML Actions
864
+
865
+ | Method | Signature | Description |
866
+ |--------|-----------|-------------|
867
+ | `executeSwml` | `(swmlContent: string \| Record<string, unknown>, transfer?: boolean): this` | Execute arbitrary SWML |
868
+ | `swmlChangeStep` | `(stepName: string): this` | Change the current SWML step |
869
+ | `swmlChangeContext` | `(contextName: string): this` | Change the current SWML context |
870
+ | `swmlUserEvent` | `(eventData: Record<string, unknown>): this` | Emit a custom user event |
871
+ | `switchContext` | `(opts?: { systemPrompt?: string; userPrompt?: string; consolidate?: boolean; fullReset?: boolean }): this` | Switch AI context with optional new prompts |
872
+
873
+ ### Function Actions
874
+
875
+ | Method | Signature | Description |
876
+ |--------|-----------|-------------|
877
+ | `toggleFunctions` | `(toggles: { function: string; active: boolean }[]): this` | Enable/disable functions by name |
878
+ | `enableFunctionsOnTimeout` | `(enabled?: boolean): this` | Control function fire on speaker timeout |
879
+ | `updateSettings` | `(settings: Record<string, unknown>): this` | Update AI engine settings at runtime |
880
+
881
+ ### Communication Actions
882
+
883
+ | Method | Signature | Description |
884
+ |--------|-----------|-------------|
885
+ | `simulateUserInput` | `(text: string): this` | Inject text as if the user had spoken it |
886
+ | `enableExtensiveData` | `(enabled?: boolean): this` | Enable extensive data reporting |
887
+ | `replaceInHistory` | `(text: string \| boolean): this` | Replace function output in conversation history |
888
+ | `sendSms` | `(opts: { toNumber, fromNumber, body?, media?, tags?, region? }): this` | Send an SMS/MMS message |
889
+ | `recordCall` | `(opts?): this` | Start recording the call |
890
+ | `stopRecordCall` | `(controlId?: string): this` | Stop an active call recording |
891
+ | `tap` | `(opts: { uri, controlId?, direction?, codec?, rtpPtime?, statusUrl? }): this` | Start a media tap |
892
+ | `stopTap` | `(controlId?: string): this` | Stop a media tap |
893
+
894
+ ### Room and Conference Actions
895
+
896
+ | Method | Signature | Description |
897
+ |--------|-----------|-------------|
898
+ | `joinRoom` | `(name: string): this` | Join a SignalWire room |
899
+ | `sipRefer` | `(toUri: string): this` | Send a SIP REFER |
900
+ | `joinConference` | `(name: string, opts?): this` | Join a conference with optional settings |
901
+
902
+ ### RPC Actions
903
+
904
+ | Method | Signature | Description |
905
+ |--------|-----------|-------------|
906
+ | `executeRpc` | `(opts: { method, params?, callId?, nodeId? }): this` | Execute a SignalWire RPC method |
907
+ | `rpcDial` | `(toNumber, fromNumber, destSwml, deviceType?): this` | Dial a number via RPC |
908
+ | `rpcAiMessage` | `(callId, messageText, role?): this` | Send an AI message to another call |
909
+ | `rpcAiUnhold` | `(callId: string): this` | Unhold a call via RPC |
910
+
911
+ ### Payment Actions
912
+
913
+ #### `pay(opts)`
914
+
915
+ ```ts
916
+ pay(opts: {
917
+ paymentConnectorUrl: string;
918
+ inputMethod?: string; // default 'dtmf'
919
+ statusUrl?: string;
920
+ paymentMethod?: string; // default 'credit-card'
921
+ timeout?: number; // default 5
922
+ maxAttempts?: number; // default 1
923
+ securityCode?: boolean; // default true
924
+ postalCode?: boolean | string; // default true
925
+ minPostalCodeLength?: number; // default 0
926
+ tokenType?: string; // default 'reusable'
927
+ chargeAmount?: string;
928
+ currency?: string; // default 'usd'
929
+ language?: string; // default 'en-US'
930
+ voice?: string; // default 'woman'
931
+ description?: string;
932
+ validCardTypes?: string; // default 'visa mastercard amex'
933
+ parameters?: PaymentParameter[];
934
+ prompts?: PaymentPrompt[];
935
+ aiResponse?: string;
936
+ }): this
937
+ ```
938
+
939
+ Initiate a payment collection flow.
940
+
941
+ ### SwaigFunctionResult Static Helpers
942
+
943
+ | Method | Signature | Returns |
944
+ |--------|-----------|---------|
945
+ | `createPaymentPrompt` | `(forSituation, actions, cardType?, errorType?)` | `PaymentPrompt` |
946
+ | `createPaymentAction` | `(actionType, phrase)` | `PaymentAction` |
947
+ | `createPaymentParameter` | `(name, value)` | `PaymentParameter` |
948
+
949
+ ### SwaigFunctionResult Serialization
950
+
951
+ #### `toDict()`
952
+
953
+ ```ts
954
+ toDict(): Record<string, unknown>
955
+ ```
956
+
957
+ Serialize to a plain object for the SWAIG response. Returns `{ response, action, post_process }`. Falls back to `{ response: "Action completed." }` when empty.
958
+
959
+ ---
960
+
961
+ ## SwaigFunction
962
+
963
+ ```ts
964
+ import { SwaigFunction } from '@anthropic/signalwire-agents';
965
+ ```
966
+
967
+ Wraps a tool handler function with metadata for SWAIG registration.
968
+
969
+ ### Constructor
970
+
971
+ ```ts
972
+ constructor(opts: SwaigFunctionOptions)
973
+ ```
974
+
975
+ See [SwaigFunctionOptions](#swaigfunctionoptions) for the options table.
976
+
977
+ ### Public Properties
978
+
979
+ | Property | Type | Description |
980
+ |----------|------|-------------|
981
+ | `name` | `string` | Unique tool name |
982
+ | `handler` | `SwaigHandler` | Handler function |
983
+ | `description` | `string` | Description shown to the AI |
984
+ | `parameters` | `Record<string, unknown>` | JSON Schema properties |
985
+ | `secure` | `boolean` | Whether session token auth is required |
986
+ | `fillers` | `Record<string, string[]>` | Language-keyed filler phrases |
987
+ | `waitFile` | `string \| undefined` | Audio file URL played while waiting |
988
+ | `waitFileLoops` | `number \| undefined` | Wait file loop count |
989
+ | `webhookUrl` | `string \| undefined` | External webhook URL |
990
+ | `required` | `string[]` | Required parameter names |
991
+ | `extraFields` | `Record<string, unknown>` | Additional SWAIG definition fields |
992
+ | `isExternal` | `boolean` | Whether this is externally hosted |
993
+
994
+ ### Methods
995
+
996
+ #### `execute(args, rawData?)`
997
+
998
+ ```ts
999
+ async execute(args: Record<string, unknown>, rawData?: Record<string, unknown>): Promise<Record<string, unknown>>
1000
+ ```
1001
+
1002
+ Invoke the handler and return a serialized result dictionary. On error, returns a user-friendly error message.
1003
+
1004
+ #### `toSwaig(baseUrl, token?, callId?)`
1005
+
1006
+ ```ts
1007
+ toSwaig(baseUrl: string, token?: string, callId?: string): Record<string, unknown>
1008
+ ```
1009
+
1010
+ Serialize to the SWAIG wire format for inclusion in SWML. Returns an object with `function`, `description`, `parameters`, `web_hook_url`, and optional fields.
1011
+
1012
+ ---
1013
+
1014
+ ## DataMap
1015
+
1016
+ ```ts
1017
+ import { DataMap, createSimpleApiTool, createExpressionTool } from '@anthropic/signalwire-agents';
1018
+ ```
1019
+
1020
+ Fluent builder for SWAIG `data_map` configurations. Creates server-side tool definitions that execute on SignalWire without requiring webhook endpoints.
1021
+
1022
+ ### DataMap Constructor
1023
+
1024
+ ```ts
1025
+ constructor(functionName: string)
1026
+ ```
1027
+
1028
+ | Parameter | Type | Description |
1029
+ |-----------|------|-------------|
1030
+ | `functionName` | `string` | Unique name for this data map tool |
1031
+
1032
+ ### DataMap Configuration Methods
1033
+
1034
+ #### `enableEnvExpansion(enabled?)`
1035
+
1036
+ ```ts
1037
+ enableEnvExpansion(enabled?: boolean): this
1038
+ ```
1039
+
1040
+ Enable `${ENV.*}` variable expansion in URLs, bodies, and outputs. Default `true`.
1041
+
1042
+ #### `purpose(description)` / `description(description)`
1043
+
1044
+ ```ts
1045
+ purpose(description: string): this
1046
+ description(description: string): this // alias
1047
+ ```
1048
+
1049
+ Set the tool description shown to the AI.
1050
+
1051
+ #### `parameter(name, paramType, description, opts?)`
1052
+
1053
+ ```ts
1054
+ parameter(name: string, paramType: string, description: string, opts?: {
1055
+ required?: boolean;
1056
+ enum?: string[];
1057
+ }): this
1058
+ ```
1059
+
1060
+ Define a parameter for this data map tool.
1061
+
1062
+ #### `expression(testValue, pattern, output, nomatchOutput?)`
1063
+
1064
+ ```ts
1065
+ expression(
1066
+ testValue: string,
1067
+ pattern: string | RegExp,
1068
+ output: SwaigFunctionResult,
1069
+ nomatchOutput?: SwaigFunctionResult,
1070
+ ): this
1071
+ ```
1072
+
1073
+ Add a pattern-matching expression that evaluates a test value against a regex.
1074
+
1075
+ ### DataMap Webhook Methods
1076
+
1077
+ #### `webhook(method, url, opts?)`
1078
+
1079
+ ```ts
1080
+ webhook(method: string, url: string, opts?: {
1081
+ headers?: Record<string, string>;
1082
+ formParam?: string;
1083
+ inputArgsAsParams?: boolean;
1084
+ requireArgs?: string[];
1085
+ }): this
1086
+ ```
1087
+
1088
+ Add a webhook called when this data map tool is invoked.
1089
+
1090
+ #### `webhookExpressions(expressions)`
1091
+
1092
+ ```ts
1093
+ webhookExpressions(expressions: Record<string, unknown>[]): this
1094
+ ```
1095
+
1096
+ Set expressions on the most recently added webhook.
1097
+
1098
+ #### `body(data)`
1099
+
1100
+ ```ts
1101
+ body(data: Record<string, unknown>): this
1102
+ ```
1103
+
1104
+ Set the JSON body for the most recently added webhook.
1105
+
1106
+ #### `params(data)`
1107
+
1108
+ ```ts
1109
+ params(data: Record<string, unknown>): this
1110
+ ```
1111
+
1112
+ Set query/form parameters for the most recently added webhook.
1113
+
1114
+ #### `foreach(config)`
1115
+
1116
+ ```ts
1117
+ foreach(config: { input_key: string; output_key: string; append: string; max?: number }): this
1118
+ ```
1119
+
1120
+ Configure iteration over an array in the webhook response.
1121
+
1122
+ ### DataMap Output Methods
1123
+
1124
+ #### `output(result)`
1125
+
1126
+ ```ts
1127
+ output(result: SwaigFunctionResult): this
1128
+ ```
1129
+
1130
+ Set the output template for the most recently added webhook.
1131
+
1132
+ #### `fallbackOutput(result)`
1133
+
1134
+ ```ts
1135
+ fallbackOutput(result: SwaigFunctionResult): this
1136
+ ```
1137
+
1138
+ Set a fallback output used when no webhook or expression matches.
1139
+
1140
+ #### `errorKeys(keys)`
1141
+
1142
+ ```ts
1143
+ errorKeys(keys: string[]): this
1144
+ ```
1145
+
1146
+ Set error keys on the most recently added webhook (or globally if no webhook exists).
1147
+
1148
+ #### `globalErrorKeys(keys)`
1149
+
1150
+ ```ts
1151
+ globalErrorKeys(keys: string[]): this
1152
+ ```
1153
+
1154
+ Set error keys at the top-level data map scope.
1155
+
1156
+ ### DataMap Registration and Serialization
1157
+
1158
+ #### `registerWithAgent(agent)`
1159
+
1160
+ ```ts
1161
+ registerWithAgent(agent: { registerSwaigFunction(fn: Record<string, unknown>): unknown }): this
1162
+ ```
1163
+
1164
+ Register this DataMap tool with an AgentBase instance.
1165
+
1166
+ #### `toSwaigFunction()`
1167
+
1168
+ ```ts
1169
+ toSwaigFunction(): Record<string, unknown>
1170
+ ```
1171
+
1172
+ Serialize to a SWAIG function definition object suitable for SWML.
1173
+
1174
+ ### DataMap Factory Functions
1175
+
1176
+ #### `createSimpleApiTool(opts)`
1177
+
1178
+ ```ts
1179
+ function createSimpleApiTool(opts: {
1180
+ name: string;
1181
+ url: string;
1182
+ responseTemplate: string;
1183
+ parameters?: Record<string, { type?: string; description?: string; required?: boolean }>;
1184
+ method?: string; // default 'GET'
1185
+ headers?: Record<string, string>;
1186
+ body?: Record<string, unknown>;
1187
+ errorKeys?: string[];
1188
+ }): DataMap
1189
+ ```
1190
+
1191
+ Create a DataMap tool that calls a single API endpoint and formats the response.
1192
+
1193
+ #### `createExpressionTool(opts)`
1194
+
1195
+ ```ts
1196
+ function createExpressionTool(opts: {
1197
+ name: string;
1198
+ patterns: Record<string, [string, SwaigFunctionResult]>;
1199
+ parameters?: Record<string, { type?: string; description?: string; required?: boolean }>;
1200
+ }): DataMap
1201
+ ```
1202
+
1203
+ Create a DataMap tool that evaluates expressions against patterns without making HTTP calls.
1204
+
1205
+ ---
1206
+
1207
+ ## ContextBuilder
1208
+
1209
+ ```ts
1210
+ import { ContextBuilder, Context, Step, GatherInfo, GatherQuestion, createSimpleContext } from '@anthropic/signalwire-agents';
1211
+ ```
1212
+
1213
+ Contexts and Steps workflow system. Contexts contain ordered Steps, each with prompt content, completion criteria, function restrictions, and navigation rules.
1214
+
1215
+ ### ContextBuilder Class
1216
+
1217
+ Builds and validates a collection of named contexts for multi-step AI workflows.
1218
+
1219
+ #### `addContext(name)`
1220
+
1221
+ ```ts
1222
+ addContext(name: string): Context
1223
+ ```
1224
+
1225
+ Add a new named context. Returns the created Context for further configuration. Throws if the name already exists.
1226
+
1227
+ #### `getContext(name)`
1228
+
1229
+ ```ts
1230
+ getContext(name: string): Context | undefined
1231
+ ```
1232
+
1233
+ Retrieve a context by name.
1234
+
1235
+ #### `validate()`
1236
+
1237
+ ```ts
1238
+ validate(): void
1239
+ ```
1240
+
1241
+ Validate all contexts: at least one must exist, single contexts must be named `'default'`, all contexts must have steps, and cross-context references must be valid. Throws on failure.
1242
+
1243
+ #### `toDict()`
1244
+
1245
+ ```ts
1246
+ toDict(): Record<string, unknown>
1247
+ ```
1248
+
1249
+ Validate and serialize all contexts to a plain object for SWML output.
1250
+
1251
+ ### Context Class
1252
+
1253
+ A named context containing ordered steps, prompt configuration, and navigation rules.
1254
+
1255
+ #### Constructor
1256
+
1257
+ ```ts
1258
+ constructor(name: string)
1259
+ ```
1260
+
1261
+ #### Step Management
1262
+
1263
+ | Method | Signature | Returns | Description |
1264
+ |--------|-----------|---------|-------------|
1265
+ | `addStep` | `(name, opts?)` | `Step` | Add a new step with optional shorthand config |
1266
+ | `getStep` | `(name: string)` | `Step \| undefined` | Retrieve a step by name |
1267
+ | `removeStep` | `(name: string)` | `this` | Remove a step by name |
1268
+ | `moveStep` | `(name: string, position: number)` | `this` | Move a step to a new position |
1269
+
1270
+ The `addStep` options shorthand:
1271
+
1272
+ | Option | Type | Description |
1273
+ |--------|------|-------------|
1274
+ | `task` | `string` | Shorthand for `addSection('Task', task)` |
1275
+ | `bullets` | `string[]` | Shorthand for `addBullets('Process', bullets)` |
1276
+ | `criteria` | `string` | Shorthand for `setStepCriteria(criteria)` |
1277
+ | `functions` | `string \| string[]` | Shorthand for `setFunctions(functions)` |
1278
+ | `validSteps` | `string[]` | Shorthand for `setValidSteps(validSteps)` |
1279
+
1280
+ #### Navigation and Configuration
1281
+
1282
+ | Method | Signature | Description |
1283
+ |--------|-----------|-------------|
1284
+ | `setValidContexts` | `(contexts: string[]): this` | Set allowed context navigation targets |
1285
+ | `setValidSteps` | `(steps: string[]): this` | Set allowed step navigation targets |
1286
+ | `setPostPrompt` | `(postPrompt: string): this` | Set context post-prompt text |
1287
+ | `setSystemPrompt` | `(systemPrompt: string): this` | Set raw system prompt (mutually exclusive with POM sections) |
1288
+ | `setConsolidate` | `(consolidate: boolean): this` | Consolidate conversation history on entry |
1289
+ | `setFullReset` | `(fullReset: boolean): this` | Fully reset conversation history on entry |
1290
+ | `setUserPrompt` | `(userPrompt: string): this` | Set user prompt text |
1291
+ | `setIsolated` | `(isolated: boolean): this` | Isolate from other contexts' history |
1292
+ | `setPrompt` | `(prompt: string): this` | Set raw prompt text (mutually exclusive with POM sections) |
1293
+
1294
+ #### POM Sections
1295
+
1296
+ | Method | Signature | Description |
1297
+ |--------|-----------|-------------|
1298
+ | `addSystemSection` | `(title: string, body: string): this` | Add POM section to system prompt |
1299
+ | `addSystemBullets` | `(title: string, bullets: string[]): this` | Add POM bullet section to system prompt |
1300
+ | `addSection` | `(title: string, body: string): this` | Add POM section to context prompt |
1301
+ | `addBullets` | `(title: string, bullets: string[]): this` | Add POM bullet section to context prompt |
1302
+
1303
+ #### Fillers
1304
+
1305
+ | Method | Signature | Description |
1306
+ |--------|-----------|-------------|
1307
+ | `setEnterFillers` | `(fillers: Record<string, string[]>): this` | Set all enter fillers by language |
1308
+ | `setExitFillers` | `(fillers: Record<string, string[]>): this` | Set all exit fillers by language |
1309
+ | `addEnterFiller` | `(languageCode: string, fillers: string[]): this` | Add enter fillers for one language |
1310
+ | `addExitFiller` | `(languageCode: string, fillers: string[]): this` | Add exit fillers for one language |
1311
+
1312
+ #### `toDict()`
1313
+
1314
+ ```ts
1315
+ toDict(): Record<string, unknown>
1316
+ ```
1317
+
1318
+ Serialize this context and all its steps to SWML output. Throws if no steps are defined.
1319
+
1320
+ ### Step Class
1321
+
1322
+ A single step within a context.
1323
+
1324
+ #### Constructor
1325
+
1326
+ ```ts
1327
+ constructor(name: string)
1328
+ ```
1329
+
1330
+ #### Content Methods
1331
+
1332
+ | Method | Signature | Description |
1333
+ |--------|-----------|-------------|
1334
+ | `setText` | `(text: string): this` | Set raw text (mutually exclusive with POM sections) |
1335
+ | `addSection` | `(title: string, body: string): this` | Add a POM section with body |
1336
+ | `addBullets` | `(title: string, bullets: string[]): this` | Add a POM section with bullets |
1337
+ | `clearSections` | `(): this` | Remove all sections and raw text |
1338
+
1339
+ #### Configuration Methods
1340
+
1341
+ | Method | Signature | Description |
1342
+ |--------|-----------|-------------|
1343
+ | `setStepCriteria` | `(criteria: string): this` | Set completion criteria |
1344
+ | `setFunctions` | `(functions: string \| string[]): this` | Restrict available functions |
1345
+ | `setValidSteps` | `(steps: string[]): this` | Set allowed step navigation |
1346
+ | `setValidContexts` | `(contexts: string[]): this` | Set allowed context navigation |
1347
+ | `setEnd` | `(end: boolean): this` | Mark as terminal step |
1348
+ | `setSkipUserTurn` | `(skip: boolean): this` | Skip waiting for user input |
1349
+ | `setSkipToNextStep` | `(skip: boolean): this` | Auto-advance to next step |
1350
+
1351
+ #### Gather Info Methods
1352
+
1353
+ | Method | Signature | Description |
1354
+ |--------|-----------|-------------|
1355
+ | `setGatherInfo` | `(opts?: { outputKey?; completionAction?; prompt? }): this` | Initialize a gather info operation |
1356
+ | `addGatherQuestion` | `(opts: { key; question; type?; confirm?; prompt?; functions? }): this` | Add a question to the gather |
1357
+
1358
+ #### Reset Methods
1359
+
1360
+ | Method | Signature | Description |
1361
+ |--------|-----------|-------------|
1362
+ | `setResetSystemPrompt` | `(systemPrompt: string): this` | System prompt for context reset |
1363
+ | `setResetUserPrompt` | `(userPrompt: string): this` | User prompt for context reset |
1364
+ | `setResetConsolidate` | `(consolidate: boolean): this` | Consolidate on reset |
1365
+ | `setResetFullReset` | `(fullReset: boolean): this` | Full reset on step entry |
1366
+
1367
+ #### `toDict()`
1368
+
1369
+ ```ts
1370
+ toDict(): Record<string, unknown>
1371
+ ```
1372
+
1373
+ Serialize this step to SWML output.
1374
+
1375
+ ### GatherInfo Class
1376
+
1377
+ Collects structured information through a series of questions.
1378
+
1379
+ #### Constructor
1380
+
1381
+ ```ts
1382
+ constructor(opts?: { outputKey?: string; completionAction?: string; prompt?: string })
1383
+ ```
1384
+
1385
+ #### Methods
1386
+
1387
+ | Method | Signature | Description |
1388
+ |--------|-----------|-------------|
1389
+ | `addQuestion` | `(opts: { key; question; type?; confirm?; prompt?; functions? }): this` | Add a question |
1390
+ | `getQuestions` | `(): GatherQuestion[]` | Return all questions |
1391
+ | `toDict` | `(): Record<string, unknown>` | Serialize to SWML output |
1392
+
1393
+ ### GatherQuestion Class
1394
+
1395
+ A single question within a gather operation.
1396
+
1397
+ #### Constructor
1398
+
1399
+ ```ts
1400
+ constructor(opts: {
1401
+ key: string;
1402
+ question: string;
1403
+ type?: string; // default 'string'
1404
+ confirm?: boolean; // default false
1405
+ prompt?: string;
1406
+ functions?: string[];
1407
+ })
1408
+ ```
1409
+
1410
+ #### Properties
1411
+
1412
+ | Property | Type | Description |
1413
+ |----------|------|-------------|
1414
+ | `key` | `string` | Unique answer storage key |
1415
+ | `question` | `string` | Question text |
1416
+ | `type` | `string` | Expected answer type |
1417
+ | `confirm` | `boolean` | Whether confirmation is required |
1418
+ | `prompt` | `string \| undefined` | Additional prompt context |
1419
+ | `functions` | `string[] \| undefined` | Available functions during this question |
1420
+
1421
+ #### `toDict()`
1422
+
1423
+ ```ts
1424
+ toDict(): Record<string, unknown>
1425
+ ```
1426
+
1427
+ ### ContextBuilder Helper Functions
1428
+
1429
+ #### `createSimpleContext(name?)`
1430
+
1431
+ ```ts
1432
+ function createSimpleContext(name?: string): Context
1433
+ ```
1434
+
1435
+ Create a standalone Context without a ContextBuilder. Name defaults to `'default'`.
1436
+
1437
+ ---
1438
+
1439
+ ## PomBuilder
1440
+
1441
+ ```ts
1442
+ import { PomBuilder, PomSection } from '@anthropic/signalwire-agents';
1443
+ ```
1444
+
1445
+ Prompt Object Model for structured prompt sections. Sections have a title, body, bullets (optionally numbered), and nested subsections.
1446
+
1447
+ ### PomSection Class
1448
+
1449
+ A single section in a POM.
1450
+
1451
+ #### Constructor
1452
+
1453
+ ```ts
1454
+ constructor(opts?: {
1455
+ title?: string | null;
1456
+ body?: string;
1457
+ bullets?: string[];
1458
+ numbered?: boolean | null;
1459
+ numberedBullets?: boolean;
1460
+ })
1461
+ ```
1462
+
1463
+ #### Properties
1464
+
1465
+ | Property | Type | Description |
1466
+ |----------|------|-------------|
1467
+ | `title` | `string \| null` | Section heading |
1468
+ | `body` | `string` | Body text |
1469
+ | `bullets` | `string[]` | Bullet points |
1470
+ | `subsections` | `PomSection[]` | Nested child sections |
1471
+ | `numbered` | `boolean \| null` | Whether this section is numbered |
1472
+ | `numberedBullets` | `boolean` | Whether bullets are numbered |
1473
+
1474
+ #### Methods
1475
+
1476
+ | Method | Signature | Returns | Description |
1477
+ |--------|-----------|---------|-------------|
1478
+ | `addSubsection` | `(opts: { title, body?, bullets?, numbered?, numberedBullets? })` | `PomSection` | Add a nested subsection |
1479
+ | `toDict` | `()` | `PomSectionData` | Serialize to plain object |
1480
+ | `renderMarkdown` | `(level?, sectionNumber?)` | `string` | Render as Markdown |
1481
+
1482
+ ### PomBuilder Class
1483
+
1484
+ Builds a structured prompt by composing named POM sections.
1485
+
1486
+ #### Methods
1487
+
1488
+ | Method | Signature | Returns | Description |
1489
+ |--------|-----------|---------|-------------|
1490
+ | `addSection` | `(title, opts?)` | `this` | Add a top-level section |
1491
+ | `addToSection` | `(title, opts?)` | `this` | Append to an existing section |
1492
+ | `addSubsection` | `(parentTitle, title, opts?)` | `this` | Add subsection under a parent |
1493
+ | `hasSection` | `(title: string)` | `boolean` | Check if section exists |
1494
+ | `getSection` | `(title: string)` | `PomSection \| undefined` | Get section by title |
1495
+ | `findSection` | `(title: string)` | `PomSection \| undefined` | Recursive deep search |
1496
+ | `toDict` | `()` | `PomSectionData[]` | Serialize all sections |
1497
+ | `renderMarkdown` | `()` | `string` | Render all sections as Markdown |
1498
+
1499
+ ---
1500
+
1501
+ ## SwmlBuilder
1502
+
1503
+ ```ts
1504
+ import { SwmlBuilder } from '@anthropic/signalwire-agents';
1505
+ ```
1506
+
1507
+ Builds SWML (SignalWire Markup Language) documents: `{ version: "1.0.0", sections: { main: [...verbs] } }`.
1508
+
1509
+ ### Methods
1510
+
1511
+ | Method | Signature | Returns | Description |
1512
+ |--------|-----------|---------|-------------|
1513
+ | `reset` | `()` | `void` | Reset to empty document |
1514
+ | `addVerb` | `(verbName: string, config: unknown)` | `void` | Append verb to the `main` section |
1515
+ | `addVerbToSection` | `(sectionName, verbName, config)` | `void` | Append verb to a named section |
1516
+ | `getDocument` | `()` | `Record<string, unknown>` | Get the raw document object |
1517
+ | `renderDocument` | `()` | `string` | Serialize to JSON string |
1518
+
1519
+ ---
1520
+
1521
+ ## PromptManager
1522
+
1523
+ ```ts
1524
+ import { PromptManager } from '@anthropic/signalwire-agents';
1525
+ ```
1526
+
1527
+ Manages agent prompt text, supporting both raw text and structured POM-based prompts.
1528
+
1529
+ ### Constructor
1530
+
1531
+ ```ts
1532
+ constructor(usePom?: boolean)
1533
+ ```
1534
+
1535
+ | Parameter | Type | Default | Description |
1536
+ |-----------|------|---------|-------------|
1537
+ | `usePom` | `boolean` | `true` | Whether to use POM sections |
1538
+
1539
+ ### Methods
1540
+
1541
+ | Method | Signature | Returns | Description |
1542
+ |--------|-----------|---------|-------------|
1543
+ | `setPromptText` | `(text: string)` | `void` | Set raw prompt text, bypassing POM |
1544
+ | `setPostPrompt` | `(text: string)` | `void` | Set post-prompt text |
1545
+ | `addSection` | `(title, opts?)` | `void` | Add a POM section |
1546
+ | `addToSection` | `(title, opts?)` | `void` | Append to a POM section |
1547
+ | `addSubsection` | `(parentTitle, title, opts?)` | `void` | Add a POM subsection |
1548
+ | `hasSection` | `(title: string)` | `boolean` | Check if section exists |
1549
+ | `getPrompt` | `()` | `string` | Get rendered prompt text |
1550
+ | `getPostPrompt` | `()` | `string \| null` | Get post-prompt text |
1551
+ | `getPomBuilder` | `()` | `PomBuilder \| null` | Get underlying PomBuilder |
1552
+
1553
+ ---
1554
+
1555
+ ## SessionManager
1556
+
1557
+ ```ts
1558
+ import { SessionManager } from '@anthropic/signalwire-agents';
1559
+ ```
1560
+
1561
+ Stateless HMAC-SHA256 token manager for SWAIG function call authentication and per-session metadata storage. Tokens encode `callId.functionName.expiry.nonce.hmacSignature` in base64url format.
1562
+
1563
+ ### Constructor
1564
+
1565
+ ```ts
1566
+ constructor(tokenExpirySecs?: number, secretKey?: string)
1567
+ ```
1568
+
1569
+ | Parameter | Type | Default | Description |
1570
+ |-----------|------|---------|-------------|
1571
+ | `tokenExpirySecs` | `number` | `3600` | Token validity in seconds |
1572
+ | `secretKey` | `string` | Random 32 bytes | HMAC signing secret |
1573
+
1574
+ ### Methods
1575
+
1576
+ #### `createSession(callId?)`
1577
+
1578
+ ```ts
1579
+ createSession(callId?: string): string
1580
+ ```
1581
+
1582
+ Return the given callId or generate a new random session identifier.
1583
+
1584
+ #### `generateToken(functionName, callId)`
1585
+
1586
+ ```ts
1587
+ generateToken(functionName: string, callId: string): string
1588
+ ```
1589
+
1590
+ Generate a signed, base64url-encoded token binding a function name to a call ID.
1591
+
1592
+ #### `createToolToken(functionName, callId)`
1593
+
1594
+ ```ts
1595
+ createToolToken(functionName: string, callId: string): string
1596
+ ```
1597
+
1598
+ Alias for `generateToken()`.
1599
+
1600
+ #### `validateToken(callId, functionName, token)`
1601
+
1602
+ ```ts
1603
+ validateToken(callId: string, functionName: string, token: string): boolean
1604
+ ```
1605
+
1606
+ Validate a token against the expected call ID and function name. Returns `true` if valid and not expired.
1607
+
1608
+ #### `validateToolToken(functionName, token, callId)`
1609
+
1610
+ ```ts
1611
+ validateToolToken(functionName: string, token: string, callId: string): boolean
1612
+ ```
1613
+
1614
+ Alias for `validateToken()` with reordered parameters.
1615
+
1616
+ #### `debugToken(token)`
1617
+
1618
+ ```ts
1619
+ debugToken(token: string): {
1620
+ callId: string;
1621
+ functionName: string;
1622
+ expiry: number;
1623
+ nonce: string;
1624
+ signature: string;
1625
+ expired: boolean;
1626
+ } | null
1627
+ ```
1628
+
1629
+ Decode token components for debugging without validating the signature. Returns `null` if malformed.
1630
+
1631
+ #### Metadata Methods
1632
+
1633
+ | Method | Signature | Returns | Description |
1634
+ |--------|-----------|---------|-------------|
1635
+ | `getSessionMetadata` | `(sessionId: string)` | `Record<string, unknown> \| undefined` | Get session metadata |
1636
+ | `setSessionMetadata` | `(sessionId, metadata)` | `void` | Merge metadata into session |
1637
+ | `deleteSessionMetadata` | `(sessionId: string)` | `boolean` | Delete all session metadata |
1638
+
1639
+ ---
1640
+
1641
+ ## Skills
1642
+
1643
+ ```ts
1644
+ import { SkillBase, SkillManager, SkillRegistry } from '@anthropic/signalwire-agents';
1645
+ ```
1646
+
1647
+ ### SkillBase
1648
+
1649
+ Abstract base class for agent skills. Skills are modular capabilities that provide tools, prompt sections, hints, and global data.
1650
+
1651
+ #### Constructor
1652
+
1653
+ ```ts
1654
+ constructor(skillName: string, config?: SkillConfig)
1655
+ ```
1656
+
1657
+ #### Properties
1658
+
1659
+ | Property | Type | Description |
1660
+ |----------|------|-------------|
1661
+ | `skillName` | `string` (readonly) | Registered skill type name |
1662
+ | `instanceId` | `string` (readonly) | Unique instance ID (includes timestamp + random bytes) |
1663
+ | `config` | `SkillConfig` (protected) | Configuration options |
1664
+
1665
+ #### Abstract Methods (must be implemented)
1666
+
1667
+ | Method | Signature | Returns | Description |
1668
+ |--------|-----------|---------|-------------|
1669
+ | `getManifest` | `()` | `SkillManifest` | Return skill metadata and requirements |
1670
+ | `getTools` | `()` | `SkillToolDefinition[]` | Return SWAIG tool definitions |
1671
+
1672
+ #### Overridable Methods
1673
+
1674
+ | Method | Signature | Returns | Description |
1675
+ |--------|-----------|---------|-------------|
1676
+ | `setup` | `()` | `Promise<void>` | Initialization hook (called when added to agent) |
1677
+ | `cleanup` | `()` | `Promise<void>` | Teardown hook (called when removed) |
1678
+ | `getPromptSections` | `()` | `SkillPromptSection[]` | Prompt sections to inject |
1679
+ | `getHints` | `()` | `string[]` | Speech recognition hints |
1680
+ | `getGlobalData` | `()` | `Record<string, unknown>` | Global data to merge |
1681
+
1682
+ #### Utility Methods
1683
+
1684
+ | Method | Signature | Returns | Description |
1685
+ |--------|-----------|---------|-------------|
1686
+ | `validateEnvVars` | `()` | `string[]` | List missing required env vars |
1687
+ | `isInitialized` | `()` | `boolean` | Check initialization state |
1688
+ | `markInitialized` | `()` | `void` | Mark as initialized (called by SkillManager) |
1689
+ | `getConfig` | `<T>(key, defaultValue?)` | `T` | Get a config value with fallback |
1690
+
1691
+ ### SkillManager
1692
+
1693
+ Manages the lifecycle of skills attached to an agent.
1694
+
1695
+ #### Methods
1696
+
1697
+ | Method | Signature | Returns | Description |
1698
+ |--------|-----------|---------|-------------|
1699
+ | `addSkill` | `(skill: SkillBase)` | `Promise<void>` | Add, validate, and setup a skill |
1700
+ | `removeSkill` | `(instanceId: string)` | `Promise<boolean>` | Remove by instance ID |
1701
+ | `removeSkillByName` | `(skillName: string)` | `Promise<number>` | Remove all instances of a skill name |
1702
+ | `hasSkill` | `(skillName: string)` | `boolean` | Check if any instance with name exists |
1703
+ | `getSkill` | `(instanceId: string)` | `SkillBase \| undefined` | Get by instance ID |
1704
+ | `listSkills` | `()` | `{ name, instanceId, initialized }[]` | List all loaded skills |
1705
+ | `getAllTools` | `()` | `SkillToolDefinition[]` | Aggregate all skill tools |
1706
+ | `getAllPromptSections` | `()` | `SkillPromptSection[]` | Aggregate all prompt sections |
1707
+ | `getAllHints` | `()` | `string[]` | Aggregate all hints |
1708
+ | `getMergedGlobalData` | `()` | `Record<string, unknown>` | Merge all skill global data |
1709
+ | `clear` | `()` | `Promise<void>` | Remove and cleanup all skills |
1710
+ | `size` | (getter) | `number` | Count of loaded skills |
1711
+
1712
+ ### SkillRegistry
1713
+
1714
+ Global singleton registry for discovering and instantiating skills. Supports the `SIGNALWIRE_SKILL_PATHS` environment variable for custom skill directories.
1715
+
1716
+ #### Static Methods
1717
+
1718
+ | Method | Signature | Returns | Description |
1719
+ |--------|-----------|---------|-------------|
1720
+ | `getInstance` | `()` | `SkillRegistry` | Get the global singleton |
1721
+ | `resetInstance` | `()` | `void` | Reset the singleton (for testing) |
1722
+
1723
+ #### Instance Methods
1724
+
1725
+ | Method | Signature | Returns | Description |
1726
+ |--------|-----------|---------|-------------|
1727
+ | `register` | `(name, factory, manifest?)` | `void` | Register a skill factory |
1728
+ | `unregister` | `(name: string)` | `boolean` | Remove a registration |
1729
+ | `create` | `(name, config?)` | `SkillBase \| null` | Create instance from registry |
1730
+ | `has` | `(name: string)` | `boolean` | Check if name is registered |
1731
+ | `getManifest` | `(name: string)` | `SkillManifest \| undefined` | Get skill manifest |
1732
+ | `listRegistered` | `()` | `string[]` | List registered names |
1733
+ | `listRegisteredWithManifests` | `()` | `{ name, manifest? }[]` | List with manifests |
1734
+ | `addSearchPath` | `(path: string)` | `void` | Add a discovery directory |
1735
+ | `getSearchPaths` | `()` | `string[]` | Get all search paths |
1736
+ | `discoverFromDirectory` | `(dirPath: string)` | `Promise<string[]>` | Discover skills from a directory |
1737
+ | `discoverAll` | `()` | `Promise<string[]>` | Discover from all search paths |
1738
+ | `clear` | `()` | `void` | Clear all registrations |
1739
+ | `size` | (getter) | `number` | Count of registered skills |
1740
+
1741
+ #### SkillFactory Type
1742
+
1743
+ ```ts
1744
+ type SkillFactory = (config?: SkillConfig) => SkillBase;
1745
+ ```
1746
+
1747
+ ---
1748
+
1749
+ ## Prefab Agents
1750
+
1751
+ Pre-built agent templates with declarative configuration, built-in tools, and prompt sections.
1752
+
1753
+ ### InfoGathererAgent
1754
+
1755
+ ```ts
1756
+ import { InfoGathererAgent, createInfoGathererAgent } from '@anthropic/signalwire-agents';
1757
+ ```
1758
+
1759
+ Sequentially collects named fields from a caller with optional validation and completion callback.
1760
+
1761
+ #### InfoGathererConfig
1762
+
1763
+ | Property | Type | Default | Description |
1764
+ |----------|------|---------|-------------|
1765
+ | `name` | `string` | `'InfoGatherer'` | Agent display name |
1766
+ | `fields` | `InfoGathererField[]` | -- | Fields to collect (required) |
1767
+ | `introMessage` | `string` | Generic greeting | Opening message |
1768
+ | `confirmationMessage` | `string` | Generic thank you | Message after all fields gathered |
1769
+ | `onComplete` | `(data: Record<string, string>) => void \| Promise<void>` | -- | Completion callback |
1770
+ | `agentOptions` | `Partial<AgentOptions>` | -- | Passed to `AgentBase` |
1771
+
1772
+ #### InfoGathererField
1773
+
1774
+ | Property | Type | Default | Description |
1775
+ |----------|------|---------|-------------|
1776
+ | `name` | `string` | -- | Unique field name |
1777
+ | `description` | `string` | -- | Description shown to AI |
1778
+ | `required` | `boolean` | `true` | Whether field must be collected |
1779
+ | `validation` | `RegExp \| string` | -- | Optional validation pattern |
1780
+
1781
+ **Built-in tools:** `save_field`, `get_status`
1782
+
1783
+ **Factory:** `createInfoGathererAgent(config: InfoGathererConfig): InfoGathererAgent`
1784
+
1785
+ ### SurveyAgent
1786
+
1787
+ ```ts
1788
+ import { SurveyAgent, createSurveyAgent } from '@anthropic/signalwire-agents';
1789
+ ```
1790
+
1791
+ Conducts surveys with branching logic, answer scoring, and conditional question flow.
1792
+
1793
+ #### SurveyConfig
1794
+
1795
+ | Property | Type | Default | Description |
1796
+ |----------|------|---------|-------------|
1797
+ | `name` | `string` | `'SurveyAgent'` | Agent display name |
1798
+ | `questions` | `SurveyQuestion[]` | -- | Ordered list of survey questions (required) |
1799
+ | `introMessage` | `string` | Generic greeting | Opening message |
1800
+ | `completionMessage` | `string` | Generic thank you | Completion message |
1801
+ | `onComplete` | `(responses, score) => void \| Promise<void>` | -- | Completion callback |
1802
+ | `agentOptions` | `Partial<AgentOptions>` | -- | Passed to `AgentBase` |
1803
+
1804
+ #### SurveyQuestion
1805
+
1806
+ | Property | Type | Description |
1807
+ |----------|------|-------------|
1808
+ | `id` | `string` | Unique question identifier |
1809
+ | `text` | `string` | Question text to ask |
1810
+ | `type` | `'multiple_choice' \| 'open_ended' \| 'rating' \| 'yes_no'` | Question type |
1811
+ | `options` | `string[]` | Options for `multiple_choice` |
1812
+ | `nextQuestion` | `string \| Record<string, string>` | Branching logic: fixed next or answer-based map |
1813
+ | `points` | `number \| Record<string, number>` | Scoring: fixed or per-answer |
1814
+
1815
+ **Built-in tools:** `answer_question`, `get_current_question`, `get_survey_progress`
1816
+
1817
+ **Factory:** `createSurveyAgent(config: SurveyConfig): SurveyAgent`
1818
+
1819
+ ### FAQBotAgent
1820
+
1821
+ ```ts
1822
+ import { FAQBotAgent, createFAQBotAgent } from '@anthropic/signalwire-agents';
1823
+ ```
1824
+
1825
+ Answers frequently asked questions using keyword/word-overlap matching with optional escalation.
1826
+
1827
+ #### FAQBotConfig
1828
+
1829
+ | Property | Type | Default | Description |
1830
+ |----------|------|---------|-------------|
1831
+ | `name` | `string` | `'FAQBot'` | Agent display name |
1832
+ | `faqs` | `FAQEntry[]` | -- | FAQ entries (required) |
1833
+ | `threshold` | `number` | `0.5` | Minimum match score (0-1) |
1834
+ | `escalationMessage` | `string` | Generic apology | No-match message |
1835
+ | `escalationNumber` | `string` | -- | Phone number for escalation transfer |
1836
+ | `agentOptions` | `Partial<AgentOptions>` | -- | Passed to `AgentBase` |
1837
+
1838
+ #### FAQEntry
1839
+
1840
+ | Property | Type | Description |
1841
+ |----------|------|-------------|
1842
+ | `question` | `string` | Representative question text |
1843
+ | `answer` | `string` | Answer to provide |
1844
+ | `keywords` | `string[]` | Additional matching keywords |
1845
+
1846
+ **Built-in tools:** `search_faq`, `escalate` (if `escalationNumber` is set)
1847
+
1848
+ **Factory:** `createFAQBotAgent(config: FAQBotConfig): FAQBotAgent`
1849
+
1850
+ ### ConciergeAgent
1851
+
1852
+ ```ts
1853
+ import { ConciergeAgent, createConciergeAgent } from '@anthropic/signalwire-agents';
1854
+ ```
1855
+
1856
+ Multi-department routing with a knowledge base of department info, hours, and transfer capabilities.
1857
+
1858
+ #### ConciergeConfig
1859
+
1860
+ | Property | Type | Default | Description |
1861
+ |----------|------|---------|-------------|
1862
+ | `name` | `string` | `'Concierge'` | Agent display name |
1863
+ | `departments` | `Department[]` | -- | Departments for routing (required) |
1864
+ | `companyName` | `string` | `'our company'` | Company name in prompts |
1865
+ | `generalInfo` | `string` | `''` | General company information |
1866
+ | `afterHoursMessage` | `string` | Generic closed message | Message when department is unavailable |
1867
+ | `agentOptions` | `Partial<AgentOptions>` | -- | Passed to `AgentBase` |
1868
+
1869
+ #### Department
1870
+
1871
+ | Property | Type | Description |
1872
+ |----------|------|-------------|
1873
+ | `name` | `string` | Department name |
1874
+ | `description` | `string` | What the department handles |
1875
+ | `transferNumber` | `string` | Phone/SIP for transfers |
1876
+ | `keywords` | `string[]` | Routing keywords |
1877
+ | `hoursOfOperation` | `string` | Human-readable hours |
1878
+
1879
+ **Built-in tools:** `list_departments`, `get_department_info`, `transfer_to_department`
1880
+
1881
+ **Factory:** `createConciergeAgent(config: ConciergeConfig): ConciergeAgent`
1882
+
1883
+ ### ReceptionistAgent
1884
+
1885
+ ```ts
1886
+ import { ReceptionistAgent, createReceptionistAgent } from '@anthropic/signalwire-agents';
1887
+ ```
1888
+
1889
+ Front-desk agent that handles visitor check-in, department directory lookup, and call transfers by extension.
1890
+
1891
+ #### ReceptionistConfig
1892
+
1893
+ | Property | Type | Default | Description |
1894
+ |----------|------|---------|-------------|
1895
+ | `name` | `string` | `'Receptionist'` | Agent display name |
1896
+ | `companyName` | `string` | -- | Company name (required) |
1897
+ | `departments` | `ReceptionistDepartment[]` | -- | Departments with extensions (required) |
1898
+ | `welcomeMessage` | `string` | Auto-generated | Custom welcome message |
1899
+ | `checkInEnabled` | `boolean` | `true` | Enable visitor check-in |
1900
+ | `onVisitorCheckIn` | `(visitor: Record<string, string>) => void \| Promise<void>` | -- | Check-in callback |
1901
+ | `agentOptions` | `Partial<AgentOptions>` | -- | Passed to `AgentBase` |
1902
+
1903
+ #### ReceptionistDepartment
1904
+
1905
+ | Property | Type | Description |
1906
+ |----------|------|-------------|
1907
+ | `name` | `string` | Department name |
1908
+ | `extension` | `string` | Internal extension or SIP address |
1909
+ | `description` | `string` | Optional description |
1910
+
1911
+ **Built-in tools:** `get_department_list`, `transfer_to_department`, `check_in_visitor` (if enabled)
1912
+
1913
+ **Factory:** `createReceptionistAgent(config: ReceptionistConfig): ReceptionistAgent`
1914
+
1915
+ ---
1916
+
1917
+ ## Utility Classes
1918
+
1919
+ ### AuthHandler
1920
+
1921
+ ```ts
1922
+ import { AuthHandler } from '@anthropic/signalwire-agents';
1923
+ ```
1924
+
1925
+ Multi-method authentication handler with timing-safe credential comparison. Supports Bearer token, API key, Basic auth, and custom validators.
1926
+
1927
+ #### Constructor
1928
+
1929
+ ```ts
1930
+ constructor(config: AuthConfig)
1931
+ ```
1932
+
1933
+ See [AuthConfig](#authconfig).
1934
+
1935
+ #### Methods
1936
+
1937
+ | Method | Signature | Returns | Description |
1938
+ |--------|-----------|---------|-------------|
1939
+ | `validate` | `(headers: Record<string, string>)` | `Promise<boolean>` | Validate against all configured methods |
1940
+ | `middleware` | `()` | Hono middleware | Create middleware rejecting with 401 |
1941
+ | `hasBearerAuth` | `()` | `boolean` | Check if Bearer is configured |
1942
+ | `hasApiKeyAuth` | `()` | `boolean` | Check if API key is configured |
1943
+ | `hasBasicAuth` | `()` | `boolean` | Check if Basic auth is configured |
1944
+
1945
+ ### ConfigLoader
1946
+
1947
+ ```ts
1948
+ import { ConfigLoader } from '@anthropic/signalwire-agents';
1949
+ ```
1950
+
1951
+ JSON configuration file loader with `${VAR|default}` environment variable interpolation and dot-notation access.
1952
+
1953
+ #### Constructor
1954
+
1955
+ ```ts
1956
+ constructor(filePath?: string)
1957
+ ```
1958
+
1959
+ Optionally loads a JSON file immediately on construction.
1960
+
1961
+ #### Static Methods
1962
+
1963
+ | Method | Signature | Returns | Description |
1964
+ |--------|-----------|---------|-------------|
1965
+ | `search` | `(filename: string)` | `ConfigLoader \| null` | Search CWD, `./config`, `$HOME/.signalwire` |
1966
+
1967
+ #### Instance Methods
1968
+
1969
+ | Method | Signature | Returns | Description |
1970
+ |--------|-----------|---------|-------------|
1971
+ | `load` | `(filePath: string)` | `this` | Load from a JSON file with env interpolation |
1972
+ | `loadFromObject` | `(obj: Record<string, unknown>)` | `this` | Load from a plain object |
1973
+ | `get` | `<T>(path: string, defaultValue?: T)` | `T` | Dot-notation access (e.g., `'server.port'`) |
1974
+ | `set` | `(path: string, value: unknown)` | `this` | Set a value at a dot-notation path |
1975
+ | `has` | `(path: string)` | `boolean` | Check if a path exists |
1976
+ | `getAll` | `()` | `Record<string, unknown>` | Shallow copy of all config |
1977
+ | `getFilePath` | `()` | `string \| null` | Path of loaded config file |
1978
+
1979
+ ### Logger
1980
+
1981
+ ```ts
1982
+ import { Logger, getLogger, setGlobalLogLevel, suppressAllLogs, setGlobalLogFormat, setGlobalLogColor, resetLoggingConfiguration } from '@anthropic/signalwire-agents';
1983
+ ```
1984
+
1985
+ Structured logger configurable via environment variables.
1986
+
1987
+ #### Environment Variables
1988
+
1989
+ | Variable | Values | Default | Description |
1990
+ |----------|--------|---------|-------------|
1991
+ | `SIGNALWIRE_LOG_LEVEL` | `debug`, `info`, `warn`, `error` | `info` | Minimum log level |
1992
+ | `SIGNALWIRE_LOG_MODE` | `off` | -- | Set to `off` to suppress all logging |
1993
+ | `SIGNALWIRE_LOG_FORMAT` | `text`, `json` | `text` | Output format |
1994
+ | `SIGNALWIRE_LOG_COLOR` | `true`, `false` | auto (TTY) | ANSI color codes in text format |
1995
+
1996
+ #### Logger Constructor
1997
+
1998
+ ```ts
1999
+ constructor(name: string, context?: Record<string, unknown>)
2000
+ ```
2001
+
2002
+ #### Logger Methods
2003
+
2004
+ | Method | Signature | Returns | Description |
2005
+ |--------|-----------|---------|-------------|
2006
+ | `debug` | `(msg: string, data?)` | `void` | Log at debug level |
2007
+ | `info` | `(msg: string, data?)` | `void` | Log at info level |
2008
+ | `warn` | `(msg: string, data?)` | `void` | Log at warn level |
2009
+ | `error` | `(msg: string, data?)` | `void` | Log at error level |
2010
+ | `bind` | `(context: Record<string, unknown>)` | `Logger` | Create child logger with merged context |
2011
+
2012
+ #### Module Functions
2013
+
2014
+ | Function | Signature | Description |
2015
+ |----------|-----------|-------------|
2016
+ | `getLogger` | `(name: string): Logger` | Create a new Logger instance |
2017
+ | `setGlobalLogLevel` | `(level: LogLevel): void` | Set minimum level for all loggers |
2018
+ | `suppressAllLogs` | `(suppress?: boolean): void` | Suppress/unsuppress all output |
2019
+ | `setGlobalLogFormat` | `(format: 'text' \| 'json'): void` | Set output format |
2020
+ | `setGlobalLogColor` | `(enabled: boolean): void` | Enable/disable ANSI colors |
2021
+ | `resetLoggingConfiguration` | `(): void` | Reset to env-var defaults |
2022
+
2023
+ ### SslConfig
2024
+
2025
+ ```ts
2026
+ import { SslConfig } from '@anthropic/signalwire-agents';
2027
+ ```
2028
+
2029
+ SSL/TLS configuration sourced from explicit options or environment variables.
2030
+
2031
+ #### Environment Variables
2032
+
2033
+ | Variable | Description |
2034
+ |----------|-------------|
2035
+ | `SWML_SSL_ENABLED` | Set to `true` to enable SSL |
2036
+ | `SWML_SSL_CERT_PATH` | Path to PEM certificate |
2037
+ | `SWML_SSL_KEY_PATH` | Path to PEM private key |
2038
+ | `SWML_SSL_DOMAIN` | Domain for HSTS headers |
2039
+
2040
+ #### Constructor
2041
+
2042
+ ```ts
2043
+ constructor(opts?: SslOptions)
2044
+ ```
2045
+
2046
+ See [SslOptions](#ssloptions).
2047
+
2048
+ #### Properties
2049
+
2050
+ | Property | Type | Description |
2051
+ |----------|------|-------------|
2052
+ | `enabled` | `boolean` | Whether SSL is enabled |
2053
+ | `certPath` | `string \| null` | PEM certificate path |
2054
+ | `keyPath` | `string \| null` | PEM private key path |
2055
+ | `domain` | `string \| null` | HSTS domain |
2056
+ | `hsts` | `boolean` | Whether to emit HSTS headers |
2057
+ | `hstsMaxAge` | `number` | HSTS max-age in seconds |
2058
+
2059
+ #### Methods
2060
+
2061
+ | Method | Signature | Returns | Description |
2062
+ |--------|-----------|---------|-------------|
2063
+ | `isConfigured` | `()` | `boolean` | Check if SSL is fully configured with valid files |
2064
+ | `getCert` | `()` | `string \| null` | Read PEM certificate from disk |
2065
+ | `getKey` | `()` | `string \| null` | Read PEM private key from disk |
2066
+ | `getHstsHeader` | `()` | `string \| null` | Build HSTS header value |
2067
+ | `getServerOptions` | `()` | `{ cert, key } \| null` | Options for `https.createServer()` |
2068
+ | `hstsMiddleware` | `()` | Hono middleware | Middleware that appends HSTS header |
2069
+
2070
+ ### SchemaUtils
2071
+
2072
+ ```ts
2073
+ import { SchemaUtils } from '@anthropic/signalwire-agents';
2074
+ ```
2075
+
2076
+ Validates SWML documents against structural rules with an LRU-style result cache.
2077
+
2078
+ #### Constructor
2079
+
2080
+ ```ts
2081
+ constructor(opts?: { skipValidation?: boolean; maxCacheSize?: number })
2082
+ ```
2083
+
2084
+ | Parameter | Type | Default | Description |
2085
+ |-----------|------|---------|-------------|
2086
+ | `skipValidation` | `boolean` | `SWML_SKIP_SCHEMA_VALIDATION` env | Skip all validation |
2087
+ | `maxCacheSize` | `number` | `100` | Maximum cached results |
2088
+
2089
+ #### Methods
2090
+
2091
+ | Method | Signature | Returns | Description |
2092
+ |--------|-----------|---------|-------------|
2093
+ | `validate` | `(swml: string \| Record<string, unknown>)` | `ValidationResult` | Validate a SWML document |
2094
+ | `clearCache` | `()` | `void` | Clear the validation cache |
2095
+ | `getCacheSize` | `()` | `number` | Get current cache entry count |
2096
+
2097
+ ### ServerlessAdapter
2098
+
2099
+ ```ts
2100
+ import { ServerlessAdapter } from '@anthropic/signalwire-agents';
2101
+ ```
2102
+
2103
+ Adapts a Hono application for deployment on serverless platforms. Auto-detects platform from environment variables.
2104
+
2105
+ #### Constructor
2106
+
2107
+ ```ts
2108
+ constructor(platform?: ServerlessPlatform)
2109
+ ```
2110
+
2111
+ | Parameter | Type | Default | Description |
2112
+ |-----------|------|---------|-------------|
2113
+ | `platform` | `ServerlessPlatform` | `'auto'` | Target platform or auto-detect |
2114
+
2115
+ #### Instance Methods
2116
+
2117
+ | Method | Signature | Returns | Description |
2118
+ |--------|-----------|---------|-------------|
2119
+ | `detectPlatform` | `()` | `ServerlessPlatform` | Detect platform from env vars |
2120
+ | `getPlatform` | `()` | `ServerlessPlatform` | Get resolved platform |
2121
+ | `handleRequest` | `(app, event)` | `Promise<ServerlessResponse>` | Route event through Hono app |
2122
+ | `generateUrl` | `(opts?)` | `string` | Generate platform-specific invocation URL |
2123
+
2124
+ #### Static Factory Methods
2125
+
2126
+ | Method | Signature | Returns | Description |
2127
+ |--------|-----------|---------|-------------|
2128
+ | `createLambdaHandler` | `(app)` | `(event) => Promise<ServerlessResponse>` | AWS Lambda handler |
2129
+ | `createGcfHandler` | `(app)` | `(req, res) => Promise<void>` | Google Cloud Functions handler |
2130
+ | `createAzureHandler` | `(app)` | `(context, req) => Promise<void>` | Azure Functions handler |
2131
+
2132
+ **Example (AWS Lambda):**
2133
+ ```ts
2134
+ const agent = new AgentBase({ name: 'MyAgent' });
2135
+ export const handler = ServerlessAdapter.createLambdaHandler(agent.getApp());
2136
+ ```
2137
+
2138
+ ---
2139
+
2140
+ ## Types and Interfaces
2141
+
2142
+ ### AgentOptions
2143
+
2144
+ ```ts
2145
+ interface AgentOptions
2146
+ ```
2147
+
2148
+ Configuration options for constructing an AgentBase instance.
2149
+
2150
+ | Property | Type | Default | Description |
2151
+ |----------|------|---------|-------------|
2152
+ | `name` | `string` | -- | Display name (required); also used as default basic-auth username |
2153
+ | `route` | `string` | `'/'` | HTTP route path |
2154
+ | `host` | `string` | `'0.0.0.0'` | Hostname to bind |
2155
+ | `port` | `number` | `PORT` env or `3000` | Port number |
2156
+ | `basicAuth` | `[string, string]` | Auto-generated | Explicit `[username, password]` credentials |
2157
+ | `usePom` | `boolean` | `true` | Use POM-based prompt rendering |
2158
+ | `tokenExpirySecs` | `number` | `3600` | Session token expiry in seconds |
2159
+ | `autoAnswer` | `boolean` | `true` | Insert an "answer" verb in SWML |
2160
+ | `recordCall` | `boolean` | `false` | Record the call |
2161
+ | `recordFormat` | `string` | `'mp4'` | Recording format |
2162
+ | `recordStereo` | `boolean` | `true` | Stereo recording |
2163
+ | `defaultWebhookUrl` | `string` | -- | Default SWAIG webhook URL |
2164
+ | `nativeFunctions` | `string[]` | `[]` | Native function names |
2165
+ | `agentId` | `string` | Random hex | Unique agent instance ID |
2166
+ | `suppressLogs` | `boolean` | `false` | Suppress all log output |
2167
+
2168
+ ### LanguageConfig
2169
+
2170
+ ```ts
2171
+ interface LanguageConfig
2172
+ ```
2173
+
2174
+ | Property | Type | Description |
2175
+ |----------|------|-------------|
2176
+ | `name` | `string` | Human-readable name (e.g., `"English"`) |
2177
+ | `code` | `string` | BCP-47 code (e.g., `"en-US"`) |
2178
+ | `voice` | `string` | Voice identifier |
2179
+ | `engine` | `string` | TTS engine identifier |
2180
+ | `fillers` | `Record<string, string[]>` | Filler phrases by category |
2181
+ | `speechModel` | `string` | Speech recognition model |
2182
+ | `functionFillers` | `Record<string, Record<string, string[]>>` | Per-function fillers by language |
2183
+
2184
+ ### PronunciationRule
2185
+
2186
+ ```ts
2187
+ interface PronunciationRule
2188
+ ```
2189
+
2190
+ | Property | Type | Description |
2191
+ |----------|------|-------------|
2192
+ | `replace` | `string` | Text pattern to match |
2193
+ | `with` | `string` | Replacement pronunciation |
2194
+ | `ignoreCase` | `boolean` | Case-insensitive matching |
2195
+
2196
+ ### FunctionInclude
2197
+
2198
+ ```ts
2199
+ interface FunctionInclude
2200
+ ```
2201
+
2202
+ | Property | Type | Description |
2203
+ |----------|------|-------------|
2204
+ | `url` | `string` | URL of the remote SWAIG endpoint |
2205
+ | `functions` | `string[]` | Function names at the endpoint |
2206
+ | `meta_data` | `Record<string, unknown>` | Optional metadata |
2207
+
2208
+ ### DynamicConfigCallback
2209
+
2210
+ ```ts
2211
+ type DynamicConfigCallback = (
2212
+ queryParams: Record<string, string>,
2213
+ bodyParams: Record<string, unknown>,
2214
+ headers: Record<string, string>,
2215
+ agent: unknown, // Ephemeral AgentBase copy
2216
+ ) => void | Promise<void>;
2217
+ ```
2218
+
2219
+ Callback invoked on each SWML request to dynamically modify an ephemeral copy of the agent. The original agent is never mutated.
2220
+
2221
+ ### SummaryCallback
2222
+
2223
+ ```ts
2224
+ type SummaryCallback = (
2225
+ summary: Record<string, unknown> | null,
2226
+ rawData: Record<string, unknown>,
2227
+ ) => void | Promise<void>;
2228
+ ```
2229
+
2230
+ Callback invoked when a post-prompt summary is received.
2231
+
2232
+ ### SwaigHandler
2233
+
2234
+ ```ts
2235
+ type SwaigHandler = (
2236
+ args: Record<string, unknown>,
2237
+ rawData: Record<string, unknown>,
2238
+ ) => SwaigFunctionResult | Record<string, unknown> | string | Promise<SwaigFunctionResult | Record<string, unknown> | string>;
2239
+ ```
2240
+
2241
+ Handler function for a SWAIG tool invocation. Can return:
2242
+ - A `SwaigFunctionResult` instance
2243
+ - A plain object with a `response` key
2244
+ - A plain string (wrapped into a SwaigFunctionResult)
2245
+ - A `Promise` of any of the above
2246
+
2247
+ ### SwaigFunctionOptions
2248
+
2249
+ ```ts
2250
+ interface SwaigFunctionOptions
2251
+ ```
2252
+
2253
+ | Property | Type | Default | Description |
2254
+ |----------|------|---------|-------------|
2255
+ | `name` | `string` | -- | Unique tool name (required) |
2256
+ | `handler` | `SwaigHandler` | -- | Handler function (required) |
2257
+ | `description` | `string` | -- | Description shown to AI (required) |
2258
+ | `parameters` | `Record<string, unknown>` | `{}` | JSON Schema parameter properties |
2259
+ | `secure` | `boolean` | `false` | Require session token auth |
2260
+ | `fillers` | `Record<string, string[]>` | -- | Language-keyed filler phrases |
2261
+ | `waitFile` | `string` | -- | Audio file URL for waiting |
2262
+ | `waitFileLoops` | `number` | -- | Wait file loop count |
2263
+ | `webhookUrl` | `string` | -- | External webhook URL |
2264
+ | `required` | `string[]` | `[]` | Required parameter names |
2265
+ | `extraFields` | `Record<string, unknown>` | `{}` | Additional SWAIG definition fields |
2266
+
2267
+ ### AuthConfig
2268
+
2269
+ ```ts
2270
+ interface AuthConfig
2271
+ ```
2272
+
2273
+ | Property | Type | Description |
2274
+ |----------|------|-------------|
2275
+ | `bearerToken` | `string` | Bearer token for Authorization header |
2276
+ | `apiKey` | `string` | API key for X-Api-Key header |
2277
+ | `basicAuth` | `[string, string]` | Basic auth `[username, password]` |
2278
+ | `customValidator` | `(request: { headers, method, url }) => boolean \| Promise<boolean>` | Custom validation function |
2279
+
2280
+ ### SslOptions
2281
+
2282
+ ```ts
2283
+ interface SslOptions
2284
+ ```
2285
+
2286
+ | Property | Type | Default | Description |
2287
+ |----------|------|---------|-------------|
2288
+ | `enabled` | `boolean` | `SWML_SSL_ENABLED` env | Whether SSL is enabled |
2289
+ | `certPath` | `string` | `SWML_SSL_CERT_PATH` env | Path to PEM certificate |
2290
+ | `keyPath` | `string` | `SWML_SSL_KEY_PATH` env | Path to PEM private key |
2291
+ | `domain` | `string` | `SWML_SSL_DOMAIN` env | Domain for HSTS |
2292
+ | `hsts` | `boolean` | `true` | Send HSTS headers |
2293
+ | `hstsMaxAge` | `number` | `31536000` | HSTS max-age in seconds |
2294
+
2295
+ ### ValidationResult
2296
+
2297
+ ```ts
2298
+ interface ValidationResult
2299
+ ```
2300
+
2301
+ | Property | Type | Description |
2302
+ |----------|------|-------------|
2303
+ | `valid` | `boolean` | Whether the document passed validation |
2304
+ | `errors` | `string[]` | Human-readable error messages (empty when valid) |
2305
+
2306
+ ### ServerlessEvent
2307
+
2308
+ ```ts
2309
+ interface ServerlessEvent
2310
+ ```
2311
+
2312
+ Normalized incoming event from a serverless platform.
2313
+
2314
+ | Property | Type | Description |
2315
+ |----------|------|-------------|
2316
+ | `httpMethod` | `string` | HTTP method (AWS Lambda style) |
2317
+ | `method` | `string` | HTTP method (GCF/Azure style) |
2318
+ | `headers` | `Record<string, string>` | Request headers |
2319
+ | `body` | `string \| Record<string, unknown>` | Request body |
2320
+ | `path` | `string` | Request path |
2321
+ | `rawPath` | `string` | Raw request path (API Gateway v2) |
2322
+ | `queryStringParameters` | `Record<string, string>` | Query parameters |
2323
+ | `requestContext` | `Record<string, unknown>` | Platform-specific context |
2324
+
2325
+ ### ServerlessResponse
2326
+
2327
+ ```ts
2328
+ interface ServerlessResponse
2329
+ ```
2330
+
2331
+ | Property | Type | Description |
2332
+ |----------|------|-------------|
2333
+ | `statusCode` | `number` | HTTP status code |
2334
+ | `headers` | `Record<string, string>` | Response headers |
2335
+ | `body` | `string` | Response body |
2336
+
2337
+ ### PomSectionData
2338
+
2339
+ ```ts
2340
+ interface PomSectionData
2341
+ ```
2342
+
2343
+ Serializable representation of a POM section for JSON export.
2344
+
2345
+ | Property | Type | Description |
2346
+ |----------|------|-------------|
2347
+ | `title` | `string` | Section heading |
2348
+ | `body` | `string` | Body text |
2349
+ | `bullets` | `string[]` | Bullet points |
2350
+ | `numbered` | `boolean` | Whether subsections are numbered |
2351
+ | `numberedBullets` | `boolean` | Whether bullets are rendered as a numbered list |
2352
+ | `subsections` | `PomSectionData[]` | Nested child sections |
2353
+
2354
+ ### Skill Types
2355
+
2356
+ #### SkillConfig
2357
+
2358
+ ```ts
2359
+ interface SkillConfig { [key: string]: unknown }
2360
+ ```
2361
+
2362
+ #### SkillToolDefinition
2363
+
2364
+ | Property | Type | Description |
2365
+ |----------|------|-------------|
2366
+ | `name` | `string` | Unique tool name |
2367
+ | `description` | `string` | Description shown to AI |
2368
+ | `parameters` | `Record<string, unknown>` | Parameter schema |
2369
+ | `handler` | `SwaigHandler` | Handler function |
2370
+ | `secure` | `boolean` | Require secure invocation |
2371
+ | `fillers` | `Record<string, string[]>` | Filler phrases by language |
2372
+ | `required` | `string[]` | Required parameter names |
2373
+
2374
+ #### SkillPromptSection
2375
+
2376
+ | Property | Type | Description |
2377
+ |----------|------|-------------|
2378
+ | `title` | `string` | Section heading |
2379
+ | `body` | `string` | Body text |
2380
+ | `bullets` | `string[]` | Bullet points |
2381
+ | `numbered` | `boolean` | Render bullets as numbered list |
2382
+
2383
+ #### SkillManifest
2384
+
2385
+ | Property | Type | Description |
2386
+ |----------|------|-------------|
2387
+ | `name` | `string` | Unique skill name |
2388
+ | `description` | `string` | Human-readable description |
2389
+ | `version` | `string` | Semantic version |
2390
+ | `author` | `string` | Author or organization |
2391
+ | `tags` | `string[]` | Categorization tags |
2392
+ | `requiredEnvVars` | `string[]` | Required environment variables |
2393
+ | `requiredPackages` | `string[]` | Required npm packages |
2394
+ | `configSchema` | `Record<string, unknown>` | JSON-schema config description |
2395
+
2396
+ ### Payment Types
2397
+
2398
+ #### PaymentPrompt
2399
+
2400
+ | Property | Type | Description |
2401
+ |----------|------|-------------|
2402
+ | `for` | `string` | Situation this prompt applies to |
2403
+ | `actions` | `PaymentAction[]` | Actions for this prompt |
2404
+ | `card_type` | `string` | Optional card type filter |
2405
+ | `error_type` | `string` | Optional error type |
2406
+
2407
+ #### PaymentAction
2408
+
2409
+ | Property | Type | Description |
2410
+ |----------|------|-------------|
2411
+ | `type` | `string` | Action type (e.g., `"say"`, `"play"`) |
2412
+ | `phrase` | `string` | Phrase or URL |
2413
+
2414
+ #### PaymentParameter
2415
+
2416
+ | Property | Type | Description |
2417
+ |----------|------|-------------|
2418
+ | `name` | `string` | Parameter name |
2419
+ | `value` | `string` | Parameter value |