@signalwire/sdk 2.0.0 → 2.0.2

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 (612) hide show
  1. package/dist/AgentBase.d.ts +1045 -0
  2. package/dist/AgentBase.js +2375 -0
  3. package/dist/AgentBase.js.map +1 -0
  4. package/dist/AgentServer.d.ts +146 -0
  5. package/dist/AgentServer.js +388 -0
  6. package/dist/AgentServer.js.map +1 -0
  7. package/dist/AuthHandler.d.ts +127 -0
  8. package/dist/AuthHandler.js +212 -0
  9. package/dist/AuthHandler.js.map +1 -0
  10. package/dist/ConfigLoader.d.ts +170 -0
  11. package/dist/ConfigLoader.js +393 -0
  12. package/dist/ConfigLoader.js.map +1 -0
  13. package/dist/ContextBuilder.d.ts +652 -0
  14. package/dist/ContextBuilder.js +1115 -0
  15. package/dist/ContextBuilder.js.map +1 -0
  16. package/dist/DataMap.d.ts +271 -0
  17. package/dist/DataMap.js +430 -0
  18. package/dist/DataMap.js.map +1 -0
  19. package/dist/FunctionResult.d.ts +481 -0
  20. package/dist/FunctionResult.js +775 -0
  21. package/dist/FunctionResult.js.map +1 -0
  22. package/dist/Logger.d.ts +113 -0
  23. package/dist/Logger.js +320 -0
  24. package/dist/Logger.js.map +1 -0
  25. package/dist/PomBuilder.d.ts +208 -0
  26. package/dist/PomBuilder.js +409 -0
  27. package/dist/PomBuilder.js.map +1 -0
  28. package/dist/PromptManager.d.ts +85 -0
  29. package/dist/PromptManager.js +108 -0
  30. package/dist/PromptManager.js.map +1 -0
  31. package/dist/SWMLHandler.d.ts +159 -0
  32. package/dist/SWMLHandler.js +229 -0
  33. package/dist/SWMLHandler.js.map +1 -0
  34. package/dist/SWMLService.d.ts +326 -0
  35. package/dist/SWMLService.js +610 -0
  36. package/dist/SWMLService.js.map +1 -0
  37. package/dist/SchemaUtils.d.ts +108 -0
  38. package/dist/SchemaUtils.js +317 -0
  39. package/dist/SchemaUtils.js.map +1 -0
  40. package/dist/SecurityUtils.d.ts +60 -0
  41. package/{src/SecurityUtils.ts → dist/SecurityUtils.js} +82 -83
  42. package/dist/SecurityUtils.js.map +1 -0
  43. package/dist/ServerlessAdapter.d.ts +119 -0
  44. package/dist/ServerlessAdapter.js +188 -0
  45. package/dist/ServerlessAdapter.js.map +1 -0
  46. package/dist/SessionManager.d.ts +142 -0
  47. package/dist/SessionManager.js +260 -0
  48. package/dist/SessionManager.js.map +1 -0
  49. package/dist/SslConfig.d.ts +77 -0
  50. package/dist/SslConfig.js +100 -0
  51. package/dist/SslConfig.js.map +1 -0
  52. package/dist/SwaigFunction.d.ts +159 -0
  53. package/dist/SwaigFunction.js +209 -0
  54. package/dist/SwaigFunction.js.map +1 -0
  55. package/dist/SwmlBuilder.d.ts +165 -0
  56. package/dist/SwmlBuilder.js +247 -0
  57. package/dist/SwmlBuilder.js.map +1 -0
  58. package/dist/SwmlVerbMethods.generated.d.ts +254 -0
  59. package/dist/SwmlVerbMethods.generated.js +9 -0
  60. package/dist/SwmlVerbMethods.generated.js.map +1 -0
  61. package/dist/TypeInference.d.ts +71 -0
  62. package/dist/TypeInference.js +164 -0
  63. package/dist/TypeInference.js.map +1 -0
  64. package/dist/WebService.d.ts +148 -0
  65. package/dist/WebService.js +532 -0
  66. package/dist/WebService.js.map +1 -0
  67. package/dist/cli/agent-loader.d.ts +22 -0
  68. package/dist/cli/agent-loader.js +144 -0
  69. package/dist/cli/agent-loader.js.map +1 -0
  70. package/dist/cli/mock-data.d.ts +37 -0
  71. package/dist/cli/mock-data.js +80 -0
  72. package/dist/cli/mock-data.js.map +1 -0
  73. package/dist/cli/swaig-test.d.ts +32 -0
  74. package/dist/cli/swaig-test.js +418 -0
  75. package/dist/cli/swaig-test.js.map +1 -0
  76. package/dist/generateVerbTypes.d.ts +11 -0
  77. package/dist/generateVerbTypes.js +265 -0
  78. package/dist/generateVerbTypes.js.map +1 -0
  79. package/dist/index.d.ts +146 -0
  80. package/dist/index.js +152 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/livewire/index.d.ts +653 -0
  83. package/dist/livewire/index.js +992 -0
  84. package/dist/livewire/index.js.map +1 -0
  85. package/dist/prefabs/ConciergeAgent.d.ts +89 -0
  86. package/dist/prefabs/ConciergeAgent.js +245 -0
  87. package/dist/prefabs/ConciergeAgent.js.map +1 -0
  88. package/dist/prefabs/FAQBotAgent.d.ts +113 -0
  89. package/dist/prefabs/FAQBotAgent.js +329 -0
  90. package/dist/prefabs/FAQBotAgent.js.map +1 -0
  91. package/dist/prefabs/InfoGathererAgent.d.ts +126 -0
  92. package/dist/prefabs/InfoGathererAgent.js +287 -0
  93. package/dist/prefabs/InfoGathererAgent.js.map +1 -0
  94. package/dist/prefabs/ReceptionistAgent.d.ts +104 -0
  95. package/dist/prefabs/ReceptionistAgent.js +303 -0
  96. package/dist/prefabs/ReceptionistAgent.js.map +1 -0
  97. package/dist/prefabs/SurveyAgent.d.ts +148 -0
  98. package/dist/prefabs/SurveyAgent.js +540 -0
  99. package/dist/prefabs/SurveyAgent.js.map +1 -0
  100. package/{src/prefabs/index.ts → dist/prefabs/index.d.ts} +1 -15
  101. package/dist/prefabs/index.js +14 -0
  102. package/dist/prefabs/index.js.map +1 -0
  103. package/dist/relay/Action.d.ts +258 -0
  104. package/dist/relay/Action.js +402 -0
  105. package/dist/relay/Action.js.map +1 -0
  106. package/dist/relay/Call.d.ts +697 -0
  107. package/dist/relay/Call.js +1062 -0
  108. package/dist/relay/Call.js.map +1 -0
  109. package/dist/relay/Deferred.d.ts +44 -0
  110. package/dist/relay/Deferred.js +69 -0
  111. package/dist/relay/Deferred.js.map +1 -0
  112. package/dist/relay/Message.d.ts +103 -0
  113. package/dist/relay/Message.js +169 -0
  114. package/dist/relay/Message.js.map +1 -0
  115. package/dist/relay/RelayClient.d.ts +302 -0
  116. package/dist/relay/RelayClient.js +1019 -0
  117. package/dist/relay/RelayClient.js.map +1 -0
  118. package/dist/relay/RelayError.d.ts +15 -0
  119. package/dist/relay/RelayError.js +20 -0
  120. package/dist/relay/RelayError.js.map +1 -0
  121. package/dist/relay/RelayEvent.d.ts +254 -0
  122. package/dist/relay/RelayEvent.js +509 -0
  123. package/dist/relay/RelayEvent.js.map +1 -0
  124. package/dist/relay/constants.d.ts +90 -0
  125. package/{src/relay/constants.ts → dist/relay/constants.js} +11 -29
  126. package/dist/relay/constants.js.map +1 -0
  127. package/dist/relay/index.d.ts +16 -0
  128. package/dist/relay/index.js +18 -0
  129. package/dist/relay/index.js.map +1 -0
  130. package/dist/relay/types.d.ts +142 -0
  131. package/dist/relay/types.js +5 -0
  132. package/dist/relay/types.js.map +1 -0
  133. package/dist/rest/HttpClient.d.ts +80 -0
  134. package/dist/rest/HttpClient.js +148 -0
  135. package/dist/rest/HttpClient.js.map +1 -0
  136. package/dist/rest/RestError.d.ts +30 -0
  137. package/dist/rest/RestError.js +39 -0
  138. package/dist/rest/RestError.js.map +1 -0
  139. package/dist/rest/base/BaseResource.d.ts +24 -0
  140. package/dist/rest/base/BaseResource.js +29 -0
  141. package/dist/rest/base/BaseResource.js.map +1 -0
  142. package/dist/rest/base/CrudResource.d.ts +68 -0
  143. package/dist/rest/base/CrudResource.js +82 -0
  144. package/dist/rest/base/CrudResource.js.map +1 -0
  145. package/dist/rest/base/CrudWithAddresses.d.ts +22 -0
  146. package/dist/rest/base/CrudWithAddresses.js +25 -0
  147. package/dist/rest/base/CrudWithAddresses.js.map +1 -0
  148. package/{src/rest/index.ts → dist/rest/index.d.ts} +53 -122
  149. package/dist/rest/index.js +195 -0
  150. package/dist/rest/index.js.map +1 -0
  151. package/dist/rest/namespaces/addresses.d.ts +46 -0
  152. package/dist/rest/namespaces/addresses.js +55 -0
  153. package/dist/rest/namespaces/addresses.js.map +1 -0
  154. package/dist/rest/namespaces/calling.d.ts +382 -0
  155. package/dist/rest/namespaces/calling.js +478 -0
  156. package/dist/rest/namespaces/calling.js.map +1 -0
  157. package/dist/rest/namespaces/chat.d.ts +22 -0
  158. package/dist/rest/namespaces/chat.js +26 -0
  159. package/dist/rest/namespaces/chat.js.map +1 -0
  160. package/dist/rest/namespaces/compat.d.ts +585 -0
  161. package/dist/rest/namespaces/compat.js +735 -0
  162. package/dist/rest/namespaces/compat.js.map +1 -0
  163. package/dist/rest/namespaces/datasphere.d.ts +66 -0
  164. package/dist/rest/namespaces/datasphere.js +77 -0
  165. package/dist/rest/namespaces/datasphere.js.map +1 -0
  166. package/dist/rest/namespaces/fabric.d.ts +282 -0
  167. package/dist/rest/namespaces/fabric.js +373 -0
  168. package/dist/rest/namespaces/fabric.js.map +1 -0
  169. package/dist/rest/namespaces/imported-numbers.d.ts +22 -0
  170. package/dist/rest/namespaces/imported-numbers.js +26 -0
  171. package/dist/rest/namespaces/imported-numbers.js.map +1 -0
  172. package/dist/rest/namespaces/logs.d.ts +105 -0
  173. package/dist/rest/namespaces/logs.js +133 -0
  174. package/dist/rest/namespaces/logs.js.map +1 -0
  175. package/dist/rest/namespaces/lookup.d.ts +29 -0
  176. package/dist/rest/namespaces/lookup.js +32 -0
  177. package/dist/rest/namespaces/lookup.js.map +1 -0
  178. package/dist/rest/namespaces/mfa.d.ts +46 -0
  179. package/dist/rest/namespaces/mfa.js +54 -0
  180. package/dist/rest/namespaces/mfa.js.map +1 -0
  181. package/dist/rest/namespaces/number-groups.d.ts +49 -0
  182. package/dist/rest/namespaces/number-groups.js +58 -0
  183. package/dist/rest/namespaces/number-groups.js.map +1 -0
  184. package/dist/rest/namespaces/phone-numbers.d.ts +60 -0
  185. package/dist/rest/namespaces/phone-numbers.js +67 -0
  186. package/dist/rest/namespaces/phone-numbers.js.map +1 -0
  187. package/dist/rest/namespaces/project.d.ts +46 -0
  188. package/dist/rest/namespaces/project.js +56 -0
  189. package/dist/rest/namespaces/project.js.map +1 -0
  190. package/dist/rest/namespaces/pubsub.d.ts +22 -0
  191. package/dist/rest/namespaces/pubsub.js +26 -0
  192. package/dist/rest/namespaces/pubsub.js.map +1 -0
  193. package/dist/rest/namespaces/queues.d.ts +42 -0
  194. package/dist/rest/namespaces/queues.js +49 -0
  195. package/dist/rest/namespaces/queues.js.map +1 -0
  196. package/dist/rest/namespaces/recordings.d.ts +38 -0
  197. package/dist/rest/namespaces/recordings.js +45 -0
  198. package/dist/rest/namespaces/recordings.js.map +1 -0
  199. package/dist/rest/namespaces/registry.d.ts +141 -0
  200. package/dist/rest/namespaces/registry.js +178 -0
  201. package/dist/rest/namespaces/registry.js.map +1 -0
  202. package/dist/rest/namespaces/short-codes.d.ts +39 -0
  203. package/dist/rest/namespaces/short-codes.js +46 -0
  204. package/dist/rest/namespaces/short-codes.js.map +1 -0
  205. package/dist/rest/namespaces/sip-profile.d.ts +28 -0
  206. package/dist/rest/namespaces/sip-profile.js +34 -0
  207. package/dist/rest/namespaces/sip-profile.js.map +1 -0
  208. package/dist/rest/namespaces/verified-callers.d.ts +33 -0
  209. package/dist/rest/namespaces/verified-callers.js +39 -0
  210. package/dist/rest/namespaces/verified-callers.js.map +1 -0
  211. package/dist/rest/namespaces/video.d.ts +235 -0
  212. package/dist/rest/namespaces/video.js +297 -0
  213. package/dist/rest/namespaces/video.js.map +1 -0
  214. package/dist/rest/pagination.d.ts +39 -0
  215. package/dist/rest/pagination.js +78 -0
  216. package/dist/rest/pagination.js.map +1 -0
  217. package/dist/rest/types.d.ts +54 -0
  218. package/dist/rest/types.js +5 -0
  219. package/dist/rest/types.js.map +1 -0
  220. package/dist/skills/SkillBase.d.ts +404 -0
  221. package/dist/skills/SkillBase.js +471 -0
  222. package/dist/skills/SkillBase.js.map +1 -0
  223. package/dist/skills/SkillManager.d.ts +195 -0
  224. package/dist/skills/SkillManager.js +378 -0
  225. package/dist/skills/SkillManager.js.map +1 -0
  226. package/dist/skills/SkillRegistry.d.ts +176 -0
  227. package/dist/skills/SkillRegistry.js +310 -0
  228. package/dist/skills/SkillRegistry.js.map +1 -0
  229. package/dist/skills/builtin/api_ninjas_trivia.d.ts +47 -0
  230. package/dist/skills/builtin/api_ninjas_trivia.js +211 -0
  231. package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -0
  232. package/dist/skills/builtin/ask_claude.d.ts +37 -0
  233. package/dist/skills/builtin/ask_claude.js +162 -0
  234. package/dist/skills/builtin/ask_claude.js.map +1 -0
  235. package/dist/skills/builtin/claude_skills.d.ts +75 -0
  236. package/dist/skills/builtin/claude_skills.js +753 -0
  237. package/dist/skills/builtin/claude_skills.js.map +1 -0
  238. package/dist/skills/builtin/custom_skills.d.ts +79 -0
  239. package/dist/skills/builtin/custom_skills.js +227 -0
  240. package/dist/skills/builtin/custom_skills.js.map +1 -0
  241. package/dist/skills/builtin/datasphere.d.ts +73 -0
  242. package/dist/skills/builtin/datasphere.js +350 -0
  243. package/dist/skills/builtin/datasphere.js.map +1 -0
  244. package/dist/skills/builtin/datasphere_serverless.d.ts +89 -0
  245. package/dist/skills/builtin/datasphere_serverless.js +291 -0
  246. package/dist/skills/builtin/datasphere_serverless.js.map +1 -0
  247. package/dist/skills/builtin/datetime.d.ts +40 -0
  248. package/dist/skills/builtin/datetime.js +118 -0
  249. package/dist/skills/builtin/datetime.js.map +1 -0
  250. package/dist/skills/builtin/google_maps.d.ts +48 -0
  251. package/dist/skills/builtin/google_maps.js +470 -0
  252. package/dist/skills/builtin/google_maps.js.map +1 -0
  253. package/dist/skills/builtin/index.d.ts +31 -0
  254. package/{src/skills/builtin/index.ts → dist/skills/builtin/index.js} +30 -36
  255. package/dist/skills/builtin/index.js.map +1 -0
  256. package/dist/skills/builtin/info_gatherer.d.ts +115 -0
  257. package/dist/skills/builtin/info_gatherer.js +328 -0
  258. package/dist/skills/builtin/info_gatherer.js.map +1 -0
  259. package/dist/skills/builtin/joke.d.ts +41 -0
  260. package/dist/skills/builtin/joke.js +156 -0
  261. package/dist/skills/builtin/joke.js.map +1 -0
  262. package/dist/skills/builtin/math.d.ts +39 -0
  263. package/dist/skills/builtin/math.js +119 -0
  264. package/dist/skills/builtin/math.js.map +1 -0
  265. package/dist/skills/builtin/mcp_gateway.d.ts +82 -0
  266. package/dist/skills/builtin/mcp_gateway.js +574 -0
  267. package/dist/skills/builtin/mcp_gateway.js.map +1 -0
  268. package/dist/skills/builtin/native_vector_search.d.ts +128 -0
  269. package/dist/skills/builtin/native_vector_search.js +752 -0
  270. package/dist/skills/builtin/native_vector_search.js.map +1 -0
  271. package/dist/skills/builtin/play_background_file.d.ts +59 -0
  272. package/dist/skills/builtin/play_background_file.js +274 -0
  273. package/dist/skills/builtin/play_background_file.js.map +1 -0
  274. package/dist/skills/builtin/spider.d.ts +91 -0
  275. package/dist/skills/builtin/spider.js +758 -0
  276. package/dist/skills/builtin/spider.js.map +1 -0
  277. package/dist/skills/builtin/swml_transfer.d.ts +66 -0
  278. package/dist/skills/builtin/swml_transfer.js +475 -0
  279. package/dist/skills/builtin/swml_transfer.js.map +1 -0
  280. package/dist/skills/builtin/weather_api.d.ts +59 -0
  281. package/dist/skills/builtin/weather_api.js +196 -0
  282. package/dist/skills/builtin/weather_api.js.map +1 -0
  283. package/dist/skills/builtin/web_search.d.ts +160 -0
  284. package/dist/skills/builtin/web_search.js +894 -0
  285. package/dist/skills/builtin/web_search.js.map +1 -0
  286. package/dist/skills/builtin/wikipedia_search.d.ts +77 -0
  287. package/dist/skills/builtin/wikipedia_search.js +241 -0
  288. package/dist/skills/builtin/wikipedia_search.js.map +1 -0
  289. package/{src/skills/index.ts → dist/skills/index.d.ts} +0 -1
  290. package/dist/skills/index.js +10 -0
  291. package/dist/skills/index.js.map +1 -0
  292. package/dist/types.d.ts +118 -0
  293. package/dist/types.js +5 -0
  294. package/dist/types.js.map +1 -0
  295. package/package.json +7 -1
  296. package/.github/workflows/publish.yml +0 -27
  297. package/.github/workflows/test.yml +0 -17
  298. package/CLAUDE.md +0 -112
  299. package/docs/MIGRATION-2.0.md +0 -81
  300. package/docs/agent-guide.md +0 -869
  301. package/docs/agent_guide.md +0 -1026
  302. package/docs/api-reference.md +0 -2420
  303. package/docs/api_reference.md +0 -1301
  304. package/docs/architecture.md +0 -843
  305. package/docs/cli-guide.md +0 -579
  306. package/docs/cli_guide.md +0 -448
  307. package/docs/cloud_functions_guide.md +0 -474
  308. package/docs/configuration.md +0 -422
  309. package/docs/contexts-guide.md +0 -787
  310. package/docs/contexts_guide.md +0 -511
  311. package/docs/datamap-guide.md +0 -1141
  312. package/docs/datamap_guide.md +0 -595
  313. package/docs/llm_parameters.md +0 -239
  314. package/docs/mcp_gateway_reference.md +0 -648
  315. package/docs/mcp_integration.md +0 -108
  316. package/docs/prefabs-guide.md +0 -800
  317. package/docs/sdk_features.md +0 -477
  318. package/docs/security.md +0 -436
  319. package/docs/serverless-guide.md +0 -513
  320. package/docs/skills-guide.md +0 -857
  321. package/docs/skills-system.md +0 -301
  322. package/docs/skills_parameter_schema.md +0 -392
  323. package/docs/skills_system.md +0 -467
  324. package/docs/swaig-reference.md +0 -1627
  325. package/docs/swaig_reference.md +0 -910
  326. package/docs/swml_service_guide.md +0 -600
  327. package/docs/third_party_skills.md +0 -533
  328. package/docs/web_service.md +0 -677
  329. package/examples/README.md +0 -131
  330. package/examples/advanced-datamap.ts +0 -100
  331. package/examples/advanced-dynamic-config.ts +0 -70
  332. package/examples/auto-vivified.ts +0 -94
  333. package/examples/call-flow.ts +0 -63
  334. package/examples/comprehensive-dynamic.ts +0 -125
  335. package/examples/contexts-steps.ts +0 -65
  336. package/examples/custom-path.ts +0 -45
  337. package/examples/datamap-tools.ts +0 -55
  338. package/examples/datasphere-multi-instance.ts +0 -63
  339. package/examples/datasphere-serverless-env.ts +0 -68
  340. package/examples/datasphere-webhook-env.ts +0 -66
  341. package/examples/datasphere.ts +0 -37
  342. package/examples/declarative.ts +0 -100
  343. package/examples/dynamic-config.ts +0 -54
  344. package/examples/dynamic-info-gatherer.ts +0 -69
  345. package/examples/dynamic-swml-service.ts +0 -67
  346. package/examples/gather-info.ts +0 -71
  347. package/examples/gather-per-question-functions-demo.ts +0 -140
  348. package/examples/joke-agent.ts +0 -34
  349. package/examples/kubernetes-agent.ts +0 -45
  350. package/examples/llm-params.ts +0 -69
  351. package/examples/mcp-agent.ts +0 -84
  352. package/examples/mcp-gateway.ts +0 -35
  353. package/examples/multi-agent.ts +0 -73
  354. package/examples/multi-endpoint.ts +0 -79
  355. package/examples/pom-prompt.ts +0 -71
  356. package/examples/prefab-concierge.ts +0 -47
  357. package/examples/prefab-faq.ts +0 -54
  358. package/examples/prefab-info-gatherer.ts +0 -33
  359. package/examples/prefab-receptionist.ts +0 -36
  360. package/examples/prefab-survey.ts +0 -68
  361. package/examples/record-call.ts +0 -67
  362. package/examples/relay-demo.ts +0 -33
  363. package/examples/room-and-sip.ts +0 -94
  364. package/examples/serverless-lambda.ts +0 -35
  365. package/examples/session-state.ts +0 -83
  366. package/examples/simple-agent.ts +0 -36
  367. package/examples/simple-static.ts +0 -29
  368. package/examples/skills-demo.ts +0 -38
  369. package/examples/step-function-inheritance-demo.ts +0 -124
  370. package/examples/swaig-features.ts +0 -187
  371. package/examples/swml-service-routing.ts +0 -66
  372. package/examples/swml-service.ts +0 -38
  373. package/examples/tap.ts +0 -68
  374. package/examples/verb-methods.ts +0 -45
  375. package/examples/web-search-multi-instance.ts +0 -72
  376. package/examples/web-search.ts +0 -38
  377. package/examples/wikipedia.ts +0 -36
  378. package/livewire/README.md +0 -140
  379. package/livewire/docs/migration-guide.md +0 -228
  380. package/livewire/examples/livewire-basic-agent.ts +0 -74
  381. package/livewire/examples/livewire-handoff.ts +0 -197
  382. package/livewire/examples/livewire-multi-tool.ts +0 -117
  383. package/relay/README.md +0 -70
  384. package/relay/RELAY_IMPLEMENTATION_GUIDE.md +0 -1257
  385. package/relay/docs/call-methods.md +0 -474
  386. package/relay/docs/client-reference.md +0 -142
  387. package/relay/docs/events.md +0 -134
  388. package/relay/docs/getting-started.md +0 -134
  389. package/relay/docs/guide.md +0 -306
  390. package/relay/docs/messaging.md +0 -182
  391. package/relay/examples/relay-inbound.ts +0 -66
  392. package/relay/examples/relay-messaging.ts +0 -71
  393. package/relay/examples/relay-outbound.ts +0 -76
  394. package/rest/README.md +0 -95
  395. package/rest/docs/calling.md +0 -273
  396. package/rest/docs/client-reference.md +0 -107
  397. package/rest/docs/compat.md +0 -204
  398. package/rest/docs/fabric.md +0 -183
  399. package/rest/docs/getting-started.md +0 -110
  400. package/rest/docs/guide.md +0 -351
  401. package/rest/docs/namespaces.md +0 -285
  402. package/rest/examples/rest-10dlc-registration.ts +0 -161
  403. package/rest/examples/rest-calling-ivr-and-ai.ts +0 -102
  404. package/rest/examples/rest-calling-play-and-record.ts +0 -91
  405. package/rest/examples/rest-client.ts +0 -65
  406. package/rest/examples/rest-compat-laml.ts +0 -210
  407. package/rest/examples/rest-datasphere-search.ts +0 -82
  408. package/rest/examples/rest-fabric-conferences-and-routing.ts +0 -144
  409. package/rest/examples/rest-fabric-subscribers-and-sip.ts +0 -108
  410. package/rest/examples/rest-fabric-swml-and-callflows.ts +0 -99
  411. package/rest/examples/rest-manage-resources.ts +0 -65
  412. package/rest/examples/rest-phone-number-management.ts +0 -197
  413. package/rest/examples/rest-queues-mfa-and-recordings.ts +0 -143
  414. package/rest/examples/rest-video-rooms.ts +0 -186
  415. package/src/AgentBase.ts +0 -2489
  416. package/src/AgentServer.ts +0 -415
  417. package/src/AuthHandler.ts +0 -256
  418. package/src/ConfigLoader.ts +0 -447
  419. package/src/ContextBuilder.ts +0 -1150
  420. package/src/DataMap.ts +0 -449
  421. package/src/FunctionResult.ts +0 -866
  422. package/src/Logger.ts +0 -337
  423. package/src/PomBuilder.ts +0 -439
  424. package/src/PromptManager.ts +0 -133
  425. package/src/SWMLHandler.ts +0 -298
  426. package/src/SWMLService.ts +0 -717
  427. package/src/SchemaUtils.ts +0 -361
  428. package/src/ServerlessAdapter.ts +0 -221
  429. package/src/SessionManager.ts +0 -311
  430. package/src/SslConfig.ts +0 -118
  431. package/src/SwaigFunction.ts +0 -276
  432. package/src/SwmlBuilder.ts +0 -258
  433. package/src/SwmlVerbMethods.generated.ts +0 -234
  434. package/src/TypeInference.ts +0 -181
  435. package/src/WebService.ts +0 -619
  436. package/src/cli/agent-loader.ts +0 -166
  437. package/src/cli/mock-data.ts +0 -111
  438. package/src/cli/swaig-test.ts +0 -452
  439. package/src/generateVerbTypes.ts +0 -322
  440. package/src/index.ts +0 -167
  441. package/src/livewire/index.ts +0 -950
  442. package/src/prefabs/ConciergeAgent.ts +0 -287
  443. package/src/prefabs/FAQBotAgent.ts +0 -384
  444. package/src/prefabs/InfoGathererAgent.ts +0 -339
  445. package/src/prefabs/ReceptionistAgent.ts +0 -366
  446. package/src/prefabs/SurveyAgent.ts +0 -646
  447. package/src/relay/Action.ts +0 -314
  448. package/src/relay/Call.ts +0 -854
  449. package/src/relay/Deferred.ts +0 -71
  450. package/src/relay/Message.ts +0 -148
  451. package/src/relay/RelayClient.ts +0 -1036
  452. package/src/relay/RelayError.ts +0 -14
  453. package/src/relay/RelayEvent.ts +0 -892
  454. package/src/relay/index.ts +0 -123
  455. package/src/relay/types.ts +0 -149
  456. package/src/rest/HttpClient.ts +0 -103
  457. package/src/rest/RestError.ts +0 -31
  458. package/src/rest/base/BaseResource.ts +0 -19
  459. package/src/rest/base/CrudResource.ts +0 -51
  460. package/src/rest/base/CrudWithAddresses.ts +0 -26
  461. package/src/rest/namespaces/addresses.ts +0 -32
  462. package/src/rest/namespaces/calling.ts +0 -187
  463. package/src/rest/namespaces/chat.ts +0 -20
  464. package/src/rest/namespaces/compat.ts +0 -352
  465. package/src/rest/namespaces/datasphere.ts +0 -45
  466. package/src/rest/namespaces/fabric.ts +0 -222
  467. package/src/rest/namespaces/imported-numbers.ts +0 -20
  468. package/src/rest/namespaces/logs.ts +0 -84
  469. package/src/rest/namespaces/lookup.ts +0 -21
  470. package/src/rest/namespaces/mfa.ts +0 -30
  471. package/src/rest/namespaces/number-groups.ts +0 -38
  472. package/src/rest/namespaces/phone-numbers.ts +0 -44
  473. package/src/rest/namespaces/project.ts +0 -36
  474. package/src/rest/namespaces/pubsub.ts +0 -20
  475. package/src/rest/namespaces/queues.ts +0 -33
  476. package/src/rest/namespaces/recordings.ts +0 -28
  477. package/src/rest/namespaces/registry.ts +0 -101
  478. package/src/rest/namespaces/short-codes.ts +0 -28
  479. package/src/rest/namespaces/sip-profile.ts +0 -25
  480. package/src/rest/namespaces/verified-callers.ts +0 -27
  481. package/src/rest/namespaces/video.ts +0 -165
  482. package/src/rest/pagination.ts +0 -84
  483. package/src/rest/types.ts +0 -61
  484. package/src/skills/SkillBase.ts +0 -547
  485. package/src/skills/SkillManager.ts +0 -415
  486. package/src/skills/SkillRegistry.ts +0 -367
  487. package/src/skills/builtin/api_ninjas_trivia.ts +0 -280
  488. package/src/skills/builtin/ask_claude.ts +0 -241
  489. package/src/skills/builtin/claude_skills.ts +0 -978
  490. package/src/skills/builtin/custom_skills.ts +0 -312
  491. package/src/skills/builtin/datasphere.ts +0 -438
  492. package/src/skills/builtin/datasphere_serverless.ts +0 -339
  493. package/src/skills/builtin/datetime.ts +0 -130
  494. package/src/skills/builtin/google_maps.ts +0 -651
  495. package/src/skills/builtin/info_gatherer.ts +0 -405
  496. package/src/skills/builtin/joke.ts +0 -191
  497. package/src/skills/builtin/math.ts +0 -142
  498. package/src/skills/builtin/mcp_gateway.ts +0 -677
  499. package/src/skills/builtin/native_vector_search.ts +0 -901
  500. package/src/skills/builtin/play_background_file.ts +0 -358
  501. package/src/skills/builtin/spider.ts +0 -869
  502. package/src/skills/builtin/swml_transfer.ts +0 -635
  503. package/src/skills/builtin/weather_api.ts +0 -248
  504. package/src/skills/builtin/web_search.ts +0 -1074
  505. package/src/skills/builtin/wikipedia_search.ts +0 -299
  506. package/src/types.ts +0 -132
  507. package/tests/AgentBase.test.ts +0 -1093
  508. package/tests/AgentServer.test.ts +0 -126
  509. package/tests/AuthHandler.test.ts +0 -133
  510. package/tests/ConfigLoader.test.ts +0 -151
  511. package/tests/ContextBuilder.test.ts +0 -108
  512. package/tests/DataMap.test.ts +0 -367
  513. package/tests/EphemeralSkillCopy.test.ts +0 -107
  514. package/tests/FunctionResult.test.ts +0 -298
  515. package/tests/GracefulShutdown.test.ts +0 -46
  516. package/tests/Logger.test.ts +0 -420
  517. package/tests/PomBuilder.test.ts +0 -228
  518. package/tests/ProxyDetection.test.ts +0 -228
  519. package/tests/SWMLService.test.ts +0 -320
  520. package/tests/SWMLVerbHandler.test.ts +0 -523
  521. package/tests/SchemaUtils.test.ts +0 -106
  522. package/tests/SchemaUtils.verb.test.ts +0 -206
  523. package/tests/SecurityUtils.test.ts +0 -192
  524. package/tests/ServerlessAdapter.test.ts +0 -222
  525. package/tests/SessionManager.test.ts +0 -257
  526. package/tests/SkillBaseFeatures.test.ts +0 -130
  527. package/tests/SkillMultiInstance.test.ts +0 -102
  528. package/tests/SkillParameterSchemas.test.ts +0 -134
  529. package/tests/SkillRegistrySchema.test.ts +0 -84
  530. package/tests/SslConfig.test.ts +0 -97
  531. package/tests/SwmlBuilder.test.ts +0 -400
  532. package/tests/TypeInference.test.ts +0 -165
  533. package/tests/VerbHandlerRegistry.test.ts +0 -128
  534. package/tests/cli/mock-data.test.ts +0 -113
  535. package/tests/cli/swaig-test.test.ts +0 -108
  536. package/tests/examples.test.ts +0 -194
  537. package/tests/fixtures/scrape-parity/README.md +0 -53
  538. package/tests/fixtures/scrape-parity/expected/01_simple_article.json +0 -5
  539. package/tests/fixtures/scrape-parity/expected/02_class_based_noise.json +0 -5
  540. package/tests/fixtures/scrape-parity/expected/03_nested_containers.json +0 -5
  541. package/tests/fixtures/scrape-parity/expected/04_bare_body.json +0 -5
  542. package/tests/fixtures/scrape-parity/expected/05_malformed.json +0 -5
  543. package/tests/fixtures/scrape-parity/expected/06_multi_class.json +0 -5
  544. package/tests/fixtures/scrape-parity/expected/07_anchor_pattern.json +0 -5
  545. package/tests/fixtures/scrape-parity/expected/08_inline_script.json +0 -5
  546. package/tests/fixtures/scrape-parity/expected/09_whitespace_nbsp.json +0 -5
  547. package/tests/fixtures/scrape-parity/expected/10_entity_unicode.json +0 -5
  548. package/tests/fixtures/scrape-parity/expected/11_cdata_comments.json +0 -5
  549. package/tests/fixtures/scrape-parity/expected/12_deep_nested_removals.json +0 -5
  550. package/tests/fixtures/scrape-parity/html/01_simple_article.html +0 -18
  551. package/tests/fixtures/scrape-parity/html/02_class_based_noise.html +0 -18
  552. package/tests/fixtures/scrape-parity/html/03_nested_containers.html +0 -13
  553. package/tests/fixtures/scrape-parity/html/04_bare_body.html +0 -9
  554. package/tests/fixtures/scrape-parity/html/05_malformed.html +0 -11
  555. package/tests/fixtures/scrape-parity/html/06_multi_class.html +0 -18
  556. package/tests/fixtures/scrape-parity/html/07_anchor_pattern.html +0 -12
  557. package/tests/fixtures/scrape-parity/html/08_inline_script.html +0 -17
  558. package/tests/fixtures/scrape-parity/html/09_whitespace_nbsp.html +0 -21
  559. package/tests/fixtures/scrape-parity/html/10_entity_unicode.html +0 -10
  560. package/tests/fixtures/scrape-parity/html/11_cdata_comments.html +0 -13
  561. package/tests/fixtures/scrape-parity/html/12_deep_nested_removals.html +0 -24
  562. package/tests/fixtures/scrape-parity/python_extract.py +0 -109
  563. package/tests/livewire/livewire.test.ts +0 -780
  564. package/tests/mcp.test.ts +0 -221
  565. package/tests/prefabs/prefabs.test.ts +0 -1093
  566. package/tests/relay/Action.test.ts +0 -392
  567. package/tests/relay/Call.test.ts +0 -535
  568. package/tests/relay/Deferred.test.ts +0 -71
  569. package/tests/relay/Message.test.ts +0 -164
  570. package/tests/relay/RelayClient.test.ts +0 -779
  571. package/tests/relay/RelayEvent.test.ts +0 -463
  572. package/tests/relay/helpers.ts +0 -79
  573. package/tests/rest/HttpClient.test.ts +0 -274
  574. package/tests/rest/RestError.test.ts +0 -53
  575. package/tests/rest/calling.test.ts +0 -156
  576. package/tests/rest/client.test.ts +0 -197
  577. package/tests/rest/compat.test.ts +0 -335
  578. package/tests/rest/datasphere.test.ts +0 -71
  579. package/tests/rest/fabric.test.ts +0 -186
  580. package/tests/rest/helpers.ts +0 -95
  581. package/tests/rest/logs.test.ts +0 -68
  582. package/tests/rest/pagination.test.ts +0 -133
  583. package/tests/rest/registry.test.ts +0 -94
  584. package/tests/rest/relay-rest.test.ts +0 -290
  585. package/tests/rest/video.test.ts +0 -173
  586. package/tests/setup.ts +0 -6
  587. package/tests/skills/SkillBase.test.ts +0 -108
  588. package/tests/skills/SkillManager.test.ts +0 -268
  589. package/tests/skills/SkillRegistry.test.ts +0 -176
  590. package/tests/skills/builtin.test.ts +0 -1472
  591. package/tests/skills/claude-skills.test.ts +0 -54
  592. package/tests/skills/custom-skills.test.ts +0 -53
  593. package/tests/skills/datasphere-serverless.test.ts +0 -70
  594. package/tests/skills/datasphere.test.ts +0 -107
  595. package/tests/skills/datetime.test.ts +0 -101
  596. package/tests/skills/google-maps.test.ts +0 -78
  597. package/tests/skills/info-gatherer.test.ts +0 -411
  598. package/tests/skills/joke.test.ts +0 -81
  599. package/tests/skills/math.test.ts +0 -68
  600. package/tests/skills/mcp-gateway.test.ts +0 -101
  601. package/tests/skills/play-background.test.ts +0 -54
  602. package/tests/skills/spider.test.ts +0 -108
  603. package/tests/skills/swml-transfer.test.ts +0 -178
  604. package/tests/skills/trivia.test.ts +0 -54
  605. package/tests/skills/vector-search.test.ts +0 -135
  606. package/tests/skills/weather-api.test.ts +0 -77
  607. package/tests/skills/web-search-parity.test.ts +0 -59
  608. package/tests/skills/web-search.test.ts +0 -103
  609. package/tests/skills/wikipedia.test.ts +0 -63
  610. package/tsconfig.json +0 -18
  611. package/vitest.config.ts +0 -9
  612. /package/{src → dist}/schema.json +0 -0
