@signalwire/sdk 2.0.5 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (656) hide show
  1. package/CHANGELOG.md +785 -0
  2. package/LICENSE +21 -0
  3. package/README.md +163 -68
  4. package/dist/AGENTS.md +13 -0
  5. package/dist/AgentBase.d.ts +481 -126
  6. package/dist/AgentBase.js +1502 -438
  7. package/dist/AgentBase.js.map +1 -1
  8. package/dist/AgentServer.d.ts +21 -0
  9. package/dist/AgentServer.js +154 -47
  10. package/dist/AgentServer.js.map +1 -1
  11. package/dist/AuthHandler.d.ts +14 -2
  12. package/dist/AuthHandler.js +7 -2
  13. package/dist/AuthHandler.js.map +1 -1
  14. package/dist/ConfigLoader.d.ts +5 -13
  15. package/dist/ConfigLoader.js +15 -29
  16. package/dist/ConfigLoader.js.map +1 -1
  17. package/dist/ContextBuilder.d.ts +202 -9
  18. package/dist/ContextBuilder.js +219 -36
  19. package/dist/ContextBuilder.js.map +1 -1
  20. package/dist/DataMap.d.ts +158 -45
  21. package/dist/DataMap.js +167 -52
  22. package/dist/DataMap.js.map +1 -1
  23. package/dist/FunctionResult.d.ts +277 -83
  24. package/dist/FunctionResult.js +444 -116
  25. package/dist/FunctionResult.js.map +1 -1
  26. package/dist/Logger.d.ts +30 -5
  27. package/dist/Logger.js +77 -19
  28. package/dist/Logger.js.map +1 -1
  29. package/dist/POM/PromptObjectModel.d.ts +12 -1
  30. package/dist/POM/PromptObjectModel.js +25 -9
  31. package/dist/POM/PromptObjectModel.js.map +1 -1
  32. package/dist/ParameterSchema.d.ts +306 -0
  33. package/dist/ParameterSchema.js +251 -0
  34. package/dist/ParameterSchema.js.map +1 -0
  35. package/dist/PlatformContracts.d.ts +21 -0
  36. package/dist/PlatformContracts.generated.d.ts +109 -0
  37. package/dist/PlatformContracts.generated.js +8 -0
  38. package/dist/PlatformContracts.generated.js.map +1 -0
  39. package/dist/PlatformContracts.js +2 -0
  40. package/dist/PlatformContracts.js.map +1 -0
  41. package/dist/PomBuilder.d.ts +18 -0
  42. package/dist/PomBuilder.js +53 -3
  43. package/dist/PomBuilder.js.map +1 -1
  44. package/dist/PostPrompt.d.ts +110 -0
  45. package/dist/PostPrompt.js +204 -0
  46. package/dist/PostPrompt.js.map +1 -0
  47. package/dist/PromptManager.d.ts +22 -1
  48. package/dist/PromptManager.js +28 -1
  49. package/dist/PromptManager.js.map +1 -1
  50. package/dist/PublicFetch.d.ts +132 -0
  51. package/dist/PublicFetch.js +311 -0
  52. package/dist/PublicFetch.js.map +1 -0
  53. package/dist/RobotsTxt.d.ts +41 -0
  54. package/dist/RobotsTxt.js +152 -0
  55. package/dist/RobotsTxt.js.map +1 -0
  56. package/dist/SWMLHandler.js.map +1 -1
  57. package/dist/SWMLService.d.ts +158 -58
  58. package/dist/SWMLService.js +435 -127
  59. package/dist/SWMLService.js.map +1 -1
  60. package/dist/SchemaUtils.d.ts +115 -2
  61. package/dist/SchemaUtils.js +444 -12
  62. package/dist/SchemaUtils.js.map +1 -1
  63. package/dist/SecurityUtils.d.ts +49 -9
  64. package/dist/SecurityUtils.js +153 -51
  65. package/dist/SecurityUtils.js.map +1 -1
  66. package/dist/ServerlessAdapter.d.ts +156 -7
  67. package/dist/ServerlessAdapter.js +399 -42
  68. package/dist/ServerlessAdapter.js.map +1 -1
  69. package/dist/SessionManager.d.ts +11 -2
  70. package/dist/SessionManager.js +50 -18
  71. package/dist/SessionManager.js.map +1 -1
  72. package/dist/SslConfig.d.ts +2 -1
  73. package/dist/SslConfig.js +4 -1
  74. package/dist/SslConfig.js.map +1 -1
  75. package/dist/SwaigActions.generated.d.ts +23 -0
  76. package/dist/SwaigActions.generated.js +8 -0
  77. package/dist/SwaigActions.generated.js.map +1 -0
  78. package/dist/SwaigContracts.d.ts +15 -0
  79. package/dist/SwaigContracts.generated.d.ts +264 -0
  80. package/dist/SwaigContracts.generated.js +12 -0
  81. package/dist/SwaigContracts.generated.js.map +1 -0
  82. package/dist/SwaigContracts.js +2 -0
  83. package/dist/SwaigContracts.js.map +1 -0
  84. package/dist/SwaigFunction.d.ts +110 -4
  85. package/dist/SwaigFunction.js +151 -19
  86. package/dist/SwaigFunction.js.map +1 -1
  87. package/dist/SwmlBuilder.d.ts +68 -19
  88. package/dist/SwmlBuilder.js +74 -38
  89. package/dist/SwmlBuilder.js.map +1 -1
  90. package/dist/SwmlVerbMethods.generated.d.ts +41 -4
  91. package/dist/SwmlVerbMethods.generated.js +1 -1
  92. package/dist/TypeInference.d.ts +39 -3
  93. package/dist/TypeInference.js +256 -16
  94. package/dist/TypeInference.js.map +1 -1
  95. package/dist/WebService.d.ts +79 -11
  96. package/dist/WebService.js +320 -109
  97. package/dist/WebService.js.map +1 -1
  98. package/dist/WebhookMiddleware.d.ts +119 -0
  99. package/dist/WebhookMiddleware.js +271 -0
  100. package/dist/WebhookMiddleware.js.map +1 -0
  101. package/dist/WebhookValidator.d.ts +92 -0
  102. package/dist/WebhookValidator.js +409 -0
  103. package/dist/WebhookValidator.js.map +1 -0
  104. package/dist/agents/BedrockAgent.d.ts +162 -0
  105. package/dist/agents/BedrockAgent.js +323 -0
  106. package/dist/agents/BedrockAgent.js.map +1 -0
  107. package/dist/ai-chat/AIChatClient.d.ts +316 -0
  108. package/dist/ai-chat/AIChatClient.js +535 -0
  109. package/dist/ai-chat/AIChatClient.js.map +1 -0
  110. package/dist/ai-chat/ChatGateway.d.ts +408 -0
  111. package/dist/ai-chat/ChatGateway.js +747 -0
  112. package/dist/ai-chat/ChatGateway.js.map +1 -0
  113. package/dist/ai-chat/HandoffRouter.d.ts +282 -0
  114. package/dist/ai-chat/HandoffRouter.js +518 -0
  115. package/dist/ai-chat/HandoffRouter.js.map +1 -0
  116. package/dist/ai-chat/index.d.ts +12 -0
  117. package/dist/ai-chat/index.js +10 -0
  118. package/dist/ai-chat/index.js.map +1 -0
  119. package/dist/capabilities.d.ts +64 -0
  120. package/dist/capabilities.js +95 -0
  121. package/dist/capabilities.js.map +1 -0
  122. package/dist/cli/agent-loader.d.ts +32 -6
  123. package/dist/cli/agent-loader.js +92 -33
  124. package/dist/cli/agent-loader.js.map +1 -1
  125. package/dist/cli/datamap-exec.d.ts +175 -0
  126. package/dist/cli/datamap-exec.js +1284 -0
  127. package/dist/cli/datamap-exec.js.map +1 -0
  128. package/dist/cli/function-args.d.ts +40 -0
  129. package/dist/cli/function-args.js +146 -0
  130. package/dist/cli/function-args.js.map +1 -0
  131. package/dist/cli/simulation.d.ts +99 -0
  132. package/dist/cli/simulation.js +490 -0
  133. package/dist/cli/simulation.js.map +1 -0
  134. package/dist/cli/swaig-test.d.ts +12 -25
  135. package/dist/cli/swaig-test.js +935 -371
  136. package/dist/cli/swaig-test.js.map +1 -1
  137. package/dist/cli/tsdocs/agentsNote.d.ts +30 -0
  138. package/dist/cli/tsdocs/agentsNote.js +92 -0
  139. package/dist/cli/tsdocs/agentsNote.js.map +1 -0
  140. package/dist/cli/tsdocs/api-index.json +1 -0
  141. package/dist/cli/tsdocs/api.d.ts +91 -0
  142. package/dist/cli/tsdocs/api.js +372 -0
  143. package/dist/cli/tsdocs/api.js.map +1 -0
  144. package/dist/cli/tsdocs/apiTypes.d.ts +64 -0
  145. package/dist/cli/tsdocs/apiTypes.js +7 -0
  146. package/dist/cli/tsdocs/apiTypes.js.map +1 -0
  147. package/dist/cli/tsdocs/bin.d.ts +6 -0
  148. package/dist/cli/tsdocs/bin.js +23 -0
  149. package/dist/cli/tsdocs/bin.js.map +1 -0
  150. package/dist/cli/tsdocs/files.d.ts +108 -0
  151. package/dist/cli/tsdocs/files.js +287 -0
  152. package/dist/cli/tsdocs/files.js.map +1 -0
  153. package/dist/cli/tsdocs/index.d.ts +28 -0
  154. package/dist/cli/tsdocs/index.js +307 -0
  155. package/dist/cli/tsdocs/index.js.map +1 -0
  156. package/dist/cli/tsdocs/live.d.ts +41 -0
  157. package/dist/cli/tsdocs/live.js +202 -0
  158. package/dist/cli/tsdocs/live.js.map +1 -0
  159. package/dist/cli/tsdocs/locate.d.ts +51 -0
  160. package/dist/cli/tsdocs/locate.js +75 -0
  161. package/dist/cli/tsdocs/locate.js.map +1 -0
  162. package/dist/cli/tsdocs/render.d.ts +75 -0
  163. package/dist/cli/tsdocs/render.js +323 -0
  164. package/dist/cli/tsdocs/render.js.map +1 -0
  165. package/dist/cli/tsdocs/topics.d.ts +43 -0
  166. package/dist/cli/tsdocs/topics.js +916 -0
  167. package/dist/cli/tsdocs/topics.js.map +1 -0
  168. package/dist/index.d.ts +47 -68
  169. package/dist/index.js +44 -73
  170. package/dist/index.js.map +1 -1
  171. package/dist/livewire/index.d.ts +229 -155
  172. package/dist/livewire/index.js +298 -195
  173. package/dist/livewire/index.js.map +1 -1
  174. package/dist/llms.txt +65 -0
  175. package/dist/prefabs/CallSessionStore.d.ts +52 -0
  176. package/dist/prefabs/CallSessionStore.js +72 -0
  177. package/dist/prefabs/CallSessionStore.js.map +1 -0
  178. package/dist/prefabs/ConciergeAgent.d.ts +13 -1
  179. package/dist/prefabs/ConciergeAgent.js +36 -31
  180. package/dist/prefabs/ConciergeAgent.js.map +1 -1
  181. package/dist/prefabs/FAQBotAgent.d.ts +9 -1
  182. package/dist/prefabs/FAQBotAgent.js +113 -47
  183. package/dist/prefabs/FAQBotAgent.js.map +1 -1
  184. package/dist/prefabs/InfoGathererAgent.d.ts +22 -3
  185. package/dist/prefabs/InfoGathererAgent.js +67 -58
  186. package/dist/prefabs/InfoGathererAgent.js.map +1 -1
  187. package/dist/prefabs/ReceptionistAgent.d.ts +16 -5
  188. package/dist/prefabs/ReceptionistAgent.js +39 -31
  189. package/dist/prefabs/ReceptionistAgent.js.map +1 -1
  190. package/dist/prefabs/SurveyAgent.d.ts +22 -4
  191. package/dist/prefabs/SurveyAgent.js +84 -68
  192. package/dist/prefabs/SurveyAgent.js.map +1 -1
  193. package/dist/relay/Action.d.ts +44 -21
  194. package/dist/relay/Action.js +75 -17
  195. package/dist/relay/Action.js.map +1 -1
  196. package/dist/relay/Call.d.ts +312 -47
  197. package/dist/relay/Call.js +369 -18
  198. package/dist/relay/Call.js.map +1 -1
  199. package/dist/relay/Deferred.js.map +1 -1
  200. package/dist/relay/Message.d.ts +26 -5
  201. package/dist/relay/Message.js +36 -6
  202. package/dist/relay/Message.js.map +1 -1
  203. package/dist/relay/RelayClient.d.ts +44 -17
  204. package/dist/relay/RelayClient.js +175 -65
  205. package/dist/relay/RelayClient.js.map +1 -1
  206. package/dist/relay/RelayError.d.ts +14 -0
  207. package/dist/relay/RelayError.js +15 -0
  208. package/dist/relay/RelayError.js.map +1 -1
  209. package/dist/relay/RelayEvent.d.ts +96 -65
  210. package/dist/relay/RelayEvent.js +85 -56
  211. package/dist/relay/RelayEvent.js.map +1 -1
  212. package/dist/relay/closedSets.d.ts +111 -0
  213. package/dist/relay/closedSets.js +83 -0
  214. package/dist/relay/closedSets.js.map +1 -0
  215. package/dist/relay/index.d.ts +3 -1
  216. package/dist/relay/index.js +1 -0
  217. package/dist/relay/index.js.map +1 -1
  218. package/dist/relay/normalize.js.map +1 -1
  219. package/dist/relay/protocol.types.generated.d.ts +1195 -0
  220. package/dist/relay/protocol.types.generated.js +8 -0
  221. package/dist/relay/protocol.types.generated.js.map +1 -0
  222. package/dist/relay/types.d.ts +73 -42
  223. package/dist/rest/HttpClient.d.ts +36 -8
  224. package/dist/rest/HttpClient.js +233 -40
  225. package/dist/rest/HttpClient.js.map +1 -1
  226. package/dist/rest/RequestOptions.d.ts +110 -0
  227. package/dist/rest/RequestOptions.js +113 -0
  228. package/dist/rest/RequestOptions.js.map +1 -0
  229. package/dist/rest/RestError.d.ts +52 -6
  230. package/dist/rest/RestError.js +89 -5
  231. package/dist/rest/RestError.js.map +1 -1
  232. package/dist/rest/base/CrudResource.d.ts +16 -26
  233. package/dist/rest/base/CrudResource.js +19 -33
  234. package/dist/rest/base/CrudResource.js.map +1 -1
  235. package/dist/rest/base/CrudWithAddresses.d.ts +3 -2
  236. package/dist/rest/base/CrudWithAddresses.js +2 -2
  237. package/dist/rest/base/CrudWithAddresses.js.map +1 -1
  238. package/dist/rest/base/FabricResource.d.ts +15 -0
  239. package/dist/rest/base/FabricResource.js +16 -0
  240. package/dist/rest/base/FabricResource.js.map +1 -0
  241. package/dist/rest/base/ReadResource.d.ts +62 -0
  242. package/dist/rest/base/ReadResource.js +69 -0
  243. package/dist/rest/base/ReadResource.js.map +1 -0
  244. package/dist/rest/callHandler.d.ts +5 -2
  245. package/dist/rest/callHandler.js +4 -1
  246. package/dist/rest/callHandler.js.map +1 -1
  247. package/dist/rest/index.d.ts +18 -77
  248. package/dist/rest/index.js +47 -120
  249. package/dist/rest/index.js.map +1 -1
  250. package/dist/rest/namespaces/_client_tree_generated.d.ts +103 -0
  251. package/dist/rest/namespaces/_client_tree_generated.js +171 -0
  252. package/dist/rest/namespaces/_client_tree_generated.js.map +1 -0
  253. package/dist/rest/namespaces/addresses.d.ts +3 -42
  254. package/dist/rest/namespaces/addresses.js +3 -50
  255. package/dist/rest/namespaces/addresses.js.map +1 -1
  256. package/dist/rest/namespaces/calling.d.ts +6 -378
  257. package/dist/rest/namespaces/calling.js +6 -473
  258. package/dist/rest/namespaces/calling.js.map +1 -1
  259. package/dist/rest/namespaces/calling.resources.generated.d.ts +165 -0
  260. package/dist/rest/namespaces/calling.resources.generated.js +477 -0
  261. package/dist/rest/namespaces/calling.resources.generated.js.map +1 -0
  262. package/dist/rest/namespaces/calling.types.generated.d.ts +2917 -0
  263. package/dist/rest/namespaces/calling.types.generated.js +8 -0
  264. package/dist/rest/namespaces/calling.types.generated.js.map +1 -0
  265. package/dist/rest/namespaces/chat.d.ts +4 -18
  266. package/dist/rest/namespaces/chat.js +4 -21
  267. package/dist/rest/namespaces/chat.js.map +1 -1
  268. package/dist/rest/namespaces/chat.resources.generated.d.ts +12 -0
  269. package/dist/rest/namespaces/chat.resources.generated.js +29 -0
  270. package/dist/rest/namespaces/chat.resources.generated.js.map +1 -0
  271. package/dist/rest/namespaces/chat.types.generated.d.ts +56 -0
  272. package/dist/rest/namespaces/chat.types.generated.js +8 -0
  273. package/dist/rest/namespaces/chat.types.generated.js.map +1 -0
  274. package/dist/rest/namespaces/datasphere.d.ts +6 -62
  275. package/dist/rest/namespaces/datasphere.js +6 -72
  276. package/dist/rest/namespaces/datasphere.js.map +1 -1
  277. package/dist/rest/namespaces/datasphere.resources.generated.d.ts +25 -0
  278. package/dist/rest/namespaces/datasphere.resources.generated.js +50 -0
  279. package/dist/rest/namespaces/datasphere.resources.generated.js.map +1 -0
  280. package/dist/rest/namespaces/datasphere.types.generated.d.ts +180 -0
  281. package/dist/rest/namespaces/datasphere.types.generated.js +8 -0
  282. package/dist/rest/namespaces/datasphere.types.generated.js.map +1 -0
  283. package/dist/rest/namespaces/fabric.d.ts +11 -327
  284. package/dist/rest/namespaces/fabric.js +14 -439
  285. package/dist/rest/namespaces/fabric.js.map +1 -1
  286. package/dist/rest/namespaces/fabric.resources.generated.d.ts +195 -0
  287. package/dist/rest/namespaces/fabric.resources.generated.js +399 -0
  288. package/dist/rest/namespaces/fabric.resources.generated.js.map +1 -0
  289. package/dist/rest/namespaces/fabric.types.generated.d.ts +4557 -0
  290. package/dist/rest/namespaces/fabric.types.generated.js +8 -0
  291. package/dist/rest/namespaces/fabric.types.generated.js.map +1 -0
  292. package/dist/rest/namespaces/fax.resources.generated.d.ts +6 -0
  293. package/dist/rest/namespaces/fax.resources.generated.js +14 -0
  294. package/dist/rest/namespaces/fax.resources.generated.js.map +1 -0
  295. package/dist/rest/namespaces/fax.types.generated.d.ts +131 -0
  296. package/dist/rest/namespaces/fax.types.generated.js +8 -0
  297. package/dist/rest/namespaces/fax.types.generated.js.map +1 -0
  298. package/dist/rest/namespaces/imported-numbers.d.ts +3 -18
  299. package/dist/rest/namespaces/imported-numbers.js +3 -21
  300. package/dist/rest/namespaces/imported-numbers.js.map +1 -1
  301. package/dist/rest/namespaces/logs.d.ts +10 -101
  302. package/dist/rest/namespaces/logs.js +10 -128
  303. package/dist/rest/namespaces/logs.js.map +1 -1
  304. package/dist/rest/namespaces/logs.resources.generated.d.ts +9 -0
  305. package/dist/rest/namespaces/logs.resources.generated.js +17 -0
  306. package/dist/rest/namespaces/logs.resources.generated.js.map +1 -0
  307. package/dist/rest/namespaces/logs.types.generated.d.ts +131 -0
  308. package/dist/rest/namespaces/logs.types.generated.js +8 -0
  309. package/dist/rest/namespaces/logs.types.generated.js.map +1 -0
  310. package/dist/rest/namespaces/lookup.d.ts +3 -25
  311. package/dist/rest/namespaces/lookup.js +3 -27
  312. package/dist/rest/namespaces/lookup.js.map +1 -1
  313. package/dist/rest/namespaces/message.resources.generated.d.ts +6 -0
  314. package/dist/rest/namespaces/message.resources.generated.js +14 -0
  315. package/dist/rest/namespaces/message.resources.generated.js.map +1 -0
  316. package/dist/rest/namespaces/message.types.generated.d.ts +122 -0
  317. package/dist/rest/namespaces/message.types.generated.js +8 -0
  318. package/dist/rest/namespaces/message.types.generated.js.map +1 -0
  319. package/dist/rest/namespaces/messages.resources.generated.d.ts +18 -0
  320. package/dist/rest/namespaces/messages.resources.generated.js +44 -0
  321. package/dist/rest/namespaces/messages.resources.generated.js.map +1 -0
  322. package/dist/rest/namespaces/messages.types.generated.d.ts +99 -0
  323. package/dist/rest/namespaces/messages.types.generated.js +8 -0
  324. package/dist/rest/namespaces/messages.types.generated.js.map +1 -0
  325. package/dist/rest/namespaces/mfa.d.ts +3 -42
  326. package/dist/rest/namespaces/mfa.js +3 -49
  327. package/dist/rest/namespaces/mfa.js.map +1 -1
  328. package/dist/rest/namespaces/number-groups.d.ts +3 -45
  329. package/dist/rest/namespaces/number-groups.js +3 -53
  330. package/dist/rest/namespaces/number-groups.js.map +1 -1
  331. package/dist/rest/namespaces/phone-numbers.d.ts +8 -196
  332. package/dist/rest/namespaces/phone-numbers.js +8 -230
  333. package/dist/rest/namespaces/phone-numbers.js.map +1 -1
  334. package/dist/rest/namespaces/project.d.ts +6 -42
  335. package/dist/rest/namespaces/project.js +6 -51
  336. package/dist/rest/namespaces/project.js.map +1 -1
  337. package/dist/rest/namespaces/project.resources.generated.d.ts +17 -0
  338. package/dist/rest/namespaces/project.resources.generated.js +44 -0
  339. package/dist/rest/namespaces/project.resources.generated.js.map +1 -0
  340. package/dist/rest/namespaces/project.types.generated.d.ts +58 -0
  341. package/dist/rest/namespaces/project.types.generated.js +8 -0
  342. package/dist/rest/namespaces/project.types.generated.js.map +1 -0
  343. package/dist/rest/namespaces/projects.resources.generated.d.ts +12 -0
  344. package/dist/rest/namespaces/projects.resources.generated.js +25 -0
  345. package/dist/rest/namespaces/projects.resources.generated.js.map +1 -0
  346. package/dist/rest/namespaces/projects.types.generated.d.ts +77 -0
  347. package/dist/rest/namespaces/projects.types.generated.js +8 -0
  348. package/dist/rest/namespaces/projects.types.generated.js.map +1 -0
  349. package/dist/rest/namespaces/pubsub.d.ts +4 -18
  350. package/dist/rest/namespaces/pubsub.js +4 -21
  351. package/dist/rest/namespaces/pubsub.js.map +1 -1
  352. package/dist/rest/namespaces/pubsub.resources.generated.d.ts +12 -0
  353. package/dist/rest/namespaces/pubsub.resources.generated.js +29 -0
  354. package/dist/rest/namespaces/pubsub.resources.generated.js.map +1 -0
  355. package/dist/rest/namespaces/pubsub.types.generated.d.ts +60 -0
  356. package/dist/rest/namespaces/pubsub.types.generated.js +8 -0
  357. package/dist/rest/namespaces/pubsub.types.generated.js.map +1 -0
  358. package/dist/rest/namespaces/queues.d.ts +3 -38
  359. package/dist/rest/namespaces/queues.js +3 -44
  360. package/dist/rest/namespaces/queues.js.map +1 -1
  361. package/dist/rest/namespaces/recordings.d.ts +3 -34
  362. package/dist/rest/namespaces/recordings.js +3 -40
  363. package/dist/rest/namespaces/recordings.js.map +1 -1
  364. package/dist/rest/namespaces/registry.d.ts +6 -137
  365. package/dist/rest/namespaces/registry.js +6 -173
  366. package/dist/rest/namespaces/registry.js.map +1 -1
  367. package/dist/rest/namespaces/relay-rest.resources.generated.d.ts +168 -0
  368. package/dist/rest/namespaces/relay-rest.resources.generated.js +430 -0
  369. package/dist/rest/namespaces/relay-rest.resources.generated.js.map +1 -0
  370. package/dist/rest/namespaces/relay-rest.types.generated.d.ts +1906 -0
  371. package/dist/rest/namespaces/relay-rest.types.generated.js +8 -0
  372. package/dist/rest/namespaces/relay-rest.types.generated.js.map +1 -0
  373. package/dist/rest/namespaces/short-codes.d.ts +3 -35
  374. package/dist/rest/namespaces/short-codes.js +3 -41
  375. package/dist/rest/namespaces/short-codes.js.map +1 -1
  376. package/dist/rest/namespaces/sip-profile.d.ts +3 -24
  377. package/dist/rest/namespaces/sip-profile.js +3 -29
  378. package/dist/rest/namespaces/sip-profile.js.map +1 -1
  379. package/dist/rest/namespaces/verified-callers.d.ts +3 -29
  380. package/dist/rest/namespaces/verified-callers.js +3 -34
  381. package/dist/rest/namespaces/verified-callers.js.map +1 -1
  382. package/dist/rest/namespaces/video.d.ts +10 -227
  383. package/dist/rest/namespaces/video.js +10 -288
  384. package/dist/rest/namespaces/video.js.map +1 -1
  385. package/dist/rest/namespaces/video.resources.generated.d.ts +81 -0
  386. package/dist/rest/namespaces/video.resources.generated.js +171 -0
  387. package/dist/rest/namespaces/video.resources.generated.js.map +1 -0
  388. package/dist/rest/namespaces/video.types.generated.d.ts +771 -0
  389. package/dist/rest/namespaces/video.types.generated.js +8 -0
  390. package/dist/rest/namespaces/video.types.generated.js.map +1 -0
  391. package/dist/rest/namespaces/voice.resources.generated.d.ts +9 -0
  392. package/dist/rest/namespaces/voice.resources.generated.js +17 -0
  393. package/dist/rest/namespaces/voice.resources.generated.js.map +1 -0
  394. package/dist/rest/namespaces/voice.types.generated.d.ts +214 -0
  395. package/dist/rest/namespaces/voice.types.generated.js +8 -0
  396. package/dist/rest/namespaces/voice.types.generated.js.map +1 -0
  397. package/dist/rest/pagination.d.ts +5 -1
  398. package/dist/rest/pagination.js +40 -20
  399. package/dist/rest/pagination.js.map +1 -1
  400. package/dist/rest/types.d.ts +21 -3
  401. package/dist/schema.json +299 -98
  402. package/dist/skills/SkillBase.d.ts +97 -20
  403. package/dist/skills/SkillBase.js +100 -17
  404. package/dist/skills/SkillBase.js.map +1 -1
  405. package/dist/skills/SkillManager.d.ts +66 -13
  406. package/dist/skills/SkillManager.js +101 -20
  407. package/dist/skills/SkillManager.js.map +1 -1
  408. package/dist/skills/SkillName.d.ts +44 -0
  409. package/dist/skills/SkillName.js +2 -0
  410. package/dist/skills/SkillName.js.map +1 -0
  411. package/dist/skills/SkillRegistry.d.ts +22 -11
  412. package/dist/skills/SkillRegistry.js +47 -17
  413. package/dist/skills/SkillRegistry.js.map +1 -1
  414. package/dist/skills/builtin/api_ninjas_trivia.d.ts +3 -1
  415. package/dist/skills/builtin/api_ninjas_trivia.js +18 -6
  416. package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -1
  417. package/dist/skills/builtin/ask_claude.d.ts +14 -4
  418. package/dist/skills/builtin/ask_claude.js +36 -14
  419. package/dist/skills/builtin/ask_claude.js.map +1 -1
  420. package/dist/skills/builtin/claude_skills.d.ts +3 -1
  421. package/dist/skills/builtin/claude_skills.js +19 -15
  422. package/dist/skills/builtin/claude_skills.js.map +1 -1
  423. package/dist/skills/builtin/custom_skills.d.ts +10 -3
  424. package/dist/skills/builtin/custom_skills.js +26 -9
  425. package/dist/skills/builtin/custom_skills.js.map +1 -1
  426. package/dist/skills/builtin/datasphere.d.ts +5 -3
  427. package/dist/skills/builtin/datasphere.js +21 -22
  428. package/dist/skills/builtin/datasphere.js.map +1 -1
  429. package/dist/skills/builtin/datasphere_serverless.d.ts +12 -1
  430. package/dist/skills/builtin/datasphere_serverless.js +17 -6
  431. package/dist/skills/builtin/datasphere_serverless.js.map +1 -1
  432. package/dist/skills/builtin/datetime.d.ts +3 -1
  433. package/dist/skills/builtin/datetime.js +11 -7
  434. package/dist/skills/builtin/datetime.js.map +1 -1
  435. package/dist/skills/builtin/google_maps.d.ts +29 -14
  436. package/dist/skills/builtin/google_maps.js +89 -269
  437. package/dist/skills/builtin/google_maps.js.map +1 -1
  438. package/dist/skills/builtin/index.d.ts +8 -6
  439. package/dist/skills/builtin/index.js +8 -6
  440. package/dist/skills/builtin/index.js.map +1 -1
  441. package/dist/skills/builtin/info_gatherer.d.ts +4 -2
  442. package/dist/skills/builtin/info_gatherer.js +20 -12
  443. package/dist/skills/builtin/info_gatherer.js.map +1 -1
  444. package/dist/skills/builtin/joke.d.ts +16 -6
  445. package/dist/skills/builtin/joke.js +54 -37
  446. package/dist/skills/builtin/joke.js.map +1 -1
  447. package/dist/skills/builtin/math.d.ts +3 -1
  448. package/dist/skills/builtin/math.js +14 -9
  449. package/dist/skills/builtin/math.js.map +1 -1
  450. package/dist/skills/builtin/mcp_gateway.d.ts +34 -5
  451. package/dist/skills/builtin/mcp_gateway.js +77 -46
  452. package/dist/skills/builtin/mcp_gateway.js.map +1 -1
  453. package/dist/skills/builtin/native_vector_search.d.ts +19 -5
  454. package/dist/skills/builtin/native_vector_search.js +179 -61
  455. package/dist/skills/builtin/native_vector_search.js.map +1 -1
  456. package/dist/skills/builtin/play_background_file.d.ts +21 -15
  457. package/dist/skills/builtin/play_background_file.js +43 -122
  458. package/dist/skills/builtin/play_background_file.js.map +1 -1
  459. package/dist/skills/builtin/spider.d.ts +42 -4
  460. package/dist/skills/builtin/spider.js +277 -104
  461. package/dist/skills/builtin/spider.js.map +1 -1
  462. package/dist/skills/builtin/swml_transfer.d.ts +14 -3
  463. package/dist/skills/builtin/swml_transfer.js +45 -24
  464. package/dist/skills/builtin/swml_transfer.js.map +1 -1
  465. package/dist/skills/builtin/weather_api.d.ts +24 -13
  466. package/dist/skills/builtin/weather_api.js +38 -30
  467. package/dist/skills/builtin/weather_api.js.map +1 -1
  468. package/dist/skills/builtin/web_search.d.ts +48 -10
  469. package/dist/skills/builtin/web_search.js +294 -100
  470. package/dist/skills/builtin/web_search.js.map +1 -1
  471. package/dist/skills/builtin/wikipedia_search.d.ts +4 -2
  472. package/dist/skills/builtin/wikipedia_search.js +14 -13
  473. package/dist/skills/builtin/wikipedia_search.js.map +1 -1
  474. package/dist/skills/index.d.ts +3 -2
  475. package/dist/skills/index.js +1 -1
  476. package/dist/skills/index.js.map +1 -1
  477. package/dist/swml_verbs_generated.d.ts +2824 -0
  478. package/dist/swml_verbs_generated.js +12 -0
  479. package/dist/swml_verbs_generated.js.map +1 -0
  480. package/dist/types.d.ts +59 -6
  481. package/dist/web.d.ts +27 -0
  482. package/dist/web.js +20 -0
  483. package/dist/web.js.map +1 -0
  484. package/docs/agent-guide.md +1034 -0
  485. package/docs/ai_chat.md +560 -0
  486. package/docs/api-reference.md +3534 -0
  487. package/docs/architecture.md +846 -0
  488. package/docs/bedrock_agent.md +411 -0
  489. package/docs/cli-guide.md +403 -0
  490. package/docs/cloud_functions_guide.md +399 -0
  491. package/docs/configuration.md +548 -0
  492. package/docs/contexts-guide.md +884 -0
  493. package/docs/datamap-guide.md +1160 -0
  494. package/docs/developer_pain_points.md +548 -0
  495. package/docs/llm_parameters.md +298 -0
  496. package/docs/mcp_gateway_reference.md +354 -0
  497. package/docs/mcp_integration.md +162 -0
  498. package/docs/pgi_agent_guide.md +1820 -0
  499. package/docs/prefabs-guide.md +815 -0
  500. package/docs/programmatically_governed_inference.md +301 -0
  501. package/docs/sdk_features.md +501 -0
  502. package/docs/security.md +559 -0
  503. package/docs/serverless-guide.md +520 -0
  504. package/docs/skills-guide.md +1223 -0
  505. package/docs/skills-system.md +405 -0
  506. package/docs/skills_parameter_schema.md +417 -0
  507. package/docs/swaig-reference.md +1938 -0
  508. package/docs/swml_service_guide.md +573 -0
  509. package/docs/third_party_skills.md +410 -0
  510. package/docs/web_service.md +666 -0
  511. package/examples/README.md +202 -0
  512. package/examples/advanced-datamap.ts +108 -0
  513. package/examples/advanced-dynamic-config.ts +70 -0
  514. package/examples/auto-vivified.ts +95 -0
  515. package/examples/call-flow.ts +65 -0
  516. package/examples/comprehensive-dynamic.ts +125 -0
  517. package/examples/contexts-steps.ts +65 -0
  518. package/examples/custom-path.ts +45 -0
  519. package/examples/datamap-tools.ts +51 -0
  520. package/examples/datasphere-multi-instance.ts +66 -0
  521. package/examples/datasphere-serverless-env.ts +87 -0
  522. package/examples/datasphere-webhook-env.ts +65 -0
  523. package/examples/datasphere.ts +56 -0
  524. package/examples/declarative.ts +100 -0
  525. package/examples/dynamic-config.ts +54 -0
  526. package/examples/dynamic-info-gatherer.ts +69 -0
  527. package/examples/dynamic-swml-service.ts +67 -0
  528. package/examples/gather-info.ts +95 -0
  529. package/examples/gather-per-question-functions-demo.ts +139 -0
  530. package/examples/joke-agent.ts +34 -0
  531. package/examples/kubernetes-agent.ts +45 -0
  532. package/examples/llm-params.ts +75 -0
  533. package/examples/mcp-agent.ts +89 -0
  534. package/examples/mcp-gateway.ts +81 -0
  535. package/examples/multi-agent.ts +80 -0
  536. package/examples/multi-endpoint.ts +79 -0
  537. package/examples/pgi/case-domain.ts +114 -0
  538. package/examples/pgi/serve.ts +16 -0
  539. package/examples/pgi/support-agent.ts +265 -0
  540. package/examples/pom-prompt.ts +70 -0
  541. package/examples/prefab-concierge.ts +42 -0
  542. package/examples/prefab-faq.ts +58 -0
  543. package/examples/prefab-info-gatherer.ts +33 -0
  544. package/examples/prefab-receptionist.ts +36 -0
  545. package/examples/prefab-survey.ts +69 -0
  546. package/examples/quickstart-agent.ts +29 -0
  547. package/examples/quickstart-relay.ts +25 -0
  548. package/examples/quickstart-rest.ts +25 -0
  549. package/examples/record-call.ts +65 -0
  550. package/examples/relay-demo.ts +33 -0
  551. package/examples/room-and-sip.ts +93 -0
  552. package/examples/serverless-lambda.ts +43 -0
  553. package/examples/session-state.ts +83 -0
  554. package/examples/simple-agent.ts +36 -0
  555. package/examples/simple-static.ts +29 -0
  556. package/examples/skills-demo.ts +41 -0
  557. package/examples/step-function-inheritance-demo.ts +124 -0
  558. package/examples/swaig-features.ts +193 -0
  559. package/examples/swml-service-routing.ts +66 -0
  560. package/examples/swml-service.ts +38 -0
  561. package/examples/swmlservice_ai_sidecar.ts +104 -0
  562. package/examples/swmlservice_swaig_standalone.ts +79 -0
  563. package/examples/tap.ts +67 -0
  564. package/examples/typed-tools.ts +68 -0
  565. package/examples/verb-methods.ts +45 -0
  566. package/examples/web-search-multi-instance.ts +75 -0
  567. package/examples/web-search.ts +38 -0
  568. package/examples/wikipedia.ts +36 -0
  569. package/livewire/README.md +164 -0
  570. package/livewire/docs/migration-guide.md +251 -0
  571. package/livewire/examples/livewire-basic-agent.ts +74 -0
  572. package/livewire/examples/livewire-handoff.ts +196 -0
  573. package/livewire/examples/livewire-multi-tool.ts +121 -0
  574. package/package.json +85 -13
  575. package/relay/README.md +101 -0
  576. package/relay/docs/call-methods.md +622 -0
  577. package/relay/docs/client-reference.md +281 -0
  578. package/relay/docs/events.md +193 -0
  579. package/relay/docs/getting-started.md +221 -0
  580. package/relay/docs/guide.md +386 -0
  581. package/relay/docs/messaging.md +246 -0
  582. package/relay/examples/relay-inbound.ts +66 -0
  583. package/relay/examples/relay-messaging.ts +74 -0
  584. package/relay/examples/relay-outbound.ts +76 -0
  585. package/rest/README.md +141 -0
  586. package/rest/docs/calling.md +313 -0
  587. package/rest/docs/client-reference.md +149 -0
  588. package/rest/docs/fabric.md +192 -0
  589. package/rest/docs/getting-started.md +138 -0
  590. package/rest/docs/guide.md +421 -0
  591. package/rest/docs/namespaces.md +367 -0
  592. package/rest/docs/phone-binding.md +116 -0
  593. package/rest/examples/rest-10dlc-registration.ts +177 -0
  594. package/rest/examples/rest-bind-phone-to-swml-webhook.ts +66 -0
  595. package/rest/examples/rest-calling-ivr-and-ai.ts +136 -0
  596. package/rest/examples/rest-calling-play-and-record.ts +98 -0
  597. package/rest/examples/rest-client.ts +59 -0
  598. package/rest/examples/rest-datasphere-search.ts +81 -0
  599. package/rest/examples/rest-fabric-conferences-and-routing.ts +147 -0
  600. package/rest/examples/rest-fabric-subscribers-and-sip.ts +106 -0
  601. package/rest/examples/rest-fabric-swml-and-callflows.ts +101 -0
  602. package/rest/examples/rest-manage-resources.ts +64 -0
  603. package/rest/examples/rest-phone-number-management.ts +200 -0
  604. package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
  605. package/rest/examples/rest-video-rooms.ts +186 -0
  606. package/tutorial/fred/fred.ts +218 -0
  607. package/tutorial/fred/tutorial/01-introduction.md +141 -0
  608. package/tutorial/fred/tutorial/02-setup.md +304 -0
  609. package/tutorial/fred/tutorial/03-basic-agent.md +284 -0
  610. package/tutorial/fred/tutorial/04-wikipedia-skill.md +298 -0
  611. package/tutorial/fred/tutorial/05-custom-functions.md +347 -0
  612. package/tutorial/fred/tutorial/06-running-testing.md +642 -0
  613. package/tutorial/fred/tutorial/README.md +56 -0
  614. package/tutorial/fred/tutorial/appendix-complete-code.md +632 -0
  615. package/tutorial/fred/tutorial/appendix-docker-deployment.md +504 -0
  616. package/tutorial/full-guardrails-agent/handlers.ts +436 -0
  617. package/tutorial/full-guardrails-agent/penny.ts +305 -0
  618. package/tutorial/full-guardrails-agent/reservations.ts +1109 -0
  619. package/tutorial/full-guardrails-agent/tutorial/01-why-guardrails.md +149 -0
  620. package/tutorial/full-guardrails-agent/tutorial/02-design-first.md +139 -0
  621. package/tutorial/full-guardrails-agent/tutorial/03-rules-first.md +422 -0
  622. package/tutorial/full-guardrails-agent/tutorial/04-the-shell.md +238 -0
  623. package/tutorial/full-guardrails-agent/tutorial/05-steps-and-scoping.md +247 -0
  624. package/tutorial/full-guardrails-agent/tutorial/06-tools-that-decide.md +467 -0
  625. package/tutorial/full-guardrails-agent/tutorial/07-gather-and-projection.md +160 -0
  626. package/tutorial/full-guardrails-agent/tutorial/08-the-verification-gate.md +333 -0
  627. package/tutorial/full-guardrails-agent/tutorial/09-people-and-endings.md +313 -0
  628. package/tutorial/full-guardrails-agent/tutorial/10-testing-and-running.md +387 -0
  629. package/tutorial/full-guardrails-agent/tutorial/README.md +106 -0
  630. package/tutorial/full-guardrails-agent/tutorial/appendix-complete-code.md +2207 -0
  631. package/tutorial/full-guardrails-agent/tutorial/appendix-deployment.md +191 -0
  632. package/tutorial/full-guardrails-agent/tutorial/appendix-technique-map.md +117 -0
  633. package/tutorial/full-guardrails-agent/workflow.ts +219 -0
  634. package/tutorial/multi_agents/README.md +175 -0
  635. package/tutorial/multi_agents/advanced_agent.ts +395 -0
  636. package/tutorial/multi_agents/extending_agents.ts +641 -0
  637. package/tutorial/multi_agents/knowledge.ts +59 -0
  638. package/tutorial/multi_agents/lesson1_first_agent.md +368 -0
  639. package/tutorial/multi_agents/lesson2_knowledge_bases.md +404 -0
  640. package/tutorial/multi_agents/lesson3_multi_agent_systems.md +621 -0
  641. package/tutorial/multi_agents/lesson4_advanced_features.md +805 -0
  642. package/tutorial/multi_agents/lesson5_extending_agents.md +856 -0
  643. package/tutorial/multi_agents/pc_builder.ts +529 -0
  644. package/tutorial/multi_agents/sales_agent.ts +88 -0
  645. package/tutorial/multi_agents/sales_agent_with_search.ts +116 -0
  646. package/tutorial/multi_agents/sales_knowledge.md +139 -0
  647. package/tutorial/multi_agents/support_knowledge.md +256 -0
  648. package/dist/cli/mock-data.d.ts +0 -37
  649. package/dist/cli/mock-data.js +0 -80
  650. package/dist/cli/mock-data.js.map +0 -1
  651. package/dist/generateVerbTypes.d.ts +0 -11
  652. package/dist/generateVerbTypes.js +0 -265
  653. package/dist/generateVerbTypes.js.map +0 -1
  654. package/dist/rest/namespaces/compat.d.ts +0 -585
  655. package/dist/rest/namespaces/compat.js +0 -735
  656. package/dist/rest/namespaces/compat.js.map +0 -1
