@signalwire/sdk 2.0.1 → 2.0.3

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