@@ -0,0 +1,2375 @@
1
+ /**
2
+ * AgentBase - Core agent class with Hono HTTP server and 5-phase SWML rendering.
3
+ *
4
+ * Composes PromptManager, SessionManager, SwmlBuilder, and a tool registry
5
+ * into a single HTTP-servable agent.
6
+ */
7
+ import { Hono } from 'hono';
8
+ import { basicAuth } from 'hono/basic-auth';
9
+ import { cors } from 'hono/cors';
10
+ import { randomBytes } from 'node:crypto';
11
+ import { PromptManager } from './PromptManager.js';
12
+ import { SessionManager } from './SessionManager.js';
13
+ import { SwmlBuilder } from './SwmlBuilder.js';
14
+ import { ConfigLoader } from './ConfigLoader.js';
15
+ import { SwaigFunction } from './SwaigFunction.js';
16
+ import { inferSchema, createTypedHandlerWrapper } from './TypeInference.js';
17
+ import { FunctionResult } from './FunctionResult.js';
18
+ import { ContextBuilder } from './ContextBuilder.js';
19
+ import { getLogger, suppressAllLogs } from './Logger.js';
20
+ import { safeAssign, filterSensitiveHeaders, redactUrl, isValidHostname } from './SecurityUtils.js';
21
+ import { SkillManager } from './skills/SkillManager.js';
22
+ import { SkillRegistry } from './skills/SkillRegistry.js';
23
+ import { ServerlessAdapter } from './ServerlessAdapter.js';
24
+ /**
25
+ * Core agent class that composes an HTTP server, prompt management, session handling,
26
+ * SWAIG tool registry, and 5-phase SWML rendering into a single deployable unit.
27
+ *
28
+ * A single `AgentBase` is one HTTP-servable voice agent:
29
+ *
30
+ * - `GET /` returns the SWML call-flow document
31
+ * - `POST /swaig` dispatches SWAIG function calls to registered tool handlers
32
+ * - `POST /post_prompt` receives the end-of-call summary and invokes {@link onSummary}
33
+ *
34
+ * Most user agents either (a) subclass `AgentBase` and override `defineTools()` / `onSummary()`
35
+ * or (b) use one of the {@link ./prefabs/index.js | prefab agents} (e.g. `ReceptionistAgent`).
36
+ *
37
+ * @example Subclass with a custom tool
38
+ * ```ts
39
+ * import { AgentBase, FunctionResult } from '@signalwire/sdk';
40
+ *
41
+ * class WeatherAgent extends AgentBase {
42
+ * static override PROMPT_SECTIONS = [
43
+ * { title: 'Role', body: 'You are a weather assistant.' },
44
+ * ];
45
+ *
46
+ * protected override defineTools(): void {
47
+ * this.defineTool({
48
+ * name: 'get_forecast',
49
+ * description: 'Return the forecast for a city.',
50
+ * parameters: {
51
+ * type: 'object',
52
+ * properties: { city: { type: 'string' } },
53
+ * required: ['city'],
54
+ * },
55
+ * handler: async ({ city }) => {
56
+ * const forecast = await fetchForecast(city as string);
57
+ * return new FunctionResult(forecast);
58
+ * },
59
+ * });
60
+ * }
61
+ * }
62
+ *
63
+ * const agent = new WeatherAgent({ name: 'weather', route: '/' });
64
+ * await agent.serve({ port: 3000 });
65
+ * ```
66
+ *
67
+ * @example Imperative usage (no subclass)
68
+ * ```ts
69
+ * const agent = new AgentBase({ name: 'hello', route: '/' });
70
+ * agent.setPromptText('You are a friendly greeter.');
71
+ * agent.defineTool({
72
+ * name: 'say_hi',
73
+ * description: 'Respond with a greeting.',
74
+ * parameters: { type: 'object', properties: {} },
75
+ * handler: () => new FunctionResult('Hello from SignalWire!'),
76
+ * });
77
+ * await agent.serve();
78
+ * ```
79
+ *
80
+ * @see {@link FunctionResult} — builder for tool handler responses
81
+ * @see {@link ContextBuilder} — multi-step conversation state machines
82
+ * @see {@link DataMap} — server-side tools without webhooks
83
+ * @see {@link AgentServer} — host multiple agents on one HTTP server
84
+ */
85
+ export class AgentBase {
86
+ /** Display name of this agent. */
87
+ name;
88
+ /** HTTP route path this agent listens on. */
89
+ route;
90
+ /** Hostname the HTTP server binds to. */
91
+ host;
92
+ /** Port number the HTTP server listens on. */
93
+ port;
94
+ /** Unique identifier for this agent instance. */
95
+ agentId;
96
+ // Internal managers
97
+ _promptManager;
98
+ sessionManager;
99
+ swmlBuilder;
100
+ toolRegistry = new Map();
101
+ // Auth
102
+ basicAuthCreds;
103
+ basicAuthSource = 'auto-generated';
104
+ // Call settings
105
+ autoAnswer;
106
+ _recordCall;
107
+ recordFormat;
108
+ recordStereo;
109
+ defaultWebhookUrl;
110
+ _nativeFunctions;
111
+ // AI config
112
+ hints = [];
113
+ languages = [];
114
+ pronounce = [];
115
+ params = {};
116
+ globalData = {};
117
+ functionIncludes = [];
118
+ promptLlmParams = {};
119
+ postPromptLlmParams = {};
120
+ internalFillers = {};
121
+ // Call flow verbs
122
+ preAnswerVerbs = [];
123
+ answerConfig = {};
124
+ postAnswerVerbs = [];
125
+ postAiVerbs = [];
126
+ // Dynamic config
127
+ dynamicConfigCallback = null;
128
+ swaigQueryParams = {};
129
+ // Webhook URL overrides
130
+ webHookUrlOverride = null;
131
+ postPromptUrlOverride = null;
132
+ // Contexts
133
+ contextsBuilder = null;
134
+ // MCP
135
+ _mcpServers = [];
136
+ _mcpServerEnabled = false;
137
+ // SIP Routing
138
+ _sipRoutingEnabled = false;
139
+ _sipRoute = '/sip';
140
+ _sipAutoMap = false;
141
+ _sipUsernames = null;
142
+ // Debug
143
+ debugEventsEnabled = false;
144
+ debugEventsLevel = 1;
145
+ // Proxy detection
146
+ _proxyUrlBase = process.env['SWML_PROXY_URL_BASE'] ?? null;
147
+ _proxyUrlBaseFromEnv = !!process.env['SWML_PROXY_URL_BASE'];
148
+ _proxyDebug = process.env['SWML_PROXY_DEBUG'] === 'true';
149
+ _trustProxyHeaders = process.env['SWML_TRUST_PROXY_HEADERS'] === 'true';
150
+ _enforceHttps = process.env['SWML_ENFORCE_HTTPS'] === 'true';
151
+ /** Structured logger instance for this agent, configurable via SIGNALWIRE_LOG_LEVEL. */
152
+ log = getLogger('AgentBase');
153
+ // Skills
154
+ _skillManager = new SkillManager();
155
+ // New constructor params (P1 gaps)
156
+ _enablePostPromptOverride = false;
157
+ _checkForInputOverride = false;
158
+ _schemaValidation = true;
159
+ _configFile = null;
160
+ _schemaPath = null;
161
+ // Routing callbacks (registered via registerRoutingCallback)
162
+ _routingCallbacks = new Map();
163
+ // Hono app
164
+ _app = null;
165
+ /**
166
+ * Create a new AgentBase instance.
167
+ * @param opts - Agent configuration options including name, route, auth, and call settings.
168
+ */
169
+ constructor(opts) {
170
+ // Load config file if provided — values are defaults, constructor args take precedence
171
+ let serviceConfig = {};
172
+ if (opts.configFile) {
173
+ this._configFile = opts.configFile;
174
+ try {
175
+ const loader = new ConfigLoader(opts.configFile);
176
+ serviceConfig = (loader.get('service') ?? {});
177
+ }
178
+ catch {
179
+ // Config file not found or invalid — continue with constructor args
180
+ }
181
+ }
182
+ // Config file values: constructor args take precedence unless at default values
183
+ // (matching Python's behavior where non-default constructor args always win)
184
+ this.name = serviceConfig['name'] ?? opts.name;
185
+ const routeArg = opts.route ?? '/';
186
+ this.route = (routeArg !== '/' ? routeArg : (serviceConfig['route'] ?? routeArg)).replace(/\/+$/, '') || '/';
187
+ const hostArg = opts.host ?? '0.0.0.0';
188
+ this.host = hostArg !== '0.0.0.0' ? hostArg : (serviceConfig['host'] ?? hostArg);
189
+ const configPort = serviceConfig['port'];
190
+ const parsedPort = opts.port ?? configPort ?? parseInt(process.env['PORT'] ?? '3000', 10);
191
+ if (isNaN(parsedPort) || parsedPort < 1 || parsedPort > 65535) {
192
+ throw new Error(`Invalid port: ${opts.port ?? process.env['PORT']}. Must be between 1 and 65535.`);
193
+ }
194
+ this.port = parsedPort;
195
+ this.agentId = opts.agentId ?? randomBytes(8).toString('hex');
196
+ this.autoAnswer = opts.autoAnswer ?? true;
197
+ this._recordCall = opts.recordCall ?? false;
198
+ this.recordFormat = opts.recordFormat ?? 'mp4';
199
+ this.recordStereo = opts.recordStereo ?? true;
200
+ this.defaultWebhookUrl = opts.defaultWebhookUrl ?? null;
201
+ this._nativeFunctions = opts.nativeFunctions ?? [];
202
+ // Store new constructor params
203
+ this._enablePostPromptOverride = opts.enablePostPromptOverride ?? false;
204
+ this._checkForInputOverride = opts.checkForInputOverride ?? false;
205
+ this._schemaValidation = opts.schemaValidation ?? true;
206
+ this._schemaPath = opts.schemaPath ?? null;
207
+ if (opts.suppressLogs) {
208
+ suppressAllLogs(true);
209
+ }
210
+ this._promptManager = new PromptManager(opts.usePom ?? true);
211
+ this.sessionManager = new SessionManager(opts.tokenExpirySecs ?? 3600);
212
+ // Forward schemaValidation + schemaPath into SwmlBuilder.
213
+ // Python equivalent: SchemaUtils(schema_path, schema_validation=...) inside SWMLService.
214
+ this.swmlBuilder = new SwmlBuilder({
215
+ enableValidation: this._schemaValidation,
216
+ ...(this._schemaPath ? { schemaPath: this._schemaPath } : {}),
217
+ });
218
+ // Setup auth
219
+ if (opts.basicAuth) {
220
+ this.basicAuthCreds = opts.basicAuth;
221
+ this.basicAuthSource = 'provided';
222
+ }
223
+ else {
224
+ const envUser = process.env['SWML_BASIC_AUTH_USER'];
225
+ const envPass = process.env['SWML_BASIC_AUTH_PASSWORD'];
226
+ if (envUser && envPass) {
227
+ this.basicAuthCreds = [envUser, envPass];
228
+ this.basicAuthSource = 'environment';
229
+ }
230
+ else {
231
+ // No SWML_BASIC_AUTH_PASSWORD was found in the environment and
232
+ // the caller did not pass basicAuth. Fall back to a random
233
+ // password that exists only in this process; warn loudly so
234
+ // external callers (tests, RPC clients, MCP) know why they are
235
+ // getting HTTP 401.
236
+ const username = envUser || this.name;
237
+ this.basicAuthCreds = [username, randomBytes(16).toString('hex')];
238
+ this.basicAuthSource = 'auto-generated';
239
+ this.log.warn(`basic_auth_password_autogenerated: username="${username}". ` +
240
+ `No SWML_BASIC_AUTH_PASSWORD found in environment and no basicAuth ` +
241
+ `passed to the agent constructor. The SDK generated a random ` +
242
+ `password that exists only in this process; external callers will ` +
243
+ `get HTTP 401 unless they read the value from this process's env. ` +
244
+ `To fix, set SWML_BASIC_AUTH_USER and SWML_BASIC_AUTH_PASSWORD in ` +
245
+ `your .env, or pass { basicAuth: [user, pass] } to the agent ` +
246
+ `constructor.`);
247
+ }
248
+ }
249
+ // Apply static PROMPT_SECTIONS from the class if defined
250
+ const ctor = this.constructor;
251
+ if (ctor.PROMPT_SECTIONS) {
252
+ for (const section of ctor.PROMPT_SECTIONS) {
253
+ this.promptAddSection(section.title, section);
254
+ }
255
+ }
256
+ }
257
+ /**
258
+ * Static prompt sections: subclasses can define these declaratively.
259
+ * Each entry is applied via promptAddSection() in the constructor.
260
+ */
261
+ static PROMPT_SECTIONS;
262
+ /**
263
+ * Lifecycle method to register tools. Subclasses should call this at the
264
+ * end of their own constructor (after all fields are initialized).
265
+ * Not called automatically — call `this.defineTools()` explicitly.
266
+ */
267
+ defineTools() {
268
+ // Default no-op — subclasses override
269
+ }
270
+ /**
271
+ * Public access to the list of registered tools.
272
+ *
273
+ * In Python, `define_tools()` is public and returns `List[SWAIGFunction]`.
274
+ * In TypeScript, `defineTools()` is a protected setup hook (void). This
275
+ * method provides the equivalent public "get all tools" capability.
276
+ * @returns Array of all registered SwaigFunction instances.
277
+ */
278
+ getTools() {
279
+ const tools = [];
280
+ for (const [, fn] of this.toolRegistry) {
281
+ if (fn instanceof SwaigFunction)
282
+ tools.push(fn);
283
+ }
284
+ return tools;
285
+ }
286
+ // ── Public getters for Python-public properties ────────────────────
287
+ /**
288
+ * Public accessor for the PromptManager (POM).
289
+ *
290
+ * Python exposes `self.pom` as a public attribute. This getter
291
+ * provides equivalent access for direct POM manipulation.
292
+ */
293
+ get promptManager() {
294
+ return this._promptManager;
295
+ }
296
+ /**
297
+ * Public accessor for the native functions list.
298
+ *
299
+ * Python exposes `self.native_functions` as a public read/write attribute.
300
+ * @returns A copy of the native functions list.
301
+ */
302
+ get nativeFunctions() {
303
+ return this._nativeFunctions;
304
+ }
305
+ /** Set the native functions list. */
306
+ set nativeFunctions(fns) {
307
+ this._nativeFunctions = fns;
308
+ }
309
+ /**
310
+ * Public read-only accessor for the SkillManager.
311
+ *
312
+ * Python exposes `self.skill_manager` as a public attribute. This getter
313
+ * provides equivalent read access.
314
+ */
315
+ get skillManager() {
316
+ return this._skillManager;
317
+ }
318
+ // ── Prompt methods ──────────────────────────────────────────────────
319
+ /**
320
+ * Set the main system prompt text for the AI.
321
+ * @param text - The prompt text to use.
322
+ * @returns This agent instance for chaining.
323
+ */
324
+ setPromptText(text) {
325
+ this._promptManager.setPromptText(text);
326
+ return this;
327
+ }
328
+ /**
329
+ * Set the post-prompt text evaluated after the call ends.
330
+ * @param text - The post-prompt text to use.
331
+ * @returns This agent instance for chaining.
332
+ */
333
+ setPostPrompt(text) {
334
+ this._promptManager.setPostPrompt(text);
335
+ return this;
336
+ }
337
+ /**
338
+ * Add a new section to the prompt with optional body, bullets, and subsections.
339
+ * @param title - Section heading.
340
+ * @param opts - Optional section content including body text, bullet points, and subsections.
341
+ * @returns This agent instance for chaining.
342
+ */
343
+ promptAddSection(title, opts) {
344
+ this._promptManager.addSection(title, opts);
345
+ return this;
346
+ }
347
+ /**
348
+ * Append content to an existing prompt section.
349
+ * @param title - Title of the section to append to.
350
+ * @param opts - Content to add: body text, a single bullet, or multiple bullets.
351
+ * @returns This agent instance for chaining.
352
+ */
353
+ promptAddToSection(title, opts) {
354
+ this._promptManager.addToSection(title, opts);
355
+ return this;
356
+ }
357
+ /**
358
+ * Add a subsection under an existing prompt section.
359
+ * @param parentTitle - Title of the parent section.
360
+ * @param title - Title of the new subsection.
361
+ * @param opts - Optional body text and bullet points for the subsection.
362
+ * @returns This agent instance for chaining.
363
+ */
364
+ promptAddSubsection(parentTitle, title, opts) {
365
+ this._promptManager.addSubsection(parentTitle, title, opts);
366
+ return this;
367
+ }
368
+ /**
369
+ * Check whether a prompt section with the given title exists.
370
+ * @param title - Section title to look for.
371
+ * @returns True if the section exists.
372
+ */
373
+ promptHasSection(title) {
374
+ return this._promptManager.hasSection(title);
375
+ }
376
+ /**
377
+ * Get the fully rendered main prompt text.
378
+ * @returns The assembled prompt string.
379
+ */
380
+ getPrompt() {
381
+ return this._promptManager.getPrompt();
382
+ }
383
+ /**
384
+ * Get the raw POM (Prompt Object Model) structure as an array of section data objects,
385
+ * when the agent is in POM mode and has at least one section.
386
+ *
387
+ * Matches Python `get_prompt()` which returns `Union[str, List[Dict]]` — a raw list when
388
+ * in POM mode (via `pom.to_list()` / `pom.render_dict()`), or a string otherwise.
389
+ * The TS `getPrompt()` always returns a string (rendered Markdown), so this companion
390
+ * method exposes the raw POM structure for callers that need it for serialisation or
391
+ * inspection (e.g. skills that inspect prompt sections).
392
+ *
393
+ * @returns An array of POM section data objects, or null if not in POM mode or POM is empty.
394
+ */
395
+ getPromptPom() {
396
+ const pom = this._promptManager.getPomBuilder();
397
+ if (!pom)
398
+ return null;
399
+ const sections = pom.toDict();
400
+ if (!sections.length)
401
+ return null;
402
+ return sections;
403
+ }
404
+ /**
405
+ * Get the post-prompt text, if one has been set.
406
+ * @returns The post-prompt string, or null if not configured.
407
+ */
408
+ getPostPrompt() {
409
+ return this._promptManager.getPostPrompt();
410
+ }
411
+ /**
412
+ * Set the prompt as a POM (Prompt Object Model) dictionary.
413
+ *
414
+ * Replaces the current POM sections with the provided structured data.
415
+ * Each entry should have `title`, and optionally `body`, `bullets`,
416
+ * `numbered`, `numberedBullets`, and `subsections`.
417
+ *
418
+ * @param pom - Array of POM section dictionaries.
419
+ * @returns This agent instance for chaining.
420
+ * @throws Error if POM mode is not enabled (`usePom: false`).
421
+ */
422
+ setPromptPom(pom) {
423
+ const pomBuilder = this._promptManager.getPomBuilder();
424
+ if (!pomBuilder) {
425
+ throw new Error('usePom must be true to use setPromptPom');
426
+ }
427
+ // Clear existing sections and rebuild from the provided POM array
428
+ pomBuilder.reset();
429
+ for (const section of pom) {
430
+ const title = section['title'] ?? '';
431
+ pomBuilder.addSection(title, {
432
+ body: section['body'],
433
+ bullets: section['bullets'],
434
+ numbered: section['numbered'],
435
+ numberedBullets: section['numberedBullets'],
436
+ subsections: section['subsections'],
437
+ });
438
+ }
439
+ return this;
440
+ }
441
+ // ── Contexts ────────────────────────────────────────────────────────
442
+ /**
443
+ * Define or replace the contexts configuration for the AI verb.
444
+ * @param contexts - An existing ContextBuilder instance or a plain object; a new ContextBuilder is created if omitted.
445
+ * @returns The active ContextBuilder for further configuration.
446
+ */
447
+ defineContexts(contexts) {
448
+ if (contexts instanceof ContextBuilder) {
449
+ this.contextsBuilder = contexts;
450
+ }
451
+ else {
452
+ this.contextsBuilder = new ContextBuilder();
453
+ }
454
+ // Attach agent reference so ContextBuilder.validate() can check
455
+ // user tool names against reserved native tool names.
456
+ this.contextsBuilder.attachAgent(this);
457
+ return this.contextsBuilder;
458
+ }
459
+ /**
460
+ * Remove all contexts, returning the agent to a no-contexts state.
461
+ *
462
+ * This is a convenience wrapper around `defineContexts().reset()`.
463
+ * Use it in a dynamic config callback when you need to rebuild
464
+ * contexts from scratch for a specific request.
465
+ *
466
+ * @returns This agent instance for chaining.
467
+ */
468
+ resetContexts() {
469
+ if (this.contextsBuilder) {
470
+ this.contextsBuilder.reset();
471
+ }
472
+ return this;
473
+ }
474
+ // ── AI config methods ───────────────────────────────────────────────
475
+ /**
476
+ * Add a single speech-recognition hint.
477
+ * @param hint - Word or phrase to boost in speech recognition.
478
+ * @returns This agent instance for chaining.
479
+ */
480
+ addHint(hint) {
481
+ this.hints.push(hint);
482
+ return this;
483
+ }
484
+ /**
485
+ * Add multiple speech-recognition hints at once.
486
+ * @param hints - Array of words or phrases to boost.
487
+ * @returns This agent instance for chaining.
488
+ */
489
+ addHints(hints) {
490
+ this.hints.push(...hints);
491
+ return this;
492
+ }
493
+ /**
494
+ * Add a pattern-based speech-recognition hint with find-and-replace behavior.
495
+ * @param opts - Pattern hint configuration with a descriptive hint label,
496
+ * regex pattern, replacement string, and optional case-insensitive flag.
497
+ * @returns This agent instance for chaining.
498
+ */
499
+ addPatternHint(opts) {
500
+ const entry = {
501
+ hint: opts.hint,
502
+ pattern: opts.pattern,
503
+ replace: opts.replace,
504
+ };
505
+ if (opts.ignoreCase)
506
+ entry['ignore_case'] = true;
507
+ this.hints.push(entry);
508
+ return this;
509
+ }
510
+ /**
511
+ * Add a supported language to the AI configuration.
512
+ * @param config - Language configuration including name, code, voice, and optional fillers.
513
+ * @returns This agent instance for chaining.
514
+ */
515
+ addLanguage(config) {
516
+ const lang = {
517
+ name: config.name,
518
+ code: config.code,
519
+ };
520
+ if (config.voice)
521
+ lang['voice'] = config.voice;
522
+ if (config.engine)
523
+ lang['engine'] = config.engine;
524
+ if (config.fillers)
525
+ lang['fillers'] = config.fillers;
526
+ if (config.speechModel)
527
+ lang['speech_model'] = config.speechModel;
528
+ if (config.functionFillers)
529
+ lang['function_fillers'] = config.functionFillers;
530
+ this.languages.push(lang);
531
+ return this;
532
+ }
533
+ /**
534
+ * Replace all configured languages with a new list.
535
+ * @param languages - Array of language configurations.
536
+ * @returns This agent instance for chaining.
537
+ */
538
+ setLanguages(languages) {
539
+ this.languages = [];
540
+ for (const l of languages)
541
+ this.addLanguage(l);
542
+ return this;
543
+ }
544
+ /**
545
+ * Add a pronunciation override rule for the TTS engine.
546
+ * @param rule - Pronunciation rule specifying the text to replace and its substitute.
547
+ * @returns This agent instance for chaining.
548
+ */
549
+ addPronunciation(rule) {
550
+ const r = { replace: rule.replace, with: rule.with };
551
+ if (rule.ignoreCase)
552
+ r['ignore_case'] = rule.ignoreCase;
553
+ this.pronounce.push(r);
554
+ return this;
555
+ }
556
+ /**
557
+ * Replace all pronunciation rules with a new list.
558
+ * @param rules - Array of pronunciation rule objects.
559
+ * @returns This agent instance for chaining.
560
+ */
561
+ setPronunciations(rules) {
562
+ this.pronounce = [];
563
+ for (const rule of rules) {
564
+ this.addPronunciation(rule);
565
+ }
566
+ return this;
567
+ }
568
+ /**
569
+ * Set a single AI parameter (e.g. "temperature", "top_p").
570
+ * @param key - Parameter name.
571
+ * @param value - Parameter value.
572
+ * @returns This agent instance for chaining.
573
+ */
574
+ setParam(key, value) {
575
+ this.params[key] = value;
576
+ return this;
577
+ }
578
+ /**
579
+ * Merge multiple AI parameters into the existing params object.
580
+ * @param params - Key-value pairs to merge.
581
+ * @returns This agent instance for chaining.
582
+ */
583
+ setParams(params) {
584
+ safeAssign(this.params, params);
585
+ return this;
586
+ }
587
+ /**
588
+ * Merge data into the global_data object passed into the AI configuration.
589
+ *
590
+ * Matches Python `set_global_data` which calls `.update()` on the internal dict —
591
+ * existing keys are preserved; incoming keys overwrite on collision. Skills and
592
+ * other callers can each contribute keys without clobbering one another.
593
+ *
594
+ * If you need to replace the entire object, assign a new agent instance or use
595
+ * `Object.assign(agent.globalData, {})` to clear first.
596
+ *
597
+ * @param data - Key-value pairs to merge into global data.
598
+ * @returns This agent instance for chaining.
599
+ */
600
+ setGlobalData(data) {
601
+ safeAssign(this.globalData, data);
602
+ return this;
603
+ }
604
+ /**
605
+ * Merge additional entries into the existing global_data object.
606
+ * @param data - Key-value pairs to merge into global data.
607
+ * @returns This agent instance for chaining.
608
+ */
609
+ updateGlobalData(data) {
610
+ safeAssign(this.globalData, data);
611
+ return this;
612
+ }
613
+ /**
614
+ * Set the list of native SWAIG function names (built-in platform functions).
615
+ * @param funcs - Array of native function names.
616
+ * @returns This agent instance for chaining.
617
+ */
618
+ setNativeFunctions(funcs) {
619
+ this._nativeFunctions = funcs;
620
+ return this;
621
+ }
622
+ /**
623
+ * The complete set of internal SWAIG function names that accept fillers,
624
+ * matching the SWAIGInternalFiller schema definition. Any name outside
625
+ * this set is silently ignored by the runtime — addInternalFiller /
626
+ * setInternalFillers warn if you pass an unknown name.
627
+ */
628
+ static SUPPORTED_INTERNAL_FILLER_NAMES = new Set([
629
+ 'hangup', // AI is hanging up the call
630
+ 'check_time', // AI is checking the time
631
+ 'wait_for_user', // AI is waiting for user input
632
+ 'wait_seconds', // deliberate pause / wait period
633
+ 'adjust_response_latency', // AI is adjusting response timing
634
+ 'next_step', // transitioning between steps in prompt.contexts
635
+ 'change_context', // switching between contexts in prompt.contexts
636
+ 'get_visual_input', // processing visual input (enable_vision)
637
+ 'get_ideal_strategy', // thinking (enable_thinking)
638
+ ]);
639
+ /**
640
+ * Set internal fillers for native SWAIG functions.
641
+ *
642
+ * Internal fillers are short phrases the AI agent speaks (via TTS) while
643
+ * an internal/native function is running, so the caller doesn't hear
644
+ * dead air during transitions or background work.
645
+ *
646
+ * Supported function names (matches the SWAIGInternalFiller schema):
647
+ *
648
+ * hangup — when the agent is hanging up
649
+ * check_time — when checking the time
650
+ * wait_for_user — when waiting for user input
651
+ * wait_seconds — during deliberate pauses
652
+ * adjust_response_latency — when adjusting response timing
653
+ * next_step — transitioning between steps in prompt.contexts
654
+ * change_context — switching between contexts in prompt.contexts
655
+ * get_visual_input — processing visual input (enable_vision=true)
656
+ * get_ideal_strategy — thinking (enable_thinking=true)
657
+ *
658
+ * Notably NOT supported: change_step, gather_submit, or arbitrary
659
+ * user-defined SWAIG function names. The runtime only honors fillers
660
+ * for the names listed above; everything else is silently ignored at
661
+ * the SWML level. This method warns at registration time if you pass
662
+ * an unknown name so you catch the typo early.
663
+ *
664
+ * @param internalFillers - Map of function name to language-keyed filler phrases.
665
+ * @returns This agent instance for chaining.
666
+ *
667
+ * @example
668
+ * agent.setInternalFillers({
669
+ * next_step: {
670
+ * 'en-US': ['Moving to the next step...', 'Great, let us continue...'],
671
+ * 'es': ['Pasando al siguiente paso...']
672
+ * },
673
+ * check_time: {
674
+ * 'en-US': ['Let me check the time...']
675
+ * }
676
+ * });
677
+ */
678
+ setInternalFillers(internalFillers) {
679
+ if (!internalFillers || typeof internalFillers !== 'object')
680
+ return this;
681
+ const supported = AgentBase.SUPPORTED_INTERNAL_FILLER_NAMES;
682
+ const unknown = Object.keys(internalFillers)
683
+ .filter((name) => !supported.has(name))
684
+ .sort();
685
+ if (unknown.length) {
686
+ this.log.warn(`unknown_internal_filler_names: [${unknown.join(', ')}]. ` +
687
+ `setInternalFillers received names that the SWML schema does not ` +
688
+ `recognize. Those entries will be ignored by the runtime. Supported ` +
689
+ `names: [${[...supported].sort().join(', ')}].`);
690
+ }
691
+ for (const [name, langMap] of Object.entries(internalFillers)) {
692
+ this.internalFillers[name] = { ...(this.internalFillers[name] ?? {}), ...langMap };
693
+ }
694
+ return this;
695
+ }
696
+ /**
697
+ * Add internal filler phrases for a single internal function and language.
698
+ *
699
+ * See {@link setInternalFillers} for the complete list of supported
700
+ * functionName values and an explanation of what fillers do.
701
+ *
702
+ * @param functionName - One of the supported internal function names
703
+ * (see SUPPORTED_INTERNAL_FILLER_NAMES). Names outside the supported
704
+ * set log a warning and are ignored by the runtime.
705
+ * @param languageCode - BCP-47 language code for the fillers (e.g. 'en-US').
706
+ * @param fillers - Array of filler phrases.
707
+ * @returns This agent instance for chaining.
708
+ */
709
+ addInternalFiller(functionName, languageCode, fillers) {
710
+ if (!AgentBase.SUPPORTED_INTERNAL_FILLER_NAMES.has(functionName)) {
711
+ this.log.warn(`unknown_internal_filler_name: "${functionName}". addInternalFiller ` +
712
+ `received a function name the SWML schema does not recognize. The ` +
713
+ `entry will be stored but the runtime will not play these fillers. ` +
714
+ `Supported names: [${[...AgentBase.SUPPORTED_INTERNAL_FILLER_NAMES].sort().join(', ')}].`);
715
+ }
716
+ if (!this.internalFillers[functionName]) {
717
+ this.internalFillers[functionName] = {};
718
+ }
719
+ this.internalFillers[functionName][languageCode] = fillers;
720
+ return this;
721
+ }
722
+ /**
723
+ * Add a remote SWAIG function include reference.
724
+ * @param url - URL of the remote SWAIG endpoint.
725
+ * @param functions - Function names available at that endpoint.
726
+ * @param metaData - Optional metadata to attach to the include.
727
+ * @returns This agent instance for chaining.
728
+ */
729
+ addFunctionInclude(url, functions, metaData) {
730
+ const inc = { url, functions };
731
+ if (metaData)
732
+ inc.meta_data = metaData;
733
+ this.functionIncludes.push(inc);
734
+ return this;
735
+ }
736
+ /**
737
+ * Replace the entire list of function includes.
738
+ * Each include must have a `url` and `functions` array.
739
+ * @param includes - Array of function include objects.
740
+ * @returns This agent instance for chaining.
741
+ */
742
+ setFunctionIncludes(includes) {
743
+ this.functionIncludes = includes.filter((inc) => inc.url && Array.isArray(inc.functions));
744
+ return this;
745
+ }
746
+ /**
747
+ * Merge LLM-specific parameters into the main prompt configuration (e.g. model, temperature).
748
+ * @param params - Key-value LLM parameters to merge.
749
+ * @returns This agent instance for chaining.
750
+ */
751
+ setPromptLlmParams(params) {
752
+ safeAssign(this.promptLlmParams, params);
753
+ return this;
754
+ }
755
+ /**
756
+ * Merge LLM-specific parameters into the post-prompt configuration.
757
+ * @param params - Key-value LLM parameters to merge.
758
+ * @returns This agent instance for chaining.
759
+ */
760
+ setPostPromptLlmParams(params) {
761
+ safeAssign(this.postPromptLlmParams, params);
762
+ return this;
763
+ }
764
+ /**
765
+ * Enable debug event webhooks for this agent.
766
+ * @param level - Debug verbosity level (defaults to 1).
767
+ * @returns This agent instance for chaining.
768
+ */
769
+ enableDebugEvents(level = 1) {
770
+ this.debugEventsEnabled = true;
771
+ this.debugEventsLevel = level;
772
+ return this;
773
+ }
774
+ // ── SIP routing ────────────────────────────────────────────────────
775
+ /**
776
+ * Enable SIP routing for this agent.
777
+ * @param autoMap - When true, automatically map SIP usernames to the agent route (defaults to true).
778
+ * @param path - HTTP path for the SIP routing endpoint (defaults to '/sip').
779
+ * @returns This agent instance for chaining.
780
+ */
781
+ enableSipRouting(autoMap = true, path = '/sip') {
782
+ this._sipRoutingEnabled = true;
783
+ this._sipRoute = path;
784
+ if (autoMap) {
785
+ this._sipAutoMap = true;
786
+ this.autoMapSipUsernames();
787
+ }
788
+ return this;
789
+ }
790
+ /**
791
+ * Register a SIP username to route to this agent.
792
+ * @param username - The SIP username to register.
793
+ * @returns This agent instance for chaining.
794
+ */
795
+ registerSipUsername(username) {
796
+ if (!this._sipUsernames)
797
+ this._sipUsernames = new Map();
798
+ this._sipUsernames.set(username.toLowerCase(), this.route);
799
+ return this;
800
+ }
801
+ /**
802
+ * Automatically register common SIP usernames based on this agent's
803
+ * name and route. Derives cleaned variants (alphanumeric + underscore)
804
+ * and registers each via `registerSipUsername()`.
805
+ *
806
+ * Port of Python's `auto_map_sip_usernames()`:
807
+ * - Registers a cleaned version of the agent name
808
+ * - Registers a cleaned version of the route (if different from name)
809
+ * - For names longer than 3 characters, also registers a vowel-stripped variant
810
+ *
811
+ * @returns This agent instance for chaining.
812
+ */
813
+ autoMapSipUsernames() {
814
+ // Register username based on agent name
815
+ const cleanName = this.name.toLowerCase().replace(/[^a-z0-9_]/g, '');
816
+ if (cleanName) {
817
+ this.registerSipUsername(cleanName);
818
+ }
819
+ // Register username based on route (without slashes)
820
+ const cleanRoute = this.route.toLowerCase().replace(/[^a-z0-9_]/g, '');
821
+ if (cleanRoute && cleanRoute !== cleanName) {
822
+ this.registerSipUsername(cleanRoute);
823
+ }
824
+ // Register common variations if they make sense
825
+ if (cleanName.length > 3) {
826
+ // Register without vowels
827
+ const noVowels = cleanName.replace(/[aeiou]/g, '');
828
+ if (noVowels !== cleanName && noVowels.length > 2) {
829
+ this.registerSipUsername(noVowels);
830
+ }
831
+ }
832
+ return this;
833
+ }
834
+ /**
835
+ * Register a callback at a specific HTTP path that decides how to route an
836
+ * incoming request.
837
+ *
838
+ * When called, the endpoint at `path` will invoke `callback` with the parsed
839
+ * request body. If `callback` returns a non-empty route string the server
840
+ * responds with `{ action: "redirect", route }` so the platform can forward the
841
+ * request to the right agent. If `callback` returns `null` / `undefined` the
842
+ * agent's own SWML is returned instead (normal processing).
843
+ *
844
+ * Mirrors Python `swml_service.register_routing_callback` /
845
+ * `web_mixin.register_routing_callback`.
846
+ *
847
+ * @param callback - Function receiving the parsed request body and returning a
848
+ * route string to redirect, or null/undefined for normal processing.
849
+ * @param path - HTTP path where this callback endpoint is registered
850
+ * (default: '/sip').
851
+ * @returns This agent instance for chaining.
852
+ */
853
+ registerRoutingCallback(callback, path = '/sip') {
854
+ // Normalize path: ensure leading slash, strip trailing slash
855
+ let normalized = path.replace(/\/+$/, '') || '/';
856
+ if (!normalized.startsWith('/'))
857
+ normalized = `/${normalized}`;
858
+ this._routingCallbacks.set(normalized, callback);
859
+ // Invalidate cached app so getApp() re-registers routes with the new callback
860
+ this._app = null;
861
+ return this;
862
+ }
863
+ /**
864
+ * Extract the SIP username from a request body's call.to field.
865
+ * @param requestBody - The parsed request body containing call information.
866
+ * @returns The extracted SIP username, or null if not found.
867
+ */
868
+ static extractSipUsername(requestBody) {
869
+ const call = requestBody?.['call'];
870
+ const callTo = call?.['to'];
871
+ if (callTo) {
872
+ let uri = callTo;
873
+ if (uri.startsWith('sip:') || uri.startsWith('sips:')) {
874
+ uri = uri.replace(/^sips?:/, '');
875
+ }
876
+ const atIdx = uri.indexOf('@');
877
+ if (atIdx > 0)
878
+ return uri.substring(0, atIdx);
879
+ return uri;
880
+ }
881
+ return null;
882
+ }
883
+ // ── MCP Integration ─────────────────────────────────────────────────
884
+ /**
885
+ * Add an external MCP server for tool discovery and invocation.
886
+ * Tools are discovered via MCP protocol at session start and added to the AI's tool list.
887
+ * @param url - MCP server HTTP endpoint URL
888
+ * @param opts - Optional configuration: headers, resources, resourceVars
889
+ * @returns This agent instance for chaining
890
+ */
891
+ addMcpServer(url, opts) {
892
+ const server = { url };
893
+ if (opts?.headers && Object.keys(opts.headers).length)
894
+ server['headers'] = opts.headers;
895
+ if (opts?.resources)
896
+ server['resources'] = true;
897
+ if (opts?.resourceVars && Object.keys(opts.resourceVars).length)
898
+ server['resource_vars'] = opts.resourceVars;
899
+ this._mcpServers.push(server);
900
+ return this;
901
+ }
902
+ /**
903
+ * Expose this agent's tools as an MCP server endpoint at /mcp.
904
+ * Adds a JSON-RPC 2.0 endpoint that MCP clients (Claude Desktop, other agents) can connect to.
905
+ * @returns This agent instance for chaining
906
+ */
907
+ enableMcpServer() {
908
+ this._mcpServerEnabled = true;
909
+ return this;
910
+ }
911
+ /** Check if MCP server endpoint is enabled. */
912
+ isMcpServerEnabled() {
913
+ return this._mcpServerEnabled;
914
+ }
915
+ /** Get configured MCP servers (read-only copy). */
916
+ getMcpServers() {
917
+ return [...this._mcpServers];
918
+ }
919
+ /** Build MCP tool list from registered tools. */
920
+ buildMcpToolList() {
921
+ const tools = [];
922
+ for (const [name, fn] of this.toolRegistry) {
923
+ if (fn instanceof SwaigFunction) {
924
+ const tool = {
925
+ name,
926
+ description: fn.description || name,
927
+ };
928
+ if (fn.parameters && Object.keys(fn.parameters).length) {
929
+ if ('type' in fn.parameters && 'properties' in fn.parameters) {
930
+ tool['inputSchema'] = fn.parameters;
931
+ }
932
+ else {
933
+ tool['inputSchema'] = {
934
+ type: 'object',
935
+ properties: fn.parameters,
936
+ ...(fn.required.length ? { required: fn.required } : {}),
937
+ };
938
+ }
939
+ }
940
+ else {
941
+ tool['inputSchema'] = { type: 'object', properties: {} };
942
+ }
943
+ tools.push(tool);
944
+ }
945
+ }
946
+ return tools;
947
+ }
948
+ /** Handle an MCP JSON-RPC 2.0 request. Returns the response object. */
949
+ async handleMcpRequest(body) {
950
+ const jsonrpc = body['jsonrpc'] || '';
951
+ const method = body['method'] || '';
952
+ const reqId = body['id'] ?? null;
953
+ const params = body['params'] || {};
954
+ if (jsonrpc !== '2.0') {
955
+ return { jsonrpc: '2.0', id: reqId, error: { code: -32600, message: 'Invalid JSON-RPC version' } };
956
+ }
957
+ // Initialize handshake
958
+ if (method === 'initialize') {
959
+ return {
960
+ jsonrpc: '2.0', id: reqId,
961
+ result: {
962
+ protocolVersion: '2025-06-18',
963
+ capabilities: { tools: {} },
964
+ serverInfo: { name: this.name, version: '1.0.0' },
965
+ },
966
+ };
967
+ }
968
+ // Initialized notification
969
+ if (method === 'notifications/initialized') {
970
+ return { jsonrpc: '2.0', id: reqId, result: {} };
971
+ }
972
+ // List tools
973
+ if (method === 'tools/list') {
974
+ return { jsonrpc: '2.0', id: reqId, result: { tools: this.buildMcpToolList() } };
975
+ }
976
+ // Call tool
977
+ if (method === 'tools/call') {
978
+ const toolName = params['name'] || '';
979
+ const args = params['arguments'] || {};
980
+ const fn = this.toolRegistry.get(toolName);
981
+ if (!fn || !(fn instanceof SwaigFunction)) {
982
+ return { jsonrpc: '2.0', id: reqId, error: { code: -32602, message: `Unknown tool: ${toolName}` } };
983
+ }
984
+ try {
985
+ const rawData = { function: toolName, argument: { parsed: [args] } };
986
+ const resultDict = await fn.execute(args, rawData);
987
+ const responseText = resultDict['response'] ?? '';
988
+ return {
989
+ jsonrpc: '2.0', id: reqId,
990
+ result: { content: [{ type: 'text', text: responseText }], isError: false },
991
+ };
992
+ }
993
+ catch (e) {
994
+ const msg = e instanceof Error ? e.message : String(e);
995
+ return {
996
+ jsonrpc: '2.0', id: reqId,
997
+ result: { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true },
998
+ };
999
+ }
1000
+ }
1001
+ // Ping
1002
+ if (method === 'ping') {
1003
+ return { jsonrpc: '2.0', id: reqId, result: {} };
1004
+ }
1005
+ return { jsonrpc: '2.0', id: reqId, error: { code: -32601, message: `Method not found: ${method}` } };
1006
+ }
1007
+ // ── Tools ───────────────────────────────────────────────────────────
1008
+ /**
1009
+ * Register a SWAIG tool (function) that the AI can invoke during a call.
1010
+ *
1011
+ * ## How this becomes a tool the model sees
1012
+ *
1013
+ * A SWAIG function is **exactly the same concept** as a "tool" in
1014
+ * native OpenAI / Anthropic tool calling. On every LLM turn, the SDK
1015
+ * renders each registered SWAIG function into the OpenAI tool schema:
1016
+ *
1017
+ * ```json
1018
+ * {
1019
+ * "type": "function",
1020
+ * "function": {
1021
+ * "name": "your_name_here",
1022
+ * "description": "your description text",
1023
+ * "parameters": { /* your JSON schema *\/ }
1024
+ * }
1025
+ * }
1026
+ * ```
1027
+ *
1028
+ * That schema goes to the model in the same API call that produces
1029
+ * the next assistant message. The model reads:
1030
+ *
1031
+ * - the **function `description`** to decide WHEN to call this tool
1032
+ * - each **parameter `description`** (inside the JSON schema) to
1033
+ * decide HOW to fill in each argument
1034
+ *
1035
+ * This means **descriptions are prompt engineering**, not developer
1036
+ * comments. A vague description is the #1 cause of "the model has the
1037
+ * right tool but doesn't call it" failures.
1038
+ *
1039
+ * ### Bad vs good descriptions
1040
+ *
1041
+ * ```text
1042
+ * BAD : description: 'Lookup function'
1043
+ * GOOD: description: 'Look up a customer's account details by account
1044
+ * number. Use this BEFORE quoting any account-specific info
1045
+ * (balance, plan, status). Do not use for general product
1046
+ * questions.'
1047
+ *
1048
+ * BAD : parameters: { id: { type: 'string', description: 'the id' } }
1049
+ * GOOD: parameters: { account_number: { type: 'string', description:
1050
+ * 'The customer's 8-digit account number, no dashes or spaces.
1051
+ * Ask the user if they don't provide it.' } }
1052
+ * ```
1053
+ *
1054
+ * ### Tool count matters
1055
+ *
1056
+ * LLM tool selection accuracy degrades past ~7-8 simultaneously-active
1057
+ * tools per call. Use Step.setFunctions() to partition tools across
1058
+ * steps so only the relevant subset is active at any moment.
1059
+ *
1060
+ * @param opts - Tool definition including name, description, parameter
1061
+ * schema, and handler callback. `description` and per-parameter
1062
+ * `description` strings are LLM-facing prompt engineering.
1063
+ * @returns This agent instance for chaining.
1064
+ */
1065
+ defineTool(opts) {
1066
+ const fn = new SwaigFunction({
1067
+ name: opts.name,
1068
+ description: opts.description,
1069
+ parameters: opts.parameters,
1070
+ handler: opts.handler,
1071
+ secure: opts.secure,
1072
+ fillers: opts.fillers,
1073
+ waitFile: opts.waitFile,
1074
+ waitFileLoops: opts.waitFileLoops,
1075
+ required: opts.required,
1076
+ webhookUrl: opts.webhookUrl,
1077
+ extraFields: opts.extraFields,
1078
+ });
1079
+ this.toolRegistry.set(opts.name, fn);
1080
+ return this;
1081
+ }
1082
+ /**
1083
+ * Register a SWAIG tool with a typed handler that receives named parameters
1084
+ * instead of the standard `(args, rawData)` convention.
1085
+ *
1086
+ * The SDK wraps the handler to unpack the args dict into positional params.
1087
+ * If no `parameters` schema is provided, one is inferred from the handler's
1088
+ * source code (parameter names and default values).
1089
+ *
1090
+ * @param opts - Tool definition with a typed handler function.
1091
+ * @returns This agent instance for chaining.
1092
+ */
1093
+ defineTypedTool(opts) {
1094
+ let params = opts.parameters;
1095
+ let required = opts.required ?? [];
1096
+ let paramNames;
1097
+ let hasRawData = false;
1098
+ const inferred = inferSchema(opts.handler);
1099
+ if (inferred) {
1100
+ paramNames = inferred.paramNames;
1101
+ hasRawData = inferred.hasRawData;
1102
+ if (!params) {
1103
+ params = inferred.parameters;
1104
+ required = inferred.required;
1105
+ }
1106
+ }
1107
+ else {
1108
+ // Could not infer — treat as old-style handler
1109
+ paramNames = [];
1110
+ }
1111
+ const wrapper = paramNames.length > 0
1112
+ ? createTypedHandlerWrapper(opts.handler, paramNames, hasRawData)
1113
+ : opts.handler;
1114
+ const fn = new SwaigFunction({
1115
+ name: opts.name,
1116
+ description: opts.description,
1117
+ parameters: params,
1118
+ handler: wrapper,
1119
+ secure: opts.secure,
1120
+ fillers: opts.fillers,
1121
+ waitFile: opts.waitFile,
1122
+ waitFileLoops: opts.waitFileLoops,
1123
+ required,
1124
+ isTypedHandler: true,
1125
+ });
1126
+ this.toolRegistry.set(opts.name, fn);
1127
+ return this;
1128
+ }
1129
+ /**
1130
+ * Get a summary of all registered tools with their names, descriptions, and parameter schemas.
1131
+ * @returns Array of tool descriptors.
1132
+ */
1133
+ getRegisteredTools() {
1134
+ const tools = [];
1135
+ for (const [name, fn] of this.toolRegistry) {
1136
+ if (fn instanceof SwaigFunction) {
1137
+ tools.push({ name, description: fn.description, parameters: fn.parameters });
1138
+ }
1139
+ else {
1140
+ tools.push({
1141
+ name,
1142
+ description: fn['purpose'] ?? '',
1143
+ parameters: fn['argument'] ?? {},
1144
+ });
1145
+ }
1146
+ }
1147
+ return tools;
1148
+ }
1149
+ /**
1150
+ * Look up a registered SwaigFunction by name.
1151
+ * @param name - The tool name to search for.
1152
+ * @returns The SwaigFunction instance, or undefined if not found or not a SwaigFunction.
1153
+ */
1154
+ getTool(name) {
1155
+ const fn = this.toolRegistry.get(name);
1156
+ return fn instanceof SwaigFunction ? fn : undefined;
1157
+ }
1158
+ /**
1159
+ * Register a pre-built SwaigFunction instance or a raw function descriptor (e.g. DataMap).
1160
+ * @param fn - A SwaigFunction instance or a plain object with a "function" key.
1161
+ * @returns This agent instance for chaining.
1162
+ */
1163
+ registerSwaigFunction(fn) {
1164
+ if (fn instanceof SwaigFunction) {
1165
+ this.toolRegistry.set(fn.name, fn);
1166
+ }
1167
+ else {
1168
+ const name = fn['function'];
1169
+ this.toolRegistry.set(name, fn);
1170
+ }
1171
+ return this;
1172
+ }
1173
+ /**
1174
+ * Validate a tool-call token for the given function.
1175
+ *
1176
+ * Mirrors Python reference `core/mixins/state_mixin.py validate_tool_token`:
1177
+ * 1. Unknown function → `false`.
1178
+ * 2. Registered but non-secure → `true` without consulting SessionManager
1179
+ * (non-secure tools never require a token).
1180
+ * 3. Raw-dict descriptors (e.g. DataMap) are treated as secure, matching
1181
+ * Python's `isinstance(func, dict) → is_secure = True` branch.
1182
+ * 4. Missing token on a secure tool → `false`.
1183
+ * 5. Otherwise delegate to `SessionManager.validateToolToken`.
1184
+ *
1185
+ * Divergences from the Python reference:
1186
+ * - No debug-logging branch: `AgentBase` does not expose an agent-level
1187
+ * debug-mode flag, so the per-call debug telemetry Python emits is
1188
+ * omitted. `SessionManager` still logs its own validation outcomes.
1189
+ * - No token-derived call-id fallback: `SessionManager.debugToken`
1190
+ * truncates the embedded call-id for log safety, so an extracted value
1191
+ * cannot be round-tripped back through `validateToolToken`. The caller
1192
+ * is expected to supply a non-empty `callId`; an empty one is forwarded
1193
+ * unchanged and the underlying validator will reject it.
1194
+ */
1195
+ validateToolToken(functionName, token, callId) {
1196
+ const fn = this.toolRegistry.get(functionName);
1197
+ if (!fn)
1198
+ return false;
1199
+ const isSecure = fn instanceof SwaigFunction ? fn.secure : true;
1200
+ if (!isSecure)
1201
+ return true;
1202
+ if (!token)
1203
+ return false;
1204
+ return this.sessionManager.validateToolToken(functionName, token, callId);
1205
+ }
1206
+ // ── Call flow ───────────────────────────────────────────────────────
1207
+ /**
1208
+ * Add a SWML verb to execute before the answer phase (phase 1).
1209
+ * @param verbName - Name of the SWML verb (e.g. "play", "record").
1210
+ * @param config - Verb configuration object.
1211
+ * @returns This agent instance for chaining.
1212
+ */
1213
+ addPreAnswerVerb(verbName, config) {
1214
+ this.preAnswerVerbs.push([verbName, config]);
1215
+ return this;
1216
+ }
1217
+ /**
1218
+ * Configure the answer verb (phase 2) with optional settings.
1219
+ * @param config - Optional answer verb configuration.
1220
+ * @returns This agent instance for chaining.
1221
+ */
1222
+ addAnswerVerb(config) {
1223
+ this.answerConfig = config ?? {};
1224
+ return this;
1225
+ }
1226
+ /**
1227
+ * Add a SWML verb to execute after the answer phase but before the AI verb (phase 3).
1228
+ * @param verbName - Name of the SWML verb.
1229
+ * @param config - Verb configuration object.
1230
+ * @returns This agent instance for chaining.
1231
+ */
1232
+ addPostAnswerVerb(verbName, config) {
1233
+ this.postAnswerVerbs.push([verbName, config]);
1234
+ return this;
1235
+ }
1236
+ /**
1237
+ * Add a SWML verb to execute after the AI verb (phase 5).
1238
+ * @param verbName - Name of the SWML verb.
1239
+ * @param config - Verb configuration object.
1240
+ * @returns This agent instance for chaining.
1241
+ */
1242
+ addPostAiVerb(verbName, config) {
1243
+ this.postAiVerbs.push([verbName, config]);
1244
+ return this;
1245
+ }
1246
+ /**
1247
+ * Remove all pre-answer verbs.
1248
+ * @returns This agent instance for chaining.
1249
+ */
1250
+ clearPreAnswerVerbs() {
1251
+ this.preAnswerVerbs = [];
1252
+ return this;
1253
+ }
1254
+ /**
1255
+ * Remove all post-answer verbs.
1256
+ * @returns This agent instance for chaining.
1257
+ */
1258
+ clearPostAnswerVerbs() {
1259
+ this.postAnswerVerbs = [];
1260
+ return this;
1261
+ }
1262
+ /**
1263
+ * Remove all post-AI verbs.
1264
+ * @returns This agent instance for chaining.
1265
+ */
1266
+ clearPostAiVerbs() {
1267
+ this.postAiVerbs = [];
1268
+ return this;
1269
+ }
1270
+ /**
1271
+ * Get the agent's display name.
1272
+ * @returns The agent name string.
1273
+ */
1274
+ getName() {
1275
+ return this.name;
1276
+ }
1277
+ // ── Skills ─────────────────────────────────────────────────────────
1278
+ /**
1279
+ * Add a skill to this agent, registering its tools, prompt sections, hints, and global data.
1280
+ * @param skill - The skill instance to add.
1281
+ * @returns This agent instance for chaining.
1282
+ */
1283
+ async addSkill(skill) {
1284
+ skill.setAgent(this);
1285
+ await this._skillManager.addSkill(skill);
1286
+ // Register skill tools, then apply any swaigFields as extraFields on the SWAIG function
1287
+ for (const toolDef of skill.getTools()) {
1288
+ this.defineTool(toolDef);
1289
+ const fn = this.toolRegistry.get(toolDef.name);
1290
+ if (fn instanceof SwaigFunction) {
1291
+ // Apply skill-level swaigFields as the base, then let tool-level filler
1292
+ // flags override — matches Python skill_base.py:70-73 (swaig_fields base,
1293
+ // explicit kwargs win) and SkillBase.defineTool() ({...swaigDefaults, ...toolDef}).
1294
+ if (Object.keys(skill.swaigFields).length > 0) {
1295
+ safeAssign(fn.extraFields, skill.swaigFields);
1296
+ }
1297
+ if (toolDef.wait_for_fillers !== undefined) {
1298
+ fn.extraFields['wait_for_fillers'] = toolDef.wait_for_fillers;
1299
+ }
1300
+ if (toolDef.skip_fillers !== undefined) {
1301
+ fn.extraFields['skip_fillers'] = toolDef.skip_fillers;
1302
+ }
1303
+ // Propagate is_hangup_hook so the SignalWire platform auto-fires this
1304
+ // tool on call hangup (Python equivalent: is_hangup_hook=True in define_tool).
1305
+ if (toolDef.isHangupHook) {
1306
+ fn.extraFields['is_hangup_hook'] = true;
1307
+ }
1308
+ }
1309
+ }
1310
+ // Register DataMap-style tools — skills that build their own SWAIG JSON
1311
+ // (e.g. DataSphereServerless) return them via getDataMapTools().
1312
+ // Python equivalent: self.agent.register_swaig_function(swaig_function)
1313
+ // inside register_tools() (skills/datasphere_serverless/skill.py:210).
1314
+ for (const dmFn of skill.getDataMapTools()) {
1315
+ this.registerSwaigFunction(dmFn);
1316
+ }
1317
+ // Inject prompt sections
1318
+ for (const section of skill.getPromptSections()) {
1319
+ this.promptAddSection(section.title, section);
1320
+ }
1321
+ // Inject hints
1322
+ const hints = skill.getHints();
1323
+ if (hints.length)
1324
+ this.addHints(hints);
1325
+ // Merge global data
1326
+ const globalData = skill.getGlobalData();
1327
+ if (Object.keys(globalData).length)
1328
+ this.updateGlobalData(globalData);
1329
+ return this;
1330
+ }
1331
+ /**
1332
+ * Add a skill by its registered name, looking it up in the global SkillRegistry.
1333
+ *
1334
+ * Matches Python's `add_skill(skill_name, params)` which loads skills by string
1335
+ * name via the SkillManager registry. Throws a `ValueError`-equivalent if the
1336
+ * skill name is not found in the registry.
1337
+ *
1338
+ * @param skillName - The name the skill was registered under in the SkillRegistry.
1339
+ * @param params - Optional configuration parameters forwarded to the skill factory.
1340
+ * @returns This agent instance for chaining.
1341
+ * @throws Error if no skill with the given name is registered.
1342
+ */
1343
+ async addSkillByName(skillName, params) {
1344
+ const skill = SkillRegistry.getInstance().create(skillName, params);
1345
+ if (!skill) {
1346
+ throw new Error(`Failed to load skill '${skillName}': skill not found in registry`);
1347
+ }
1348
+ return this.addSkill(skill);
1349
+ }
1350
+ /**
1351
+ * Remove a previously added skill by its instance ID.
1352
+ * @param instanceId - The unique instance ID of the skill to remove.
1353
+ * @returns True if the skill was found and removed.
1354
+ */
1355
+ async removeSkill(instanceId) {
1356
+ return this._skillManager.removeSkill(instanceId);
1357
+ }
1358
+ /**
1359
+ * List all registered skills with their names, instance IDs, and initialization status.
1360
+ * @returns Array of skill descriptors.
1361
+ */
1362
+ listSkills() {
1363
+ return this._skillManager.listSkills();
1364
+ }
1365
+ /**
1366
+ * Check whether a skill with the given name is registered.
1367
+ * @param skillName - The skill name to check.
1368
+ * @returns True if a skill with that name exists.
1369
+ */
1370
+ hasSkill(skillName) {
1371
+ return this._skillManager.hasSkill(skillName);
1372
+ }
1373
+ /**
1374
+ * Remove a skill by its name (Python parity).
1375
+ *
1376
+ * Python's `remove_skill(skill_name)` removes by skill name.
1377
+ * The existing `removeSkill(instanceId)` removes by instance ID.
1378
+ * This method provides name-based removal for cross-SDK parity.
1379
+ *
1380
+ * @param skillName - The skill name to remove.
1381
+ * @returns True if a skill with that name was found and removed.
1382
+ */
1383
+ async removeSkillByName(skillName) {
1384
+ const entries = this._skillManager.listSkills();
1385
+ for (const entry of entries) {
1386
+ if (entry.name === skillName) {
1387
+ return this._skillManager.removeSkill(entry.instanceId);
1388
+ }
1389
+ }
1390
+ return false;
1391
+ }
1392
+ // ── Dynamic config ──────────────────────────────────────────────────
1393
+ /**
1394
+ * Set a callback invoked on each SWML request to dynamically modify an ephemeral agent copy.
1395
+ *
1396
+ * The callback receives a clone of this agent — mutations apply only to the current
1397
+ * request, so you can vary prompt, tools, languages, params, or global data per call
1398
+ * without affecting the long-lived agent instance.
1399
+ *
1400
+ * @param cb - Callback receiving `(queryParams, bodyParams, headers, agent)` where
1401
+ * `agent` is the ephemeral `AgentBase` copy to mutate. May be async.
1402
+ * @returns This agent instance for chaining.
1403
+ *
1404
+ * @example
1405
+ * ```ts
1406
+ * agent.setDynamicConfigCallback((query, body, headers, agent) => {
1407
+ * const lang = query.lang ?? 'en';
1408
+ * if (lang === 'es') {
1409
+ * (agent as AgentBase).setPromptText('Eres un asistente útil.');
1410
+ * }
1411
+ * });
1412
+ * ```
1413
+ */
1414
+ setDynamicConfigCallback(cb) {
1415
+ this.dynamicConfigCallback = cb;
1416
+ return this;
1417
+ }
1418
+ /**
1419
+ * Add extra query parameters appended to all SWAIG webhook URLs.
1420
+ * @param params - Key-value pairs to append as query parameters.
1421
+ * @returns This agent instance for chaining.
1422
+ */
1423
+ addSwaigQueryParams(params) {
1424
+ safeAssign(this.swaigQueryParams, params);
1425
+ return this;
1426
+ }
1427
+ /**
1428
+ * Clear all SWAIG query parameters.
1429
+ * @returns This agent instance for chaining.
1430
+ */
1431
+ clearSwaigQueryParams() {
1432
+ this.swaigQueryParams = {};
1433
+ return this;
1434
+ }
1435
+ // ── Proxy detection ────────────────────────────────────────────────
1436
+ /**
1437
+ * Manually set the proxy base URL used for webhook URL generation.
1438
+ * @param url - The external-facing base URL (trailing slashes are stripped).
1439
+ * @returns This agent instance for chaining.
1440
+ */
1441
+ manualSetProxyUrl(url) {
1442
+ this._proxyUrlBase = url.replace(/\/+$/, '');
1443
+ this._proxyUrlBaseFromEnv = false;
1444
+ return this;
1445
+ }
1446
+ /**
1447
+ * Register a callback function that determines routing based on POST data.
1448
+ *
1449
+ * When a routing callback is registered, an endpoint at the specified path
1450
+ * is created in `getApp()`. The callback receives the request body and returns
1451
+ * Enable debug routes for testing and development.
1452
+ *
1453
+ * This is a backward-compatibility stub matching the Python SDK.
1454
+ * In the TypeScript SDK, debug routes (health, ready, debug_events)
1455
+ * are automatically registered in `getApp()`.
1456
+ *
1457
+ * @returns This agent instance for chaining.
1458
+ */
1459
+ enableDebugRoutes() {
1460
+ // No-op: debug routes are auto-registered in getApp()
1461
+ return this;
1462
+ }
1463
+ detectProxyFromRequest(c) {
1464
+ // Never override env var setting
1465
+ if (this._proxyUrlBaseFromEnv)
1466
+ return;
1467
+ // Only trust proxy headers when explicitly enabled
1468
+ if (!this._trustProxyHeaders)
1469
+ return;
1470
+ const get = (name) => c.req.header(name) ?? undefined;
1471
+ // 1. X-Forwarded-Host + X-Forwarded-Proto
1472
+ const xfHost = get('x-forwarded-host');
1473
+ if (xfHost) {
1474
+ const proto = get('x-forwarded-proto') ?? 'https';
1475
+ const url = `${proto}://${xfHost}`;
1476
+ if (this._proxyDebug)
1477
+ this.log.debug(`Proxy detected from X-Forwarded-Host: ${url}`);
1478
+ this._proxyUrlBase = url;
1479
+ return;
1480
+ }
1481
+ // 2. Forwarded header (RFC 7239): Forwarded: host=example.com;proto=https
1482
+ const forwarded = get('forwarded');
1483
+ if (forwarded) {
1484
+ const hostMatch = forwarded.match(/host=([^;,\s]+)/i);
1485
+ const protoMatch = forwarded.match(/proto=([^;,\s]+)/i);
1486
+ if (hostMatch && isValidHostname(hostMatch[1])) {
1487
+ const proto = protoMatch ? protoMatch[1] : 'https';
1488
+ const url = `${proto}://${hostMatch[1]}`;
1489
+ if (this._proxyDebug)
1490
+ this.log.debug(`Proxy detected from Forwarded header: ${url}`);
1491
+ this._proxyUrlBase = url;
1492
+ return;
1493
+ }
1494
+ else if (hostMatch) {
1495
+ this.log.warn(`Invalid hostname in Forwarded header: ${hostMatch[1]}`);
1496
+ }
1497
+ }
1498
+ // 3. X-Original-Host
1499
+ const xOrigHost = get('x-original-host');
1500
+ if (xOrigHost) {
1501
+ const proto = get('x-forwarded-proto') ?? 'https';
1502
+ const url = `${proto}://${xOrigHost}`;
1503
+ if (this._proxyDebug)
1504
+ this.log.debug(`Proxy detected from X-Original-Host: ${url}`);
1505
+ this._proxyUrlBase = url;
1506
+ return;
1507
+ }
1508
+ // 4. X-Forwarded-For (warn only - no host info)
1509
+ const xff = get('x-forwarded-for');
1510
+ if (xff && this._proxyDebug) {
1511
+ this.log.debug(`X-Forwarded-For detected (${xff}) but cannot determine host - set SWML_PROXY_URL_BASE manually`);
1512
+ }
1513
+ }
1514
+ // ── URL ─────────────────────────────────────────────────────────────
1515
+ /**
1516
+ * Override the default SWAIG webhook URL with a custom one.
1517
+ * @param url - The custom webhook URL.
1518
+ * @returns This agent instance for chaining.
1519
+ */
1520
+ setWebHookUrl(url) {
1521
+ this.webHookUrlOverride = url;
1522
+ return this;
1523
+ }
1524
+ /**
1525
+ * Override the default post-prompt webhook URL with a custom one.
1526
+ * @param url - The custom post-prompt URL.
1527
+ * @returns This agent instance for chaining.
1528
+ */
1529
+ setPostPromptUrl(url) {
1530
+ this.postPromptUrlOverride = url;
1531
+ return this;
1532
+ }
1533
+ /**
1534
+ * Get the full external URL of this agent, using the proxy base URL if available.
1535
+ * @param includeAuth - Whether to embed basic-auth credentials in the URL (defaults to false).
1536
+ * @returns The fully-qualified URL string.
1537
+ */
1538
+ getFullUrl(includeAuth = false) {
1539
+ if (this._proxyUrlBase) {
1540
+ let base = this._proxyUrlBase.replace(/\/+$/, '');
1541
+ if (includeAuth)
1542
+ base = this.insertAuth(base);
1543
+ if (this.route && this.route !== '/')
1544
+ base += this.route;
1545
+ return base;
1546
+ }
1547
+ const protocol = this._enforceHttps ? 'https' : 'http';
1548
+ const hostPart = this.host === '0.0.0.0' ? 'localhost' : this.host;
1549
+ let base = `${protocol}://${hostPart}:${this.port}`;
1550
+ if (includeAuth)
1551
+ base = this.insertAuth(base);
1552
+ if (this.route && this.route !== '/')
1553
+ base += this.route;
1554
+ return base;
1555
+ }
1556
+ insertAuth(baseUrl) {
1557
+ const [user, pass] = this.basicAuthCreds;
1558
+ if (!user || !pass)
1559
+ return baseUrl;
1560
+ return baseUrl.replace('://', `://${user}:${pass}@`);
1561
+ }
1562
+ buildWebhookUrl(endpoint, extraParams) {
1563
+ let url = `${this.getFullUrl(true)}/${endpoint}`;
1564
+ const params = { ...extraParams };
1565
+ const entries = Object.entries(params).filter(([, v]) => v);
1566
+ if (entries.length) {
1567
+ url += '?' + entries.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
1568
+ }
1569
+ return url;
1570
+ }
1571
+ // ── Lifecycle hooks (override in subclass) ──────────────────────────
1572
+ /**
1573
+ * Lifecycle hook called when a post-prompt summary is received. Override in subclasses.
1574
+ *
1575
+ * Invoked once at the end of a call when the AI has produced a structured summary
1576
+ * (configured via `setPostPrompt()` / `setPostPromptJson()`). Use this hook to persist
1577
+ * call data, notify other systems, or trigger follow-up workflows.
1578
+ *
1579
+ * @param _summary - Parsed summary object (JSON when the post-prompt requests
1580
+ * structured output), or `null` if extraction/parsing failed.
1581
+ * @param _rawData - Full raw post-prompt payload received from the platform,
1582
+ * including call metadata, conversation history, and the summary text.
1583
+ *
1584
+ * @example
1585
+ * ```ts
1586
+ * class MyAgent extends AgentBase {
1587
+ * async onSummary(summary, rawData) {
1588
+ * if (!summary) return;
1589
+ * await db.calls.insert({
1590
+ * callSid: rawData.call_id,
1591
+ * summary,
1592
+ * endedAt: new Date(),
1593
+ * });
1594
+ * }
1595
+ * }
1596
+ * ```
1597
+ */
1598
+ onSummary(_summary, _rawData) {
1599
+ // Default no-op
1600
+ }
1601
+ /**
1602
+ * Lifecycle hook called on every SWML request before rendering. Override in subclasses.
1603
+ *
1604
+ * May optionally return a modification dict that will be merged into the
1605
+ * rendered SWML document (matching Python's `Optional[dict]` return type).
1606
+ *
1607
+ * Matches Python `on_swml_request(request_data, callback_path, request)` — the third
1608
+ * parameter is the FastAPI `Request` in Python; here it is the raw Hono context object
1609
+ * so that subclasses can access query parameters (`context.req.query()`), raw request
1610
+ * headers (`context.req.raw.headers`), etc.
1611
+ *
1612
+ * @param _rawData - The parsed request body.
1613
+ * @param _callbackPath - Optional callback path from the request.
1614
+ * @param _context - The raw Hono context object (c), providing access to headers and query params.
1615
+ * @returns Optionally a dict of SWML modifications, or void.
1616
+ */
1617
+ onSwmlRequest(_rawData, _callbackPath, _context) {
1618
+ // Default no-op
1619
+ }
1620
+ /**
1621
+ * Lifecycle hook called when a debug event webhook is received. Override in subclasses.
1622
+ * @param _event - The debug event payload.
1623
+ */
1624
+ onDebugEvent(_event) {
1625
+ // Default no-op
1626
+ }
1627
+ /**
1628
+ * Override to add custom basic-auth validation logic beyond credential matching.
1629
+ * @param _username - The username from the request.
1630
+ * @param _password - The password from the request.
1631
+ * @returns True if the credentials are valid; false to reject the request.
1632
+ */
1633
+ validateBasicAuth(_username, _password) {
1634
+ return true;
1635
+ }
1636
+ /**
1637
+ * Hook called before each SWAIG function execution. Override in subclasses.
1638
+ *
1639
+ * **Behavioral note:** In the Python SDK, `on_function_call` IS the dispatcher
1640
+ * — it retrieves and executes the function, returning the result. In TypeScript,
1641
+ * `fn.execute()` is called separately after this hook. However, if this method
1642
+ * returns a non-void value, it is used as the result and the default execution
1643
+ * is skipped, enabling dispatch interception parity with Python.
1644
+ *
1645
+ * @param _name - Name of the function about to execute.
1646
+ * @param _args - Parsed arguments for the function.
1647
+ * @param _rawData - The full raw SWAIG request payload.
1648
+ * @returns Optionally a result dict to short-circuit default execution,
1649
+ * or void/undefined to proceed normally.
1650
+ */
1651
+ onFunctionCall(_name, _args, _rawData) {
1652
+ // Default no-op
1653
+ }
1654
+ // ── 5-phase SWML rendering ─────────────────────────────────────────
1655
+ /**
1656
+ * Render the complete SWML document by assembling all 5 phases: pre-answer, answer,
1657
+ * post-answer, AI, and post-AI verbs.
1658
+ *
1659
+ * @param callId - Optional call ID to use for session tokens; auto-generated if omitted.
1660
+ * @param modifications - Optional dict returned from `onSwmlRequest` to merge into the AI
1661
+ * verb config before rendering. Matches Python's `_render_swml(modifications)` semantics:
1662
+ * `global_data` is deep-merged; all other keys override the AI config directly.
1663
+ * @returns The rendered SWML document as a JSON string.
1664
+ */
1665
+ renderSwml(callId, modifications) {
1666
+ this.swmlBuilder.reset();
1667
+ const prompt = this.getPrompt();
1668
+ const postPrompt = this.getPostPrompt();
1669
+ if (!callId)
1670
+ callId = this.sessionManager.createSession();
1671
+ // Build webhook URLs
1672
+ const qp = { ...this.swaigQueryParams };
1673
+ let defaultWebhookUrl = this.buildWebhookUrl('swaig', qp);
1674
+ if (this.webHookUrlOverride)
1675
+ defaultWebhookUrl = this.webHookUrlOverride;
1676
+ // Build SWAIG object
1677
+ const swaigObj = {};
1678
+ if (this._nativeFunctions.length)
1679
+ swaigObj['native_functions'] = this._nativeFunctions;
1680
+ if (this.functionIncludes.length)
1681
+ swaigObj['includes'] = this.functionIncludes;
1682
+ if (Object.keys(this.internalFillers).length)
1683
+ swaigObj['internal_fillers'] = this.internalFillers;
1684
+ // Build functions array
1685
+ const functions = [];
1686
+ for (const [name, fn] of this.toolRegistry) {
1687
+ if (fn instanceof SwaigFunction) {
1688
+ let token;
1689
+ if (fn.secure && callId) {
1690
+ token = this.sessionManager.createToolToken(name, callId);
1691
+ }
1692
+ const entry = {
1693
+ function: name,
1694
+ description: fn.description,
1695
+ parameters: fn.parameters && Object.keys(fn.parameters).length
1696
+ ? ('type' in fn.parameters && 'properties' in fn.parameters
1697
+ ? fn.parameters
1698
+ : { type: 'object', properties: fn.parameters, ...(fn.required.length ? { required: fn.required } : {}) })
1699
+ : { type: 'object', properties: {} },
1700
+ };
1701
+ if (fn.fillers && Object.keys(fn.fillers).length)
1702
+ entry['fillers'] = fn.fillers;
1703
+ if (fn.waitFile)
1704
+ entry['wait_file'] = fn.waitFile;
1705
+ if (fn.waitFileLoops !== undefined)
1706
+ entry['wait_file_loops'] = fn.waitFileLoops;
1707
+ if (fn.webhookUrl) {
1708
+ entry['web_hook_url'] = fn.webhookUrl;
1709
+ }
1710
+ else if (token || Object.keys(this.swaigQueryParams).length) {
1711
+ const urlParams = { ...this.swaigQueryParams };
1712
+ if (token)
1713
+ urlParams['__token'] = token;
1714
+ entry['web_hook_url'] = this.buildWebhookUrl('swaig', urlParams);
1715
+ }
1716
+ safeAssign(entry, fn.extraFields);
1717
+ functions.push(entry);
1718
+ }
1719
+ else {
1720
+ // Raw dict (DataMap) - use as-is
1721
+ const entry = { ...fn, function: name };
1722
+ functions.push(entry);
1723
+ }
1724
+ }
1725
+ if (functions.length) {
1726
+ swaigObj['functions'] = functions;
1727
+ swaigObj['defaults'] = { web_hook_url: defaultWebhookUrl };
1728
+ }
1729
+ // MCP servers
1730
+ if (this._mcpServers.length) {
1731
+ swaigObj['mcp_servers'] = [...this._mcpServers];
1732
+ }
1733
+ // Build post-prompt URL
1734
+ let postPromptUrl;
1735
+ if (postPrompt) {
1736
+ const ppParams = { ...this.swaigQueryParams };
1737
+ if (callId) {
1738
+ const ppToken = this.sessionManager.createToolToken('post_prompt', callId);
1739
+ if (ppToken)
1740
+ ppParams['__token'] = ppToken;
1741
+ }
1742
+ postPromptUrl = this.buildWebhookUrl('post_prompt', ppParams);
1743
+ if (this.postPromptUrlOverride)
1744
+ postPromptUrl = this.postPromptUrlOverride;
1745
+ }
1746
+ // ── PHASE 1: Pre-answer verbs ──
1747
+ for (const [verb, config] of this.preAnswerVerbs) {
1748
+ this.swmlBuilder.addVerb(verb, config);
1749
+ }
1750
+ // ── PHASE 2: Answer verb ──
1751
+ if (this.autoAnswer) {
1752
+ this.swmlBuilder.addVerb('answer', this.answerConfig);
1753
+ }
1754
+ // ── PHASE 3: Post-answer verbs ──
1755
+ if (this._recordCall) {
1756
+ this.swmlBuilder.addVerb('record_call', {
1757
+ format: this.recordFormat,
1758
+ stereo: this.recordStereo,
1759
+ });
1760
+ }
1761
+ for (const [verb, config] of this.postAnswerVerbs) {
1762
+ this.swmlBuilder.addVerb(verb, config);
1763
+ }
1764
+ // ── PHASE 4: AI verb ──
1765
+ const aiConfig = {};
1766
+ // Prompt
1767
+ if (this.contextsBuilder) {
1768
+ const contextsDict = this.contextsBuilder.toDict();
1769
+ const promptObj = { text: prompt || `You are ${this.name}, a helpful AI assistant.` };
1770
+ if (Object.keys(this.promptLlmParams).length)
1771
+ Object.assign(promptObj, this.promptLlmParams);
1772
+ aiConfig['prompt'] = promptObj;
1773
+ aiConfig['contexts'] = contextsDict;
1774
+ }
1775
+ else {
1776
+ const promptObj = { text: prompt };
1777
+ if (Object.keys(this.promptLlmParams).length)
1778
+ Object.assign(promptObj, this.promptLlmParams);
1779
+ aiConfig['prompt'] = promptObj;
1780
+ }
1781
+ // Post-prompt
1782
+ if (postPrompt) {
1783
+ const ppObj = { text: postPrompt };
1784
+ if (Object.keys(this.postPromptLlmParams).length)
1785
+ Object.assign(ppObj, this.postPromptLlmParams);
1786
+ aiConfig['post_prompt'] = ppObj;
1787
+ if (postPromptUrl)
1788
+ aiConfig['post_prompt_url'] = postPromptUrl;
1789
+ }
1790
+ // SWAIG
1791
+ if (Object.keys(swaigObj).length)
1792
+ aiConfig['SWAIG'] = swaigObj;
1793
+ // Additional config
1794
+ if (this.hints.length)
1795
+ aiConfig['hints'] = this.hints;
1796
+ if (this.languages.length)
1797
+ aiConfig['languages'] = this.languages;
1798
+ if (this.pronounce.length)
1799
+ aiConfig['pronounce'] = this.pronounce;
1800
+ if (Object.keys(this.params).length)
1801
+ aiConfig['params'] = this.params;
1802
+ if (Object.keys(this.globalData).length)
1803
+ aiConfig['global_data'] = this.globalData;
1804
+ // Debug events
1805
+ if (this.debugEventsEnabled) {
1806
+ aiConfig['debug_webhook_url'] = this.buildWebhookUrl('debug_events');
1807
+ aiConfig['debug_webhook_level'] = this.debugEventsLevel;
1808
+ }
1809
+ // Apply modifications from onSwmlRequest (Python parity: merge into AI verb config).
1810
+ // global_data is deep-merged; all other keys override AI config fields directly.
1811
+ if (modifications && typeof modifications === 'object') {
1812
+ if (modifications['global_data'] && typeof modifications['global_data'] === 'object') {
1813
+ aiConfig['global_data'] = {
1814
+ ...(aiConfig['global_data'] ?? {}),
1815
+ ...modifications['global_data'],
1816
+ };
1817
+ }
1818
+ for (const [key, value] of Object.entries(modifications)) {
1819
+ if (key !== 'global_data') {
1820
+ aiConfig[key] = value;
1821
+ }
1822
+ }
1823
+ }
1824
+ this.swmlBuilder.addVerb('ai', aiConfig);
1825
+ // ── PHASE 5: Post-AI verbs ──
1826
+ for (const [verb, config] of this.postAiVerbs) {
1827
+ this.swmlBuilder.addVerb(verb, config);
1828
+ }
1829
+ return this.swmlBuilder.renderDocument();
1830
+ }
1831
+ // ── Ephemeral copy for dynamic config ───────────────────────────────
1832
+ createEphemeralCopy() {
1833
+ const copy = Object.create(Object.getPrototypeOf(this));
1834
+ Object.assign(copy, this);
1835
+ // Deep-copy mutable state
1836
+ copy._promptManager = new PromptManager(true);
1837
+ // Carry over the current prompt
1838
+ const p = this.getPrompt();
1839
+ if (p)
1840
+ copy._promptManager.setPromptText(p);
1841
+ const pp = this.getPostPrompt();
1842
+ if (pp)
1843
+ copy._promptManager.setPostPrompt(pp);
1844
+ copy.toolRegistry = new Map(this.toolRegistry);
1845
+ copy.hints = [...this.hints];
1846
+ copy.languages = [...this.languages];
1847
+ copy.pronounce = [...this.pronounce];
1848
+ copy.params = { ...this.params };
1849
+ copy.globalData = { ...this.globalData };
1850
+ copy.preAnswerVerbs = [...this.preAnswerVerbs];
1851
+ copy.postAnswerVerbs = [...this.postAnswerVerbs];
1852
+ copy.postAiVerbs = [...this.postAiVerbs];
1853
+ copy.swmlBuilder = new SwmlBuilder();
1854
+ // Replay skills into the ephemeral copy so dynamic config callbacks can modify them
1855
+ copy._skillManager = new SkillManager();
1856
+ for (const entry of this._skillManager.getLoadedSkillEntries()) {
1857
+ try {
1858
+ const skill = new entry.SkillClass(entry.config);
1859
+ skill.setAgent(copy);
1860
+ // Synchronous re-add: mark initialized, register tools/prompts/hints/data
1861
+ skill.markInitialized();
1862
+ copy._skillManager.addSkill(skill).catch((err) => {
1863
+ // Swallow re-add errors in the cloning path — the primary agent already
1864
+ // validated env vars / packages / schema / setup when this skill was first
1865
+ // added, and the clone inherits that validation. Python's equivalent at
1866
+ // skill_manager.py:161-170 specifically swallows "already exists"
1867
+ // ValueErrors during cloning; TS has no such error class (toolRegistry
1868
+ // uses Map.set which silently overwrites), so the blanket swallow is
1869
+ // the closest parity. Log at debug so the error isn't entirely lost.
1870
+ this.log.debug('Skipping re-add error during agent clone', {
1871
+ skill: entry.skillName,
1872
+ error: err instanceof Error ? err.message : String(err),
1873
+ });
1874
+ });
1875
+ for (const toolDef of skill.getTools()) {
1876
+ copy.defineTool(toolDef);
1877
+ const fn = copy.toolRegistry.get(toolDef.name);
1878
+ if (fn instanceof SwaigFunction) {
1879
+ if (Object.keys(skill.swaigFields).length > 0) {
1880
+ safeAssign(fn.extraFields, skill.swaigFields);
1881
+ }
1882
+ if (toolDef.wait_for_fillers !== undefined) {
1883
+ fn.extraFields['wait_for_fillers'] = toolDef.wait_for_fillers;
1884
+ }
1885
+ if (toolDef.skip_fillers !== undefined) {
1886
+ fn.extraFields['skip_fillers'] = toolDef.skip_fillers;
1887
+ }
1888
+ if (toolDef.isHangupHook) {
1889
+ fn.extraFields['is_hangup_hook'] = true;
1890
+ }
1891
+ }
1892
+ }
1893
+ for (const dmFn of skill.getDataMapTools()) {
1894
+ copy.registerSwaigFunction(dmFn);
1895
+ }
1896
+ for (const section of skill.getPromptSections()) {
1897
+ copy.promptAddSection(section.title, section);
1898
+ }
1899
+ const hints = skill.getHints();
1900
+ if (hints.length)
1901
+ copy.addHints(hints);
1902
+ const globalData = skill.getGlobalData();
1903
+ if (Object.keys(globalData).length)
1904
+ copy.updateGlobalData(globalData);
1905
+ }
1906
+ catch (e) {
1907
+ this.log.warn(`Failed to replay skill '${entry.skillName}' in ephemeral copy: ${e}`);
1908
+ }
1909
+ }
1910
+ return copy;
1911
+ }
1912
+ // ── Hono HTTP app ───────────────────────────────────────────────────
1913
+ /**
1914
+ * Get or lazily create the Hono HTTP application with all routes, middleware, auth, and CORS.
1915
+ * @returns The configured Hono application instance.
1916
+ */
1917
+ getApp() {
1918
+ if (this._app)
1919
+ return this._app;
1920
+ const app = new Hono();
1921
+ // Security headers
1922
+ const requestTimeout = parseInt(process.env['SWML_REQUEST_TIMEOUT'] ?? '30000', 10);
1923
+ const maxRequestSize = parseInt(process.env['SWML_MAX_REQUEST_SIZE'] ?? '1048576', 10);
1924
+ app.use('*', async (c, next) => {
1925
+ await next();
1926
+ c.res.headers.set('X-Content-Type-Options', 'nosniff');
1927
+ c.res.headers.set('X-Frame-Options', 'DENY');
1928
+ c.res.headers.set('X-XSS-Protection', '1; mode=block');
1929
+ c.res.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
1930
+ c.res.headers.set('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");
1931
+ c.res.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
1932
+ });
1933
+ // Request size limit
1934
+ app.use('*', async (c, next) => {
1935
+ const contentLength = c.req.header('content-length');
1936
+ const size = parseInt(contentLength ?? '', 10);
1937
+ if (contentLength && (isNaN(size) || size > maxRequestSize)) {
1938
+ return c.json({ error: 'Request too large' }, 413);
1939
+ }
1940
+ await next();
1941
+ });
1942
+ // Allowed hosts (configurable via env)
1943
+ const allowedHosts = process.env['SWML_ALLOWED_HOSTS'];
1944
+ if (allowedHosts) {
1945
+ const hostSet = new Set(allowedHosts.split(',').map(h => h.trim().toLowerCase()));
1946
+ app.use('*', async (c, next) => {
1947
+ const host = (c.req.header('host') ?? '').split(':')[0].toLowerCase();
1948
+ if (!hostSet.has(host)) {
1949
+ return c.json({ error: 'Forbidden: host not allowed' }, 403);
1950
+ }
1951
+ await next();
1952
+ });
1953
+ }
1954
+ // Rate limiting (configurable via env, requests per minute per IP)
1955
+ const rateLimitStr = process.env['SWML_RATE_LIMIT'];
1956
+ if (rateLimitStr) {
1957
+ const maxPerMinute = parseInt(rateLimitStr, 10);
1958
+ if (maxPerMinute > 0) {
1959
+ const hits = new Map();
1960
+ app.use('*', async (c, next) => {
1961
+ const ip = this._trustProxyHeaders
1962
+ ? (c.req.header('x-forwarded-for')?.split(',')[0].trim()
1963
+ ?? c.req.header('x-real-ip')
1964
+ ?? 'unknown')
1965
+ : 'unknown';
1966
+ const now = Date.now();
1967
+ let entry = hits.get(ip);
1968
+ if (!entry || now >= entry.resetAt) {
1969
+ entry = { count: 0, resetAt: now + 60_000 };
1970
+ hits.set(ip, entry);
1971
+ }
1972
+ // Cleanup if map grows too large
1973
+ if (hits.size > 10000) {
1974
+ for (const [k, v] of hits) {
1975
+ if (now >= v.resetAt)
1976
+ hits.delete(k);
1977
+ }
1978
+ }
1979
+ entry.count++;
1980
+ if (entry.count > maxPerMinute) {
1981
+ return c.json({ error: 'Rate limit exceeded' }, 429);
1982
+ }
1983
+ await next();
1984
+ });
1985
+ }
1986
+ }
1987
+ // CORS (configurable via env)
1988
+ const corsOrigins = process.env['SWML_CORS_ORIGINS'];
1989
+ const corsOrigin = corsOrigins ? corsOrigins.split(',').map(o => o.trim()) : '*';
1990
+ const corsCredentials = corsOrigin !== '*';
1991
+ app.use('*', cors({ origin: corsOrigin, credentials: corsCredentials }));
1992
+ // CSRF protection (optional, gated by env)
1993
+ if (process.env['SWML_CSRF_PROTECTION'] === 'true') {
1994
+ const allowedOrigins = corsOrigins
1995
+ ? new Set(corsOrigins.split(',').map(o => o.trim().toLowerCase()))
1996
+ : null;
1997
+ app.use('*', async (c, next) => {
1998
+ if (c.req.method === 'POST') {
1999
+ const origin = c.req.header('origin');
2000
+ if (origin && allowedOrigins && !allowedOrigins.has(origin.toLowerCase())) {
2001
+ return c.json({ error: 'Origin not allowed' }, 403);
2002
+ }
2003
+ }
2004
+ await next();
2005
+ });
2006
+ }
2007
+ // Auth middleware
2008
+ const [user, pass] = this.basicAuthCreds;
2009
+ const authMw = basicAuth({ username: user, password: pass });
2010
+ const basePath = this.route === '/' ? '' : this.route;
2011
+ // Root - returns SWML
2012
+ const handleSwml = async (c) => {
2013
+ let reqLog = this.log.bind({ endpoint: this.route });
2014
+ reqLog.debug('endpoint_called');
2015
+ let body = {};
2016
+ try {
2017
+ body = await c.req.json();
2018
+ }
2019
+ catch { /* GET or no body */ }
2020
+ reqLog.debug('request_body_received', { body_size: JSON.stringify(body).length });
2021
+ this.detectProxyFromRequest(c);
2022
+ const callbackPath = body['callback_path'] ?? undefined;
2023
+ let swmlMods = undefined;
2024
+ try {
2025
+ swmlMods = await this.onSwmlRequest(body, callbackPath, c);
2026
+ if (swmlMods)
2027
+ reqLog.debug('on_swml_request_modifications_applied');
2028
+ }
2029
+ catch (err) {
2030
+ reqLog.error('error_in_on_swml_request', { error: err instanceof Error ? err.message : String(err) });
2031
+ }
2032
+ const callId = body['call_id'] || undefined;
2033
+ if (callId)
2034
+ reqLog = reqLog.bind({ call_id: callId });
2035
+ let agentToUse = this;
2036
+ if (this.dynamicConfigCallback) {
2037
+ agentToUse = this.createEphemeralCopy();
2038
+ const queryParams = {};
2039
+ const url = new URL(c.req.url);
2040
+ url.searchParams.forEach((v, k) => { queryParams[k] = v; });
2041
+ const rawHeaders = {};
2042
+ c.req.raw.headers.forEach((v, k) => { rawHeaders[k] = v; });
2043
+ const headers = filterSensitiveHeaders(rawHeaders);
2044
+ await this.dynamicConfigCallback(queryParams, body, headers, agentToUse);
2045
+ reqLog.debug('dynamic_config_complete');
2046
+ }
2047
+ const swml = agentToUse.renderSwml(callId, swmlMods || undefined);
2048
+ reqLog.debug('swml_rendered', { swml_size: swml.length });
2049
+ reqLog.info('request_successful');
2050
+ return c.json(JSON.parse(swml));
2051
+ };
2052
+ app.get(`${basePath}`, authMw, handleSwml);
2053
+ app.post(`${basePath}`, authMw, handleSwml);
2054
+ if (basePath) {
2055
+ app.get(`${basePath}/`, authMw, handleSwml);
2056
+ app.post(`${basePath}/`, authMw, handleSwml);
2057
+ }
2058
+ // SWAIG function dispatcher
2059
+ const handleSwaig = async (c) => {
2060
+ let reqLog = this.log.bind({ endpoint: `${basePath}/swaig` });
2061
+ reqLog.debug('endpoint_called');
2062
+ let body = {};
2063
+ try {
2064
+ body = await c.req.json();
2065
+ }
2066
+ catch { /* empty */ }
2067
+ const fnName = body['function'];
2068
+ if (!fnName)
2069
+ return c.json({ error: 'Missing function name' }, 400);
2070
+ if (fnName.length > 128)
2071
+ return c.json({ error: 'Invalid function name' }, 400);
2072
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(fnName)) {
2073
+ reqLog.warn('invalid_function_name_format', { function: fnName });
2074
+ return c.json({ error: 'Invalid function name' }, 400);
2075
+ }
2076
+ reqLog = reqLog.bind({ function: fnName });
2077
+ reqLog.debug('function_call_received');
2078
+ const callIdStr = body['call_id'] ?? '';
2079
+ if (callIdStr)
2080
+ reqLog = reqLog.bind({ call_id: callIdStr });
2081
+ const fn = this.toolRegistry.get(fnName);
2082
+ if (!fn || !(fn instanceof SwaigFunction)) {
2083
+ reqLog.warn('function_not_found', { requested: fnName });
2084
+ return c.json({ error: `Unknown function: ${fnName}` }, 404);
2085
+ }
2086
+ // Token validation for secure functions
2087
+ if (fn.secure) {
2088
+ const url = new URL(c.req.url);
2089
+ const token = url.searchParams.get('__token') ?? url.searchParams.get('token');
2090
+ if (!token) {
2091
+ reqLog.warn('missing_token');
2092
+ const result = new FunctionResult('The security token for this function is missing or expired. This action cannot be completed.');
2093
+ return c.json(result.toDict());
2094
+ }
2095
+ if (!this.sessionManager.validateToken(callIdStr, fnName, token)) {
2096
+ reqLog.warn('token_invalid');
2097
+ const result = new FunctionResult('The security token for this function is invalid or expired. This action cannot be completed.');
2098
+ return c.json(result.toDict());
2099
+ }
2100
+ reqLog.debug('token_valid');
2101
+ }
2102
+ const rawArgs = body['argument'];
2103
+ const args = (rawArgs !== null && typeof rawArgs === 'object' && !Array.isArray(rawArgs))
2104
+ ? rawArgs
2105
+ : {};
2106
+ reqLog.debug('executing_function', { args: JSON.stringify(args) });
2107
+ const hookResult = await this.onFunctionCall(fnName, args, body);
2108
+ // If onFunctionCall returned a result, use it (dispatch interception)
2109
+ if (hookResult !== undefined && hookResult !== null) {
2110
+ reqLog.info('function_intercepted_by_hook');
2111
+ return c.json(hookResult);
2112
+ }
2113
+ try {
2114
+ const result = await fn.execute(args, body);
2115
+ reqLog.info('function_executed_successfully');
2116
+ reqLog.debug('function_result', { result_size: JSON.stringify(result).length });
2117
+ return c.json(result);
2118
+ }
2119
+ catch (err) {
2120
+ reqLog.error('function_execution_error', { error: err instanceof Error ? err.message : String(err) });
2121
+ return c.json({ error: 'Function execution failed' }, 500);
2122
+ }
2123
+ };
2124
+ app.get(`${basePath}/swaig`, authMw, handleSwaig);
2125
+ app.post(`${basePath}/swaig`, authMw, handleSwaig);
2126
+ // Post-prompt handler
2127
+ const handlePostPrompt = async (c) => {
2128
+ let reqLog = this.log.bind({ endpoint: `${basePath}/post_prompt` });
2129
+ reqLog.debug('endpoint_called');
2130
+ let body = {};
2131
+ try {
2132
+ body = await c.req.json();
2133
+ }
2134
+ catch { /* empty */ }
2135
+ const callId = body['call_id'] || undefined;
2136
+ if (callId)
2137
+ reqLog = reqLog.bind({ call_id: callId });
2138
+ reqLog.info('post_prompt_received');
2139
+ const summary = this.findSummary(body);
2140
+ await this.onSummary(summary, body);
2141
+ return c.json({ ok: true });
2142
+ };
2143
+ app.get(`${basePath}/post_prompt`, authMw, handlePostPrompt);
2144
+ app.post(`${basePath}/post_prompt`, authMw, handlePostPrompt);
2145
+ // Debug events handler
2146
+ const handleDebugEvents = async (c) => {
2147
+ const reqLog = this.log.bind({ endpoint: `${basePath}/debug_events` });
2148
+ reqLog.debug('endpoint_called');
2149
+ let body = {};
2150
+ try {
2151
+ body = await c.req.json();
2152
+ }
2153
+ catch { /* empty */ }
2154
+ reqLog.debug('debug_event_received', body);
2155
+ await this.onDebugEvent(body);
2156
+ return c.json({ ok: true });
2157
+ };
2158
+ app.post(`${basePath}/debug_events`, authMw, handleDebugEvents);
2159
+ // MCP server endpoint (JSON-RPC 2.0)
2160
+ if (this._mcpServerEnabled) {
2161
+ app.post(`${basePath}/mcp`, async (c) => {
2162
+ let body = {};
2163
+ try {
2164
+ body = await c.req.json();
2165
+ }
2166
+ catch {
2167
+ return c.json({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
2168
+ }
2169
+ const result = await this.handleMcpRequest(body);
2170
+ return c.json(result);
2171
+ });
2172
+ }
2173
+ // Post-prompt override endpoint (enabled via constructor option)
2174
+ if (this._enablePostPromptOverride) {
2175
+ const handlePostPromptOverride = async (c) => {
2176
+ const reqLog = this.log.bind({ endpoint: `${basePath}/post_prompt_override` });
2177
+ reqLog.debug('endpoint_called');
2178
+ let body = {};
2179
+ try {
2180
+ body = await c.req.json();
2181
+ }
2182
+ catch { /* empty */ }
2183
+ const newPostPrompt = body['post_prompt'];
2184
+ if (newPostPrompt !== undefined) {
2185
+ this.setPostPrompt(newPostPrompt);
2186
+ reqLog.info('post_prompt_overridden');
2187
+ }
2188
+ return c.json({ ok: true });
2189
+ };
2190
+ app.post(`${basePath}/post_prompt_override`, authMw, handlePostPromptOverride);
2191
+ }
2192
+ // Check-for-input endpoint (enabled via constructor option)
2193
+ if (this._checkForInputOverride) {
2194
+ const handleCheckForInput = async (c) => {
2195
+ const reqLog = this.log.bind({ endpoint: `${basePath}/check_for_input` });
2196
+ reqLog.debug('endpoint_called');
2197
+ let body = {};
2198
+ try {
2199
+ body = await c.req.json();
2200
+ }
2201
+ catch { /* empty */ }
2202
+ reqLog.info('check_for_input_received');
2203
+ return c.json({ ok: true, received: body });
2204
+ };
2205
+ app.get(`${basePath}/check_for_input`, authMw, handleCheckForInput);
2206
+ app.post(`${basePath}/check_for_input`, authMw, handleCheckForInput);
2207
+ }
2208
+ // Routing callbacks (registered via registerRoutingCallback)
2209
+ for (const [callbackPath, callback] of this._routingCallbacks) {
2210
+ const fullPath = basePath ? `${basePath}${callbackPath}` : callbackPath;
2211
+ const handleRouting = async (c) => {
2212
+ const reqLog = this.log.bind({ endpoint: fullPath });
2213
+ reqLog.debug('routing_callback_called');
2214
+ let body = {};
2215
+ try {
2216
+ body = await c.req.json();
2217
+ }
2218
+ catch { /* GET or no body */ }
2219
+ try {
2220
+ const route = await callback(body);
2221
+ if (route) {
2222
+ reqLog.info('routing_callback_redirect', { route });
2223
+ return c.json({ action: 'redirect', route });
2224
+ }
2225
+ // No redirect — return SWML for this agent
2226
+ this.detectProxyFromRequest(c);
2227
+ const swml = this.renderSwml();
2228
+ return c.json(JSON.parse(swml));
2229
+ }
2230
+ catch (err) {
2231
+ reqLog.error('routing_callback_error', { error: err instanceof Error ? err.message : String(err) });
2232
+ return c.json({ error: 'Routing callback failed' }, 500);
2233
+ }
2234
+ };
2235
+ app.get(fullPath, authMw, handleRouting);
2236
+ app.post(fullPath, authMw, handleRouting);
2237
+ }
2238
+ // Health / Ready
2239
+ app.get(`${basePath}/health`, (c) => c.json({ status: 'ok' }));
2240
+ app.get(`${basePath}/ready`, (c) => c.json({ status: 'ready' }));
2241
+ this._app = app;
2242
+ return app;
2243
+ }
2244
+ /**
2245
+ * Return this agent's Hono app for mounting as a sub-router in an AgentServer.
2246
+ * @returns The Hono application instance.
2247
+ */
2248
+ asRouter() {
2249
+ return this.getApp();
2250
+ }
2251
+ /**
2252
+ * Start the HTTP server and begin listening for requests.
2253
+ *
2254
+ * Uses `@hono/node-server` under the hood. When run in CLI mode
2255
+ * (`SWAIG_CLI_MODE=true`, set automatically by `npx swaig-test`), this is a
2256
+ * no-op so agent config can be inspected without starting a server.
2257
+ *
2258
+ * @param opts - Optional host/port overrides. Defaults to the values provided
2259
+ * in the constructor options or the `PORT` environment variable.
2260
+ * @returns A promise that resolves once the server has begun listening.
2261
+ *
2262
+ * @example
2263
+ * ```ts
2264
+ * const agent = new AgentBase({ name: 'demo', port: 3000 });
2265
+ * await agent.serve();
2266
+ * // Or override at runtime:
2267
+ * await agent.serve({ port: 8080, host: '127.0.0.1' });
2268
+ * ```
2269
+ */
2270
+ async serve(opts) {
2271
+ // When loaded by the CLI tool, skip server startup — only the agent config is needed.
2272
+ if (process.env['SWAIG_CLI_MODE'] === 'true')
2273
+ return;
2274
+ const host = opts?.host ?? this.host;
2275
+ const port = opts?.port ?? this.port;
2276
+ const { serve: honoServe } = await import('@hono/node-server');
2277
+ const app = this.getApp();
2278
+ const listenUrl = `http://${host}:${port}${this.route}`;
2279
+ this.log.info(`Agent '${this.name}' running at ${listenUrl}`);
2280
+ this.log.info(`Auth: ${this.basicAuthCreds[0]}:**** (source: ${this.basicAuthSource})`);
2281
+ if (this._proxyUrlBase) {
2282
+ this.log.info(`Proxy URL: ${redactUrl(this._proxyUrlBase)}`);
2283
+ }
2284
+ honoServe({ fetch: app.fetch, port, hostname: host });
2285
+ }
2286
+ /**
2287
+ * Alias for {@link serve}. Starts the HTTP server.
2288
+ * @param opts - Optional host and port overrides.
2289
+ * @returns A promise that resolves once the server is running.
2290
+ */
2291
+ async run(opts) {
2292
+ return this.serve(opts);
2293
+ }
2294
+ /**
2295
+ * Handle a single serverless invocation (AWS Lambda, Google Cloud Functions, Azure Functions, or CGI).
2296
+ *
2297
+ * Matches Python `run(event, context)` when executed in a serverless environment. Python's
2298
+ * `run()` auto-detects the platform via `get_execution_mode()` and dispatches accordingly;
2299
+ * in TypeScript the serverless path is an **explicit** method so that `run()` keeps its
2300
+ * HTTP-server semantics and callers opt in to serverless dispatch deliberately.
2301
+ *
2302
+ * Platform detection follows the same environment-variable heuristics as Python's
2303
+ * `ServerlessMixin`: `AWS_LAMBDA_FUNCTION_NAME` → Lambda, `K_SERVICE` → GCF,
2304
+ * `FUNCTIONS_WORKER_RUNTIME` → Azure, `GATEWAY_INTERFACE` → CGI.
2305
+ *
2306
+ * Usage in a Lambda handler file:
2307
+ * ```ts
2308
+ * export const handler = (event: any, context: any) => agent.runServerless(event, context);
2309
+ * ```
2310
+ *
2311
+ * @param event - The serverless event payload (Lambda event, GCF request body, etc.).
2312
+ * @param context - The serverless context object (Lambda context, Azure context, etc.).
2313
+ * @param platform - Optional platform override; defaults to 'auto' (environment detection).
2314
+ * @returns The normalized serverless response object.
2315
+ */
2316
+ async runServerless(event, context, platform) {
2317
+ void context; // context is available for subclasses; not used in base routing
2318
+ const adapter = new ServerlessAdapter(platform ?? 'auto');
2319
+ const app = this.getApp();
2320
+ // Wrap Hono's fetch (which returns `Response | Promise<Response>`) into a plain
2321
+ // `Promise<Response>` so it satisfies ServerlessAdapter.handleRequest's type constraint.
2322
+ const fetchFn = (req) => Promise.resolve(app.fetch(req));
2323
+ return adapter.handleRequest({ fetch: fetchFn }, event);
2324
+ }
2325
+ // ── Graceful shutdown ─────────────────────────────────────────────
2326
+ static _shutdownRegistered = false;
2327
+ /**
2328
+ * Register process signal handlers for clean Kubernetes/Docker shutdown.
2329
+ * Handles SIGTERM and SIGINT, waits for a timeout, then exits.
2330
+ * @param opts - Optional timeout in milliseconds (default 5000).
2331
+ */
2332
+ static setupGracefulShutdown(opts) {
2333
+ if (AgentBase._shutdownRegistered)
2334
+ return;
2335
+ AgentBase._shutdownRegistered = true;
2336
+ const timeout = opts?.timeout ?? 5000;
2337
+ const log = getLogger('GracefulShutdown');
2338
+ const handler = (signal) => {
2339
+ log.info(`Received ${signal}, shutting down in ${timeout}ms...`);
2340
+ setTimeout(() => {
2341
+ log.info('Shutdown complete.');
2342
+ process.exit(0);
2343
+ }, timeout);
2344
+ };
2345
+ process.on('SIGTERM', () => handler('SIGTERM'));
2346
+ process.on('SIGINT', () => handler('SIGINT'));
2347
+ }
2348
+ // ── Helpers ─────────────────────────────────────────────────────────
2349
+ findSummary(body) {
2350
+ if (!body)
2351
+ return null;
2352
+ if (body['summary'])
2353
+ return body['summary'];
2354
+ const ppd = body['post_prompt_data'];
2355
+ if (ppd) {
2356
+ if (Array.isArray(ppd['parsed']) && ppd['parsed'].length)
2357
+ return ppd['parsed'][0];
2358
+ if (ppd['raw']) {
2359
+ try {
2360
+ return JSON.parse(ppd['raw']);
2361
+ }
2362
+ catch {
2363
+ return ppd['raw'];
2364
+ }
2365
+ }
2366
+ }
2367
+ return null;
2368
+ }
2369
+ getBasicAuthCredentials(includeSource) {
2370
+ if (includeSource)
2371
+ return [...this.basicAuthCreds, this.basicAuthSource];
2372
+ return this.basicAuthCreds;
2373
+ }
2374
+ }
2375
+ //# sourceMappingURL=AgentBase.js.map