@signalwire/sdk 2.0.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 (325) hide show
  1. package/.github/workflows/publish.yml +27 -0
  2. package/.github/workflows/test.yml +17 -0
  3. package/CLAUDE.md +112 -0
  4. package/README.md +254 -0
  5. package/docs/MIGRATION-2.0.md +81 -0
  6. package/docs/agent-guide.md +869 -0
  7. package/docs/agent_guide.md +1026 -0
  8. package/docs/api-reference.md +2420 -0
  9. package/docs/api_reference.md +1301 -0
  10. package/docs/architecture.md +843 -0
  11. package/docs/cli-guide.md +579 -0
  12. package/docs/cli_guide.md +448 -0
  13. package/docs/cloud_functions_guide.md +474 -0
  14. package/docs/configuration.md +422 -0
  15. package/docs/contexts-guide.md +787 -0
  16. package/docs/contexts_guide.md +511 -0
  17. package/docs/datamap-guide.md +1141 -0
  18. package/docs/datamap_guide.md +595 -0
  19. package/docs/llm_parameters.md +239 -0
  20. package/docs/mcp_gateway_reference.md +648 -0
  21. package/docs/mcp_integration.md +108 -0
  22. package/docs/prefabs-guide.md +800 -0
  23. package/docs/sdk_features.md +477 -0
  24. package/docs/security.md +436 -0
  25. package/docs/serverless-guide.md +513 -0
  26. package/docs/skills-guide.md +857 -0
  27. package/docs/skills-system.md +301 -0
  28. package/docs/skills_parameter_schema.md +392 -0
  29. package/docs/skills_system.md +467 -0
  30. package/docs/swaig-reference.md +1627 -0
  31. package/docs/swaig_reference.md +910 -0
  32. package/docs/swml_service_guide.md +600 -0
  33. package/docs/third_party_skills.md +533 -0
  34. package/docs/web_service.md +677 -0
  35. package/examples/README.md +131 -0
  36. package/examples/advanced-datamap.ts +100 -0
  37. package/examples/advanced-dynamic-config.ts +70 -0
  38. package/examples/auto-vivified.ts +94 -0
  39. package/examples/call-flow.ts +63 -0
  40. package/examples/comprehensive-dynamic.ts +125 -0
  41. package/examples/contexts-steps.ts +65 -0
  42. package/examples/custom-path.ts +45 -0
  43. package/examples/datamap-tools.ts +55 -0
  44. package/examples/datasphere-multi-instance.ts +63 -0
  45. package/examples/datasphere-serverless-env.ts +68 -0
  46. package/examples/datasphere-webhook-env.ts +66 -0
  47. package/examples/datasphere.ts +37 -0
  48. package/examples/declarative.ts +100 -0
  49. package/examples/dynamic-config.ts +54 -0
  50. package/examples/dynamic-info-gatherer.ts +69 -0
  51. package/examples/dynamic-swml-service.ts +67 -0
  52. package/examples/gather-info.ts +71 -0
  53. package/examples/gather-per-question-functions-demo.ts +140 -0
  54. package/examples/joke-agent.ts +34 -0
  55. package/examples/kubernetes-agent.ts +45 -0
  56. package/examples/llm-params.ts +69 -0
  57. package/examples/mcp-agent.ts +84 -0
  58. package/examples/mcp-gateway.ts +35 -0
  59. package/examples/multi-agent.ts +73 -0
  60. package/examples/multi-endpoint.ts +79 -0
  61. package/examples/pom-prompt.ts +71 -0
  62. package/examples/prefab-concierge.ts +47 -0
  63. package/examples/prefab-faq.ts +54 -0
  64. package/examples/prefab-info-gatherer.ts +33 -0
  65. package/examples/prefab-receptionist.ts +36 -0
  66. package/examples/prefab-survey.ts +68 -0
  67. package/examples/record-call.ts +67 -0
  68. package/examples/relay-demo.ts +33 -0
  69. package/examples/room-and-sip.ts +94 -0
  70. package/examples/serverless-lambda.ts +35 -0
  71. package/examples/session-state.ts +83 -0
  72. package/examples/simple-agent.ts +36 -0
  73. package/examples/simple-static.ts +29 -0
  74. package/examples/skills-demo.ts +38 -0
  75. package/examples/step-function-inheritance-demo.ts +124 -0
  76. package/examples/swaig-features.ts +187 -0
  77. package/examples/swml-service-routing.ts +66 -0
  78. package/examples/swml-service.ts +38 -0
  79. package/examples/tap.ts +68 -0
  80. package/examples/verb-methods.ts +45 -0
  81. package/examples/web-search-multi-instance.ts +72 -0
  82. package/examples/web-search.ts +38 -0
  83. package/examples/wikipedia.ts +36 -0
  84. package/livewire/README.md +140 -0
  85. package/livewire/docs/migration-guide.md +228 -0
  86. package/livewire/examples/livewire-basic-agent.ts +74 -0
  87. package/livewire/examples/livewire-handoff.ts +197 -0
  88. package/livewire/examples/livewire-multi-tool.ts +117 -0
  89. package/package.json +38 -0
  90. package/relay/README.md +70 -0
  91. package/relay/RELAY_IMPLEMENTATION_GUIDE.md +1257 -0
  92. package/relay/docs/call-methods.md +474 -0
  93. package/relay/docs/client-reference.md +142 -0
  94. package/relay/docs/events.md +134 -0
  95. package/relay/docs/getting-started.md +134 -0
  96. package/relay/docs/guide.md +306 -0
  97. package/relay/docs/messaging.md +182 -0
  98. package/relay/examples/relay-inbound.ts +66 -0
  99. package/relay/examples/relay-messaging.ts +71 -0
  100. package/relay/examples/relay-outbound.ts +76 -0
  101. package/rest/README.md +95 -0
  102. package/rest/docs/calling.md +273 -0
  103. package/rest/docs/client-reference.md +107 -0
  104. package/rest/docs/compat.md +204 -0
  105. package/rest/docs/fabric.md +183 -0
  106. package/rest/docs/getting-started.md +110 -0
  107. package/rest/docs/guide.md +351 -0
  108. package/rest/docs/namespaces.md +285 -0
  109. package/rest/examples/rest-10dlc-registration.ts +161 -0
  110. package/rest/examples/rest-calling-ivr-and-ai.ts +102 -0
  111. package/rest/examples/rest-calling-play-and-record.ts +91 -0
  112. package/rest/examples/rest-client.ts +65 -0
  113. package/rest/examples/rest-compat-laml.ts +210 -0
  114. package/rest/examples/rest-datasphere-search.ts +82 -0
  115. package/rest/examples/rest-fabric-conferences-and-routing.ts +144 -0
  116. package/rest/examples/rest-fabric-subscribers-and-sip.ts +108 -0
  117. package/rest/examples/rest-fabric-swml-and-callflows.ts +99 -0
  118. package/rest/examples/rest-manage-resources.ts +65 -0
  119. package/rest/examples/rest-phone-number-management.ts +197 -0
  120. package/rest/examples/rest-queues-mfa-and-recordings.ts +143 -0
  121. package/rest/examples/rest-video-rooms.ts +186 -0
  122. package/src/AgentBase.ts +2489 -0
  123. package/src/AgentServer.ts +415 -0
  124. package/src/AuthHandler.ts +256 -0
  125. package/src/ConfigLoader.ts +447 -0
  126. package/src/ContextBuilder.ts +1150 -0
  127. package/src/DataMap.ts +449 -0
  128. package/src/FunctionResult.ts +866 -0
  129. package/src/Logger.ts +337 -0
  130. package/src/PomBuilder.ts +439 -0
  131. package/src/PromptManager.ts +133 -0
  132. package/src/SWMLHandler.ts +298 -0
  133. package/src/SWMLService.ts +717 -0
  134. package/src/SchemaUtils.ts +361 -0
  135. package/src/SecurityUtils.ts +153 -0
  136. package/src/ServerlessAdapter.ts +221 -0
  137. package/src/SessionManager.ts +311 -0
  138. package/src/SslConfig.ts +118 -0
  139. package/src/SwaigFunction.ts +276 -0
  140. package/src/SwmlBuilder.ts +258 -0
  141. package/src/SwmlVerbMethods.generated.ts +234 -0
  142. package/src/TypeInference.ts +181 -0
  143. package/src/WebService.ts +619 -0
  144. package/src/cli/agent-loader.ts +166 -0
  145. package/src/cli/mock-data.ts +111 -0
  146. package/src/cli/swaig-test.ts +452 -0
  147. package/src/generateVerbTypes.ts +322 -0
  148. package/src/index.ts +167 -0
  149. package/src/livewire/index.ts +950 -0
  150. package/src/prefabs/ConciergeAgent.ts +287 -0
  151. package/src/prefabs/FAQBotAgent.ts +384 -0
  152. package/src/prefabs/InfoGathererAgent.ts +339 -0
  153. package/src/prefabs/ReceptionistAgent.ts +366 -0
  154. package/src/prefabs/SurveyAgent.ts +646 -0
  155. package/src/prefabs/index.ts +27 -0
  156. package/src/relay/Action.ts +314 -0
  157. package/src/relay/Call.ts +854 -0
  158. package/src/relay/Deferred.ts +71 -0
  159. package/src/relay/Message.ts +148 -0
  160. package/src/relay/RelayClient.ts +1036 -0
  161. package/src/relay/RelayError.ts +14 -0
  162. package/src/relay/RelayEvent.ts +892 -0
  163. package/src/relay/constants.ts +132 -0
  164. package/src/relay/index.ts +123 -0
  165. package/src/relay/types.ts +149 -0
  166. package/src/rest/HttpClient.ts +103 -0
  167. package/src/rest/RestError.ts +31 -0
  168. package/src/rest/base/BaseResource.ts +19 -0
  169. package/src/rest/base/CrudResource.ts +51 -0
  170. package/src/rest/base/CrudWithAddresses.ts +26 -0
  171. package/src/rest/index.ts +200 -0
  172. package/src/rest/namespaces/addresses.ts +32 -0
  173. package/src/rest/namespaces/calling.ts +187 -0
  174. package/src/rest/namespaces/chat.ts +20 -0
  175. package/src/rest/namespaces/compat.ts +352 -0
  176. package/src/rest/namespaces/datasphere.ts +45 -0
  177. package/src/rest/namespaces/fabric.ts +222 -0
  178. package/src/rest/namespaces/imported-numbers.ts +20 -0
  179. package/src/rest/namespaces/logs.ts +84 -0
  180. package/src/rest/namespaces/lookup.ts +21 -0
  181. package/src/rest/namespaces/mfa.ts +30 -0
  182. package/src/rest/namespaces/number-groups.ts +38 -0
  183. package/src/rest/namespaces/phone-numbers.ts +44 -0
  184. package/src/rest/namespaces/project.ts +36 -0
  185. package/src/rest/namespaces/pubsub.ts +20 -0
  186. package/src/rest/namespaces/queues.ts +33 -0
  187. package/src/rest/namespaces/recordings.ts +28 -0
  188. package/src/rest/namespaces/registry.ts +101 -0
  189. package/src/rest/namespaces/short-codes.ts +28 -0
  190. package/src/rest/namespaces/sip-profile.ts +25 -0
  191. package/src/rest/namespaces/verified-callers.ts +27 -0
  192. package/src/rest/namespaces/video.ts +165 -0
  193. package/src/rest/pagination.ts +84 -0
  194. package/src/rest/types.ts +61 -0
  195. package/src/schema.json +12250 -0
  196. package/src/skills/SkillBase.ts +547 -0
  197. package/src/skills/SkillManager.ts +415 -0
  198. package/src/skills/SkillRegistry.ts +367 -0
  199. package/src/skills/builtin/api_ninjas_trivia.ts +280 -0
  200. package/src/skills/builtin/ask_claude.ts +241 -0
  201. package/src/skills/builtin/claude_skills.ts +978 -0
  202. package/src/skills/builtin/custom_skills.ts +312 -0
  203. package/src/skills/builtin/datasphere.ts +438 -0
  204. package/src/skills/builtin/datasphere_serverless.ts +339 -0
  205. package/src/skills/builtin/datetime.ts +130 -0
  206. package/src/skills/builtin/google_maps.ts +651 -0
  207. package/src/skills/builtin/index.ts +88 -0
  208. package/src/skills/builtin/info_gatherer.ts +405 -0
  209. package/src/skills/builtin/joke.ts +191 -0
  210. package/src/skills/builtin/math.ts +142 -0
  211. package/src/skills/builtin/mcp_gateway.ts +677 -0
  212. package/src/skills/builtin/native_vector_search.ts +901 -0
  213. package/src/skills/builtin/play_background_file.ts +358 -0
  214. package/src/skills/builtin/spider.ts +869 -0
  215. package/src/skills/builtin/swml_transfer.ts +635 -0
  216. package/src/skills/builtin/weather_api.ts +248 -0
  217. package/src/skills/builtin/web_search.ts +1074 -0
  218. package/src/skills/builtin/wikipedia_search.ts +299 -0
  219. package/src/skills/index.ts +12 -0
  220. package/src/types.ts +132 -0
  221. package/tests/AgentBase.test.ts +1093 -0
  222. package/tests/AgentServer.test.ts +126 -0
  223. package/tests/AuthHandler.test.ts +133 -0
  224. package/tests/ConfigLoader.test.ts +151 -0
  225. package/tests/ContextBuilder.test.ts +108 -0
  226. package/tests/DataMap.test.ts +367 -0
  227. package/tests/EphemeralSkillCopy.test.ts +107 -0
  228. package/tests/FunctionResult.test.ts +298 -0
  229. package/tests/GracefulShutdown.test.ts +46 -0
  230. package/tests/Logger.test.ts +420 -0
  231. package/tests/PomBuilder.test.ts +228 -0
  232. package/tests/ProxyDetection.test.ts +228 -0
  233. package/tests/SWMLService.test.ts +320 -0
  234. package/tests/SWMLVerbHandler.test.ts +523 -0
  235. package/tests/SchemaUtils.test.ts +106 -0
  236. package/tests/SchemaUtils.verb.test.ts +206 -0
  237. package/tests/SecurityUtils.test.ts +192 -0
  238. package/tests/ServerlessAdapter.test.ts +222 -0
  239. package/tests/SessionManager.test.ts +257 -0
  240. package/tests/SkillBaseFeatures.test.ts +130 -0
  241. package/tests/SkillMultiInstance.test.ts +102 -0
  242. package/tests/SkillParameterSchemas.test.ts +134 -0
  243. package/tests/SkillRegistrySchema.test.ts +84 -0
  244. package/tests/SslConfig.test.ts +97 -0
  245. package/tests/SwmlBuilder.test.ts +400 -0
  246. package/tests/TypeInference.test.ts +165 -0
  247. package/tests/VerbHandlerRegistry.test.ts +128 -0
  248. package/tests/cli/mock-data.test.ts +113 -0
  249. package/tests/cli/swaig-test.test.ts +108 -0
  250. package/tests/examples.test.ts +194 -0
  251. package/tests/fixtures/scrape-parity/README.md +53 -0
  252. package/tests/fixtures/scrape-parity/expected/01_simple_article.json +5 -0
  253. package/tests/fixtures/scrape-parity/expected/02_class_based_noise.json +5 -0
  254. package/tests/fixtures/scrape-parity/expected/03_nested_containers.json +5 -0
  255. package/tests/fixtures/scrape-parity/expected/04_bare_body.json +5 -0
  256. package/tests/fixtures/scrape-parity/expected/05_malformed.json +5 -0
  257. package/tests/fixtures/scrape-parity/expected/06_multi_class.json +5 -0
  258. package/tests/fixtures/scrape-parity/expected/07_anchor_pattern.json +5 -0
  259. package/tests/fixtures/scrape-parity/expected/08_inline_script.json +5 -0
  260. package/tests/fixtures/scrape-parity/expected/09_whitespace_nbsp.json +5 -0
  261. package/tests/fixtures/scrape-parity/expected/10_entity_unicode.json +5 -0
  262. package/tests/fixtures/scrape-parity/expected/11_cdata_comments.json +5 -0
  263. package/tests/fixtures/scrape-parity/expected/12_deep_nested_removals.json +5 -0
  264. package/tests/fixtures/scrape-parity/html/01_simple_article.html +18 -0
  265. package/tests/fixtures/scrape-parity/html/02_class_based_noise.html +18 -0
  266. package/tests/fixtures/scrape-parity/html/03_nested_containers.html +13 -0
  267. package/tests/fixtures/scrape-parity/html/04_bare_body.html +9 -0
  268. package/tests/fixtures/scrape-parity/html/05_malformed.html +11 -0
  269. package/tests/fixtures/scrape-parity/html/06_multi_class.html +18 -0
  270. package/tests/fixtures/scrape-parity/html/07_anchor_pattern.html +12 -0
  271. package/tests/fixtures/scrape-parity/html/08_inline_script.html +17 -0
  272. package/tests/fixtures/scrape-parity/html/09_whitespace_nbsp.html +21 -0
  273. package/tests/fixtures/scrape-parity/html/10_entity_unicode.html +10 -0
  274. package/tests/fixtures/scrape-parity/html/11_cdata_comments.html +13 -0
  275. package/tests/fixtures/scrape-parity/html/12_deep_nested_removals.html +24 -0
  276. package/tests/fixtures/scrape-parity/python_extract.py +109 -0
  277. package/tests/livewire/livewire.test.ts +780 -0
  278. package/tests/mcp.test.ts +221 -0
  279. package/tests/prefabs/prefabs.test.ts +1093 -0
  280. package/tests/relay/Action.test.ts +392 -0
  281. package/tests/relay/Call.test.ts +535 -0
  282. package/tests/relay/Deferred.test.ts +71 -0
  283. package/tests/relay/Message.test.ts +164 -0
  284. package/tests/relay/RelayClient.test.ts +779 -0
  285. package/tests/relay/RelayEvent.test.ts +463 -0
  286. package/tests/relay/helpers.ts +79 -0
  287. package/tests/rest/HttpClient.test.ts +274 -0
  288. package/tests/rest/RestError.test.ts +53 -0
  289. package/tests/rest/calling.test.ts +156 -0
  290. package/tests/rest/client.test.ts +197 -0
  291. package/tests/rest/compat.test.ts +335 -0
  292. package/tests/rest/datasphere.test.ts +71 -0
  293. package/tests/rest/fabric.test.ts +186 -0
  294. package/tests/rest/helpers.ts +95 -0
  295. package/tests/rest/logs.test.ts +68 -0
  296. package/tests/rest/pagination.test.ts +133 -0
  297. package/tests/rest/registry.test.ts +94 -0
  298. package/tests/rest/relay-rest.test.ts +290 -0
  299. package/tests/rest/video.test.ts +173 -0
  300. package/tests/setup.ts +6 -0
  301. package/tests/skills/SkillBase.test.ts +108 -0
  302. package/tests/skills/SkillManager.test.ts +268 -0
  303. package/tests/skills/SkillRegistry.test.ts +176 -0
  304. package/tests/skills/builtin.test.ts +1472 -0
  305. package/tests/skills/claude-skills.test.ts +54 -0
  306. package/tests/skills/custom-skills.test.ts +53 -0
  307. package/tests/skills/datasphere-serverless.test.ts +70 -0
  308. package/tests/skills/datasphere.test.ts +107 -0
  309. package/tests/skills/datetime.test.ts +101 -0
  310. package/tests/skills/google-maps.test.ts +78 -0
  311. package/tests/skills/info-gatherer.test.ts +411 -0
  312. package/tests/skills/joke.test.ts +81 -0
  313. package/tests/skills/math.test.ts +68 -0
  314. package/tests/skills/mcp-gateway.test.ts +101 -0
  315. package/tests/skills/play-background.test.ts +54 -0
  316. package/tests/skills/spider.test.ts +108 -0
  317. package/tests/skills/swml-transfer.test.ts +178 -0
  318. package/tests/skills/trivia.test.ts +54 -0
  319. package/tests/skills/vector-search.test.ts +135 -0
  320. package/tests/skills/weather-api.test.ts +77 -0
  321. package/tests/skills/web-search-parity.test.ts +59 -0
  322. package/tests/skills/web-search.test.ts +103 -0
  323. package/tests/skills/wikipedia.test.ts +63 -0
  324. package/tsconfig.json +18 -0
  325. package/vitest.config.ts +9 -0
