@signalwire/sdk 2.0.5 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (656) hide show
  1. package/CHANGELOG.md +785 -0
  2. package/LICENSE +21 -0
  3. package/README.md +163 -68
  4. package/dist/AGENTS.md +13 -0
  5. package/dist/AgentBase.d.ts +481 -126
  6. package/dist/AgentBase.js +1502 -438
  7. package/dist/AgentBase.js.map +1 -1
  8. package/dist/AgentServer.d.ts +21 -0
  9. package/dist/AgentServer.js +154 -47
  10. package/dist/AgentServer.js.map +1 -1
  11. package/dist/AuthHandler.d.ts +14 -2
  12. package/dist/AuthHandler.js +7 -2
  13. package/dist/AuthHandler.js.map +1 -1
  14. package/dist/ConfigLoader.d.ts +5 -13
  15. package/dist/ConfigLoader.js +15 -29
  16. package/dist/ConfigLoader.js.map +1 -1
  17. package/dist/ContextBuilder.d.ts +202 -9
  18. package/dist/ContextBuilder.js +219 -36
  19. package/dist/ContextBuilder.js.map +1 -1
  20. package/dist/DataMap.d.ts +158 -45
  21. package/dist/DataMap.js +167 -52
  22. package/dist/DataMap.js.map +1 -1
  23. package/dist/FunctionResult.d.ts +277 -83
  24. package/dist/FunctionResult.js +444 -116
  25. package/dist/FunctionResult.js.map +1 -1
  26. package/dist/Logger.d.ts +30 -5
  27. package/dist/Logger.js +77 -19
  28. package/dist/Logger.js.map +1 -1
  29. package/dist/POM/PromptObjectModel.d.ts +12 -1
  30. package/dist/POM/PromptObjectModel.js +25 -9
  31. package/dist/POM/PromptObjectModel.js.map +1 -1
  32. package/dist/ParameterSchema.d.ts +306 -0
  33. package/dist/ParameterSchema.js +251 -0
  34. package/dist/ParameterSchema.js.map +1 -0
  35. package/dist/PlatformContracts.d.ts +21 -0
  36. package/dist/PlatformContracts.generated.d.ts +109 -0
  37. package/dist/PlatformContracts.generated.js +8 -0
  38. package/dist/PlatformContracts.generated.js.map +1 -0
  39. package/dist/PlatformContracts.js +2 -0
  40. package/dist/PlatformContracts.js.map +1 -0
  41. package/dist/PomBuilder.d.ts +18 -0
  42. package/dist/PomBuilder.js +53 -3
  43. package/dist/PomBuilder.js.map +1 -1
  44. package/dist/PostPrompt.d.ts +110 -0
  45. package/dist/PostPrompt.js +204 -0
  46. package/dist/PostPrompt.js.map +1 -0
  47. package/dist/PromptManager.d.ts +22 -1
  48. package/dist/PromptManager.js +28 -1
  49. package/dist/PromptManager.js.map +1 -1
  50. package/dist/PublicFetch.d.ts +132 -0
  51. package/dist/PublicFetch.js +311 -0
  52. package/dist/PublicFetch.js.map +1 -0
  53. package/dist/RobotsTxt.d.ts +41 -0
  54. package/dist/RobotsTxt.js +152 -0
  55. package/dist/RobotsTxt.js.map +1 -0
  56. package/dist/SWMLHandler.js.map +1 -1
  57. package/dist/SWMLService.d.ts +158 -58
  58. package/dist/SWMLService.js +435 -127
  59. package/dist/SWMLService.js.map +1 -1
  60. package/dist/SchemaUtils.d.ts +115 -2
  61. package/dist/SchemaUtils.js +444 -12
  62. package/dist/SchemaUtils.js.map +1 -1
  63. package/dist/SecurityUtils.d.ts +49 -9
  64. package/dist/SecurityUtils.js +153 -51
  65. package/dist/SecurityUtils.js.map +1 -1
  66. package/dist/ServerlessAdapter.d.ts +156 -7
  67. package/dist/ServerlessAdapter.js +399 -42
  68. package/dist/ServerlessAdapter.js.map +1 -1
  69. package/dist/SessionManager.d.ts +11 -2
  70. package/dist/SessionManager.js +50 -18
  71. package/dist/SessionManager.js.map +1 -1
  72. package/dist/SslConfig.d.ts +2 -1
  73. package/dist/SslConfig.js +4 -1
  74. package/dist/SslConfig.js.map +1 -1
  75. package/dist/SwaigActions.generated.d.ts +23 -0
  76. package/dist/SwaigActions.generated.js +8 -0
  77. package/dist/SwaigActions.generated.js.map +1 -0
  78. package/dist/SwaigContracts.d.ts +15 -0
  79. package/dist/SwaigContracts.generated.d.ts +264 -0
  80. package/dist/SwaigContracts.generated.js +12 -0
  81. package/dist/SwaigContracts.generated.js.map +1 -0
  82. package/dist/SwaigContracts.js +2 -0
  83. package/dist/SwaigContracts.js.map +1 -0
  84. package/dist/SwaigFunction.d.ts +110 -4
  85. package/dist/SwaigFunction.js +151 -19
  86. package/dist/SwaigFunction.js.map +1 -1
  87. package/dist/SwmlBuilder.d.ts +68 -19
  88. package/dist/SwmlBuilder.js +74 -38
  89. package/dist/SwmlBuilder.js.map +1 -1
  90. package/dist/SwmlVerbMethods.generated.d.ts +41 -4
  91. package/dist/SwmlVerbMethods.generated.js +1 -1
  92. package/dist/TypeInference.d.ts +39 -3
  93. package/dist/TypeInference.js +256 -16
  94. package/dist/TypeInference.js.map +1 -1
  95. package/dist/WebService.d.ts +79 -11
  96. package/dist/WebService.js +320 -109
  97. package/dist/WebService.js.map +1 -1
  98. package/dist/WebhookMiddleware.d.ts +119 -0
  99. package/dist/WebhookMiddleware.js +271 -0
  100. package/dist/WebhookMiddleware.js.map +1 -0
  101. package/dist/WebhookValidator.d.ts +92 -0
  102. package/dist/WebhookValidator.js +409 -0
  103. package/dist/WebhookValidator.js.map +1 -0
  104. package/dist/agents/BedrockAgent.d.ts +162 -0
  105. package/dist/agents/BedrockAgent.js +323 -0
  106. package/dist/agents/BedrockAgent.js.map +1 -0
  107. package/dist/ai-chat/AIChatClient.d.ts +316 -0
  108. package/dist/ai-chat/AIChatClient.js +535 -0
  109. package/dist/ai-chat/AIChatClient.js.map +1 -0
  110. package/dist/ai-chat/ChatGateway.d.ts +408 -0
  111. package/dist/ai-chat/ChatGateway.js +747 -0
  112. package/dist/ai-chat/ChatGateway.js.map +1 -0
  113. package/dist/ai-chat/HandoffRouter.d.ts +282 -0
  114. package/dist/ai-chat/HandoffRouter.js +518 -0
  115. package/dist/ai-chat/HandoffRouter.js.map +1 -0
  116. package/dist/ai-chat/index.d.ts +12 -0
  117. package/dist/ai-chat/index.js +10 -0
  118. package/dist/ai-chat/index.js.map +1 -0
  119. package/dist/capabilities.d.ts +64 -0
  120. package/dist/capabilities.js +95 -0
  121. package/dist/capabilities.js.map +1 -0
  122. package/dist/cli/agent-loader.d.ts +32 -6
  123. package/dist/cli/agent-loader.js +92 -33
  124. package/dist/cli/agent-loader.js.map +1 -1
  125. package/dist/cli/datamap-exec.d.ts +175 -0
  126. package/dist/cli/datamap-exec.js +1284 -0
  127. package/dist/cli/datamap-exec.js.map +1 -0
  128. package/dist/cli/function-args.d.ts +40 -0
  129. package/dist/cli/function-args.js +146 -0
  130. package/dist/cli/function-args.js.map +1 -0
  131. package/dist/cli/simulation.d.ts +99 -0
  132. package/dist/cli/simulation.js +490 -0
  133. package/dist/cli/simulation.js.map +1 -0
  134. package/dist/cli/swaig-test.d.ts +12 -25
  135. package/dist/cli/swaig-test.js +935 -371
  136. package/dist/cli/swaig-test.js.map +1 -1
  137. package/dist/cli/tsdocs/agentsNote.d.ts +30 -0
  138. package/dist/cli/tsdocs/agentsNote.js +92 -0
  139. package/dist/cli/tsdocs/agentsNote.js.map +1 -0
  140. package/dist/cli/tsdocs/api-index.json +1 -0
  141. package/dist/cli/tsdocs/api.d.ts +91 -0
  142. package/dist/cli/tsdocs/api.js +372 -0
  143. package/dist/cli/tsdocs/api.js.map +1 -0
  144. package/dist/cli/tsdocs/apiTypes.d.ts +64 -0
  145. package/dist/cli/tsdocs/apiTypes.js +7 -0
  146. package/dist/cli/tsdocs/apiTypes.js.map +1 -0
  147. package/dist/cli/tsdocs/bin.d.ts +6 -0
  148. package/dist/cli/tsdocs/bin.js +23 -0
  149. package/dist/cli/tsdocs/bin.js.map +1 -0
  150. package/dist/cli/tsdocs/files.d.ts +108 -0
  151. package/dist/cli/tsdocs/files.js +287 -0
  152. package/dist/cli/tsdocs/files.js.map +1 -0
  153. package/dist/cli/tsdocs/index.d.ts +28 -0
  154. package/dist/cli/tsdocs/index.js +307 -0
  155. package/dist/cli/tsdocs/index.js.map +1 -0
  156. package/dist/cli/tsdocs/live.d.ts +41 -0
  157. package/dist/cli/tsdocs/live.js +202 -0
  158. package/dist/cli/tsdocs/live.js.map +1 -0
  159. package/dist/cli/tsdocs/locate.d.ts +51 -0
  160. package/dist/cli/tsdocs/locate.js +75 -0
  161. package/dist/cli/tsdocs/locate.js.map +1 -0
  162. package/dist/cli/tsdocs/render.d.ts +75 -0
  163. package/dist/cli/tsdocs/render.js +323 -0
  164. package/dist/cli/tsdocs/render.js.map +1 -0
  165. package/dist/cli/tsdocs/topics.d.ts +43 -0
  166. package/dist/cli/tsdocs/topics.js +916 -0
  167. package/dist/cli/tsdocs/topics.js.map +1 -0
  168. package/dist/index.d.ts +47 -68
  169. package/dist/index.js +44 -73
  170. package/dist/index.js.map +1 -1
  171. package/dist/livewire/index.d.ts +229 -155
  172. package/dist/livewire/index.js +298 -195
  173. package/dist/livewire/index.js.map +1 -1
  174. package/dist/llms.txt +65 -0
  175. package/dist/prefabs/CallSessionStore.d.ts +52 -0
  176. package/dist/prefabs/CallSessionStore.js +72 -0
  177. package/dist/prefabs/CallSessionStore.js.map +1 -0
  178. package/dist/prefabs/ConciergeAgent.d.ts +13 -1
  179. package/dist/prefabs/ConciergeAgent.js +36 -31
  180. package/dist/prefabs/ConciergeAgent.js.map +1 -1
  181. package/dist/prefabs/FAQBotAgent.d.ts +9 -1
  182. package/dist/prefabs/FAQBotAgent.js +113 -47
  183. package/dist/prefabs/FAQBotAgent.js.map +1 -1
  184. package/dist/prefabs/InfoGathererAgent.d.ts +22 -3
  185. package/dist/prefabs/InfoGathererAgent.js +67 -58
  186. package/dist/prefabs/InfoGathererAgent.js.map +1 -1
  187. package/dist/prefabs/ReceptionistAgent.d.ts +16 -5
  188. package/dist/prefabs/ReceptionistAgent.js +39 -31
  189. package/dist/prefabs/ReceptionistAgent.js.map +1 -1
  190. package/dist/prefabs/SurveyAgent.d.ts +22 -4
  191. package/dist/prefabs/SurveyAgent.js +84 -68
  192. package/dist/prefabs/SurveyAgent.js.map +1 -1
  193. package/dist/relay/Action.d.ts +44 -21
  194. package/dist/relay/Action.js +75 -17
  195. package/dist/relay/Action.js.map +1 -1
  196. package/dist/relay/Call.d.ts +312 -47
  197. package/dist/relay/Call.js +369 -18
  198. package/dist/relay/Call.js.map +1 -1
  199. package/dist/relay/Deferred.js.map +1 -1
  200. package/dist/relay/Message.d.ts +26 -5
  201. package/dist/relay/Message.js +36 -6
  202. package/dist/relay/Message.js.map +1 -1
  203. package/dist/relay/RelayClient.d.ts +44 -17
  204. package/dist/relay/RelayClient.js +175 -65
  205. package/dist/relay/RelayClient.js.map +1 -1
  206. package/dist/relay/RelayError.d.ts +14 -0
  207. package/dist/relay/RelayError.js +15 -0
  208. package/dist/relay/RelayError.js.map +1 -1
  209. package/dist/relay/RelayEvent.d.ts +96 -65
  210. package/dist/relay/RelayEvent.js +85 -56
  211. package/dist/relay/RelayEvent.js.map +1 -1
  212. package/dist/relay/closedSets.d.ts +111 -0
  213. package/dist/relay/closedSets.js +83 -0
  214. package/dist/relay/closedSets.js.map +1 -0
  215. package/dist/relay/index.d.ts +3 -1
  216. package/dist/relay/index.js +1 -0
  217. package/dist/relay/index.js.map +1 -1
  218. package/dist/relay/normalize.js.map +1 -1
  219. package/dist/relay/protocol.types.generated.d.ts +1195 -0
  220. package/dist/relay/protocol.types.generated.js +8 -0
  221. package/dist/relay/protocol.types.generated.js.map +1 -0
  222. package/dist/relay/types.d.ts +73 -42
  223. package/dist/rest/HttpClient.d.ts +36 -8
  224. package/dist/rest/HttpClient.js +233 -40
  225. package/dist/rest/HttpClient.js.map +1 -1
  226. package/dist/rest/RequestOptions.d.ts +110 -0
  227. package/dist/rest/RequestOptions.js +113 -0
  228. package/dist/rest/RequestOptions.js.map +1 -0
  229. package/dist/rest/RestError.d.ts +52 -6
  230. package/dist/rest/RestError.js +89 -5
  231. package/dist/rest/RestError.js.map +1 -1
  232. package/dist/rest/base/CrudResource.d.ts +16 -26
  233. package/dist/rest/base/CrudResource.js +19 -33
  234. package/dist/rest/base/CrudResource.js.map +1 -1
  235. package/dist/rest/base/CrudWithAddresses.d.ts +3 -2
  236. package/dist/rest/base/CrudWithAddresses.js +2 -2
  237. package/dist/rest/base/CrudWithAddresses.js.map +1 -1
  238. package/dist/rest/base/FabricResource.d.ts +15 -0
  239. package/dist/rest/base/FabricResource.js +16 -0
  240. package/dist/rest/base/FabricResource.js.map +1 -0
  241. package/dist/rest/base/ReadResource.d.ts +62 -0
  242. package/dist/rest/base/ReadResource.js +69 -0
  243. package/dist/rest/base/ReadResource.js.map +1 -0
  244. package/dist/rest/callHandler.d.ts +5 -2
  245. package/dist/rest/callHandler.js +4 -1
  246. package/dist/rest/callHandler.js.map +1 -1
  247. package/dist/rest/index.d.ts +18 -77
  248. package/dist/rest/index.js +47 -120
  249. package/dist/rest/index.js.map +1 -1
  250. package/dist/rest/namespaces/_client_tree_generated.d.ts +103 -0
  251. package/dist/rest/namespaces/_client_tree_generated.js +171 -0
  252. package/dist/rest/namespaces/_client_tree_generated.js.map +1 -0
  253. package/dist/rest/namespaces/addresses.d.ts +3 -42
  254. package/dist/rest/namespaces/addresses.js +3 -50
  255. package/dist/rest/namespaces/addresses.js.map +1 -1
  256. package/dist/rest/namespaces/calling.d.ts +6 -378
  257. package/dist/rest/namespaces/calling.js +6 -473
  258. package/dist/rest/namespaces/calling.js.map +1 -1
  259. package/dist/rest/namespaces/calling.resources.generated.d.ts +165 -0
  260. package/dist/rest/namespaces/calling.resources.generated.js +477 -0
  261. package/dist/rest/namespaces/calling.resources.generated.js.map +1 -0
  262. package/dist/rest/namespaces/calling.types.generated.d.ts +2917 -0
  263. package/dist/rest/namespaces/calling.types.generated.js +8 -0
  264. package/dist/rest/namespaces/calling.types.generated.js.map +1 -0
  265. package/dist/rest/namespaces/chat.d.ts +4 -18
  266. package/dist/rest/namespaces/chat.js +4 -21
  267. package/dist/rest/namespaces/chat.js.map +1 -1
  268. package/dist/rest/namespaces/chat.resources.generated.d.ts +12 -0
  269. package/dist/rest/namespaces/chat.resources.generated.js +29 -0
  270. package/dist/rest/namespaces/chat.resources.generated.js.map +1 -0
  271. package/dist/rest/namespaces/chat.types.generated.d.ts +56 -0
  272. package/dist/rest/namespaces/chat.types.generated.js +8 -0
  273. package/dist/rest/namespaces/chat.types.generated.js.map +1 -0
  274. package/dist/rest/namespaces/datasphere.d.ts +6 -62
  275. package/dist/rest/namespaces/datasphere.js +6 -72
  276. package/dist/rest/namespaces/datasphere.js.map +1 -1
  277. package/dist/rest/namespaces/datasphere.resources.generated.d.ts +25 -0
  278. package/dist/rest/namespaces/datasphere.resources.generated.js +50 -0
  279. package/dist/rest/namespaces/datasphere.resources.generated.js.map +1 -0
  280. package/dist/rest/namespaces/datasphere.types.generated.d.ts +180 -0
  281. package/dist/rest/namespaces/datasphere.types.generated.js +8 -0
  282. package/dist/rest/namespaces/datasphere.types.generated.js.map +1 -0
  283. package/dist/rest/namespaces/fabric.d.ts +11 -327
  284. package/dist/rest/namespaces/fabric.js +14 -439
  285. package/dist/rest/namespaces/fabric.js.map +1 -1
  286. package/dist/rest/namespaces/fabric.resources.generated.d.ts +195 -0
  287. package/dist/rest/namespaces/fabric.resources.generated.js +399 -0
  288. package/dist/rest/namespaces/fabric.resources.generated.js.map +1 -0
  289. package/dist/rest/namespaces/fabric.types.generated.d.ts +4557 -0
  290. package/dist/rest/namespaces/fabric.types.generated.js +8 -0
  291. package/dist/rest/namespaces/fabric.types.generated.js.map +1 -0
  292. package/dist/rest/namespaces/fax.resources.generated.d.ts +6 -0
  293. package/dist/rest/namespaces/fax.resources.generated.js +14 -0
  294. package/dist/rest/namespaces/fax.resources.generated.js.map +1 -0
  295. package/dist/rest/namespaces/fax.types.generated.d.ts +131 -0
  296. package/dist/rest/namespaces/fax.types.generated.js +8 -0
  297. package/dist/rest/namespaces/fax.types.generated.js.map +1 -0
  298. package/dist/rest/namespaces/imported-numbers.d.ts +3 -18
  299. package/dist/rest/namespaces/imported-numbers.js +3 -21
  300. package/dist/rest/namespaces/imported-numbers.js.map +1 -1
  301. package/dist/rest/namespaces/logs.d.ts +10 -101
  302. package/dist/rest/namespaces/logs.js +10 -128
  303. package/dist/rest/namespaces/logs.js.map +1 -1
  304. package/dist/rest/namespaces/logs.resources.generated.d.ts +9 -0
  305. package/dist/rest/namespaces/logs.resources.generated.js +17 -0
  306. package/dist/rest/namespaces/logs.resources.generated.js.map +1 -0
  307. package/dist/rest/namespaces/logs.types.generated.d.ts +131 -0
  308. package/dist/rest/namespaces/logs.types.generated.js +8 -0
  309. package/dist/rest/namespaces/logs.types.generated.js.map +1 -0
  310. package/dist/rest/namespaces/lookup.d.ts +3 -25
  311. package/dist/rest/namespaces/lookup.js +3 -27
  312. package/dist/rest/namespaces/lookup.js.map +1 -1
  313. package/dist/rest/namespaces/message.resources.generated.d.ts +6 -0
  314. package/dist/rest/namespaces/message.resources.generated.js +14 -0
  315. package/dist/rest/namespaces/message.resources.generated.js.map +1 -0
  316. package/dist/rest/namespaces/message.types.generated.d.ts +122 -0
  317. package/dist/rest/namespaces/message.types.generated.js +8 -0
  318. package/dist/rest/namespaces/message.types.generated.js.map +1 -0
  319. package/dist/rest/namespaces/messages.resources.generated.d.ts +18 -0
  320. package/dist/rest/namespaces/messages.resources.generated.js +44 -0
  321. package/dist/rest/namespaces/messages.resources.generated.js.map +1 -0
  322. package/dist/rest/namespaces/messages.types.generated.d.ts +99 -0
  323. package/dist/rest/namespaces/messages.types.generated.js +8 -0
  324. package/dist/rest/namespaces/messages.types.generated.js.map +1 -0
  325. package/dist/rest/namespaces/mfa.d.ts +3 -42
  326. package/dist/rest/namespaces/mfa.js +3 -49
  327. package/dist/rest/namespaces/mfa.js.map +1 -1
  328. package/dist/rest/namespaces/number-groups.d.ts +3 -45
  329. package/dist/rest/namespaces/number-groups.js +3 -53
  330. package/dist/rest/namespaces/number-groups.js.map +1 -1
  331. package/dist/rest/namespaces/phone-numbers.d.ts +8 -196
  332. package/dist/rest/namespaces/phone-numbers.js +8 -230
  333. package/dist/rest/namespaces/phone-numbers.js.map +1 -1
  334. package/dist/rest/namespaces/project.d.ts +6 -42
  335. package/dist/rest/namespaces/project.js +6 -51
  336. package/dist/rest/namespaces/project.js.map +1 -1
  337. package/dist/rest/namespaces/project.resources.generated.d.ts +17 -0
  338. package/dist/rest/namespaces/project.resources.generated.js +44 -0
  339. package/dist/rest/namespaces/project.resources.generated.js.map +1 -0
  340. package/dist/rest/namespaces/project.types.generated.d.ts +58 -0
  341. package/dist/rest/namespaces/project.types.generated.js +8 -0
  342. package/dist/rest/namespaces/project.types.generated.js.map +1 -0
  343. package/dist/rest/namespaces/projects.resources.generated.d.ts +12 -0
  344. package/dist/rest/namespaces/projects.resources.generated.js +25 -0
  345. package/dist/rest/namespaces/projects.resources.generated.js.map +1 -0
  346. package/dist/rest/namespaces/projects.types.generated.d.ts +77 -0
  347. package/dist/rest/namespaces/projects.types.generated.js +8 -0
  348. package/dist/rest/namespaces/projects.types.generated.js.map +1 -0
  349. package/dist/rest/namespaces/pubsub.d.ts +4 -18
  350. package/dist/rest/namespaces/pubsub.js +4 -21
  351. package/dist/rest/namespaces/pubsub.js.map +1 -1
  352. package/dist/rest/namespaces/pubsub.resources.generated.d.ts +12 -0
  353. package/dist/rest/namespaces/pubsub.resources.generated.js +29 -0
  354. package/dist/rest/namespaces/pubsub.resources.generated.js.map +1 -0
  355. package/dist/rest/namespaces/pubsub.types.generated.d.ts +60 -0
  356. package/dist/rest/namespaces/pubsub.types.generated.js +8 -0
  357. package/dist/rest/namespaces/pubsub.types.generated.js.map +1 -0
  358. package/dist/rest/namespaces/queues.d.ts +3 -38
  359. package/dist/rest/namespaces/queues.js +3 -44
  360. package/dist/rest/namespaces/queues.js.map +1 -1
  361. package/dist/rest/namespaces/recordings.d.ts +3 -34
  362. package/dist/rest/namespaces/recordings.js +3 -40
  363. package/dist/rest/namespaces/recordings.js.map +1 -1
  364. package/dist/rest/namespaces/registry.d.ts +6 -137
  365. package/dist/rest/namespaces/registry.js +6 -173
  366. package/dist/rest/namespaces/registry.js.map +1 -1
  367. package/dist/rest/namespaces/relay-rest.resources.generated.d.ts +168 -0
  368. package/dist/rest/namespaces/relay-rest.resources.generated.js +430 -0
  369. package/dist/rest/namespaces/relay-rest.resources.generated.js.map +1 -0
  370. package/dist/rest/namespaces/relay-rest.types.generated.d.ts +1906 -0
  371. package/dist/rest/namespaces/relay-rest.types.generated.js +8 -0
  372. package/dist/rest/namespaces/relay-rest.types.generated.js.map +1 -0
  373. package/dist/rest/namespaces/short-codes.d.ts +3 -35
  374. package/dist/rest/namespaces/short-codes.js +3 -41
  375. package/dist/rest/namespaces/short-codes.js.map +1 -1
  376. package/dist/rest/namespaces/sip-profile.d.ts +3 -24
  377. package/dist/rest/namespaces/sip-profile.js +3 -29
  378. package/dist/rest/namespaces/sip-profile.js.map +1 -1
  379. package/dist/rest/namespaces/verified-callers.d.ts +3 -29
  380. package/dist/rest/namespaces/verified-callers.js +3 -34
  381. package/dist/rest/namespaces/verified-callers.js.map +1 -1
  382. package/dist/rest/namespaces/video.d.ts +10 -227
  383. package/dist/rest/namespaces/video.js +10 -288
  384. package/dist/rest/namespaces/video.js.map +1 -1
  385. package/dist/rest/namespaces/video.resources.generated.d.ts +81 -0
  386. package/dist/rest/namespaces/video.resources.generated.js +171 -0
  387. package/dist/rest/namespaces/video.resources.generated.js.map +1 -0
  388. package/dist/rest/namespaces/video.types.generated.d.ts +771 -0
  389. package/dist/rest/namespaces/video.types.generated.js +8 -0
  390. package/dist/rest/namespaces/video.types.generated.js.map +1 -0
  391. package/dist/rest/namespaces/voice.resources.generated.d.ts +9 -0
  392. package/dist/rest/namespaces/voice.resources.generated.js +17 -0
  393. package/dist/rest/namespaces/voice.resources.generated.js.map +1 -0
  394. package/dist/rest/namespaces/voice.types.generated.d.ts +214 -0
  395. package/dist/rest/namespaces/voice.types.generated.js +8 -0
  396. package/dist/rest/namespaces/voice.types.generated.js.map +1 -0
  397. package/dist/rest/pagination.d.ts +5 -1
  398. package/dist/rest/pagination.js +40 -20
  399. package/dist/rest/pagination.js.map +1 -1
  400. package/dist/rest/types.d.ts +21 -3
  401. package/dist/schema.json +299 -98
  402. package/dist/skills/SkillBase.d.ts +97 -20
  403. package/dist/skills/SkillBase.js +100 -17
  404. package/dist/skills/SkillBase.js.map +1 -1
  405. package/dist/skills/SkillManager.d.ts +66 -13
  406. package/dist/skills/SkillManager.js +101 -20
  407. package/dist/skills/SkillManager.js.map +1 -1
  408. package/dist/skills/SkillName.d.ts +44 -0
  409. package/dist/skills/SkillName.js +2 -0
  410. package/dist/skills/SkillName.js.map +1 -0
  411. package/dist/skills/SkillRegistry.d.ts +22 -11
  412. package/dist/skills/SkillRegistry.js +47 -17
  413. package/dist/skills/SkillRegistry.js.map +1 -1
  414. package/dist/skills/builtin/api_ninjas_trivia.d.ts +3 -1
  415. package/dist/skills/builtin/api_ninjas_trivia.js +18 -6
  416. package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -1
  417. package/dist/skills/builtin/ask_claude.d.ts +14 -4
  418. package/dist/skills/builtin/ask_claude.js +36 -14
  419. package/dist/skills/builtin/ask_claude.js.map +1 -1
  420. package/dist/skills/builtin/claude_skills.d.ts +3 -1
  421. package/dist/skills/builtin/claude_skills.js +19 -15
  422. package/dist/skills/builtin/claude_skills.js.map +1 -1
  423. package/dist/skills/builtin/custom_skills.d.ts +10 -3
  424. package/dist/skills/builtin/custom_skills.js +26 -9
  425. package/dist/skills/builtin/custom_skills.js.map +1 -1
  426. package/dist/skills/builtin/datasphere.d.ts +5 -3
  427. package/dist/skills/builtin/datasphere.js +21 -22
  428. package/dist/skills/builtin/datasphere.js.map +1 -1
  429. package/dist/skills/builtin/datasphere_serverless.d.ts +12 -1
  430. package/dist/skills/builtin/datasphere_serverless.js +17 -6
  431. package/dist/skills/builtin/datasphere_serverless.js.map +1 -1
  432. package/dist/skills/builtin/datetime.d.ts +3 -1
  433. package/dist/skills/builtin/datetime.js +11 -7
  434. package/dist/skills/builtin/datetime.js.map +1 -1
  435. package/dist/skills/builtin/google_maps.d.ts +29 -14
  436. package/dist/skills/builtin/google_maps.js +89 -269
  437. package/dist/skills/builtin/google_maps.js.map +1 -1
  438. package/dist/skills/builtin/index.d.ts +8 -6
  439. package/dist/skills/builtin/index.js +8 -6
  440. package/dist/skills/builtin/index.js.map +1 -1
  441. package/dist/skills/builtin/info_gatherer.d.ts +4 -2
  442. package/dist/skills/builtin/info_gatherer.js +20 -12
  443. package/dist/skills/builtin/info_gatherer.js.map +1 -1
  444. package/dist/skills/builtin/joke.d.ts +16 -6
  445. package/dist/skills/builtin/joke.js +54 -37
  446. package/dist/skills/builtin/joke.js.map +1 -1
  447. package/dist/skills/builtin/math.d.ts +3 -1
  448. package/dist/skills/builtin/math.js +14 -9
  449. package/dist/skills/builtin/math.js.map +1 -1
  450. package/dist/skills/builtin/mcp_gateway.d.ts +34 -5
  451. package/dist/skills/builtin/mcp_gateway.js +77 -46
  452. package/dist/skills/builtin/mcp_gateway.js.map +1 -1
  453. package/dist/skills/builtin/native_vector_search.d.ts +19 -5
  454. package/dist/skills/builtin/native_vector_search.js +179 -61
  455. package/dist/skills/builtin/native_vector_search.js.map +1 -1
  456. package/dist/skills/builtin/play_background_file.d.ts +21 -15
  457. package/dist/skills/builtin/play_background_file.js +43 -122
  458. package/dist/skills/builtin/play_background_file.js.map +1 -1
  459. package/dist/skills/builtin/spider.d.ts +42 -4
  460. package/dist/skills/builtin/spider.js +277 -104
  461. package/dist/skills/builtin/spider.js.map +1 -1
  462. package/dist/skills/builtin/swml_transfer.d.ts +14 -3
  463. package/dist/skills/builtin/swml_transfer.js +45 -24
  464. package/dist/skills/builtin/swml_transfer.js.map +1 -1
  465. package/dist/skills/builtin/weather_api.d.ts +24 -13
  466. package/dist/skills/builtin/weather_api.js +38 -30
  467. package/dist/skills/builtin/weather_api.js.map +1 -1
  468. package/dist/skills/builtin/web_search.d.ts +48 -10
  469. package/dist/skills/builtin/web_search.js +294 -100
  470. package/dist/skills/builtin/web_search.js.map +1 -1
  471. package/dist/skills/builtin/wikipedia_search.d.ts +4 -2
  472. package/dist/skills/builtin/wikipedia_search.js +14 -13
  473. package/dist/skills/builtin/wikipedia_search.js.map +1 -1
  474. package/dist/skills/index.d.ts +3 -2
  475. package/dist/skills/index.js +1 -1
  476. package/dist/skills/index.js.map +1 -1
  477. package/dist/swml_verbs_generated.d.ts +2824 -0
  478. package/dist/swml_verbs_generated.js +12 -0
  479. package/dist/swml_verbs_generated.js.map +1 -0
  480. package/dist/types.d.ts +59 -6
  481. package/dist/web.d.ts +27 -0
  482. package/dist/web.js +20 -0
  483. package/dist/web.js.map +1 -0
  484. package/docs/agent-guide.md +1034 -0
  485. package/docs/ai_chat.md +560 -0
  486. package/docs/api-reference.md +3534 -0
  487. package/docs/architecture.md +846 -0
  488. package/docs/bedrock_agent.md +411 -0
  489. package/docs/cli-guide.md +403 -0
  490. package/docs/cloud_functions_guide.md +399 -0
  491. package/docs/configuration.md +548 -0
  492. package/docs/contexts-guide.md +884 -0
  493. package/docs/datamap-guide.md +1160 -0
  494. package/docs/developer_pain_points.md +548 -0
  495. package/docs/llm_parameters.md +298 -0
  496. package/docs/mcp_gateway_reference.md +354 -0
  497. package/docs/mcp_integration.md +162 -0
  498. package/docs/pgi_agent_guide.md +1820 -0
  499. package/docs/prefabs-guide.md +815 -0
  500. package/docs/programmatically_governed_inference.md +301 -0
  501. package/docs/sdk_features.md +501 -0
  502. package/docs/security.md +559 -0
  503. package/docs/serverless-guide.md +520 -0
  504. package/docs/skills-guide.md +1223 -0
  505. package/docs/skills-system.md +405 -0
  506. package/docs/skills_parameter_schema.md +417 -0
  507. package/docs/swaig-reference.md +1938 -0
  508. package/docs/swml_service_guide.md +573 -0
  509. package/docs/third_party_skills.md +410 -0
  510. package/docs/web_service.md +666 -0
  511. package/examples/README.md +202 -0
  512. package/examples/advanced-datamap.ts +108 -0
  513. package/examples/advanced-dynamic-config.ts +70 -0
  514. package/examples/auto-vivified.ts +95 -0
  515. package/examples/call-flow.ts +65 -0
  516. package/examples/comprehensive-dynamic.ts +125 -0
  517. package/examples/contexts-steps.ts +65 -0
  518. package/examples/custom-path.ts +45 -0
  519. package/examples/datamap-tools.ts +51 -0
  520. package/examples/datasphere-multi-instance.ts +66 -0
  521. package/examples/datasphere-serverless-env.ts +87 -0
  522. package/examples/datasphere-webhook-env.ts +65 -0
  523. package/examples/datasphere.ts +56 -0
  524. package/examples/declarative.ts +100 -0
  525. package/examples/dynamic-config.ts +54 -0
  526. package/examples/dynamic-info-gatherer.ts +69 -0
  527. package/examples/dynamic-swml-service.ts +67 -0
  528. package/examples/gather-info.ts +95 -0
  529. package/examples/gather-per-question-functions-demo.ts +139 -0
  530. package/examples/joke-agent.ts +34 -0
  531. package/examples/kubernetes-agent.ts +45 -0
  532. package/examples/llm-params.ts +75 -0
  533. package/examples/mcp-agent.ts +89 -0
  534. package/examples/mcp-gateway.ts +81 -0
  535. package/examples/multi-agent.ts +80 -0
  536. package/examples/multi-endpoint.ts +79 -0
  537. package/examples/pgi/case-domain.ts +114 -0
  538. package/examples/pgi/serve.ts +16 -0
  539. package/examples/pgi/support-agent.ts +265 -0
  540. package/examples/pom-prompt.ts +70 -0
  541. package/examples/prefab-concierge.ts +42 -0
  542. package/examples/prefab-faq.ts +58 -0
  543. package/examples/prefab-info-gatherer.ts +33 -0
  544. package/examples/prefab-receptionist.ts +36 -0
  545. package/examples/prefab-survey.ts +69 -0
  546. package/examples/quickstart-agent.ts +29 -0
  547. package/examples/quickstart-relay.ts +25 -0
  548. package/examples/quickstart-rest.ts +25 -0
  549. package/examples/record-call.ts +65 -0
  550. package/examples/relay-demo.ts +33 -0
  551. package/examples/room-and-sip.ts +93 -0
  552. package/examples/serverless-lambda.ts +43 -0
  553. package/examples/session-state.ts +83 -0
  554. package/examples/simple-agent.ts +36 -0
  555. package/examples/simple-static.ts +29 -0
  556. package/examples/skills-demo.ts +41 -0
  557. package/examples/step-function-inheritance-demo.ts +124 -0
  558. package/examples/swaig-features.ts +193 -0
  559. package/examples/swml-service-routing.ts +66 -0
  560. package/examples/swml-service.ts +38 -0
  561. package/examples/swmlservice_ai_sidecar.ts +104 -0
  562. package/examples/swmlservice_swaig_standalone.ts +79 -0
  563. package/examples/tap.ts +67 -0
  564. package/examples/typed-tools.ts +68 -0
  565. package/examples/verb-methods.ts +45 -0
  566. package/examples/web-search-multi-instance.ts +75 -0
  567. package/examples/web-search.ts +38 -0
  568. package/examples/wikipedia.ts +36 -0
  569. package/livewire/README.md +164 -0
  570. package/livewire/docs/migration-guide.md +251 -0
  571. package/livewire/examples/livewire-basic-agent.ts +74 -0
  572. package/livewire/examples/livewire-handoff.ts +196 -0
  573. package/livewire/examples/livewire-multi-tool.ts +121 -0
  574. package/package.json +85 -13
  575. package/relay/README.md +101 -0
  576. package/relay/docs/call-methods.md +622 -0
  577. package/relay/docs/client-reference.md +281 -0
  578. package/relay/docs/events.md +193 -0
  579. package/relay/docs/getting-started.md +221 -0
  580. package/relay/docs/guide.md +386 -0
  581. package/relay/docs/messaging.md +246 -0
  582. package/relay/examples/relay-inbound.ts +66 -0
  583. package/relay/examples/relay-messaging.ts +74 -0
  584. package/relay/examples/relay-outbound.ts +76 -0
  585. package/rest/README.md +141 -0
  586. package/rest/docs/calling.md +313 -0
  587. package/rest/docs/client-reference.md +149 -0
  588. package/rest/docs/fabric.md +192 -0
  589. package/rest/docs/getting-started.md +138 -0
  590. package/rest/docs/guide.md +421 -0
  591. package/rest/docs/namespaces.md +367 -0
  592. package/rest/docs/phone-binding.md +116 -0
  593. package/rest/examples/rest-10dlc-registration.ts +177 -0
  594. package/rest/examples/rest-bind-phone-to-swml-webhook.ts +66 -0
  595. package/rest/examples/rest-calling-ivr-and-ai.ts +136 -0
  596. package/rest/examples/rest-calling-play-and-record.ts +98 -0
  597. package/rest/examples/rest-client.ts +59 -0
  598. package/rest/examples/rest-datasphere-search.ts +81 -0
  599. package/rest/examples/rest-fabric-conferences-and-routing.ts +147 -0
  600. package/rest/examples/rest-fabric-subscribers-and-sip.ts +106 -0
  601. package/rest/examples/rest-fabric-swml-and-callflows.ts +101 -0
  602. package/rest/examples/rest-manage-resources.ts +64 -0
  603. package/rest/examples/rest-phone-number-management.ts +200 -0
  604. package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
  605. package/rest/examples/rest-video-rooms.ts +186 -0
  606. package/tutorial/fred/fred.ts +218 -0
  607. package/tutorial/fred/tutorial/01-introduction.md +141 -0
  608. package/tutorial/fred/tutorial/02-setup.md +304 -0
  609. package/tutorial/fred/tutorial/03-basic-agent.md +284 -0
  610. package/tutorial/fred/tutorial/04-wikipedia-skill.md +298 -0
  611. package/tutorial/fred/tutorial/05-custom-functions.md +347 -0
  612. package/tutorial/fred/tutorial/06-running-testing.md +642 -0
  613. package/tutorial/fred/tutorial/README.md +56 -0
  614. package/tutorial/fred/tutorial/appendix-complete-code.md +632 -0
  615. package/tutorial/fred/tutorial/appendix-docker-deployment.md +504 -0
  616. package/tutorial/full-guardrails-agent/handlers.ts +436 -0
  617. package/tutorial/full-guardrails-agent/penny.ts +305 -0
  618. package/tutorial/full-guardrails-agent/reservations.ts +1109 -0
  619. package/tutorial/full-guardrails-agent/tutorial/01-why-guardrails.md +149 -0
  620. package/tutorial/full-guardrails-agent/tutorial/02-design-first.md +139 -0
  621. package/tutorial/full-guardrails-agent/tutorial/03-rules-first.md +422 -0
  622. package/tutorial/full-guardrails-agent/tutorial/04-the-shell.md +238 -0
  623. package/tutorial/full-guardrails-agent/tutorial/05-steps-and-scoping.md +247 -0
  624. package/tutorial/full-guardrails-agent/tutorial/06-tools-that-decide.md +467 -0
  625. package/tutorial/full-guardrails-agent/tutorial/07-gather-and-projection.md +160 -0
  626. package/tutorial/full-guardrails-agent/tutorial/08-the-verification-gate.md +333 -0
  627. package/tutorial/full-guardrails-agent/tutorial/09-people-and-endings.md +313 -0
  628. package/tutorial/full-guardrails-agent/tutorial/10-testing-and-running.md +387 -0
  629. package/tutorial/full-guardrails-agent/tutorial/README.md +106 -0
  630. package/tutorial/full-guardrails-agent/tutorial/appendix-complete-code.md +2207 -0
  631. package/tutorial/full-guardrails-agent/tutorial/appendix-deployment.md +191 -0
  632. package/tutorial/full-guardrails-agent/tutorial/appendix-technique-map.md +117 -0
  633. package/tutorial/full-guardrails-agent/workflow.ts +219 -0
  634. package/tutorial/multi_agents/README.md +175 -0
  635. package/tutorial/multi_agents/advanced_agent.ts +395 -0
  636. package/tutorial/multi_agents/extending_agents.ts +641 -0
  637. package/tutorial/multi_agents/knowledge.ts +59 -0
  638. package/tutorial/multi_agents/lesson1_first_agent.md +368 -0
  639. package/tutorial/multi_agents/lesson2_knowledge_bases.md +404 -0
  640. package/tutorial/multi_agents/lesson3_multi_agent_systems.md +621 -0
  641. package/tutorial/multi_agents/lesson4_advanced_features.md +805 -0
  642. package/tutorial/multi_agents/lesson5_extending_agents.md +856 -0
  643. package/tutorial/multi_agents/pc_builder.ts +529 -0
  644. package/tutorial/multi_agents/sales_agent.ts +88 -0
  645. package/tutorial/multi_agents/sales_agent_with_search.ts +116 -0
  646. package/tutorial/multi_agents/sales_knowledge.md +139 -0
  647. package/tutorial/multi_agents/support_knowledge.md +256 -0
  648. package/dist/cli/mock-data.d.ts +0 -37
  649. package/dist/cli/mock-data.js +0 -80
  650. package/dist/cli/mock-data.js.map +0 -1
  651. package/dist/generateVerbTypes.d.ts +0 -11
  652. package/dist/generateVerbTypes.js +0 -265
  653. package/dist/generateVerbTypes.js.map +0 -1
  654. package/dist/rest/namespaces/compat.d.ts +0 -585
  655. package/dist/rest/namespaces/compat.js +0 -735
  656. package/dist/rest/namespaces/compat.js.map +0 -1
