@signalwire/sdk 2.0.5 → 3.5.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 (656) hide show
  1. package/CHANGELOG.md +785 -0
  2. package/LICENSE +21 -0
  3. package/README.md +163 -68
  4. package/dist/AGENTS.md +13 -0
  5. package/dist/AgentBase.d.ts +481 -126
  6. package/dist/AgentBase.js +1502 -438
  7. package/dist/AgentBase.js.map +1 -1
  8. package/dist/AgentServer.d.ts +21 -0
  9. package/dist/AgentServer.js +154 -47
  10. package/dist/AgentServer.js.map +1 -1
  11. package/dist/AuthHandler.d.ts +14 -2
  12. package/dist/AuthHandler.js +7 -2
  13. package/dist/AuthHandler.js.map +1 -1
  14. package/dist/ConfigLoader.d.ts +5 -13
  15. package/dist/ConfigLoader.js +15 -29
  16. package/dist/ConfigLoader.js.map +1 -1
  17. package/dist/ContextBuilder.d.ts +202 -9
  18. package/dist/ContextBuilder.js +219 -36
  19. package/dist/ContextBuilder.js.map +1 -1
  20. package/dist/DataMap.d.ts +158 -45
  21. package/dist/DataMap.js +167 -52
  22. package/dist/DataMap.js.map +1 -1
  23. package/dist/FunctionResult.d.ts +277 -83
  24. package/dist/FunctionResult.js +444 -116
  25. package/dist/FunctionResult.js.map +1 -1
  26. package/dist/Logger.d.ts +30 -5
  27. package/dist/Logger.js +77 -19
  28. package/dist/Logger.js.map +1 -1
  29. package/dist/POM/PromptObjectModel.d.ts +12 -1
  30. package/dist/POM/PromptObjectModel.js +25 -9
  31. package/dist/POM/PromptObjectModel.js.map +1 -1
  32. package/dist/ParameterSchema.d.ts +306 -0
  33. package/dist/ParameterSchema.js +251 -0
  34. package/dist/ParameterSchema.js.map +1 -0
  35. package/dist/PlatformContracts.d.ts +21 -0
  36. package/dist/PlatformContracts.generated.d.ts +109 -0
  37. package/dist/PlatformContracts.generated.js +8 -0
  38. package/dist/PlatformContracts.generated.js.map +1 -0
  39. package/dist/PlatformContracts.js +2 -0
  40. package/dist/PlatformContracts.js.map +1 -0
  41. package/dist/PomBuilder.d.ts +18 -0
  42. package/dist/PomBuilder.js +53 -3
  43. package/dist/PomBuilder.js.map +1 -1
  44. package/dist/PostPrompt.d.ts +110 -0
  45. package/dist/PostPrompt.js +204 -0
  46. package/dist/PostPrompt.js.map +1 -0
  47. package/dist/PromptManager.d.ts +22 -1
  48. package/dist/PromptManager.js +28 -1
  49. package/dist/PromptManager.js.map +1 -1
  50. package/dist/PublicFetch.d.ts +132 -0
  51. package/dist/PublicFetch.js +311 -0
  52. package/dist/PublicFetch.js.map +1 -0
  53. package/dist/RobotsTxt.d.ts +41 -0
  54. package/dist/RobotsTxt.js +152 -0
  55. package/dist/RobotsTxt.js.map +1 -0
  56. package/dist/SWMLHandler.js.map +1 -1
  57. package/dist/SWMLService.d.ts +158 -58
  58. package/dist/SWMLService.js +435 -127
  59. package/dist/SWMLService.js.map +1 -1
  60. package/dist/SchemaUtils.d.ts +115 -2
  61. package/dist/SchemaUtils.js +444 -12
  62. package/dist/SchemaUtils.js.map +1 -1
  63. package/dist/SecurityUtils.d.ts +49 -9
  64. package/dist/SecurityUtils.js +153 -51
  65. package/dist/SecurityUtils.js.map +1 -1
  66. package/dist/ServerlessAdapter.d.ts +156 -7
  67. package/dist/ServerlessAdapter.js +399 -42
  68. package/dist/ServerlessAdapter.js.map +1 -1
  69. package/dist/SessionManager.d.ts +11 -2
  70. package/dist/SessionManager.js +50 -18
  71. package/dist/SessionManager.js.map +1 -1
  72. package/dist/SslConfig.d.ts +2 -1
  73. package/dist/SslConfig.js +4 -1
  74. package/dist/SslConfig.js.map +1 -1
  75. package/dist/SwaigActions.generated.d.ts +23 -0
  76. package/dist/SwaigActions.generated.js +8 -0
  77. package/dist/SwaigActions.generated.js.map +1 -0
  78. package/dist/SwaigContracts.d.ts +15 -0
  79. package/dist/SwaigContracts.generated.d.ts +264 -0
  80. package/dist/SwaigContracts.generated.js +12 -0
  81. package/dist/SwaigContracts.generated.js.map +1 -0
  82. package/dist/SwaigContracts.js +2 -0
  83. package/dist/SwaigContracts.js.map +1 -0
  84. package/dist/SwaigFunction.d.ts +110 -4
  85. package/dist/SwaigFunction.js +151 -19
  86. package/dist/SwaigFunction.js.map +1 -1
  87. package/dist/SwmlBuilder.d.ts +68 -19
  88. package/dist/SwmlBuilder.js +74 -38
  89. package/dist/SwmlBuilder.js.map +1 -1
  90. package/dist/SwmlVerbMethods.generated.d.ts +41 -4
  91. package/dist/SwmlVerbMethods.generated.js +1 -1
  92. package/dist/TypeInference.d.ts +39 -3
  93. package/dist/TypeInference.js +256 -16
  94. package/dist/TypeInference.js.map +1 -1
  95. package/dist/WebService.d.ts +79 -11
  96. package/dist/WebService.js +320 -109
  97. package/dist/WebService.js.map +1 -1
  98. package/dist/WebhookMiddleware.d.ts +119 -0
  99. package/dist/WebhookMiddleware.js +271 -0
  100. package/dist/WebhookMiddleware.js.map +1 -0
  101. package/dist/WebhookValidator.d.ts +92 -0
  102. package/dist/WebhookValidator.js +409 -0
  103. package/dist/WebhookValidator.js.map +1 -0
  104. package/dist/agents/BedrockAgent.d.ts +162 -0
  105. package/dist/agents/BedrockAgent.js +323 -0
  106. package/dist/agents/BedrockAgent.js.map +1 -0
  107. package/dist/ai-chat/AIChatClient.d.ts +316 -0
  108. package/dist/ai-chat/AIChatClient.js +535 -0
  109. package/dist/ai-chat/AIChatClient.js.map +1 -0
  110. package/dist/ai-chat/ChatGateway.d.ts +408 -0
  111. package/dist/ai-chat/ChatGateway.js +747 -0
  112. package/dist/ai-chat/ChatGateway.js.map +1 -0
  113. package/dist/ai-chat/HandoffRouter.d.ts +282 -0
  114. package/dist/ai-chat/HandoffRouter.js +518 -0
  115. package/dist/ai-chat/HandoffRouter.js.map +1 -0
  116. package/dist/ai-chat/index.d.ts +12 -0
  117. package/dist/ai-chat/index.js +10 -0
  118. package/dist/ai-chat/index.js.map +1 -0
  119. package/dist/capabilities.d.ts +64 -0
  120. package/dist/capabilities.js +95 -0
  121. package/dist/capabilities.js.map +1 -0
  122. package/dist/cli/agent-loader.d.ts +32 -6
  123. package/dist/cli/agent-loader.js +92 -33
  124. package/dist/cli/agent-loader.js.map +1 -1
  125. package/dist/cli/datamap-exec.d.ts +175 -0
  126. package/dist/cli/datamap-exec.js +1284 -0
  127. package/dist/cli/datamap-exec.js.map +1 -0
  128. package/dist/cli/function-args.d.ts +40 -0
  129. package/dist/cli/function-args.js +146 -0
  130. package/dist/cli/function-args.js.map +1 -0
  131. package/dist/cli/simulation.d.ts +99 -0
  132. package/dist/cli/simulation.js +490 -0
  133. package/dist/cli/simulation.js.map +1 -0
  134. package/dist/cli/swaig-test.d.ts +12 -25
  135. package/dist/cli/swaig-test.js +935 -371
  136. package/dist/cli/swaig-test.js.map +1 -1
  137. package/dist/cli/tsdocs/agentsNote.d.ts +30 -0
  138. package/dist/cli/tsdocs/agentsNote.js +92 -0
  139. package/dist/cli/tsdocs/agentsNote.js.map +1 -0
  140. package/dist/cli/tsdocs/api-index.json +1 -0
  141. package/dist/cli/tsdocs/api.d.ts +91 -0
  142. package/dist/cli/tsdocs/api.js +372 -0
  143. package/dist/cli/tsdocs/api.js.map +1 -0
  144. package/dist/cli/tsdocs/apiTypes.d.ts +64 -0
  145. package/dist/cli/tsdocs/apiTypes.js +7 -0
  146. package/dist/cli/tsdocs/apiTypes.js.map +1 -0
  147. package/dist/cli/tsdocs/bin.d.ts +6 -0
  148. package/dist/cli/tsdocs/bin.js +23 -0
  149. package/dist/cli/tsdocs/bin.js.map +1 -0
  150. package/dist/cli/tsdocs/files.d.ts +108 -0
  151. package/dist/cli/tsdocs/files.js +287 -0
  152. package/dist/cli/tsdocs/files.js.map +1 -0
  153. package/dist/cli/tsdocs/index.d.ts +28 -0
  154. package/dist/cli/tsdocs/index.js +307 -0
  155. package/dist/cli/tsdocs/index.js.map +1 -0
  156. package/dist/cli/tsdocs/live.d.ts +41 -0
  157. package/dist/cli/tsdocs/live.js +202 -0
  158. package/dist/cli/tsdocs/live.js.map +1 -0
  159. package/dist/cli/tsdocs/locate.d.ts +51 -0
  160. package/dist/cli/tsdocs/locate.js +75 -0
  161. package/dist/cli/tsdocs/locate.js.map +1 -0
  162. package/dist/cli/tsdocs/render.d.ts +75 -0
  163. package/dist/cli/tsdocs/render.js +323 -0
  164. package/dist/cli/tsdocs/render.js.map +1 -0
  165. package/dist/cli/tsdocs/topics.d.ts +43 -0
  166. package/dist/cli/tsdocs/topics.js +916 -0
  167. package/dist/cli/tsdocs/topics.js.map +1 -0
  168. package/dist/index.d.ts +47 -68
  169. package/dist/index.js +44 -73
  170. package/dist/index.js.map +1 -1
  171. package/dist/livewire/index.d.ts +229 -155
  172. package/dist/livewire/index.js +298 -195
  173. package/dist/livewire/index.js.map +1 -1
  174. package/dist/llms.txt +65 -0
  175. package/dist/prefabs/CallSessionStore.d.ts +52 -0
  176. package/dist/prefabs/CallSessionStore.js +72 -0
  177. package/dist/prefabs/CallSessionStore.js.map +1 -0
  178. package/dist/prefabs/ConciergeAgent.d.ts +13 -1
  179. package/dist/prefabs/ConciergeAgent.js +36 -31
  180. package/dist/prefabs/ConciergeAgent.js.map +1 -1
  181. package/dist/prefabs/FAQBotAgent.d.ts +9 -1
  182. package/dist/prefabs/FAQBotAgent.js +113 -47
  183. package/dist/prefabs/FAQBotAgent.js.map +1 -1
  184. package/dist/prefabs/InfoGathererAgent.d.ts +22 -3
  185. package/dist/prefabs/InfoGathererAgent.js +67 -58
  186. package/dist/prefabs/InfoGathererAgent.js.map +1 -1
  187. package/dist/prefabs/ReceptionistAgent.d.ts +16 -5
  188. package/dist/prefabs/ReceptionistAgent.js +39 -31
  189. package/dist/prefabs/ReceptionistAgent.js.map +1 -1
  190. package/dist/prefabs/SurveyAgent.d.ts +22 -4
  191. package/dist/prefabs/SurveyAgent.js +84 -68
  192. package/dist/prefabs/SurveyAgent.js.map +1 -1
  193. package/dist/relay/Action.d.ts +44 -21
  194. package/dist/relay/Action.js +75 -17
  195. package/dist/relay/Action.js.map +1 -1
  196. package/dist/relay/Call.d.ts +312 -47
  197. package/dist/relay/Call.js +369 -18
  198. package/dist/relay/Call.js.map +1 -1
  199. package/dist/relay/Deferred.js.map +1 -1
  200. package/dist/relay/Message.d.ts +26 -5
  201. package/dist/relay/Message.js +36 -6
  202. package/dist/relay/Message.js.map +1 -1
  203. package/dist/relay/RelayClient.d.ts +44 -17
  204. package/dist/relay/RelayClient.js +175 -65
  205. package/dist/relay/RelayClient.js.map +1 -1
  206. package/dist/relay/RelayError.d.ts +14 -0
  207. package/dist/relay/RelayError.js +15 -0
  208. package/dist/relay/RelayError.js.map +1 -1
  209. package/dist/relay/RelayEvent.d.ts +96 -65
  210. package/dist/relay/RelayEvent.js +85 -56
  211. package/dist/relay/RelayEvent.js.map +1 -1
  212. package/dist/relay/closedSets.d.ts +111 -0
  213. package/dist/relay/closedSets.js +83 -0
  214. package/dist/relay/closedSets.js.map +1 -0
  215. package/dist/relay/index.d.ts +3 -1
  216. package/dist/relay/index.js +1 -0
  217. package/dist/relay/index.js.map +1 -1
  218. package/dist/relay/normalize.js.map +1 -1
  219. package/dist/relay/protocol.types.generated.d.ts +1195 -0
  220. package/dist/relay/protocol.types.generated.js +8 -0
  221. package/dist/relay/protocol.types.generated.js.map +1 -0
  222. package/dist/relay/types.d.ts +73 -42
  223. package/dist/rest/HttpClient.d.ts +36 -8
  224. package/dist/rest/HttpClient.js +233 -40
  225. package/dist/rest/HttpClient.js.map +1 -1
  226. package/dist/rest/RequestOptions.d.ts +110 -0
  227. package/dist/rest/RequestOptions.js +113 -0
  228. package/dist/rest/RequestOptions.js.map +1 -0
  229. package/dist/rest/RestError.d.ts +52 -6
  230. package/dist/rest/RestError.js +89 -5
  231. package/dist/rest/RestError.js.map +1 -1
  232. package/dist/rest/base/CrudResource.d.ts +16 -26
  233. package/dist/rest/base/CrudResource.js +19 -33
  234. package/dist/rest/base/CrudResource.js.map +1 -1
  235. package/dist/rest/base/CrudWithAddresses.d.ts +3 -2
  236. package/dist/rest/base/CrudWithAddresses.js +2 -2
  237. package/dist/rest/base/CrudWithAddresses.js.map +1 -1
  238. package/dist/rest/base/FabricResource.d.ts +15 -0
  239. package/dist/rest/base/FabricResource.js +16 -0
  240. package/dist/rest/base/FabricResource.js.map +1 -0
  241. package/dist/rest/base/ReadResource.d.ts +62 -0
  242. package/dist/rest/base/ReadResource.js +69 -0
  243. package/dist/rest/base/ReadResource.js.map +1 -0
  244. package/dist/rest/callHandler.d.ts +5 -2
  245. package/dist/rest/callHandler.js +4 -1
  246. package/dist/rest/callHandler.js.map +1 -1
  247. package/dist/rest/index.d.ts +18 -77
  248. package/dist/rest/index.js +47 -120
  249. package/dist/rest/index.js.map +1 -1
  250. package/dist/rest/namespaces/_client_tree_generated.d.ts +103 -0
  251. package/dist/rest/namespaces/_client_tree_generated.js +171 -0
  252. package/dist/rest/namespaces/_client_tree_generated.js.map +1 -0
  253. package/dist/rest/namespaces/addresses.d.ts +3 -42
  254. package/dist/rest/namespaces/addresses.js +3 -50
  255. package/dist/rest/namespaces/addresses.js.map +1 -1
  256. package/dist/rest/namespaces/calling.d.ts +6 -378
  257. package/dist/rest/namespaces/calling.js +6 -473
  258. package/dist/rest/namespaces/calling.js.map +1 -1
  259. package/dist/rest/namespaces/calling.resources.generated.d.ts +165 -0
  260. package/dist/rest/namespaces/calling.resources.generated.js +477 -0
  261. package/dist/rest/namespaces/calling.resources.generated.js.map +1 -0
  262. package/dist/rest/namespaces/calling.types.generated.d.ts +2917 -0
  263. package/dist/rest/namespaces/calling.types.generated.js +8 -0
  264. package/dist/rest/namespaces/calling.types.generated.js.map +1 -0
  265. package/dist/rest/namespaces/chat.d.ts +4 -18
  266. package/dist/rest/namespaces/chat.js +4 -21
  267. package/dist/rest/namespaces/chat.js.map +1 -1
  268. package/dist/rest/namespaces/chat.resources.generated.d.ts +12 -0
  269. package/dist/rest/namespaces/chat.resources.generated.js +29 -0
  270. package/dist/rest/namespaces/chat.resources.generated.js.map +1 -0
  271. package/dist/rest/namespaces/chat.types.generated.d.ts +56 -0
  272. package/dist/rest/namespaces/chat.types.generated.js +8 -0
  273. package/dist/rest/namespaces/chat.types.generated.js.map +1 -0
  274. package/dist/rest/namespaces/datasphere.d.ts +6 -62
  275. package/dist/rest/namespaces/datasphere.js +6 -72
  276. package/dist/rest/namespaces/datasphere.js.map +1 -1
  277. package/dist/rest/namespaces/datasphere.resources.generated.d.ts +25 -0
  278. package/dist/rest/namespaces/datasphere.resources.generated.js +50 -0
  279. package/dist/rest/namespaces/datasphere.resources.generated.js.map +1 -0
  280. package/dist/rest/namespaces/datasphere.types.generated.d.ts +180 -0
  281. package/dist/rest/namespaces/datasphere.types.generated.js +8 -0
  282. package/dist/rest/namespaces/datasphere.types.generated.js.map +1 -0
  283. package/dist/rest/namespaces/fabric.d.ts +11 -327
  284. package/dist/rest/namespaces/fabric.js +14 -439
  285. package/dist/rest/namespaces/fabric.js.map +1 -1
  286. package/dist/rest/namespaces/fabric.resources.generated.d.ts +195 -0
  287. package/dist/rest/namespaces/fabric.resources.generated.js +399 -0
  288. package/dist/rest/namespaces/fabric.resources.generated.js.map +1 -0
  289. package/dist/rest/namespaces/fabric.types.generated.d.ts +4557 -0
  290. package/dist/rest/namespaces/fabric.types.generated.js +8 -0
  291. package/dist/rest/namespaces/fabric.types.generated.js.map +1 -0
  292. package/dist/rest/namespaces/fax.resources.generated.d.ts +6 -0
  293. package/dist/rest/namespaces/fax.resources.generated.js +14 -0
  294. package/dist/rest/namespaces/fax.resources.generated.js.map +1 -0
  295. package/dist/rest/namespaces/fax.types.generated.d.ts +131 -0
  296. package/dist/rest/namespaces/fax.types.generated.js +8 -0
  297. package/dist/rest/namespaces/fax.types.generated.js.map +1 -0
  298. package/dist/rest/namespaces/imported-numbers.d.ts +3 -18
  299. package/dist/rest/namespaces/imported-numbers.js +3 -21
  300. package/dist/rest/namespaces/imported-numbers.js.map +1 -1
  301. package/dist/rest/namespaces/logs.d.ts +10 -101
  302. package/dist/rest/namespaces/logs.js +10 -128
  303. package/dist/rest/namespaces/logs.js.map +1 -1
  304. package/dist/rest/namespaces/logs.resources.generated.d.ts +9 -0
  305. package/dist/rest/namespaces/logs.resources.generated.js +17 -0
  306. package/dist/rest/namespaces/logs.resources.generated.js.map +1 -0
  307. package/dist/rest/namespaces/logs.types.generated.d.ts +131 -0
  308. package/dist/rest/namespaces/logs.types.generated.js +8 -0
  309. package/dist/rest/namespaces/logs.types.generated.js.map +1 -0
  310. package/dist/rest/namespaces/lookup.d.ts +3 -25
  311. package/dist/rest/namespaces/lookup.js +3 -27
  312. package/dist/rest/namespaces/lookup.js.map +1 -1
  313. package/dist/rest/namespaces/message.resources.generated.d.ts +6 -0
  314. package/dist/rest/namespaces/message.resources.generated.js +14 -0
  315. package/dist/rest/namespaces/message.resources.generated.js.map +1 -0
  316. package/dist/rest/namespaces/message.types.generated.d.ts +122 -0
  317. package/dist/rest/namespaces/message.types.generated.js +8 -0
  318. package/dist/rest/namespaces/message.types.generated.js.map +1 -0
  319. package/dist/rest/namespaces/messages.resources.generated.d.ts +18 -0
  320. package/dist/rest/namespaces/messages.resources.generated.js +44 -0
  321. package/dist/rest/namespaces/messages.resources.generated.js.map +1 -0
  322. package/dist/rest/namespaces/messages.types.generated.d.ts +99 -0
  323. package/dist/rest/namespaces/messages.types.generated.js +8 -0
  324. package/dist/rest/namespaces/messages.types.generated.js.map +1 -0
  325. package/dist/rest/namespaces/mfa.d.ts +3 -42
  326. package/dist/rest/namespaces/mfa.js +3 -49
  327. package/dist/rest/namespaces/mfa.js.map +1 -1
  328. package/dist/rest/namespaces/number-groups.d.ts +3 -45
  329. package/dist/rest/namespaces/number-groups.js +3 -53
  330. package/dist/rest/namespaces/number-groups.js.map +1 -1
  331. package/dist/rest/namespaces/phone-numbers.d.ts +8 -196
  332. package/dist/rest/namespaces/phone-numbers.js +8 -230
  333. package/dist/rest/namespaces/phone-numbers.js.map +1 -1
  334. package/dist/rest/namespaces/project.d.ts +6 -42
  335. package/dist/rest/namespaces/project.js +6 -51
  336. package/dist/rest/namespaces/project.js.map +1 -1
  337. package/dist/rest/namespaces/project.resources.generated.d.ts +17 -0
  338. package/dist/rest/namespaces/project.resources.generated.js +44 -0
  339. package/dist/rest/namespaces/project.resources.generated.js.map +1 -0
  340. package/dist/rest/namespaces/project.types.generated.d.ts +58 -0
  341. package/dist/rest/namespaces/project.types.generated.js +8 -0
  342. package/dist/rest/namespaces/project.types.generated.js.map +1 -0
  343. package/dist/rest/namespaces/projects.resources.generated.d.ts +12 -0
  344. package/dist/rest/namespaces/projects.resources.generated.js +25 -0
  345. package/dist/rest/namespaces/projects.resources.generated.js.map +1 -0
  346. package/dist/rest/namespaces/projects.types.generated.d.ts +77 -0
  347. package/dist/rest/namespaces/projects.types.generated.js +8 -0
  348. package/dist/rest/namespaces/projects.types.generated.js.map +1 -0
  349. package/dist/rest/namespaces/pubsub.d.ts +4 -18
  350. package/dist/rest/namespaces/pubsub.js +4 -21
  351. package/dist/rest/namespaces/pubsub.js.map +1 -1
  352. package/dist/rest/namespaces/pubsub.resources.generated.d.ts +12 -0
  353. package/dist/rest/namespaces/pubsub.resources.generated.js +29 -0
  354. package/dist/rest/namespaces/pubsub.resources.generated.js.map +1 -0
  355. package/dist/rest/namespaces/pubsub.types.generated.d.ts +60 -0
  356. package/dist/rest/namespaces/pubsub.types.generated.js +8 -0
  357. package/dist/rest/namespaces/pubsub.types.generated.js.map +1 -0
  358. package/dist/rest/namespaces/queues.d.ts +3 -38
  359. package/dist/rest/namespaces/queues.js +3 -44
  360. package/dist/rest/namespaces/queues.js.map +1 -1
  361. package/dist/rest/namespaces/recordings.d.ts +3 -34
  362. package/dist/rest/namespaces/recordings.js +3 -40
  363. package/dist/rest/namespaces/recordings.js.map +1 -1
  364. package/dist/rest/namespaces/registry.d.ts +6 -137
  365. package/dist/rest/namespaces/registry.js +6 -173
  366. package/dist/rest/namespaces/registry.js.map +1 -1
  367. package/dist/rest/namespaces/relay-rest.resources.generated.d.ts +168 -0
  368. package/dist/rest/namespaces/relay-rest.resources.generated.js +430 -0
  369. package/dist/rest/namespaces/relay-rest.resources.generated.js.map +1 -0
  370. package/dist/rest/namespaces/relay-rest.types.generated.d.ts +1906 -0
  371. package/dist/rest/namespaces/relay-rest.types.generated.js +8 -0
  372. package/dist/rest/namespaces/relay-rest.types.generated.js.map +1 -0
  373. package/dist/rest/namespaces/short-codes.d.ts +3 -35
  374. package/dist/rest/namespaces/short-codes.js +3 -41
  375. package/dist/rest/namespaces/short-codes.js.map +1 -1
  376. package/dist/rest/namespaces/sip-profile.d.ts +3 -24
  377. package/dist/rest/namespaces/sip-profile.js +3 -29
  378. package/dist/rest/namespaces/sip-profile.js.map +1 -1
  379. package/dist/rest/namespaces/verified-callers.d.ts +3 -29
  380. package/dist/rest/namespaces/verified-callers.js +3 -34
  381. package/dist/rest/namespaces/verified-callers.js.map +1 -1
  382. package/dist/rest/namespaces/video.d.ts +10 -227
  383. package/dist/rest/namespaces/video.js +10 -288
  384. package/dist/rest/namespaces/video.js.map +1 -1
  385. package/dist/rest/namespaces/video.resources.generated.d.ts +81 -0
  386. package/dist/rest/namespaces/video.resources.generated.js +171 -0
  387. package/dist/rest/namespaces/video.resources.generated.js.map +1 -0
  388. package/dist/rest/namespaces/video.types.generated.d.ts +771 -0
  389. package/dist/rest/namespaces/video.types.generated.js +8 -0
  390. package/dist/rest/namespaces/video.types.generated.js.map +1 -0
  391. package/dist/rest/namespaces/voice.resources.generated.d.ts +9 -0
  392. package/dist/rest/namespaces/voice.resources.generated.js +17 -0
  393. package/dist/rest/namespaces/voice.resources.generated.js.map +1 -0
  394. package/dist/rest/namespaces/voice.types.generated.d.ts +214 -0
  395. package/dist/rest/namespaces/voice.types.generated.js +8 -0
  396. package/dist/rest/namespaces/voice.types.generated.js.map +1 -0
  397. package/dist/rest/pagination.d.ts +5 -1
  398. package/dist/rest/pagination.js +40 -20
  399. package/dist/rest/pagination.js.map +1 -1
  400. package/dist/rest/types.d.ts +21 -3
  401. package/dist/schema.json +299 -98
  402. package/dist/skills/SkillBase.d.ts +97 -20
  403. package/dist/skills/SkillBase.js +100 -17
  404. package/dist/skills/SkillBase.js.map +1 -1
  405. package/dist/skills/SkillManager.d.ts +66 -13
  406. package/dist/skills/SkillManager.js +101 -20
  407. package/dist/skills/SkillManager.js.map +1 -1
  408. package/dist/skills/SkillName.d.ts +44 -0
  409. package/dist/skills/SkillName.js +2 -0
  410. package/dist/skills/SkillName.js.map +1 -0
  411. package/dist/skills/SkillRegistry.d.ts +22 -11
  412. package/dist/skills/SkillRegistry.js +47 -17
  413. package/dist/skills/SkillRegistry.js.map +1 -1
  414. package/dist/skills/builtin/api_ninjas_trivia.d.ts +3 -1
  415. package/dist/skills/builtin/api_ninjas_trivia.js +18 -6
  416. package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -1
  417. package/dist/skills/builtin/ask_claude.d.ts +14 -4
  418. package/dist/skills/builtin/ask_claude.js +36 -14
  419. package/dist/skills/builtin/ask_claude.js.map +1 -1
  420. package/dist/skills/builtin/claude_skills.d.ts +3 -1
  421. package/dist/skills/builtin/claude_skills.js +19 -15
  422. package/dist/skills/builtin/claude_skills.js.map +1 -1
  423. package/dist/skills/builtin/custom_skills.d.ts +10 -3
  424. package/dist/skills/builtin/custom_skills.js +26 -9
  425. package/dist/skills/builtin/custom_skills.js.map +1 -1
  426. package/dist/skills/builtin/datasphere.d.ts +5 -3
  427. package/dist/skills/builtin/datasphere.js +21 -22
  428. package/dist/skills/builtin/datasphere.js.map +1 -1
  429. package/dist/skills/builtin/datasphere_serverless.d.ts +12 -1
  430. package/dist/skills/builtin/datasphere_serverless.js +17 -6
  431. package/dist/skills/builtin/datasphere_serverless.js.map +1 -1
  432. package/dist/skills/builtin/datetime.d.ts +3 -1
  433. package/dist/skills/builtin/datetime.js +11 -7
  434. package/dist/skills/builtin/datetime.js.map +1 -1
  435. package/dist/skills/builtin/google_maps.d.ts +29 -14
  436. package/dist/skills/builtin/google_maps.js +89 -269
  437. package/dist/skills/builtin/google_maps.js.map +1 -1
  438. package/dist/skills/builtin/index.d.ts +8 -6
  439. package/dist/skills/builtin/index.js +8 -6
  440. package/dist/skills/builtin/index.js.map +1 -1
  441. package/dist/skills/builtin/info_gatherer.d.ts +4 -2
  442. package/dist/skills/builtin/info_gatherer.js +20 -12
  443. package/dist/skills/builtin/info_gatherer.js.map +1 -1
  444. package/dist/skills/builtin/joke.d.ts +16 -6
  445. package/dist/skills/builtin/joke.js +54 -37
  446. package/dist/skills/builtin/joke.js.map +1 -1
  447. package/dist/skills/builtin/math.d.ts +3 -1
  448. package/dist/skills/builtin/math.js +14 -9
  449. package/dist/skills/builtin/math.js.map +1 -1
  450. package/dist/skills/builtin/mcp_gateway.d.ts +34 -5
  451. package/dist/skills/builtin/mcp_gateway.js +77 -46
  452. package/dist/skills/builtin/mcp_gateway.js.map +1 -1
  453. package/dist/skills/builtin/native_vector_search.d.ts +19 -5
  454. package/dist/skills/builtin/native_vector_search.js +179 -61
  455. package/dist/skills/builtin/native_vector_search.js.map +1 -1
  456. package/dist/skills/builtin/play_background_file.d.ts +21 -15
  457. package/dist/skills/builtin/play_background_file.js +43 -122
  458. package/dist/skills/builtin/play_background_file.js.map +1 -1
  459. package/dist/skills/builtin/spider.d.ts +42 -4
  460. package/dist/skills/builtin/spider.js +277 -104
  461. package/dist/skills/builtin/spider.js.map +1 -1
  462. package/dist/skills/builtin/swml_transfer.d.ts +14 -3
  463. package/dist/skills/builtin/swml_transfer.js +45 -24
  464. package/dist/skills/builtin/swml_transfer.js.map +1 -1
  465. package/dist/skills/builtin/weather_api.d.ts +24 -13
  466. package/dist/skills/builtin/weather_api.js +38 -30
  467. package/dist/skills/builtin/weather_api.js.map +1 -1
  468. package/dist/skills/builtin/web_search.d.ts +48 -10
  469. package/dist/skills/builtin/web_search.js +294 -100
  470. package/dist/skills/builtin/web_search.js.map +1 -1
  471. package/dist/skills/builtin/wikipedia_search.d.ts +4 -2
  472. package/dist/skills/builtin/wikipedia_search.js +14 -13
  473. package/dist/skills/builtin/wikipedia_search.js.map +1 -1
  474. package/dist/skills/index.d.ts +3 -2
  475. package/dist/skills/index.js +1 -1
  476. package/dist/skills/index.js.map +1 -1
  477. package/dist/swml_verbs_generated.d.ts +2824 -0
  478. package/dist/swml_verbs_generated.js +12 -0
  479. package/dist/swml_verbs_generated.js.map +1 -0
  480. package/dist/types.d.ts +59 -6
  481. package/dist/web.d.ts +27 -0
  482. package/dist/web.js +20 -0
  483. package/dist/web.js.map +1 -0
  484. package/docs/agent-guide.md +1034 -0
  485. package/docs/ai_chat.md +560 -0
  486. package/docs/api-reference.md +3534 -0
  487. package/docs/architecture.md +846 -0
  488. package/docs/bedrock_agent.md +411 -0
  489. package/docs/cli-guide.md +403 -0
  490. package/docs/cloud_functions_guide.md +399 -0
  491. package/docs/configuration.md +548 -0
  492. package/docs/contexts-guide.md +884 -0
  493. package/docs/datamap-guide.md +1160 -0
  494. package/docs/developer_pain_points.md +548 -0
  495. package/docs/llm_parameters.md +298 -0
  496. package/docs/mcp_gateway_reference.md +354 -0
  497. package/docs/mcp_integration.md +162 -0
  498. package/docs/pgi_agent_guide.md +1820 -0
  499. package/docs/prefabs-guide.md +815 -0
  500. package/docs/programmatically_governed_inference.md +301 -0
  501. package/docs/sdk_features.md +501 -0
  502. package/docs/security.md +559 -0
  503. package/docs/serverless-guide.md +520 -0
  504. package/docs/skills-guide.md +1223 -0
  505. package/docs/skills-system.md +405 -0
  506. package/docs/skills_parameter_schema.md +417 -0
  507. package/docs/swaig-reference.md +1938 -0
  508. package/docs/swml_service_guide.md +573 -0
  509. package/docs/third_party_skills.md +410 -0
  510. package/docs/web_service.md +666 -0
  511. package/examples/README.md +202 -0
  512. package/examples/advanced-datamap.ts +108 -0
  513. package/examples/advanced-dynamic-config.ts +70 -0
  514. package/examples/auto-vivified.ts +95 -0
  515. package/examples/call-flow.ts +65 -0
  516. package/examples/comprehensive-dynamic.ts +125 -0
  517. package/examples/contexts-steps.ts +65 -0
  518. package/examples/custom-path.ts +45 -0
  519. package/examples/datamap-tools.ts +51 -0
  520. package/examples/datasphere-multi-instance.ts +66 -0
  521. package/examples/datasphere-serverless-env.ts +87 -0
  522. package/examples/datasphere-webhook-env.ts +65 -0
  523. package/examples/datasphere.ts +56 -0
  524. package/examples/declarative.ts +100 -0
  525. package/examples/dynamic-config.ts +54 -0
  526. package/examples/dynamic-info-gatherer.ts +69 -0
  527. package/examples/dynamic-swml-service.ts +67 -0
  528. package/examples/gather-info.ts +95 -0
  529. package/examples/gather-per-question-functions-demo.ts +139 -0
  530. package/examples/joke-agent.ts +34 -0
  531. package/examples/kubernetes-agent.ts +45 -0
  532. package/examples/llm-params.ts +75 -0
  533. package/examples/mcp-agent.ts +89 -0
  534. package/examples/mcp-gateway.ts +81 -0
  535. package/examples/multi-agent.ts +80 -0
  536. package/examples/multi-endpoint.ts +79 -0
  537. package/examples/pgi/case-domain.ts +114 -0
  538. package/examples/pgi/serve.ts +16 -0
  539. package/examples/pgi/support-agent.ts +265 -0
  540. package/examples/pom-prompt.ts +70 -0
  541. package/examples/prefab-concierge.ts +42 -0
  542. package/examples/prefab-faq.ts +58 -0
  543. package/examples/prefab-info-gatherer.ts +33 -0
  544. package/examples/prefab-receptionist.ts +36 -0
  545. package/examples/prefab-survey.ts +69 -0
  546. package/examples/quickstart-agent.ts +29 -0
  547. package/examples/quickstart-relay.ts +25 -0
  548. package/examples/quickstart-rest.ts +25 -0
  549. package/examples/record-call.ts +65 -0
  550. package/examples/relay-demo.ts +33 -0
  551. package/examples/room-and-sip.ts +93 -0
  552. package/examples/serverless-lambda.ts +43 -0
  553. package/examples/session-state.ts +83 -0
  554. package/examples/simple-agent.ts +36 -0
  555. package/examples/simple-static.ts +29 -0
  556. package/examples/skills-demo.ts +41 -0
  557. package/examples/step-function-inheritance-demo.ts +124 -0
  558. package/examples/swaig-features.ts +193 -0
  559. package/examples/swml-service-routing.ts +66 -0
  560. package/examples/swml-service.ts +38 -0
  561. package/examples/swmlservice_ai_sidecar.ts +104 -0
  562. package/examples/swmlservice_swaig_standalone.ts +79 -0
  563. package/examples/tap.ts +67 -0
  564. package/examples/typed-tools.ts +68 -0
  565. package/examples/verb-methods.ts +45 -0
  566. package/examples/web-search-multi-instance.ts +75 -0
  567. package/examples/web-search.ts +38 -0
  568. package/examples/wikipedia.ts +36 -0
  569. package/livewire/README.md +164 -0
  570. package/livewire/docs/migration-guide.md +251 -0
  571. package/livewire/examples/livewire-basic-agent.ts +74 -0
  572. package/livewire/examples/livewire-handoff.ts +196 -0
  573. package/livewire/examples/livewire-multi-tool.ts +121 -0
  574. package/package.json +85 -13
  575. package/relay/README.md +101 -0
  576. package/relay/docs/call-methods.md +622 -0
  577. package/relay/docs/client-reference.md +281 -0
  578. package/relay/docs/events.md +193 -0
  579. package/relay/docs/getting-started.md +221 -0
  580. package/relay/docs/guide.md +386 -0
  581. package/relay/docs/messaging.md +246 -0
  582. package/relay/examples/relay-inbound.ts +66 -0
  583. package/relay/examples/relay-messaging.ts +74 -0
  584. package/relay/examples/relay-outbound.ts +76 -0
  585. package/rest/README.md +141 -0
  586. package/rest/docs/calling.md +313 -0
  587. package/rest/docs/client-reference.md +149 -0
  588. package/rest/docs/fabric.md +192 -0
  589. package/rest/docs/getting-started.md +138 -0
  590. package/rest/docs/guide.md +421 -0
  591. package/rest/docs/namespaces.md +367 -0
  592. package/rest/docs/phone-binding.md +116 -0
  593. package/rest/examples/rest-10dlc-registration.ts +177 -0
  594. package/rest/examples/rest-bind-phone-to-swml-webhook.ts +66 -0
  595. package/rest/examples/rest-calling-ivr-and-ai.ts +136 -0
  596. package/rest/examples/rest-calling-play-and-record.ts +98 -0
  597. package/rest/examples/rest-client.ts +59 -0
  598. package/rest/examples/rest-datasphere-search.ts +81 -0
  599. package/rest/examples/rest-fabric-conferences-and-routing.ts +147 -0
  600. package/rest/examples/rest-fabric-subscribers-and-sip.ts +106 -0
  601. package/rest/examples/rest-fabric-swml-and-callflows.ts +101 -0
  602. package/rest/examples/rest-manage-resources.ts +64 -0
  603. package/rest/examples/rest-phone-number-management.ts +200 -0
  604. package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
  605. package/rest/examples/rest-video-rooms.ts +186 -0
  606. package/tutorial/fred/fred.ts +218 -0
  607. package/tutorial/fred/tutorial/01-introduction.md +141 -0
  608. package/tutorial/fred/tutorial/02-setup.md +304 -0
  609. package/tutorial/fred/tutorial/03-basic-agent.md +284 -0
  610. package/tutorial/fred/tutorial/04-wikipedia-skill.md +298 -0
  611. package/tutorial/fred/tutorial/05-custom-functions.md +347 -0
  612. package/tutorial/fred/tutorial/06-running-testing.md +642 -0
  613. package/tutorial/fred/tutorial/README.md +56 -0
  614. package/tutorial/fred/tutorial/appendix-complete-code.md +632 -0
  615. package/tutorial/fred/tutorial/appendix-docker-deployment.md +504 -0
  616. package/tutorial/full-guardrails-agent/handlers.ts +436 -0
  617. package/tutorial/full-guardrails-agent/penny.ts +305 -0
  618. package/tutorial/full-guardrails-agent/reservations.ts +1109 -0
  619. package/tutorial/full-guardrails-agent/tutorial/01-why-guardrails.md +149 -0
  620. package/tutorial/full-guardrails-agent/tutorial/02-design-first.md +139 -0
  621. package/tutorial/full-guardrails-agent/tutorial/03-rules-first.md +422 -0
  622. package/tutorial/full-guardrails-agent/tutorial/04-the-shell.md +238 -0
  623. package/tutorial/full-guardrails-agent/tutorial/05-steps-and-scoping.md +247 -0
  624. package/tutorial/full-guardrails-agent/tutorial/06-tools-that-decide.md +467 -0
  625. package/tutorial/full-guardrails-agent/tutorial/07-gather-and-projection.md +160 -0
  626. package/tutorial/full-guardrails-agent/tutorial/08-the-verification-gate.md +333 -0
  627. package/tutorial/full-guardrails-agent/tutorial/09-people-and-endings.md +313 -0
  628. package/tutorial/full-guardrails-agent/tutorial/10-testing-and-running.md +387 -0
  629. package/tutorial/full-guardrails-agent/tutorial/README.md +106 -0
  630. package/tutorial/full-guardrails-agent/tutorial/appendix-complete-code.md +2207 -0
  631. package/tutorial/full-guardrails-agent/tutorial/appendix-deployment.md +191 -0
  632. package/tutorial/full-guardrails-agent/tutorial/appendix-technique-map.md +117 -0
  633. package/tutorial/full-guardrails-agent/workflow.ts +219 -0
  634. package/tutorial/multi_agents/README.md +175 -0
  635. package/tutorial/multi_agents/advanced_agent.ts +395 -0
  636. package/tutorial/multi_agents/extending_agents.ts +641 -0
  637. package/tutorial/multi_agents/knowledge.ts +59 -0
  638. package/tutorial/multi_agents/lesson1_first_agent.md +368 -0
  639. package/tutorial/multi_agents/lesson2_knowledge_bases.md +404 -0
  640. package/tutorial/multi_agents/lesson3_multi_agent_systems.md +621 -0
  641. package/tutorial/multi_agents/lesson4_advanced_features.md +805 -0
  642. package/tutorial/multi_agents/lesson5_extending_agents.md +856 -0
  643. package/tutorial/multi_agents/pc_builder.ts +529 -0
  644. package/tutorial/multi_agents/sales_agent.ts +88 -0
  645. package/tutorial/multi_agents/sales_agent_with_search.ts +116 -0
  646. package/tutorial/multi_agents/sales_knowledge.md +139 -0
  647. package/tutorial/multi_agents/support_knowledge.md +256 -0
  648. package/dist/cli/mock-data.d.ts +0 -37
  649. package/dist/cli/mock-data.js +0 -80
  650. package/dist/cli/mock-data.js.map +0 -1
  651. package/dist/generateVerbTypes.d.ts +0 -11
  652. package/dist/generateVerbTypes.js +0 -265
  653. package/dist/generateVerbTypes.js.map +0 -1
  654. package/dist/rest/namespaces/compat.d.ts +0 -585
  655. package/dist/rest/namespaces/compat.js +0 -735
  656. package/dist/rest/namespaces/compat.js.map +0 -1
