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