signalwire-agents 0.1.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 (245) hide show
  1. package/CLAUDE.md +112 -0
  2. package/README.md +417 -0
  3. package/dist/AgentBase.d.ts +481 -0
  4. package/dist/AgentBase.js +1155 -0
  5. package/dist/AgentBase.js.map +1 -0
  6. package/dist/AgentServer.d.ts +60 -0
  7. package/dist/AgentServer.js +128 -0
  8. package/dist/AgentServer.js.map +1 -0
  9. package/dist/AuthHandler.d.ts +56 -0
  10. package/dist/AuthHandler.js +119 -0
  11. package/dist/AuthHandler.js.map +1 -0
  12. package/dist/ConfigLoader.d.ts +68 -0
  13. package/dist/ConfigLoader.js +150 -0
  14. package/dist/ConfigLoader.js.map +1 -0
  15. package/dist/ContextBuilder.d.ts +431 -0
  16. package/dist/ContextBuilder.js +751 -0
  17. package/dist/ContextBuilder.js.map +1 -0
  18. package/dist/DataMap.d.ts +179 -0
  19. package/dist/DataMap.js +321 -0
  20. package/dist/DataMap.js.map +1 -0
  21. package/dist/Logger.d.ts +91 -0
  22. package/dist/Logger.js +191 -0
  23. package/dist/Logger.js.map +1 -0
  24. package/dist/PomBuilder.d.ts +144 -0
  25. package/dist/PomBuilder.js +249 -0
  26. package/dist/PomBuilder.js.map +1 -0
  27. package/dist/PromptManager.d.ts +85 -0
  28. package/dist/PromptManager.js +108 -0
  29. package/dist/PromptManager.js.map +1 -0
  30. package/dist/SchemaUtils.d.ts +42 -0
  31. package/dist/SchemaUtils.js +148 -0
  32. package/dist/SchemaUtils.js.map +1 -0
  33. package/dist/ServerlessAdapter.d.ts +100 -0
  34. package/dist/ServerlessAdapter.js +166 -0
  35. package/dist/ServerlessAdapter.js.map +1 -0
  36. package/dist/SessionManager.d.ts +86 -0
  37. package/dist/SessionManager.js +155 -0
  38. package/dist/SessionManager.js.map +1 -0
  39. package/dist/SslConfig.d.ts +77 -0
  40. package/dist/SslConfig.js +100 -0
  41. package/dist/SslConfig.js.map +1 -0
  42. package/dist/SwaigFunction.d.ts +88 -0
  43. package/dist/SwaigFunction.js +125 -0
  44. package/dist/SwaigFunction.js.map +1 -0
  45. package/dist/SwaigFunctionResult.d.ts +442 -0
  46. package/dist/SwaigFunctionResult.js +735 -0
  47. package/dist/SwaigFunctionResult.js.map +1 -0
  48. package/dist/SwmlBuilder.d.ts +37 -0
  49. package/dist/SwmlBuilder.js +55 -0
  50. package/dist/SwmlBuilder.js.map +1 -0
  51. package/dist/cli/agent-loader.d.ts +22 -0
  52. package/dist/cli/agent-loader.js +106 -0
  53. package/dist/cli/agent-loader.js.map +1 -0
  54. package/dist/cli/mock-data.d.ts +37 -0
  55. package/dist/cli/mock-data.js +79 -0
  56. package/dist/cli/mock-data.js.map +1 -0
  57. package/dist/cli/swaig-test.d.ts +32 -0
  58. package/dist/cli/swaig-test.js +405 -0
  59. package/dist/cli/swaig-test.js.map +1 -0
  60. package/dist/index.d.ts +36 -0
  61. package/dist/index.js +44 -0
  62. package/dist/index.js.map +1 -0
  63. package/dist/prefabs/ConciergeAgent.d.ts +64 -0
  64. package/dist/prefabs/ConciergeAgent.js +188 -0
  65. package/dist/prefabs/ConciergeAgent.js.map +1 -0
  66. package/dist/prefabs/FAQBotAgent.d.ts +68 -0
  67. package/dist/prefabs/FAQBotAgent.js +206 -0
  68. package/dist/prefabs/FAQBotAgent.js.map +1 -0
  69. package/dist/prefabs/InfoGathererAgent.d.ts +73 -0
  70. package/dist/prefabs/InfoGathererAgent.js +202 -0
  71. package/dist/prefabs/InfoGathererAgent.js.map +1 -0
  72. package/dist/prefabs/ReceptionistAgent.d.ts +65 -0
  73. package/dist/prefabs/ReceptionistAgent.js +205 -0
  74. package/dist/prefabs/ReceptionistAgent.js.map +1 -0
  75. package/dist/prefabs/SurveyAgent.d.ts +84 -0
  76. package/dist/prefabs/SurveyAgent.js +324 -0
  77. package/dist/prefabs/SurveyAgent.js.map +1 -0
  78. package/dist/prefabs/index.d.ts +13 -0
  79. package/dist/prefabs/index.js +14 -0
  80. package/dist/prefabs/index.js.map +1 -0
  81. package/dist/skills/SkillBase.d.ts +134 -0
  82. package/dist/skills/SkillBase.js +105 -0
  83. package/dist/skills/SkillBase.js.map +1 -0
  84. package/dist/skills/SkillManager.d.ts +83 -0
  85. package/dist/skills/SkillManager.js +159 -0
  86. package/dist/skills/SkillManager.js.map +1 -0
  87. package/dist/skills/SkillRegistry.d.ts +105 -0
  88. package/dist/skills/SkillRegistry.js +195 -0
  89. package/dist/skills/SkillRegistry.js.map +1 -0
  90. package/dist/skills/builtin/api_ninjas_trivia.d.ts +35 -0
  91. package/dist/skills/builtin/api_ninjas_trivia.js +161 -0
  92. package/dist/skills/builtin/api_ninjas_trivia.js.map +1 -0
  93. package/dist/skills/builtin/claude_skills.d.ts +34 -0
  94. package/dist/skills/builtin/claude_skills.js +156 -0
  95. package/dist/skills/builtin/claude_skills.js.map +1 -0
  96. package/dist/skills/builtin/custom_skills.d.ts +59 -0
  97. package/dist/skills/builtin/custom_skills.js +231 -0
  98. package/dist/skills/builtin/custom_skills.js.map +1 -0
  99. package/dist/skills/builtin/datasphere.d.ts +34 -0
  100. package/dist/skills/builtin/datasphere.js +163 -0
  101. package/dist/skills/builtin/datasphere.js.map +1 -0
  102. package/dist/skills/builtin/datasphere_serverless.d.ts +54 -0
  103. package/dist/skills/builtin/datasphere_serverless.js +155 -0
  104. package/dist/skills/builtin/datasphere_serverless.js.map +1 -0
  105. package/dist/skills/builtin/datetime.d.ts +31 -0
  106. package/dist/skills/builtin/datetime.js +95 -0
  107. package/dist/skills/builtin/datetime.js.map +1 -0
  108. package/dist/skills/builtin/google_maps.d.ts +33 -0
  109. package/dist/skills/builtin/google_maps.js +233 -0
  110. package/dist/skills/builtin/google_maps.js.map +1 -0
  111. package/dist/skills/builtin/index.d.ts +28 -0
  112. package/dist/skills/builtin/index.js +75 -0
  113. package/dist/skills/builtin/index.js.map +1 -0
  114. package/dist/skills/builtin/info_gatherer.d.ts +52 -0
  115. package/dist/skills/builtin/info_gatherer.js +237 -0
  116. package/dist/skills/builtin/info_gatherer.js.map +1 -0
  117. package/dist/skills/builtin/joke.d.ts +32 -0
  118. package/dist/skills/builtin/joke.js +142 -0
  119. package/dist/skills/builtin/joke.js.map +1 -0
  120. package/dist/skills/builtin/math.d.ts +33 -0
  121. package/dist/skills/builtin/math.js +120 -0
  122. package/dist/skills/builtin/math.js.map +1 -0
  123. package/dist/skills/builtin/mcp_gateway.d.ts +35 -0
  124. package/dist/skills/builtin/mcp_gateway.js +85 -0
  125. package/dist/skills/builtin/mcp_gateway.js.map +1 -0
  126. package/dist/skills/builtin/native_vector_search.d.ts +44 -0
  127. package/dist/skills/builtin/native_vector_search.js +248 -0
  128. package/dist/skills/builtin/native_vector_search.js.map +1 -0
  129. package/dist/skills/builtin/play_background_file.d.ts +34 -0
  130. package/dist/skills/builtin/play_background_file.js +135 -0
  131. package/dist/skills/builtin/play_background_file.js.map +1 -0
  132. package/dist/skills/builtin/spider.d.ts +34 -0
  133. package/dist/skills/builtin/spider.js +164 -0
  134. package/dist/skills/builtin/spider.js.map +1 -0
  135. package/dist/skills/builtin/swml_transfer.d.ts +44 -0
  136. package/dist/skills/builtin/swml_transfer.js +204 -0
  137. package/dist/skills/builtin/swml_transfer.js.map +1 -0
  138. package/dist/skills/builtin/weather_api.d.ts +34 -0
  139. package/dist/skills/builtin/weather_api.js +136 -0
  140. package/dist/skills/builtin/weather_api.js.map +1 -0
  141. package/dist/skills/builtin/web_search.d.ts +34 -0
  142. package/dist/skills/builtin/web_search.js +141 -0
  143. package/dist/skills/builtin/web_search.js.map +1 -0
  144. package/dist/skills/builtin/wikipedia_search.d.ts +34 -0
  145. package/dist/skills/builtin/wikipedia_search.js +166 -0
  146. package/dist/skills/builtin/wikipedia_search.js.map +1 -0
  147. package/dist/skills/index.d.ts +11 -0
  148. package/dist/skills/index.js +10 -0
  149. package/dist/skills/index.js.map +1 -0
  150. package/dist/types.d.ts +85 -0
  151. package/dist/types.js +5 -0
  152. package/dist/types.js.map +1 -0
  153. package/docs/agent-guide.md +869 -0
  154. package/docs/api-reference.md +2419 -0
  155. package/docs/architecture.md +843 -0
  156. package/docs/cli-guide.md +579 -0
  157. package/docs/configuration.md +422 -0
  158. package/docs/contexts-guide.md +787 -0
  159. package/docs/datamap-guide.md +1141 -0
  160. package/docs/prefabs-guide.md +830 -0
  161. package/docs/security.md +436 -0
  162. package/docs/serverless-guide.md +513 -0
  163. package/docs/skills-guide.md +845 -0
  164. package/docs/swaig-reference.md +1627 -0
  165. package/examples/call-flow.ts +60 -0
  166. package/examples/contexts-steps.ts +62 -0
  167. package/examples/datamap-tools.ts +52 -0
  168. package/examples/dynamic-config.ts +51 -0
  169. package/examples/multi-agent.ts +67 -0
  170. package/examples/pom-prompt.ts +68 -0
  171. package/examples/simple-agent.ts +33 -0
  172. package/package.json +35 -0
  173. package/src/AgentBase.ts +1279 -0
  174. package/src/AgentServer.ts +149 -0
  175. package/src/AuthHandler.ts +141 -0
  176. package/src/ConfigLoader.ts +165 -0
  177. package/src/ContextBuilder.ts +796 -0
  178. package/src/DataMap.ts +365 -0
  179. package/src/Logger.ts +197 -0
  180. package/src/PomBuilder.ts +298 -0
  181. package/src/PromptManager.ts +133 -0
  182. package/src/SchemaUtils.ts +170 -0
  183. package/src/ServerlessAdapter.ts +218 -0
  184. package/src/SessionManager.ts +161 -0
  185. package/src/SslConfig.ts +118 -0
  186. package/src/SwaigFunction.ts +168 -0
  187. package/src/SwaigFunctionResult.ts +864 -0
  188. package/src/SwmlBuilder.ts +62 -0
  189. package/src/cli/agent-loader.ts +122 -0
  190. package/src/cli/mock-data.ts +110 -0
  191. package/src/cli/swaig-test.ts +440 -0
  192. package/src/index.ts +99 -0
  193. package/src/prefabs/ConciergeAgent.ts +251 -0
  194. package/src/prefabs/FAQBotAgent.ts +263 -0
  195. package/src/prefabs/InfoGathererAgent.ts +276 -0
  196. package/src/prefabs/ReceptionistAgent.ts +277 -0
  197. package/src/prefabs/SurveyAgent.ts +413 -0
  198. package/src/prefabs/index.ts +23 -0
  199. package/src/skills/SkillBase.ts +184 -0
  200. package/src/skills/SkillManager.ts +177 -0
  201. package/src/skills/SkillRegistry.ts +231 -0
  202. package/src/skills/builtin/api_ninjas_trivia.ts +230 -0
  203. package/src/skills/builtin/claude_skills.ts +239 -0
  204. package/src/skills/builtin/custom_skills.ts +326 -0
  205. package/src/skills/builtin/datasphere.ts +225 -0
  206. package/src/skills/builtin/datasphere_serverless.ts +194 -0
  207. package/src/skills/builtin/datetime.ts +115 -0
  208. package/src/skills/builtin/google_maps.ts +347 -0
  209. package/src/skills/builtin/index.ts +79 -0
  210. package/src/skills/builtin/info_gatherer.ts +331 -0
  211. package/src/skills/builtin/joke.ts +180 -0
  212. package/src/skills/builtin/math.ts +150 -0
  213. package/src/skills/builtin/mcp_gateway.ts +99 -0
  214. package/src/skills/builtin/native_vector_search.ts +327 -0
  215. package/src/skills/builtin/play_background_file.ts +189 -0
  216. package/src/skills/builtin/spider.ts +232 -0
  217. package/src/skills/builtin/swml_transfer.ts +285 -0
  218. package/src/skills/builtin/weather_api.ts +193 -0
  219. package/src/skills/builtin/web_search.ts +212 -0
  220. package/src/skills/builtin/wikipedia_search.ts +248 -0
  221. package/src/skills/index.ts +12 -0
  222. package/src/types.ts +99 -0
  223. package/tests/AgentBase.test.ts +693 -0
  224. package/tests/AgentServer.test.ts +102 -0
  225. package/tests/AuthHandler.test.ts +121 -0
  226. package/tests/ConfigLoader.test.ts +121 -0
  227. package/tests/DataMap.test.ts +286 -0
  228. package/tests/Logger.test.ts +218 -0
  229. package/tests/PomBuilder.test.ts +164 -0
  230. package/tests/ProxyDetection.test.ts +185 -0
  231. package/tests/SchemaUtils.test.ts +106 -0
  232. package/tests/ServerlessAdapter.test.ts +200 -0
  233. package/tests/SessionManager.test.ts +139 -0
  234. package/tests/SslConfig.test.ts +97 -0
  235. package/tests/SwaigFunctionResult.test.ts +298 -0
  236. package/tests/cli/mock-data.test.ts +94 -0
  237. package/tests/cli/swaig-test.test.ts +96 -0
  238. package/tests/prefabs/prefabs.test.ts +854 -0
  239. package/tests/setup.ts +6 -0
  240. package/tests/skills/SkillBase.test.ts +118 -0
  241. package/tests/skills/SkillManager.test.ts +164 -0
  242. package/tests/skills/SkillRegistry.test.ts +124 -0
  243. package/tests/skills/builtin.test.ts +924 -0
  244. package/tsconfig.json +18 -0
  245. package/vitest.config.ts +9 -0