@@ -0,0 +1,3534 @@
1
+ # API Reference
2
+
3
+ This page lists the classes, functions and types you use to build agents with the SignalWire AI Agents TypeScript SDK. Every name on it is exported from `@signalwire/sdk`. The RELAY client and the REST client have their own references: see [relay/docs/client-reference.md](../relay/docs/client-reference.md) and [rest/docs/client-reference.md](../rest/docs/client-reference.md). For non-AI call flows, see the [SWMLService guide](swml_service_guide.md).
4
+
5
+ The examples on this page share a setup block that declares the agents they use:
6
+
7
+ <!-- snippet-setup -->
8
+ ```ts
9
+ export {}; // treat each runnable example as a module
10
+ // Shared instances the runnable fragments on this page assume.
11
+ // Ambient import()-types avoid clashing with the per-section `import { ... }` blocks.
12
+ declare const agent: import('@signalwire/sdk').AgentBase;
13
+ declare const agent1: import('@signalwire/sdk').AgentBase;
14
+ declare const agent2: import('@signalwire/sdk').AgentBase;
15
+ ```
16
+
17
+ ---
18
+
19
+ ## Table of Contents
20
+
21
+ The page covers these classes, functions and types:
22
+
23
+ - [AgentBase](#agentbase)
24
+ - [Constructor](#agentbase-constructor)
25
+ - [Static Members](#agentbase-static-members)
26
+ - [Public Properties](#agentbase-public-properties)
27
+ - [Prompt Methods](#prompt-methods)
28
+ - [Tool Methods](#tool-methods)
29
+ - [Speech and Language Methods](#speech-and-language-methods)
30
+ - [AI Configuration Methods](#ai-configuration-methods)
31
+ - [Call Flow Methods](#call-flow-methods)
32
+ - [Context Methods](#context-methods)
33
+ - [Skill Methods](#skill-methods)
34
+ - [Per-Request Configuration Methods](#per-request-configuration-methods)
35
+ - [SIP Routing and MCP Methods](#sip-routing-and-mcp-methods)
36
+ - [URL and Proxy Methods](#url-and-proxy-methods)
37
+ - [Server Methods](#server-methods)
38
+ - [Utility Methods](#utility-methods)
39
+ - [Lifecycle Hooks](#lifecycle-hooks)
40
+ - [AgentServer](#agentserver)
41
+ - [FunctionResult](#functionresult)
42
+ - [Constructor](#functionresult-constructor)
43
+ - [Core Methods](#functionresult-core-methods)
44
+ - [Call Control Actions](#call-control-actions)
45
+ - [Audio Actions](#audio-actions)
46
+ - [Speech Actions](#speech-actions)
47
+ - [Data Actions](#data-actions)
48
+ - [SWML Actions](#swml-actions)
49
+ - [Function Actions](#function-actions)
50
+ - [Communication Actions](#communication-actions)
51
+ - [Room and Conference Actions](#room-and-conference-actions)
52
+ - [RPC Actions](#rpc-actions)
53
+ - [Payment Actions](#payment-actions)
54
+ - [Static Helpers](#functionresult-static-helpers)
55
+ - [Serialization](#functionresult-serialization)
56
+ - [SwaigFunction](#swaigfunction)
57
+ - [DataMap](#datamap)
58
+ - [Constructor](#datamap-constructor)
59
+ - [Configuration Methods](#datamap-configuration-methods)
60
+ - [Webhook Methods](#datamap-webhook-methods)
61
+ - [Output Methods](#datamap-output-methods)
62
+ - [Registration and Serialization](#datamap-registration-and-serialization)
63
+ - [Module Functions](#datamap-module-functions)
64
+ - [ContextBuilder](#contextbuilder)
65
+ - [ContextBuilder Class](#contextbuilder-class)
66
+ - [Context Class](#context-class)
67
+ - [Step Class](#step-class)
68
+ - [GatherInfo Class](#gatherinfo-class)
69
+ - [GatherQuestion Class](#gatherquestion-class)
70
+ - [Helper Functions](#contextbuilder-helper-functions)
71
+ - [PomBuilder](#pombuilder)
72
+ - [PomSection Class](#pomsection-class)
73
+ - [PomBuilder Class](#pombuilder-class)
74
+ - [SwmlBuilder](#swmlbuilder)
75
+ - [PromptManager](#promptmanager)
76
+ - [SessionManager](#sessionmanager)
77
+ - [Skills](#skills)
78
+ - [SkillBase](#skillbase)
79
+ - [SkillManager](#skillmanager)
80
+ - [SkillRegistry](#skillregistry)
81
+ - [Prefab Agents](#prefab-agents)
82
+ - [InfoGathererAgent](#infogathereragent)
83
+ - [SurveyAgent](#surveyagent)
84
+ - [FAQBotAgent](#faqbotagent)
85
+ - [ConciergeAgent](#conciergeagent)
86
+ - [ReceptionistAgent](#receptionistagent)
87
+ - [Capability Helpers](#capability-helpers)
88
+ - [Post-Prompt Helpers](#post-prompt-helpers)
89
+ - [AI Chat Gateway and Handoff](#ai-chat-gateway-and-handoff)
90
+ - [Utility Classes](#utility-classes)
91
+ - [AuthHandler](#authhandler)
92
+ - [ConfigLoader](#configloader)
93
+ - [Logger](#logger)
94
+ - [SslConfig](#sslconfig)
95
+ - [SchemaUtils](#schemautils)
96
+ - [ServerlessAdapter](#serverlessadapter)
97
+ - [Types and Interfaces](#types-and-interfaces)
98
+ - [AgentOptions](#agentoptions)
99
+ - [LanguageConfig](#languageconfig)
100
+ - [PronunciationRule](#pronunciationrule)
101
+ - [FunctionInclude](#functioninclude)
102
+ - [DynamicConfigCallback](#dynamicconfigcallback)
103
+ - [SummaryCallback](#summarycallback)
104
+ - [SwaigHandler](#swaighandler)
105
+ - [SwaigFunctionOptions](#swaigfunctionoptions)
106
+ - [AuthConfig](#authconfig)
107
+ - [SslOptions](#ssloptions)
108
+ - [ValidationResult](#validationresult)
109
+ - [ServerlessEvent](#serverlessevent)
110
+ - [ServerlessResponse](#serverlessresponse)
111
+ - [PomSectionData](#pomsectiondata)
112
+ - [Skill Types](#skill-types)
113
+ - [Payment Types](#payment-types)
114
+
115
+ ---
116
+
117
+ ## AgentBase
118
+
119
+ Import the class from the package root:
120
+
121
+ ```ts
122
+ import { AgentBase } from '@signalwire/sdk';
123
+ ```
124
+
125
+ `AgentBase` is one HTTP-servable voice agent. It extends `SWMLService` and holds a prompt manager, a session manager for tool tokens, a SWAIG tool registry and a skill manager. It renders the SWML document in five phases and serves it, along with the SWAIG and post-prompt endpoints, from a Hono app.
126
+
127
+ ### AgentBase Constructor
128
+
129
+ The constructor takes one options object:
130
+
131
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
132
+ ```ts
133
+ constructor(opts: AgentOptions)
134
+ ```
135
+
136
+ [AgentOptions](#agentoptions) lists every option and its default. The constructor throws when the resolved port is outside 1 to 65535.
137
+
138
+ **Example:**
139
+
140
+ ```ts
141
+ import { AgentBase } from '@signalwire/sdk';
142
+
143
+ const myAgent = new AgentBase({ name: 'MyAgent', route: '/agent' });
144
+ ```
145
+
146
+ ### AgentBase Static Members
147
+
148
+ #### `PROMPT_SECTIONS`
149
+
150
+ Subclasses can declare prompt sections on the class:
151
+
152
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
153
+ ```ts
154
+ static PROMPT_SECTIONS?: { title: string; body?: string; bullets?: string[]; numbered?: boolean }[]
155
+ ```
156
+
157
+ The constructor adds each entry with `promptAddSection()`.
158
+
159
+ **Example:**
160
+
161
+ ```ts
162
+ import { AgentBase } from '@signalwire/sdk';
163
+
164
+ class MyAgent extends AgentBase {
165
+ static override PROMPT_SECTIONS = [
166
+ { title: 'Role', body: 'You are a helpful assistant.' },
167
+ { title: 'Rules', bullets: ['Be concise.', 'Be polite.'] },
168
+ ];
169
+ }
170
+ ```
171
+
172
+ #### `SUPPORTED_INTERNAL_FILLER_NAMES`
173
+
174
+ The set of internal function names that accept fillers:
175
+
176
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
177
+ ```ts
178
+ static readonly SUPPORTED_INTERNAL_FILLER_NAMES: ReadonlySet<string>
179
+ ```
180
+
181
+ It holds `hangup`, `check_time`, `wait_for_user`, `wait_seconds`, `adjust_response_latency`, `next_step`, `change_context`, `get_visual_input` and `get_ideal_strategy`. `setInternalFillers()` and `addInternalFiller()` log a warning for any other name.
182
+
183
+ #### `extractSipUsername(requestBody)`
184
+
185
+ This static method reads the SIP username from a request body:
186
+
187
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
188
+ ```ts
189
+ static extractSipUsername(requestBody: SwmlRequestData): string | null
190
+ ```
191
+
192
+ It reads `call.to`. For a `sip:` or `sips:` URI it returns the part before `@`, and for a `tel:` URI it removes the scheme. Otherwise it returns `call.to` as is. It returns `null` when `call.to` is missing.
193
+
194
+ #### `setupGracefulShutdown(opts?)`
195
+
196
+ This static method registers `SIGTERM` and `SIGINT` handlers once per process:
197
+
198
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
199
+ ```ts
200
+ static setupGracefulShutdown(opts?: { timeout?: number }): void
201
+ ```
202
+
203
+ On a signal, the handler logs, waits `timeout` milliseconds (default `5000`) and calls `process.exit(0)`. It doesn't close the HTTP server or wait for requests in flight.
204
+
205
+ ### AgentBase Public Properties
206
+
207
+ | Property | Type | Description |
208
+ |----------|------|-------------|
209
+ | `name` | `string` (readonly) | Display name of this agent |
210
+ | `route` | `string` (readonly) | HTTP route path, without a trailing slash (`/` for the root) |
211
+ | `host` | `string` (readonly) | Hostname the HTTP server binds to |
212
+ | `port` | `number` (readonly) | Port the HTTP server listens on |
213
+ | `agentId` | `string` | Identifier for this agent instance |
214
+ | `signingKey` | `string \| null` (getter) | The resolved webhook signing key, or `null` when signature validation is off |
215
+ | `promptManager` | `PromptManager` (getter) | The agent's [PromptManager](#promptmanager) |
216
+ | `pom` | `PromptObjectModel \| null` (getter) | A new `PromptObjectModel` built from the current POM sections, or `null` when POM mode is off. Changing it doesn't change the agent. |
217
+ | `nativeFunctions` | `string[]` (getter and setter) | Native SWAIG function names |
218
+ | `skillManager` | `SkillManager` (getter) | The agent's [SkillManager](#skillmanager) |
219
+ | `schemaUtils` | `SchemaUtils` (readonly) | A [SchemaUtils](#schemautils) built from the `schemaPath` and `schemaValidation` options |
220
+ | `log` | `Logger` | The agent's logger |
221
+
222
+ ### Prompt Methods
223
+
224
+ #### `setPromptText(text)`
225
+
226
+ Set the main prompt as raw text. A raw prompt takes precedence over POM sections when the SWML is rendered.
227
+
228
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
229
+ ```ts
230
+ setPromptText(text: string): this
231
+ ```
232
+
233
+ #### `setPostPrompt(text)`
234
+
235
+ Set the post-prompt text. When it's set, the rendered AI verb carries a `post_prompt` and a `post_prompt_url` that points at this agent's `/post_prompt` endpoint, with a per-call token.
236
+
237
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
238
+ ```ts
239
+ setPostPrompt(text: string): this
240
+ ```
241
+
242
+ #### `promptAddSection(title, opts?)`
243
+
244
+ Add a section to the POM prompt.
245
+
246
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
247
+ ```ts
248
+ promptAddSection(title: string, opts?: {
249
+ body?: string;
250
+ bullets?: string[];
251
+ numbered?: boolean;
252
+ numberedBullets?: boolean;
253
+ subsections?: { title: string; body?: string; bullets?: string[] }[];
254
+ }): this
255
+ ```
256
+
257
+ #### `promptAddToSection(title, opts?)`
258
+
259
+ Append body text or bullets to a section. The section is created if it doesn't exist.
260
+
261
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
262
+ ```ts
263
+ promptAddToSection(title: string, opts?: {
264
+ body?: string;
265
+ bullet?: string;
266
+ bullets?: string[];
267
+ }): this
268
+ ```
269
+
270
+ #### `promptAddSubsection(parentTitle, title, opts?)`
271
+
272
+ Add a subsection under a section. The parent section is created if it doesn't exist.
273
+
274
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
275
+ ```ts
276
+ promptAddSubsection(parentTitle: string, title: string, opts?: {
277
+ body?: string;
278
+ bullets?: string[];
279
+ }): this
280
+ ```
281
+
282
+ #### `promptHasSection(title)`
283
+
284
+ Check whether a top-level prompt section with the given title exists.
285
+
286
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
287
+ ```ts
288
+ promptHasSection(title: string): boolean
289
+ ```
290
+
291
+ #### `getPrompt()`
292
+
293
+ Get the prompt as text: the raw prompt when one is set, otherwise the POM sections rendered as Markdown.
294
+
295
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
296
+ ```ts
297
+ getPrompt(): string
298
+ ```
299
+
300
+ #### `getPromptPom()`
301
+
302
+ Get the POM sections as plain objects, or `null` when POM mode is off or there are no sections.
303
+
304
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
305
+ ```ts
306
+ getPromptPom(): Record<string, unknown>[] | null
307
+ ```
308
+
309
+ #### `getRawPrompt()`
310
+
311
+ Get the text stored by `setPromptText()`, or `null` when none is set.
312
+
313
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
314
+ ```ts
315
+ getRawPrompt(): string | null
316
+ ```
317
+
318
+ #### `setPromptPom(pom)`
319
+
320
+ Replace every POM section with the given list. Each entry has a `title` and optionally `body`, `bullets`, `numbered`, `numberedBullets` and `subsections`. Throws when the agent was created with `usePom: false`.
321
+
322
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
323
+ ```ts
324
+ setPromptPom(pom: Record<string, unknown>[]): this
325
+ ```
326
+
327
+ #### `getPostPrompt()`
328
+
329
+ Get the post-prompt text, or `null` when none is set.
330
+
331
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
332
+ ```ts
333
+ getPostPrompt(): string | null
334
+ ```
335
+
336
+ ### Tool Methods
337
+
338
+ #### `defineTool(opts)`
339
+
340
+ `defineTool()` registers a SWAIG function that the model can call. Its signature is generic over the `parameters` map:
341
+
342
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
343
+ ```ts
344
+ defineTool<P extends ToolParameters, R extends readonly PropertyKey[]>(
345
+ opts: Omit<SwaigFunctionOptions, 'parameters' | 'required' | 'handler'> & {
346
+ parameters?: P;
347
+ required?: R;
348
+ handler: (
349
+ args: ToolArgs<P, R>,
350
+ rawData: SwaigRequest,
351
+ agent?: AgentBase,
352
+ ) => FunctionResult | Record<string, unknown> | string
353
+ | Promise<FunctionResult | Record<string, unknown> | string>;
354
+ },
355
+ ): this
356
+ ```
357
+
358
+ When `parameters` is a flat map of property definitions written inline, TypeScript infers the type of `args` from it. A full JSON Schema object (`{ type: 'object', properties }`) is also accepted; `args` is then an open record. The options are those of [SwaigFunctionOptions](#swaigfunctionoptions):
359
+
360
+ | Option | Type | Default | Description |
361
+ |--------|------|---------|-------------|
362
+ | `name` | `string` | (required) | Tool name |
363
+ | `description` | `string` | (required) | Description the model reads to decide when to call the tool |
364
+ | `parameters` | `Record<string, unknown>` | `{}` | Property definitions, or a full JSON Schema object |
365
+ | `handler` | function | (required) | Called with `(args, rawData, agent)` |
366
+ | `secure` | `boolean` | `true` | Require a per-call token. The rendered SWML gives the tool its own `web_hook_url` with a `__token` for that function and call. Pass `false` to let the tool run without a token. |
367
+ | `fillers` | `Record<string, string[]>` | none | Filler phrases by language code, emitted as the function's `fillers` |
368
+ | `waitFile` | `string` | none | Audio URL, emitted as `wait_file` |
369
+ | `waitFileLoops` | `number` | none | Emitted as `wait_file_loops` |
370
+ | `required` | `string[]` | `[]` | Required parameter names, used when `parameters` is a flat map |
371
+ | `webhookUrl` | `string` | none | An external URL that runs the tool instead of this agent |
372
+ | `extraFields` | `Record<string, unknown>` | `{}` | Extra keys merged into the function definition |
373
+ | `onError` | `SwaigErrorHandler` | none | Called when the handler throws; may return a `FunctionResult` to use as the response |
374
+ | `errorMessage` | `string` | A generic apology | Response used when the handler throws and no error hook returns one |
375
+ | `isTypedHandler` | `boolean` | `false` | Marks a handler that takes named parameters; `defineTypedTool()` sets it |
376
+
377
+ The handler's third argument is the agent the request was configured on. With a dynamic config callback or `addPerCallConfig()`, that's the per-request copy. The handler's return value is the tool's response: context for the model, which decides what to say. See [SwaigHandler](#swaighandler) for how each return type is serialized.
378
+
379
+ **Example:**
380
+
381
+ ```ts
382
+ import { FunctionResult } from '@signalwire/sdk';
383
+
384
+ agent.defineTool({
385
+ name: 'get_weather',
386
+ description: 'Get the current weather for a city',
387
+ parameters: { city: { type: 'string', description: 'City name' } },
388
+ required: ['city'],
389
+ handler: async (args, rawData, running) => {
390
+ const units = running?.getName() === 'metric-weather' ? 'C' : 'F';
391
+ return new FunctionResult(`Weather in ${args.city}: sunny, 22 ${units}. Call ${rawData.call_id}.`);
392
+ },
393
+ });
394
+ ```
395
+
396
+ #### `defineTypedTool(opts)`
397
+
398
+ Register a tool whose handler takes the arguments as named positional parameters instead of an `args` object. When `parameters` is omitted, the SDK infers a schema from the handler's parameter names and default values.
399
+
400
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
401
+ ```ts
402
+ defineTypedTool(opts: {
403
+ name: string;
404
+ description: string;
405
+ parameters?: Record<string, unknown>;
406
+ handler: TypedToolHandler;
407
+ secure?: boolean;
408
+ fillers?: Record<string, string[]>;
409
+ waitFile?: string;
410
+ waitFileLoops?: number;
411
+ required?: string[];
412
+ }): this
413
+ ```
414
+
415
+ #### `getTools()`
416
+
417
+ Get every registered `SwaigFunction`. DataMap and other raw function definitions aren't included. Calls `defineTools()` first if it hasn't run.
418
+
419
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
420
+ ```ts
421
+ getTools(): SwaigFunction[]
422
+ ```
423
+
424
+ #### `getRegisteredTools()`
425
+
426
+ Get a summary of every registered tool. For a raw definition such as a DataMap tool, `description` is read from its `purpose` key and `parameters` from its `argument` key.
427
+
428
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
429
+ ```ts
430
+ getRegisteredTools(): { name: string; description: string; parameters: Record<string, unknown> }[]
431
+ ```
432
+
433
+ #### `getTool(name)`
434
+
435
+ Look up a registered `SwaigFunction` by name. Returns `undefined` for a raw definition.
436
+
437
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
438
+ ```ts
439
+ getTool(name: string): SwaigFunction | undefined
440
+ ```
441
+
442
+ #### `registerSwaigFunction(fn)`
443
+
444
+ Register a `SwaigFunction`, or a raw function definition such as the output of `DataMap.toSwaigFunction()`. A raw definition is registered under its `function` key and rendered as is.
445
+
446
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
447
+ ```ts
448
+ registerSwaigFunction(fn: SwaigFunction | Record<string, unknown>): this
449
+ ```
450
+
451
+ #### Tool Registry Methods
452
+
453
+ `AgentBase` inherits these registry methods from `SWMLService`:
454
+
455
+ | Method | Signature | Description |
456
+ |--------|-----------|-------------|
457
+ | `hasTool` | `(name: string): boolean` | Whether a tool with the name is registered |
458
+ | `hasFunction` | `(name: string): boolean` | Same as `hasTool` |
459
+ | `getFunction` | `(name: string): SwaigFunction \| Record<string, unknown> \| undefined` | The registered entry, including raw definitions |
460
+ | `getAllFunctions` | `(): Record<string, SwaigFunction \| Record<string, unknown>>` | Every registered entry, keyed by name |
461
+ | `removeFunction` | `(name: string): boolean` | Remove a tool; returns `false` when it wasn't registered |
462
+ | `listToolNames` | `(): string[]` | Registered names in registration order |
463
+
464
+ #### `onError(handler)`
465
+
466
+ Set an agent-level hook that runs when a tool handler throws, after the tool's own `onError`. It receives `(error, { functionName, args, rawData })` and may return a `FunctionResult` to use as the response. Pass `undefined` to clear it. The error never reaches the HTTP layer.
467
+
468
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
469
+ ```ts
470
+ onError(handler: SwaigErrorHandler | undefined): this
471
+ ```
472
+
473
+ #### `validateToolToken(functionName, token, callId)`
474
+
475
+ Check a token for a tool. Returns `false` for an unknown tool and `true` for a tool registered with `secure: false`. A raw definition counts as secure.
476
+
477
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
478
+ ```ts
479
+ validateToolToken(functionName: string, token: string, callId: string): boolean
480
+ ```
481
+
482
+ #### `createToolToken(toolName, callId)`
483
+
484
+ Mint a token for a tool and call with the agent's session manager. Returns `''` on failure.
485
+
486
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
487
+ ```ts
488
+ createToolToken(toolName: string, callId: string): string
489
+ ```
490
+
491
+ ### Speech and Language Methods
492
+
493
+ #### `addHint(hint)`
494
+
495
+ Add a speech-recognition hint, emitted in the AI verb's `hints`.
496
+
497
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
498
+ ```ts
499
+ addHint(hint: string): this
500
+ ```
501
+
502
+ #### `addHints(hints)`
503
+
504
+ Add several hints at once.
505
+
506
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
507
+ ```ts
508
+ addHints(hints: string[]): this
509
+ ```
510
+
511
+ #### `addPatternHint(opts)`
512
+
513
+ Add a pattern hint, emitted in `hints` as `{ hint, pattern, replace, ignore_case }`. `ignore_case` is emitted only when `ignoreCase` is `true`.
514
+
515
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
516
+ ```ts
517
+ addPatternHint(opts: { hint: string; pattern: string; replace: string; ignoreCase?: boolean }): this
518
+ ```
519
+
520
+ #### `addLanguage(config)`
521
+
522
+ Add a language to the AI verb's `languages`. `speechFillers` and `functionFillers` are emitted as `speech_fillers` and `function_fillers` when both are given, and one alone as `fillers`. `speechModel` is emitted as `speech_model`, and `params` only when it isn't empty. See [LanguageConfig](#languageconfig).
523
+
524
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
525
+ ```ts
526
+ addLanguage(config: LanguageConfig): this
527
+ ```
528
+
529
+ #### `setLanguages(languages)`
530
+
531
+ Replace every configured language.
532
+
533
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
534
+ ```ts
535
+ setLanguages(languages: LanguageConfig[]): this
536
+ ```
537
+
538
+ #### `setMultilingual(config)`
539
+
540
+ Set a top-level `multilingual` object on the AI verb. The SDK passes the object through as given.
541
+
542
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
543
+ ```ts
544
+ setMultilingual(config: Record<string, unknown>): this
545
+ ```
546
+
547
+ #### `setLanguageParams(code, params)`
548
+
549
+ Set the `params` of a language added earlier. An empty object removes the key, and an unknown code does nothing.
550
+
551
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
552
+ ```ts
553
+ setLanguageParams(code: string, params: Record<string, unknown>): this
554
+ ```
555
+
556
+ #### `getLanguageParams(code)`
557
+
558
+ Get a language's `params`, or `undefined` when the code is unknown or has none.
559
+
560
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
561
+ ```ts
562
+ getLanguageParams(code: string): Record<string, unknown> | undefined
563
+ ```
564
+
565
+ #### `addPronunciation(rule)`
566
+
567
+ Add a pronunciation rule, emitted in `pronounce`. See [PronunciationRule](#pronunciationrule).
568
+
569
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
570
+ ```ts
571
+ addPronunciation(rule: PronunciationRule): this
572
+ ```
573
+
574
+ #### `setPronunciations(rules)`
575
+
576
+ Replace every pronunciation rule.
577
+
578
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
579
+ ```ts
580
+ setPronunciations(rules: PronunciationRule[]): this
581
+ ```
582
+
583
+ ### AI Configuration Methods
584
+
585
+ #### `setParam(key, value)`
586
+
587
+ Set one entry in the AI verb's `params`, such as `temperature` or `end_of_speech_timeout`.
588
+
589
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
590
+ ```ts
591
+ setParam(key: string, value: unknown): this
592
+ ```
593
+
594
+ #### `setParams(params)`
595
+
596
+ Merge entries into `params`.
597
+
598
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
599
+ ```ts
600
+ setParams(params: Record<string, unknown>): this
601
+ ```
602
+
603
+ #### `setGlobalData(data)`
604
+
605
+ Merge entries into `global_data`. Existing keys, including those a skill added, are kept unless `data` has the same key. To clear the object first, use `replaceGlobalData()`.
606
+
607
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
608
+ ```ts
609
+ setGlobalData(data: Record<string, unknown>): this
610
+ ```
611
+
612
+ #### `updateGlobalData(data)`
613
+
614
+ Merge entries into `global_data`, like `setGlobalData()`.
615
+
616
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
617
+ ```ts
618
+ updateGlobalData(data: Record<string, unknown>): this
619
+ ```
620
+
621
+ #### `replaceGlobalData(data)`
622
+
623
+ Replace `global_data` with a shallow copy of `data`, removing every earlier key, including skill-added ones.
624
+
625
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
626
+ ```ts
627
+ replaceGlobalData(data: Record<string, unknown>): this
628
+ ```
629
+
630
+ #### `setNativeFunctions(funcs)`
631
+
632
+ Set the names emitted in `SWAIG.native_functions`.
633
+
634
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
635
+ ```ts
636
+ setNativeFunctions(funcs: string[]): this
637
+ ```
638
+
639
+ #### `setInternalFillers(internalFillers)`
640
+
641
+ Merge fillers for internal functions, keyed by function name and then language code. They're emitted in `SWAIG.internal_fillers`. A name outside `SUPPORTED_INTERNAL_FILLER_NAMES` logs a warning.
642
+
643
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
644
+ ```ts
645
+ setInternalFillers(internalFillers: Record<string, Record<string, string[]>>): this
646
+ ```
647
+
648
+ #### `addInternalFiller(functionName, languageCode, fillers)`
649
+
650
+ Set the fillers for one internal function and language. An unsupported name logs a warning and is still stored.
651
+
652
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
653
+ ```ts
654
+ addInternalFiller(functionName: string, languageCode: string, fillers: string[]): this
655
+ ```
656
+
657
+ #### `addFunctionInclude(url, functions, metaData?)`
658
+
659
+ Add an entry to `SWAIG.includes`, naming functions served by another endpoint.
660
+
661
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
662
+ ```ts
663
+ addFunctionInclude(url: string, functions: string[], metaData?: Record<string, unknown>): this
664
+ ```
665
+
666
+ #### `setFunctionIncludes(includes)`
667
+
668
+ Replace every include. Entries without a `url` or a `functions` array are dropped.
669
+
670
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
671
+ ```ts
672
+ setFunctionIncludes(includes: FunctionInclude[]): this
673
+ ```
674
+
675
+ #### `setPromptLlmParams(params)`
676
+
677
+ Merge keys into the AI verb's `prompt` object, beside `text` or `pom`.
678
+
679
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
680
+ ```ts
681
+ setPromptLlmParams(params: Record<string, unknown>): this
682
+ ```
683
+
684
+ #### `setPostPromptLlmParams(params)`
685
+
686
+ Merge keys into the `post_prompt` object.
687
+
688
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
689
+ ```ts
690
+ setPostPromptLlmParams(params: Record<string, unknown>): this
691
+ ```
692
+
693
+ #### `enableDebugEvents(level?)`
694
+
695
+ Emit `debug_webhook_url` (this agent's `/debug_events` endpoint) and `debug_webhook_level` (default `1`) on the AI verb.
696
+
697
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
698
+ ```ts
699
+ enableDebugEvents(level?: number): this
700
+ ```
701
+
702
+ ### Call Flow Methods
703
+
704
+ `renderSwml()` builds the `main` section in five phases:
705
+
706
+ 1. Pre-answer verbs
707
+ 2. The `answer` verb, when `autoAnswer` is `true`
708
+ 3. A `record_call` verb when `recordCall` is `true`, then the post-answer verbs
709
+ 4. The `ai` verb
710
+ 5. Post-AI verbs
711
+
712
+ When the SWML is rendered, verbs added through these methods are checked against the bundled SWML schema, unless `SWML_SKIP_SCHEMA_VALIDATION=true`. `renderSwml()` throws a `SchemaValidationError` for an unknown verb or an invalid config.
713
+
714
+ #### `addPreAnswerVerb(verbName, config)`
715
+
716
+ Add a verb to phase 1. A number is for verbs that take one, such as `sleep`.
717
+
718
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
719
+ ```ts
720
+ addPreAnswerVerb(verbName: string, config: Record<string, unknown> | number): this
721
+ ```
722
+
723
+ #### `addAnswerVerb(config?)`
724
+
725
+ Set the configuration of the phase 2 `answer` verb.
726
+
727
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
728
+ ```ts
729
+ addAnswerVerb(config?: Record<string, unknown>): this
730
+ ```
731
+
732
+ #### `addPostAnswerVerb(verbName, config)`
733
+
734
+ Add a verb to phase 3.
735
+
736
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
737
+ ```ts
738
+ addPostAnswerVerb(verbName: string, config: Record<string, unknown> | number): this
739
+ ```
740
+
741
+ #### `addPostAiVerb(verbName, config)`
742
+
743
+ Add a verb to phase 5.
744
+
745
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
746
+ ```ts
747
+ addPostAiVerb(verbName: string, config: Record<string, unknown>): this
748
+ ```
749
+
750
+ #### `clearPreAnswerVerbs()`, `clearPostAnswerVerbs()`, `clearPostAiVerbs()`
751
+
752
+ Remove every verb in that phase.
753
+
754
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
755
+ ```ts
756
+ clearPreAnswerVerbs(): this
757
+ clearPostAnswerVerbs(): this
758
+ clearPostAiVerbs(): this
759
+ ```
760
+
761
+ ### Context Methods
762
+
763
+ #### `defineContexts(contexts?)`
764
+
765
+ With no argument, return the agent's `ContextBuilder`, creating it on first use; a second call returns the same builder. Pass a `ContextBuilder` to use it instead. Pass the contexts as a plain object to render them as they are, as the Python SDK does with a dict; that form returns the agent. See [ContextBuilder](#contextbuilder).
766
+
767
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
768
+ ```ts
769
+ defineContexts(contexts?: ContextBuilder): ContextBuilder
770
+ defineContexts(contexts: Record<string, unknown>): this
771
+ ```
772
+
773
+ #### `resetContexts()`
774
+
775
+ Remove every context from the active builder.
776
+
777
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
778
+ ```ts
779
+ resetContexts(): this
780
+ ```
781
+
782
+ #### `getContexts()`
783
+
784
+ Get the serialized contexts, or `null` when `defineContexts()` hasn't been called. Serializing validates the contexts and throws on an error.
785
+
786
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
787
+ ```ts
788
+ getContexts(): Record<string, unknown> | null
789
+ ```
790
+
791
+ ### Skill Methods
792
+
793
+ #### `addSkill(skill)`
794
+
795
+ Add a skill instance. The skill manager validates it and runs its `setup()`. The agent then registers the skill's tools and DataMap tools, adds its prompt sections and hints, and merges its global data. See [SkillBase](#skillbase).
796
+
797
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
798
+ ```ts
799
+ async addSkill(skill: SkillBase): Promise<this>
800
+ ```
801
+
802
+ #### `addSkillByName(skillName, params?)`
803
+
804
+ Create a skill from the global `SkillRegistry` and add it. Throws when the name isn't registered.
805
+
806
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
807
+ ```ts
808
+ async addSkillByName(skillName: SkillNameOrString, params?: SkillConfig): Promise<this>
809
+ ```
810
+
811
+ #### `removeSkill(instanceId)`
812
+
813
+ Remove a skill by instance key or instance ID, running its `cleanup()`. Returns `false` when no skill matches. The skill's tools, prompt sections and hints stay registered.
814
+
815
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
816
+ ```ts
817
+ async removeSkill(instanceId: string): Promise<boolean>
818
+ ```
819
+
820
+ #### `removeSkillByName(skillName)`
821
+
822
+ Remove the first loaded skill with the given name.
823
+
824
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
825
+ ```ts
826
+ async removeSkillByName(skillName: string): Promise<boolean>
827
+ ```
828
+
829
+ #### `listSkills()`
830
+
831
+ List the loaded skills.
832
+
833
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
834
+ ```ts
835
+ listSkills(): { name: string; instanceId: string; initialized: boolean }[]
836
+ ```
837
+
838
+ #### `hasSkill(skillName)`
839
+
840
+ Check whether a skill with the given name is loaded.
841
+
842
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
843
+ ```ts
844
+ hasSkill(skillName: SkillNameOrString): boolean
845
+ ```
846
+
847
+ ### Per-Request Configuration Methods
848
+
849
+ A per-request configuration callback lets one agent serve different configurations to different calls. The SDK makes a per-request copy of the agent for each request that renders SWML, runs a SWAIG function or delivers a summary. It runs the callbacks on that copy. The SWML is rendered from the copy, and `/swaig` and `/post_prompt` requests run on the copy. The original agent isn't modified.
850
+
851
+ The SDK copies these settings, so changing them on the copy affects only that request:
852
+
853
+ - The prompt, tools, hints, languages and pronunciations
854
+ - The params, global data, function includes, LLM params and fillers
855
+ - The call-flow verbs, SWAIG query params and native functions
856
+ - The MCP servers, SIP usernames, routing callbacks and contexts
857
+
858
+ Skills the agent loaded are shared with the copy, and their `setup()` doesn't run again. Anything else, such as a field a subclass adds, is shared with the agent and every request in flight. Assign a new value to such a field on the copy rather than changing a shared object in place.
859
+
860
+ A handler that captured the original agent (an arrow function that refers to it, or a method bound with `.bind(this)`) still sees the original. Read per-call configuration from the handler's third argument. A subclass's JavaScript `#private` fields aren't on the copy, so methods that read them throw there; use TypeScript `private` fields instead.
861
+
862
+ #### `setDynamicConfigCallback(cb)`
863
+
864
+ Set the per-request configuration callback. It replaces every callback registered so far, including those from `addPerCallConfig()`. The callback receives `(queryParams, bodyParams, headers, agent)`, where `agent` is the per-request copy; credential-bearing headers are removed first. See [DynamicConfigCallback](#dynamicconfigcallback).
865
+
866
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
867
+ ```ts
868
+ setDynamicConfigCallback(cb: DynamicConfigCallback): this
869
+ ```
870
+
871
+ #### `addPerCallConfig(cb)`
872
+
873
+ Add a per-request configuration callback, keeping the ones already registered. The callbacks run in registration order on the same copy, so a later one sees what an earlier one set. When a callback throws, the error is logged, the later callbacks are skipped, and the request continues with the copy as configured so far.
874
+
875
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
876
+ ```ts
877
+ addPerCallConfig(cb: DynamicConfigCallback): this
878
+ ```
879
+
880
+ **Example:**
881
+
882
+ ```ts
883
+ import { AgentBase, hasCapability } from '@signalwire/sdk';
884
+
885
+ const support = new AgentBase({ name: 'support' });
886
+ support.setPromptText('You are a support agent.');
887
+
888
+ support.addPerCallConfig((query, body, headers, copy) => {
889
+ if (query['tier'] === 'gold') copy.updateGlobalData({ tier: 'gold' });
890
+ });
891
+ support.addPerCallConfig((query, body, headers, copy) => {
892
+ if (hasCapability(body, 'display_content')) {
893
+ copy.promptAddSection('Screen', { body: 'The caller can see content you show.' });
894
+ }
895
+ });
896
+ ```
897
+
898
+ #### `onCallEnd(handler)`
899
+
900
+ Register a handler that runs when the call ends, and return it. The first registration defines a tool named `hangup_hook` and sets the `swaig_post_conversation` param to `true`, unless that param is explicitly `false`, which logs a warning. Handlers run in registration order with the call log (`call_log`, or `raw_call_log` when that's empty) and the whole SWAIG request. Return values are ignored, and an exception is logged without stopping the other handlers.
901
+
902
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
903
+ ```ts
904
+ onCallEnd(
905
+ handler: (callLog: Record<string, unknown>[], rawData: SwaigRequest) => void | Promise<void>,
906
+ ): (callLog: Record<string, unknown>[], rawData: SwaigRequest) => void | Promise<void>
907
+ ```
908
+
909
+ **Example:**
910
+
911
+ ```ts
912
+ import { AgentBase } from '@signalwire/sdk';
913
+
914
+ const archiver = new AgentBase({ name: 'archiver' });
915
+ archiver.onCallEnd((callLog, rawData) => {
916
+ console.log(`call ${rawData.call_id} ended after ${callLog.length} log entries`);
917
+ });
918
+ ```
919
+
920
+ #### `addSwaigQueryParams(params)`
921
+
922
+ Add query parameters to the SWAIG and post-prompt webhook URLs the agent renders. Entries with an empty value are left out.
923
+
924
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
925
+ ```ts
926
+ addSwaigQueryParams(params: Record<string, string>): this
927
+ ```
928
+
929
+ #### `clearSwaigQueryParams()`
930
+
931
+ Remove every SWAIG query parameter.
932
+
933
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
934
+ ```ts
935
+ clearSwaigQueryParams(): this
936
+ ```
937
+
938
+ ### SIP Routing and MCP Methods
939
+
940
+ #### `enableSipRouting(autoMap?, path?)`
941
+
942
+ Register a routing callback at `path` (default `/sip`) that reads the SIP username from each request. With `autoMap` (default `true`), it also calls `autoMapSipUsernames()`. The agent's own callback never redirects; it serves the agent's SWML.
943
+
944
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
945
+ ```ts
946
+ enableSipRouting(autoMap?: boolean, path?: string): this
947
+ ```
948
+
949
+ #### `registerSipUsername(username)`
950
+
951
+ Map a SIP username (stored in lowercase) to this agent's route.
952
+
953
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
954
+ ```ts
955
+ registerSipUsername(username: string): this
956
+ ```
957
+
958
+ #### `autoMapSipUsernames()`
959
+
960
+ Register usernames derived from the agent's name and route: each lowercased with characters other than letters, digits and `_` removed. For a name longer than three characters, a form without vowels is also registered.
961
+
962
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
963
+ ```ts
964
+ autoMapSipUsernames(): this
965
+ ```
966
+
967
+ #### `registerRoutingCallback(callback, path?)`
968
+
969
+ Serve a routing endpoint at `path` (default `/sip`). On a POST with a body, the callback receives `(body, headers)`. When it returns a route, the endpoint responds `307` with that route in `Location`; when it returns `null` or `undefined`, the endpoint serves the agent's SWML.
970
+
971
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
972
+ ```ts
973
+ registerRoutingCallback(callback: RoutingCallback, path?: string): this
974
+ ```
975
+
976
+ #### `addMcpServer(url, opts?)`
977
+
978
+ Add an entry to `SWAIG.mcp_servers` in the rendered SWML, with `headers`, `resources` and `resource_vars` when set.
979
+
980
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
981
+ ```ts
982
+ addMcpServer(url: string, opts?: {
983
+ headers?: Record<string, string>;
984
+ resources?: boolean;
985
+ resourceVars?: Record<string, string>;
986
+ }): this
987
+ ```
988
+
989
+ #### `enableMcpServer()`
990
+
991
+ Serve the agent's tools as an MCP server (JSON-RPC 2.0) at `POST {route}/mcp`. The endpoint requires the agent's basic auth. It lists and calls only tools the agent runs itself, not DataMap tools or tools with a `webhookUrl`.
992
+
993
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
994
+ ```ts
995
+ enableMcpServer(): this
996
+ ```
997
+
998
+ #### `isMcpServerEnabled()` and `getMcpServers()`
999
+
1000
+ Report whether the `/mcp` endpoint is on, and get a copy of the list added with `addMcpServer()`.
1001
+
1002
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1003
+ ```ts
1004
+ isMcpServerEnabled(): boolean
1005
+ getMcpServers(): Record<string, unknown>[]
1006
+ ```
1007
+
1008
+ ### URL and Proxy Methods
1009
+
1010
+ #### `manualSetProxyUrl(url)`
1011
+
1012
+ Set the public base URL used to build webhook URLs, with trailing slashes removed. It replaces the value from `SWML_PROXY_URL_BASE` and stops proxy headers from changing it.
1013
+
1014
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1015
+ ```ts
1016
+ manualSetProxyUrl(url: string): this
1017
+ ```
1018
+
1019
+ #### `setWebHookUrl(url)`
1020
+
1021
+ Set the URL emitted as `SWAIG.defaults.web_hook_url`. A secure tool still gets its own `web_hook_url` with its token.
1022
+
1023
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1024
+ ```ts
1025
+ setWebHookUrl(url: string): this
1026
+ ```
1027
+
1028
+ #### `setPostPromptUrl(url)`
1029
+
1030
+ Set the URL emitted as `post_prompt_url`, replacing the agent's own `/post_prompt` URL and its token.
1031
+
1032
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1033
+ ```ts
1034
+ setPostPromptUrl(url: string): this
1035
+ ```
1036
+
1037
+ #### `getFullUrl(includeAuth?)`
1038
+
1039
+ Get the agent's public URL, including its route. The base is the proxy URL when one is set. Otherwise, in a serverless environment (and before `serve()` runs), it's the platform's function URL; otherwise it's `http://host:port`, with `localhost` for `0.0.0.0` and `https` when `SWML_ENFORCE_HTTPS=true`. With `includeAuth` (default `false`), the basic-auth credentials are embedded in the URL.
1040
+
1041
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1042
+ ```ts
1043
+ getFullUrl(includeAuth?: boolean): string
1044
+ ```
1045
+
1046
+ ### Server Methods
1047
+
1048
+ #### `getApp()`
1049
+
1050
+ Get the Hono app that serves the agent, building it on first use. It calls `defineTools()` first if it hasn't run.
1051
+
1052
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1053
+ ```ts
1054
+ getApp(): Hono
1055
+ ```
1056
+
1057
+ The app serves these routes under the agent's route:
1058
+
1059
+ | Endpoint | Method | Description |
1060
+ |----------|--------|-------------|
1061
+ | `{route}` | GET, POST | Renders the SWML. A GET reads `call_id` from the query string, and a POST from the body. |
1062
+ | `{route}/swaig` | POST | Runs a SWAIG function. A secure function needs a valid `__token` for that function and call. |
1063
+ | `{route}/swaig` | GET | Renders the SWML |
1064
+ | `{route}/post_prompt` | POST | Delivers the call summary to `onSummary`. Needs the post-prompt token for the call. |
1065
+ | `{route}/post_prompt` | GET | Renders the SWML |
1066
+ | `{route}/debug_events` | POST | Passes the body to `onDebugEvent` |
1067
+ | `{route}/mcp` | POST | MCP endpoint, when `enableMcpServer()` was called |
1068
+ | `{route}/post_prompt_override` | POST | Replaces the post-prompt text, when `enablePostPromptOverride` is set |
1069
+ | `{route}/check_for_input` | GET, POST | Echoes the body, when `checkForInputOverride` is set |
1070
+ | `{route}{path}` | GET, POST | A routing callback registered with `registerRoutingCallback()` |
1071
+ | `{route}/health` | GET | Returns `{ status: 'ok' }` |
1072
+ | `{route}/ready` | GET | Returns `{ status: 'ready' }` |
1073
+
1074
+ Every route except `/health` and `/ready` requires the agent's basic auth. When a signing key is set, a POST to the root, `/swaig`, `/post_prompt` or a routing-callback path also needs a valid webhook signature. An unsigned or mis-signed request gets `403`. The middleware checks `X-SignalWire-Sha256-Signature` first, then `X-SignalWire-Signature` (SHA-1). For more information, see [Security](security.md).
1075
+
1076
+ #### `asRouter()`
1077
+
1078
+ Get a Hono app with the agent's routes relative to its root (`/`, `/swaig`, `/post_prompt` and the rest), for mounting in a host app: `hostApp.route(agent.route, agent.asRouter())`. `HostAppRouter` is an alias for `Hono`.
1079
+
1080
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1081
+ ```ts
1082
+ asRouter(): HostAppRouter
1083
+ ```
1084
+
1085
+ #### `mount(appOrRouter, opts?)`
1086
+
1087
+ Serve another Hono app, or a fetch handler, beside the agent's routes. `prefix` is the path from the host root (default the root), with a trailing slash removed; `name` has no effect. The agent's routes take precedence. A mounted app isn't behind the agent's basic auth, CORS, CSRF check or security headers, so it applies its own. Call `mount()` before `serve()`.
1088
+
1089
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1090
+ ```ts
1091
+ mount(
1092
+ appOrRouter: Hono | ((req: Request) => Response | Promise<Response>),
1093
+ opts?: { prefix?: string; name?: string },
1094
+ ): this
1095
+ ```
1096
+
1097
+ **Example:**
1098
+
1099
+ ```ts
1100
+ import { AgentBase } from '@signalwire/sdk';
1101
+
1102
+ const withStatus = new AgentBase({ name: 'with-status', route: '/agent' });
1103
+ withStatus.mount(() => new Response('ok'), { prefix: '/status' });
1104
+ ```
1105
+
1106
+ #### `serve(opts?)`
1107
+
1108
+ Start an HTTP server with `@hono/node-server`, using the constructor's host and port unless `opts` overrides them. It does nothing when `SWAIG_CLI_MODE=true`, which `swaig-test` sets.
1109
+
1110
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1111
+ ```ts
1112
+ async serve(opts?: { host?: string; port?: number }): Promise<void>
1113
+ ```
1114
+
1115
+ #### `run(opts?)`
1116
+
1117
+ Call `runServerless()` when `opts.event` is given or a serverless environment is detected (`AWS_LAMBDA_FUNCTION_NAME`, `_HANDLER`, `K_SERVICE`, `FUNCTION_TARGET`, `FUNCTIONS_WORKER_RUNTIME` or `GATEWAY_INTERFACE` is set). Otherwise call `serve()`. For predictable behavior, call `serve()` or `runServerless()` directly.
1118
+
1119
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1120
+ ```ts
1121
+ async run(opts?: {
1122
+ host?: string;
1123
+ port?: number;
1124
+ event?: ServerlessEvent;
1125
+ context?: unknown;
1126
+ platform?: 'lambda' | 'gcf' | 'azure' | 'cgi' | 'auto';
1127
+ }): Promise<void | ServerlessResponse>
1128
+ ```
1129
+
1130
+ #### `runServerless(event, context?, platform?)`
1131
+
1132
+ Handle one serverless invocation through the agent's app with a [ServerlessAdapter](#serverlessadapter). In CGI mode with an empty event, the request is read from the environment and standard input, and the response is written to standard output.
1133
+
1134
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1135
+ ```ts
1136
+ async runServerless(
1137
+ event: ServerlessEvent,
1138
+ context?: unknown,
1139
+ platform?: 'lambda' | 'gcf' | 'azure' | 'cgi' | 'auto',
1140
+ ): Promise<ServerlessResponse>
1141
+ ```
1142
+
1143
+ #### `renderSwml(callId?, modifications?)`
1144
+
1145
+ Render the SWML document as a JSON string. `callId` is used for the per-call tokens; a random ID is generated when it's omitted. `modifications` is merged into the AI verb: `global_data` is merged key by key, and every other key replaces the AI verb's value.
1146
+
1147
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1148
+ ```ts
1149
+ renderSwml(callId?: string, modifications?: Record<string, unknown>): string
1150
+ ```
1151
+
1152
+ #### `handleRequest(method, url, headers, body?)`
1153
+
1154
+ Handle a SWML request without Hono and return `[status, headers, body]`. It checks basic auth (`401`), runs a routing callback (`307`), calls `onSwmlRequest()` and renders the SWML from the per-request copy when callbacks are registered. It doesn't check webhook signatures.
1155
+
1156
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1157
+ ```ts
1158
+ async handleRequest(
1159
+ method: string,
1160
+ url: string,
1161
+ headers: Record<string, string>,
1162
+ body?: Record<string, unknown> | null,
1163
+ ): Promise<[number, Record<string, string>, string]>
1164
+ ```
1165
+
1166
+ ### Utility Methods
1167
+
1168
+ #### `getName()`
1169
+
1170
+ Get the agent's name.
1171
+
1172
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1173
+ ```ts
1174
+ getName(): string
1175
+ ```
1176
+
1177
+ #### `getBasicAuthCredentials(includeSource?)`
1178
+
1179
+ Get the basic-auth username and password. With `includeSource: true`, a third element says where they came from.
1180
+
1181
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1182
+ ```ts
1183
+ getBasicAuthCredentials(includeSource?: false): [string, string]
1184
+ getBasicAuthCredentials(includeSource: true): [string, string, 'provided' | 'environment' | 'config file' | 'generated']
1185
+ ```
1186
+
1187
+ #### `enableDebugRoutes()`
1188
+
1189
+ Does nothing. It exists for code written for the Python SDK; `getApp()` always serves `/health`, `/ready` and `/debug_events`.
1190
+
1191
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1192
+ ```ts
1193
+ enableDebugRoutes(): this
1194
+ ```
1195
+
1196
+ ### Lifecycle Hooks
1197
+
1198
+ Override these methods in a subclass.
1199
+
1200
+ #### `defineTools()`
1201
+
1202
+ Register the subclass's tools here with `this.defineTool()`. The agent calls it once, the first time tools are needed: from `renderSwml()`, `getTools()`, `getApp()`, `asRouter()` or SWAIG dispatch. Calling it yourself from a constructor is safe, since it runs only once. The default does nothing.
1203
+
1204
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1205
+ ```ts
1206
+ protected defineTools(): void
1207
+ ```
1208
+
1209
+ #### `onSummary(summary, rawData)`
1210
+
1211
+ Called for each POST to `/post_prompt` that carries a valid post-prompt token. `summary` is the body's `summary`, else `post_prompt_data.parsed[0]`, else `post_prompt_data.raw` parsed as JSON (or the raw string when it isn't JSON), else `null`. With per-request configuration, it runs on the per-request copy. For a request whose `action` is `fetch_conversation`, a returned object is sent back as the response instead of `{ success: true }`. To read the body in one shape across voice and chat, see [Post-Prompt Helpers](#post-prompt-helpers).
1212
+
1213
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1214
+ ```ts
1215
+ onSummary(
1216
+ summary: PostPromptData | null,
1217
+ rawData: PostPrompt,
1218
+ ): void | Record<string, unknown> | Promise<void | Record<string, unknown>>
1219
+ ```
1220
+
1221
+ #### `onSwmlRequest(rawData, callbackPath?, context?)`
1222
+
1223
+ Called on the agent before each SWML render. `context` is the Hono context of a served request, and `undefined` from `handleRequest()`. A returned object is passed to `renderSwml()` as `modifications`.
1224
+
1225
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1226
+ ```ts
1227
+ onSwmlRequest(
1228
+ rawData: SwmlRequestData,
1229
+ callbackPath?: string,
1230
+ context?: Context,
1231
+ ): Record<string, unknown> | void | Promise<Record<string, unknown> | void>
1232
+ ```
1233
+
1234
+ #### `onRequest(requestData?, callbackPath?)`
1235
+
1236
+ Calls `onSwmlRequest()` and returns its result. Override `onSwmlRequest()` instead.
1237
+
1238
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1239
+ ```ts
1240
+ onRequest(
1241
+ requestData?: SwmlRequestData | null,
1242
+ callbackPath?: string | null,
1243
+ ): Record<string, unknown> | void | Promise<Record<string, unknown> | void>
1244
+ ```
1245
+
1246
+ #### `onDebugEvent(event)`
1247
+
1248
+ Called with the body of each POST to `/debug_events`.
1249
+
1250
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1251
+ ```ts
1252
+ onDebugEvent(event: Record<string, unknown>): void | Promise<void>
1253
+ ```
1254
+
1255
+ #### `onFunctionCall(name, args, rawData)`
1256
+
1257
+ Called after the token check and before a SWAIG function runs, on the agent the request runs on. A returned object is sent as the response, and the function doesn't run.
1258
+
1259
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1260
+ ```ts
1261
+ onFunctionCall(
1262
+ name: string,
1263
+ args: Record<string, unknown>,
1264
+ rawData: Record<string, unknown>,
1265
+ ): Record<string, unknown> | void | Promise<Record<string, unknown> | void>
1266
+ ```
1267
+
1268
+ #### `validateBasicAuth(username, password)`
1269
+
1270
+ Every route that requires basic auth calls it with the request's credentials. The default compares them with the configured pair in constant time. An override replaces that comparison, so call `super.validateBasicAuth()` to keep it and add your own check.
1271
+
1272
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1273
+ ```ts
1274
+ validateBasicAuth(username: string, password: string): boolean | Promise<boolean>
1275
+ ```
1276
+
1277
+ ---
1278
+
1279
+ ## AgentServer
1280
+
1281
+ Import the class from the package root:
1282
+
1283
+ ```ts
1284
+ import { AgentServer } from '@signalwire/sdk';
1285
+ ```
1286
+
1287
+ `AgentServer` serves several agents from one HTTP server, each under its own route prefix.
1288
+
1289
+ ### Constructor
1290
+
1291
+ The constructor takes an optional options object:
1292
+
1293
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1294
+ ```ts
1295
+ constructor(opts?: { host?: string; port?: number; logLevel?: string })
1296
+ ```
1297
+
1298
+ | Parameter | Type | Default | Description |
1299
+ |-----------|------|---------|-------------|
1300
+ | `host` | `string` | `'0.0.0.0'` | Hostname to bind to |
1301
+ | `port` | `number` | `PORT` env, else `3000` | Port to listen on |
1302
+ | `logLevel` | `string` | `'info'` | Passed to `setGlobalLogLevel()`, except under `swaig-test` |
1303
+
1304
+ ### Methods
1305
+
1306
+ | Method | Signature | Description |
1307
+ |--------|-----------|-------------|
1308
+ | `register` | `(agent: AgentBase, route?: string): void` | Mount the agent's `asRouter()` at `route` (default the agent's route). Throws when the route is taken. |
1309
+ | `unregister` | `(route: string): boolean` | Remove an agent and its routes; returns `false` when none was registered there. |
1310
+ | `getAgents` | `(): Map<string, AgentBase>` | Registered agents keyed by route |
1311
+ | `getAgent` | `(route: string): AgentBase \| undefined` | The agent at a route |
1312
+ | `serveStaticFiles` | `(directory: string, route?: string): void` | Serve files from a directory, rejecting paths with `..` |
1313
+ | `setupSipRouting` | `(route?: string, autoMap?: boolean): void` | Route SIP requests to agents by username at `route` (default `/sip`) |
1314
+ | `registerSipUsername` | `(username: string, route: string): void` | Map a SIP username to an agent's route |
1315
+ | `registerGlobalRoutingCallback` | `(callbackFn: RoutingCallback, path: string): void` | Register a routing callback on every agent, including agents registered later |
1316
+ | `getApp` | `(): Hono` | The server's Hono app. Adds a `GET /` listing of the agents unless an agent is registered at `/`. |
1317
+ | `run` | `(host?: string, port?: number): Promise<void>` | Start the HTTP server. Does nothing when `SWAIG_CLI_MODE=true`. |
1318
+
1319
+ **Example:**
1320
+
1321
+ <!-- snippet: no-run starts a blocking HTTP server (serve/start/run on a fixed port): it collides under the concurrent gate and cannot run standalone -->
1322
+ ```ts
1323
+ import { AgentServer } from '@signalwire/sdk';
1324
+
1325
+ const server = new AgentServer({ port: 8080 });
1326
+ server.register(agent1, '/sales');
1327
+ server.register(agent2, '/support');
1328
+ await server.run();
1329
+ ```
1330
+
1331
+ ---
1332
+
1333
+ ## FunctionResult
1334
+
1335
+ Import the class from the package root:
1336
+
1337
+ ```ts
1338
+ import { FunctionResult } from '@signalwire/sdk';
1339
+ ```
1340
+
1341
+ `FunctionResult` builds a SWAIG function's response: a response for the model and an ordered list of actions for the platform. The response is context for the model, not speech: the model reads it and decides what to say. Every method that changes the result returns `this`. `SwaigFunctionResult` is a deprecated alias.
1342
+
1343
+ ### FunctionResult Constructor
1344
+
1345
+ The constructor takes the response and optional settings:
1346
+
1347
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1348
+ ```ts
1349
+ constructor(
1350
+ response?: string | { tool_result?: string; tool_prompt?: string },
1351
+ postProcess?: boolean,
1352
+ toolResult?: string,
1353
+ toolPrompt?: string,
1354
+ )
1355
+ ```
1356
+
1357
+ | Parameter | Type | Default | Description |
1358
+ |-----------|------|---------|-------------|
1359
+ | `response` | `string \| { tool_result?, tool_prompt? }` | `''` | The response text, or the structured form |
1360
+ | `postProcess` | `boolean` | `false` | Whether the model takes one more turn before the actions run |
1361
+ | `toolResult` | `string` | none | Sets the structured response's `tool_result`, as `setToolResponse()` does |
1362
+ | `toolPrompt` | `string` | none | Sets the structured response's `tool_prompt` |
1363
+
1364
+ ### Public Properties
1365
+
1366
+ | Property | Type | Description |
1367
+ |----------|------|-------------|
1368
+ | `response` | `string` | The response text. It's `''` while a structured response is set. |
1369
+ | `action` | `Record<string, unknown>[]` | Ordered list of actions |
1370
+ | `postProcess` | `boolean` | Whether post-processing is on |
1371
+
1372
+ ### FunctionResult Core Methods
1373
+
1374
+ | Method | Signature | Description |
1375
+ |--------|-----------|-------------|
1376
+ | `setResponse` | `(response: string): this` | Set the response text, clearing a structured response |
1377
+ | `setToolResponse` | `(toolResult?: string, toolPrompt?: string): this` | Set the structured response `{ tool_result, tool_prompt }` |
1378
+ | `setPostProcess` | `(postProcess: boolean): this` | Turn post-processing on or off |
1379
+ | `addAction` | `(name: string, data: unknown): this` | Append `{ [name]: data }` |
1380
+ | `addActions` | `(actions: Record<string, unknown>[]): this` | Append several actions |
1381
+
1382
+ The structured response separates what the tool did from what the model should say next. `tool_result` is a factual status line for the model to reason from, and `tool_prompt` is an instruction. Splitting them keeps a status line from being read aloud as speech, and keeps an instruction from being taken as data.
1383
+
1384
+ **Example:**
1385
+
1386
+ ```ts
1387
+ import { FunctionResult } from '@signalwire/sdk';
1388
+
1389
+ const result = new FunctionResult().setToolResponse(
1390
+ 'payment declined: insufficient funds',
1391
+ 'Tell the caller the card was declined and ask for another card.',
1392
+ );
1393
+ console.log(JSON.stringify(result.toDict()));
1394
+ ```
1395
+
1396
+ ### Call Control Actions
1397
+
1398
+ | Method | Signature | Emits |
1399
+ |--------|-----------|-------|
1400
+ | `connect` | `(destination: string, final?: boolean, fromAddr?: string): this` | A `SWML` action with a `connect` verb (`to`, and `from` when `fromAddr` is set), and `transfer: 'true'` or `'false'` from `final` (default `true`) |
1401
+ | `swmlTransfer` | `(dest: string, aiResponse: string, final?: boolean): this` | A `SWML` action that sets `ai_response` and then runs `transfer` to `dest`, with `transfer` from `final` (default `true`) |
1402
+ | `hangup` | `(): this` | `{ hangup: true }` |
1403
+ | `hold` | `(prompt?: string \| number, timeout?: number, step?: string, timeoutStep?: string): this` | `{ hold: timeout }`, or `{ hold: { timeout, step, timeout_step } }` when a step is given. See [`hold()`](#hold). |
1404
+ | `waitForUser` | `(opts?: { enabled?: boolean; timeout?: number; answerFirst?: boolean }): this` | `{ wait_for_user: value }`, where value is `'answer_first'`, the timeout, `enabled` or `true`, in that order of precedence |
1405
+ | `stop` | `(): this` | `{ stop: true }` |
1406
+
1407
+ #### `hold()`
1408
+
1409
+ `hold()` puts the call on hold, and can announce it and route the call when the hold ends:
1410
+
1411
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1412
+ ```ts
1413
+ hold(prompt?: string | number, timeout?: number, step?: string, timeoutStep?: string): this
1414
+ ```
1415
+
1416
+ | Parameter | Type | Default | Description |
1417
+ |-----------|------|---------|-------------|
1418
+ | `prompt` | `string \| number` | none | Instruction for the model to deliver before the hold. A number here is read as `timeout`, so `hold(120)` still works. |
1419
+ | `timeout` | `number` | `300` | Hold length in seconds, clamped to 0 to 900 |
1420
+ | `step` | `string` | none | Step to move to when the call is taken off hold |
1421
+ | `timeoutStep` | `string` | none | Step to move to when the hold times out |
1422
+
1423
+ Speech detection pauses during a hold, so the caller has to hear anything important before it starts. A string `prompt` sets the structured response to `{ tool_result: 'status: on hold', tool_prompt: prompt }`. It also turns on `postProcess`, so the model speaks before the hold runs. `step` and `timeoutStep` take effect when the hold ends. `swmlChangeStep()` applies at once, which would move the caller before the hold begins.
1424
+
1425
+ **Example:**
1426
+
1427
+ ```ts
1428
+ import { FunctionResult } from '@signalwire/sdk';
1429
+
1430
+ const result = new FunctionResult().hold(
1431
+ 'Tell the caller you are checking whether the manager is available.',
1432
+ 300,
1433
+ 'back_with_manager',
1434
+ 'take_a_message',
1435
+ );
1436
+ console.log(JSON.stringify(result.toDict()));
1437
+ ```
1438
+
1439
+ ### Audio Actions
1440
+
1441
+ | Method | Signature | Emits |
1442
+ |--------|-----------|-------|
1443
+ | `say` | `(text: string): this` | `{ say: text }` |
1444
+ | `playBackgroundFile` | `(filename: string, wait?: boolean): this` | `{ playback_bg: filename }`, or `{ playback_bg: { file, wait: true } }` when `wait` is `true` |
1445
+ | `stopBackgroundFile` | `(): this` | `{ stop_playback_bg: true }` |
1446
+
1447
+ ### Speech Actions
1448
+
1449
+ | Method | Signature | Emits |
1450
+ |--------|-----------|-------|
1451
+ | `addDynamicHints` | `(hints: (string \| { pattern: string; replace: string; ignore_case?: boolean })[]): this` | `{ add_dynamic_hints: hints }` |
1452
+ | `clearDynamicHints` | `(): this` | `{ clear_dynamic_hints: {} }` |
1453
+ | `setEndOfSpeechTimeout` | `(milliseconds: number): this` | `{ end_of_speech_timeout: milliseconds }` |
1454
+ | `setSpeechEventTimeout` | `(milliseconds: number): this` | `{ speech_event_timeout: milliseconds }` |
1455
+
1456
+ ### Data Actions
1457
+
1458
+ | Method | Signature | Emits |
1459
+ |--------|-----------|-------|
1460
+ | `updateGlobalData` | `(data: Record<string, unknown>): this` | `{ set_global_data: data }` |
1461
+ | `removeGlobalData` | `(keys: string \| string[]): this` | `{ unset_global_data: keys }` |
1462
+ | `setMetadata` | `(data: Record<string, unknown>): this` | `{ set_meta_data: data }` |
1463
+ | `removeMetadata` | `(keys: string \| string[]): this` | `{ unset_meta_data: keys }` |
1464
+
1465
+ ### SWML Actions
1466
+
1467
+ | Method | Signature | Emits |
1468
+ |--------|-----------|-------|
1469
+ | `executeSwml` | `(swmlContent: string \| Record<string, unknown> \| { toDict(): Record<string, unknown> }, transfer?: boolean): this` | `{ SWML: document }`, with `transfer: 'true'` when `transfer` is `true`. A string that isn't JSON becomes `{ raw_swml: string }`; any other value throws. |
1470
+ | `swmlChangeStep` | `(stepName: string): this` | `{ change_step: stepName }` |
1471
+ | `swmlChangeContext` | `(contextName: string): this` | `{ change_context: contextName }` |
1472
+ | `swmlUserEvent` | `(eventData: Record<string, unknown>): this` | A `SWML` action with a `user_event` verb |
1473
+ | `switchContext` | `(opts?: { systemPrompt?: string; userPrompt?: string; consolidate?: boolean; fullReset?: boolean }): this` | `{ context_switch: systemPrompt }` when only `systemPrompt` is set, otherwise an object with `system_prompt`, `user_prompt`, `consolidate` and `full_reset` |
1474
+
1475
+ ### Function Actions
1476
+
1477
+ | Method | Signature | Emits |
1478
+ |--------|-----------|-------|
1479
+ | `toggleFunctions` | `(toggles: { function: string; active: boolean }[]): this` | `{ toggle_functions: toggles }` |
1480
+ | `enableFunctionsOnTimeout` | `(enabled?: boolean): this` | `{ functions_on_speaker_timeout: enabled }` (default `true`) |
1481
+ | `updateSettings` | `(settings: Record<string, unknown>): this` | `{ settings: settings }` |
1482
+
1483
+ ### Communication Actions
1484
+
1485
+ | Method | Signature | Emits |
1486
+ |--------|-----------|-------|
1487
+ | `simulateUserInput` | `(text: string): this` | `{ user_input: text }` |
1488
+ | `enableExtensiveData` | `(enabled?: boolean): this` | `{ extensive_data: enabled }` (default `true`) |
1489
+ | `replaceInHistory` | `(text?: string \| boolean): this` | `{ replace_in_history: text }` (default `true`) |
1490
+ | `sendSms` | `(opts: { toNumber: string; fromNumber: string; body?: string; media?: string[]; tags?: string[]; region?: string }): this` | A `SWML` action with a `send_sms` verb. Throws when neither `body` nor `media` is given. |
1491
+ | `recordCall` | `(opts?: { controlId?, stereo?, format?, direction?, terminators?, beep?, inputSensitivity?, initialTimeout?, endSilenceTimeout?, maxLength?, statusUrl? }): this` | A `SWML` action with a `record_call` verb. Defaults: `stereo: false`, `format: 'wav'`, `direction: 'both'`, `beep: false`, `input_sensitivity: 44`. |
1492
+ | `stopRecordCall` | `(controlId?: string): this` | A `SWML` action with a `stop_record_call` verb |
1493
+ | `tap` | `(opts: { uri: string; controlId?: string; direction?: 'speak' \| 'listen' \| 'both'; codec?: 'PCMU' \| 'PCMA'; rtpPtime?: number; statusUrl?: string }): this` | A `SWML` action with a `tap` verb. `direction` defaults to `'both'` and is always sent. Throws on an invalid `direction` or `codec`, or an `rtpPtime` that isn't positive. |
1494
+ | `stopTap` | `(controlId?: string): this` | A `SWML` action with a `stop_tap` verb |
1495
+
1496
+ ### Room and Conference Actions
1497
+
1498
+ | Method | Signature | Emits |
1499
+ |--------|-----------|-------|
1500
+ | `joinRoom` | `(name: string): this` | A `SWML` action with `join_room: { name }` |
1501
+ | `sipRefer` | `(toUri: string): this` | A `SWML` action with `sip_refer: { to_uri }` |
1502
+ | `joinConference` | `(name: string, opts?): this` | A `SWML` action with a `join_conference` verb: the name alone when every option is at its default, otherwise an object. Throws on an empty name, or a `maxParticipants` that isn't an integer of at least 2 or a SWML variable reference. `maxParticipants` is sent whenever it's given. |
1503
+
1504
+ The `joinConference()` options are `muted`, `beep`, `startOnEnter`, `endOnExit`, `waitUrl`, `maxParticipants`, `record`, `region`, `trim`, `coach`, `statusCallbackEvent`, `statusCallback`, `statusCallbackMethod`, `recordingStatusCallback`, `recordingStatusCallbackMethod`, `recordingStatusCallbackEvent` and `result`. Each is emitted in snake case.
1505
+
1506
+ ### RPC Actions
1507
+
1508
+ | Method | Signature | Emits |
1509
+ |--------|-----------|-------|
1510
+ | `executeRpc` | `(opts: { method: string; params?: Record<string, unknown>; callId?: string; nodeId?: string }): this` | A `SWML` action with an `execute_rpc` verb. An empty `params` is left out. |
1511
+ | `rpcDial` | `(toNumber: string, fromNumber: string, destSwml: string, deviceType?: string): this` | `execute_rpc` with method `dial` (`deviceType` defaults to `'phone'`) |
1512
+ | `rpcAiMessage` | `(callId: string, messageText?: string \| null, role?: string, globalData?: Record<string, unknown>): this` | `execute_rpc` with method `ai_message` |
1513
+ | `rpcAiGlobalData` | `(callId: string, data: Record<string, unknown>): this` | `execute_rpc` with method `ai_message` and only `global_data` |
1514
+ | `rpcAiUnhold` | `(callId: string): this` | `execute_rpc` with method `ai_unhold` |
1515
+
1516
+ `rpcAiMessage()` sends a message, global data or both to the AI agent on another call. `messageText` is sent with `role` (default `'system'`) as a turn in that conversation. `globalData` is merged into that call's global data, where a prompt reads it with `${global_data.key}`. The method throws when neither is given.
1517
+
1518
+ **Example:**
1519
+
1520
+ ```ts
1521
+ import { FunctionResult } from '@signalwire/sdk';
1522
+
1523
+ const result = new FunctionResult('Tell the caller the agent has their notes.')
1524
+ .rpcAiGlobalData('b6f1c2d4-call-id', { caller_notes: 'Wants a refund for order 1234.' });
1525
+ console.log(JSON.stringify(result.toDict()));
1526
+ ```
1527
+
1528
+ ### Payment Actions
1529
+
1530
+ #### `pay(opts)`
1531
+
1532
+ `pay()` starts a payment collection:
1533
+
1534
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1535
+ ```ts
1536
+ pay(opts: {
1537
+ paymentConnectorUrl: string;
1538
+ inputMethod?: string; // default 'dtmf'
1539
+ statusUrl?: string;
1540
+ paymentMethod?: string; // default 'credit-card'
1541
+ timeout?: number | string; // default 5
1542
+ maxAttempts?: number | string; // default 1
1543
+ securityCode?: boolean | string; // default true
1544
+ postalCode?: boolean | string; // default true
1545
+ minPostalCodeLength?: number | string; // default 0
1546
+ tokenType?: string; // default 'reusable'
1547
+ chargeAmount?: string;
1548
+ currency?: string; // default 'usd'
1549
+ language?: string; // default 'en-US'
1550
+ voice?: string; // default 'woman'
1551
+ description?: string;
1552
+ validCardTypes?: string; // default 'visa mastercard amex'
1553
+ parameters?: PaymentParameter[];
1554
+ prompts?: PaymentPrompt[];
1555
+ aiResponse?: string;
1556
+ }): this
1557
+ ```
1558
+
1559
+ It emits a `SWML` action that sets `ai_response` and runs the `pay` verb. `timeout`, `max_attempts`, `min_postal_code_length`, `security_code` and `postal_code` are sent as strings, as the platform reads them (an input that isn't an integer or a boolean throws, and a SWML variable reference passes through), and `inputMethod` is sent as `input`. The default `aiResponse` is `'The payment status is ${pay_result}, do not mention anything else about collecting payment if successful.'`
1560
+
1561
+ ### FunctionResult Static Helpers
1562
+
1563
+ | Method | Signature | Returns |
1564
+ |--------|-----------|---------|
1565
+ | `createPaymentPrompt` | `(forSituation: string, actions: PaymentAction[], cardType?: string, errorType?: string)` | `PaymentPrompt` |
1566
+ | `createPaymentAction` | `(actionType: string, phrase: string)` | `PaymentAction` |
1567
+ | `createPaymentParameter` | `(name: string, value: string)` | `PaymentParameter` |
1568
+
1569
+ ### FunctionResult Serialization
1570
+
1571
+ #### `toDict()`
1572
+
1573
+ Serialize the result for the SWAIG response. `response` is the structured form when it has a field, otherwise the text when it isn't empty. `action` is present when there are actions, and `post_process: true` when post-processing is on and there are actions. An otherwise empty result serializes as `{ response: 'Action completed.' }`. `toJSON()` returns the same object, so `JSON.stringify(result)` emits it.
1574
+
1575
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1576
+ ```ts
1577
+ toDict(): SwaigResultDict
1578
+ ```
1579
+
1580
+ ---
1581
+
1582
+ ## SwaigFunction
1583
+
1584
+ Import the class from the package root:
1585
+
1586
+ ```ts
1587
+ import { SwaigFunction } from '@signalwire/sdk';
1588
+ ```
1589
+
1590
+ `SwaigFunction` wraps a tool handler with the metadata SWAIG needs. `defineTool()` creates one for you.
1591
+
1592
+ ### Constructor
1593
+
1594
+ The constructor takes one options object:
1595
+
1596
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1597
+ ```ts
1598
+ constructor(opts: SwaigFunctionOptions)
1599
+ ```
1600
+
1601
+ See [SwaigFunctionOptions](#swaigfunctionoptions) for the options.
1602
+
1603
+ ### Public Properties
1604
+
1605
+ | Property | Type | Description |
1606
+ |----------|------|-------------|
1607
+ | `name` | `string` | Tool name |
1608
+ | `handler` | `SwaigHandler` | Handler function |
1609
+ | `description` | `string` | Description the model reads |
1610
+ | `parameters` | `Record<string, unknown>` | Property definitions or a full JSON Schema object |
1611
+ | `secure` | `boolean` | Whether a per-call token is required |
1612
+ | `fillers` | `Record<string, string[]> \| undefined` | Filler phrases by language code |
1613
+ | `waitFile` | `string \| undefined` | Wait audio URL |
1614
+ | `waitFileLoops` | `number \| undefined` | Wait audio loop count |
1615
+ | `webhookUrl` | `string \| undefined` | External webhook URL |
1616
+ | `required` | `string[]` | Required parameter names |
1617
+ | `extraFields` | `Record<string, unknown>` | Extra keys merged into the definition |
1618
+ | `isTypedHandler` | `boolean` | Whether the handler takes named parameters |
1619
+ | `isExternal` | `boolean` | Whether `webhookUrl` was given |
1620
+ | `onError` | `SwaigErrorHandler \| undefined` | Per-tool error hook |
1621
+ | `errorMessage` | `string \| undefined` | Per-tool error response |
1622
+
1623
+ ### Methods
1624
+
1625
+ #### `validateArgs(args)`
1626
+
1627
+ Validate arguments against the parameter schema with Ajv. Returns `[true, []]` when the schema has no properties. Every call to the tool runs it first: arguments that don't match are logged as a warning, and the handler still runs, as in the Python SDK.
1628
+
1629
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1630
+ ```ts
1631
+ validateArgs(args: Record<string, unknown>): [boolean, string[]]
1632
+ ```
1633
+
1634
+ #### `execute(args, rawData?, agentOnError?)`
1635
+
1636
+ Run the handler and return the serialized result. The handler's third argument is `undefined` here. When the handler throws, the tool's `onError`, then `agentOnError`, may supply a `FunctionResult`; otherwise the result carries `errorMessage` or the default error message.
1637
+
1638
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1639
+ ```ts
1640
+ async execute(
1641
+ args: Record<string, unknown>,
1642
+ rawData?: SwaigRequest,
1643
+ agentOnError?: SwaigErrorHandler,
1644
+ ): Promise<SwaigResultDict>
1645
+ ```
1646
+
1647
+ #### `toSwaig(baseUrl, token?, callId?)`
1648
+
1649
+ Serialize the function for SWML: `function`, `description`, `parameters`, `web_hook_url` (`{baseUrl}/swaig`, with `?token=...&call_id=...` when both are given), the filler and wait-file keys when set, and `extraFields`.
1650
+
1651
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1652
+ ```ts
1653
+ toSwaig(baseUrl: string, token?: string, callId?: string): Record<string, unknown>
1654
+ ```
1655
+
1656
+ ---
1657
+
1658
+ ## DataMap
1659
+
1660
+ Import the class and helpers from the package root:
1661
+
1662
+ ```ts
1663
+ import { DataMap, createSimpleApiTool, createExpressionTool } from '@signalwire/sdk';
1664
+ ```
1665
+
1666
+ `DataMap` builds a SWAIG function with a `data_map`, which SignalWire runs on its servers. The platform calls the webhooks and evaluates the expressions without a request to your agent. The SDK only serializes the definition.
1667
+
1668
+ Templates in URLs, `params`, expressions and outputs are expanded by the platform; header values are sent as written. A URL, `params`, the top-level expressions and the fallback output read the arguments as `${args.name}`. A webhook's `output`, `expressions` and `foreach` read the webhook's JSON response from the root of the template data (`${total}`, `${results[0].title}`), an array response under `array`, and the arguments as `${input.args.name}`. For the template reference, see the [DataMap guide](datamap-guide.md#template-data).
1669
+
1670
+ ### DataMap Constructor
1671
+
1672
+ The constructor takes the function name:
1673
+
1674
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1675
+ ```ts
1676
+ constructor(functionName: string)
1677
+ ```
1678
+
1679
+ The name is stored in the public `functionName` property.
1680
+
1681
+ ### DataMap Configuration Methods
1682
+
1683
+ #### `enableEnvExpansion(enabled?)`
1684
+
1685
+ Turn on `${ENV.NAME}` expansion (the argument defaults to `true`; expansion is off until you call it). The SDK expands the variables in the whole definition when `toSwaigFunction()` runs, from the process environment. Only names with an allowed prefix are expanded, `SIGNALWIRE_`, `SWML_` or `SW_` by default; any other reference, or an unset variable, becomes an empty string. The expanded values are part of the SWML that SignalWire receives.
1686
+
1687
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1688
+ ```ts
1689
+ enableEnvExpansion(enabled?: boolean): this
1690
+ ```
1691
+
1692
+ #### `setAllowedEnvPrefixes(prefixes)`
1693
+
1694
+ Set the allowed prefixes for this DataMap, overriding the global list. An empty array allows every variable.
1695
+
1696
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1697
+ ```ts
1698
+ setAllowedEnvPrefixes(prefixes: string[]): this
1699
+ ```
1700
+
1701
+ #### `purpose(description)` and `description(description)`
1702
+
1703
+ Set the tool description the model reads. Without one, the description is `Execute {functionName}`.
1704
+
1705
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1706
+ ```ts
1707
+ purpose(description: string): this
1708
+ description(description: string): this // alias
1709
+ ```
1710
+
1711
+ #### `parameter(name, paramType, description, opts?)`
1712
+
1713
+ Add a parameter. The description is also read by the model.
1714
+
1715
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1716
+ ```ts
1717
+ parameter(name: string, paramType: string, description: string, opts?: {
1718
+ required?: boolean;
1719
+ enum?: string[];
1720
+ }): this
1721
+ ```
1722
+
1723
+ #### `expression(testValue, pattern, output, nomatchOutput?)`
1724
+
1725
+ Add an entry to `data_map.expressions`: `{ string, pattern, output, 'nomatch-output' }`. The platform wraps a pattern that doesn't start with `/` as `/pattern/i`, so matching is case-insensitive by default; to match case-sensitively, write the pattern as `/pattern/`. A `RegExp` is sent as its `source`, so its flags are dropped.
1726
+
1727
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1728
+ ```ts
1729
+ expression(
1730
+ testValue: string,
1731
+ pattern: string | RegExp,
1732
+ output: FunctionResult,
1733
+ nomatchOutput?: FunctionResult,
1734
+ ): this
1735
+ ```
1736
+
1737
+ ### DataMap Webhook Methods
1738
+
1739
+ #### `webhook(method, url, opts?)`
1740
+
1741
+ Add a webhook, with `method` in upper case. The options are emitted as `headers`, `form_param`, `input_args_as_params` and `require_args`. The platform sends a `POST` when the method is `POST` or the webhook has `params`, and a `GET` otherwise. It tries the webhooks in order, skipping one when none of its `require_args` is present, and the first one it requests decides the result: if that one fails, the fallback output answers and later webhooks aren't tried.
1742
+
1743
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1744
+ ```ts
1745
+ webhook(method: string, url: string, opts?: {
1746
+ headers?: Record<string, string>;
1747
+ formParam?: string;
1748
+ inputArgsAsParams?: boolean;
1749
+ requireArgs?: string[];
1750
+ }): this
1751
+ ```
1752
+
1753
+ The next five methods apply to the most recently added webhook, and throw when there is none:
1754
+
1755
+ | Method | Signature | Sets |
1756
+ |--------|-----------|------|
1757
+ | `webhookExpressions` | `(expressions: Record<string, unknown>[]): this` | The webhook's `expressions` |
1758
+ | `body` | `(data: Record<string, unknown>): this` | The webhook's `params` (the same as `params()`) |
1759
+ | `params` | `(data: Record<string, unknown>): this` | The webhook's `params` |
1760
+ | `foreach` | `(config: { input_key: string; output_key: string; append: string; max?: number }): this` | The webhook's `foreach` |
1761
+ | `output` | `(result: FunctionResult): this` | The webhook's `output` |
1762
+
1763
+ In a `foreach`, `input_key` is the path to the array, and `append` is a template where `${this.field}` is a field of the current element (`${this}` for a string or number element); the built text is stored under `output_key`. `body()` and `params()` both set `params`, which the platform sends as the JSON request body.
1764
+
1765
+ ### DataMap Output Methods
1766
+
1767
+ #### `fallbackOutput(result)`
1768
+
1769
+ Set the top-level `data_map.output`, the response the platform uses when no expression matched and no webhook produced a result, such as when the webhook it requested failed.
1770
+
1771
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1772
+ ```ts
1773
+ fallbackOutput(result: FunctionResult): this
1774
+ ```
1775
+
1776
+ #### `errorKeys(keys)`
1777
+
1778
+ Set `error_keys` on the most recently added webhook, or on the `data_map` when there's no webhook. The platform fails a webhook when one of these keys is present in its JSON response, whatever the value, and reads `error_keys` only on a webhook.
1779
+
1780
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1781
+ ```ts
1782
+ errorKeys(keys: string[]): this
1783
+ ```
1784
+
1785
+ #### `globalErrorKeys(keys)`
1786
+
1787
+ Set `error_keys` on the `data_map`. The platform reads `error_keys` only on a webhook, so these keys fail no request; use `errorKeys()` after each `webhook()`.
1788
+
1789
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1790
+ ```ts
1791
+ globalErrorKeys(keys: string[]): this
1792
+ ```
1793
+
1794
+ ### DataMap Registration and Serialization
1795
+
1796
+ #### `registerWithAgent(agent)`
1797
+
1798
+ Pass `toSwaigFunction()` to the agent's `registerSwaigFunction()`.
1799
+
1800
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1801
+ ```ts
1802
+ registerWithAgent(agent: { registerSwaigFunction(fn: Record<string, unknown>): unknown }): this
1803
+ ```
1804
+
1805
+ #### `toSwaigFunction()`
1806
+
1807
+ Serialize to `{ function, description, parameters, data_map }`, expanding `${ENV.*}` references when expansion is on.
1808
+
1809
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1810
+ ```ts
1811
+ toSwaigFunction(): Record<string, unknown>
1812
+ ```
1813
+
1814
+ **Example:**
1815
+
1816
+ ```ts
1817
+ import { AgentBase, DataMap, FunctionResult } from '@signalwire/sdk';
1818
+
1819
+ const weatherAgent = new AgentBase({ name: 'weather' });
1820
+ new DataMap('get_weather')
1821
+ .purpose('Get the current weather for a city')
1822
+ .parameter('city', 'string', 'City name', { required: true })
1823
+ .webhook('GET', 'https://api.example.com/weather?q=${lc:enc:args.city}')
1824
+ .output(new FunctionResult('It is ${temp} degrees and ${condition} in ${input.args.city}.'))
1825
+ .fallbackOutput(new FunctionResult('The weather service is unavailable.'))
1826
+ .registerWithAgent(weatherAgent);
1827
+ ```
1828
+
1829
+ ### DataMap Module Functions
1830
+
1831
+ #### `createSimpleApiTool(opts)`
1832
+
1833
+ Build a DataMap with one webhook whose output is `responseTemplate`. A parameter's type defaults to `'string'`.
1834
+
1835
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1836
+ ```ts
1837
+ function createSimpleApiTool(opts: {
1838
+ name: string;
1839
+ url: string;
1840
+ responseTemplate: string;
1841
+ parameters?: Record<string, { type?: string; description?: string; required?: boolean }>;
1842
+ method?: string; // default 'GET'
1843
+ headers?: Record<string, string>;
1844
+ body?: Record<string, unknown>;
1845
+ errorKeys?: string[];
1846
+ }): DataMap
1847
+ ```
1848
+
1849
+ #### `createExpressionTool(opts)`
1850
+
1851
+ Build a DataMap with one expression per entry: each key is the test value, and each value is `[pattern, result]`.
1852
+
1853
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1854
+ ```ts
1855
+ function createExpressionTool(opts: {
1856
+ name: string;
1857
+ patterns: Record<string, [string, FunctionResult]>;
1858
+ parameters?: Record<string, { type?: string; description?: string; required?: boolean }>;
1859
+ }): DataMap
1860
+ ```
1861
+
1862
+ #### `setAllowedEnvPrefixes(prefixes)` and `getAllowedEnvPrefixes()`
1863
+
1864
+ Set or read the global list of prefixes allowed in `${ENV.*}` expansion. The default is `['SIGNALWIRE_', 'SWML_', 'SW_']`, and an empty array allows every variable.
1865
+
1866
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1867
+ ```ts
1868
+ function setAllowedEnvPrefixes(prefixes: string[]): void
1869
+ function getAllowedEnvPrefixes(): string[]
1870
+ ```
1871
+
1872
+ ---
1873
+
1874
+ ## ContextBuilder
1875
+
1876
+ Import the classes and helpers from the package root:
1877
+
1878
+ ```ts
1879
+ import { ContextBuilder, Context, Step, GatherInfo, GatherQuestion, createSimpleContext, HISTORY_MODES } from '@signalwire/sdk';
1880
+ ```
1881
+
1882
+ Contexts hold ordered steps. Each step has prompt text, completion criteria, the functions it allows and the steps and contexts it can move to. `agent.defineContexts()` attaches a builder to an agent, and the rendered AI verb carries the result as `contexts`. For a walkthrough, see the [contexts guide](contexts-guide.md).
1883
+
1884
+ ### ContextBuilder Class
1885
+
1886
+ #### `addContext(name)`
1887
+
1888
+ Add a context and return it. Throws when the name exists or when there are already 50 contexts. A flow with one context must name it `default`.
1889
+
1890
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1891
+ ```ts
1892
+ addContext(name: string): Context
1893
+ ```
1894
+
1895
+ #### `getContext(name)`
1896
+
1897
+ Get a context by name.
1898
+
1899
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1900
+ ```ts
1901
+ getContext(name: string): Context | undefined
1902
+ ```
1903
+
1904
+ #### `reset()`
1905
+
1906
+ Remove every context.
1907
+
1908
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1909
+ ```ts
1910
+ reset(): this
1911
+ ```
1912
+
1913
+ #### `validate()`
1914
+
1915
+ Check the contexts and throw on the first problem. It requires at least one context, the name `default` for a single context, and at least one step in each context. It checks that every `initial_step`, `valid_steps`, `valid_contexts` and gather `completion_action` names something that exists, and that gather question keys are unique. On an agent, it also rejects tools named `next_step`, `change_context` or `gather_submit`, and `functions` lists that name unregistered tools.
1916
+
1917
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1918
+ ```ts
1919
+ validate(): void
1920
+ ```
1921
+
1922
+ #### `toDict()`
1923
+
1924
+ Validate, then serialize every context in the order it was added.
1925
+
1926
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1927
+ ```ts
1928
+ toDict(): Record<string, ContextDict>
1929
+ ```
1930
+
1931
+ ### Context Class
1932
+
1933
+ A `Context` is a named set of ordered steps with its own prompt settings.
1934
+
1935
+ #### Constructor
1936
+
1937
+ The constructor has this signature:
1938
+
1939
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
1940
+ ```ts
1941
+ constructor(name: string)
1942
+ ```
1943
+
1944
+ #### Step Management
1945
+
1946
+ | Method | Signature | Returns | Description |
1947
+ |--------|-----------|---------|-------------|
1948
+ | `addStep` | `(name: string, opts?)` | `Step` | Add a step. Throws when the name exists or the context has 100 steps. |
1949
+ | `getStep` | `(name: string)` | `Step \| undefined` | Get a step by name |
1950
+ | `removeStep` | `(name: string)` | `this` | Remove a step |
1951
+ | `moveStep` | `(name: string, position: number)` | `this` | Move a step to a zero-based position. Throws for an unknown step. |
1952
+
1953
+ The `addStep()` options are shortcuts:
1954
+
1955
+ | Option | Type | Description |
1956
+ |--------|------|-------------|
1957
+ | `task` | `string` | Calls `addSection('Task', task)` |
1958
+ | `bullets` | `string[]` | Calls `addBullets('Process', bullets)` |
1959
+ | `criteria` | `string` | Calls `setStepCriteria(criteria)` |
1960
+ | `functions` | `string \| string[]` | Calls `setFunctions(functions)` |
1961
+ | `validSteps` | `string[]` | Calls `setValidSteps(validSteps)` |
1962
+
1963
+ #### Navigation and Configuration
1964
+
1965
+ | Method | Signature | Description |
1966
+ |--------|-----------|-------------|
1967
+ | `setValidContexts` | `(contexts: string[]): this` | Contexts the model can move to |
1968
+ | `setValidSteps` | `(steps: string[]): this` | Steps the model can move to |
1969
+ | `setInitialStep` | `(stepName: string): this` | Step the context starts on, instead of the first |
1970
+ | `setPostPrompt` | `(postPrompt: string): this` | Context `post_prompt` |
1971
+ | `setSystemPrompt` | `(systemPrompt: string): this` | Raw `system_prompt`. Throws when system POM sections exist. |
1972
+ | `setConsolidate` | `(consolidate: boolean): this` | Emits `consolidate: true` |
1973
+ | `setFullReset` | `(fullReset: boolean): this` | Emits `full_reset: true` |
1974
+ | `setUserPrompt` | `(userPrompt: string): this` | Emits `user_prompt` |
1975
+ | `setIsolated` | `(isolated: boolean): this` | Emits `isolated: true` |
1976
+ | `setPrompt` | `(prompt: string): this` | Raw `prompt`. Throws when prompt POM sections exist. |
1977
+ | `setHistory` | `(history: string): this` | Default history mode for the context's steps: `keep`, `default` or `hide`. Throws on any other value. |
1978
+
1979
+ #### POM Sections
1980
+
1981
+ | Method | Signature | Description |
1982
+ |--------|-----------|-------------|
1983
+ | `addSystemSection` | `(title: string, body: string): this` | Section rendered into `system_prompt`. Throws after `setSystemPrompt()`. |
1984
+ | `addSystemBullets` | `(title: string, bullets: string[]): this` | Bullet section rendered into `system_prompt` |
1985
+ | `addSection` | `(title: string, body: string): this` | Section emitted in the context's `pom`. Throws after `setPrompt()`. |
1986
+ | `addBullets` | `(title: string, bullets: string[]): this` | Bullet section emitted in `pom` |
1987
+
1988
+ #### Fillers
1989
+
1990
+ | Method | Signature | Description |
1991
+ |--------|-----------|-------------|
1992
+ | `setEnterFillers` | `(fillers: Record<string, string[]>): this` | `enter_fillers`, by language code |
1993
+ | `setExitFillers` | `(fillers: Record<string, string[]>): this` | `exit_fillers`, by language code |
1994
+ | `addEnterFiller` | `(languageCode: string, fillers: string[]): this` | Enter fillers for one language |
1995
+ | `addExitFiller` | `(languageCode: string, fillers: string[]): this` | Exit fillers for one language |
1996
+
1997
+ #### `toDict()`
1998
+
1999
+ Serialize the context and its steps. Throws when it has no steps.
2000
+
2001
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2002
+ ```ts
2003
+ toDict(): ContextDict
2004
+ ```
2005
+
2006
+ ### Step Class
2007
+
2008
+ A `Step` is one stage of a context.
2009
+
2010
+ #### Constructor
2011
+
2012
+ The constructor has this signature:
2013
+
2014
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2015
+ ```ts
2016
+ constructor(name: string)
2017
+ ```
2018
+
2019
+ #### Content Methods
2020
+
2021
+ | Method | Signature | Description |
2022
+ |--------|-----------|-------------|
2023
+ | `setText` | `(text: string): this` | Raw step text. Throws when sections exist. |
2024
+ | `addSection` | `(title: string, body: string): this` | Section rendered into the step text. Throws after `setText()`. |
2025
+ | `addBullets` | `(title: string, bullets: string[]): this` | Bullet section rendered into the step text |
2026
+ | `clearSections` | `(): this` | Remove every section and the raw text |
2027
+
2028
+ #### Configuration Methods
2029
+
2030
+ | Method | Signature | Description |
2031
+ |--------|-----------|-------------|
2032
+ | `setStepCriteria` | `(criteria: string): this` | Emits `step_criteria` |
2033
+ | `setFunctions` | `(functions: string \| string[]): this` | Emits `functions`: a list of allowed tools, or `[]` or `'none'` for none. A step that doesn't set it keeps the previous step's functions. |
2034
+ | `setValidSteps` | `(steps: string[]): this` | Emits `valid_steps` |
2035
+ | `setValidContexts` | `(contexts: string[]): this` | Emits `valid_contexts` |
2036
+ | `setEnd` | `(end: boolean): this` | Emits `end: true`, which leaves step mode after this step. It doesn't end the call. |
2037
+ | `setSkipUserTurn` | `(skip: boolean): this` | Emits `skip_user_turn: true` |
2038
+ | `setSkipToNextStep` | `(skip: boolean): this` | Emits `skip_to_next_step: true` |
2039
+ | `setHistory` | `(history: string): this` | History mode when the step is entered: `keep`, `default` or `hide`. Throws on any other value. |
2040
+
2041
+ #### Gather Info Methods
2042
+
2043
+ | Method | Signature | Description |
2044
+ |--------|-----------|-------------|
2045
+ | `setGatherInfo` | `(opts?: { outputKey?: string; completionAction?: string; prompt?: string; isolated?: boolean }): this` | Start a `gather_info` for the step |
2046
+ | `addGatherQuestion` | `(opts: { key: string; question: string; type?: string; confirm?: boolean; prompt?: string; functions?: string[]; isolated?: boolean }): this` | Add a question. Throws when `setGatherInfo()` hasn't been called. |
2047
+
2048
+ `completionAction` is `'next_step'` or the name of a step in the same context. `isolated` on the gather is the default for its questions, and a question's own `isolated` overrides it. A question's `false` is emitted, so it can override an isolated gather.
2049
+
2050
+ #### Reset Methods
2051
+
2052
+ | Method | Signature | Description |
2053
+ |--------|-----------|-------------|
2054
+ | `setResetSystemPrompt` | `(systemPrompt: string): this` | Emits `reset.system_prompt` |
2055
+ | `setResetUserPrompt` | `(userPrompt: string): this` | Emits `reset.user_prompt` |
2056
+ | `setResetConsolidate` | `(consolidate: boolean): this` | Emits `reset.consolidate: true` |
2057
+ | `setResetFullReset` | `(fullReset: boolean): this` | Emits `reset.full_reset: true` |
2058
+
2059
+ #### `toDict()`
2060
+
2061
+ Serialize the step. Throws when it has neither text nor sections.
2062
+
2063
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2064
+ ```ts
2065
+ toDict(): StepDict
2066
+ ```
2067
+
2068
+ ### GatherInfo Class
2069
+
2070
+ `GatherInfo` collects answers to a series of questions.
2071
+
2072
+ #### Constructor
2073
+
2074
+ The constructor has this signature:
2075
+
2076
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2077
+ ```ts
2078
+ constructor(opts?: { outputKey?: string; completionAction?: string; prompt?: string; isolated?: boolean })
2079
+ ```
2080
+
2081
+ #### Methods
2082
+
2083
+ | Method | Signature | Description |
2084
+ |--------|-----------|-------------|
2085
+ | `addQuestion` | `(opts: { key; question; type?; confirm?; prompt?; functions?; isolated? }): this` | Add a question |
2086
+ | `getQuestions` | `(): GatherQuestion[]` | Get the questions |
2087
+ | `toDict` | `(): GatherInfoDict` | Serialize. Throws when there are no questions. |
2088
+
2089
+ ### GatherQuestion Class
2090
+
2091
+ A `GatherQuestion` is one question in a gather.
2092
+
2093
+ #### Constructor
2094
+
2095
+ The constructor has this signature:
2096
+
2097
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2098
+ ```ts
2099
+ constructor(opts: {
2100
+ key: string;
2101
+ question: string;
2102
+ type?: string; // default 'string'
2103
+ confirm?: boolean; // default false
2104
+ prompt?: string;
2105
+ functions?: string[];
2106
+ isolated?: boolean;
2107
+ })
2108
+ ```
2109
+
2110
+ #### Properties
2111
+
2112
+ | Property | Type | Description |
2113
+ |----------|------|-------------|
2114
+ | `key` | `string` | Key the answer is stored under |
2115
+ | `question` | `string` | Question text |
2116
+ | `type` | `string` | Answer type; emitted only when it isn't `'string'` |
2117
+ | `confirm` | `boolean` | Whether the answer needs confirmation |
2118
+ | `prompt` | `string \| undefined` | Extra prompt text for this question |
2119
+ | `functions` | `string[] \| undefined` | Tools available while this question is asked |
2120
+ | `isolated` | `boolean \| undefined` | Overrides the gather's `isolated` for this question |
2121
+
2122
+ #### `toDict()`
2123
+
2124
+ Serialize the question.
2125
+
2126
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2127
+ ```ts
2128
+ toDict(): Record<string, unknown>
2129
+ ```
2130
+
2131
+ ### ContextBuilder Helper Functions
2132
+
2133
+ #### `createSimpleContext(name?)`
2134
+
2135
+ Create a `Context` without a builder. The name defaults to `'default'`.
2136
+
2137
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2138
+ ```ts
2139
+ function createSimpleContext(name?: string): Context
2140
+ ```
2141
+
2142
+ #### `HISTORY_MODES`
2143
+
2144
+ The accepted history modes:
2145
+
2146
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2147
+ ```ts
2148
+ const HISTORY_MODES: readonly ['keep', 'default', 'hide']
2149
+ type HistoryMode = 'keep' | 'default' | 'hide'
2150
+ ```
2151
+
2152
+ ---
2153
+
2154
+ ## PomBuilder
2155
+
2156
+ Import the classes from the package root:
2157
+
2158
+ ```ts
2159
+ import { PomBuilder, PomSection } from '@signalwire/sdk';
2160
+ ```
2161
+
2162
+ The Prompt Object Model structures a prompt as sections, each with a title, body, bullets and nested subsections.
2163
+
2164
+ ### PomSection Class
2165
+
2166
+ A `PomSection` is one section.
2167
+
2168
+ #### Constructor
2169
+
2170
+ The constructor has this signature:
2171
+
2172
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2173
+ ```ts
2174
+ constructor(opts?: {
2175
+ title?: string | null;
2176
+ body?: string;
2177
+ bullets?: string[];
2178
+ numbered?: boolean | null;
2179
+ numberedBullets?: boolean;
2180
+ })
2181
+ ```
2182
+
2183
+ #### Properties
2184
+
2185
+ | Property | Type | Description |
2186
+ |----------|------|-------------|
2187
+ | `title` | `string \| null` | Section heading |
2188
+ | `body` | `string` | Body text |
2189
+ | `bullets` | `string[]` | Bullet points |
2190
+ | `subsections` | `PomSection[]` | Nested sections |
2191
+ | `numbered` | `boolean \| null` | Whether the section is numbered |
2192
+ | `numberedBullets` | `boolean` | Whether bullets are numbered |
2193
+
2194
+ #### Methods
2195
+
2196
+ | Method | Signature | Returns | Description |
2197
+ |--------|-----------|---------|-------------|
2198
+ | `addSubsection` | `(opts: { title, body?, bullets?, numbered?, numberedBullets? })` | `PomSection` | Add a nested section |
2199
+ | `toDict` | `()` | `PomSectionData` | Serialize |
2200
+ | `renderMarkdown` | `(level?: number, sectionNumber?: number[])` | `string` | Render as Markdown, starting at heading level 2 |
2201
+ | `renderXml` | `(indent?: number, sectionNumber?: number[])` | `string` | Render as XML |
2202
+
2203
+ ### PomBuilder Class
2204
+
2205
+ A `PomBuilder` holds the top-level sections.
2206
+
2207
+ #### Methods
2208
+
2209
+ | Method | Signature | Returns | Description |
2210
+ |--------|-----------|---------|-------------|
2211
+ | `addSection` | `(title, opts?)` | `this` | Add a top-level section |
2212
+ | `addToSection` | `(title, opts?)` | `this` | Append body text or bullets, creating the section if needed |
2213
+ | `addSubsection` | `(parentTitle, title, opts?)` | `this` | Add a subsection, creating the parent if needed |
2214
+ | `hasSection` | `(title: string)` | `boolean` | Whether a top-level section exists |
2215
+ | `getSection` | `(title: string)` | `PomSection \| undefined` | Top-level section by title |
2216
+ | `findSection` | `(title: string)` | `PomSection \| undefined` | Search every depth |
2217
+ | `addPomAsSubsection` | `(target: string \| PomSection, pomToAdd: PomBuilder)` | `this` | Append another builder's sections as subsections. Throws for an unknown title. |
2218
+ | `reset` | `()` | `this` | Remove every section |
2219
+ | `toDict` | `()` | `PomSectionData[]` | Serialize every section |
2220
+ | `toJson` | `()` | `string` | Serialize to a JSON string |
2221
+ | `renderMarkdown` | `()` | `string` | Render every section as Markdown |
2222
+ | `renderXml` | `()` | `string` | Render every section as XML under a `<prompt>` root |
2223
+ | `pom` | (getter) | `PromptObjectModel` | A new `PromptObjectModel` built from the sections |
2224
+ | `fromSections` | (static) `(sections: PomSectionData[])` | `PomBuilder` | Build a builder from serialized sections |
2225
+
2226
+ ---
2227
+
2228
+ ## SwmlBuilder
2229
+
2230
+ Import the class from the package root:
2231
+
2232
+ ```ts
2233
+ import { SwmlBuilder } from '@signalwire/sdk';
2234
+ ```
2235
+
2236
+ `SwmlBuilder` builds a SWML document, `{ version: '1.0.0', sections: { main: [...] } }`. Its constructor also installs one method per verb in the bundled SWML schema, such as `answer()`, `play()` and `hangup()`, each returning `this`.
2237
+
2238
+ ### Constructor
2239
+
2240
+ The constructor takes optional settings:
2241
+
2242
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2243
+ ```ts
2244
+ constructor(opts?: SwmlBuilderOptions)
2245
+ ```
2246
+
2247
+ | Option | Type | Default | Description |
2248
+ |--------|------|---------|-------------|
2249
+ | `initialDocument` | `{ version?: string; sections?: Record<string, unknown[]> }` | An empty document | Document to start from |
2250
+ | `enableValidation` | `boolean` | `true` unless `SWML_SKIP_SCHEMA_VALIDATION=true` | Validate verbs against the schema |
2251
+ | `schemaPath` | `string` | The bundled schema | Path to another SWML schema file |
2252
+ | `service` | `{ name: string; route: string }` | none | The service the builder belongs to, kept in `service` |
2253
+
2254
+ ### Methods
2255
+
2256
+ | Method | Signature | Returns | Description |
2257
+ |--------|-----------|---------|-------------|
2258
+ | `addVerb` | `(verbName: string, config: unknown, opts?: { skipValidation?: boolean })` | `void` | Append a verb to `main`. Throws `SchemaValidationError` for an unknown verb or invalid config when validation is on. |
2259
+ | `addVerbToSection` | `(sectionName: string, verbName: string, config: unknown, opts?: { skipValidation?: boolean })` | `void` | Append a verb to a section, creating it. Validates like `addVerb()`. |
2260
+ | `addSection` | `(sectionName: string)` | `this` | Create an empty section if it doesn't exist |
2261
+ | `say` | `(text: string, opts?: { voice?: string; language?: string; gender?: 'male' \| 'female'; volume?: number })` | `this` | Append a `play` verb with a `say:` URL |
2262
+ | `reset` | `()` | `this` | Start over with an empty document |
2263
+ | `setValidation` | `(enabled: boolean)` | `void` | Turn validation on or off |
2264
+ | `build` | `()` | `Record<string, unknown>` | The document object |
2265
+ | `render` | `()` | `string` | The document as JSON |
2266
+ | `document` | (getter) | `{ version: string; sections: Record<string, unknown[]> }` | The document being built |
2267
+ | `getSchemaUtils` | (static) `()` | `SchemaUtils` | The shared `SchemaUtils` for the bundled schema |
2268
+
2269
+ ---
2270
+
2271
+ ## PromptManager
2272
+
2273
+ Import the class from the package root:
2274
+
2275
+ ```ts
2276
+ import { PromptManager } from '@signalwire/sdk';
2277
+ ```
2278
+
2279
+ `PromptManager` holds an agent's raw prompt text, post-prompt and POM sections.
2280
+
2281
+ ### Constructor
2282
+
2283
+ The constructor takes the POM setting and an optional agent:
2284
+
2285
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2286
+ ```ts
2287
+ constructor(usePom?: boolean, agent?: AgentBase)
2288
+ ```
2289
+
2290
+ | Parameter | Type | Default | Description |
2291
+ |-----------|------|---------|-------------|
2292
+ | `usePom` | `boolean` | `true` | Create a `PomBuilder` for sections |
2293
+ | `agent` | `AgentBase` | none | Owning agent, kept in the readonly `agent` property |
2294
+
2295
+ ### Methods
2296
+
2297
+ | Method | Signature | Returns | Description |
2298
+ |--------|-----------|---------|-------------|
2299
+ | `setPromptText` | `(text: string)` | `void` | Set raw prompt text, which takes precedence over sections |
2300
+ | `setPostPrompt` | `(text: string)` | `void` | Set the post-prompt text |
2301
+ | `addSection` | `(title, opts?)` | `void` | Add a POM section, creating the builder if needed |
2302
+ | `addToSection` | `(title, opts?)` | `void` | Append to a section, creating it if needed |
2303
+ | `addSubsection` | `(parentTitle, title, opts?)` | `void` | Add a subsection, creating the parent if needed |
2304
+ | `hasSection` | `(title: string)` | `boolean` | Whether a section exists |
2305
+ | `getPrompt` | `()` | `string` | The raw prompt, or the sections rendered as Markdown |
2306
+ | `getRawPrompt` | `()` | `string \| null` | The raw prompt text |
2307
+ | `getPostPrompt` | `()` | `string \| null` | The post-prompt text |
2308
+ | `getPomBuilder` | `()` | `PomBuilder \| null` | The underlying builder |
2309
+
2310
+ ---
2311
+
2312
+ ## SessionManager
2313
+
2314
+ Import the class from the package root:
2315
+
2316
+ ```ts
2317
+ import { SessionManager } from '@signalwire/sdk';
2318
+ ```
2319
+
2320
+ `SessionManager` creates and checks the per-call tokens that secure SWAIG functions. A token is base64url of `callId.functionName.expiry.nonce.signature`, where the signature is an HMAC-SHA256 of the other fields. Validation needs no stored state, only the secret. It also keeps an in-memory metadata map per session.
2321
+
2322
+ ### Constructor
2323
+
2324
+ The constructor takes the token lifetime and the secret:
2325
+
2326
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2327
+ ```ts
2328
+ constructor(tokenExpirySecs?: number, secretKey?: string)
2329
+ ```
2330
+
2331
+ | Parameter | Type | Default | Description |
2332
+ |-----------|------|---------|-------------|
2333
+ | `tokenExpirySecs` | `number` | `900` | Token lifetime in seconds. `AgentBase` passes its `tokenExpirySecs` option, which defaults to `3600`. |
2334
+ | `secretKey` | `string` | 32 random bytes, hex-encoded | HMAC secret. `AgentBase` passes `swaigSecret`, then `SIGNALWIRE_SWAIG_SECRET`. |
2335
+
2336
+ A random secret exists only in its process. Tokens it signs stop validating after a restart and on other replicas, so set `swaigSecret` or `SIGNALWIRE_SWAIG_SECRET` to the same value on every replica.
2337
+
2338
+ ### Properties
2339
+
2340
+ | Property | Type | Description |
2341
+ |----------|------|-------------|
2342
+ | `tokenExpirySecs` | `number` | Token lifetime in seconds |
2343
+ | `secretKey` | `string` | HMAC secret |
2344
+ | `debugMode` | `boolean` | Whether `debugToken()` decodes tokens (default `false`) |
2345
+
2346
+ ### Methods
2347
+
2348
+ #### `createSession(callId?)`
2349
+
2350
+ Return `callId`, or a random identifier when it's omitted.
2351
+
2352
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2353
+ ```ts
2354
+ createSession(callId?: string): string
2355
+ ```
2356
+
2357
+ #### `generateToken(functionName, callId)` and `createToolToken(functionName, callId)`
2358
+
2359
+ Create a token for a function and call. The two methods are equivalent.
2360
+
2361
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2362
+ ```ts
2363
+ generateToken(functionName: string, callId: string): string
2364
+ createToolToken(functionName: string, callId: string): string
2365
+ ```
2366
+
2367
+ #### `validateToken(callId, functionName, token)`
2368
+
2369
+ Return `true` when the token is for this function and call, hasn't expired and carries a valid signature. An empty `callId` fails. The signature is compared in constant time.
2370
+
2371
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2372
+ ```ts
2373
+ validateToken(callId: string, functionName: string, token: string): boolean
2374
+ ```
2375
+
2376
+ #### `validateToolToken(functionName, token, callId)`
2377
+
2378
+ The same check as `validateToken()`, with the arguments in a different order.
2379
+
2380
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2381
+ ```ts
2382
+ validateToolToken(functionName: string, token: string, callId: string): boolean
2383
+ ```
2384
+
2385
+ #### `debugToken(token)`
2386
+
2387
+ Decode a token without checking its signature. When `debugMode` is `false`, it returns `{ valid_format: false, error: 'debug mode not enabled' }`. Otherwise it returns `{ valid_format, components, status }`. `components` holds `call_id`, `function`, `expiry`, `expiry_date`, `nonce` and `signature`, with `call_id` and `signature` shortened to eight characters. `status` holds `current_time`, `is_expired` and `expires_in_seconds`.
2388
+
2389
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2390
+ ```ts
2391
+ debugToken(token: string): DebugTokenResult
2392
+ ```
2393
+
2394
+ #### Metadata Methods
2395
+
2396
+ | Method | Signature | Returns | Description |
2397
+ |--------|-----------|---------|-------------|
2398
+ | `getSessionMetadata` | `(sessionId: string)` | `Record<string, unknown>` | The session's metadata, or `{}` |
2399
+ | `setSessionMetadata` | `(sessionId: string, metadata: Record<string, unknown>)` | `void` | Merge metadata into the session |
2400
+ | `setSessionMetadata` | `(sessionId: string, key: string, value: unknown)` | `boolean` | Set one key; returns `true` |
2401
+ | `deleteSessionMetadata` | `(sessionId: string)` | `boolean` | Delete the session's metadata |
2402
+ | `cleanup` | `(maxAgeMs?: number)` | `void` | Delete metadata older than `maxAgeMs` (default the token lifetime). It also runs when the map passes 1,000 sessions. |
2403
+ | `activateSession` | `(callId: string)` | `boolean` | Does nothing; returns `true` |
2404
+ | `endSession` | `(callId: string)` | `boolean` | Does nothing; returns `true` |
2405
+
2406
+ ---
2407
+
2408
+ ## Skills
2409
+
2410
+ Import the skill classes from the package root:
2411
+
2412
+ ```ts
2413
+ import { SkillBase, SkillManager, SkillRegistry } from '@signalwire/sdk';
2414
+ ```
2415
+
2416
+ ### SkillBase
2417
+
2418
+ `SkillBase` is the abstract base class for skills. A skill adds tools, prompt sections, hints and global data to an agent.
2419
+
2420
+ #### Constructor
2421
+
2422
+ Throws when the subclass doesn't set `SKILL_NAME` or `SKILL_DESCRIPTION`. The `swaig_fields` config key is moved to `swaigFields`.
2423
+
2424
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2425
+ ```ts
2426
+ constructor(config?: SkillConfig)
2427
+ ```
2428
+
2429
+ #### Properties
2430
+
2431
+ | Property | Type | Description |
2432
+ |----------|------|-------------|
2433
+ | `skillName` | `string` (readonly) | The class's `SKILL_NAME` |
2434
+ | `instanceId` | `string` (readonly) | `{SKILL_NAME}-{timestamp}-{random hex}` |
2435
+ | `swaigFields` | `Record<string, unknown>` (readonly) | Extra SWAIG fields merged into each of the skill's tools |
2436
+ | `params` | `Readonly<SkillConfig>` (getter) | The configuration, without `swaig_fields` |
2437
+ | `agent` | `AgentBase \| undefined` | The agent the skill was added to |
2438
+ | `config` | `SkillConfig` (protected) | The configuration |
2439
+ | `logger` | `Logger` (protected) | Logger named `signalwire.skills.{SKILL_NAME}` |
2440
+
2441
+ #### Static Members
2442
+
2443
+ | Member | Type | Description |
2444
+ |--------|------|-------------|
2445
+ | `SKILL_NAME` | `string` | Unique skill name. Required. |
2446
+ | `SKILL_DESCRIPTION` | `string` | Description. Required. |
2447
+ | `SKILL_VERSION` | `string` | Defaults to `'1.0.0'` |
2448
+ | `REQUIRED_ENV_VARS` | `readonly string[]` | Environment variables checked when the skill is added |
2449
+ | `REQUIRED_PACKAGES` | `readonly string[]` | npm packages checked with `import()` when the skill is added |
2450
+ | `SUPPORTS_MULTIPLE_INSTANCES` | `boolean` | Whether several instances can load, told apart by `tool_name` (default `false`) |
2451
+ | `getParameterSchema()` | `() => Record<string, ParameterSchemaEntry>` | Configuration schema. The base returns `swaig_fields` and `skip_prompt`, plus `tool_name` for multi-instance skills. |
2452
+
2453
+ #### Overridable Methods
2454
+
2455
+ | Method | Signature | Returns | Description |
2456
+ |--------|-----------|---------|-------------|
2457
+ | `setup` | `()` | `Promise<boolean>` | Runs when the skill is added. Returning `false` makes adding it fail. |
2458
+ | `getTools` | `()` | `SkillToolDefinition[]` | The skill's tools. The default returns those added with the protected `defineTool()`. |
2459
+ | `getDataMapTools` | `()` | `Record<string, unknown>[]` | Raw function definitions to register (default `[]`) |
2460
+ | `getPromptSections` | `()` | `SkillPromptSection[]` | Prompt sections; returns `[]` when `skip_prompt` is set. Override `_getPromptSections()` instead. |
2461
+ | `getHints` | `()` | `string[]` | Speech-recognition hints |
2462
+ | `getGlobalData` | `()` | `Record<string, unknown>` | Global data to merge |
2463
+ | `getInstanceKey` | `()` | `string` | The skill name, or `{skillName}_{tool_name}` for a multi-instance skill |
2464
+ | `cleanup` | `()` | `Promise<void>` | Runs when the skill is removed |
2465
+
2466
+ #### Utility Methods
2467
+
2468
+ | Method | Signature | Returns | Description |
2469
+ |--------|-----------|---------|-------------|
2470
+ | `validateEnvVars` | `()` | `string[]` | Missing required environment variables |
2471
+ | `hasAllEnvVars` | `()` | `boolean` | Whether none are missing |
2472
+ | `validatePackages` | `()` | `Promise<string[]>` | Required packages that can't be imported |
2473
+ | `hasAllPackages` | `()` | `Promise<boolean>` | Whether every package can be imported |
2474
+ | `isInitialized` | `()` | `boolean` | Whether setup completed |
2475
+ | `markInitialized` | `()` | `void` | Mark setup complete (the skill manager calls it) |
2476
+ | `getConfig` | `<T>(key: string, defaultValue?: T)` | `T` | A configuration value, or the default |
2477
+ | `setAgent` | `(agent: AgentBase)` | `void` | Set `agent` |
2478
+ | `getSkillNamespace` | `()` | `string` | Key for the skill's data in global data, such as `skill:datetime` |
2479
+ | `getSkillData` | `(rawData: SwaigRequest)` | `Record<string, unknown>` | The skill's data from a request's global data |
2480
+ | `updateSkillData` | `(result: FunctionResult, data: Record<string, unknown>)` | `FunctionResult` | Add a `set_global_data` action for the skill's namespace |
2481
+
2482
+ ### SkillManager
2483
+
2484
+ `SkillManager` loads and removes an agent's skills.
2485
+
2486
+ #### Constructor
2487
+
2488
+ The constructor has this signature:
2489
+
2490
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2491
+ ```ts
2492
+ constructor(agent?: AgentBase)
2493
+ ```
2494
+
2495
+ #### Methods
2496
+
2497
+ | Method | Signature | Returns | Description |
2498
+ |--------|-----------|---------|-------------|
2499
+ | `addSkill` | `(skill: SkillBase)` | `Promise<void>` | Validate and set up a skill. Throws for a duplicate single-instance skill, missing environment variables or packages, or a failed `setup()`. |
2500
+ | `loadSkill` | `(skillClass: typeof SkillBase, config?: SkillConfig)` | `Promise<[boolean, string]>` | Create and add a skill; on `agent.skillManager` it also registers the skill's tools, prompt sections, hints and global data on the agent. Returns `[false, message]` instead of throwing |
2501
+ | `loadSkillByName` | `(skillName: string, config?: SkillConfig)` | `Promise<[boolean, string]>` | Create a skill from the registry and add it, as `loadSkill` does |
2502
+ | `removeSkill` | `(keyOrId: string)` | `Promise<boolean>` | Remove by instance key or instance ID |
2503
+ | `removeSkillByName` | `(skillName: string)` | `Promise<number>` | Remove every instance with the name; returns the count |
2504
+ | `hasSkill` | `(skillName: string)` | `boolean` | Whether an instance with the name is loaded |
2505
+ | `hasSkillByKey` | `(instanceKey: string)` | `boolean` | Whether an instance with the key is loaded |
2506
+ | `getSkill` | `(keyOrId: string)` | `SkillBase \| undefined` | By instance key or instance ID |
2507
+ | `listSkills` | `()` | `{ name, instanceId, initialized }[]` | Loaded skills |
2508
+ | `listSkillKeys` | `()` | `string[]` | Loaded instance keys |
2509
+ | `getAllTools` | `()` | `SkillToolDefinition[]` | Every skill's tools |
2510
+ | `getAllPromptSections` | `()` | `SkillPromptSection[]` | Every skill's prompt sections |
2511
+ | `getAllHints` | `()` | `string[]` | Every skill's hints |
2512
+ | `getMergedGlobalData` | `()` | `Record<string, unknown>` | Every skill's global data, merged |
2513
+ | `clear` | `()` | `Promise<void>` | Remove every skill |
2514
+ | `loadedSkills` | (getter) | `ReadonlyMap<string, SkillBase>` | Loaded skills by instance key |
2515
+ | `size` | (getter) | `number` | Number of loaded skills |
2516
+
2517
+ ### SkillRegistry
2518
+
2519
+ `SkillRegistry` maps skill names to classes. It's a process-wide singleton; `SIGNALWIRE_SKILL_PATHS` (colon-separated) sets its initial search paths.
2520
+
2521
+ #### Static Methods
2522
+
2523
+ | Method | Signature | Returns | Description |
2524
+ |--------|-----------|---------|-------------|
2525
+ | `getInstance` | `()` | `SkillRegistry` | The singleton |
2526
+ | `resetInstance` | `()` | `void` | Drop the singleton, for tests |
2527
+
2528
+ #### Instance Methods
2529
+
2530
+ | Method | Signature | Returns | Description |
2531
+ |--------|-----------|---------|-------------|
2532
+ | `register` | `(SkillClass: typeof SkillBase)` | `void` | Register a class under its `SKILL_NAME`. Throws when the name or parameter schema is empty; a locked name is kept and a warning logged. |
2533
+ | `lock` | `(names?: string[])` | `void` | Stop names (default: all registered) from being overwritten, unregistered or cleared |
2534
+ | `unregister` | `(name: string)` | `boolean` | Remove a registration; returns `false` for a locked name, which stays registered |
2535
+ | `create` | `(name: string, config?: SkillConfig)` | `SkillBase \| null` | Create an instance |
2536
+ | `getSkillClass` | `(name: string)` | `typeof SkillBase \| undefined` | The registered class |
2537
+ | `has` | `(name: string)` | `boolean` | Whether the name is registered |
2538
+ | `listRegistered` | `()` | `string[]` | Registered names |
2539
+ | `listSkills` | `()` | `SkillSchemaInfo[]` | Registered skills with metadata |
2540
+ | `getSkillSchema` | `(name: string)` | `SkillSchemaInfo \| undefined` | One skill's metadata |
2541
+ | `getAllSkillsSchema` | `()` | `Record<string, SkillSchemaInfo>` | Every skill's metadata |
2542
+ | `addSearchPath` | `(path: string)` | `void` | Add a discovery directory |
2543
+ | `addSkillDirectory` | `(path: string)` | `void` | Add a discovery directory; throws when it doesn't exist or isn't a directory |
2544
+ | `getSearchPaths` | `()` | `string[]` | Search paths |
2545
+ | `getExternalPaths` | `()` | `string[]` | Directories added with `addSkillDirectory()` |
2546
+ | `discoverFromDirectory` | `(dirPath: string)` | `Promise<string[]>` | Import skill files from a directory and register them. Does nothing unless `SWML_SKILL_DISCOVERY_ENABLED=true`. |
2547
+ | `discoverAll` | `()` | `Promise<string[]>` | Discover from every search path and every `addSkillDirectory()` directory |
2548
+ | `listAllSkillSources` | `()` | `Record<string, string[]>` | Registered names grouped by source |
2549
+ | `clear` | `()` | `void` | Remove every registration except locked names |
2550
+ | `size` | (getter) | `number` | Number of registered skills |
2551
+
2552
+ The package root also exports functions that use the singleton: `listSkills()`, `listSkillsWithParams()`, `registerSkill(skillClass)` and `addSkillDirectory(path)`. `addSkillDirectory()` calls `addSearchPath()`.
2553
+
2554
+ ---
2555
+
2556
+ ## Prefab Agents
2557
+
2558
+ Prefab agents are `AgentBase` subclasses with their own prompt sections and tools. Each takes a config object; `agentOptions` is passed to `AgentBase`. For examples, see the [prefabs guide](prefabs-guide.md). `BedrockAgent`, which renders an `amazon_bedrock` verb instead of `ai`, has its own guide: [Bedrock Agent](bedrock_agent.md).
2559
+
2560
+ ### InfoGathererAgent
2561
+
2562
+ Import the class from the package root:
2563
+
2564
+ ```ts
2565
+ import { InfoGathererAgent } from '@signalwire/sdk';
2566
+ ```
2567
+
2568
+ `InfoGathererAgent` asks the caller a list of questions, one at a time. In static mode, the questions come from the config. In dynamic mode, a callback supplies them for each request.
2569
+
2570
+ #### InfoGathererConfig
2571
+
2572
+ | Property | Type | Default | Description |
2573
+ |----------|------|---------|-------------|
2574
+ | `name` | `string` | `'info_gatherer'` | Agent name |
2575
+ | `route` | `string` | `'/info_gatherer'` | HTTP route |
2576
+ | `questions` | `InfoGathererQuestion[]` | none | Questions to ask (static mode). Omit for dynamic mode. |
2577
+ | `questionCallback` | `InfoGathererQuestionCallback` | none | Supplies the questions for each request (dynamic mode) |
2578
+ | `agentOptions` | `Partial<AgentOptions>` | none | Passed to `AgentBase` |
2579
+
2580
+ #### InfoGathererQuestion
2581
+
2582
+ | Property | Type | Description |
2583
+ |----------|------|-------------|
2584
+ | `key_name` | `string` | Key the answer is stored under |
2585
+ | `question_text` | `string` | Question to ask |
2586
+ | `confirm` | `boolean` | Whether the caller must confirm the answer before it's submitted |
2587
+
2588
+ Built-in tools: `start_questions` and `submit_answer`.
2589
+
2590
+ In dynamic mode, call `setQuestionCallback(cb)` or pass `questionCallback`. The callback receives `(queryParams, bodyParams, headers)` and returns the questions for that request. When no callback is registered, or it throws, the agent asks for a name and a message.
2591
+
2592
+ ### SurveyAgent
2593
+
2594
+ Import the class from the package root:
2595
+
2596
+ ```ts
2597
+ import { SurveyAgent } from '@signalwire/sdk';
2598
+ ```
2599
+
2600
+ `SurveyAgent` runs a survey with typed questions, branching and scoring.
2601
+
2602
+ #### SurveyConfig
2603
+
2604
+ | Property | Type | Default | Description |
2605
+ |----------|------|---------|-------------|
2606
+ | `name` | `string` | `'survey'` | Agent name |
2607
+ | `route` | `string` | `'/survey'` | HTTP route |
2608
+ | `surveyName` | `string` | (required) | Survey name used in the prompt and global data |
2609
+ | `questions` | `SurveyQuestion[]` | (required) | Survey questions in order |
2610
+ | `introduction` | `string` | `` `Welcome to our ${surveyName}. We appreciate your participation.` `` | Opening message, also installed as a non-bargeable static greeting |
2611
+ | `conclusion` | `string` | `'Thank you for completing our survey. Your feedback is valuable to us.'` | Closing message |
2612
+ | `brandName` | `string` | `'Our Company'` | Company the agent represents |
2613
+ | `maxRetries` | `number` | `2` | Retries for an invalid answer |
2614
+ | `onComplete` | `(responses, score) => void \| Promise<void>` | none | Called when the survey is finished |
2615
+ | `agentOptions` | `Partial<AgentOptions>` | none | Passed to `AgentBase` |
2616
+
2617
+ #### SurveyQuestion
2618
+
2619
+ | Property | Type | Description |
2620
+ |----------|------|-------------|
2621
+ | `id` | `string` | Question identifier |
2622
+ | `text` | `string` | Question text |
2623
+ | `type` | `'multiple_choice' \| 'open_ended' \| 'rating' \| 'yes_no'` | Question type |
2624
+ | `options` | `string[]` | Choices for `multiple_choice` |
2625
+ | `scale` | `number` | Upper bound of a `rating` scale from 1 (default `5`) |
2626
+ | `required` | `boolean` | Whether an answer is required (default `true`) |
2627
+ | `nextQuestion` | `string \| Record<string, string>` | Next question ID, or a map from answer to next question ID |
2628
+ | `points` | `number \| Record<string, number>` | Points for any answer, or per answer |
2629
+
2630
+ Built-in tools: `validate_response`, `log_response`, `answer_question`, `get_current_question` and `get_survey_progress`.
2631
+
2632
+ ### FAQBotAgent
2633
+
2634
+ Import the class from the package root:
2635
+
2636
+ ```ts
2637
+ import { FAQBotAgent } from '@signalwire/sdk';
2638
+ ```
2639
+
2640
+ `FAQBotAgent` answers questions from a list of FAQs. Its `search_faqs` tool scores the FAQs by word overlap with the query and returns up to three matching questions; the answers are in the agent's prompt.
2641
+
2642
+ #### FAQBotConfig
2643
+
2644
+ | Property | Type | Default | Description |
2645
+ |----------|------|---------|-------------|
2646
+ | `name` | `string` | `'faq_bot'` | Agent name |
2647
+ | `route` | `string` | `'/faq'` | HTTP route |
2648
+ | `faqs` | `FAQEntry[]` | (required) | The FAQs |
2649
+ | `suggestRelated` | `boolean` | `true` | Add a related-questions prompt section and instruction |
2650
+ | `persona` | `string` | A helpful FAQ bot description | Text of the "Personality" prompt section |
2651
+ | `threshold` | `number` | `0.5` | Minimum match score, from 0 to 1 |
2652
+ | `escalationMessage` | `string` | An apology that offers a transfer | Message used when nothing matches |
2653
+ | `escalationNumber` | `string` | none | Transfer number; the `escalate` tool is registered only when it's set |
2654
+ | `agentOptions` | `Partial<AgentOptions>` | none | Passed to `AgentBase` |
2655
+
2656
+ #### FAQEntry
2657
+
2658
+ | Property | Type | Description |
2659
+ |----------|------|-------------|
2660
+ | `question` | `string` | Question text |
2661
+ | `answer` | `string` | Answer |
2662
+ | `keywords` | `string[]` | Extra words for matching |
2663
+ | `categories` | `string[]` | Categories, used by the `category` argument of `search_faqs` |
2664
+
2665
+ Built-in tools: `search_faqs`, and `escalate` when `escalationNumber` is set.
2666
+
2667
+ ### ConciergeAgent
2668
+
2669
+ Import the class from the package root:
2670
+
2671
+ ```ts
2672
+ import { ConciergeAgent } from '@signalwire/sdk';
2673
+ ```
2674
+
2675
+ `ConciergeAgent` answers questions about a venue's services, amenities, hours and directions.
2676
+
2677
+ #### ConciergeConfig
2678
+
2679
+ | Property | Type | Default | Description |
2680
+ |----------|------|---------|-------------|
2681
+ | `name` | `string` | `'concierge'` | Agent name |
2682
+ | `route` | `string` | `'/concierge'` | HTTP route |
2683
+ | `venueName` | `string` | (required) | Venue or business name |
2684
+ | `services` | `string[]` | (required) | Services offered |
2685
+ | `amenities` | `Record<string, Record<string, string>>` | (required) | Amenities, each with detail pairs |
2686
+ | `hoursOfOperation` | `Record<string, string>` | `{ default: '9 AM - 5 PM' }` | Hours by category |
2687
+ | `specialInstructions` | `string[]` | `[]` | Extra instruction bullets |
2688
+ | `welcomeMessage` | `string` | none | When set, installed as a non-bargeable static greeting |
2689
+ | `agentOptions` | `Partial<AgentOptions>` | none | Passed to `AgentBase` |
2690
+
2691
+ Built-in tools: `check_availability` and `get_directions`.
2692
+
2693
+ ### ReceptionistAgent
2694
+
2695
+ Import the class from the package root:
2696
+
2697
+ ```ts
2698
+ import { ReceptionistAgent } from '@signalwire/sdk';
2699
+ ```
2700
+
2701
+ `ReceptionistAgent` greets callers, collects their details and transfers them to a department.
2702
+
2703
+ #### ReceptionistConfig
2704
+
2705
+ | Property | Type | Default | Description |
2706
+ |----------|------|---------|-------------|
2707
+ | `name` | `string` | `'receptionist'` | Agent name |
2708
+ | `route` | `string` | `'/receptionist'` | HTTP route |
2709
+ | `departments` | `ReceptionistDepartment[]` | (required) | Departments to transfer to |
2710
+ | `greeting` | `string` | `'Thank you for calling. How can I help you today?'` | Initial greeting |
2711
+ | `voice` | `string` | `'rime.spore'` | Voice passed to `addLanguage()` |
2712
+ | `companyName` | `string` | none | Added to the greeting when set |
2713
+ | `checkInEnabled` | `boolean` | `false` | Register the `check_in_visitor` tool |
2714
+ | `onVisitorCheckIn` | `(visitor: Record<string, string>) => void \| Promise<void>` | none | Called when a visitor checks in |
2715
+ | `agentOptions` | `Partial<AgentOptions>` | none | Passed to `AgentBase` |
2716
+
2717
+ #### ReceptionistDepartment
2718
+
2719
+ | Property | Type | Description |
2720
+ |----------|------|-------------|
2721
+ | `name` | `string` | Department identifier |
2722
+ | `description` | `string` | Description the model reads |
2723
+ | `number` | `string` | Phone number or SIP address `transfer_call` connects to |
2724
+
2725
+ Built-in tools: `collect_caller_info`, `transfer_call`, and `check_in_visitor` when `checkInEnabled` is set.
2726
+
2727
+ ---
2728
+
2729
+ ## Capability Helpers
2730
+
2731
+ A browser client, such as the SignalWire address widget, declares what it can render in the user variables it sends when it dials: `vars.userVariables.capabilities`. These functions read those declarations from a SWML request body. A declaration is a hint for deciding what to offer, not a permission: the caller controls its own user variables. Missing or malformed data counts as not declared.
2732
+
2733
+ Import the helpers from the package root:
2734
+
2735
+ ```ts
2736
+ import { userVariables, declaredCapabilities, hasCapability } from '@signalwire/sdk';
2737
+ ```
2738
+
2739
+ | Function | Signature | Returns |
2740
+ |----------|-----------|---------|
2741
+ | `userVariables` | `(bodyParams: unknown): Record<string, unknown>` | `vars.userVariables` from a request body, or `{}` |
2742
+ | `declaredCapabilities` | `(bodyParams: unknown): ReadonlySet<string>` | Names declared with a truthy value. Accepts a request body or user variables that are already extracted. An empty array or object counts as false. |
2743
+ | `hasCapability` | `(bodyParams: unknown, name: string): boolean` | Whether `name` is declared truthy |
2744
+
2745
+ The [`addPerCallConfig()` example](#addpercallconfigcb) uses `hasCapability()` in a per-request callback.
2746
+
2747
+ ---
2748
+
2749
+ ## Post-Prompt Helpers
2750
+
2751
+ The voice and chat engines deliver the post-prompt in different shapes. These helpers read either one into the same structure. None of them throws: data they can't use becomes an empty value.
2752
+
2753
+ Import the helpers from the package root:
2754
+
2755
+ ```ts
2756
+ import {
2757
+ normalizePostPrompt,
2758
+ parsePostPromptData,
2759
+ dialogueTurns,
2760
+ stripJsonFence,
2761
+ NormalizedPostPrompt,
2762
+ DIALOGUE_ROLES,
2763
+ } from '@signalwire/sdk';
2764
+ ```
2765
+
2766
+ | Name | Signature | Description |
2767
+ |------|-----------|-------------|
2768
+ | `normalizePostPrompt` | `(body: unknown): NormalizedPostPrompt` | Normalize a whole post-prompt body. The result is frozen. |
2769
+ | `parsePostPromptData` | `(data: unknown): Record<string, unknown>` | Read `post_prompt_data` in any shape: an object inside `parsed`, flat keys, or a `raw` string (with or without a code fence). Prose that isn't JSON becomes `{ summary: text }`. |
2770
+ | `dialogueTurns` | `(callLog: unknown, opts?: { roles?: readonly string[]; dropEcho?: string \| null }): DialogueTurn[]` | The turns with the given roles (default `DIALOGUE_ROLES`) and non-empty content, without entries that carry `tool_calls`. A turn whose content equals `dropEcho` is dropped. |
2771
+ | `stripJsonFence` | `(text: string): string` | Remove a surrounding code fence, such as one labeled `json` |
2772
+ | `DIALOGUE_ROLES` | `readonly string[]` | `['user', 'assistant']` |
2773
+
2774
+ `DialogueTurn` is `{ role: string; content: string }`. A `NormalizedPostPrompt` has these readonly properties:
2775
+
2776
+ | Property | Type | Description |
2777
+ |----------|------|-------------|
2778
+ | `medium` | `string` | The body's `conversation_type`, or `''` |
2779
+ | `conversationId` | `string \| null` | The body's `conversation_id`, or `null` |
2780
+ | `summary` | `Record<string, unknown>` | `parsePostPromptData(body.post_prompt_data)` |
2781
+ | `dialogue` | `readonly DialogueTurn[]` | Dialogue from `call_log`, `raw_call_log` or `raw_messages`, the first that isn't empty, without the chat engine's copy of the summary |
2782
+ | `callId` | `string \| null` | The body's `call_id`, or `null` |
2783
+ | `raw` | `Record<string, unknown>` | The whole body |
2784
+
2785
+ **Example:**
2786
+
2787
+ ```ts
2788
+ import { AgentBase, normalizePostPrompt } from '@signalwire/sdk';
2789
+
2790
+ class SummaryAgent extends AgentBase {
2791
+ override onSummary(summary: unknown, rawData: unknown): void {
2792
+ const leg = normalizePostPrompt(rawData);
2793
+ console.log(leg.medium, leg.conversationId ?? leg.callId, leg.summary, leg.dialogue.length);
2794
+ }
2795
+ }
2796
+
2797
+ const summaries = new SummaryAgent({ name: 'summaries' });
2798
+ summaries.setPostPrompt('Summarize the call as JSON with keys "topic" and "outcome".');
2799
+ ```
2800
+
2801
+ ---
2802
+
2803
+ ## AI Chat Gateway and Handoff
2804
+
2805
+ The package root also exports the AI Chat client and two classes that let a browser chat with an agent:
2806
+
2807
+ - `AIChatClient`: a client for the SignalWire AI Chat service
2808
+ - `ChatGateway`: a proxy you mount in your app, so a browser widget can chat with an agent using a publishable key, not your API token
2809
+ - `HandoffRouter`: routes that move a conversation between a phone call and chat, and let a browser type into a live call
2810
+
2811
+ For a guide to all three, see [AI Chat](ai_chat.md).
2812
+
2813
+ ### ChatGateway
2814
+
2815
+ The constructor takes a `ChatGatewayOptions` object:
2816
+
2817
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2818
+ ```ts
2819
+ constructor(options: ChatGatewayOptions)
2820
+ ```
2821
+
2822
+ | Option | Type | Default | Description |
2823
+ |--------|------|---------|-------------|
2824
+ | `configUrl` | `string` | (required) | The agent config the key reaches. It's sent on every call and never taken from the request. |
2825
+ | `key` | `string` | `SIGNALWIRE_CHAT_GATEWAY_KEY`, else a generated key | The publishable key the browser presents as a bearer token |
2826
+ | `allowedOrigins` | `readonly string[]` | `[]` | Origins allowed to use the key; localhost is always allowed |
2827
+ | `client` | `AIChatClient` | Built from the environment | The client that forwards requests |
2828
+ | `secret` | `string \| Uint8Array` | `SIGNALWIRE_CHAT_GATEWAY_SECRET`, else random per process | Key that signs conversation handles. Set it when you run several replicas or restart often. |
2829
+ | `handleTtl` | `number` | 86400 | Seconds a handle stays valid |
2830
+ | `conversationTimeout` | `number \| null` | The service default | Idle seconds before the service ends a conversation |
2831
+ | `maxNewConversations` | `number` | 60 | New conversations per window |
2832
+ | `maxTurns` | `number` | 200 | Turns per conversation |
2833
+ | `windowSeconds` | `number` | 60 | Window for `maxNewConversations`, in seconds |
2834
+
2835
+ `router()` returns a Hono app that answers `POST /` with the JSON-RPC methods `start`, `chat`, `log` and `end`. The caps are counted in the process, so behind several replicas each keeps its own count. The origin check stops a key pasted into another page, since the browser sends that page's origin. It doesn't stop a client that sends no origin or a false one. The gateway forwards the browser's `user_meta_data` (up to `MAX_USER_METADATA_BYTES`, 8 KiB), which is the visitor's claim about itself, not a verified value. A request body over `MAX_REQUEST_BODY_BYTES` (64 KiB) or a chat message over `MAX_MESSAGE_BYTES` (8 KiB of UTF-8) gets 413. `close()` closes a client the gateway created.
2836
+
2837
+ ### HandoffRouter
2838
+
2839
+ The constructor takes a `HandoffRouterOptions` object:
2840
+
2841
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2842
+ ```ts
2843
+ constructor(options: HandoffRouterOptions)
2844
+ ```
2845
+
2846
+ | Option | Type | Default | Description |
2847
+ |--------|------|---------|-------------|
2848
+ | `gateway` | `ChatGateway` | (required) | Issues and reads handles and checks origins |
2849
+ | `captureLeg` | `(conversationId: string, medium: string) => boolean \| Promise<boolean>` | none | Ends a leg and writes its record; returns `true` once the record is written |
2850
+ | `endCall` | `(callId: string) => void \| Promise<void>` | none | Hangs up a call |
2851
+ | `sendMessage` | `(callId: string, text: string) => boolean \| Promise<boolean>` | none | Delivers typed text into a call. Without it, `/say` returns 404. |
2852
+ | `nextConversationId` | `(conversationId: string) => string` | Appends or increments `.N` | The ID of the next leg |
2853
+ | `nonceTtl` | `number` | 3600 | Seconds a nonce can be redeemed |
2854
+ | `maxMessagesPerCall` | `number` | 200 | Typed messages allowed per call |
2855
+ | `captureTimeout` | `number` | 8 | Seconds to wait for `captureLeg` |
2856
+ | `registry` | `Map<string, NonceEntry>` | A new `Map` | The nonce table. Supply shared storage to run more than one replica. It may return copies of its entries, because the router writes every change back with `set()`. Its read-then-write steps aren't atomic across replicas that share it. |
2857
+
2858
+ Your application puts a random `handoff_nonce` in the user variables of a dial. From that call's per-request callback, it calls `register(nonce, { conversationId, callId })` with the call ID from the platform's request. The browser later presents the nonce, never a call ID.
2859
+
2860
+ `router()` returns a Hono app with three routes:
2861
+
2862
+ - `POST /handoff` takes `{ nonce }` and returns `{ handle }`, once per nonce.
2863
+ - `POST /escalate` takes `{ handle }` and returns `{ ok: true }`.
2864
+ - `POST /say` takes `{ nonce, text }` and returns `{ ok: true }`.
2865
+
2866
+ A nonce or handle that doesn't verify gets 404, and a refused origin gets 403. A body over `MAX_REQUEST_BODY_BYTES` gets 413 on every route, and `/say` text over `MAX_MESSAGE_BYTES` gets 413, both checked before the nonce is looked up.
2867
+
2868
+ Mount both routers at the same prefix, because the browser derives every path from the gateway's URL:
2869
+
2870
+ <!-- snippet: no-run constructs an AIChatClient, which needs SignalWire credentials in the environment -->
2871
+ ```ts
2872
+ import { AgentBase, ChatGateway, HandoffRouter } from '@signalwire/sdk';
2873
+
2874
+ const shop = new AgentBase({ name: 'shop', route: '/agent' });
2875
+ const gateway = new ChatGateway({
2876
+ configUrl: 'https://shop.example.com/agent',
2877
+ allowedOrigins: ['https://shop.example.com'],
2878
+ });
2879
+ const handoff = new HandoffRouter({ gateway });
2880
+ shop.mount(gateway.router(), { prefix: '/chat' });
2881
+ shop.mount(handoff.router(), { prefix: '/chat' });
2882
+ ```
2883
+
2884
+ ---
2885
+
2886
+ ## Utility Classes
2887
+
2888
+ ### AuthHandler
2889
+
2890
+ Import the class from the package root:
2891
+
2892
+ ```ts
2893
+ import { AuthHandler } from '@signalwire/sdk';
2894
+ ```
2895
+
2896
+ `AuthHandler` checks a request's headers against a bearer token, an API key, basic auth or a custom validator. Credentials are compared in constant time.
2897
+
2898
+ #### Constructor
2899
+
2900
+ See [AuthConfig](#authconfig). The configuration is kept in the readonly `config` property.
2901
+
2902
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2903
+ ```ts
2904
+ constructor(config: AuthConfig)
2905
+ ```
2906
+
2907
+ #### Methods
2908
+
2909
+ | Method | Signature | Returns | Description |
2910
+ |--------|-----------|---------|-------------|
2911
+ | `validate` | `(headers: Record<string, string>)` | `Promise<boolean>` | `true` when any configured method accepts the request. With no method configured, it allows the request and logs a warning, unless `allowUnauthenticated` is `false`. |
2912
+ | `verifyBasicAuth` | `(username: string, password: string)` | `boolean` | Check basic-auth credentials |
2913
+ | `verifyBearerToken` | `(token: string)` | `boolean` | Check a bearer token |
2914
+ | `verifyApiKey` | `(key: string)` | `boolean` | Check an API key |
2915
+ | `middleware` | `(optional?: boolean)` | Hono middleware | Reject with `401` unless `optional` is `true` |
2916
+ | `expressMiddleware` | `(optional?: boolean)` | Express middleware | The same check for Express or Connect |
2917
+ | `getAuthInfo` | `()` | `{ basic?, bearer?, apiKey? }` | Which methods are configured |
2918
+ | `hasBearerAuth` | `()` | `boolean` | Whether a bearer token is configured |
2919
+ | `hasApiKeyAuth` | `()` | `boolean` | Whether an API key is configured |
2920
+ | `hasBasicAuth` | `()` | `boolean` | Whether basic auth is configured |
2921
+
2922
+ The custom validator receives `{ headers, method, url }`; `validate()` passes `''` for `method` and `url`.
2923
+
2924
+ ### ConfigLoader
2925
+
2926
+ Import the class from the package root:
2927
+
2928
+ ```ts
2929
+ import { ConfigLoader } from '@signalwire/sdk';
2930
+ ```
2931
+
2932
+ `ConfigLoader` loads a JSON file after replacing `${VAR}` and `${VAR|default}` with environment values. An unset variable with no default becomes an empty string.
2933
+
2934
+ #### Constructor
2935
+
2936
+ A single path is loaded at once and throws when the file doesn't exist. From an array, the first file that exists is loaded, and none existing isn't an error.
2937
+
2938
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2939
+ ```ts
2940
+ constructor(filePaths?: string | string[])
2941
+ ```
2942
+
2943
+ #### Static Methods
2944
+
2945
+ | Method | Signature | Returns | Description |
2946
+ |--------|-----------|---------|-------------|
2947
+ | `search` | `(filename: string, additionalPaths?: string[], serviceName?: string)` | `ConfigLoader \| null` | Load the first match. The search covers service-specific names, then `additionalPaths`, then the current directory, `./config`, `~/.signalwire`, `./.swml`, `~/.swml` and `/etc/swml`. |
2948
+ | `findConfigFile` | `(serviceName?: string, additionalPaths?: string[])` | `string \| null` | The path of the first config file found, without loading it |
2949
+
2950
+ #### Instance Methods
2951
+
2952
+ | Method | Signature | Returns | Description |
2953
+ |--------|-----------|---------|-------------|
2954
+ | `load` | `(filePath: string)` | `this` | Load a file. Throws when it doesn't exist. |
2955
+ | `loadFromObject` | `(obj: Record<string, unknown>)` | `this` | Use an object as the configuration |
2956
+ | `get` | `<T>(path: string, defaultValue?: T)` | `T` | Value at a dotted path, such as `'server.port'` |
2957
+ | `set` | `(path: string, value: unknown)` | `this` | Set a value at a dotted path |
2958
+ | `has` | `(path: string)` | `boolean` | Whether a dotted path exists |
2959
+ | `getSection` | `(section: string)` | `Record<string, unknown>` | A top-level section with variables substituted, or `{}` |
2960
+ | `substituteVars` | `(value: unknown, maxDepth?: number)` | `unknown` | Substitute variables in any value |
2961
+ | `mergeWithEnv` | `(envPrefix?: string)` | `Record<string, unknown>` | The configuration plus environment variables with the prefix (default `'SWML_'`) that aren't already set |
2962
+ | `interpolateEnvVars` | `(input: string)` | `string` | Substitute variables in a string |
2963
+ | `getConfig` | `()` | `Record<string, unknown>` | A shallow copy of the configuration |
2964
+ | `getConfigFile` | `()` | `string \| null` | Absolute path of the loaded file |
2965
+ | `hasConfig` | `()` | `boolean` | Whether a file or object was loaded |
2966
+ | `configPaths` | (getter) | `string[]` | The paths passed to the constructor |
2967
+
2968
+ `get()` and `set()` ignore paths that contain `__proto__`, `constructor` or `prototype`.
2969
+
2970
+ ### Logger
2971
+
2972
+ Import the logger and its functions from the package root:
2973
+
2974
+ ```ts
2975
+ import { Logger, getLogger, setGlobalLogLevel, suppressAllLogs, setGlobalLogFormat, setGlobalLogColor, setGlobalLogStream, resetLoggingConfiguration } from '@signalwire/sdk';
2976
+ ```
2977
+
2978
+ The SDK logs through `Logger` instances that share one global configuration, read from the environment.
2979
+
2980
+ #### Environment Variables
2981
+
2982
+ | Variable | Values | Default | Description |
2983
+ |----------|--------|---------|-------------|
2984
+ | `SIGNALWIRE_LOG_LEVEL` | `debug`, `info`, `warn`, `error` | `info` | Minimum level. Case doesn't matter; an unknown value means `info`. |
2985
+ | `SIGNALWIRE_LOG_MODE` | `off`, `stderr`, `auto` | `auto` | `off` silences all SDK logging. `auto` turns logging off under CGI and writes to standard error on Lambda. |
2986
+ | `SIGNALWIRE_LOG_FORMAT` | `text`, `json` | `text` | Output format |
2987
+ | `SIGNALWIRE_LOG_COLOR` | `true`, `false` | On when standard output is a terminal | ANSI colors in text output |
2988
+
2989
+ #### Logger Constructor
2990
+
2991
+ The constructor has this signature:
2992
+
2993
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
2994
+ ```ts
2995
+ constructor(name: string, context?: Record<string, unknown>)
2996
+ ```
2997
+
2998
+ #### Logger Methods
2999
+
3000
+ | Method | Signature | Returns | Description |
3001
+ |--------|-----------|---------|-------------|
3002
+ | `debug` | `(msg: string, data?: Record<string, unknown>)` | `void` | Log at debug level |
3003
+ | `info` | `(msg: string, data?: Record<string, unknown>)` | `void` | Log at info level |
3004
+ | `warn` | `(msg: string, data?: Record<string, unknown>)` | `void` | Log at warn level |
3005
+ | `error` | `(msg: string, data?: Record<string, unknown>)` | `void` | Log at error level |
3006
+ | `bind` | `(context: Record<string, unknown>)` | `Logger` | A logger with the context added to every entry |
3007
+
3008
+ #### Module Functions
3009
+
3010
+ | Function | Signature | Description |
3011
+ |----------|-----------|-------------|
3012
+ | `getLogger` | `(name: string): Logger` | The logger for a name, created once and cached |
3013
+ | `setGlobalLogLevel` | `(level: LogLevel): void` | Set the minimum level for every logger |
3014
+ | `suppressAllLogs` | `(suppress?: boolean): void` | Silence (default) or restore every logger |
3015
+ | `setGlobalLogFormat` | `(format: 'text' \| 'json'): void` | Set the output format |
3016
+ | `setGlobalLogColor` | `(enabled: boolean): void` | Turn ANSI colors on or off |
3017
+ | `setGlobalLogStream` | `(stream: 'stdout' \| 'stderr'): void` | Set the output stream |
3018
+ | `resetLoggingConfiguration` | `(): void` | Read the configuration from the environment again |
3019
+ | `getExecutionMode` | `(): string` | `'cgi'`, `'lambda'`, `'google_cloud_function'`, `'azure_function'` or `'server'`, from the environment |
3020
+ | `stripControlChars` | `<T>(data: T): T` | A copy of a record with control characters removed from its strings |
3021
+
3022
+ ### SslConfig
3023
+
3024
+ Import the class from the package root:
3025
+
3026
+ ```ts
3027
+ import { SslConfig } from '@signalwire/sdk';
3028
+ ```
3029
+
3030
+ `SslConfig` holds TLS settings from explicit options or the environment.
3031
+
3032
+ #### Environment Variables
3033
+
3034
+ | Variable | Description |
3035
+ |----------|-------------|
3036
+ | `SWML_SSL_ENABLED` | `true` to enable TLS |
3037
+ | `SWML_SSL_CERT_PATH` | Path to the PEM certificate |
3038
+ | `SWML_SSL_KEY_PATH` | Path to the PEM private key |
3039
+ | `SWML_SSL_DOMAIN` | Domain name |
3040
+
3041
+ #### Constructor
3042
+
3043
+ See [SslOptions](#ssloptions).
3044
+
3045
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3046
+ ```ts
3047
+ constructor(opts?: SslOptions)
3048
+ ```
3049
+
3050
+ #### Properties
3051
+
3052
+ | Property | Type | Description |
3053
+ |----------|------|-------------|
3054
+ | `enabled` | `boolean` | Whether TLS is enabled |
3055
+ | `certPath` | `string \| null` | PEM certificate path |
3056
+ | `keyPath` | `string \| null` | PEM private key path |
3057
+ | `domain` | `string \| null` | Domain name |
3058
+ | `hsts` | `boolean` | Whether to send HSTS headers |
3059
+ | `hstsMaxAge` | `number` | HSTS `max-age` in seconds |
3060
+
3061
+ #### Methods
3062
+
3063
+ | Method | Signature | Returns | Description |
3064
+ |--------|-----------|---------|-------------|
3065
+ | `isConfigured` | `()` | `boolean` | Enabled, with both files present |
3066
+ | `getCert` | `()` | `string \| null` | The certificate file's contents |
3067
+ | `getKey` | `()` | `string \| null` | The key file's contents |
3068
+ | `getHstsHeader` | `()` | `string \| null` | `max-age={hstsMaxAge}; includeSubDomains`, or `null` when HSTS or TLS is off |
3069
+ | `getServerOptions` | `()` | `{ cert, key } \| null` | Options for `https.createServer()` |
3070
+ | `hstsMiddleware` | `()` | Hono middleware | Adds `Strict-Transport-Security` to responses |
3071
+
3072
+ ### SchemaUtils
3073
+
3074
+ Import the class from the package root:
3075
+
3076
+ ```ts
3077
+ import { SchemaUtils, SchemaValidationError } from '@signalwire/sdk';
3078
+ ```
3079
+
3080
+ `SchemaUtils` reads the SWML schema and validates verbs and documents. `SwmlBuilder` uses it to check each verb.
3081
+
3082
+ #### Constructor
3083
+
3084
+ The constructor has this signature:
3085
+
3086
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3087
+ ```ts
3088
+ constructor(opts?: { skipValidation?: boolean; maxCacheSize?: number; schemaPath?: string })
3089
+ ```
3090
+
3091
+ | Parameter | Type | Default | Description |
3092
+ |-----------|------|---------|-------------|
3093
+ | `skipValidation` | `boolean` | `true` when `SWML_SKIP_SCHEMA_VALIDATION=true` | Make `validate()` and `validateVerb()` accept everything |
3094
+ | `maxCacheSize` | `number` | `100` | Cached `validate()` results |
3095
+ | `schemaPath` | `string` | The bundled schema | Schema file to read |
3096
+
3097
+ #### Methods
3098
+
3099
+ | Method | Signature | Returns | Description |
3100
+ |--------|-----------|---------|-------------|
3101
+ | `validateVerb` | `(verbName: string, config: unknown)` | `ValidationResult` | Check one verb's config against the schema; an unknown verb is invalid |
3102
+ | `validate` | `(swml: string \| Record<string, unknown>)` | `ValidationResult` | Structural checks of a document: `version`, `sections.main`, arrays, and the AI verb's prompt and SWAIG functions |
3103
+ | `getVerbNames` | `()` | `string[]` | Verbs in the schema |
3104
+ | `hasVerb` | `(verbName: string)` | `boolean` | Whether the schema defines a verb |
3105
+ | `getVerbProperties` | `(verbName: string)` | `Record<string, unknown>` | A verb's schema definition |
3106
+ | `getVerbParameters` | `(verbName: string)` | `Record<string, unknown>` | A verb's parameter properties |
3107
+ | `getVerbRequiredProperties` | `(verbName: string)` | `string[]` | A verb's required properties |
3108
+ | `getVerbDescription` | `(verbName: string)` | `string` | A verb's description |
3109
+ | `loadSchema` | `()` | `Record<string, unknown> \| null` | Load the schema |
3110
+ | `clearCache` | `()` | `void` | Clear the `validate()` cache |
3111
+ | `getCacheSize` | `()` | `number` | Cached entries |
3112
+ | `schemaPath` | (getter) | `string \| null` | The schema path, or `null` for the bundled schema |
3113
+ | `fullValidationAvailable` | (getter) | `boolean` | Whether a schema is loaded |
3114
+
3115
+ `SchemaValidationError` extends `Error` with readonly `verbName` and `errors` properties. `SwmlBuilder.addVerb()` throws it.
3116
+
3117
+ ### ServerlessAdapter
3118
+
3119
+ Import the class from the package root:
3120
+
3121
+ ```ts
3122
+ import { ServerlessAdapter } from '@signalwire/sdk';
3123
+ ```
3124
+
3125
+ `ServerlessAdapter` runs a Hono app on a serverless platform: it turns the platform's event into a `Request`, and the app's `Response` into the platform's response.
3126
+
3127
+ #### Constructor
3128
+
3129
+ `ServerlessPlatform` is `'lambda' | 'gcf' | 'azure' | 'cgi' | 'auto'`. With `'auto'` (the default), the platform is detected from the environment.
3130
+
3131
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3132
+ ```ts
3133
+ constructor(platform?: ServerlessPlatform)
3134
+ ```
3135
+
3136
+ #### Instance Methods
3137
+
3138
+ | Method | Signature | Returns | Description |
3139
+ |--------|-----------|---------|-------------|
3140
+ | `detectPlatform` | `()` | `ServerlessPlatform` | Detect from environment variables; `'lambda'` when nothing matches |
3141
+ | `getPlatform` | `()` | `ServerlessPlatform` | The platform in use |
3142
+ | `handleRequest` | `(app, event: ServerlessEvent)` | `Promise<ServerlessResponse>` | Route an event through the app. The app receives the URL the platform was called on, for the webhook signature check. |
3143
+ | `generateUrl` | `(opts?: { region?, projectId?, functionName?, stage?, apiId? })` | `string` | A platform-style URL built from the options and environment |
3144
+
3145
+ #### Static Methods
3146
+
3147
+ | Method | Signature | Returns | Description |
3148
+ |--------|-----------|---------|-------------|
3149
+ | `createLambdaHandler` | `(app)` | `(event) => Promise<ServerlessResponse>` | AWS Lambda handler |
3150
+ | `createGcfHandler` | `(app)` | `(req, res) => Promise<void>` | Google Cloud Functions handler |
3151
+ | `createAzureHandler` | `(app)` | `(context, req) => Promise<void>` | Azure Functions handler; sets `context.res` |
3152
+ | `createCgiHandler` | `(app)` | `() => Promise<void>` | Runs one CGI request from the environment and standard input |
3153
+ | `buildCgiEvent` | `(env?, body?)` | `ServerlessEvent` | An event built from CGI environment variables |
3154
+
3155
+ **Example (AWS Lambda):**
3156
+
3157
+ ```ts
3158
+ import { AgentBase, ServerlessAdapter } from '@signalwire/sdk';
3159
+
3160
+ const lambdaAgent = new AgentBase({ name: 'MyAgent' });
3161
+ export const handler = ServerlessAdapter.createLambdaHandler(lambdaAgent.getApp());
3162
+ ```
3163
+
3164
+ ---
3165
+
3166
+ ## Types and Interfaces
3167
+
3168
+ ### AgentOptions
3169
+
3170
+ The options accepted by the `AgentBase` constructor:
3171
+
3172
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3173
+ ```ts
3174
+ interface AgentOptions
3175
+ ```
3176
+
3177
+ | Property | Type | Default | Description |
3178
+ |----------|------|---------|-------------|
3179
+ | `name` | `string` | (required) | Agent name. Also the basic-auth username when the SDK generates the credentials and `SWML_BASIC_AUTH_USER` isn't set. |
3180
+ | `route` | `string` | `'/'` | HTTP route; trailing slashes are removed |
3181
+ | `host` | `string` | `'0.0.0.0'` | Hostname to bind |
3182
+ | `port` | `number` | `PORT` env, else `3000` | Port. Must be 1 to 65535. |
3183
+ | `basicAuth` | `[string, string]` | See the note after this table | `[username, password]` for every route except `/health` and `/ready` |
3184
+ | `usePom` | `boolean` | `true` | Keep prompt sections as a POM, rendered as `prompt.pom` |
3185
+ | `tokenExpirySecs` | `number` | `3600` | Lifetime of per-call tool tokens, in seconds |
3186
+ | `swaigSecret` | `string` | `SIGNALWIRE_SWAIG_SECRET`, else random per process | Secret that signs per-call tool tokens. Set the same value on every replica and keep it across restarts, or tokens minted by one process fail on another. |
3187
+ | `signingKey` | `string` | `SIGNALWIRE_SIGNING_KEY` | SignalWire signing key. When set, POSTs to the root, `/swaig`, `/post_prompt` and routing-callback paths need a valid webhook signature (`403` otherwise). When neither is set, signatures aren't checked and a warning is logged. |
3188
+ | `webhookTrustProxy` | `boolean` | `false` | Use `X-Forwarded-Proto` and `X-Forwarded-Host` to rebuild the signed URL. These headers can be forged, so enable it only behind a proxy you control. `SWML_PROXY_URL_BASE` takes precedence. |
3189
+ | `autoAnswer` | `boolean` | `true` | Add the `answer` verb |
3190
+ | `recordCall` | `boolean` | `false` | Add a `record_call` verb after `answer` |
3191
+ | `recordFormat` | `string` | `'mp4'` | `record_call` format |
3192
+ | `recordStereo` | `boolean` | `true` | `record_call` stereo setting |
3193
+ | `defaultWebhookUrl` | `string` | none | Stored by the constructor; `renderSwml()` doesn't read it. Use `setWebHookUrl()`. |
3194
+ | `nativeFunctions` | `string[]` | `[]` | Native function names |
3195
+ | `agentId` | `string` | 16 random hex characters | Agent instance ID |
3196
+ | `suppressLogs` | `boolean` | `false` | Call `suppressAllLogs(true)`, which silences every SDK logger in the process, not only this agent's, from the start of the constructor. |
3197
+ | `schemaPath` | `string` | The bundled schema | Path to a SWML JSON Schema file that verbs are validated against, in place of the bundled schema. |
3198
+ | `schemaValidation` | `boolean` | `true` | `false` turns off the validation of verbs, as `SWML_SKIP_SCHEMA_VALIDATION=true` does. |
3199
+ | `enablePostPromptOverride` | `boolean` | `false` | Serve `POST {route}/post_prompt_override`, which replaces the post-prompt text |
3200
+ | `checkForInputOverride` | `boolean` | `false` | Serve `{route}/check_for_input`, which echoes the request body |
3201
+ | `configFile` | `string` | none | JSON config file. Its `service` section supplies `route`, `host` and `port` when the options omit them, and its `security` section supplies basic auth and TLS settings. |
3202
+
3203
+ When `basicAuth` isn't given, the credentials come from the config file's `security.auth.basic` (or `security.basicAuth`), then from `SWML_BASIC_AUTH_PASSWORD` with `SWML_BASIC_AUTH_USER` (default user `signalwire`). When no password is configured, the SDK generates a random password that exists only in this process, and logs a warning. The username is then `SWML_BASIC_AUTH_USER` or the agent's name.
3204
+
3205
+ ### LanguageConfig
3206
+
3207
+ The configuration passed to `addLanguage()`:
3208
+
3209
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3210
+ ```ts
3211
+ interface LanguageConfig
3212
+ ```
3213
+
3214
+ | Property | Type | Description |
3215
+ |----------|------|-------------|
3216
+ | `name` | `string` | Language name, such as `"English"` |
3217
+ | `code` | `string` | Language code, such as `"en-US"` |
3218
+ | `voice` | `string` | Voice identifier (optional) |
3219
+ | `engine` | `string` | TTS engine (optional) |
3220
+ | `model` | `string` | TTS model (optional) |
3221
+ | `speechFillers` | `string[]` | Phrases that fill a pause in speech, emitted as `speech_fillers` (optional) |
3222
+ | `functionFillers` | `string[] \| Record<string, Record<string, string[]>>` | Phrases said while a tool runs, emitted as `function_fillers`; the keyed form is flattened (optional) |
3223
+ | `fillers` | `string[] \| Record<string, string[]>` | The older list for both, used as speech fillers; the keyed form is flattened (optional) |
3224
+ | `speechModel` | `string` | Speech recognition model, emitted as `speech_model` (optional) |
3225
+ | `params` | `Record<string, unknown>` | Engine-specific settings, emitted only when not empty (optional) |
3226
+
3227
+ ### PronunciationRule
3228
+
3229
+ A rule passed to `addPronunciation()`:
3230
+
3231
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3232
+ ```ts
3233
+ interface PronunciationRule
3234
+ ```
3235
+
3236
+ | Property | Type | Description |
3237
+ |----------|------|-------------|
3238
+ | `replace` | `string` | Text to match |
3239
+ | `with` | `string` | Replacement pronunciation |
3240
+ | `ignoreCase` | `boolean` | Case-insensitive match, emitted as `ignore_case` when `true` (optional) |
3241
+
3242
+ ### FunctionInclude
3243
+
3244
+ An entry in `SWAIG.includes`:
3245
+
3246
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3247
+ ```ts
3248
+ interface FunctionInclude
3249
+ ```
3250
+
3251
+ | Property | Type | Description |
3252
+ |----------|------|-------------|
3253
+ | `url` | `string` | URL of the remote SWAIG endpoint |
3254
+ | `functions` | `string[]` | Function names at the endpoint |
3255
+ | `meta_data` | `Record<string, unknown>` | Metadata (optional) |
3256
+
3257
+ ### DynamicConfigCallback
3258
+
3259
+ The type of a per-request configuration callback:
3260
+
3261
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3262
+ ```ts
3263
+ type DynamicConfigCallback<TAgent = AgentBase> = (
3264
+ queryParams: Record<string, string>,
3265
+ bodyParams: SwmlRequestData,
3266
+ headers: Record<string, string>,
3267
+ agent: TAgent,
3268
+ ) => void | Promise<void>;
3269
+ ```
3270
+
3271
+ `agent` is the per-request copy; configure it, not the original agent. `headers` has credential-bearing headers removed. See [Per-Request Configuration Methods](#per-request-configuration-methods).
3272
+
3273
+ ### SummaryCallback
3274
+
3275
+ The type of a summary callback:
3276
+
3277
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3278
+ ```ts
3279
+ type SummaryCallback = (
3280
+ summary: PostPromptData | null,
3281
+ rawData: PostPrompt,
3282
+ ) => void | Promise<void>;
3283
+ ```
3284
+
3285
+ ### SwaigHandler
3286
+
3287
+ The type of a tool handler:
3288
+
3289
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3290
+ ```ts
3291
+ type SwaigHandler = (
3292
+ args: Record<string, unknown>,
3293
+ rawData: SwaigRequest,
3294
+ agent?: AgentBase,
3295
+ ) => FunctionResult | Record<string, unknown> | string
3296
+ | Promise<FunctionResult | Record<string, unknown> | string>;
3297
+ ```
3298
+
3299
+ `args` holds the arguments the model supplied. `rawData` is the whole SWAIG request, with `call_id`, `global_data` and the rest. `agent` is the agent the request was configured on: the per-request copy when per-request configuration is in use, and `undefined` when you call `SwaigFunction.execute()` yourself.
3300
+
3301
+ The return value is serialized as follows:
3302
+
3303
+ - A `FunctionResult` is serialized with `toDict()`.
3304
+ - An object with a `response` key is sent as is.
3305
+ - An object without a `response` key is replaced by `{ response: 'Function completed successfully' }`.
3306
+ - Any other value is converted to a string and wrapped in a `FunctionResult`, and the SDK logs a warning.
3307
+
3308
+ A synchronous or CPU-bound handler blocks Node's event loop, and with it every other request, until it returns.
3309
+
3310
+ ### SwaigFunctionOptions
3311
+
3312
+ The options accepted by the `SwaigFunction` constructor and by `defineTool()`:
3313
+
3314
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3315
+ ```ts
3316
+ interface SwaigFunctionOptions
3317
+ ```
3318
+
3319
+ | Property | Type | Default | Description |
3320
+ |----------|------|---------|-------------|
3321
+ | `name` | `string` | (required) | Tool name |
3322
+ | `handler` | `SwaigHandler` | (required) | Handler function |
3323
+ | `description` | `string` | (required) | Description the model reads |
3324
+ | `parameters` | `Record<string, unknown>` | `{}` | Property definitions or a full JSON Schema object |
3325
+ | `secure` | `boolean` | `true` | Require a per-call token; `false` lets the tool run without one |
3326
+ | `fillers` | `Record<string, string[]>` | none | Filler phrases by language code |
3327
+ | `waitFile` | `string` | none | Wait audio URL |
3328
+ | `waitFileLoops` | `number` | none | Wait audio loop count |
3329
+ | `webhookUrl` | `string` | none | External URL that runs the tool |
3330
+ | `required` | `string[]` | `[]` | Required parameter names |
3331
+ | `extraFields` | `Record<string, unknown>` | `{}` | Extra keys merged into the definition |
3332
+ | `isTypedHandler` | `boolean` | `false` | Whether the handler takes named parameters |
3333
+ | `onError` | `SwaigErrorHandler` | none | Per-tool error hook |
3334
+ | `errorMessage` | `string` | A generic apology | Response when the handler throws and no hook returns one |
3335
+
3336
+ ### AuthConfig
3337
+
3338
+ The configuration accepted by `AuthHandler`:
3339
+
3340
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3341
+ ```ts
3342
+ interface AuthConfig
3343
+ ```
3344
+
3345
+ | Property | Type | Description |
3346
+ |----------|------|-------------|
3347
+ | `bearerToken` | `string` | Token matched against `Authorization: Bearer` |
3348
+ | `apiKey` | `string` | Key matched against the API key header |
3349
+ | `apiKeyHeader` | `string` | Header for the API key (default `X-Api-Key`) |
3350
+ | `basicAuth` | `[string, string]` | Basic-auth `[username, password]` |
3351
+ | `customValidator` | `(request: { headers, method, url }) => boolean \| Promise<boolean>` | Custom check |
3352
+ | `allowUnauthenticated` | `boolean` | When `false`, deny requests when no method is configured |
3353
+
3354
+ ### SslOptions
3355
+
3356
+ The options accepted by `SslConfig`:
3357
+
3358
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3359
+ ```ts
3360
+ interface SslOptions
3361
+ ```
3362
+
3363
+ | Property | Type | Default | Description |
3364
+ |----------|------|---------|-------------|
3365
+ | `enabled` | `boolean` | `SWML_SSL_ENABLED` env | Whether TLS is enabled |
3366
+ | `certPath` | `string` | `SWML_SSL_CERT_PATH` env | Path to the PEM certificate |
3367
+ | `keyPath` | `string` | `SWML_SSL_KEY_PATH` env | Path to the PEM private key |
3368
+ | `domain` | `string` | `SWML_SSL_DOMAIN` env | Domain name |
3369
+ | `hsts` | `boolean` | `true` | Send HSTS headers |
3370
+ | `hstsMaxAge` | `number` | `31536000` | HSTS `max-age` in seconds |
3371
+
3372
+ ### ValidationResult
3373
+
3374
+ The result of a validation:
3375
+
3376
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3377
+ ```ts
3378
+ interface ValidationResult
3379
+ ```
3380
+
3381
+ | Property | Type | Description |
3382
+ |----------|------|-------------|
3383
+ | `valid` | `boolean` | Whether validation passed |
3384
+ | `errors` | `string[]` | Error messages, empty when valid |
3385
+
3386
+ ### ServerlessEvent
3387
+
3388
+ The event a serverless platform passes in:
3389
+
3390
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3391
+ ```ts
3392
+ interface ServerlessEvent
3393
+ ```
3394
+
3395
+ Every property is optional.
3396
+
3397
+ | Property | Type | Description |
3398
+ |----------|------|-------------|
3399
+ | `httpMethod` | `string` | HTTP method (AWS Lambda style) |
3400
+ | `method` | `string` | HTTP method (Google Cloud Functions and Azure style) |
3401
+ | `headers` | `Record<string, string>` | Request headers |
3402
+ | `body` | `string \| Record<string, unknown>` | Request body |
3403
+ | `path` | `string` | Request path |
3404
+ | `rawPath` | `string` | Request path (API Gateway HTTP API) |
3405
+ | `queryStringParameters` | `Record<string, string>` | Query parameters |
3406
+ | `multiValueQueryStringParameters` | `Record<string, string[]>` | Repeated query parameters |
3407
+ | `rawQueryString` | `string` | Query string as received |
3408
+ | `pathParameters` | `Record<string, string>` | Path parameters |
3409
+ | `requestContext` | `Record<string, unknown>` | Platform-specific context |
3410
+
3411
+ ### ServerlessResponse
3412
+
3413
+ The response returned to a serverless platform:
3414
+
3415
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3416
+ ```ts
3417
+ interface ServerlessResponse
3418
+ ```
3419
+
3420
+ | Property | Type | Description |
3421
+ |----------|------|-------------|
3422
+ | `statusCode` | `number` | HTTP status code |
3423
+ | `headers` | `Record<string, string>` | Response headers |
3424
+ | `body` | `string` | Response body |
3425
+
3426
+ ### PomSectionData
3427
+
3428
+ The serialized form of a POM section:
3429
+
3430
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3431
+ ```ts
3432
+ interface PomSectionData
3433
+ ```
3434
+
3435
+ Every property is optional, and a key is present only when it has a value.
3436
+
3437
+ | Property | Type | Description |
3438
+ |----------|------|-------------|
3439
+ | `title` | `string` | Section heading |
3440
+ | `body` | `string` | Body text |
3441
+ | `bullets` | `string[]` | Bullet points |
3442
+ | `numbered` | `boolean` | Whether the section is numbered |
3443
+ | `numberedBullets` | `boolean` | Whether bullets are numbered |
3444
+ | `subsections` | `PomSectionData[]` | Nested sections |
3445
+
3446
+ ### Skill Types
3447
+
3448
+ #### SkillConfig
3449
+
3450
+ The configuration passed to a skill:
3451
+
3452
+ <!-- snippet: no-compile API signature / type reference, not runnable code -->
3453
+ ```ts
3454
+ interface SkillConfig { [key: string]: unknown }
3455
+ ```
3456
+
3457
+ #### SkillToolDefinition
3458
+
3459
+ | Property | Type | Description |
3460
+ |----------|------|-------------|
3461
+ | `name` | `string` | Tool name |
3462
+ | `description` | `string` | Description the model reads |
3463
+ | `parameters` | `Record<string, unknown>` | Parameter definitions (optional) |
3464
+ | `handler` | `SwaigHandler` | Handler function |
3465
+ | `secure` | `boolean` | Require a per-call token (optional; `true` when omitted) |
3466
+ | `fillers` | `Record<string, string[]>` | Filler phrases by language code (optional) |
3467
+ | `required` | `string[]` | Required parameter names (optional) |
3468
+ | `wait_for_fillers` | `boolean` | Emitted as `wait_for_fillers` (optional) |
3469
+ | `skip_fillers` | `boolean` | Emitted as `skip_fillers` (optional) |
3470
+ | `isHangupHook` | `boolean` | Emitted as `is_hangup_hook: true` (optional) |
3471
+
3472
+ `defineSkillTool(toolDef)` returns a `SkillToolDefinition` with `args` typed from its `parameters`, as `defineTool()` does.
3473
+
3474
+ #### SkillPromptSection
3475
+
3476
+ | Property | Type | Description |
3477
+ |----------|------|-------------|
3478
+ | `title` | `string` | Section heading |
3479
+ | `body` | `string` | Body text (optional) |
3480
+ | `bullets` | `string[]` | Bullet points (optional) |
3481
+ | `numbered` | `boolean` | Whether the section is numbered (optional) |
3482
+
3483
+ #### ParameterSchemaEntry
3484
+
3485
+ | Property | Type | Description |
3486
+ |----------|------|-------------|
3487
+ | `type` | `'string' \| 'number' \| 'integer' \| 'boolean' \| 'object' \| 'array'` | Value type |
3488
+ | `description` | `string` | Description |
3489
+ | `default` | `unknown` | Default value (optional) |
3490
+ | `required` | `boolean` | Whether it's required (optional) |
3491
+ | `hidden` | `boolean` | Whether to hide it from user-facing output, such as an API key (optional) |
3492
+ | `env_var` | `string` | Environment variable a configuration tool can read this value from; the SDK doesn't read it (optional) |
3493
+ | `enum` | `unknown[]` | Allowed values (optional) |
3494
+ | `min` | `number` | Minimum (optional) |
3495
+ | `max` | `number` | Maximum (optional) |
3496
+ | `items` | `Record<string, unknown>` | Schema of array items (optional) |
3497
+
3498
+ #### SkillSchemaInfo
3499
+
3500
+ | Property | Type | Description |
3501
+ |----------|------|-------------|
3502
+ | `name` | `string` | Skill name |
3503
+ | `description` | `string` | Description |
3504
+ | `version` | `string` | Version |
3505
+ | `supportsMultipleInstances` | `boolean` | Whether several instances can load |
3506
+ | `requiredEnvVars` | `string[]` | Required environment variables |
3507
+ | `requiredPackages` | `string[]` | Required npm packages |
3508
+ | `parameters` | `Record<string, ParameterSchemaEntry>` | Configuration schema |
3509
+ | `source` | `string` | Where the skill came from (optional) |
3510
+
3511
+ ### Payment Types
3512
+
3513
+ #### PaymentPrompt
3514
+
3515
+ | Property | Type | Description |
3516
+ |----------|------|-------------|
3517
+ | `for` | `string` | Situation the prompt applies to |
3518
+ | `actions` | `PaymentAction[]` | Actions for the prompt |
3519
+ | `card_type` | `string` | Card type filter (optional) |
3520
+ | `error_type` | `string` | Error type (optional) |
3521
+
3522
+ #### PaymentAction
3523
+
3524
+ | Property | Type | Description |
3525
+ |----------|------|-------------|
3526
+ | `type` | `string` | Action type, such as `"say"` or `"play"` |
3527
+ | `phrase` | `string` | Phrase or URL |
3528
+
3529
+ #### PaymentParameter
3530
+
3531
+ | Property | Type | Description |
3532
+ |----------|------|-------------|
3533
+ | `name` | `string` | Parameter name |
3534
+ | `value` | `string` | Parameter value |