@@ -1,422 +1,986 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * swaig-test - CLI tool for testing SignalWire AI agents locally.
3
+ * swaig-test - test a SignalWire AI agent file locally.
4
4
  *
5
- * Usage:
6
- * swaig-test <agent-path> [options]
5
+ * swaig-test <agent-file> --list-tools
6
+ * swaig-test <agent-file> --dump-swml
7
+ * swaig-test <agent-file> --exec <function> [--param value ...]
7
8
  *
8
- * Actions:
9
- * --list-tools List all SWAIG functions with parameters
10
- * --list-agents List all exported agents in a file
11
- * --dump-swml Generate and output SWML document
12
- * --exec <name> Execute a function (use --arg key=value for args)
9
+ * Requests go through the agent's own HTTP app, as SignalWire's would: the
10
+ * SWML is fetched with a simulated call, a dynamic config callback runs once
11
+ * per request on a copy of the agent, and a function is called at the
12
+ * web_hook_url the SWML gives it, token and all. A DataMap function runs in
13
+ * the local DataMap simulator. With --simulate-serverless the agent runs with
14
+ * a serverless platform's environment, so its webhook URLs are the
15
+ * platform's.
13
16
  *
14
- * Options:
15
- * --raw Raw JSON output (suppresses logs)
16
- * --verbose Verbose output
17
- * --format-json Format output as indented JSON
18
- * --call-type sip|webrtc (default: webrtc)
19
- * --call-direction inbound|outbound (default: inbound)
20
- * --call-state active|ringing|hold (default: active)
21
- * --call-id Override call ID
22
- * --from-number Override from number
23
- * --to-extension Override to extension
24
- * --arg key=value Function argument (repeatable)
25
- * --override k=v Override call data field (repeatable)
26
- * --agent-class Name of specific agent class to use
27
- * --route Route for agent (default: /)
28
- * --env KEY=VALUE Set env var (repeatable)
29
- * --env-file Load env vars from file
30
- * --simulate-serverless <platform> Simulate serverless platform
17
+ * Mirrors signalwire-python's `swaig-test` (signalwire/cli/test_swaig.py).
31
18
  */