@@ -0,0 +1,747 @@
1
+ /**
2
+ * ChatGateway - a browser-facing gateway for the SignalWire AI Chat service.
3
+ *
4
+ * A chat widget running in a page can't hold a SignalWire API token. The token
5
+ * carries the whole project, so putting it in JavaScript would let every
6
+ * visitor run up turns, and every turn is billed. The widget still has to
7
+ * reach the chat service, so it talks to a gateway mounted in your own app,
8
+ * which holds the credential server-side and forwards on the widget's behalf:
9
+ *
10
+ * ```text
11
+ * browser ──(publishable key)──▶ your app ──(project:token)──▶ chat service
12
+ * ```
13
+ *
14
+ * The browser learns two things: the gateway's URL and a publishable key. It
15
+ * doesn't learn the project, the space, the token, or which agent config
16
+ * runs. The gateway sends `config_url` itself, so a key can only reach the
17
+ * one agent it was issued for.
18
+ *
19
+ * Mount it on the app an agent already serves:
20
+ *
21
+ * ```ts
22
+ * import { AgentBase, ChatGateway } from '@signalwire/sdk';
23
+ *
24
+ * const agent = new AgentBase({ name: 'shop', route: '/swml' });
25
+ * const gateway = new ChatGateway({
26
+ * configUrl: 'https://my-agent.example.com/swml',
27
+ * key: 'pk_live_...', // what the widget carries
28
+ * allowedOrigins: ['https://shop.example.com'],
29
+ * });
30
+ * agent.mount(gateway.router(), { prefix: '/chat' });
31
+ * ```
32
+ *
33
+ * ## What a stolen key allows
34
+ *
35
+ * It can't read anything: the full `chat_log` isn't exposed, and conversation
36
+ * handles are signed by the gateway, so they can't be guessed or enumerated.
37
+ * It can start and continue conversations, which costs the project money.
38
+ * That makes the caps the main control: `maxNewConversations` and `maxTurns`
39
+ * bound how many conversations can exist and how long each can run.
40
+ *
41
+ * The origin allowlist is a second layer. It stops a key pasted into someone
42
+ * else's page, because a browser sends that page's origin and the gateway
43
+ * refuses it. It doesn't stop a script that sends no origin or a false one.
44
+ * Treat it as leak containment, not access control.
45
+ *
46
+ * ## What the browser may send
47
+ *
48
+ * One field is forwarded rather than replaced: `user_meta_data`, the page
49
+ * context a widget collects about itself (url, title, referrer, locale,
50
+ * viewport). It lets a chat agent tailor its greeting the way a voice agent
51
+ * does from dial-time `userVariables`, and it reaches the agent's config
52
+ * request as `params.user_meta_data`.
53
+ *
54
+ * The service reads it when it creates a conversation: the `start` call, or
55
+ * whichever `chat` auto-creates one. An open conversation doesn't fetch its
56
+ * config again, so metadata sent on later turns is accepted and unused. Send
57
+ * it every turn so the creating turn carries it, but don't expect the agent
58
+ * to see a visitor move between pages mid-conversation.
59
+ *
60
+ * The browser writes it, so treat it as the visitor's claim about themselves,
61
+ * never as authority; a page can put anything in it, including text aimed at
62
+ * your prompt. The gateway limits its size ({@link MAX_USER_METADATA_BYTES})
63
+ * and keeps it nested under its own key, so it can't replace the conversation
64
+ * id or `config_url` the gateway sets. It can't vouch for the contents.
65
+ *
66
+ * ## Size limits
67
+ *
68
+ * Whoever holds the key chooses the size of every field above, so each is
69
+ * limited and answered with `413` past its limit: the request body
70
+ * ({@link MAX_REQUEST_BODY_BYTES}, 64 KiB, refused before it's parsed), a chat
71
+ * message ({@link MAX_MESSAGE_BYTES}, 8 KiB of UTF-8, refused before a
72
+ * conversation is created or a turn counted) and `user_meta_data`
73
+ * ({@link MAX_USER_METADATA_BYTES}, 8 KiB serialized). `HandoffRouter`
74
+ * applies the same body and message limits to its routes.
75
+ *
76
+ * Mirrors signalwire-python's `signalwire.ai_chat.gateway`.
77
+ */
78
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
79
+ import { Hono } from 'hono';
80
+ import { getLogger } from '../Logger.js';
81
+ import { AIChatClient } from './AIChatClient.js';
82
+ const logger = getLogger('ai_chat.gateway');
83
+ /** Seconds a handle stays valid: past a page refresh, not overnight. */
84
+ export const DEFAULT_HANDLE_TTL = 24 * 60 * 60;
85
+ /**
86
+ * The chat service's own default conversation timeout, in seconds. Reported to
87
+ * the browser when no `conversationTimeout` is set; the service applies it.
88
+ */
89
+ export const SERVICE_DEFAULT_CONVERSATION_TIMEOUT = 3600;
90
+ /** New conversations per window, per gateway. */
91
+ export const DEFAULT_MAX_NEW_CONVERSATIONS = 60;
92
+ /** Turns per conversation, in total. */
93
+ export const DEFAULT_MAX_TURNS = 200;
94
+ /** Seconds in the window `maxNewConversations` counts over. */
95
+ export const DEFAULT_WINDOW_SECONDS = 60;
96
+ /** Hosts allowed without listing, so local development works unconfigured. */
97
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
98
+ /** The `method` values a browser may send. */
99
+ export const ALLOWED_METHODS = new Set(['start', 'chat', 'log', 'end']);
100
+ /**
101
+ * Limit on the browser-supplied `user_meta_data`, serialized, in bytes. A
102
+ * widget's real payload is one to two KB; without a limit a page could send
103
+ * unbounded bytes to a metered service with every turn.
104
+ */
105
+ export const MAX_USER_METADATA_BYTES = 8 * 1024;
106
+ /**
107
+ * Limit on one typed message, in UTF-8 bytes: a chat turn here, and the text
108
+ * a `HandoffRouter`'s `/say` sends into a live call. 8 KiB is several pages,
109
+ * far more than a visitor types into a widget, and every byte of it goes into
110
+ * a billed turn.
111
+ */
112
+ export const MAX_MESSAGE_BYTES = 8 * 1024;
113
+ /**
114
+ * Limit on a whole request body, in bytes, checked before it's parsed. The
115
+ * largest honest request is a chat turn with a full message and a full
116
+ * metadata bag; JSON escaping can triple the size of non-ASCII text, and this
117
+ * leaves room for that.
118
+ */
119
+ export const MAX_REQUEST_BODY_BYTES = 64 * 1024;
120
+ /**
121
+ * Roles a browser may see. `chat_log` returns the whole conversation as the
122
+ * service holds it, including the substituted system prompt, tool calls and
123
+ * tool results, so the transcript is reduced to the dialogue.
124
+ */
125
+ export const VISIBLE_ROLES = new Set(['user', 'assistant']);
126
+ /**
127
+ * A request the gateway refused, with the status the browser should see.
128
+ *
129
+ * Deliberately coarse: the browser learns that it was refused and, at most,
130
+ * which of a few categories it fell into. Anything finer would let a caller
131
+ * map out the caps and the allowlist by probing.
132
+ */
133
+ export class GatewayRejection extends Error {
134
+ /** HTTP status to return: 400, 401, 403, 413 or 429. */
135
+ status;
136
+ /**
137
+ * Short explanation that reaches the browser. It names a category and
138
+ * nothing finer: a handle that fails is reported as `malformed handle`,
139
+ * `invalid handle` (bad signature) or `expired handle`, and a cap as
140
+ * `too many new conversations` or `conversation turn limit reached`.
141
+ */
142
+ reason;
143
+ /**
144
+ * @param status - HTTP status to return (401 bad key, 403 origin or handle,
145
+ * 400 malformed request, 413 a request, message or metadata over its size
146
+ * limit, 429 a cap was hit).
147
+ * @param reason - Short explanation, safe to show the browser: a category,
148
+ * never a detail such as a cap's value.
149
+ */
150
+ constructor(status, reason) {
151
+ super(`${status}: ${reason}`);
152
+ this.name = 'GatewayRejection';
153
+ this.status = status;
154
+ this.reason = reason;
155
+ }
156
+ }
157
+ function isPlainObject(value) {
158
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
159
+ }
160
+ /** Seconds on a monotonic clock, for the caps. */
161
+ function monotonic() {
162
+ return performance.now() / 1000;
163
+ }
164
+ const BASE64URL = /^[A-Za-z0-9_-]*$/;
165
+ /**
166
+ * Serialized size as the reference measures it (compact JSON with non-ASCII
167
+ * escaped), so the same payload hits the limit in both SDKs.
168
+ */
169
+ function jsonByteLength(value) {
170
+ const encoded = JSON.stringify(value);
171
+ let bytes = 0;
172
+ for (let i = 0; i < encoded.length; i++)
173
+ bytes += encoded.charCodeAt(i) < 0x7f ? 1 : 6;
174
+ return bytes;
175
+ }
176
+ /**
177
+ * Length of `text` in UTF-8 bytes. A lone surrogate counts as three bytes, as
178
+ * the reference counts it, and never throws.
179
+ *
180
+ * @internal Shared with `HandoffRouter`; not part of the package surface.
181
+ */
182
+ export function _utf8Length(text) {
183
+ return Buffer.byteLength(text, 'utf8');
184
+ }
185
+ /**
186
+ * Parse a request's JSON body, refusing one over `limit` bytes.
187
+ *
188
+ * A declared `Content-Length` over the limit is refused before anything is
189
+ * read. The body is then read in chunks and abandoned as soon as it passes
190
+ * the limit, so a chunked or understated upload can't make the process hold
191
+ * more than `limit` bytes of it.
192
+ *
193
+ * Middleware ahead of the route may already have read the body with
194
+ * `c.req.json()`, `c.req.text()` or another `HonoRequest` accessor. Hono
195
+ * caches what it read, so the body is then read from that cache, and the
196
+ * same limit is applied to its size. (A body cached as parsed JSON is
197
+ * measured as Hono serializes it again, compactly.) A body this reads
198
+ * from the stream is put in that cache, so middleware can read it again
199
+ * after the route has answered.
200
+ *
201
+ * @internal Shared with `HandoffRouter`; not part of the package surface.
202
+ * @param req - The route's `c.req`.
203
+ * @param limit - The limit in bytes; {@link MAX_REQUEST_BODY_BYTES} by default.
204
+ * @returns The parsed JSON value.
205
+ * @throws {GatewayRejection} 413 `request too large` when the body is over `limit`.
206
+ * @throws {SyntaxError} When the body isn't valid JSON.
207
+ * @throws {TypeError} When the raw body was consumed outside Hono's cache.
208
+ */
209
+ export async function _readJsonBody(req, limit = MAX_REQUEST_BODY_BYTES) {
210
+ const tooLarge = () => new GatewayRejection(413, 'request too large');
211
+ const declared = req.header('content-length') ?? '';
212
+ if (/^\d+$/.test(declared) && Number(declared) > limit)
213
+ throw tooLarge();
214
+ const request = req.raw;
215
+ if (request.bodyUsed || Object.keys(req.bodyCache).length > 0) {
216
+ // Already read by middleware: all of it is in memory, so only its size
217
+ // is left to check.
218
+ const cached = await req.arrayBuffer();
219
+ if (cached.byteLength > limit)
220
+ throw tooLarge();
221
+ return JSON.parse(new TextDecoder().decode(cached));
222
+ }
223
+ const chunks = [];
224
+ let received = 0;
225
+ if (request.body) {
226
+ const reader = request.body.getReader();
227
+ for (;;) {
228
+ const { done, value } = await reader.read();
229
+ if (done)
230
+ break;
231
+ received += value.byteLength;
232
+ if (received > limit) {
233
+ // Not awaited: when middleware has cloned the request, the body is
234
+ // one branch of a tee, and cancelling it waits until the other
235
+ // branch is read, which that middleware can do only after this
236
+ // route has answered.
237
+ reader.cancel().catch(() => undefined);
238
+ reader.releaseLock();
239
+ throw tooLarge();
240
+ }
241
+ chunks.push(value);
242
+ }
243
+ reader.releaseLock();
244
+ }
245
+ const bytes = new Uint8Array(received);
246
+ let offset = 0;
247
+ for (const chunk of chunks) {
248
+ bytes.set(chunk, offset);
249
+ offset += chunk.byteLength;
250
+ }
251
+ // Into Hono's body cache, as c.req.arrayBuffer() would put it, so
252
+ // middleware that reads the body after this route (c.req.json(), text(),
253
+ // arrayBuffer()) gets it from there instead of the used-up stream.
254
+ req.bodyCache['arrayBuffer'] = Promise.resolve(bytes.buffer);
255
+ return JSON.parse(new TextDecoder().decode(bytes));
256
+ }
257
+ /**
258
+ * Server-side proxy that lets a browser chat without holding a token.
259
+ *
260
+ * The caps are counted in this process. Behind several replicas each keeps its
261
+ * own counts, so the effective cap is multiplied by the replica count; set
262
+ * them with that in mind, or put a shared limiter in front.
263
+ */
264
+ export class ChatGateway {
265
+ /** The agent config sent on every call. */
266
+ configUrl;
267
+ /** The publishable key the browser presents. */
268
+ key;
269
+ /** Listed origins, without trailing slashes. */
270
+ allowedOrigins;
271
+ /** Seconds a handle stays valid. */
272
+ handleTtl;
273
+ /** Idle seconds before the service ends a conversation, or null for its default. */
274
+ conversationTimeout;
275
+ /** New conversations allowed per window. */
276
+ maxNewConversations;
277
+ /** Turns allowed per conversation. */
278
+ maxTurns;
279
+ /** Window for `maxNewConversations`, in seconds. */
280
+ windowSeconds;
281
+ _client;
282
+ _ownsClient;
283
+ _secret;
284
+ _mints = [];
285
+ _turns = new Map();
286
+ /**
287
+ * @param options - The agent config, the key, and the limits.
288
+ * @throws {Error} When `configUrl` is empty.
289
+ */
290
+ constructor(options) {
291
+ if (!options.configUrl) {
292
+ throw new Error('configUrl is required; it is what a key is scoped to.');
293
+ }
294
+ this.configUrl = options.configUrl;
295
+ this.key =
296
+ options.key ||
297
+ process.env['SIGNALWIRE_CHAT_GATEWAY_KEY'] ||
298
+ 'pk_' + randomBytes(24).toString('base64url');
299
+ this.allowedOrigins = new Set((options.allowedOrigins ?? []).map((o) => o.replace(/\/+$/, '')));
300
+ this.handleTtl = options.handleTtl ?? DEFAULT_HANDLE_TTL;
301
+ this.conversationTimeout = options.conversationTimeout ?? null;
302
+ this.maxNewConversations = options.maxNewConversations ?? DEFAULT_MAX_NEW_CONVERSATIONS;
303
+ this.maxTurns = options.maxTurns ?? DEFAULT_MAX_TURNS;
304
+ this.windowSeconds = options.windowSeconds ?? DEFAULT_WINDOW_SECONDS;
305
+ this._client = options.client ?? new AIChatClient();
306
+ this._ownsClient = options.client === undefined;
307
+ const secret = options.secret ?? (process.env['SIGNALWIRE_CHAT_GATEWAY_SECRET'] || randomBytes(32));
308
+ this._secret = typeof secret === 'string' ? Buffer.from(secret) : Buffer.from(secret);
309
+ }
310
+ /**
311
+ * Epoch seconds of the newest message, or null when none is dated.
312
+ *
313
+ * Lets a browser restore its idle clock after a reload. Without it a widget
314
+ * restarts the clock at zero, so a tab closed for 55 minutes of a 60-minute
315
+ * timeout waits another hour before warning while the conversation ends in
316
+ * five.
317
+ *
318
+ * The service stamps messages in microseconds; this converts to seconds.
319
+ * Every role counts, not only the visible ones, because the service's idle
320
+ * clock moves on any write.
321
+ *
322
+ * @param messages - Messages as `chat_log` returns them.
323
+ * @returns Epoch seconds, or null.
324
+ */
325
+ static lastActivity(messages) {
326
+ let newest = null;
327
+ for (const msg of messages ?? []) {
328
+ if (!isPlainObject(msg))
329
+ continue;
330
+ const ts = msg['timestamp'];
331
+ if (typeof ts === 'number' &&
332
+ Number.isInteger(ts) &&
333
+ ts > 0 &&
334
+ (newest === null || ts > newest)) {
335
+ newest = ts;
336
+ }
337
+ }
338
+ return newest !== null ? newest / 1_000_000 : null;
339
+ }
340
+ /**
341
+ * The idle seconds a conversation actually gets: `conversationTimeout`, or
342
+ * the service default when unset, so the number given to a browser is never
343
+ * null.
344
+ */
345
+ get effectiveTimeout() {
346
+ return this.conversationTimeout || SERVICE_DEFAULT_CONVERSATION_TIMEOUT;
347
+ }
348
+ /**
349
+ * Close the client, if the gateway built it. A client passed in the options
350
+ * belongs to the caller and is left open.
351
+ */
352
+ async close() {
353
+ if (this._ownsClient)
354
+ await this._client.close();
355
+ }
356
+ // ── Handles ──────────────────────────────────────────────────────
357
+ /**
358
+ * Issue a signed handle for a conversation.
359
+ *
360
+ * The browser never names a conversation. If it could, a publishable key
361
+ * and a guessed id would be enough to continue someone else's chat; with
362
+ * signing, a caller can only present handles this gateway issued.
363
+ *
364
+ * @param conversationId - The conversation to name; a new random id when omitted.
365
+ * @returns The handle.
366
+ */
367
+ mintHandle(conversationId) {
368
+ const id = conversationId || `chat-${randomBytes(18).toString('base64url')}`;
369
+ const expires = Math.floor(Date.now() / 1000) + this.handleTtl;
370
+ const payload = Buffer.from(`${id}:${expires}`);
371
+ const sig = createHmac('sha256', this._secret).update(payload).digest();
372
+ return `${payload.toString('base64url')}.${sig.toString('base64url')}`;
373
+ }
374
+ /**
375
+ * The conversation id inside a handle. The signature is checked first and
376
+ * the expiry second, both before the id is used.
377
+ *
378
+ * @param handle - A handle from {@link mintHandle}.
379
+ * @returns The conversation id.
380
+ * @throws {GatewayRejection} 400 for a malformed handle, 403 for a bad
381
+ * signature or an expired handle.
382
+ */
383
+ readHandle(handle) {
384
+ // Checked at runtime too: the handle comes from a request body.
385
+ const dot = typeof handle === 'string' ? handle.indexOf('.') : -1;
386
+ if (dot < 0)
387
+ throw new GatewayRejection(400, 'malformed handle');
388
+ const raw = handle.slice(0, dot);
389
+ const sig = handle.slice(dot + 1);
390
+ if (!BASE64URL.test(raw) || !BASE64URL.test(sig)) {
391
+ throw new GatewayRejection(400, 'malformed handle');
392
+ }
393
+ const payload = Buffer.from(raw, 'base64url');
394
+ const given = Buffer.from(sig, 'base64url');
395
+ const expected = createHmac('sha256', this._secret).update(payload).digest();
396
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
397
+ throw new GatewayRejection(403, 'invalid handle');
398
+ }
399
+ const text = payload.toString('utf8');
400
+ const colon = text.lastIndexOf(':');
401
+ const expires = colon < 0 ? '' : text.slice(colon + 1);
402
+ if (!/^-?\d+$/.test(expires))
403
+ throw new GatewayRejection(400, 'malformed handle');
404
+ if (Date.now() / 1000 > Number(expires))
405
+ throw new GatewayRejection(403, 'expired handle');
406
+ return text.slice(0, colon);
407
+ }
408
+ // ── Guards ───────────────────────────────────────────────────────
409
+ /**
410
+ * Allow localhost and listed origins; refuse any other.
411
+ *
412
+ * A missing `Origin` is allowed: browsers send one on the cross-origin POSTs
413
+ * this serves, so its absence means a caller that isn't a browser. Refusing
414
+ * those would break server-side use without stopping an attacker, who can
415
+ * leave the header out.
416
+ *
417
+ * @param origin - The request's `Origin` header, or null/undefined when absent.
418
+ * @throws {GatewayRejection} 403 for an origin that isn't allowed.
419
+ */
420
+ checkOrigin(origin) {
421
+ if (origin === null || origin === undefined)
422
+ return;
423
+ let host = '';
424
+ try {
425
+ host = new URL(origin).hostname;
426
+ }
427
+ catch {
428
+ // Not a URL; only an exact listing can match it.
429
+ }
430
+ if (LOCAL_HOSTS.has(host) || host.endsWith('.localhost'))
431
+ return;
432
+ if (this.allowedOrigins.has(origin.replace(/\/+$/, '')))
433
+ return;
434
+ throw new GatewayRejection(403, 'origin not allowed');
435
+ }
436
+ /**
437
+ * Verify the publishable key the browser sent, in constant time.
438
+ *
439
+ * @param presented - The key from the request, or null/undefined when absent.
440
+ * @throws {GatewayRejection} 401 when the key is missing or wrong.
441
+ */
442
+ checkKey(presented) {
443
+ // Comparing digests keeps the comparison constant-time whatever the lengths.
444
+ const digest = (s) => createHmac('sha256', this._secret).update(s).digest();
445
+ if (!presented || !timingSafeEqual(digest(presented), digest(this.key))) {
446
+ throw new GatewayRejection(401, 'bad key');
447
+ }
448
+ }
449
+ /**
450
+ * The transcript a browser may redraw, and nothing else.
451
+ *
452
+ * `chat_log` returns the conversation as the service holds it: the
453
+ * substituted system prompt, then tool calls and results alongside the
454
+ * dialogue. Relaying that would publish the developer's prompt to anyone
455
+ * with a handle. Only user and assistant turns with text are kept, reduced
456
+ * to role, content and, when dated, the time in epoch seconds, so a
457
+ * restored transcript isn't shown as sent now.
458
+ *
459
+ * @param messages - Messages as `chat_log` returns them.
460
+ * @returns The visible turns.
461
+ */
462
+ static visibleMessages(messages) {
463
+ const out = [];
464
+ for (const msg of messages ?? []) {
465
+ if (!isPlainObject(msg))
466
+ continue;
467
+ const role = msg['role'];
468
+ const content = msg['content'];
469
+ if (typeof role !== 'string' || !VISIBLE_ROLES.has(role))
470
+ continue;
471
+ if (typeof content !== 'string' || !content.trim())
472
+ continue;
473
+ const entry = { role, content };
474
+ const ts = msg['timestamp'];
475
+ if (typeof ts === 'number' && Number.isInteger(ts) && ts > 0) {
476
+ entry['timestamp'] = ts / 1_000_000;
477
+ }
478
+ out.push(entry);
479
+ }
480
+ return out;
481
+ }
482
+ _chargeMint() {
483
+ const now = monotonic();
484
+ const cutoff = now - this.windowSeconds;
485
+ this._mints = this._mints.filter((t) => t > cutoff);
486
+ if (this._mints.length >= this.maxNewConversations) {
487
+ throw new GatewayRejection(429, 'too many new conversations');
488
+ }
489
+ this._mints.push(now);
490
+ }
491
+ _chargeTurn(conversationId) {
492
+ const now = monotonic();
493
+ // Swept here rather than on a timer: a handle can't outlive its TTL, so
494
+ // older entries can never be charged again.
495
+ const cutoff = now - this.handleTtl;
496
+ for (const [id, entry] of this._turns)
497
+ if (entry.at <= cutoff)
498
+ this._turns.delete(id);
499
+ const count = this._turns.get(conversationId)?.count ?? 0;
500
+ if (count >= this.maxTurns) {
501
+ throw new GatewayRejection(429, 'conversation turn limit reached');
502
+ }
503
+ this._turns.set(conversationId, { count: count + 1, at: now });
504
+ }
505
+ // ── The forwarded call ───────────────────────────────────────────
506
+ /**
507
+ * Validate the page context a browser sent (`user_meta_data`).
508
+ *
509
+ * The only field forwarded instead of replaced, so the only one that needs
510
+ * a shape and a size limit. Absent, null and empty all yield null.
511
+ *
512
+ * @param body - The browser's request body.
513
+ * @returns The metadata, or null.
514
+ * @throws {GatewayRejection} 400 when it isn't a JSON object, 413 when it's
515
+ * larger than {@link MAX_USER_METADATA_BYTES} serialized.
516
+ */
517
+ readUserMetadata(body) {
518
+ const raw = body['user_meta_data'];
519
+ if (raw === null || raw === undefined)
520
+ return null;
521
+ if (!isPlainObject(raw))
522
+ throw new GatewayRejection(400, 'user_meta_data must be an object');
523
+ if (Object.keys(raw).length === 0)
524
+ return null;
525
+ let size;
526
+ try {
527
+ size = jsonByteLength(raw);
528
+ }
529
+ catch {
530
+ // Reachable through prepare() with an object that never came from JSON.
531
+ throw new GatewayRejection(400, 'user_meta_data must be JSON-serializable');
532
+ }
533
+ if (size > MAX_USER_METADATA_BYTES)
534
+ throw new GatewayRejection(413, 'user_meta_data too large');
535
+ return raw;
536
+ }
537
+ /**
538
+ * Validate a browser request and build the call to the chat service.
539
+ *
540
+ * Everything the browser could use to widen its own access is refused or
541
+ * replaced here: the method must be one of four, the conversation comes
542
+ * from a signed handle, and `config_url` is the gateway's. The one
543
+ * exception is `user_meta_data`, which is forwarded (see
544
+ * {@link readUserMetadata}).
545
+ *
546
+ * A chat message over {@link MAX_MESSAGE_BYTES} (UTF-8) is refused with
547
+ * 413 before a conversation is created or a turn counted.
548
+ *
549
+ * @param body - The browser's request body:
550
+ * `{ method?, handle?, message?, user_meta_data? }`.
551
+ * @param opts - `origin`: the `Origin` header; `key`: the presented key.
552
+ * @returns `[method, params, mintedHandle]`, the service method and params
553
+ * to send, and the new handle when this call created the conversation
554
+ * (null otherwise), for the caller to return to the browser.
555
+ * @throws {GatewayRejection} When the request is refused.
556
+ */
557
+ prepare(body, opts) {
558
+ this.checkKey(opts.key);
559
+ this.checkOrigin(opts.origin);
560
+ const method = body['method'] ?? 'chat';
561
+ if (typeof method !== 'string' || !ALLOWED_METHODS.has(method)) {
562
+ throw new GatewayRejection(400, 'method not allowed');
563
+ }
564
+ // Read before minting, so a malformed value doesn't use up a
565
+ // new-conversation slot on a request that never reaches the service.
566
+ const userMetadata = this.readUserMetadata(body);
567
+ // The message size is checked before minting for the same reason.
568
+ const message = body['message'];
569
+ if (method === 'chat' &&
570
+ typeof message === 'string' &&
571
+ _utf8Length(message) > MAX_MESSAGE_BYTES) {
572
+ throw new GatewayRejection(413, 'message too large');
573
+ }
574
+ const handle = body['handle'];
575
+ let minted = null;
576
+ let conversationId;
577
+ if (handle) {
578
+ conversationId = this.readHandle(handle);
579
+ }
580
+ else if (method === 'end' || method === 'log') {
581
+ throw new GatewayRejection(400, `${method} requires a handle`);
582
+ }
583
+ else {
584
+ this._chargeMint();
585
+ minted = this.mintHandle();
586
+ conversationId = this.readHandle(minted);
587
+ }
588
+ if (method === 'end')
589
+ return ['end_conversation', { id: conversationId }, null];
590
+ // Scoped to the conversation inside the signed handle, never to anything
591
+ // the caller sent.
592
+ if (method === 'log')
593
+ return ['chat_log', { id: conversationId }, null];
594
+ if (method === 'start') {
595
+ // Opens the conversation with no user message, so the agent speaks first.
596
+ const params = { id: conversationId, config_url: this.configUrl };
597
+ if (this.conversationTimeout)
598
+ params['conversation_timeout'] = this.conversationTimeout;
599
+ if (userMetadata)
600
+ params['user_meta_data'] = userMetadata;
601
+ return ['create_conversation', params, minted];
602
+ }
603
+ if (typeof message !== 'string' || !message.trim()) {
604
+ throw new GatewayRejection(400, 'message is required');
605
+ }
606
+ this._chargeTurn(conversationId);
607
+ // config_url and the timeout on every chat: the service auto-creates the
608
+ // conversation on the first one and ignores both after.
609
+ const params = {
610
+ id: conversationId,
611
+ message,
612
+ config_url: this.configUrl,
613
+ };
614
+ if (this.conversationTimeout)
615
+ params['conversation_timeout'] = this.conversationTimeout;
616
+ // On every chat, since any chat may be the one that creates the
617
+ // conversation, the only time the service reads it.
618
+ if (userMetadata)
619
+ params['user_meta_data'] = userMetadata;
620
+ return ['chat', params, minted];
621
+ }
622
+ // ── HTTP ─────────────────────────────────────────────────────────
623
+ /**
624
+ * A Hono app serving this gateway at `/`. Mount it with
625
+ * `agent.mount(gateway.router(), { prefix: '/chat' })`, or `app.route()`.
626
+ *
627
+ * `POST /` takes `{ method: 'start'|'chat'|'log'|'end', handle?, message?,
628
+ * user_meta_data? }` with the key in `Authorization: Bearer`. A chat
629
+ * streams the service's JSON-RPC response through without buffering it:
630
+ * the service pads slow turns with keepalive whitespace so proxies don't
631
+ * close the connection, and collecting the body here would hold that
632
+ * padding back and bring the timeout into your own stack. A new handle is
633
+ * returned in the `X-Chat-Handle` header, which is why it can be sent
634
+ * before the body.
635
+ *
636
+ * `start` returns `{ greeting, status, timeout }`, `log` returns
637
+ * `{ messages, timeout, last_activity }` with only the visible dialogue,
638
+ * and `end` returns `{ status: 'ended' }`. A refusal returns
639
+ * `{ error: reason }` with the rejection's status, and a failure reaching
640
+ * the chat service before any reply is sent returns 502
641
+ * `{ error: 'chat service error' }`, with CORS headers either way. A
642
+ * request body over {@link MAX_REQUEST_BODY_BYTES} is answered with 413
643
+ * `{ error: 'request too large' }` without being parsed.
644
+ *
645
+ * @returns The Hono app.
646
+ */
647
+ router() {
648
+ const router = new Hono();
649
+ const cors = (origin) => {
650
+ if (origin === undefined)
651
+ return {};
652
+ try {
653
+ this.checkOrigin(origin);
654
+ }
655
+ catch {
656
+ return {};
657
+ }
658
+ return {
659
+ 'Access-Control-Allow-Origin': origin,
660
+ 'Access-Control-Expose-Headers': 'X-Chat-Handle',
661
+ Vary: 'Origin',
662
+ };
663
+ };
664
+ router.options('/', (c) => {
665
+ const headers = cors(c.req.header('origin'));
666
+ if (Object.keys(headers).length > 0) {
667
+ headers['Access-Control-Allow-Headers'] = 'Authorization, Content-Type';
668
+ headers['Access-Control-Allow-Methods'] = 'POST, OPTIONS';
669
+ headers['Access-Control-Max-Age'] = '600';
670
+ }
671
+ return c.body(null, 204, headers);
672
+ });
673
+ router.post('/', async (c) => {
674
+ const origin = c.req.header('origin');
675
+ const auth = c.req.header('authorization') ?? '';
676
+ const key = auth.toLowerCase().startsWith('bearer ') ? auth.slice(7) : null;
677
+ const corsHeaders = cors(origin);
678
+ let method;
679
+ let params;
680
+ let minted;
681
+ try {
682
+ // A GatewayRejection (413) goes to the handler below; anything
683
+ // else is a body that isn't JSON.
684
+ const body = await _readJsonBody(c.req);
685
+ if (!isPlainObject(body))
686
+ throw new GatewayRejection(400, 'body must be an object');
687
+ [method, params, minted] = this.prepare(body, { origin, key });
688
+ }
689
+ catch (err) {
690
+ if (err instanceof GatewayRejection) {
691
+ return c.json({ error: err.reason }, err.status, corsHeaders);
692
+ }
693
+ return c.json({ error: 'bad request' }, 400, corsHeaders);
694
+ }
695
+ const id = params['id'];
696
+ try {
697
+ return await this._forward(c, method, id, params, minted, corsHeaders);
698
+ }
699
+ catch (err) {
700
+ // Before any of the reply was sent: answer with the CORS headers, so
701
+ // the widget can read the refusal. (A failure after streaming
702
+ // started can only end the stream.) Only the error's type is logged.
703
+ logger.error('chat_gateway_upstream_failed', {
704
+ method,
705
+ error_type: err instanceof Error ? err.name : typeof err,
706
+ });
707
+ return c.json({ error: 'chat service error' }, 502, corsHeaders);
708
+ }
709
+ });
710
+ return router;
711
+ }
712
+ /** Send a prepared call to the chat service and build the browser's answer. */
713
+ async _forward(c, method, id, params, minted, corsHeaders) {
714
+ if (method === 'end_conversation') {
715
+ await this._client.end(id);
716
+ return c.json({ status: 'ended' }, 200, corsHeaders);
717
+ }
718
+ if (method === 'create_conversation') {
719
+ // prepare() decides whether a timeout applies; it has to reach the
720
+ // service, or the browser is told one number and the service keeps another.
721
+ const info = await this._client.createConversation(id, {
722
+ configUrl: params['config_url'],
723
+ timeout: params['conversation_timeout'],
724
+ userMetadata: params['user_meta_data'],
725
+ });
726
+ const headers = minted ? { ...corsHeaders, 'X-Chat-Handle': minted } : corsHeaders;
727
+ return c.json({ greeting: info.initialMessage, status: info.status, timeout: this.effectiveTimeout }, 200, headers);
728
+ }
729
+ if (method === 'chat_log') {
730
+ const log = await this._client.log(id);
731
+ return c.json({
732
+ messages: ChatGateway.visibleMessages(log.messages),
733
+ timeout: this.effectiveTimeout,
734
+ last_activity: ChatGateway.lastActivity(log.messages),
735
+ }, 200, corsHeaders);
736
+ }
737
+ const upstream = await this._client.rawPost(method, params);
738
+ const headers = {
739
+ ...corsHeaders,
740
+ 'Content-Type': 'application/json',
741
+ };
742
+ if (minted)
743
+ headers['X-Chat-Handle'] = minted;
744
+ return new Response(upstream.body, { status: 200, headers });
745
+ }
746
+ }
747
+ //# sourceMappingURL=ChatGateway.js.map