@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,1938 @@
1
+ # FunctionResult Reference
2
+
3
+ This page is the API reference for the `FunctionResult` class in the SignalWire AI Agents TypeScript SDK. `FunctionResult` is what a SWAIG tool handler returns.
4
+
5
+ The examples on this page assume this import and agent:
6
+
7
+ <!-- snippet-setup -->
8
+ ```ts
9
+ import { AgentBase, FunctionResult } from '@signalwire/sdk';
10
+
11
+ const agent = new AgentBase({ name: 'support-agent' });
12
+ ```
13
+
14
+ ---
15
+
16
+ ## Table of Contents
17
+
18
+ The reference groups the methods by what they do:
19
+
20
+ - [Overview](#overview)
21
+ - [Basic usage](#basic-usage)
22
+ - [Writing the response](#writing-the-response)
23
+ - [Returning a result from a handler](#returning-a-result-from-a-handler)
24
+ - [How serialization works](#how-serialization-works)
25
+ - [Properties](#properties)
26
+ - [Core Methods](#core-methods)
27
+ - [constructor](#constructor)
28
+ - [setResponse](#setresponse)
29
+ - [setToolResponse](#settoolresponse)
30
+ - [setPostProcess](#setpostprocess)
31
+ - [addAction](#addaction)
32
+ - [addActions](#addactions)
33
+ - [toDict](#todict)
34
+ - [toJSON](#tojson)
35
+ - [Call Control](#call-control)
36
+ - [connect](#connect)
37
+ - [swmlTransfer](#swmltransfer)
38
+ - [hangup](#hangup)
39
+ - [hold](#hold)
40
+ - [waitForUser](#waitforuser)
41
+ - [stop](#stop)
42
+ - [Audio](#audio)
43
+ - [say](#say)
44
+ - [playBackgroundFile](#playbackgroundfile)
45
+ - [stopBackgroundFile](#stopbackgroundfile)
46
+ - [Speech](#speech)
47
+ - [addDynamicHints](#adddynamichints)
48
+ - [clearDynamicHints](#cleardynamichints)
49
+ - [setEndOfSpeechTimeout](#setendofspeechtimeout)
50
+ - [setSpeechEventTimeout](#setspeecheventtimeout)
51
+ - [Data Management](#data-management)
52
+ - [updateGlobalData](#updateglobaldata)
53
+ - [removeGlobalData](#removeglobaldata)
54
+ - [setMetadata](#setmetadata)
55
+ - [removeMetadata](#removemetadata)
56
+ - [SWML Actions](#swml-actions)
57
+ - [executeSwml](#executeswml)
58
+ - [switchContext](#switchcontext)
59
+ - [swmlChangeStep](#swmlchangestep)
60
+ - [swmlChangeContext](#swmlchangecontext)
61
+ - [swmlUserEvent](#swmluserevent)
62
+ - [Function Control](#function-control)
63
+ - [toggleFunctions](#togglefunctions)
64
+ - [enableFunctionsOnTimeout](#enablefunctionsontimeout)
65
+ - [updateSettings](#updatesettings)
66
+ - [User Input and History](#user-input-and-history)
67
+ - [simulateUserInput](#simulateuserinput)
68
+ - [enableExtensiveData](#enableextensivedata)
69
+ - [replaceInHistory](#replaceinhistory)
70
+ - [Communication](#communication)
71
+ - [sendSms](#sendsms)
72
+ - [recordCall](#recordcall)
73
+ - [stopRecordCall](#stoprecordcall)
74
+ - [tap](#tap)
75
+ - [stopTap](#stoptap)
76
+ - [Rooms and Conferencing](#rooms-and-conferencing)
77
+ - [joinRoom](#joinroom)
78
+ - [sipRefer](#siprefer)
79
+ - [joinConference](#joinconference)
80
+ - [RPC](#rpc)
81
+ - [executeRpc](#executerpc)
82
+ - [rpcDial](#rpcdial)
83
+ - [rpcAiMessage](#rpcaimessage)
84
+ - [rpcAiGlobalData](#rpcaiglobaldata)
85
+ - [rpcAiUnhold](#rpcaiunhold)
86
+ - [Payments](#payments)
87
+ - [pay](#pay)
88
+ - [createPaymentPrompt (static)](#createpaymentprompt-static)
89
+ - [createPaymentAction (static)](#createpaymentaction-static)
90
+ - [createPaymentParameter (static)](#createpaymentparameter-static)
91
+ - [Full payment example](#full-payment-example)
92
+ - [Fluent Chaining](#fluent-chaining)
93
+
94
+ ---
95
+
96
+ ## Overview
97
+
98
+ `FunctionResult` is the return type for SWAIG tool handlers. It carries two things back to SignalWire:
99
+
100
+ 1. **Response**: context for the model. The model reads it and decides what to say next. It isn't played to the caller.
101
+ 2. **Actions**: an ordered list of structured commands (hangup, connect, send SMS and others) that the platform carries out.
102
+
103
+ A handler builds a `FunctionResult`, adds any actions, and returns it. The SDK serializes it with `toDict()` and sends it to SignalWire as the response to the `/swaig` request.
104
+
105
+ ### Basic usage
106
+
107
+ This tool records a transfer reason and connects the caller to a support line:
108
+
109
+ ```typescript
110
+ agent.defineTool({
111
+ name: 'transfer_to_support',
112
+ description: 'Transfer the caller to a human support agent',
113
+ parameters: {},
114
+ handler: () => {
115
+ return new FunctionResult('Tell the caller you are connecting them to support.', true)
116
+ .connect('+15551234567');
117
+ },
118
+ });
119
+ ```
120
+
121
+ The second constructor argument turns on post-processing, so the model gets one more turn to tell the caller before the transfer runs.
122
+
123
+ ### Writing the response
124
+
125
+ The response is context for the model, not a script. The model reads it, then decides what to say. It can hold facts, an instruction, or both.
126
+
127
+ The clearest form keeps facts and instruction apart. Pass them as the constructor's `toolResult` and `toolPrompt`, or with [setToolResponse](#settoolresponse), and the SDK sends `{ tool_result, tool_prompt }`:
128
+
129
+ ```typescript
130
+ const structured = new FunctionResult(
131
+ undefined,
132
+ false,
133
+ 'Order 1234 shipped Tuesday.',
134
+ 'Tell the caller when their order shipped.',
135
+ );
136
+ ```
137
+
138
+ A plain string works too, as facts or as an instruction:
139
+
140
+ ```typescript
141
+ const facts = new FunctionResult('Order 1234 shipped Tuesday.');
142
+ const instruction = new FunctionResult('Tell the caller their order shipped Tuesday.');
143
+ ```
144
+
145
+ Avoid a line written for the caller, such as `'Your order shipped Tuesday.'`. The model tends to repeat it, but it interprets the line rather than speaking it, so the wording can drift or merge with other context. To speak exact words, use [say](#say).
146
+
147
+ ### Returning a result from a handler
148
+
149
+ A tool handler receives `(args, rawData, agent)`. `args` holds the parsed arguments, and `rawData` is the full SWAIG request body. `agent` is the agent the request was configured on: the per-request copy when a dynamic config callback or `addPerCallConfig()` is in use.
150
+
151
+ The SDK handles these return values:
152
+
153
+ - A `FunctionResult`, or a promise that resolves to one: serialized with `toDict()`.
154
+ - A plain object with a `response` key: sent as it is.
155
+ - A plain object without a `response` key: replaced by `{ response: "Function completed successfully" }`.
156
+ - Any other value, such as a string: converted to a string and sent as the response, with a logged warning.
157
+
158
+ If the handler throws, the SDK logs the error. It then returns the result of the tool's `onError` hook, or of the agent's `onError()` handler, when either returns a `FunctionResult`. Otherwise it returns the tool's `errorMessage`, or a default apology message.
159
+
160
+ Tools registered with `defineTool()` are secure by default. The SWML the agent renders gives each secure tool a per-call token (`__token`). The agent runs the handler only when a `/swaig` request carries a valid token for that function and call. Otherwise it returns a refusal response. Set `swaigSecret` or `SIGNALWIRE_SWAIG_SECRET` so tokens survive a restart and work across replicas. For details, see [Secure Tools (HMAC Tokens)](security.md#secure-tools-hmac-tokens).
161
+
162
+ ### How serialization works
163
+
164
+ When the handler returns, the SDK calls `toDict()` to produce a plain object:
165
+
166
+ ```typescript
167
+ const result = new FunctionResult('Order 1234 is cancelled.').hangup();
168
+ console.log(result.toDict());
169
+ // { response: 'Order 1234 is cancelled.', action: [ { hangup: true } ] }
170
+ ```
171
+
172
+ If the response is empty and there are no actions, `toDict()` returns `{ response: "Action completed." }`, so the model always receives a response.
173
+
174
+ ### Properties
175
+
176
+ The class has three public properties:
177
+
178
+ | Property | Type | Description |
179
+ |---------------|-----------------------------|--------------------------------------------------------------|
180
+ | `response` | `string` | The string response. Empty when the structured form is set. |
181
+ | `action` | `Record<string, unknown>[]` | Ordered list of action objects. |
182
+ | `postProcess` | `boolean` | When `true`, the model takes one more turn before the actions run. |
183
+
184
+ ## Core Methods
185
+
186
+ ### constructor
187
+
188
+ Create a new `FunctionResult`.
189
+
190
+ <!-- snippet: no-compile API signature reference, not runnable code -->
191
+ ```typescript
192
+ constructor(
193
+ response?: string | { tool_result?: string; tool_prompt?: string },
194
+ postProcess?: boolean,
195
+ toolResult?: string,
196
+ toolPrompt?: string,
197
+ )
198
+ ```
199
+
200
+ | Parameter | Type | Default | Description |
201
+ |---------------|-----------------------------------------------------|---------|--------------------------------------------------------------|
202
+ | `response` | `string \| { tool_result?: string; tool_prompt?: string }` | `''` | The response: a string, or the structured form. |
203
+ | `postProcess` | `boolean` | `false` | Whether the model takes one more turn before the actions run. |
204
+ | `toolResult` | `string` | none | Sets `tool_result`, as [setToolResponse](#settoolresponse) does. |
205
+ | `toolPrompt` | `string` | none | Sets `tool_prompt`, as [setToolResponse](#settoolresponse) does. |
206
+
207
+ When `toolResult` or `toolPrompt` is given, the structured form replaces a string `response`.
208
+
209
+ **Returns:** A new `FunctionResult` instance.
210
+
211
+ **Example:**
212
+
213
+ ```typescript
214
+ // Empty result (serializes as "Action completed.")
215
+ const r1 = new FunctionResult();
216
+
217
+ // Facts as a string
218
+ const r2 = new FunctionResult('Order 1234 was placed.');
219
+
220
+ // Post-processing on, so the model speaks before the actions run
221
+ const r3 = new FunctionResult('Tell the caller the payment is being processed.', true);
222
+
223
+ // Structured form as the first argument
224
+ const r4 = new FunctionResult({
225
+ tool_result: 'Payment declined.',
226
+ tool_prompt: 'Ask the caller for another card.',
227
+ });
228
+ ```
229
+
230
+ ### setResponse
231
+
232
+ Set or replace the string response. It also clears a structured response set earlier.
233
+
234
+ <!-- snippet: no-compile API signature reference, not runnable code -->
235
+ ```typescript
236
+ setResponse(response: string): this
237
+ ```
238
+
239
+ | Parameter | Type | Description |
240
+ |------------|----------|----------------------------------------|
241
+ | `response` | `string` | The new response: facts or an instruction. |
242
+
243
+ **Returns:** `this` for chaining.
244
+
245
+ **Example:**
246
+
247
+ ```typescript
248
+ const result = new FunctionResult()
249
+ .setResponse('The account balance is $42.50.');
250
+ ```
251
+
252
+ ### setToolResponse
253
+
254
+ Set the structured response, which keeps facts and instruction apart. The SDK sends `response` as `{ tool_result, tool_prompt }`, with only the fields you pass. It replaces any string response.
255
+
256
+ <!-- snippet: no-compile API signature reference, not runnable code -->
257
+ ```typescript
258
+ setToolResponse(toolResult?: string, toolPrompt?: string): this
259
+ ```
260
+
261
+ | Parameter | Type | Description |
262
+ |--------------|----------|----------------------------------------------------------------------|
263
+ | `toolResult` | `string` | What the tool did or found: facts for the model to reason from. |
264
+ | `toolPrompt` | `string` | What the model should do next: an instruction. |
265
+
266
+ **Returns:** `this` for chaining.
267
+
268
+ **Example:**
269
+
270
+ ```typescript
271
+ const result = new FunctionResult()
272
+ .setToolResponse('3 seats left on the 7:40 flight.', 'Tell the caller how many seats are left.');
273
+ console.log(result.toDict());
274
+ // {
275
+ // response: {
276
+ // tool_result: '3 seats left on the 7:40 flight.',
277
+ // tool_prompt: 'Tell the caller how many seats are left.'
278
+ // }
279
+ // }
280
+ ```
281
+
282
+ ### setPostProcess
283
+
284
+ Enable or disable post-processing.
285
+
286
+ With post-processing on, the model takes one more turn before the actions run. Use it when the caller must hear something before an action takes effect, such as a hangup, hold or transfer. The SDK includes `post_process: true` in the result only when there are actions.
287
+
288
+ <!-- snippet: no-compile API signature reference, not runnable code -->
289
+ ```typescript
290
+ setPostProcess(postProcess: boolean): this
291
+ ```
292
+
293
+ | Parameter | Type | Description |
294
+ |---------------|-----------|------------------------------------------|
295
+ | `postProcess` | `boolean` | Whether to enable post-processing. |
296
+
297
+ **Returns:** `this` for chaining.
298
+
299
+ **Example:**
300
+
301
+ ```typescript
302
+ const result = new FunctionResult('Tell the caller goodbye.')
303
+ .setPostProcess(true)
304
+ .hangup();
305
+ // The model gets one more turn to say goodbye, then the hangup runs.
306
+ ```
307
+
308
+ ### addAction
309
+
310
+ Append a single named action to the action list. Most helper methods use it. Use it directly for an action that has no helper.
311
+
312
+ <!-- snippet: no-compile API signature reference, not runnable code -->
313
+ ```typescript
314
+ addAction(name: string, data: unknown): this
315
+ ```
316
+
317
+ | Parameter | Type | Description |
318
+ |-----------|-----------|-----------------------------------------|
319
+ | `name` | `string` | The action name (for example `"say"`). |
320
+ | `data` | `unknown` | The action payload. |
321
+
322
+ **Returns:** `this` for chaining.
323
+
324
+ **Example:**
325
+
326
+ ```typescript
327
+ const result = new FunctionResult('Order 1234 is confirmed.')
328
+ .addAction('say', 'Your order is confirmed.');
329
+ // action: [{ say: "Your order is confirmed." }], the same as .say(...)
330
+ ```
331
+
332
+ ### addActions
333
+
334
+ Append several action objects at once. Each object maps an action name to its payload.
335
+
336
+ <!-- snippet: no-compile API signature reference, not runnable code -->
337
+ ```typescript
338
+ addActions(actions: Record<string, unknown>[]): this
339
+ ```
340
+
341
+ | Parameter | Type | Description |
342
+ |-----------|-----------------------------|------------------------------------|
343
+ | `actions` | `Record<string, unknown>[]` | Array of action objects to append. |
344
+
345
+ **Returns:** `this` for chaining.
346
+
347
+ **Example:**
348
+
349
+ ```typescript
350
+ const result = new FunctionResult('The survey is complete.')
351
+ .addActions([
352
+ { say: 'Thank you for taking the survey.' },
353
+ { hangup: true },
354
+ ]);
355
+ ```
356
+
357
+ ### toDict
358
+
359
+ Serialize the result to a plain object in the SWAIG response format.
360
+
361
+ <!-- snippet: no-compile API signature reference, not runnable code -->
362
+ ```typescript
363
+ toDict(): {
364
+ response?: string | { tool_result?: string; tool_prompt?: string };
365
+ action?: Record<string, unknown>[];
366
+ post_process?: boolean;
367
+ }
368
+ ```
369
+
370
+ **Returns:** An object with `response`, `action` and `post_process` fields, each present only when it applies.
371
+
372
+ These rules decide which fields appear:
373
+
374
+ - A structured response with at least one field is sent as `response`. Otherwise a non-empty string response is.
375
+ - A non-empty action list is included as `action`.
376
+ - `post_process: true` is included only when `postProcess` is `true` and there are actions.
377
+ - When none of these fields is set, the result is `{ response: "Action completed." }`.
378
+
379
+ **Example:**
380
+
381
+ ```typescript
382
+ const result = new FunctionResult('The caller is verified.').say('Thank you, you are verified.');
383
+ console.log(result.toDict());
384
+ // {
385
+ // response: 'The caller is verified.',
386
+ // action: [ { say: 'Thank you, you are verified.' } ]
387
+ // }
388
+
389
+ const empty = new FunctionResult();
390
+ console.log(empty.toDict());
391
+ // { response: 'Action completed.' }
392
+ ```
393
+
394
+ ### toJSON
395
+
396
+ Return the same object as `toDict()`, so `JSON.stringify(result)` produces the wire format.
397
+
398
+ <!-- snippet: no-compile API signature reference, not runnable code -->
399
+ ```typescript
400
+ toJSON(): {
401
+ response?: string | { tool_result?: string; tool_prompt?: string };
402
+ action?: Record<string, unknown>[];
403
+ post_process?: boolean;
404
+ }
405
+ ```
406
+
407
+ **Example:**
408
+
409
+ ```typescript
410
+ console.log(JSON.stringify(new FunctionResult('Order 1234 is cancelled.').hangup()));
411
+ // {"response":"Order 1234 is cancelled.","action":[{"hangup":true}]}
412
+ ```
413
+
414
+ ## Call Control
415
+
416
+ ### connect
417
+
418
+ Connect (transfer) the call to another destination. The SDK emits an inline SWML document with a `connect` verb, and a `transfer` key beside it set to `"true"` or `"false"`.
419
+
420
+ <!-- snippet: no-compile API signature reference, not runnable code -->
421
+ ```typescript
422
+ connect(destination: string, final?: boolean, fromAddr?: string): this
423
+ ```
424
+
425
+ | Parameter | Type | Default | Description |
426
+ |---------------|-----------|---------|----------------------------------------------------------|
427
+ | `destination` | `string` | none | Phone number or SIP address to connect to. |
428
+ | `final` | `boolean` | `true` | `true` for a permanent transfer: the call leaves the agent. `false` returns the call to the agent when the far end hangs up. |
429
+ | `fromAddr` | `string` | none | Caller ID for the outbound leg. Without it, the current call's from address is used. |
430
+
431
+ **Returns:** `this` for chaining.
432
+
433
+ **Example:**
434
+
435
+ ```typescript
436
+ // Permanent transfer
437
+ const result = new FunctionResult('Tell the caller you are connecting them to support.', true)
438
+ .connect('+15551234567');
439
+
440
+ // Temporary transfer: the call returns to the agent afterwards
441
+ const result2 = new FunctionResult('Tell the caller you are bringing in a manager.', true)
442
+ .connect('+15559876543', false);
443
+
444
+ // Transfer with a custom caller ID
445
+ const result3 = new FunctionResult('Tell the caller you are transferring them.', true)
446
+ .connect('+15551234567', true, '+15550001111');
447
+ ```
448
+
449
+ The emitted action for the first example has this shape:
450
+
451
+ ```json
452
+ {
453
+ "SWML": {
454
+ "sections": { "main": [{ "connect": { "to": "+15551234567" } }] },
455
+ "version": "1.0.0"
456
+ },
457
+ "transfer": "true"
458
+ }
459
+ ```
460
+
461
+ ### swmlTransfer
462
+
463
+ Transfer the call with an inline SWML document. The document sets `ai_response` with the `set` verb, then runs the `transfer` verb. Like `connect`, the action carries `transfer: "true"` or `"false"` beside the document.
464
+
465
+ <!-- snippet: no-compile API signature reference, not runnable code -->
466
+ ```typescript
467
+ swmlTransfer(dest: string, aiResponse: string, final?: boolean): this
468
+ ```
469
+
470
+ | Parameter | Type | Default | Description |
471
+ |--------------|-----------|---------|----------------------------------------------------|
472
+ | `dest` | `string` | none | The transfer destination, such as a SWML URL or SIP address. |
473
+ | `aiResponse` | `string` | none | Stored as `ai_response`, for the agent to use when a non-final transfer returns the call. |
474
+ | `final` | `boolean` | `true` | `true` for a permanent transfer, `false` to return to the agent. |
475
+
476
+ **Returns:** `this` for chaining.
477
+
478
+ **Example:**
479
+
480
+ ```typescript
481
+ const result = new FunctionResult('Tell the caller you are transferring them to billing.', true)
482
+ .swmlTransfer(
483
+ 'https://example.com/billing-swml',
484
+ 'The billing call is complete. Ask whether the caller needs anything else.',
485
+ false,
486
+ );
487
+ ```
488
+
489
+ ### hangup
490
+
491
+ Hang up the call. Adds a `{ hangup: true }` action.
492
+
493
+ <!-- snippet: no-compile API signature reference, not runnable code -->
494
+ ```typescript
495
+ hangup(): this
496
+ ```
497
+
498
+ **Returns:** `this` for chaining.
499
+
500
+ **Example:**
501
+
502
+ ```typescript
503
+ const result = new FunctionResult('Thank the caller and say goodbye.')
504
+ .setPostProcess(true)
505
+ .hangup();
506
+ ```
507
+
508
+ ### hold
509
+
510
+ Put the call on hold. During a hold, speech detection is paused and the agent doesn't respond to the caller. The platform plays hold music while the call waits.
511
+
512
+ <!-- snippet: no-compile API signature reference, not runnable code -->
513
+ ```typescript
514
+ hold(prompt?: string | number, timeout?: number, step?: string, timeoutStep?: string): this
515
+ ```
516
+
517
+ | Parameter | Type | Default | Description |
518
+ |---------------|--------------------|---------|-------------------------------------------------------------|
519
+ | `prompt` | `string \| number` | none | Instruction for the model to act on before the hold. A number here is read as `timeout`. |
520
+ | `timeout` | `number` | `300` | Hold duration in seconds, clamped to 0 through 900. |
521
+ | `step` | `string` | none | Step to move to when the call is taken off hold. |
522
+ | `timeoutStep` | `string` | none | Step to move to when the hold times out. |
523
+
524
+ **Returns:** `this` for chaining.
525
+
526
+ The hold action carries no announcement of its own, so say anything the caller needs to hear before the hold takes effect. Passing `prompt` does that for you. It sets the structured response to `tool_result: "status: on hold"` with your prompt as `tool_prompt`, and turns on `postProcess`. The model then takes one more turn, and can tell the caller, before the hold runs.
527
+
528
+ A number as the first argument is the timeout, so `hold(120)` means a 120-second hold with no prompt:
529
+
530
+ ```typescript
531
+ const shortHold = new FunctionResult('The caller is waiting for a supervisor.').hold(120);
532
+ // action: [{ hold: 120 }]
533
+ ```
534
+
535
+ `step` and `timeoutStep` choose the step the call moves to when the hold ends. `step` applies when someone takes the call off hold, for example with [rpcAiUnhold](#rpcaiunhold). `timeoutStep` applies when the timeout passes with nobody releasing the call. Leave one out, and a hold that ends that way resumes in the current step.
536
+
537
+ Both transitions wait for the hold to end. [swmlChangeStep](#swmlchangestep) applies at once instead. Returning it with a hold moves the caller before the hold begins.
538
+
539
+ This example announces the hold and routes the call when the hold ends:
540
+
541
+ ```typescript
542
+ const routed = new FunctionResult().hold(
543
+ 'Tell the caller you are checking whether someone is available.',
544
+ 60,
545
+ 'human_available',
546
+ 'take_message',
547
+ );
548
+ console.log(JSON.stringify(routed.toDict(), null, 2));
549
+ ```
550
+
551
+ The result carries the prompt, the routing and `post_process`:
552
+
553
+ ```json
554
+ {
555
+ "response": {
556
+ "tool_result": "status: on hold",
557
+ "tool_prompt": "Tell the caller you are checking whether someone is available."
558
+ },
559
+ "action": [
560
+ {
561
+ "hold": {
562
+ "timeout": 60,
563
+ "step": "human_available",
564
+ "timeout_step": "take_message"
565
+ }
566
+ }
567
+ ],
568
+ "post_process": true
569
+ }
570
+ ```
571
+
572
+ Without `step` and `timeoutStep`, the action is the bare timeout, such as `{ hold: 300 }`.
573
+
574
+ ### waitForUser
575
+
576
+ Emit a `wait_for_user` action, which controls how the agent waits for the caller's input.
577
+
578
+ <!-- snippet: no-compile API signature reference, not runnable code -->
579
+ ```typescript
580
+ waitForUser(opts?: {
581
+ enabled?: boolean;
582
+ timeout?: number;
583
+ answerFirst?: boolean;
584
+ }): this
585
+ ```
586
+
587
+ | Parameter | Type | Default | Description |
588
+ |--------------------|-----------|---------|--------------------------------------------------|
589
+ | `opts.enabled` | `boolean` | none | Enable or disable waiting for user input. Emits the boolean. |
590
+ | `opts.timeout` | `number` | none | Seconds to wait for user input. Emits the number. |
591
+ | `opts.answerFirst` | `boolean` | none | When `true`, emits the string `"answer_first"`. |
592
+
593
+ **Priority:** `answerFirst` > `timeout` > `enabled`. With no options, the SDK emits `wait_for_user: true`.
594
+
595
+ **Returns:** `this` for chaining.
596
+
597
+ **Example:**
598
+
599
+ ```typescript
600
+ // Wait for the caller
601
+ const r1 = new FunctionResult('Ask the caller to take their time.').waitForUser();
602
+
603
+ // Wait up to 10 seconds
604
+ const r2 = new FunctionResult('The caller is looking for their account number.')
605
+ .waitForUser({ timeout: 10 });
606
+
607
+ // answer_first mode
608
+ const r3 = new FunctionResult('The caller has not spoken yet.')
609
+ .waitForUser({ answerFirst: true });
610
+
611
+ // Stop waiting
612
+ const r4 = new FunctionResult('Continue with the next question.')
613
+ .waitForUser({ enabled: false });
614
+ ```
615
+
616
+ ### stop
617
+
618
+ Stop the AI conversation. Adds a `{ stop: true }` action.
619
+
620
+ <!-- snippet: no-compile API signature reference, not runnable code -->
621
+ ```typescript
622
+ stop(): this
623
+ ```
624
+
625
+ **Returns:** `this` for chaining.
626
+
627
+ **Example:**
628
+
629
+ ```typescript
630
+ const result = new FunctionResult('The session is complete.').stop();
631
+ ```
632
+
633
+ ## Audio
634
+
635
+ ### say
636
+
637
+ Speak text to the caller with text-to-speech. Unlike the response, which the model interprets, this text is spoken to the caller. Adds a `{ say: text }` action.
638
+
639
+ <!-- snippet: no-compile API signature reference, not runnable code -->
640
+ ```typescript
641
+ say(text: string): this
642
+ ```
643
+
644
+ | Parameter | Type | Description |
645
+ |-----------|----------|--------------------------|
646
+ | `text` | `string` | The text to speak. |
647
+
648
+ **Returns:** `this` for chaining.
649
+
650
+ **Example:**
651
+
652
+ ```typescript
653
+ const result = new FunctionResult('Order 12345 was found.')
654
+ .say('Your order number is 12345.');
655
+ ```
656
+
657
+ ### playBackgroundFile
658
+
659
+ Play an audio file in the background during the call. The AI conversation continues while the file plays.
660
+
661
+ <!-- snippet: no-compile API signature reference, not runnable code -->
662
+ ```typescript
663
+ playBackgroundFile(filename: string, wait?: boolean): this
664
+ ```
665
+
666
+ | Parameter | Type | Default | Description |
667
+ |------------|-----------|---------|----------------------------------------------------|
668
+ | `filename` | `string` | none | URL or path of the audio file. |
669
+ | `wait` | `boolean` | `false` | When `true`, wait for the file to finish playing before continuing. |
670
+
671
+ With `wait` false, the action is `{ playback_bg: filename }`. With `wait` true, it's `{ playback_bg: { file: filename, wait: true } }`.
672
+
673
+ **Returns:** `this` for chaining.
674
+
675
+ **Example:**
676
+
677
+ ```typescript
678
+ // Play background music
679
+ const result = new FunctionResult('Hold music is playing.')
680
+ .playBackgroundFile('https://example.com/hold-music.mp3');
681
+
682
+ // Play and wait for the file to finish
683
+ const result2 = new FunctionResult('The announcement is playing.')
684
+ .playBackgroundFile('https://example.com/announcement.wav', true);
685
+ ```
686
+
687
+ ### stopBackgroundFile
688
+
689
+ Stop the background audio file that is playing. Adds a `{ stop_playback_bg: true }` action.
690
+
691
+ <!-- snippet: no-compile API signature reference, not runnable code -->
692
+ ```typescript
693
+ stopBackgroundFile(): this
694
+ ```
695
+
696
+ **Returns:** `this` for chaining.
697
+
698
+ **Example:**
699
+
700
+ ```typescript
701
+ const result = new FunctionResult('The music is stopped.')
702
+ .stopBackgroundFile();
703
+ ```
704
+
705
+ ## Speech
706
+
707
+ ### addDynamicHints
708
+
709
+ Add speech recognition hints during the call, to improve recognition of specific words or phrases. A hint is a string, or a pattern object that replaces matching recognized text.
710
+
711
+ <!-- snippet: no-compile API signature reference, not runnable code -->
712
+ ```typescript
713
+ addDynamicHints(
714
+ hints: (string | { pattern: string; replace: string; ignore_case?: boolean })[]
715
+ ): this
716
+ ```
717
+
718
+ | Parameter | Type | Description |
719
+ |-----------|-----------------------------------------------------------------------------------|------------------------------------------------|
720
+ | `hints` | `(string \| { pattern: string; replace: string; ignore_case?: boolean })[]` | Array of hint strings or pattern objects. |
721
+
722
+ **Returns:** `this` for chaining.
723
+
724
+ **Example:**
725
+
726
+ ```typescript
727
+ // Word hints
728
+ const result = new FunctionResult('Hints are added.')
729
+ .addDynamicHints(['SignalWire', 'SWML', 'SWAIG']);
730
+
731
+ // Pattern-replacement hints
732
+ const result2 = new FunctionResult('Hints are added.')
733
+ .addDynamicHints([
734
+ { pattern: 'signal wire', replace: 'SignalWire', ignore_case: true },
735
+ { pattern: 'swiggy', replace: 'SWAIG' },
736
+ ]);
737
+ ```
738
+
739
+ ### clearDynamicHints
740
+
741
+ Remove all hints added with `addDynamicHints()`. Adds a `{ clear_dynamic_hints: {} }` action.
742
+
743
+ <!-- snippet: no-compile API signature reference, not runnable code -->
744
+ ```typescript
745
+ clearDynamicHints(): this
746
+ ```
747
+
748
+ **Returns:** `this` for chaining.
749
+
750
+ **Example:**
751
+
752
+ ```typescript
753
+ const result = new FunctionResult('Hints are cleared.')
754
+ .clearDynamicHints();
755
+ ```
756
+
757
+ ### setEndOfSpeechTimeout
758
+
759
+ Set how many milliseconds of silence after detected speech finalize speech recognition (`end_of_speech_timeout`). A shorter timeout ends the caller's turn sooner. A longer one allows for pauses.
760
+
761
+ <!-- snippet: no-compile API signature reference, not runnable code -->
762
+ ```typescript
763
+ setEndOfSpeechTimeout(milliseconds: number): this
764
+ ```
765
+
766
+ | Parameter | Type | Description |
767
+ |----------------|----------|-----------------------------------|
768
+ | `milliseconds` | `number` | Timeout in milliseconds. |
769
+
770
+ **Returns:** `this` for chaining.
771
+
772
+ **Example:**
773
+
774
+ ```typescript
775
+ const result = new FunctionResult('The speech timeout is adjusted.')
776
+ .setEndOfSpeechTimeout(500); // 500 ms of silence ends the caller's turn
777
+ ```
778
+
779
+ ### setSpeechEventTimeout
780
+
781
+ Set how many milliseconds after the last speech detection event recognition is finalized (`speech_event_timeout`). It works better than the end-of-speech timeout in noisy environments.
782
+
783
+ <!-- snippet: no-compile API signature reference, not runnable code -->
784
+ ```typescript
785
+ setSpeechEventTimeout(milliseconds: number): this
786
+ ```
787
+
788
+ | Parameter | Type | Description |
789
+ |----------------|----------|-----------------------------------|
790
+ | `milliseconds` | `number` | Timeout in milliseconds. |
791
+
792
+ **Returns:** `this` for chaining.
793
+
794
+ **Example:**
795
+
796
+ ```typescript
797
+ const result = new FunctionResult('The event timeout is set.')
798
+ .setSpeechEventTimeout(3000);
799
+ ```
800
+
801
+ ## Data Management
802
+
803
+ ### updateGlobalData
804
+
805
+ Merge key-value pairs into the call's global data (`set_global_data`). Global data lasts for the AI session. Every function can read it, and prompts can expand it with `${global_data.key}`.
806
+
807
+ <!-- snippet: no-compile API signature reference, not runnable code -->
808
+ ```typescript
809
+ updateGlobalData(data: Record<string, unknown>): this
810
+ ```
811
+
812
+ | Parameter | Type | Description |
813
+ |-----------|----------------------------|------------------------------------|
814
+ | `data` | `Record<string, unknown>` | Key-value pairs to set or update. |
815
+
816
+ **Returns:** `this` for chaining.
817
+
818
+ **Example:**
819
+
820
+ ```typescript
821
+ const result = new FunctionResult('The customer record is loaded.')
822
+ .updateGlobalData({ customer_id: 'C-123', tier: 'premium' });
823
+ ```
824
+
825
+ ### removeGlobalData
826
+
827
+ Remove one or more keys from the global data (`unset_global_data`).
828
+
829
+ <!-- snippet: no-compile API signature reference, not runnable code -->
830
+ ```typescript
831
+ removeGlobalData(keys: string | string[]): this
832
+ ```
833
+
834
+ | Parameter | Type | Description |
835
+ |-----------|----------------------|------------------------------------------|
836
+ | `keys` | `string \| string[]` | A single key or array of keys to remove. |
837
+
838
+ **Returns:** `this` for chaining.
839
+
840
+ **Example:**
841
+
842
+ ```typescript
843
+ // Remove a single key
844
+ const r1 = new FunctionResult('The temporary token is removed.')
845
+ .removeGlobalData('temp_token');
846
+
847
+ // Remove several keys
848
+ const r2 = new FunctionResult('The session cache is cleared.')
849
+ .removeGlobalData(['temp_token', 'session_cache']);
850
+ ```
851
+
852
+ ### setMetadata
853
+
854
+ Set metadata (`set_meta_data`) scoped to the current function's `meta_data_token`. Functions that share a token share the metadata. Without a token, the scope is the function.
855
+
856
+ <!-- snippet: no-compile API signature reference, not runnable code -->
857
+ ```typescript
858
+ setMetadata(data: Record<string, unknown>): this
859
+ ```
860
+
861
+ | Parameter | Type | Description |
862
+ |-----------|----------------------------|-------------------------------|
863
+ | `data` | `Record<string, unknown>` | Metadata key-value pairs. |
864
+
865
+ **Returns:** `this` for chaining.
866
+
867
+ **Example:**
868
+
869
+ ```typescript
870
+ const result = new FunctionResult('The lookup is saved.')
871
+ .setMetadata({ last_action: 'lookup', retry_count: 2 });
872
+ ```
873
+
874
+ ### removeMetadata
875
+
876
+ Remove metadata keys (`unset_meta_data`) from the current function's `meta_data_token` scope.
877
+
878
+ <!-- snippet: no-compile API signature reference, not runnable code -->
879
+ ```typescript
880
+ removeMetadata(keys: string | string[]): this
881
+ ```
882
+
883
+ | Parameter | Type | Description |
884
+ |-----------|----------------------|------------------------------------------|
885
+ | `keys` | `string \| string[]` | A single key or array of keys to remove. |
886
+
887
+ **Returns:** `this` for chaining.
888
+
889
+ **Example:**
890
+
891
+ ```typescript
892
+ const result = new FunctionResult('The temporary metadata is removed.')
893
+ .removeMetadata(['temp_flag', 'debug_info']);
894
+ ```
895
+
896
+ ## SWML Actions
897
+
898
+ ### executeSwml
899
+
900
+ Run arbitrary SWML content as an action.
901
+
902
+ <!-- snippet: no-compile API signature reference, not runnable code -->
903
+ ```typescript
904
+ executeSwml(
905
+ swmlContent: string | Record<string, unknown> | { toDict(): Record<string, unknown> },
906
+ transfer?: boolean
907
+ ): this
908
+ ```
909
+
910
+ | Parameter | Type | Default | Description |
911
+ |---------------|-----------------------------------------|---------|---------------------------------------------------|
912
+ | `swmlContent` | `string \| Record<string, unknown> \| { toDict() }` | none | SWML as a JSON string, a plain object, or an object with a `toDict()` method. |
913
+ | `transfer` | `boolean` | `false` | When `true`, the call leaves the agent for this SWML. |
914
+
915
+ The SDK normalizes `swmlContent` as follows:
916
+
917
+ - A JSON string is parsed. A string that isn't valid JSON is sent as `{ raw_swml: <string> }`.
918
+ - An object with a `toDict()` method is converted through it.
919
+ - A plain object is copied, so the SDK never changes yours.
920
+ - Any other value, such as a number, an array or `null`, throws an `Error`.
921
+
922
+ The action is `{ SWML: <document> }`. With `transfer` set, the SDK adds `transfer: "true"` beside the `SWML` key, not inside the document. That is the same shape `connect()` and `swmlTransfer()` emit.
923
+
924
+ **Returns:** `this` for chaining.
925
+
926
+ **Example:**
927
+
928
+ ```typescript
929
+ // Run SWML from an object
930
+ const result = new FunctionResult('A short announcement is playing.')
931
+ .executeSwml({
932
+ version: '1.0.0',
933
+ sections: {
934
+ main: [{ play: { url: 'https://example.com/audio.mp3' } }],
935
+ },
936
+ });
937
+
938
+ // Run SWML and leave the agent
939
+ const result2 = new FunctionResult('Tell the caller you are transferring them.', true)
940
+ .executeSwml({
941
+ version: '1.0.0',
942
+ sections: {
943
+ main: [{ connect: { to: '+15551234567' } }],
944
+ },
945
+ }, true);
946
+ ```
947
+
948
+ The second example emits this action:
949
+
950
+ ```json
951
+ {
952
+ "SWML": {
953
+ "version": "1.0.0",
954
+ "sections": { "main": [{ "connect": { "to": "+15551234567" } }] }
955
+ },
956
+ "transfer": "true"
957
+ }
958
+ ```
959
+
960
+ ### switchContext
961
+
962
+ Replace the agent's prompt during the call (`context_switch`). It can set a new system prompt, add a user prompt, summarize the conversation so far, or reset the context completely.
963
+
964
+ <!-- snippet: no-compile API signature reference, not runnable code -->
965
+ ```typescript
966
+ switchContext(opts?: {
967
+ systemPrompt?: string;
968
+ userPrompt?: string;
969
+ consolidate?: boolean;
970
+ fullReset?: boolean;
971
+ }): this
972
+ ```
973
+
974
+ | Parameter | Type | Description |
975
+ |---------------------|-----------|-------------------------------------------------------------------|
976
+ | `opts.systemPrompt` | `string` | New system prompt. |
977
+ | `opts.userPrompt` | `string` | Text added as if the user had said it, to give the new prompt context. |
978
+ | `opts.consolidate` | `boolean` | When `true`, summarize the existing conversation. |
979
+ | `opts.fullReset` | `boolean` | When `true`, reset the context completely. |
980
+
981
+ **Behavior:** With only `systemPrompt`, the action value is the prompt string. Otherwise it's an object with the fields that are set.
982
+
983
+ **Returns:** `this` for chaining.
984
+
985
+ **Example:**
986
+
987
+ ```typescript
988
+ // Change the system prompt only
989
+ const r1 = new FunctionResult('The caller has a billing question.')
990
+ .switchContext({ systemPrompt: 'You are a billing specialist.' });
991
+
992
+ // Change it and summarize the conversation so far
993
+ const r2 = new FunctionResult('The call is escalated to a supervisor.')
994
+ .switchContext({
995
+ systemPrompt: 'You are a supervisor handling an escalated call.',
996
+ consolidate: true,
997
+ });
998
+
999
+ // Full reset
1000
+ const r3 = new FunctionResult('The caller wants to start over.')
1001
+ .switchContext({
1002
+ systemPrompt: 'You are a general assistant.',
1003
+ fullReset: true,
1004
+ });
1005
+ ```
1006
+
1007
+ ### swmlChangeStep
1008
+
1009
+ Move the conversation to another step in the current context (`change_step`). The step must exist in the current context of the agent's contexts, which you define with `defineContexts()`. The change applies at once, and a change from a tool isn't limited by the step's `setValidSteps()` list.
1010
+
1011
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1012
+ ```typescript
1013
+ swmlChangeStep(stepName: string): this
1014
+ ```
1015
+
1016
+ | Parameter | Type | Description |
1017
+ |------------|----------|------------------------------------|
1018
+ | `stepName` | `string` | The name of the step to switch to. |
1019
+
1020
+ **Returns:** `this` for chaining.
1021
+
1022
+ The model reads the response before the new step's instructions, so put the reason for the move there. Pass values the step needs with `updateGlobalData()`, and expand them in the step's text.
1023
+
1024
+ **Example:**
1025
+
1026
+ ```typescript
1027
+ const result = new FunctionResult('The premium plan is confirmed. Collect payment details next.')
1028
+ .updateGlobalData({ plan: 'premium' })
1029
+ .swmlChangeStep('collect_payment');
1030
+ ```
1031
+
1032
+ ### swmlChangeContext
1033
+
1034
+ Move the conversation to another context (`change_context`). The context must exist in the agent's contexts, which you define with `defineContexts()`. A change from a tool isn't limited by `setValidContexts()`.
1035
+
1036
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1037
+ ```typescript
1038
+ swmlChangeContext(contextName: string): this
1039
+ ```
1040
+
1041
+ | Parameter | Type | Description |
1042
+ |---------------|----------|---------------------------------------|
1043
+ | `contextName` | `string` | The name of the context to switch to. |
1044
+
1045
+ **Returns:** `this` for chaining.
1046
+
1047
+ **Example:**
1048
+
1049
+ ```typescript
1050
+ const result = new FunctionResult('The caller asked for support in Spanish.')
1051
+ .swmlChangeContext('spanish_support');
1052
+ ```
1053
+
1054
+ ### swmlUserEvent
1055
+
1056
+ Send an event to the client connected to the call, such as a browser using the SignalWire browser SDK. The SDK wraps `eventData` in an inline SWML `user_event` verb, and the client receives it as a `user_event` event.
1057
+
1058
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1059
+ ```typescript
1060
+ swmlUserEvent(eventData: Record<string, unknown>): this
1061
+ ```
1062
+
1063
+ | Parameter | Type | Description |
1064
+ |-------------|----------------------------|----------------------|
1065
+ | `eventData` | `Record<string, unknown>` | The event payload. |
1066
+
1067
+ **Returns:** `this` for chaining.
1068
+
1069
+ **Example:**
1070
+
1071
+ ```typescript
1072
+ const result = new FunctionResult('Order ORD-456 was placed.')
1073
+ .swmlUserEvent({
1074
+ type: 'order_placed',
1075
+ order_id: 'ORD-456',
1076
+ total: 29.99,
1077
+ });
1078
+ ```
1079
+
1080
+ ## Function Control
1081
+
1082
+ ### toggleFunctions
1083
+
1084
+ Enable or disable SWAIG functions by name during the call (`toggle_functions`), to control which tools the model can call.
1085
+
1086
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1087
+ ```typescript
1088
+ toggleFunctions(toggles: { function: string; active: boolean }[]): this
1089
+ ```
1090
+
1091
+ | Parameter | Type | Description |
1092
+ |--------------------|-----------|------------------------------------------|
1093
+ | `toggles[].function` | `string` | The name of the SWAIG function. |
1094
+ | `toggles[].active` | `boolean` | `true` to enable, `false` to disable. |
1095
+
1096
+ **Returns:** `this` for chaining.
1097
+
1098
+ **Example:**
1099
+
1100
+ ```typescript
1101
+ // After verification, enable the account tools
1102
+ const result = new FunctionResult('The caller is verified.')
1103
+ .toggleFunctions([
1104
+ { function: 'check_balance', active: true },
1105
+ { function: 'make_payment', active: true },
1106
+ { function: 'verify_identity', active: false },
1107
+ ]);
1108
+ ```
1109
+
1110
+ ### enableFunctionsOnTimeout
1111
+
1112
+ Control whether the model can call functions on a speaker timeout, when the caller is silent (`functions_on_speaker_timeout`).
1113
+
1114
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1115
+ ```typescript
1116
+ enableFunctionsOnTimeout(enabled?: boolean): this
1117
+ ```
1118
+
1119
+ | Parameter | Type | Default | Description |
1120
+ |-----------|-----------|---------|------------------------------------------------------|
1121
+ | `enabled` | `boolean` | `true` | Whether functions can be called on speaker timeout. |
1122
+
1123
+ **Returns:** `this` for chaining.
1124
+
1125
+ **Example:**
1126
+
1127
+ ```typescript
1128
+ // Allow functions on speaker timeout
1129
+ const r1 = new FunctionResult('The caller may go quiet while searching.')
1130
+ .enableFunctionsOnTimeout();
1131
+
1132
+ // Disallow them
1133
+ const r2 = new FunctionResult('Wait for the caller to answer.')
1134
+ .enableFunctionsOnTimeout(false);
1135
+ ```
1136
+
1137
+ ### updateSettings
1138
+
1139
+ Update AI settings during the call (`settings`). The platform validates the keys. The Python SDK's reference lists `temperature`, `top-p`, `max-tokens`, `frequency-penalty`, `presence-penalty`, `confidence` and `barge-confidence`.
1140
+
1141
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1142
+ ```typescript
1143
+ updateSettings(settings: Record<string, unknown>): this
1144
+ ```
1145
+
1146
+ | Parameter | Type | Description |
1147
+ |------------|----------------------------|--------------------------------------|
1148
+ | `settings` | `Record<string, unknown>` | Key-value pairs of settings. |
1149
+
1150
+ **Returns:** `this` for chaining.
1151
+
1152
+ **Example:**
1153
+
1154
+ ```typescript
1155
+ const result = new FunctionResult('The settings are updated.')
1156
+ .updateSettings({ temperature: 0.3, 'top-p': 0.9 });
1157
+ ```
1158
+
1159
+ ## User Input and History
1160
+
1161
+ ### simulateUserInput
1162
+
1163
+ Queue text as if the caller had said it (`user_input`). Use it to drive the conversation from code.
1164
+
1165
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1166
+ ```typescript
1167
+ simulateUserInput(text: string): this
1168
+ ```
1169
+
1170
+ | Parameter | Type | Description |
1171
+ |-----------|----------|------------------------------------|
1172
+ | `text` | `string` | The simulated user input text. |
1173
+
1174
+ **Returns:** `this` for chaining.
1175
+
1176
+ **Example:**
1177
+
1178
+ ```typescript
1179
+ const result = new FunctionResult('The caller accepted the default option.')
1180
+ .simulateUserInput('Yes, go ahead with the default.');
1181
+ ```
1182
+
1183
+ ### enableExtensiveData
1184
+
1185
+ Send the full data to the model for this turn only, and a smaller replacement in later turns (`extensive_data`).
1186
+
1187
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1188
+ ```typescript
1189
+ enableExtensiveData(enabled?: boolean): this
1190
+ ```
1191
+
1192
+ | Parameter | Type | Default | Description |
1193
+ |-----------|-----------|---------|------------------------------------------|
1194
+ | `enabled` | `boolean` | `true` | Whether to send extensive data this turn. |
1195
+
1196
+ **Returns:** `this` for chaining.
1197
+
1198
+ **Example:**
1199
+
1200
+ ```typescript
1201
+ const result = new FunctionResult('The full order history is attached.')
1202
+ .enableExtensiveData();
1203
+ ```
1204
+
1205
+ ### replaceInHistory
1206
+
1207
+ After the first send, remove or replace this tool call and its result in the conversation history (`replace_in_history`). Use it when a function call is an implementation detail that would confuse the model if it stayed in context.
1208
+
1209
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1210
+ ```typescript
1211
+ replaceInHistory(text?: string | boolean): this
1212
+ ```
1213
+
1214
+ | Parameter | Type | Default | Description |
1215
+ |-----------|-----------------------|---------|-----------------------------------------------------------|
1216
+ | `text` | `string \| boolean` | `true` | A string replaces the pair with an assistant message holding that text. `true` removes the pair. |
1217
+
1218
+ **Returns:** `this` for chaining.
1219
+
1220
+ **Example:**
1221
+
1222
+ ```typescript
1223
+ // Remove the tool call and result from the history
1224
+ const r1 = new FunctionResult('The answer is saved.')
1225
+ .replaceInHistory();
1226
+
1227
+ // Replace them with an assistant message
1228
+ const r2 = new FunctionResult('The identity check passed.')
1229
+ .replaceInHistory('Identity verification completed.');
1230
+ ```
1231
+
1232
+ ## Communication
1233
+
1234
+ ### sendSms
1235
+
1236
+ Send an SMS or MMS message from within the call flow. The SDK emits an inline SWML `send_sms` verb. Provide `body`, `media`, or both.
1237
+
1238
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1239
+ ```typescript
1240
+ sendSms(opts: {
1241
+ toNumber: string;
1242
+ fromNumber: string;
1243
+ body?: string;
1244
+ media?: string[];
1245
+ tags?: string[];
1246
+ region?: string;
1247
+ }): this
1248
+ ```
1249
+
1250
+ | Parameter | Type | Description |
1251
+ |------------------|------------|------------------------------------------------|
1252
+ | `opts.toNumber` | `string` | Recipient phone number, in E.164 format. |
1253
+ | `opts.fromNumber` | `string` | Sender phone number, in E.164 format. |
1254
+ | `opts.body` | `string` | Message text. |
1255
+ | `opts.media` | `string[]` | Media URLs for an MMS. |
1256
+ | `opts.tags` | `string[]` | Tags for the message. |
1257
+ | `opts.region` | `string` | Region to send the message from. |
1258
+
1259
+ **Throws:** `Error` if neither `body` nor `media` is provided.
1260
+
1261
+ **Returns:** `this` for chaining.
1262
+
1263
+ **Example:**
1264
+
1265
+ ```typescript
1266
+ // Send a text message
1267
+ const result = new FunctionResult('The confirmation text is sent.')
1268
+ .sendSms({
1269
+ toNumber: '+15551234567',
1270
+ fromNumber: '+15559876543',
1271
+ body: 'Your appointment is confirmed for tomorrow at 2pm.',
1272
+ });
1273
+
1274
+ // Send an MMS with an image
1275
+ const result2 = new FunctionResult('The receipt is sent.')
1276
+ .sendSms({
1277
+ toNumber: '+15551234567',
1278
+ fromNumber: '+15559876543',
1279
+ body: 'Here is your receipt:',
1280
+ media: ['https://example.com/receipt.png'],
1281
+ });
1282
+ ```
1283
+
1284
+ ### recordCall
1285
+
1286
+ Start a background recording of the call. The SDK emits an inline SWML `record_call` verb, and the call continues while it records.
1287
+
1288
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1289
+ ```typescript
1290
+ recordCall(opts?: {
1291
+ controlId?: string;
1292
+ stereo?: boolean;
1293
+ format?: 'wav' | 'mp3' | 'mp4';
1294
+ direction?: 'speak' | 'listen' | 'both';
1295
+ terminators?: string;
1296
+ beep?: boolean;
1297
+ inputSensitivity?: number;
1298
+ initialTimeout?: number;
1299
+ endSilenceTimeout?: number;
1300
+ maxLength?: number;
1301
+ statusUrl?: string;
1302
+ }): this
1303
+ ```
1304
+
1305
+ | Parameter | Type | Default | Description |
1306
+ |-------------------------|---------------------------------|----------|-------------------------------------------------|
1307
+ | `opts.controlId` | `string` | none | Identifier for this recording, for `stopRecordCall()`. |
1308
+ | `opts.stereo` | `boolean` | `false` | Record in stereo. |
1309
+ | `opts.format` | `'wav' \| 'mp3' \| 'mp4'` | `'wav'` | Recording file format. |
1310
+ | `opts.direction` | `'speak' \| 'listen' \| 'both'` | `'both'` | Audio to record: what the party says, hears, or both. |
1311
+ | `opts.terminators` | `string` | none | DTMF digits that stop the recording. |
1312
+ | `opts.beep` | `boolean` | `false` | Play a beep before recording. |
1313
+ | `opts.inputSensitivity` | `number` | `44.0` | Sensitivity of the voice activity detector to background noise, from 0 to 100. |
1314
+ | `opts.initialTimeout` | `number` | none | Seconds to wait for speech to start. |
1315
+ | `opts.endSilenceTimeout`| `number` | none | Seconds of silence before the recording ends. |
1316
+ | `opts.maxLength` | `number` | none | Maximum recording length in seconds. |
1317
+ | `opts.statusUrl` | `string` | none | URL that receives recording status events. |
1318
+
1319
+ The SDK always sends `stereo`, `format`, `direction`, `beep` and `input_sensitivity`, and sends the other options only when set.
1320
+
1321
+ **Returns:** `this` for chaining.
1322
+
1323
+ **Example:**
1324
+
1325
+ ```typescript
1326
+ // Record with the defaults
1327
+ const result = new FunctionResult('The recording has started.')
1328
+ .recordCall();
1329
+
1330
+ // Stereo MP3 recording with a control ID
1331
+ const result2 = new FunctionResult('The recording has started.')
1332
+ .recordCall({
1333
+ controlId: 'main-recording',
1334
+ stereo: true,
1335
+ format: 'mp3',
1336
+ maxLength: 3600,
1337
+ statusUrl: 'https://example.com/recording-status',
1338
+ });
1339
+ ```
1340
+
1341
+ ### stopRecordCall
1342
+
1343
+ Stop a background recording (SWML `stop_record_call`).
1344
+
1345
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1346
+ ```typescript
1347
+ stopRecordCall(controlId?: string): this
1348
+ ```
1349
+
1350
+ | Parameter | Type | Description |
1351
+ |-------------|----------|--------------------------------------------------|
1352
+ | `controlId` | `string` | Control ID of the recording to stop. Omit it to stop the most recent recording. |
1353
+
1354
+ **Returns:** `this` for chaining.
1355
+
1356
+ **Example:**
1357
+
1358
+ ```typescript
1359
+ const result = new FunctionResult('The recording has stopped.')
1360
+ .stopRecordCall('main-recording');
1361
+ ```
1362
+
1363
+ ### tap
1364
+
1365
+ Start a background media tap, which streams the call's audio to a WebSocket or RTP destination, for example for real-time transcription or monitoring. The SDK emits an inline SWML `tap` verb.
1366
+
1367
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1368
+ ```typescript
1369
+ tap(opts: {
1370
+ uri: string;
1371
+ controlId?: string;
1372
+ direction?: 'speak' | 'listen' | 'both';
1373
+ codec?: 'PCMU' | 'PCMA';
1374
+ rtpPtime?: number;
1375
+ statusUrl?: string;
1376
+ }): this
1377
+ ```
1378
+
1379
+ | Parameter | Type | Default | Description |
1380
+ |------------------|----------------------------------|----------|----------------------------------------------|
1381
+ | `opts.uri` | `string` | none | Destination of the stream: `ws://...`, `wss://...` or `rtp://IP:port`. |
1382
+ | `opts.controlId` | `string` | none | Identifier for this tap, for `stopTap()`. |
1383
+ | `opts.direction` | `'speak' \| 'listen' \| 'both'` | `'both'` | `speak` is what the party says, `listen` is what it hears, and `both` is both. |
1384
+ | `opts.codec` | `'PCMU' \| 'PCMA'` | `'PCMU'` | Audio codec for the stream. |
1385
+ | `opts.rtpPtime` | `number` | `20` | RTP packetization time in milliseconds, for an `rtp://` destination. |
1386
+ | `opts.statusUrl` | `string` | none | URL that receives tap status events. |
1387
+
1388
+ The SDK always sends `direction`, because the SWML `tap` verb defaults to `speak` when it's missing. It sends `codec` and `rtp_ptime` only when they differ from `PCMU` and 20.
1389
+
1390
+ **Throws:** `Error` when `direction` or `codec` isn't one of the listed values, or `rtpPtime` isn't positive.
1391
+
1392
+ **Returns:** `this` for chaining.
1393
+
1394
+ **Example:**
1395
+
1396
+ ```typescript
1397
+ const result = new FunctionResult('The transcription stream has started.')
1398
+ .tap({
1399
+ uri: 'wss://transcription.example.com/stream',
1400
+ controlId: 'realtime-tap',
1401
+ direction: 'both',
1402
+ });
1403
+ ```
1404
+
1405
+ ### stopTap
1406
+
1407
+ Stop a media tap (SWML `stop_tap`).
1408
+
1409
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1410
+ ```typescript
1411
+ stopTap(controlId?: string): this
1412
+ ```
1413
+
1414
+ | Parameter | Type | Description |
1415
+ |-------------|----------|---------------------------------------------|
1416
+ | `controlId` | `string` | Control ID of the tap to stop. Omit it to stop the most recent tap. |
1417
+
1418
+ **Returns:** `this` for chaining.
1419
+
1420
+ **Example:**
1421
+
1422
+ ```typescript
1423
+ const result = new FunctionResult('The transcription stream has stopped.')
1424
+ .stopTap('realtime-tap');
1425
+ ```
1426
+
1427
+ ## Rooms and Conferencing
1428
+
1429
+ ### joinRoom
1430
+
1431
+ Join a RELAY room by name (SWML `join_room`). The platform creates the room if it doesn't exist.
1432
+
1433
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1434
+ ```typescript
1435
+ joinRoom(name: string): this
1436
+ ```
1437
+
1438
+ | Parameter | Type | Description |
1439
+ |-----------|----------|-----------------------|
1440
+ | `name` | `string` | The room name. Letters, digits, underscores and hyphens are allowed. |
1441
+
1442
+ **Returns:** `this` for chaining.
1443
+
1444
+ **Example:**
1445
+
1446
+ ```typescript
1447
+ const result = new FunctionResult('The caller is joining the team meeting.')
1448
+ .joinRoom('team-standup');
1449
+ ```
1450
+
1451
+ ### sipRefer
1452
+
1453
+ Send a SIP REFER to transfer the call to another SIP endpoint (SWML `sip_refer`).
1454
+
1455
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1456
+ ```typescript
1457
+ sipRefer(toUri: string): this
1458
+ ```
1459
+
1460
+ | Parameter | Type | Description |
1461
+ |-----------|----------|---------------------------------------|
1462
+ | `toUri` | `string` | The SIP URI to send the REFER to. |
1463
+
1464
+ **Returns:** `this` for chaining.
1465
+
1466
+ **Example:**
1467
+
1468
+ ```typescript
1469
+ const result = new FunctionResult('Tell the caller you are transferring them.', true)
1470
+ .sipRefer('sip:agent@pbx.example.com');
1471
+ ```
1472
+
1473
+ ### joinConference
1474
+
1475
+ Join a conference by name (SWML `join_conference`), with optional settings.
1476
+
1477
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1478
+ ```typescript
1479
+ joinConference(name: string, opts?: {
1480
+ muted?: boolean;
1481
+ beep?: 'true' | 'false' | 'onEnter' | 'onExit';
1482
+ startOnEnter?: boolean;
1483
+ endOnExit?: boolean;
1484
+ waitUrl?: string;
1485
+ maxParticipants?: number | string;
1486
+ record?: 'do-not-record' | 'record-from-start';
1487
+ region?: string;
1488
+ trim?: 'trim-silence' | 'do-not-trim';
1489
+ coach?: string;
1490
+ statusCallbackEvent?: string;
1491
+ statusCallback?: string;
1492
+ statusCallbackMethod?: 'GET' | 'POST';
1493
+ recordingStatusCallback?: string;
1494
+ recordingStatusCallbackMethod?: 'GET' | 'POST';
1495
+ recordingStatusCallbackEvent?: string;
1496
+ result?: unknown;
1497
+ }): this
1498
+ ```
1499
+
1500
+ | Parameter | Type | Default | Description |
1501
+ |----------------------------------------|---------------------------------------------|---------------------|------------------------------------------------------|
1502
+ | `name` | `string` | none | Conference name. Must not be blank. |
1503
+ | `opts.muted` | `boolean` | `false` | Join muted. |
1504
+ | `opts.beep` | `'true' \| 'false' \| 'onEnter' \| 'onExit'` | `'true'` | When to play the beep. |
1505
+ | `opts.startOnEnter` | `boolean` | `true` | Start the conference when this participant joins. |
1506
+ | `opts.endOnExit` | `boolean` | `false` | End the conference when this participant leaves. |
1507
+ | `opts.waitUrl` | `string` | none | URL of media to play while the conference is on hold. |
1508
+ | `opts.maxParticipants` | `number \| string` | none | Maximum number of participants, an integer of 2 or more, or a SWML variable reference such as `'${room_size}'`. A numeric string is sent as an integer. Sent whenever it's given. The platform refuses fewer than 2 and sets no upper limit; the schema's cap of 100000 isn't enforced. |
1509
+ | `opts.record` | `'do-not-record' \| 'record-from-start'` | `'do-not-record'` | Recording mode. |
1510
+ | `opts.region` | `string` | none | Region for the conference. |
1511
+ | `opts.trim` | `'trim-silence' \| 'do-not-trim'` | `'trim-silence'` | Silence trimming for recordings. |
1512
+ | `opts.coach` | `string` | none | Call SID of a call connected to the conference, to coach. |
1513
+ | `opts.statusCallbackEvent` | `string` | none | Space-separated events to send to the status callback. |
1514
+ | `opts.statusCallback` | `string` | none | URL for status callbacks. |
1515
+ | `opts.statusCallbackMethod` | `'GET' \| 'POST'` | `'POST'` | HTTP method for status callbacks. |
1516
+ | `opts.recordingStatusCallback` | `string` | none | URL for recording status callbacks. |
1517
+ | `opts.recordingStatusCallbackMethod` | `'GET' \| 'POST'` | `'POST'` | HTTP method for recording status callbacks. |
1518
+ | `opts.recordingStatusCallbackEvent` | `string` | `'completed'` | Events to send to the recording status callback. |
1519
+ | `opts.result` | `unknown` | none | Actions to switch on by result, as the verb's `result` object. |
1520
+
1521
+ **Behavior:** The SDK leaves out any option set to its default value, except `maxParticipants`, which is sent whenever it's given. When no option remains, the `join_conference` value is the name string. Otherwise it's an object with `name` and the other options.
1522
+
1523
+ **Throws:** `Error` when `name` is blank, or `maxParticipants` isn't an integer of at least 2 or a SWML variable reference.
1524
+
1525
+ **Returns:** `this` for chaining.
1526
+
1527
+ **Example:**
1528
+
1529
+ ```typescript
1530
+ // Join with the defaults
1531
+ const result = new FunctionResult('The caller is joining the support conference.')
1532
+ .joinConference('support-queue');
1533
+
1534
+ // Join muted, recorded, and capped at 50 participants
1535
+ const result2 = new FunctionResult('The caller is joining as a listener.')
1536
+ .joinConference('all-hands', {
1537
+ muted: true,
1538
+ record: 'record-from-start',
1539
+ maxParticipants: 50,
1540
+ beep: 'onEnter',
1541
+ });
1542
+ ```
1543
+
1544
+ ## RPC
1545
+
1546
+ ### executeRpc
1547
+
1548
+ Run a SignalWire RPC method from an inline SWML `execute_rpc` verb. It's the low-level method under `rpcDial()`, `rpcAiMessage()`, `rpcAiGlobalData()` and `rpcAiUnhold()`, which use the `dial`, `ai_message` and `ai_unhold` methods.
1549
+
1550
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1551
+ ```typescript
1552
+ executeRpc(opts: {
1553
+ method: string;
1554
+ params?: Record<string, unknown>;
1555
+ callId?: string;
1556
+ nodeId?: string;
1557
+ }): this
1558
+ ```
1559
+
1560
+ | Parameter | Type | Description |
1561
+ |---------------|----------------------------|-------------------------------------|
1562
+ | `opts.method` | `string` | The RPC method name. |
1563
+ | `opts.params` | `Record<string, unknown>` | Parameters for the method. An empty object is left out. |
1564
+ | `opts.callId` | `string` | Target call ID. |
1565
+ | `opts.nodeId` | `string` | Target node ID. |
1566
+
1567
+ **Returns:** `this` for chaining.
1568
+
1569
+ **Example:**
1570
+
1571
+ ```typescript
1572
+ const result = new FunctionResult('The other caller has been notified.')
1573
+ .executeRpc({
1574
+ method: 'ai_message',
1575
+ callId: 'call-abc-123',
1576
+ params: { role: 'system', message_text: 'The customer has been verified.' },
1577
+ });
1578
+ ```
1579
+
1580
+ ### rpcDial
1581
+
1582
+ Dial out with the `dial` RPC method. Use it, for example, to hold the caller and dial a person whose call runs the SWML at `destSwml`.
1583
+
1584
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1585
+ ```typescript
1586
+ rpcDial(
1587
+ toNumber: string,
1588
+ fromNumber: string,
1589
+ destSwml: string,
1590
+ deviceType?: string
1591
+ ): this
1592
+ ```
1593
+
1594
+ | Parameter | Type | Default | Description |
1595
+ |--------------|----------|-----------|------------------------------------------|
1596
+ | `toNumber` | `string` | none | Number to dial, in E.164 format. |
1597
+ | `fromNumber` | `string` | none | Caller ID, in E.164 format. |
1598
+ | `destSwml` | `string` | none | URL of the SWML that handles the dialed call. |
1599
+ | `deviceType` | `string` | `'phone'` | Device type for the outbound leg. |
1600
+
1601
+ **Returns:** `this` for chaining.
1602
+
1603
+ **Example:**
1604
+
1605
+ ```typescript
1606
+ const result = new FunctionResult()
1607
+ .hold('Tell the caller you are checking whether a manager is available.', 120)
1608
+ .rpcDial('+15551234567', '+15559876543', 'https://example.com/manager-swml');
1609
+ ```
1610
+
1611
+ ### rpcAiMessage
1612
+
1613
+ Send a message, global data, or both to the AI agent on another call, with the `ai_message` RPC method.
1614
+
1615
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1616
+ ```typescript
1617
+ rpcAiMessage(
1618
+ callId: string,
1619
+ messageText?: string | null,
1620
+ role?: string,
1621
+ globalData?: Record<string, unknown>
1622
+ ): this
1623
+ ```
1624
+
1625
+ | Parameter | Type | Default | Description |
1626
+ |---------------|---------------------------|------------|-------------------------------------------------|
1627
+ | `callId` | `string` | none | The target call ID. |
1628
+ | `messageText` | `string \| null` | none | Message to add as a turn in the other conversation. |
1629
+ | `role` | `string` | `'system'` | Role for the message. Sent only with `messageText`. |
1630
+ | `globalData` | `Record<string, unknown>` | none | Object merged into the target call's global data. |
1631
+
1632
+ **Throws:** `Error` when neither `messageText` nor `globalData` is given.
1633
+
1634
+ **Returns:** `this` for chaining.
1635
+
1636
+ The two payloads behave differently. `messageText` arrives as a turn in the other conversation, alongside everything else arriving then. `globalData` is merged into the other call's global data without a turn, and a prompt there reads it with `${global_data.your_key}`. For content that a later step on the other call must say, prefer global data. [rpcAiGlobalData](#rpcaiglobaldata) sends global data only.
1637
+
1638
+ **Example:**
1639
+
1640
+ ```typescript
1641
+ const result = new FunctionResult('The manager declined the call.')
1642
+ .rpcAiMessage('call-abc-123', 'No one is available. Take a message.')
1643
+ .rpcAiUnhold('call-abc-123');
1644
+ ```
1645
+
1646
+ ### rpcAiGlobalData
1647
+
1648
+ Merge data into another call's global data, with no conversation turn. It calls `rpcAiMessage(callId, undefined, 'system', data)`.
1649
+
1650
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1651
+ ```typescript
1652
+ rpcAiGlobalData(callId: string, data: Record<string, unknown>): this
1653
+ ```
1654
+
1655
+ | Parameter | Type | Description |
1656
+ |-----------|---------------------------|----------------------------------------------|
1657
+ | `callId` | `string` | The target call ID. |
1658
+ | `data` | `Record<string, unknown>` | Object merged into that call's global data. |
1659
+
1660
+ **Returns:** `this` for chaining.
1661
+
1662
+ This example sends a message for the held caller's agent and then releases the hold:
1663
+
1664
+ ```typescript
1665
+ const result = new FunctionResult('The manager declined the call.')
1666
+ .rpcAiGlobalData('call-abc-123', {
1667
+ decline_message: 'The manager is in a meeting until 3pm.',
1668
+ })
1669
+ .rpcAiUnhold('call-abc-123');
1670
+ ```
1671
+
1672
+ A step on the other call can then use the value, with text such as `Tell the caller: ${global_data.decline_message}`.
1673
+
1674
+ ### rpcAiUnhold
1675
+
1676
+ Take another call off hold, with the `ai_unhold` RPC method. When that call's hold has a `step`, the call moves to that step. For more information, see [hold](#hold).
1677
+
1678
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1679
+ ```typescript
1680
+ rpcAiUnhold(callId: string): this
1681
+ ```
1682
+
1683
+ | Parameter | Type | Description |
1684
+ |-----------|----------|--------------------------------|
1685
+ | `callId` | `string` | The ID of the call to take off hold. |
1686
+
1687
+ **Returns:** `this` for chaining.
1688
+
1689
+ **Example:**
1690
+
1691
+ ```typescript
1692
+ const result = new FunctionResult('The held caller is being reconnected.')
1693
+ .rpcAiUnhold('call-abc-123');
1694
+ ```
1695
+
1696
+ ## Payments
1697
+
1698
+ ### pay
1699
+
1700
+ Start a payment collection flow on the call. The SDK emits an inline SWML document that sets `ai_response` with the `set` verb and then runs the `pay` verb. The payment connector at `paymentConnectorUrl` processes the payment.
1701
+
1702
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1703
+ ```typescript
1704
+ pay(opts: {
1705
+ paymentConnectorUrl: string;
1706
+ inputMethod?: string;
1707
+ statusUrl?: string;
1708
+ paymentMethod?: string;
1709
+ timeout?: number | string;
1710
+ maxAttempts?: number | string;
1711
+ securityCode?: boolean | string;
1712
+ postalCode?: boolean | string;
1713
+ minPostalCodeLength?: number | string;
1714
+ tokenType?: string;
1715
+ chargeAmount?: string;
1716
+ currency?: string;
1717
+ language?: string;
1718
+ voice?: string;
1719
+ description?: string;
1720
+ validCardTypes?: string;
1721
+ parameters?: PaymentParameter[];
1722
+ prompts?: PaymentPrompt[];
1723
+ aiResponse?: string;
1724
+ }): this
1725
+ ```
1726
+
1727
+ | Parameter | Type | Default | Description |
1728
+ |----------------------------|----------------------|---------------------------------------|-----------------------------------------------------------------|
1729
+ | `opts.paymentConnectorUrl` | `string` | none | URL of the payment connector. |
1730
+ | `opts.inputMethod` | `string` | `'dtmf'` | How the caller enters details. The SWML `pay` verb accepts only `'dtmf'`. |
1731
+ | `opts.statusUrl` | `string` | none | URL that receives payment status events. |
1732
+ | `opts.paymentMethod` | `string` | `'credit-card'` | Payment method. The verb accepts only `'credit-card'`. |
1733
+ | `opts.timeout` | `number \| string` | `5` | Seconds to wait for the next digit. |
1734
+ | `opts.maxAttempts` | `number \| string` | `1` | Number of times the `pay` verb retries collecting the details. |
1735
+ | `opts.securityCode` | `boolean \| string` | `true` | Whether to ask for the security code. |
1736
+ | `opts.postalCode` | `boolean \| string` | `true` | Whether to ask for the postal code, or the postal code itself when it's known. |
1737
+ | `opts.minPostalCodeLength` | `number \| string` | `0` | Minimum postal code length. |
1738
+ | `opts.tokenType` | `string` | `'reusable'` | `'one-time'` or `'reusable'`. |
1739
+ | `opts.chargeAmount` | `string` | none | Amount to charge, as a decimal string (for example `'29.99'`). |
1740
+ | `opts.currency` | `string` | `'usd'` | ISO 4217 currency code. |
1741
+ | `opts.language` | `string` | `'en-US'` | Language of the payment prompts. |
1742
+ | `opts.voice` | `string` | `'woman'` | Text-to-speech voice for the payment prompts. |
1743
+ | `opts.description` | `string` | none | Description of the payment. |
1744
+ | `opts.validCardTypes` | `string` | `'visa mastercard amex'` | Space-separated list of accepted card types. |
1745
+ | `opts.parameters` | `PaymentParameter[]` | none | Name-value pairs for the payment connector. |
1746
+ | `opts.prompts` | `PaymentPrompt[]` | none | Custom prompts for payment steps. |
1747
+ | `opts.aiResponse` | `string` | Text that references `${pay_result}` | Set as `ai_response` before the `pay` verb runs. |
1748
+
1749
+ The SDK sends `timeout`, `max_attempts`, `min_postal_code_length`, `security_code` and `postal_code` as strings, as the platform reads them: its SWML validator requires strings for `security_code` and `postal_code`, and the pay request reads all five as strings. The bundled SWML schema types some of them as integers and booleans, but the platform's own checks win. The SDK checks each input first: `timeout`, `maxAttempts` and `minPostalCodeLength` must be integers or numeric strings, and `securityCode` a boolean or `'true'` or `'false'`. A SWML variable reference such as `'${pay_timeout}'` is sent as written. The default `aiResponse` is `The payment status is ${pay_result}, do not mention anything else about collecting payment if successful.`
1750
+
1751
+ **Throws:** `Error` when `timeout`, `maxAttempts` or `minPostalCodeLength` isn't an integer, or `securityCode` isn't a boolean, or a SWML variable reference.
1752
+
1753
+ **Returns:** `this` for chaining.
1754
+
1755
+ **Example:**
1756
+
1757
+ ```typescript
1758
+ const result = new FunctionResult('Tell the caller you are starting the card payment.', true)
1759
+ .pay({
1760
+ paymentConnectorUrl: 'https://payments.example.com/connector',
1761
+ chargeAmount: '49.99',
1762
+ currency: 'usd',
1763
+ maxAttempts: 3,
1764
+ timeout: 10,
1765
+ });
1766
+ ```
1767
+
1768
+ ### createPaymentPrompt (static)
1769
+
1770
+ Create a `PaymentPrompt` object for the `prompts` option of `pay()`.
1771
+
1772
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1773
+ ```typescript
1774
+ static createPaymentPrompt(
1775
+ forSituation: string,
1776
+ actions: PaymentAction[],
1777
+ cardType?: string,
1778
+ errorType?: string
1779
+ ): PaymentPrompt
1780
+ ```
1781
+
1782
+ | Parameter | Type | Description |
1783
+ |----------------|-------------------|---------------------------------------------------|
1784
+ | `forSituation` | `string` | The payment step the prompt is for, such as `'payment-card-number'`, `'expiration-date'` or `'security-code'`. |
1785
+ | `actions` | `PaymentAction[]` | Actions to perform for this prompt. |
1786
+ | `cardType` | `string` | Space-separated card types the prompt applies to (for example `'visa'`). |
1787
+ | `errorType` | `string` | Space-separated error types the prompt applies to (for example `'invalid-card-number timeout'`). |
1788
+
1789
+ **Returns:** A `PaymentPrompt` object.
1790
+
1791
+ **Example:**
1792
+
1793
+ ```typescript
1794
+ const prompt = FunctionResult.createPaymentPrompt(
1795
+ 'payment-card-number',
1796
+ [FunctionResult.createPaymentAction('Say', 'Enter your card number.')],
1797
+ );
1798
+ ```
1799
+
1800
+ ### createPaymentAction (static)
1801
+
1802
+ Create a `PaymentAction` for a `PaymentPrompt`.
1803
+
1804
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1805
+ ```typescript
1806
+ static createPaymentAction(actionType: string, phrase: string): PaymentAction
1807
+ ```
1808
+
1809
+ | Parameter | Type | Description |
1810
+ |--------------|----------|------------------------------------------|
1811
+ | `actionType` | `string` | `'Say'` to speak the phrase, or `'Play'` to play an audio file. The SWML `pay` verb accepts these two values. |
1812
+ | `phrase` | `string` | The text to say, or for `'Play'` the URL of the audio file. |
1813
+
1814
+ **Returns:** A `PaymentAction` object.
1815
+
1816
+ **Example:**
1817
+
1818
+ ```typescript
1819
+ const action = FunctionResult.createPaymentAction(
1820
+ 'Say',
1821
+ 'Enter your credit card number, followed by the pound key.',
1822
+ );
1823
+ ```
1824
+
1825
+ ### createPaymentParameter (static)
1826
+
1827
+ Create a `PaymentParameter`, a name-value pair for the payment connector.
1828
+
1829
+ <!-- snippet: no-compile API signature reference, not runnable code -->
1830
+ ```typescript
1831
+ static createPaymentParameter(name: string, value: string): PaymentParameter
1832
+ ```
1833
+
1834
+ | Parameter | Type | Description |
1835
+ |-----------|----------|------------------------|
1836
+ | `name` | `string` | The parameter name. |
1837
+ | `value` | `string` | The parameter value. |
1838
+
1839
+ **Returns:** A `PaymentParameter` object.
1840
+
1841
+ **Example:**
1842
+
1843
+ ```typescript
1844
+ const param = FunctionResult.createPaymentParameter('merchant_id', 'MERCH-001');
1845
+ ```
1846
+
1847
+ ### Full payment example
1848
+
1849
+ This example sets custom prompts for three payment steps and passes a merchant ID to the connector:
1850
+
1851
+ ```typescript
1852
+ const prompts = [
1853
+ FunctionResult.createPaymentPrompt(
1854
+ 'payment-card-number',
1855
+ [FunctionResult.createPaymentAction('Say', 'Enter your card number.')],
1856
+ ),
1857
+ FunctionResult.createPaymentPrompt(
1858
+ 'expiration-date',
1859
+ [FunctionResult.createPaymentAction('Say', 'Enter the expiration date.')],
1860
+ ),
1861
+ FunctionResult.createPaymentPrompt(
1862
+ 'security-code',
1863
+ [FunctionResult.createPaymentAction('Say', 'Enter the security code on the back of your card.')],
1864
+ ),
1865
+ ];
1866
+
1867
+ const params = [
1868
+ FunctionResult.createPaymentParameter('merchant_id', 'MERCH-001'),
1869
+ ];
1870
+
1871
+ const result = new FunctionResult('Tell the caller you are starting the payment.', true)
1872
+ .pay({
1873
+ paymentConnectorUrl: 'https://payments.example.com/connector',
1874
+ chargeAmount: '99.95',
1875
+ currency: 'usd',
1876
+ maxAttempts: 3,
1877
+ timeout: 15,
1878
+ prompts,
1879
+ parameters: params,
1880
+ description: 'Annual subscription',
1881
+ });
1882
+ ```
1883
+
1884
+ ## Fluent Chaining
1885
+
1886
+ Every mutating method on `FunctionResult` returns `this`, so you can build a result with several actions in one expression. This tool completes an order, stores data, texts a confirmation and switches the available tools:
1887
+
1888
+ ```typescript
1889
+ agent.defineTool({
1890
+ name: 'complete_order',
1891
+ description: 'Complete an order and send confirmation',
1892
+ parameters: {
1893
+ order_id: { type: 'string', description: 'The order ID' },
1894
+ },
1895
+ handler: (args) => {
1896
+ const orderId = args.order_id as string;
1897
+
1898
+ return new FunctionResult(`Order ${orderId} is complete.`)
1899
+ .setPostProcess(true)
1900
+ // Store data for other tools
1901
+ .updateGlobalData({ last_order: orderId, order_status: 'complete' })
1902
+ // Set metadata for this function
1903
+ .setMetadata({ order_id: orderId })
1904
+ // Send an SMS confirmation
1905
+ .sendSms({
1906
+ toNumber: '+15551234567',
1907
+ fromNumber: '+15559876543',
1908
+ body: `Your order ${orderId} has been confirmed.`,
1909
+ })
1910
+ // Speak a confirmation
1911
+ .say(`Your order ${orderId} is confirmed.`)
1912
+ // Send an event to the connected client
1913
+ .swmlUserEvent({ type: 'order_complete', order_id: orderId })
1914
+ // Disable the order tool, enable the feedback tool
1915
+ .toggleFunctions([
1916
+ { function: 'complete_order', active: false },
1917
+ { function: 'submit_feedback', active: true },
1918
+ ]);
1919
+ },
1920
+ });
1921
+ ```
1922
+
1923
+ For `order_id` `ORD-789`, the handler returns this result. The `action` array keeps the order of the calls:
1924
+
1925
+ ```json
1926
+ {
1927
+ "response": "Order ORD-789 is complete.",
1928
+ "action": [
1929
+ { "set_global_data": { "last_order": "ORD-789", "order_status": "complete" } },
1930
+ { "set_meta_data": { "order_id": "ORD-789" } },
1931
+ { "SWML": { "version": "1.0.0", "sections": { "main": [{ "send_sms": { "to_number": "+15551234567", "from_number": "+15559876543", "body": "Your order ORD-789 has been confirmed." } }] } } },
1932
+ { "say": "Your order ORD-789 is confirmed." },
1933
+ { "SWML": { "sections": { "main": [{ "user_event": { "event": { "type": "order_complete", "order_id": "ORD-789" } } }] }, "version": "1.0.0" } },
1934
+ { "toggle_functions": [{ "function": "complete_order", "active": false }, { "function": "submit_feedback", "active": true }] }
1935
+ ],
1936
+ "post_process": true
1937
+ }
1938
+ ```