32
- import { loadAgent, listAgents } from './agent-loader.js';
33
- import { generateFakePostData, generateMinimalPostData } from './mock-data.js';
34
- import { suppressAllLogs, setGlobalLogLevel } from '../Logger.js';
35
- import { ServerlessAdapter } from '../ServerlessAdapter.js';
36
- function printUsage() {
37
- console.log(`
38
- swaig-test - CLI tool for testing SignalWire AI agents locally
39
-
40
- Usage:
41
- swaig-test <agent-path> [options]
42
-
43
- Actions:
44
- --list-tools List all SWAIG functions with parameters
45
- --list-agents List all exported agents in a file
46
- --dump-swml Generate and output SWML document
47
- --exec <name> Execute a function (use --arg key=value for args)
48
-
49
- Options:
50
- --raw Raw JSON output (suppresses logs)
51
- --verbose Verbose output
52
- --format-json Format output as indented JSON
53
- --call-type sip|webrtc (default: webrtc)
54
- --call-direction inbound|outbound (default: inbound)
55
- --call-state active|ringing|hold (default: active)
56
- --call-id Override call ID
57
- --from-number Override from number
58
- --to-extension Override to extension
59
- --arg key=value Function argument (repeatable)
60
- --override k=v Override call data field (repeatable)
61
- --agent-class Name of specific agent class to use
62
- --route Route for the agent
63
- --env KEY=VALUE Set env var (repeatable)
64
- --env-file Load env vars from file
65
- --simulate-serverless <platform> Simulate serverless (lambda|gcf|azure|cgi)
66
- --help Show this help message
67
- `);
68
- }
19
+ import { createHmac } from 'node:crypto';
20
+ import { describeAgents, loadAgent } from './agent-loader.js';
21
+ import { executeDataMap, PLATFORM_ERROR_RESPONSE } from './datamap-exec.js';
22
+ import { parseFunctionArguments, undeclaredArgumentWarnings } from './function-args.js';
23
+ import { SIMULATED_PLATFORMS, ServerlessSimulator, applyConvenienceMappings, applyOverrides, comprehensivePostData, fakeSwmlPostData, loadEnvFile, minimalPostData, } from './simulation.js';
24
+ import { setGlobalLogLevel, suppressAllLogs } from '../Logger.js';
25
+ const VALUE_OPTIONS = {
26
+ '--agent-class': 'agentClass',
27
+ '--route': 'route',
28
+ '--custom-data': 'customData',
29
+ '--call-type': 'callType',
30
+ '--call-direction': 'callDirection',
31
+ '--call-state': 'callState',
32
+ '--from-number': 'fromNumber',
33
+ '--to-extension': 'toExtension',
34
+ '--user-vars': 'userVars',
35
+ '--query-params': 'queryParams',
36
+ '--simulate-serverless': 'simulateServerless',
37
+ '--env-file': 'envFile',
38
+ '--call-id': 'callId',
39
+ '--project-id': 'projectId',
40
+ '--space-id': 'spaceId',
41
+ '--method': 'method',
42
+ '--body': 'body',
43
+ '--aws-function-name': 'awsFunctionName',
44
+ '--aws-function-url': 'awsFunctionUrl',
45
+ '--aws-region': 'awsRegion',
46
+ '--aws-api-gateway-id': 'awsApiGatewayId',
47
+ '--aws-stage': 'awsStage',
48
+ '--cgi-host': 'cgiHost',
49
+ '--cgi-script-name': 'cgiScriptName',
50
+ '--cgi-path-info': 'cgiPathInfo',
51
+ '--gcp-project': 'gcpProject',
52
+ '--gcp-function-url': 'gcpFunctionUrl',
53
+ '--gcp-region': 'gcpRegion',
54
+ '--gcp-service': 'gcpService',
55
+ '--azure-env': 'azureEnv',
56
+ '--azure-function-url': 'azureFunctionUrl',
57
+ };
58
+ const LIST_OPTIONS = {
59
+ '--override': 'overrides',
60
+ '--override-json': 'overrideJson',
61
+ '--header': 'headers',
62
+ '--env': 'envVars',
63
+ };
64
+ const FLAG_OPTIONS = {
65
+ '--verbose': 'verbose',
66
+ '-v': 'verbose',
67
+ '--raw': 'raw',
68
+ '--format-json': 'formatJson',
69
+ '--minimal': 'minimal',
70
+ '--fake-full-data': 'fakeFullData',
71
+ '--cgi-https': 'cgiHttps',
72
+ };
73
+ const ACTION_OPTIONS = {
74
+ '--list-tools': 'list-tools',
75
+ '--list-agents': 'list-agents',
76
+ '--dump-swml': 'dump-swml',
77
+ };
78
+ /** Every option swaig-test takes, for the undeclared-argument warning. */
79
+ const CLI_OPTIONS = new Set([
80
+ ...Object.keys(VALUE_OPTIONS),
81
+ ...Object.keys(LIST_OPTIONS),
82
+ ...Object.keys(FLAG_OPTIONS),
83
+ ...Object.keys(ACTION_OPTIONS),
84
+ '--exec',
85
+ '--help',
86
+ '--help-platforms',
87
+ '--help-examples',
88
+ '--parse-only',
89
+ '--dry-run',
90
+ ]);
91
+ /** A usage error (printed with a hint, exit 2): an Error tagged `usage`. */
92
+ const usageError = (message) => Object.assign(new Error(message), { usage: true });
93
+ const isUsageError = (err) => err instanceof Error && err.usage === true;
94
+ const AGENT_FILE = /\.(ts|js|mjs|mts)$/i;
69
95
  function parseArgs(argv) {
70
- const args = argv.slice(2); // skip node + script
71
- if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
72
- printUsage();
73
- process.exit(0);
96
+ // Everything after `--exec <function>` is the function's.
97
+ let cli = argv;
98
+ let execName;
99
+ let functionTokens = [];
100
+ const execAt = argv.indexOf('--exec');
101
+ if (execAt >= 0) {
102
+ execName = argv[execAt + 1];
103
+ if (!execName || execName.startsWith('--'))
104
+ throw usageError('--exec requires a function name');
105
+ cli = argv.slice(0, execAt);
106
+ functionTokens = argv.slice(execAt + 2);
74
107
  }
75
108
  const opts = {
76
109
  agentPath: '',
77
- action: 'dump-swml',
78
- raw: false,
110
+ action: execName ? 'exec' : null,
111
+ execName,
112
+ functionTokens,
79
113
  verbose: false,
114
+ raw: false,
80
115
  formatJson: false,
116
+ minimal: false,
117
+ fakeFullData: false,
81
118
  callType: 'webrtc',
82
119
  callDirection: 'inbound',
83
- callState: 'active',
84
- args: {},
85
- overrides: {},
86
- envVars: {},
120
+ callState: 'created',
121
+ overrides: [],
122
+ overrideJson: [],
123
+ headers: [],
124
+ envVars: [],
125
+ method: 'POST',
126
+ cgiHttps: false,
87
127
  };
88
- let i = 0;
89
- // First positional arg is the agent path
90
- if (!args[0].startsWith('--')) {
91
- opts.agentPath = args[0];
92
- i = 1;
93
- }
94
- for (; i < args.length; i++) {
95
- const arg = args[i];
96
- switch (arg) {
97
- case '--list-tools':
98
- opts.action = 'list-tools';
99
- break;
100
- case '--list-agents':
101
- opts.action = 'list-agents';
102
- break;
103
- case '--dump-swml':
104
- opts.action = 'dump-swml';
105
- break;
106
- case '--exec':
107
- opts.action = 'exec';
108
- opts.execName = args[++i];
109
- if (!opts.execName) {
110
- console.error('Error: --exec requires a function name');
111
- process.exit(1);
112
- }
113
- break;
114
- case '--raw':
115
- opts.raw = true;
116
- break;
117
- case '--verbose':
118
- opts.verbose = true;
119
- break;
120
- case '--format-json':
121
- opts.formatJson = true;
122
- break;
123
- case '--call-type':
124
- opts.callType = args[++i];
125
- break;
126
- case '--call-direction':
127
- opts.callDirection = args[++i];
128
- break;
129
- case '--call-state':
130
- opts.callState = args[++i];
131
- break;
132
- case '--call-id':
133
- opts.callId = args[++i];
134
- break;
135
- case '--from-number':
136
- opts.fromNumber = args[++i];
137
- break;
138
- case '--to-extension':
139
- opts.toExtension = args[++i];
140
- break;
141
- case '--agent-class':
142
- opts.agentClass = args[++i];
143
- break;
144
- case '--route':
145
- opts.route = args[++i];
146
- break;
147
- case '--simulate-serverless':
148
- opts.simulateServerless = args[++i];
149
- break;
150
- case '--env-file':
151
- opts.envFile = args[++i];
152
- break;
153
- case '--arg': {
154
- const kv = args[++i];
155
- if (!kv || !kv.includes('=')) {
156
- console.error('Error: --arg requires key=value format');
157
- process.exit(1);
158
- }
159
- const eqIdx = kv.indexOf('=');
160
- const key = kv.slice(0, eqIdx);
161
- const val = kv.slice(eqIdx + 1);
162
- // Try to parse as JSON, fall back to string
163
- try {
164
- opts.args[key] = JSON.parse(val);
165
- }
166
- catch {
167
- opts.args[key] = val;
168
- }
169
- break;
170
- }
171
- case '--override': {
172
- const kv = args[++i];
173
- if (!kv || !kv.includes('=')) {
174
- console.error('Error: --override requires key=value format');
175
- process.exit(1);
176
- }
177
- const eqIdx = kv.indexOf('=');
178
- const key = kv.slice(0, eqIdx);
179
- const val = kv.slice(eqIdx + 1);
180
- try {
181
- opts.overrides[key] = JSON.parse(val);
182
- }
183
- catch {
184
- opts.overrides[key] = val;
185
- }
186
- break;
128
+ for (let i = 0; i < cli.length; i++) {
129
+ let token = cli[i];
130
+ let inlineValue;
131
+ const eq = token.indexOf('=');
132
+ if (token.startsWith('--') && eq > 2) {
133
+ inlineValue = token.slice(eq + 1);
134
+ token = token.slice(0, eq);
135
+ }
136
+ const value = () => {
137
+ if (inlineValue !== undefined)
138
+ return inlineValue;
139
+ const next = cli[++i];
140
+ if (next === undefined)
141
+ throw usageError(`${token} requires a value`);
142
+ return next;
143
+ };
144
+ if (token in FLAG_OPTIONS)
145
+ opts[FLAG_OPTIONS[token]] = true;
146
+ else if (token in ACTION_OPTIONS) {
147
+ if (opts.action && opts.action !== ACTION_OPTIONS[token]) {
148
+ throw usageError('choose one action: --list-agents, --list-tools, --dump-swml or --exec');
187
149
  }
188
- case '--env': {
189
- const kv = args[++i];
190
- if (!kv || !kv.includes('=')) {
191
- console.error('Error: --env requires KEY=VALUE format');
192
- process.exit(1);
193
- }
194
- const eqIdx = kv.indexOf('=');
195
- opts.envVars[kv.slice(0, eqIdx)] = kv.slice(eqIdx + 1);
150
+ opts.action = ACTION_OPTIONS[token];
151
+ }
152
+ else if (token in VALUE_OPTIONS)
153
+ opts[VALUE_OPTIONS[token]] = value();
154
+ else if (token in LIST_OPTIONS)
155
+ opts[LIST_OPTIONS[token]].push(value());
156
+ else if (token === '--arg') {
157
+ // --arg name=value before --exec: a function argument all the same.
158
+ opts.functionTokens.push('--arg', value());
159
+ }
160
+ else if (!token.startsWith('-') && !opts.agentPath)
161
+ opts.agentPath = token;
162
+ else
163
+ throw usageError(`unknown option: ${cli[i]}`);
164
+ }
165
+ // The agent file may trail the function's arguments; take it from there.
166
+ if (!opts.agentPath) {
167
+ const tokens = opts.functionTokens;
168
+ for (let k = tokens.length - 1; k >= 0; k--) {
169
+ const t = tokens[k];
170
+ if (AGENT_FILE.test(t) &&
171
+ !t.startsWith('-') &&
172
+ (k === 0 || !tokens[k - 1].startsWith('--'))) {
173
+ opts.agentPath = tokens.splice(k, 1)[0];
196
174
  break;
197
175
  }
198
- default:
199
- if (!opts.agentPath && !arg.startsWith('--')) {
200
- opts.agentPath = arg;
201
- }
202
- else {
203
- console.error(`Unknown option: ${arg}`);
204
- process.exit(1);
205
- }
206
176
  }
207
177
  }
208
- if (!opts.agentPath) {
209
- console.error('Error: agent path is required');
210
- printUsage();
211
- process.exit(1);
178
+ if (!opts.agentPath)
179
+ throw usageError('missing the agent file');
180
+ if (!['sip', 'webrtc'].includes(opts.callType)) {
181
+ throw usageError(`--call-type must be sip or webrtc, not ${opts.callType}`);
182
+ }
183
+ if (!['inbound', 'outbound'].includes(opts.callDirection)) {
184
+ throw usageError(`--call-direction must be inbound or outbound, not ${opts.callDirection}`);
185
+ }
186
+ if (opts.route && opts.agentClass) {
187
+ throw usageError('Cannot specify both --route and --agent-class. Choose one.');
188
+ }
189
+ if (opts.simulateServerless !== undefined) {
190
+ if (!(opts.simulateServerless in SIMULATED_PLATFORMS)) {
191
+ throw usageError(`--simulate-serverless ${opts.simulateServerless}: unknown platform. ` +
192
+ `This TypeScript port supports: ${Object.keys(SIMULATED_PLATFORMS).join(', ')}. ` +
193
+ '(No silent fallback to the server path.)');
194
+ }
195
+ if (SIMULATED_PLATFORMS[opts.simulateServerless] === 'cgi' && !opts.cgiHost) {
196
+ throw usageError('--cgi-host is required with --simulate-serverless cgi');
197
+ }
212
198
  }
213
199
  return opts;
214
200
  }
215
- function loadEnvFile(filePath) {
216
- const { readFileSync } = require('node:fs');
217
- const { resolve } = require('node:path');
218
- const content = readFileSync(resolve(filePath), 'utf-8');
219
- for (const line of content.split('\n')) {
220
- const trimmed = line.trim();
221
- if (!trimmed || trimmed.startsWith('#'))
201
+ // ── Help ─────────────────────────────────────────────────────────────────
202
+ const USAGE = 'Usage: swaig-test <agent-file> [options]';
203
+ function printHelp() {
204
+ console.log(`swaig-test - test a SignalWire AI agent file locally
205
+
206
+ ${USAGE}
207
+
208
+ Actions (choose one):
209
+ --list-agents List the agents and services in the file
210
+ --list-tools List the agent's SWAIG functions
211
+ --dump-swml Print the SWML document the agent serves
212
+ --exec <function> [--param value ...]
213
+ Call a function. Everything after the function name is
214
+ an argument for it (--name value, typed by the
215
+ function's parameters; --arg name=value also works),
216
+ so put swaig-test's own options before --exec.
217
+
218
+ Common options:
219
+ -v, --verbose Verbose output
220
+ --raw Output raw JSON only (for piping to jq)
221
+ --format-json Print the result as indented JSON
222
+ --agent-class NAME Use this exported agent class or instance
223
+ --route ROUTE Use the service with this route (e.g. /healthcare)
224
+
225
+ Function execution:
226
+ --minimal Send the smallest request (call_id and arguments)
227
+ --fake-full-data Send a request with every key SignalWire may send (the default)
228
+ --custom-data JSON Values to merge into the request; a DataMap function's call data
229
+
230
+ SWML and call data (each applies to --dump-swml, --list-tools and --exec):
231
+ --call-type sip|webrtc Call type (default: webrtc)
232
+ --call-direction inbound|outbound
233
+ Call direction (default: inbound)
234
+ --call-state STATE Call state, set as call.state (default: created)
235
+ --call-id ID call_id the simulated request carries
236
+ --project-id ID call.project_id
237
+ --space-id ID call.space_id
238
+ --from-number NUMBER call.from
239
+ --to-extension EXT call.to
240
+ --user-vars JSON vars.userVariables
241
+ --query-params JSON Query parameters for the request (also in userVariables)
242
+ --header NAME=VALUE Request header (repeatable)
243
+ --override PATH=VALUE Set a value in the request, e.g. call.state=answered (repeatable)
244
+ --override-json PATH=JSON Set a JSON value in the request (repeatable)
245
+ --method POST|GET Method of the SWML request (default: POST)
246
+ --body JSON Extra fields for the SWML request body
247
+
248
+ Environment and serverless:
249
+ --env KEY=VALUE Set an environment variable (repeatable)
250
+ --env-file FILE Load environment variables from a file
251
+ --simulate-serverless lambda|cgi|gcf|azure
252
+ Run with a serverless platform's environment
253
+ (cloud_function and azure_function also accepted);
254
+ see --help-platforms
255
+
256
+ --parse-only, --dry-run Validate the arguments and exit without loading the agent
257
+ --help-platforms Serverless platform options
258
+ --help-examples Usage examples
259
+ -h, --help This help
260
+
261
+ The SDK's documentation for the installed version: sw-tsdocs (npx sw-tsdocs).`);
262
+ }
263
+ function printHelpPlatforms() {
264
+ console.log(`Serverless platform options
265
+
266
+ AWS Lambda (--simulate-serverless lambda):
267
+ --aws-function-name NAME Function name (AWS_LAMBDA_FUNCTION_NAME)
268
+ --aws-function-url URL Function URL (AWS_LAMBDA_FUNCTION_URL)
269
+ --aws-region REGION Region (AWS_REGION)
270
+ --aws-api-gateway-id ID Serve at an API Gateway URL,
271
+ https://ID.execute-api.REGION.amazonaws.com/STAGE
272
+ --aws-stage STAGE API Gateway stage (default: prod)
273
+
274
+ CGI (--simulate-serverless cgi):
275
+ --cgi-host HOST Server host name (required)
276
+ --cgi-script-name NAME Script path (SCRIPT_NAME)
277
+ --cgi-https Serve over HTTPS
278
+ --cgi-path-info PATH PATH_INFO
279
+
280
+ Google Cloud Functions (--simulate-serverless gcf):
281
+ --gcp-project ID Project (GOOGLE_CLOUD_PROJECT)
282
+ --gcp-function-url URL Function URL (FUNCTION_URL)
283
+ --gcp-region REGION Region (GOOGLE_CLOUD_REGION)
284
+ --gcp-service NAME Service name (K_SERVICE)
285
+
286
+ Azure Functions (--simulate-serverless azure):
287
+ --azure-env ENV Environment (AZURE_FUNCTIONS_ENVIRONMENT)
288
+ --azure-function-url URL Function URL (AZURE_FUNCTION_URL)
289
+
290
+ Example:
291
+ swaig-test agent.ts --simulate-serverless lambda --aws-region us-west-2 --dump-swml`);
292
+ }
293
+ function printHelpExamples() {
294
+ console.log(`Examples
295
+
296
+ # List the functions, then call one
297
+ swaig-test agent.ts --list-tools
298
+ swaig-test agent.ts --exec get_weather --city "San Francisco"
299
+ swaig-test agent.ts --verbose --exec search --query test --limit 5
300
+
301
+ # The SWML document, for jq
302
+ swaig-test agent.ts --dump-swml --raw | jq '.sections.main'
303
+
304
+ # A dynamic agent, with the request it would get
305
+ swaig-test agent.ts --dump-swml --query-params '{"tier":"premium"}' --header "X-Customer-ID=12345"
306
+
307
+ # Call data
308
+ swaig-test agent.ts --call-type sip --call-state answered --exec transfer --dest sales
309
+ swaig-test agent.ts --override call.project_id=my-project --dump-swml
310
+
311
+ # A file with several agents
312
+ swaig-test server.ts --list-agents
313
+ swaig-test server.ts --route /sales --list-tools
314
+
315
+ # Serverless
316
+ swaig-test agent.ts --simulate-serverless lambda --dump-swml
317
+ swaig-test agent.ts --simulate-serverless cgi --cgi-host example.com --cgi-https --exec my_function`);
318
+ }
319
+ const isAgent = (t) => typeof t.getPrompt === 'function';
320
+ /** The target's HTTP app, called as SignalWire would call it. */
321
+ class Client {
322
+ target;
323
+ headers;
324
+ constructor(target, headers) {
325
+ this.target = target;
326
+ this.headers = headers;
327
+ }
328
+ /** The route prefix of the target's app ('' for '/'). */
329
+ get prefix() {
330
+ const route = this.target.route ?? '/';
331
+ return route === '/' ? '' : route.replace(/\/+$/, '');
332
+ }
333
+ async send(method, pathAndQuery, body) {
334
+ const headers = { ...this.headers };
335
+ if (body !== undefined)
336
+ headers['Content-Type'] = 'application/json';
337
+ const creds = this.target.getBasicAuthCredentials?.();
338
+ if (creds?.[0] && creds[1]) {
339
+ headers['Authorization'] =
340
+ 'Basic ' + Buffer.from(`${creds[0]}:${creds[1]}`).toString('base64');
341
+ }
342
+ // Signed as SignalWire signs it, when the agent checks signatures.
343
+ // Over the public URL the agent reconstructs: SWML_PROXY_URL_BASE and
344
+ // the path, or the URL as received.
345
+ const key = this.target.signingKey;
346
+ if (key) {
347
+ const proxyBase = process.env['SWML_PROXY_URL_BASE']?.replace(/\/+$/, '');
348
+ const signed = `${proxyBase ?? 'http://localhost'}${pathAndQuery}${body ?? ''}`;
349
+ headers['X-SignalWire-Signature'] = createHmac('sha1', key).update(signed).digest('hex');
350
+ headers['X-SignalWire-Sha256-Signature'] = createHmac('sha256', key)
351
+ .update(signed)
352
+ .digest('hex');
353
+ }
354
+ return this.target.getApp().request(pathAndQuery, { method, headers, body });
355
+ }
356
+ }
357
+ function queryString(params) {
358
+ const search = new URLSearchParams();
359
+ for (const [k, v] of Object.entries(params)) {
360
+ search.append(k, typeof v === 'string' ? v : JSON.stringify(v));
361
+ }
362
+ const s = search.toString();
363
+ return s ? `?${s}` : '';
364
+ }
365
+ function parseJsonOption(name, text, io) {
366
+ if (!text)
367
+ return {};
368
+ try {
369
+ const value = JSON.parse(text);
370
+ if (value && typeof value === 'object' && !Array.isArray(value))
371
+ return value;
372
+ io.err(`Warning: ${name} must be a JSON object; ignored`);
373
+ }
374
+ catch (err) {
375
+ io.err(`Warning: Invalid JSON in ${name}: ${err instanceof Error ? err.message : err}`);
376
+ }
377
+ return {};
378
+ }
379
+ /** Fetch the SWML the target serves for a simulated call. */
380
+ async function fetchSwml(client, opts, postData, io) {
381
+ const query = parseJsonOption('--query-params', opts.queryParams, io);
382
+ const extraBody = parseJsonOption('--body', opts.body, io);
383
+ const method = opts.method.toUpperCase();
384
+ let path = client.prefix || '/';
385
+ let body;
386
+ if (method === 'GET') {
387
+ const callId = postData['call']?.['call_id'] ?? postData['call_id'];
388
+ path += queryString({ ...(callId ? { call_id: callId } : {}), ...query });
389
+ }
390
+ else {
391
+ path += queryString(query);
392
+ body = JSON.stringify({ ...postData, ...extraBody });
393
+ }
394
+ io.verbose(`${method} ${path}`);
395
+ if (body)
396
+ io.verbose(`Request body: ${body}`);
397
+ const res = await client.send(method, path, body);
398
+ const text = await res.text();
399
+ if (!res.ok)
400
+ throw new Error(`The agent answered the SWML request with ${res.status}: ${text}`);
401
+ try {
402
+ return JSON.parse(text);
403
+ }
404
+ catch {
405
+ throw new Error(`The agent's SWML isn't JSON: ${text.slice(0, 200)}`);
406
+ }
407
+ }
408
+ /** The AI verb's SWAIG block: its functions, and the default web_hook_url. */
409
+ function swaigOf(doc) {
410
+ const main = (doc['sections']?.['main'] ?? []);
411
+ for (const verb of main) {
412
+ const ai = (verb?.['ai'] ?? verb?.['amazon_bedrock']);
413
+ if (!ai)
222
414
  continue;
223
- const eqIdx = trimmed.indexOf('=');
224
- if (eqIdx > 0) {
225
- const key = trimmed.slice(0, eqIdx).trim();
226
- let val = trimmed.slice(eqIdx + 1).trim();
227
- // Strip quotes
228
- if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
229
- val = val.slice(1, -1);
415
+ const swaig = (ai['SWAIG'] ?? {});
416
+ const functions = (Array.isArray(swaig['functions']) ? swaig['functions'] : []);
417
+ const defaults = (swaig['defaults'] ?? {});
418
+ const globalData = ai['global_data'];
419
+ return {
420
+ functions,
421
+ defaultUrl: typeof defaults['web_hook_url'] === 'string' ? defaults['web_hook_url'] : undefined,
422
+ globalData: globalData && typeof globalData === 'object' && !Array.isArray(globalData)
423
+ ? globalData
424
+ : undefined,
425
+ };
426
+ }
427
+ return { functions: [] };
428
+ }
429
+ /**
430
+ * The path in the target's own app a web_hook_url names, or null when it
431
+ * points somewhere else (an external webhook).
432
+ */
433
+ function localPath(target, client, url) {
434
+ if (!target.getFullUrl)
435
+ return null;
436
+ try {
437
+ const hook = new URL(url);
438
+ const base = new URL(target.getFullUrl(false));
439
+ const hookPath = `${hook.origin}${hook.pathname}`;
440
+ const basePath = `${base.origin}${base.pathname}`.replace(/\/+$/, '');
441
+ if (hookPath !== basePath && !hookPath.startsWith(`${basePath}/`))
442
+ return null;
443
+ return `${client.prefix}${hookPath.slice(basePath.length)}${hook.search}` || '/';
444
+ }
445
+ catch {
446
+ return null;
447
+ }
448
+ }
449
+ function kindOf(target, client, entry, defaultUrl) {
450
+ if (entry.data_map)
451
+ return 'datamap';
452
+ const url = entry.web_hook_url ?? defaultUrl;
453
+ return url && localPath(target, client, url) === null ? 'external' : 'local';
454
+ }
455
+ // ── Output ───────────────────────────────────────────────────────────────
456
+ function describeParameter(name, def, required) {
457
+ const type = typeof def['type'] === 'string' ? def['type'] : 'unknown';
458
+ const constraints = [];
459
+ if (Array.isArray(def['enum']))
460
+ constraints.push(`options: ${def['enum'].join(', ')}`);
461
+ const numeric = [
462
+ ['minimum', 'min'],
463
+ ['maximum', 'max'],
464
+ ['exclusiveMinimum', 'min (exclusive)'],
465
+ ['exclusiveMaximum', 'max (exclusive)'],
466
+ ['multipleOf', 'multiple of'],
467
+ ['minLength', 'min length'],
468
+ ['maxLength', 'max length'],
469
+ ['pattern', 'pattern'],
470
+ ['format', 'format'],
471
+ ];
472
+ for (const [key, label] of numeric)
473
+ if (key in def)
474
+ constraints.push(`${label}: ${String(def[key])}`);
475
+ if (type === 'array') {
476
+ if ('minItems' in def)
477
+ constraints.push(`min items: ${String(def['minItems'])}`);
478
+ if ('maxItems' in def)
479
+ constraints.push(`max items: ${String(def['maxItems'])}`);
480
+ if (def['uniqueItems'])
481
+ constraints.push('unique items');
482
+ const items = def['items'];
483
+ if (items?.['type'])
484
+ constraints.push(`item type: ${String(items['type'])}`);
485
+ }
486
+ if ('default' in def)
487
+ constraints.push(`default: ${JSON.stringify(def['default'])}`);
488
+ const typeText = constraints.length ? `${type} [${constraints.join(', ')}]` : type;
489
+ const description = typeof def['description'] === 'string' ? def['description'] : 'No description';
490
+ return ` ${name} (${typeText})${required ? ' (required)' : ''}: ${description}`;
491
+ }
492
+ function printParameters(io, parameters) {
493
+ const params = (parameters ?? {});
494
+ const props = (params['properties'] ?? params);
495
+ const required = Array.isArray(params['required']) ? params['required'] : [];
496
+ const names = Object.keys(props).filter((k) => props[k] && typeof props[k] === 'object');
497
+ if (names.length === 0) {
498
+ io.out(' Parameters: None');
499
+ return;
500
+ }
501
+ io.out(' Parameters:');
502
+ for (const name of names)
503
+ io.out(describeParameter(name, props[name], required.includes(name)));
504
+ }
505
+ function formatResult(result) {
506
+ if (result && typeof result === 'object' && !Array.isArray(result)) {
507
+ const r = result;
508
+ if ('response' in r) {
509
+ const lines = [
510
+ `Response: ${typeof r['response'] === 'string' ? r['response'] : JSON.stringify(r['response'])}`,
511
+ ];
512
+ if (Array.isArray(r['action']) && r['action'].length) {
513
+ lines.push('\nActions:', ...r['action'].map((a) => JSON.stringify(a, null, 2)));
230
514
  }
231
- process.env[key] = val;
515
+ if (r['post_process'])
516
+ lines.push(`\nPost-process: ${String(r['post_process'])}`);
517
+ return lines.join('\n');
232
518
  }
519
+ return `Dict: ${JSON.stringify(result, null, 2)}`;
233
520
  }
521
+ if (typeof result === 'string')
522
+ return `String: ${result}`;
523
+ return `Other: ${JSON.stringify(result)}`;
234
524
  }
235
- async function main() {
236
- const opts = parseArgs(process.argv);
237
- if (opts.raw) {
238
- suppressAllLogs(true);
239
- }
240
- else if (opts.verbose) {
241
- setGlobalLogLevel('debug');
525
+ // ── Main ─────────────────────────────────────────────────────────────────
526
+ /**
527
+ * The variables each platform's function URL is built from, when the URL
528
+ * variable itself isn't set. The SDK uses the URL variable first.
529
+ */
530
+ const URL_PARTS = {
531
+ lambda: { url: 'AWS_LAMBDA_FUNCTION_URL', parts: ['AWS_LAMBDA_FUNCTION_NAME', 'AWS_REGION'] },
532
+ cloud_function: {
533
+ url: 'FUNCTION_URL',
534
+ parts: [
535
+ 'GOOGLE_CLOUD_PROJECT',
536
+ 'GCP_PROJECT',
537
+ 'GOOGLE_CLOUD_REGION',
538
+ 'FUNCTION_REGION',
539
+ 'K_SERVICE',
540
+ 'FUNCTION_TARGET',
541
+ ],
542
+ },
543
+ azure_function: {
544
+ url: 'AZURE_FUNCTION_URL',
545
+ parts: ['WEBSITE_SITE_NAME', 'AZURE_FUNCTIONS_APP_NAME', 'AZURE_FUNCTION_NAME'],
546
+ },
547
+ };
548
+ /**
549
+ * Variables the SDK reads for the same part of a function URL, the one it
550
+ * prefers first. A preset value under a preferred name would hide a value
551
+ * the user gave under a later one.
552
+ */
553
+ const URL_PART_NAMES = {
554
+ cloud_function: [
555
+ ['GOOGLE_CLOUD_PROJECT', 'GCP_PROJECT'],
556
+ ['FUNCTION_REGION', 'GOOGLE_CLOUD_REGION'],
557
+ ['K_SERVICE', 'FUNCTION_TARGET'],
558
+ ],
559
+ azure_function: [['WEBSITE_SITE_NAME', 'AZURE_FUNCTIONS_APP_NAME']],
560
+ };
561
+ /**
562
+ * The preset variables to leave out of a serverless simulation, so the
563
+ * user's values (`env`: flags, `--env` and `--env-file` merged) decide the
564
+ * URL:
565
+ *
566
+ * - The SDK uses a platform's function URL variable before it builds the URL
567
+ * from the parts, so when the user sets a part without the URL, the
568
+ * preset's URL is left out.
569
+ * - The SDK reads some parts under two names, preferring one. When the user
570
+ * sets a part under the other name only, the preset's preferred one is
571
+ * left out.
572
+ */
573
+ function presetVariablesToOmit(platform, env) {
574
+ const omit = new Set();
575
+ const spec = URL_PARTS[platform];
576
+ if (spec && !(spec.url in env) && spec.parts.some((part) => part in env))
577
+ omit.add(spec.url);
578
+ for (const names of URL_PART_NAMES[platform] ?? []) {
579
+ const first = names.findIndex((name) => name in env);
580
+ if (first > 0)
581
+ for (const name of names.slice(0, first))
582
+ omit.add(name);
242
583
  }
243
- // Apply env vars
584
+ return [...omit];
585
+ }
586
+ function applyEnvironment(opts, io) {
587
+ const env = {};
244
588
  if (opts.envFile) {
245
- loadEnvFile(opts.envFile);
589
+ Object.assign(env, loadEnvFile(opts.envFile));
590
+ io.verbose(`Loaded ${Object.keys(env).length} environment variables from ${opts.envFile}`);
246
591
  }
247
- for (const [k, v] of Object.entries(opts.envVars)) {
248
- process.env[k] = v;
592
+ for (const entry of opts.envVars) {
593
+ const eq = entry.indexOf('=');
594
+ if (eq <= 0)
595
+ throw usageError(`--env requires KEY=VALUE, got ${entry}`);
596
+ env[entry.slice(0, eq)] = entry.slice(eq + 1);
249
597
  }
250
- // List agents action (doesn't need a loaded agent)
251
- if (opts.action === 'list-agents') {
252
- const agents = await listAgents(opts.agentPath);
253
- if (opts.raw || opts.formatJson) {
254
- console.log(JSON.stringify(agents, null, 2));
598
+ if (!opts.simulateServerless) {
599
+ Object.assign(process.env, env);
600
+ return null;
601
+ }
602
+ const platform = SIMULATED_PLATFORMS[opts.simulateServerless];
603
+ const set = (key, value) => {
604
+ if (value)
605
+ env[key] = value;
606
+ };
607
+ if (platform === 'lambda') {
608
+ set('AWS_LAMBDA_FUNCTION_NAME', opts.awsFunctionName);
609
+ set('AWS_LAMBDA_FUNCTION_URL', opts.awsFunctionUrl);
610
+ set('AWS_REGION', opts.awsRegion);
611
+ // Behind API Gateway, the agent's URL is the gateway's.
612
+ if (opts.awsApiGatewayId && opts.awsFunctionUrl) {
613
+ io.err('Warning: --aws-api-gateway-id is ignored when --aws-function-url is set');
255
614
  }
256
- else {
257
- console.log(`\nExported agents in ${opts.agentPath}:\n`);
258
- for (const name of agents) {
259
- console.log(` ${name}`);
260
- }
261
- console.log();
615
+ else if (opts.awsApiGatewayId) {
616
+ env['AWS_LAMBDA_FUNCTION_URL'] =
617
+ `https://${opts.awsApiGatewayId}.execute-api.${opts.awsRegion || 'us-east-1'}` +
618
+ `.amazonaws.com/${opts.awsStage || 'prod'}`;
619
+ }
620
+ else if (opts.awsStage) {
621
+ io.err('Warning: --aws-stage only applies with --aws-api-gateway-id');
262
622
  }
263
- return;
264
623
  }
265
- // Load agent
266
- const agent = await loadAgent(opts.agentPath, opts.agentClass);
267
- // Apply --route override
268
- if (opts.route && typeof agent.route !== 'undefined') {
269
- agent.route = opts.route;
270
- }
271
- // Handle --simulate-serverless
272
- if (opts.simulateServerless) {
273
- const platform = opts.simulateServerless;
274
- const adapter = new ServerlessAdapter(platform);
275
- const app = agent.getApp();
276
- const postData = generateFakePostData({
277
- callType: opts.callType,
278
- callDirection: opts.callDirection,
279
- callState: opts.callState,
280
- callId: opts.callId,
281
- fromNumber: opts.fromNumber,
282
- toExtension: opts.toExtension,
283
- overrides: opts.overrides,
284
- });
285
- const event = {
286
- httpMethod: 'POST',
287
- path: agent.route ?? '/',
288
- headers: {
289
- 'content-type': 'application/json',
290
- 'authorization': 'Basic ' + Buffer.from(`${agent.basicAuthCreds?.[0] ?? 'user'}:${agent.basicAuthCreds?.[1] ?? 'pass'}`).toString('base64'),
291
- },
292
- body: postData,
293
- };
294
- const response = await adapter.handleRequest(app, event);
624
+ else if (platform === 'cgi') {
625
+ set('HTTP_HOST', opts.cgiHost);
626
+ set('SERVER_NAME', opts.cgiHost);
627
+ set('SCRIPT_NAME', opts.cgiScriptName);
628
+ if (opts.cgiHttps)
629
+ env['HTTPS'] = 'on';
630
+ set('PATH_INFO', opts.cgiPathInfo);
631
+ }
632
+ else if (platform === 'cloud_function') {
633
+ set('GOOGLE_CLOUD_PROJECT', opts.gcpProject);
634
+ set('FUNCTION_URL', opts.gcpFunctionUrl);
635
+ set('GOOGLE_CLOUD_REGION', opts.gcpRegion);
636
+ set('K_SERVICE', opts.gcpService);
637
+ }
638
+ else if (platform === 'azure_function') {
639
+ set('AZURE_FUNCTIONS_ENVIRONMENT', opts.azureEnv);
640
+ set('AZURE_FUNCTION_URL', opts.azureFunctionUrl);
641
+ }
642
+ // The user's values, by flag, --env or --env-file, decide the URL: an
643
+ // empty override leaves out a preset variable that would win over them.
644
+ for (const name of presetVariablesToOmit(platform, env))
645
+ env[name] = '';
646
+ const simulator = new ServerlessSimulator(platform, env);
647
+ simulator.activate();
648
+ io.verbose(`Simulating ${platform}: ${JSON.stringify(simulator.environment)}`);
649
+ return simulator;
650
+ }
651
+ async function run(opts, io) {
652
+ if (opts.action === 'list-agents') {
653
+ const agents = await describeAgents(opts.agentPath);
295
654
  if (opts.raw || opts.formatJson) {
296
- try {
297
- console.log(JSON.stringify(JSON.parse(response.body), null, 2));
298
- }
299
- catch {
300
- console.log(response.body);
301
- }
655
+ io.out(JSON.stringify(agents, null, 2));
656
+ return 0;
302
657
  }
303
- else {
304
- console.log(`\n--- Serverless Simulation (${platform}) ---`);
305
- console.log(`Status: ${response.statusCode}`);
306
- console.log(`Headers: ${JSON.stringify(response.headers, null, 2)}`);
307
- console.log('Body:');
308
- try {
309
- console.log(JSON.stringify(JSON.parse(response.body), null, 2));
310
- }
311
- catch {
312
- console.log(response.body);
658
+ if (agents.length === 0) {
659
+ io.out(`No agents found in ${opts.agentPath}`);
660
+ return 1;
661
+ }
662
+ io.out(`\nAgents found in ${opts.agentPath}:`);
663
+ for (const a of agents) {
664
+ io.out(` ${a.name} (${a.kind})`);
665
+ if (a.kind === 'instance') {
666
+ io.out(` Name: ${a.agentName}`);
667
+ io.out(` Route: ${a.route}`);
313
668
  }
314
- console.log();
315
669
  }
316
- return;
670
+ return 0;
317
671
  }
318
- switch (opts.action) {
319
- case 'list-tools': {
320
- // getRegisteredTools is on SWMLService now, so AgentBase and
321
- // standalone SWMLService instances both work here.
322
- if (typeof agent.getRegisteredTools !== 'function') {
323
- console.log('This target does not expose getRegisteredTools(); use --dump-swml.');
324
- break;
325
- }
326
- const tools = agent.getRegisteredTools();
327
- if (opts.raw || opts.formatJson) {
328
- console.log(JSON.stringify(tools, null, 2));
329
- }
672
+ const target = (await loadAgent(opts.agentPath, opts.agentClass, {
673
+ route: opts.route,
674
+ }));
675
+ const headers = {};
676
+ for (const entry of opts.headers) {
677
+ const eq = entry.indexOf('=');
678
+ if (eq <= 0)
679
+ throw usageError(`--header requires NAME=VALUE, got ${entry}`);
680
+ headers[entry.slice(0, eq)] = entry.slice(eq + 1);
681
+ }
682
+ const client = new Client(target, headers);
683
+ const flags = {
684
+ callId: opts.callId,
685
+ projectId: opts.projectId,
686
+ spaceId: opts.spaceId,
687
+ callState: opts.callState,
688
+ callDirection: opts.callDirection,
689
+ callType: opts.callType,
690
+ fromNumber: opts.fromNumber,
691
+ toExtension: opts.toExtension,
692
+ userVars: parseJsonOption('--user-vars', opts.userVars, io),
693
+ queryParams: parseJsonOption('--query-params', opts.queryParams, io),
694
+ };
695
+ const swmlPostData = () => applyOverrides(applyConvenienceMappings(fakeSwmlPostData(opts.callType, opts.callDirection, opts.callState), flags), opts.overrides, opts.overrideJson, io.err);
696
+ if (opts.action === 'dump-swml') {
697
+ const doc = await fetchSwml(client, opts, swmlPostData(), io);
698
+ io.out(opts.raw ? JSON.stringify(doc) : JSON.stringify(doc, null, 2));
699
+ return 0;
700
+ }
701
+ // A plain SWMLService has no SWAIG block to read; use its registry.
702
+ if (!isAgent(target)) {
703
+ const tools = target.getRegisteredTools?.() ?? [];
704
+ if (opts.action === 'list-tools') {
705
+ if (opts.raw || opts.formatJson)
706
+ io.out(JSON.stringify(tools, null, 2));
330
707
  else {
331
- if (tools.length === 0) {
332
- console.log('No tools registered.');
333
- }
334
- else {
335
- console.log(`\nRegistered tools (${tools.length}):\n`);
336
- for (const tool of tools) {
337
- console.log(` ${tool.name}`);
338
- console.log(` Description: ${tool.description}`);
339
- if (tool.parameters && Object.keys(tool.parameters).length) {
340
- console.log(` Parameters: ${JSON.stringify(tool.parameters, null, 6).replace(/\n/g, '\n ')}`);
341
- }
342
- console.log();
343
- }
708
+ io.out('\nAvailable SWAIG functions:');
709
+ if (tools.length === 0)
710
+ io.out(' No SWAIG functions registered');
711
+ for (const t of tools) {
712
+ io.out(` ${t.name} - ${t.description} (LOCAL webhook)`);
713
+ printParameters(io, t.parameters);
344
714
  }
345
715
  }
346
- break;
716
+ return 0;
347
717
  }
348
- case 'dump-swml': {
349
- // SWMLService.renderSwml() returns an object; AgentBase.renderSwml() returns a string.
350
- // Use `getPrompt` as the discriminator — agent-only — because
351
- // getRegisteredTools is now on both classes.
352
- let swmlJson;
353
- if (typeof agent.getPrompt !== 'function') {
354
- // SWMLService — renderSwml returns object directly
355
- swmlJson = agent.renderSwml();
356
- }
357
- else {
358
- // AgentBase — renderSwml(callId) returns JSON string
359
- const postData = generateFakePostData({
360
- callType: opts.callType,
361
- callDirection: opts.callDirection,
362
- callState: opts.callState,
363
- callId: opts.callId,
364
- fromNumber: opts.fromNumber,
365
- toExtension: opts.toExtension,
366
- overrides: opts.overrides,
367
- });
368
- swmlJson = JSON.parse(agent.renderSwml(postData['call_id']));
369
- }
370
- if (opts.raw || opts.formatJson) {
371
- console.log(JSON.stringify(swmlJson, null, 2));
372
- }
373
- else {
374
- console.log('\n--- SWML Document ---\n');
375
- console.log(JSON.stringify(swmlJson, null, 2));
376
- console.log();
377
- }
378
- break;
718
+ const tool = tools.find((t) => t.name === opts.execName);
719
+ if (!tool) {
720
+ io.out(`Error: Function '${opts.execName}' not found.`);
721
+ return 1;
379
722
  }
380
- case 'exec': {
381
- if (!opts.execName) {
382
- console.error('Error: --exec requires a function name');
383
- process.exit(1);
384
- }
385
- const tool = agent.getTool(opts.execName);
386
- if (!tool) {
387
- console.error(`Error: function '${opts.execName}' not found`);
388
- const available = agent.getRegisteredTools().map((t) => t.name);
389
- if (available.length) {
390
- console.error(`Available functions: ${available.join(', ')}`);
391
- }
392
- process.exit(1);
393
- }
394
- const postData = generateMinimalPostData(opts.execName, opts.args, {
395
- callId: opts.callId,
396
- overrides: opts.overrides,
723
+ let args;
724
+ try {
725
+ args = parseFunctionArguments(opts.functionTokens, tool.parameters);
726
+ }
727
+ catch (err) {
728
+ io.out(`Error parsing arguments: ${err instanceof Error ? err.message : err}`);
729
+ return 1;
730
+ }
731
+ for (const w of undeclaredArgumentWarnings(args, tool.parameters, CLI_OPTIONS))
732
+ io.err(w);
733
+ // Through the service's own /swaig route, as a call would reach it.
734
+ const request = functionRequestData(opts, flags, io);
735
+ const body = JSON.stringify({
736
+ ...request,
737
+ params: args,
738
+ function: tool.name,
739
+ argument: { parsed: [args], raw: JSON.stringify(args) },
740
+ });
741
+ return printCallResult(await client.send('POST', `${client.prefix}/swaig`, body), opts, io);
742
+ }
743
+ if (opts.action === 'list-tools') {
744
+ const doc = await fetchSwml(client, opts, swmlPostData(), io);
745
+ const { functions, defaultUrl } = swaigOf(doc);
746
+ if (opts.raw || opts.formatJson) {
747
+ const list = functions.map((f) => {
748
+ const kind = kindOf(target, client, f, defaultUrl);
749
+ return {
750
+ name: f.function,
751
+ description: f.description ?? '',
752
+ parameters: f.parameters ?? {},
753
+ type: kind,
754
+ ...(kind === 'external' ? { web_hook_url: f.web_hook_url ?? defaultUrl } : {}),
755
+ };
397
756
  });
398
- if (!opts.raw) {
399
- console.log(`\nExecuting: ${opts.execName}`);
400
- if (Object.keys(opts.args).length) {
401
- console.log(`Arguments: ${JSON.stringify(opts.args)}`);
402
- }
403
- console.log();
404
- }
405
- const result = await tool.execute(opts.args, postData);
406
- if (opts.raw || opts.formatJson) {
407
- console.log(JSON.stringify(result, null, 2));
408
- }
409
- else {
410
- console.log('--- Result ---\n');
411
- console.log(JSON.stringify(result, null, 2));
412
- console.log();
413
- }
414
- break;
757
+ io.out(JSON.stringify(list, null, 2));
758
+ return 0;
759
+ }
760
+ io.out('\nAvailable SWAIG functions:');
761
+ if (functions.length === 0)
762
+ io.out(' No SWAIG functions registered');
763
+ for (const f of functions) {
764
+ const kind = kindOf(target, client, f, defaultUrl);
765
+ const suffix = kind === 'local' ? ' (LOCAL webhook)' : kind === 'external' ? ' (EXTERNAL webhook)' : '';
766
+ const description = f.description ?? (kind === 'datamap' ? 'DataMap function (serverless)' : '');
767
+ io.out(` ${f.function} - ${description}${suffix}`);
768
+ if (kind === 'external')
769
+ io.out(` External URL: ${f.web_hook_url ?? defaultUrl}`);
770
+ printParameters(io, f.parameters);
771
+ if (opts.verbose)
772
+ io.out(` Config: ${JSON.stringify(f, null, 2).replace(/\n/g, '\n ')}`);
773
+ }
774
+ return 0;
775
+ }
776
+ // --exec: the SWML for the call names the function and where to call it.
777
+ // The SWML request and the function request describe the same call.
778
+ const name = opts.execName;
779
+ const callData = functionRequestData(opts, flags, io, name);
780
+ const callId = String(callData['call_id'] ?? callData['call']?.['call_id'] ?? '');
781
+ const swmlData = applyOverrides(applyConvenienceMappings(fakeSwmlPostData(opts.callType, opts.callDirection, opts.callState), {
782
+ ...flags,
783
+ callId,
784
+ }), opts.overrides, opts.overrideJson, () => undefined);
785
+ const doc = await fetchSwml(client, opts, swmlData, io);
786
+ const { functions, defaultUrl, globalData } = swaigOf(doc);
787
+ const entry = functions.find((f) => f.function === name);
788
+ if (!entry) {
789
+ io.out(`Error: Function '${name}' not found.`);
790
+ io.out(`Available functions: ${functions.map((f) => f.function).join(', ') || '(none)'}`);
791
+ return 1;
792
+ }
793
+ let args;
794
+ try {
795
+ args = parseFunctionArguments(opts.functionTokens, entry.parameters);
796
+ }
797
+ catch (err) {
798
+ io.out(`Error parsing arguments: ${err instanceof Error ? err.message : err}`);
799
+ return 1;
800
+ }
801
+ for (const w of undeclaredArgumentWarnings(args, entry.parameters, CLI_OPTIONS))
802
+ io.err(w);
803
+ const kind = kindOf(target, client, entry, defaultUrl);
804
+ io.verbose(`\nCalling ${kind === 'datamap' ? 'DataMap' : kind === 'external' ? 'EXTERNAL webhook' : 'LOCAL webhook'} function: ${name}`);
805
+ io.verbose(`Arguments: ${JSON.stringify(args, null, 2)}`);
806
+ let result;
807
+ if (kind === 'datamap') {
808
+ // --custom-data is the call data the platform adds, such as global_data.
809
+ // It was parsed, and any warning given, for the function request above.
810
+ // Without its global_data, the global data in the agent's SWML applies,
811
+ // as a call starts with it.
812
+ const custom = parseJsonOption('--custom-data', opts.customData, {
813
+ ...io,
814
+ err: () => undefined,
815
+ });
816
+ if (!Object.hasOwn(custom, 'global_data') && globalData && Object.keys(globalData).length) {
817
+ custom['global_data'] = structuredClone(globalData);
818
+ }
819
+ result = await executeDataMap(entry, args, {
820
+ verbose: opts.verbose && !opts.raw,
821
+ ...(Object.keys(custom).length ? { callData: custom } : {}),
822
+ });
823
+ }
824
+ else {
825
+ const payload = {
826
+ ...callData,
827
+ params: args,
828
+ call_id: callId,
829
+ function: name,
830
+ argument: { parsed: [args], raw: JSON.stringify(args) },
831
+ };
832
+ const body = JSON.stringify(payload);
833
+ io.verbose(`Request: ${body}`);
834
+ const url = entry.web_hook_url ?? defaultUrl ?? '';
835
+ if (kind === 'local') {
836
+ return printCallResult(await client.send('POST', localPath(target, client, url), body), opts, io);
837
+ }
838
+ io.verbose(`External URL: ${url}`);
839
+ return printCallResult(await postExternal(url, body), opts, io);
840
+ }
841
+ if (opts.raw || opts.formatJson)
842
+ io.out(JSON.stringify(result, null, 2));
843
+ else
844
+ io.out(`RESULT:\n${formatResult(result)}`);
845
+ // When nothing produced a result, the platform answers with its generic
846
+ // error. That is a valid result, not a tool failure, so the exit status is
847
+ // 0, as it is when the expanded output isn't JSON and the result says so.
848
+ const r = (result ?? {});
849
+ if (Object.keys(r).length === 1 && r['response'] === PLATFORM_ERROR_RESPONSE) {
850
+ io.err('Nothing produced a result: no expression matched, no webhook succeeded with an ' +
851
+ 'output, and there is no data_map output. The platform answers with its generic error.');
852
+ }
853
+ return 0;
854
+ }
855
+ /** The function request for --exec: minimal or full, with the call flags and overrides. */
856
+ function functionRequestData(opts, flags, io, name = opts.execName ?? '') {
857
+ const custom = parseJsonOption('--custom-data', opts.customData, io);
858
+ const skeleton = opts.minimal
859
+ ? { ...minimalPostData({}), ...custom }
860
+ : comprehensivePostData(name, {}, custom);
861
+ return applyOverrides(applyConvenienceMappings(skeleton, flags), opts.overrides, opts.overrideJson, io.err);
862
+ }
863
+ /** Seconds to wait for an external webhook. */
864
+ const EXTERNAL_TIMEOUT = 30;
865
+ /** POST to an external webhook; credentials in its URL become basic auth. */
866
+ async function postExternal(url, body) {
867
+ const target = new URL(url);
868
+ const headers = {
869
+ 'Content-Type': 'application/json',
870
+ 'User-Agent': 'SignalWire-SWAIG-Test/1.0',
871
+ };
872
+ if (target.username || target.password) {
873
+ const creds = `${decodeURIComponent(target.username)}:${decodeURIComponent(target.password)}`;
874
+ headers['Authorization'] = 'Basic ' + Buffer.from(creds).toString('base64');
875
+ target.username = '';
876
+ target.password = '';
877
+ }
878
+ return fetch(target, {
879
+ method: 'POST',
880
+ headers,
881
+ body,
882
+ signal: AbortSignal.timeout(EXTERNAL_TIMEOUT * 1000),
883
+ });
884
+ }
885
+ /** Print the SWAIG response of a function call; exit status 1 unless it's 2xx. */
886
+ async function printCallResult(res, opts, io) {
887
+ const text = await res.text();
888
+ if (!res.ok) {
889
+ io.out(`Error calling function: HTTP ${res.status}: ${text}`);
890
+ return 1;
891
+ }
892
+ let result;
893
+ try {
894
+ result = JSON.parse(text);
895
+ }
896
+ catch {
897
+ result = { response: text };
898
+ }
899
+ if (opts.raw || opts.formatJson)
900
+ io.out(JSON.stringify(result, null, 2));
901
+ else
902
+ io.out(`RESULT:\n${formatResult(result)}`);
903
+ return 0;
904
+ }
905
+ async function main() {
906
+ let argv = process.argv.slice(2);
907
+ // --parse-only / --dry-run: stripped first, so it works wherever it is,
908
+ // even after --exec's arguments.
909
+ const parseOnly = argv.includes('--parse-only') || argv.includes('--dry-run');
910
+ argv = argv.filter((a) => a !== '--parse-only' && a !== '--dry-run');
911
+ if (argv.includes('--help-platforms')) {
912
+ printHelpPlatforms();
913
+ return 0;
914
+ }
915
+ if (argv.includes('--help-examples')) {
916
+ printHelpExamples();
917
+ return 0;
918
+ }
919
+ const beforeExec = argv.includes('--exec') ? argv.slice(0, argv.indexOf('--exec')) : argv;
920
+ if (beforeExec.includes('--help') ||
921
+ beforeExec.includes('-h') ||
922
+ (argv.length === 0 && !parseOnly)) {
923
+ printHelp();
924
+ return 0;
925
+ }
926
+ let opts;
927
+ try {
928
+ opts = parseArgs(argv);
929
+ }
930
+ catch (err) {
931
+ if (!isUsageError(err))
932
+ throw err;
933
+ console.error(`Error: ${err.message}\n\n${USAGE}\nFor full help: swaig-test --help`);
934
+ return 2;
935
+ }
936
+ if (parseOnly) {
937
+ console.log('parse OK');
938
+ return 0;
939
+ }
940
+ if (!opts.action) {
941
+ if (!opts.simulateServerless) {
942
+ console.error('Error: one of --dump-swml, --list-tools, or --exec is required');
943
+ return 2;
415
944
  }
945
+ opts.action = 'dump-swml';
946
+ }
947
+ const quiet = opts.raw || (opts.action === 'dump-swml' && !opts.verbose);
948
+ if (quiet)
949
+ suppressAllLogs(true);
950
+ else
951
+ setGlobalLogLevel(opts.verbose ? 'debug' : 'error');
952
+ const io = {
953
+ out: (line) => console.log(line),
954
+ err: (line) => console.error(line),
955
+ verbose: (line) => {
956
+ if (opts.verbose && !opts.raw)
957
+ console.log(line);
958
+ },
959
+ };
960
+ let simulator = null;
961
+ try {
962
+ simulator = applyEnvironment(opts, io);
963
+ return await run(opts, io);
964
+ }
965
+ catch (err) {
966
+ if (isUsageError(err)) {
967
+ console.error(`Error: ${err.message}`);
968
+ return 2;
969
+ }
970
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
971
+ if (opts.verbose && err instanceof Error && err.stack)
972
+ console.error(err.stack);
973
+ return 1;
974
+ }
975
+ finally {
976
+ simulator?.deactivate();
416
977
  }
417
978
  }
418
- main().catch((err) => {
419
- console.error(err.message ?? err);
420
- process.exit(1);
979
+ // exitCode rather than exit(), so piped output is flushed first.
980
+ main().then((code) => {
981
+ process.exitCode = code;
982
+ }, (err) => {
983
+ console.error(err instanceof Error ? err.message : String(err));
984
+ process.exitCode = 1;
421
985
  });
422
986
  //# sourceMappingURL=swaig-test.js.map