@@ -0,0 +1,276 @@
1
+ /**
2
+ * SwaigFunction - Wraps a handler function with metadata for SWAIG registration.
3
+ */
4
+
5
+ import Ajv from 'ajv';
6
+ import { FunctionResult } from './FunctionResult.js';
7
+ import { getLogger } from './Logger.js';
8
+
9
+ const ajv = new Ajv({ allErrors: true });
10
+
11
+ const log = getLogger('SwaigFunction');
12
+
13
+ /**
14
+ * Handler function for a SWAIG tool invocation.
15
+ * @param args - Parsed arguments extracted by the AI from user speech.
16
+ * @param rawData - The full raw request payload from SignalWire.
17
+ * @returns A FunctionResult, a plain object with a response key, a string, or a Promise of any of these.
18
+ */
19
+ export type SwaigHandler = (
20
+ args: Record<string, unknown>,
21
+ rawData: Record<string, unknown>,
22
+ ) => FunctionResult | Record<string, unknown> | string | Promise<FunctionResult | Record<string, unknown> | string>;
23
+
24
+ /** Configuration options for creating a SwaigFunction. */
25
+ export interface SwaigFunctionOptions {
26
+ /** Unique name used to register and invoke this tool. */
27
+ name: string;
28
+ /** The handler function called when the tool is invoked. */
29
+ handler: SwaigHandler;
30
+ /** Human-readable description of what the tool does, shown to the AI. */
31
+ description: string;
32
+ /** JSON Schema properties describing the tool's parameters. */
33
+ parameters?: Record<string, unknown>;
34
+ /** Whether this tool requires session token authentication. */
35
+ secure?: boolean;
36
+ /** Language-keyed filler phrases spoken while the tool executes. */
37
+ fillers?: Record<string, string[]>;
38
+ /** Audio file URL to play while waiting for the tool to complete. */
39
+ waitFile?: string;
40
+ /** Number of times to loop the wait file. */
41
+ waitFileLoops?: number;
42
+ /** External webhook URL; makes this an externally-hosted tool. */
43
+ webhookUrl?: string;
44
+ /** List of required parameter names. */
45
+ required?: string[];
46
+ /**
47
+ * Additional fields to merge directly into the SWAIG function definition.
48
+ *
49
+ * **Python equivalent:** `**extra_swaig_fields` kwargs on the constructor.
50
+ * In Python these are passed as bare keyword arguments and merged directly
51
+ * into the output dict via `function_def.update(self.extra_swaig_fields)`.
52
+ * In TypeScript the same fields are collected under this single options key
53
+ * and merged identically in `toSwaig()` — the wire format is identical.
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * // Python: SWAIGFunction(..., meta_data_token="abc", web_hook_auth_user="u")
58
+ * new SwaigFunction({
59
+ * ...,
60
+ * extraFields: { meta_data_token: 'abc', web_hook_auth_user: 'u' },
61
+ * });
62
+ * ```
63
+ */
64
+ extraFields?: Record<string, unknown>;
65
+ /** Whether this tool uses a typed handler with named parameters. */
66
+ isTypedHandler?: boolean;
67
+ }
68
+
69
+ /**
70
+ * A SWAIG function — exactly the same concept as a "tool" in native
71
+ * OpenAI / Anthropic tool calling.
72
+ *
73
+ * Each SwaigFunction is rendered, on every LLM turn, into the OpenAI
74
+ * tool schema:
75
+ *
76
+ * ```json
77
+ * {
78
+ * "type": "function",
79
+ * "function": {
80
+ * "name": "<this.name>",
81
+ * "description": "<this.description>",
82
+ * "parameters": { "type": "object", "properties": { ... } }
83
+ * }
84
+ * }
85
+ * ```
86
+ *
87
+ * The `name`, `description`, and every per-parameter `description` inside
88
+ * `parameters` are **read by the model** and directly determine whether
89
+ * the model picks this tool when a matching user request comes in.
90
+ * They are prompt engineering, not developer comments.
91
+ */
92
+ export class SwaigFunction {
93
+ /** Unique name — read by the LLM; use snake_case verbs. */
94
+ name: string;
95
+ /** The handler function called when the tool is invoked. */
96
+ handler: SwaigHandler;
97
+ /**
98
+ * LLM-facing description. Tells the model WHEN to call this tool.
99
+ * A vague description is the #1 cause of "model has the tool but
100
+ * doesn't call it" failures.
101
+ */
102
+ description: string;
103
+ /**
104
+ * JSON Schema properties describing the tool's parameters. Each
105
+ * property's `description` field is ALSO LLM-facing — it tells the
106
+ * model HOW to extract that argument from the user's utterance.
107
+ */
108
+ parameters: Record<string, unknown>;
109
+ /** Whether this tool requires session token authentication. */
110
+ secure: boolean;
111
+ /** Language-keyed filler phrases spoken while the tool executes. */
112
+ fillers?: Record<string, string[]>;
113
+ /** Audio file URL to play while waiting for the tool to complete. */
114
+ waitFile?: string;
115
+ /** Number of times to loop the wait file. */
116
+ waitFileLoops?: number;
117
+ /** External webhook URL; set when the tool is externally hosted. */
118
+ webhookUrl?: string;
119
+ /** List of required parameter names. */
120
+ required: string[];
121
+ /** Additional fields included in the SWAIG definition output. */
122
+ extraFields: Record<string, unknown>;
123
+ /** Whether this tool uses a typed handler with named parameters. */
124
+ isTypedHandler: boolean;
125
+ /** Whether this tool is externally hosted (has a webhookUrl). */
126
+ isExternal: boolean;
127
+
128
+ /**
129
+ * Create a new SwaigFunction.
130
+ *
131
+ * @param opts - Configuration options for the SWAIG function.
132
+ * Use `opts.extraFields` to pass any additional SWAIG-only fields
133
+ * (e.g. `meta_data_token`, `web_hook_auth_user`, `web_hook_auth_password`).
134
+ * This mirrors the Python constructor's `**extra_swaig_fields` kwargs:
135
+ * both are merged directly into the serialized SWAIG definition, so the
136
+ * wire format is identical — only the call-site syntax differs.
137
+ */
138
+ constructor(opts: SwaigFunctionOptions) {
139
+ this.name = opts.name;
140
+ this.handler = opts.handler;
141
+ this.description = opts.description;
142
+ this.parameters = opts.parameters ?? {};
143
+ this.secure = opts.secure ?? false;
144
+ this.fillers = opts.fillers;
145
+ this.waitFile = opts.waitFile;
146
+ this.waitFileLoops = opts.waitFileLoops;
147
+ this.webhookUrl = opts.webhookUrl;
148
+ this.required = opts.required ?? [];
149
+ this.extraFields = opts.extraFields ?? {};
150
+ this.isTypedHandler = opts.isTypedHandler ?? false;
151
+ this.isExternal = opts.webhookUrl !== undefined;
152
+ }
153
+
154
+ private ensureParameterStructure(): Record<string, unknown> {
155
+ if (!this.parameters || Object.keys(this.parameters).length === 0) {
156
+ return { type: 'object', properties: {} };
157
+ }
158
+ if ('type' in this.parameters && 'properties' in this.parameters) {
159
+ return this.parameters;
160
+ }
161
+ const result: Record<string, unknown> = {
162
+ type: 'object',
163
+ properties: this.parameters,
164
+ };
165
+ if (this.required.length) result['required'] = this.required;
166
+ return result;
167
+ }
168
+
169
+ /**
170
+ * Validate arguments against the parameter JSON schema using full
171
+ * JSON Schema Draft-7 validation (via ajv).
172
+ *
173
+ * Mirrors Python's `validate_args` which tries `jsonschema_rs` (Rust-based
174
+ * Draft-7 validator) then falls back to `jsonschema` (pure Python Draft-7).
175
+ * All JSON Schema constraint keywords are honoured: `required`, `type`,
176
+ * `minLength`, `maxLength`, `pattern`, `format`, `minimum`, `maximum`,
177
+ * `enum`, `anyOf`, `oneOf`, `$ref`, nested object/array validation, etc.
178
+ *
179
+ * If the schema has no properties, validation is skipped and the args are
180
+ * considered valid — matching Python's early-return path.
181
+ *
182
+ * @param args - Arguments to validate.
183
+ * @returns A tuple of `[isValid, errors]`. When no validation is needed
184
+ * (empty schema), returns `[true, []]`.
185
+ */
186
+ validateArgs(args: Record<string, unknown>): [boolean, string[]] {
187
+ const schema = this.ensureParameterStructure();
188
+ const properties = schema['properties'] as Record<string, unknown> | undefined;
189
+ if (!properties || Object.keys(properties).length === 0) {
190
+ return [true, []];
191
+ }
192
+
193
+ const validate = ajv.compile(schema);
194
+ const valid = validate(args);
195
+ if (valid) {
196
+ return [true, []];
197
+ }
198
+ const errors = (validate.errors ?? []).map((e) => {
199
+ // Produce messages similar to Python's jsonschema:
200
+ // "instancePath message" or just "message" when path is empty.
201
+ const path = e.instancePath ? e.instancePath.replace(/^\//, '').replace(/\//g, '.') : '';
202
+ return path ? `'${path}' ${e.message}` : (e.message ?? String(e));
203
+ });
204
+ return [false, errors];
205
+ }
206
+
207
+ /**
208
+ * Invoke the handler with the given arguments and return a serialized result.
209
+ * @param args - Parsed arguments from the AI.
210
+ * @param rawData - The full raw request payload.
211
+ * @returns A serialized result dictionary suitable for the SWAIG response.
212
+ */
213
+ async execute(
214
+ args: Record<string, unknown>,
215
+ rawData?: Record<string, unknown>,
216
+ ): Promise<Record<string, unknown>> {
217
+ try {
218
+ const result = await this.handler(args, rawData ?? {});
219
+ if (result instanceof FunctionResult) {
220
+ return result.toDict();
221
+ }
222
+ if (typeof result === 'object' && result !== null && !('response' in result)) {
223
+ // Plain object without a "response" key — matches Python's behavior:
224
+ // `elif isinstance(result, dict): return FunctionResult("Function completed successfully").to_dict()`
225
+ // Python replaces such dicts entirely; do the same here.
226
+ return new FunctionResult('Function completed successfully').toDict();
227
+ }
228
+ if (typeof result === 'object' && result !== null) {
229
+ return result as Record<string, unknown>;
230
+ }
231
+ // Neither a FunctionResult nor a dict — warn and fall back to
232
+ // wrapping the stringified value. See Python's web_mixin /
233
+ // serverless_mixin / tool_mixin for the equivalent check.
234
+ log.warn(
235
+ `SWAIG function "${this.name}" returned a value of type "${typeof result}" ` +
236
+ `that is neither FunctionResult nor object; falling back to str(result). ` +
237
+ `The AI will see the stringified value as its tool response. Wrap your ` +
238
+ `return in new FunctionResult(...) or return an object with at least a ` +
239
+ `"response" key.`,
240
+ );
241
+ return new FunctionResult(String(result)).toDict();
242
+ } catch (err) {
243
+ log.error(`Error executing SWAIG function ${this.name}: ${err}`);
244
+ return new FunctionResult(
245
+ "Sorry, I couldn't complete that action. Please try again or contact support if the issue persists.",
246
+ ).toDict();
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Serialize this function to the SWAIG wire format for inclusion in SWML.
252
+ * @param baseUrl - The base URL of the agent server.
253
+ * @param token - Optional session token for secure functions.
254
+ * @param callId - Optional call ID for secure function URLs.
255
+ * @returns A SWAIG function definition object.
256
+ */
257
+ toSwaig(baseUrl: string, token?: string, callId?: string): Record<string, unknown> {
258
+ let url = `${baseUrl}/swaig`;
259
+ if (token && callId) {
260
+ url = `${url}?token=${token}&call_id=${callId}`;
261
+ }
262
+ const def: Record<string, unknown> = {
263
+ function: this.name,
264
+ description: this.description,
265
+ parameters: this.ensureParameterStructure(),
266
+ };
267
+ if (url) def['web_hook_url'] = url;
268
+ if (this.fillers && Object.keys(this.fillers).length > 0) {
269
+ def['fillers'] = this.fillers;
270
+ }
271
+ if (this.waitFile) def['wait_file'] = this.waitFile;
272
+ if (this.waitFileLoops !== undefined) def['wait_file_loops'] = this.waitFileLoops;
273
+ Object.assign(def, this.extraFields);
274
+ return def;
275
+ }
276
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * SwmlBuilder - Builds SWML (SignalWire Markup Language) documents.
3
+ *
4
+ * Produces `{ version: "1.0.0", sections: { main: [...verbs] } }`.
5
+ *
6
+ * Verb methods (`.answer()`, `.hangup()`, `.play()`, etc.) are auto-installed
7
+ * at construction from the bundled schema.json. All verb methods support
8
+ * fluent chaining and call `addVerb()` internally.
9
+ */
10
+
11
+ import { SchemaUtils } from './SchemaUtils.js';
12
+ import type { ValidationResult } from './SchemaUtils.js';
13
+
14
+ // Ensure module augmentation from generated file is active
15
+ import './SwmlVerbMethods.generated.js';
16
+
17
+ /** Options for constructing a SwmlBuilder. */
18
+ export interface SwmlBuilderOptions {
19
+ /** An initial SWML document to seed the builder with, enabling document injection.
20
+ * When provided, the builder uses this document instead of creating an empty one.
21
+ * This mirrors the Python SDK's pattern of injecting an SWMLService instance. */
22
+ initialDocument?: { version?: string; sections?: Record<string, unknown[]> };
23
+ /** When false, disables verb schema validation.
24
+ * Defaults to true unless `SWML_SKIP_SCHEMA_VALIDATION=true` is set in the environment. */
25
+ enableValidation?: boolean;
26
+ /** Optional path to a custom SWML schema JSON file. When set, the builder uses
27
+ * a per-instance SchemaUtils loaded from this path instead of the bundled schema.
28
+ * Mirrors Python's `schema_path` constructor parameter on `SWMLService`/`AgentBase`. */
29
+ schemaPath?: string;
30
+ }
31
+
32
+ /** Builds SWML documents composed of verb instructions organized into named sections. */
33
+ export class SwmlBuilder {
34
+ private _document: { version: string; sections: Record<string, unknown[]> };
35
+ private static _schemaUtils: SchemaUtils | null = null;
36
+ /** Per-instance SchemaUtils used when a custom `schemaPath` was supplied. */
37
+ private _instanceSchemaUtils: SchemaUtils | null = null;
38
+ private enableValidation: boolean;
39
+
40
+ /**
41
+ * Creates a new SwmlBuilder.
42
+ * @param opts - Optional configuration.
43
+ * - `initialDocument`: inject an existing document (mirrors Python SDK's `SWMLService` injection pattern).
44
+ * - `enableValidation`: explicit override for verb schema validation (falls back to env var).
45
+ * - `schemaPath`: load SWML schema from a custom JSON file instead of the bundled one.
46
+ */
47
+ constructor(opts?: SwmlBuilderOptions) {
48
+ if (opts?.initialDocument) {
49
+ this._document = {
50
+ version: opts.initialDocument.version ?? '1.0.0',
51
+ sections: opts.initialDocument.sections ?? { main: [] },
52
+ };
53
+ } else {
54
+ this._document = this.createEmpty();
55
+ }
56
+ if (opts?.enableValidation !== undefined) {
57
+ this.enableValidation = opts.enableValidation;
58
+ } else {
59
+ this.enableValidation = process.env['SWML_SKIP_SCHEMA_VALIDATION'] !== 'true';
60
+ }
61
+ if (opts?.schemaPath) {
62
+ this._instanceSchemaUtils = new SchemaUtils({ schemaPath: opts.schemaPath });
63
+ }
64
+ this._installVerbMethods();
65
+ }
66
+
67
+ /** Returns the SchemaUtils for this builder — per-instance if a custom
68
+ * `schemaPath` was supplied, otherwise the shared singleton. */
69
+ private getSchemaUtils(): SchemaUtils {
70
+ return this._instanceSchemaUtils ?? SwmlBuilder.getSchemaUtils();
71
+ }
72
+
73
+ /**
74
+ * Public read-only accessor for the underlying SWML document.
75
+ * Provides direct access to the document, equivalent to the Python SDK's
76
+ * `service` property on `SWMLBuilder`.
77
+ */
78
+ get document(): { version: string; sections: Record<string, unknown[]> } {
79
+ return this._document;
80
+ }
81
+
82
+ /**
83
+ * Enable or disable verb schema validation at runtime.
84
+ * Matches the Python `schema_validation` constructor parameter on AgentBase.
85
+ * @param enabled - True to enable validation, false to disable.
86
+ */
87
+ setValidation(enabled: boolean): void {
88
+ this.enableValidation = enabled;
89
+ }
90
+
91
+ private createEmpty() {
92
+ return { version: '1.0.0', sections: { main: [] as unknown[] } };
93
+ }
94
+
95
+ /**
96
+ * Get or create the shared SchemaUtils singleton.
97
+ * Exposed for use by the type generator and tests.
98
+ */
99
+ static getSchemaUtils(): SchemaUtils {
100
+ if (!SwmlBuilder._schemaUtils) {
101
+ SwmlBuilder._schemaUtils = new SchemaUtils();
102
+ }
103
+ return SwmlBuilder._schemaUtils;
104
+ }
105
+
106
+ /**
107
+ * Install verb methods on this instance for every verb defined in the schema.
108
+ * Uses a closure factory so each method captures the correct verb name.
109
+ * Mirrors Python SDK's `_create_verb_methods()`.
110
+ */
111
+ private _installVerbMethods(): void {
112
+ const schemaUtils = this.getSchemaUtils();
113
+ const verbNames = schemaUtils.getVerbNames();
114
+
115
+ for (const verbName of verbNames) {
116
+ // Skip if this instance already has the method (e.g. from prototype)
117
+ if (verbName in this) continue;
118
+
119
+ // Special handling for sleep — accepts number directly or config object
120
+ if (verbName === 'sleep') {
121
+ const self = this;
122
+ (this as Record<string, unknown>)['sleep'] = function sleep(
123
+ durationOrConfig: number | Record<string, unknown>,
124
+ ): SwmlBuilder {
125
+ if (typeof durationOrConfig === 'number') {
126
+ self.addVerb('sleep', durationOrConfig);
127
+ } else {
128
+ self.addVerb('sleep', durationOrConfig);
129
+ }
130
+ return self;
131
+ };
132
+ continue;
133
+ }
134
+
135
+ // Closure factory to capture verbName
136
+ const makeMethod = (name: string) =>
137
+ (config?: Record<string, unknown>): SwmlBuilder => {
138
+ this.addVerb(name, config ?? {});
139
+ return this;
140
+ };
141
+
142
+ (this as Record<string, unknown>)[verbName] = makeMethod(verbName);
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Resets the document to an empty SWML structure.
148
+ * @returns this for fluent chaining.
149
+ */
150
+ reset(): this {
151
+ this._document = this.createEmpty();
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Appends a verb to the main section.
157
+ * Validates the verb config against the schema when validation is enabled.
158
+ * @param verbName - The SWML verb name (e.g., "answer", "ai").
159
+ * @param config - The verb's configuration payload.
160
+ */
161
+ addVerb(verbName: string, config: unknown): void {
162
+ if (this.enableValidation) {
163
+ const schemaUtils = this.getSchemaUtils();
164
+ if (schemaUtils.hasVerb(verbName)) {
165
+ const result: ValidationResult = schemaUtils.validateVerb(verbName, config);
166
+ if (!result.valid) {
167
+ throw new Error(`SWML verb validation failed: ${result.errors.join('; ')}`);
168
+ }
169
+ }
170
+ }
171
+ this._document.sections['main'].push({ [verbName]: config });
172
+ }
173
+
174
+ /**
175
+ * Appends a verb to a named section, creating the section if it does not exist.
176
+ * @param sectionName - The target section name.
177
+ * @param verbName - The SWML verb name.
178
+ * @param config - The verb's configuration payload.
179
+ */
180
+ addVerbToSection(sectionName: string, verbName: string, config: unknown): void {
181
+ if (!this._document.sections[sectionName]) {
182
+ this._document.sections[sectionName] = [];
183
+ }
184
+ this._document.sections[sectionName].push({ [verbName]: config });
185
+ }
186
+
187
+ /**
188
+ * Add a 'play' verb with say: prefix for text-to-speech.
189
+ * Convenience wrapper matching Python SDK's `say()` method.
190
+ *
191
+ * @param text - Text to speak.
192
+ * @param opts - Optional TTS parameters (voice, language, gender, volume).
193
+ * @returns this for fluent chaining.
194
+ */
195
+ say(
196
+ text: string,
197
+ opts?: { voice?: string; language?: string; gender?: string; volume?: number },
198
+ ): this {
199
+ const config: Record<string, unknown> = { url: `say:${text}` };
200
+ if (opts?.voice !== undefined) config['say_voice'] = opts.voice;
201
+ if (opts?.language !== undefined) config['say_language'] = opts.language;
202
+ if (opts?.gender !== undefined) config['say_gender'] = opts.gender;
203
+ if (opts?.volume !== undefined) config['volume'] = opts.volume;
204
+ this.addVerb('play', config);
205
+ return this;
206
+ }
207
+
208
+ /**
209
+ * Creates a new empty named section in the document.
210
+ * If the section already exists, this is a no-op.
211
+ * Matches Python SDK's `add_section(section_name)`.
212
+ *
213
+ * @param sectionName - The name of the section to create.
214
+ * @returns this for fluent chaining.
215
+ */
216
+ addSection(sectionName: string): this {
217
+ if (!this._document.sections[sectionName]) {
218
+ this._document.sections[sectionName] = [];
219
+ }
220
+ return this;
221
+ }
222
+
223
+ /**
224
+ * Returns the raw SWML document object.
225
+ * @returns The document with version and sections.
226
+ */
227
+ getDocument(): Record<string, unknown> {
228
+ return this._document;
229
+ }
230
+
231
+ /**
232
+ * Alias for {@link getDocument}. Matches the Python SDK's `build()` method.
233
+ * Build and return the SWML document as a dictionary/object.
234
+ *
235
+ * @returns The document with version and sections.
236
+ */
237
+ build(): Record<string, unknown> {
238
+ return this.getDocument();
239
+ }
240
+
241
+ /**
242
+ * Serializes the SWML document to a JSON string.
243
+ * @returns The JSON-encoded SWML document.
244
+ */
245
+ renderDocument(): string {
246
+ return JSON.stringify(this._document);
247
+ }
248
+
249
+ /**
250
+ * Alias for {@link renderDocument}. Matches the Python SDK's `render()` method.
251
+ * Build and render the SWML document as a JSON string.
252
+ *
253
+ * @returns The JSON-encoded SWML document.
254
+ */
255
+ render(): string {
256
+ return this.renderDocument();
257
+ }
258
+ }