@@ -0,0 +1,735 @@
1
+ /**
2
+ * SwaigFunctionResult - Builder for SWAIG function responses.
3
+ *
4
+ * Carries response text and a list of structured actions (connect, hangup, SMS, etc.).
5
+ * Every mutating method returns `this` for fluent chaining.
6
+ */
7
+ /**
8
+ * Builder for SWAIG function responses.
9
+ *
10
+ * Carries response text and a list of structured actions (connect, hangup, SMS, etc.).
11
+ * Every mutating method returns `this` for fluent chaining.
12
+ */
13
+ export class SwaigFunctionResult {
14
+ /** The text response returned to the AI agent. */
15
+ response;
16
+ /** Ordered list of actions to execute after the response. */
17
+ action;
18
+ /** Whether actions should be post-processed after the AI responds. */
19
+ postProcess;
20
+ /**
21
+ * @param response - Initial response text; defaults to empty string.
22
+ * @param postProcess - Whether to enable post-processing of actions.
23
+ */
24
+ constructor(response, postProcess = false) {
25
+ this.response = response ?? '';
26
+ this.action = [];
27
+ this.postProcess = postProcess;
28
+ }
29
+ // ── Core ────────────────────────────────────────────────────────────
30
+ /**
31
+ * Set the response text returned to the AI agent.
32
+ * @param response - The response text.
33
+ * @returns This instance for chaining.
34
+ */
35
+ setResponse(response) {
36
+ this.response = response;
37
+ return this;
38
+ }
39
+ /**
40
+ * Enable or disable post-processing of actions.
41
+ * @param postProcess - Whether to post-process actions.
42
+ * @returns This instance for chaining.
43
+ */
44
+ setPostProcess(postProcess) {
45
+ this.postProcess = postProcess;
46
+ return this;
47
+ }
48
+ /**
49
+ * Append a single named action to the action list.
50
+ * @param name - The action name (e.g., "hangup", "say").
51
+ * @param data - The action payload.
52
+ * @returns This instance for chaining.
53
+ */
54
+ addAction(name, data) {
55
+ this.action.push({ [name]: data });
56
+ return this;
57
+ }
58
+ /**
59
+ * Append multiple action objects to the action list.
60
+ * @param actions - Array of action objects to append.
61
+ * @returns This instance for chaining.
62
+ */
63
+ addActions(actions) {
64
+ this.action.push(...actions);
65
+ return this;
66
+ }
67
+ // ── Call control ────────────────────────────────────────────────────
68
+ /**
69
+ * Connect the call to another destination via SWML transfer.
70
+ * @param destination - The destination address (phone number or SIP URI).
71
+ * @param final - Whether this is a final transfer that ends the AI session.
72
+ * @param fromAddr - Optional caller ID to use for the outbound leg.
73
+ * @returns This instance for chaining.
74
+ */
75
+ connect(destination, final = true, fromAddr) {
76
+ const connectParams = { to: destination };
77
+ if (fromAddr !== undefined) {
78
+ connectParams['from'] = fromAddr;
79
+ }
80
+ this.action.push({
81
+ SWML: {
82
+ sections: { main: [{ connect: connectParams }] },
83
+ version: '1.0.0',
84
+ },
85
+ transfer: String(final),
86
+ });
87
+ return this;
88
+ }
89
+ /**
90
+ * Transfer the call to a SWML destination with a custom AI response.
91
+ * @param dest - The transfer destination.
92
+ * @param aiResponse - The AI response text to set before transferring.
93
+ * @param final - Whether this is a final transfer.
94
+ * @returns This instance for chaining.
95
+ */
96
+ swmlTransfer(dest, aiResponse, final = true) {
97
+ this.action.push({
98
+ SWML: {
99
+ version: '1.0.0',
100
+ sections: {
101
+ main: [
102
+ { set: { ai_response: aiResponse } },
103
+ { transfer: { dest } },
104
+ ],
105
+ },
106
+ },
107
+ transfer: String(final),
108
+ });
109
+ return this;
110
+ }
111
+ /**
112
+ * Hang up the call.
113
+ * @returns This instance for chaining.
114
+ */
115
+ hangup() {
116
+ return this.addAction('hangup', true);
117
+ }
118
+ /**
119
+ * Place the call on hold for a specified duration.
120
+ * @param timeout - Hold duration in seconds, clamped to 0-900.
121
+ * @returns This instance for chaining.
122
+ */
123
+ hold(timeout = 300) {
124
+ return this.addAction('hold', Math.max(0, Math.min(timeout, 900)));
125
+ }
126
+ /**
127
+ * Wait for user input before continuing.
128
+ * @param opts - Options controlling wait behavior: enable/disable, timeout, or answer-first mode.
129
+ * @returns This instance for chaining.
130
+ */
131
+ waitForUser(opts) {
132
+ let value = true;
133
+ if (opts?.answerFirst) {
134
+ value = 'answer_first';
135
+ }
136
+ else if (opts?.timeout !== undefined) {
137
+ value = opts.timeout;
138
+ }
139
+ else if (opts?.enabled !== undefined) {
140
+ value = opts.enabled;
141
+ }
142
+ return this.addAction('wait_for_user', value);
143
+ }
144
+ /**
145
+ * Stop the AI session.
146
+ * @returns This instance for chaining.
147
+ */
148
+ stop() {
149
+ return this.addAction('stop', true);
150
+ }
151
+ // ── Audio ───────────────────────────────────────────────────────────
152
+ /**
153
+ * Speak text to the caller via TTS.
154
+ * @param text - The text to speak.
155
+ * @returns This instance for chaining.
156
+ */
157
+ say(text) {
158
+ return this.addAction('say', text);
159
+ }
160
+ /**
161
+ * Play an audio file in the background during the call.
162
+ * @param filename - URL or path of the audio file.
163
+ * @param wait - Whether to wait for playback to complete before continuing.
164
+ * @returns This instance for chaining.
165
+ */
166
+ playBackgroundFile(filename, wait = false) {
167
+ if (wait) {
168
+ return this.addAction('playback_bg', { file: filename, wait: true });
169
+ }
170
+ return this.addAction('playback_bg', filename);
171
+ }
172
+ /**
173
+ * Stop any currently playing background audio file.
174
+ * @returns This instance for chaining.
175
+ */
176
+ stopBackgroundFile() {
177
+ return this.addAction('stop_playback_bg', true);
178
+ }
179
+ // ── Speech ──────────────────────────────────────────────────────────
180
+ /**
181
+ * Add dynamic speech recognition hints to improve transcription accuracy.
182
+ * @param hints - Array of hint strings or pattern-replacement objects.
183
+ * @returns This instance for chaining.
184
+ */
185
+ addDynamicHints(hints) {
186
+ return this.addAction('add_dynamic_hints', hints);
187
+ }
188
+ /**
189
+ * Remove all previously added dynamic speech hints.
190
+ * @returns This instance for chaining.
191
+ */
192
+ clearDynamicHints() {
193
+ this.action.push({ clear_dynamic_hints: {} });
194
+ return this;
195
+ }
196
+ /**
197
+ * Set the silence duration that marks the end of a user's speech.
198
+ * @param milliseconds - Timeout in milliseconds.
199
+ * @returns This instance for chaining.
200
+ */
201
+ setEndOfSpeechTimeout(milliseconds) {
202
+ return this.addAction('end_of_speech_timeout', milliseconds);
203
+ }
204
+ /**
205
+ * Set the timeout for speech event detection.
206
+ * @param milliseconds - Timeout in milliseconds.
207
+ * @returns This instance for chaining.
208
+ */
209
+ setSpeechEventTimeout(milliseconds) {
210
+ return this.addAction('speech_event_timeout', milliseconds);
211
+ }
212
+ // ── Data ────────────────────────────────────────────────────────────
213
+ /**
214
+ * Merge key-value pairs into the global data store shared across functions.
215
+ * @param data - Key-value pairs to set or update.
216
+ * @returns This instance for chaining.
217
+ */
218
+ updateGlobalData(data) {
219
+ return this.addAction('set_global_data', data);
220
+ }
221
+ /**
222
+ * Remove keys from the global data store.
223
+ * @param keys - A single key or array of keys to remove.
224
+ * @returns This instance for chaining.
225
+ */
226
+ removeGlobalData(keys) {
227
+ return this.addAction('unset_global_data', keys);
228
+ }
229
+ /**
230
+ * Set metadata key-value pairs on the current call.
231
+ * @param data - Metadata key-value pairs to set.
232
+ * @returns This instance for chaining.
233
+ */
234
+ setMetadata(data) {
235
+ return this.addAction('set_meta_data', data);
236
+ }
237
+ /**
238
+ * Remove metadata keys from the current call.
239
+ * @param keys - A single key or array of keys to remove.
240
+ * @returns This instance for chaining.
241
+ */
242
+ removeMetadata(keys) {
243
+ return this.addAction('unset_meta_data', keys);
244
+ }
245
+ // ── SWML helpers ────────────────────────────────────────────────────
246
+ /**
247
+ * Execute arbitrary SWML content as an action.
248
+ * @param swmlContent - SWML as a JSON string or object.
249
+ * @param transfer - Whether this SWML execution should transfer the call.
250
+ * @returns This instance for chaining.
251
+ */
252
+ executeSwml(swmlContent, transfer = false) {
253
+ let swmlData;
254
+ if (typeof swmlContent === 'string') {
255
+ try {
256
+ swmlData = JSON.parse(swmlContent);
257
+ }
258
+ catch {
259
+ swmlData = { raw_swml: swmlContent };
260
+ }
261
+ }
262
+ else {
263
+ swmlData = { ...swmlContent };
264
+ }
265
+ if (transfer) {
266
+ swmlData['transfer'] = 'true';
267
+ }
268
+ return this.addAction('SWML', swmlData);
269
+ }
270
+ /**
271
+ * Change the current SWML step.
272
+ * @param stepName - The name of the step to switch to.
273
+ * @returns This instance for chaining.
274
+ */
275
+ swmlChangeStep(stepName) {
276
+ return this.addAction('change_step', stepName);
277
+ }
278
+ /**
279
+ * Change the current SWML context.
280
+ * @param contextName - The name of the context to switch to.
281
+ * @returns This instance for chaining.
282
+ */
283
+ swmlChangeContext(contextName) {
284
+ return this.addAction('change_context', contextName);
285
+ }
286
+ /**
287
+ * Emit a custom user event via SWML.
288
+ * @param eventData - The event payload.
289
+ * @returns This instance for chaining.
290
+ */
291
+ swmlUserEvent(eventData) {
292
+ return this.addAction('SWML', {
293
+ sections: { main: [{ user_event: { event: eventData } }] },
294
+ version: '1.0.0',
295
+ });
296
+ }
297
+ /**
298
+ * Switch the AI context with optional new prompts and reset options.
299
+ * @param opts - Context switch options including system/user prompts and reset flags.
300
+ * @returns This instance for chaining.
301
+ */
302
+ switchContext(opts) {
303
+ const sp = opts?.systemPrompt;
304
+ const up = opts?.userPrompt;
305
+ const cons = opts?.consolidate;
306
+ const fr = opts?.fullReset;
307
+ if (sp && !up && !cons && !fr) {
308
+ return this.addAction('context_switch', sp);
309
+ }
310
+ const data = {};
311
+ if (sp)
312
+ data['system_prompt'] = sp;
313
+ if (up)
314
+ data['user_prompt'] = up;
315
+ if (cons)
316
+ data['consolidate'] = true;
317
+ if (fr)
318
+ data['full_reset'] = true;
319
+ return this.addAction('context_switch', data);
320
+ }
321
+ // ── Functions ───────────────────────────────────────────────────────
322
+ /**
323
+ * Enable or disable SWAIG functions by name.
324
+ * @param toggles - Array of function name and active state pairs.
325
+ * @returns This instance for chaining.
326
+ */
327
+ toggleFunctions(toggles) {
328
+ return this.addAction('toggle_functions', toggles);
329
+ }
330
+ /**
331
+ * Control whether functions fire on speaker timeout.
332
+ * @param enabled - Whether to enable function execution on timeout.
333
+ * @returns This instance for chaining.
334
+ */
335
+ enableFunctionsOnTimeout(enabled = true) {
336
+ return this.addAction('functions_on_speaker_timeout', enabled);
337
+ }
338
+ /**
339
+ * Update AI engine settings at runtime.
340
+ * @param settings - Key-value pairs of settings to update.
341
+ * @returns This instance for chaining.
342
+ */
343
+ updateSettings(settings) {
344
+ return this.addAction('settings', settings);
345
+ }
346
+ // ── User input / history ────────────────────────────────────────────
347
+ /**
348
+ * Inject text as if the user had spoken it.
349
+ * @param text - The simulated user input text.
350
+ * @returns This instance for chaining.
351
+ */
352
+ simulateUserInput(text) {
353
+ return this.addAction('user_input', text);
354
+ }
355
+ /**
356
+ * Enable or disable extensive data reporting in function calls.
357
+ * @param enabled - Whether to enable extensive data.
358
+ * @returns This instance for chaining.
359
+ */
360
+ enableExtensiveData(enabled = true) {
361
+ return this.addAction('extensive_data', enabled);
362
+ }
363
+ /**
364
+ * Replace the function call output in conversation history.
365
+ * @param text - Replacement text, or true to replace with the response.
366
+ * @returns This instance for chaining.
367
+ */
368
+ replaceInHistory(text = true) {
369
+ return this.addAction('replace_in_history', text);
370
+ }
371
+ // ── Comms ───────────────────────────────────────────────────────────
372
+ /**
373
+ * Send an SMS or MMS message from within the call flow.
374
+ * @param opts - SMS parameters including to/from numbers and body or media.
375
+ * @returns This instance for chaining.
376
+ */
377
+ sendSms(opts) {
378
+ if (!opts.body && !opts.media) {
379
+ throw new Error('Either body or media must be provided');
380
+ }
381
+ const smsParams = {
382
+ to_number: opts.toNumber,
383
+ from_number: opts.fromNumber,
384
+ };
385
+ if (opts.body)
386
+ smsParams['body'] = opts.body;
387
+ if (opts.media)
388
+ smsParams['media'] = opts.media;
389
+ if (opts.tags)
390
+ smsParams['tags'] = opts.tags;
391
+ if (opts.region)
392
+ smsParams['region'] = opts.region;
393
+ return this.executeSwml({
394
+ version: '1.0.0',
395
+ sections: { main: [{ send_sms: smsParams }] },
396
+ });
397
+ }
398
+ /**
399
+ * Start recording the call.
400
+ * @param opts - Recording options including format, direction, and timeouts.
401
+ * @returns This instance for chaining.
402
+ */
403
+ recordCall(opts) {
404
+ const format = opts?.format ?? 'wav';
405
+ const direction = opts?.direction ?? 'both';
406
+ const params = {
407
+ stereo: opts?.stereo ?? false,
408
+ format,
409
+ direction,
410
+ beep: opts?.beep ?? false,
411
+ input_sensitivity: opts?.inputSensitivity ?? 44.0,
412
+ };
413
+ if (opts?.controlId)
414
+ params['control_id'] = opts.controlId;
415
+ if (opts?.terminators)
416
+ params['terminators'] = opts.terminators;
417
+ if (opts?.initialTimeout !== undefined)
418
+ params['initial_timeout'] = opts.initialTimeout;
419
+ if (opts?.endSilenceTimeout !== undefined)
420
+ params['end_silence_timeout'] = opts.endSilenceTimeout;
421
+ if (opts?.maxLength !== undefined)
422
+ params['max_length'] = opts.maxLength;
423
+ if (opts?.statusUrl)
424
+ params['status_url'] = opts.statusUrl;
425
+ return this.executeSwml({
426
+ version: '1.0.0',
427
+ sections: { main: [{ record_call: params }] },
428
+ });
429
+ }
430
+ /**
431
+ * Stop an active call recording.
432
+ * @param controlId - Optional control ID of the recording to stop.
433
+ * @returns This instance for chaining.
434
+ */
435
+ stopRecordCall(controlId) {
436
+ const params = {};
437
+ if (controlId)
438
+ params['control_id'] = controlId;
439
+ return this.executeSwml({
440
+ version: '1.0.0',
441
+ sections: { main: [{ stop_record_call: params }] },
442
+ });
443
+ }
444
+ /**
445
+ * Start a media tap to stream audio to an external URI.
446
+ * @param opts - Tap parameters including URI, direction, and codec.
447
+ * @returns This instance for chaining.
448
+ */
449
+ tap(opts) {
450
+ const params = { uri: opts.uri };
451
+ if (opts.controlId)
452
+ params['control_id'] = opts.controlId;
453
+ if (opts.direction && opts.direction !== 'both')
454
+ params['direction'] = opts.direction;
455
+ if (opts.codec && opts.codec !== 'PCMU')
456
+ params['codec'] = opts.codec;
457
+ if (opts.rtpPtime && opts.rtpPtime !== 20)
458
+ params['rtp_ptime'] = opts.rtpPtime;
459
+ if (opts.statusUrl)
460
+ params['status_url'] = opts.statusUrl;
461
+ return this.executeSwml({
462
+ version: '1.0.0',
463
+ sections: { main: [{ tap: params }] },
464
+ });
465
+ }
466
+ /**
467
+ * Stop an active media tap.
468
+ * @param controlId - Optional control ID of the tap to stop.
469
+ * @returns This instance for chaining.
470
+ */
471
+ stopTap(controlId) {
472
+ const params = {};
473
+ if (controlId)
474
+ params['control_id'] = controlId;
475
+ return this.executeSwml({
476
+ version: '1.0.0',
477
+ sections: { main: [{ stop_tap: params }] },
478
+ });
479
+ }
480
+ // ── Rooms / Conferences ─────────────────────────────────────────────
481
+ /**
482
+ * Join a SignalWire room.
483
+ * @param name - The room name to join.
484
+ * @returns This instance for chaining.
485
+ */
486
+ joinRoom(name) {
487
+ return this.executeSwml({
488
+ version: '1.0.0',
489
+ sections: { main: [{ join_room: { name } }] },
490
+ });
491
+ }
492
+ /**
493
+ * Send a SIP REFER to transfer the call.
494
+ * @param toUri - The SIP URI to refer the call to.
495
+ * @returns This instance for chaining.
496
+ */
497
+ sipRefer(toUri) {
498
+ return this.executeSwml({
499
+ version: '1.0.0',
500
+ sections: { main: [{ sip_refer: { to_uri: toUri } }] },
501
+ });
502
+ }
503
+ /**
504
+ * Join a conference by name with optional configuration.
505
+ * @param name - The conference name to join.
506
+ * @param opts - Optional conference settings such as mute, recording, and callbacks.
507
+ * @returns This instance for chaining.
508
+ */
509
+ joinConference(name, opts) {
510
+ const hasNonDefaults = opts && (opts.muted || (opts.beep && opts.beep !== 'true') ||
511
+ opts.startOnEnter === false || opts.endOnExit ||
512
+ opts.waitUrl || (opts.maxParticipants && opts.maxParticipants !== 250) ||
513
+ (opts.record && opts.record !== 'do-not-record') || opts.region ||
514
+ (opts.trim && opts.trim !== 'trim-silence') || opts.coach ||
515
+ opts.statusCallbackEvent || opts.statusCallback ||
516
+ (opts.statusCallbackMethod && opts.statusCallbackMethod !== 'POST') ||
517
+ opts.recordingStatusCallback ||
518
+ (opts.recordingStatusCallbackMethod && opts.recordingStatusCallbackMethod !== 'POST') ||
519
+ (opts.recordingStatusCallbackEvent && opts.recordingStatusCallbackEvent !== 'completed') ||
520
+ opts.result !== undefined);
521
+ let joinParams;
522
+ if (!hasNonDefaults) {
523
+ joinParams = name;
524
+ }
525
+ else {
526
+ const p = { name };
527
+ if (opts.muted)
528
+ p['muted'] = opts.muted;
529
+ if (opts.beep && opts.beep !== 'true')
530
+ p['beep'] = opts.beep;
531
+ if (opts.startOnEnter === false)
532
+ p['start_on_enter'] = false;
533
+ if (opts.endOnExit)
534
+ p['end_on_exit'] = opts.endOnExit;
535
+ if (opts.waitUrl)
536
+ p['wait_url'] = opts.waitUrl;
537
+ if (opts.maxParticipants && opts.maxParticipants !== 250)
538
+ p['max_participants'] = opts.maxParticipants;
539
+ if (opts.record && opts.record !== 'do-not-record')
540
+ p['record'] = opts.record;
541
+ if (opts.region)
542
+ p['region'] = opts.region;
543
+ if (opts.trim && opts.trim !== 'trim-silence')
544
+ p['trim'] = opts.trim;
545
+ if (opts.coach)
546
+ p['coach'] = opts.coach;
547
+ if (opts.statusCallbackEvent)
548
+ p['status_callback_event'] = opts.statusCallbackEvent;
549
+ if (opts.statusCallback)
550
+ p['status_callback'] = opts.statusCallback;
551
+ if (opts.statusCallbackMethod && opts.statusCallbackMethod !== 'POST')
552
+ p['status_callback_method'] = opts.statusCallbackMethod;
553
+ if (opts.recordingStatusCallback)
554
+ p['recording_status_callback'] = opts.recordingStatusCallback;
555
+ if (opts.recordingStatusCallbackMethod && opts.recordingStatusCallbackMethod !== 'POST')
556
+ p['recording_status_callback_method'] = opts.recordingStatusCallbackMethod;
557
+ if (opts.recordingStatusCallbackEvent && opts.recordingStatusCallbackEvent !== 'completed')
558
+ p['recording_status_callback_event'] = opts.recordingStatusCallbackEvent;
559
+ if (opts.result !== undefined)
560
+ p['result'] = opts.result;
561
+ joinParams = p;
562
+ }
563
+ return this.executeSwml({
564
+ version: '1.0.0',
565
+ sections: { main: [{ join_conference: joinParams }] },
566
+ });
567
+ }
568
+ // ── RPC ─────────────────────────────────────────────────────────────
569
+ /**
570
+ * Execute a SignalWire RPC method via SWML.
571
+ * @param opts - RPC parameters including method name and optional call/node IDs.
572
+ * @returns This instance for chaining.
573
+ */
574
+ executeRpc(opts) {
575
+ const rpcParams = { method: opts.method };
576
+ if (opts.callId)
577
+ rpcParams['call_id'] = opts.callId;
578
+ if (opts.nodeId)
579
+ rpcParams['node_id'] = opts.nodeId;
580
+ if (opts.params)
581
+ rpcParams['params'] = opts.params;
582
+ return this.executeSwml({
583
+ version: '1.0.0',
584
+ sections: { main: [{ execute_rpc: rpcParams }] },
585
+ });
586
+ }
587
+ /**
588
+ * Dial a number via RPC, optionally specifying device type.
589
+ * @param toNumber - The destination phone number.
590
+ * @param fromNumber - The caller ID number.
591
+ * @param destSwml - The SWML destination for the dialed call.
592
+ * @param deviceType - The device type (defaults to "phone").
593
+ * @returns This instance for chaining.
594
+ */
595
+ rpcDial(toNumber, fromNumber, destSwml, deviceType = 'phone') {
596
+ return this.executeRpc({
597
+ method: 'dial',
598
+ params: {
599
+ devices: {
600
+ type: deviceType,
601
+ params: { to_number: toNumber, from_number: fromNumber },
602
+ },
603
+ dest_swml: destSwml,
604
+ },
605
+ });
606
+ }
607
+ /**
608
+ * Send an AI message to another call via RPC.
609
+ * @param callId - The target call ID.
610
+ * @param messageText - The message text to inject.
611
+ * @param role - The message role (defaults to "system").
612
+ * @returns This instance for chaining.
613
+ */
614
+ rpcAiMessage(callId, messageText, role = 'system') {
615
+ return this.executeRpc({
616
+ method: 'ai_message',
617
+ callId,
618
+ params: { role, message_text: messageText },
619
+ });
620
+ }
621
+ /**
622
+ * Unhold a call that was previously placed on hold via RPC.
623
+ * @param callId - The target call ID to unhold.
624
+ * @returns This instance for chaining.
625
+ */
626
+ rpcAiUnhold(callId) {
627
+ return this.executeRpc({
628
+ method: 'ai_unhold',
629
+ callId,
630
+ params: {},
631
+ });
632
+ }
633
+ // ── Payment ─────────────────────────────────────────────────────────
634
+ /**
635
+ * Initiate a payment collection flow on the call.
636
+ * @param opts - Payment configuration including connector URL, method, and prompt options.
637
+ * @returns This instance for chaining.
638
+ */
639
+ pay(opts) {
640
+ const payParams = {
641
+ payment_connector_url: opts.paymentConnectorUrl,
642
+ input: opts.inputMethod ?? 'dtmf',
643
+ payment_method: opts.paymentMethod ?? 'credit-card',
644
+ timeout: String(opts.timeout ?? 5),
645
+ max_attempts: String(opts.maxAttempts ?? 1),
646
+ security_code: String(opts.securityCode ?? true),
647
+ min_postal_code_length: String(opts.minPostalCodeLength ?? 0),
648
+ token_type: opts.tokenType ?? 'reusable',
649
+ currency: opts.currency ?? 'usd',
650
+ language: opts.language ?? 'en-US',
651
+ voice: opts.voice ?? 'woman',
652
+ valid_card_types: opts.validCardTypes ?? 'visa mastercard amex',
653
+ };
654
+ const postalCode = opts.postalCode ?? true;
655
+ payParams['postal_code'] = typeof postalCode === 'boolean' ? String(postalCode) : postalCode;
656
+ if (opts.statusUrl)
657
+ payParams['status_url'] = opts.statusUrl;
658
+ if (opts.chargeAmount)
659
+ payParams['charge_amount'] = opts.chargeAmount;
660
+ if (opts.description)
661
+ payParams['description'] = opts.description;
662
+ if (opts.parameters)
663
+ payParams['parameters'] = opts.parameters;
664
+ if (opts.prompts)
665
+ payParams['prompts'] = opts.prompts;
666
+ const aiResponse = opts.aiResponse ??
667
+ 'The payment status is ${pay_result}, do not mention anything else about collecting payment if successful.';
668
+ return this.executeSwml({
669
+ version: '1.0.0',
670
+ sections: {
671
+ main: [
672
+ { set: { ai_response: aiResponse } },
673
+ { pay: payParams },
674
+ ],
675
+ },
676
+ });
677
+ }
678
+ // ── Static payment helpers ──────────────────────────────────────────
679
+ /**
680
+ * Create a payment prompt configuration object.
681
+ * @param forSituation - The situation this prompt applies to.
682
+ * @param actions - Actions to perform for this prompt.
683
+ * @param cardType - Optional card type filter.
684
+ * @param errorType - Optional error type this prompt handles.
685
+ * @returns A new PaymentPrompt object.
686
+ */
687
+ static createPaymentPrompt(forSituation, actions, cardType, errorType) {
688
+ const prompt = { for: forSituation, actions };
689
+ if (cardType)
690
+ prompt.card_type = cardType;
691
+ if (errorType)
692
+ prompt.error_type = errorType;
693
+ return prompt;
694
+ }
695
+ /**
696
+ * Create a payment action for use within a payment prompt.
697
+ * @param actionType - The action type (e.g., "say", "play").
698
+ * @param phrase - The phrase or URL for this action.
699
+ * @returns A new PaymentAction object.
700
+ */
701
+ static createPaymentAction(actionType, phrase) {
702
+ return { type: actionType, phrase };
703
+ }
704
+ /**
705
+ * Create a custom payment parameter for the payment connector.
706
+ * @param name - The parameter name.
707
+ * @param value - The parameter value.
708
+ * @returns A new PaymentParameter object.
709
+ */
710
+ static createPaymentParameter(name, value) {
711
+ return { name, value };
712
+ }
713
+ // ── Serialization ───────────────────────────────────────────────────
714
+ /**
715
+ * Serialize this result to a plain object for the SWAIG response.
716
+ * @returns A dictionary with response, action, and post_process fields; falls back to "Action completed." if empty.
717
+ */
718
+ toDict() {
719
+ const result = {};
720
+ if (this.response) {
721
+ result['response'] = this.response;
722
+ }
723
+ if (this.action.length > 0) {
724
+ result['action'] = this.action;
725
+ }
726
+ if (this.postProcess && this.action.length > 0) {
727
+ result['post_process'] = true;
728
+ }
729
+ if (Object.keys(result).length === 0) {
730
+ result['response'] = 'Action completed.';
731
+ }
732
+ return result;
733
+ }
734
+ }
735
+ //# sourceMappingURL=SwaigFunctionResult.js.map