@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,717 @@
1
+ /**
2
+ * SWMLService - Lightweight HTTP service for non-AI SWML documents.
3
+ *
4
+ * Unlike AgentBase (which always produces an AI block), SWMLService generates
5
+ * pure SWML call-flow documents: IVR menus, voicemail, call recording, etc.
6
+ * Uses SwmlBuilder for verb methods and Hono for HTTP serving.
7
+ */
8
+
9
+ import { Hono } from 'hono';
10
+ import { cors } from 'hono/cors';
11
+ import { basicAuth } from 'hono/basic-auth';
12
+ import { randomBytes } from 'node:crypto';
13
+ import { SwmlBuilder } from './SwmlBuilder.js';
14
+ import { SchemaUtils } from './SchemaUtils.js';
15
+ import { SslConfig } from './SslConfig.js';
16
+ import { ConfigLoader } from './ConfigLoader.js';
17
+ import { getLogger, Logger } from './Logger.js';
18
+ import type { Server } from 'node:http';
19
+
20
+ // ── Verb handler interfaces ────────────────────────────────────────────
21
+
22
+ /**
23
+ * Interface for custom SWML verb handlers.
24
+ * Mirrors Python SDK's `SWMLVerbHandler` abstract base class.
25
+ */
26
+ export interface SWMLVerbHandler {
27
+ /** Return the verb name this handler manages. */
28
+ getVerbName(): string;
29
+ /** Validate a verb configuration. Returns [isValid, errorMessages]. */
30
+ validateConfig(config: Record<string, unknown>): [boolean, string[]];
31
+ /** Build a verb configuration from keyword arguments. */
32
+ buildConfig(kwargs: Record<string, unknown>): Record<string, unknown>;
33
+ }
34
+
35
+ /**
36
+ * Registry for custom SWML verb handlers.
37
+ * Mirrors Python SDK's `VerbHandlerRegistry`.
38
+ */
39
+ export class VerbHandlerRegistry {
40
+ private handlers = new Map<string, SWMLVerbHandler>();
41
+
42
+ /** Register a custom verb handler. */
43
+ registerHandler(handler: SWMLVerbHandler): void {
44
+ this.handlers.set(handler.getVerbName(), handler);
45
+ }
46
+
47
+ /** Get the handler for a specific verb, or undefined if none registered. */
48
+ getHandler(verbName: string): SWMLVerbHandler | undefined {
49
+ return this.handlers.get(verbName);
50
+ }
51
+
52
+ /** Check whether a handler exists for the given verb. */
53
+ hasHandler(verbName: string): boolean {
54
+ return this.handlers.has(verbName);
55
+ }
56
+ }
57
+
58
+ // ── Security config ────────────────────────────────────────────────────
59
+
60
+ /**
61
+ * Unified security configuration.
62
+ * Mirrors Python SDK's `SecurityConfig` — reads from env vars and optional config file.
63
+ */
64
+ export class SecurityConfig {
65
+ /** Whether SSL is enabled. */
66
+ sslEnabled: boolean;
67
+ /** Filesystem path to the PEM certificate. */
68
+ sslCertPath: string | null;
69
+ /** Filesystem path to the PEM private key. */
70
+ sslKeyPath: string | null;
71
+ /** Domain name for SSL. */
72
+ domain: string | null;
73
+ /** Basic auth username from config, or null. */
74
+ basicAuthUser: string | null;
75
+ /** Basic auth password from config, or null. */
76
+ basicAuthPassword: string | null;
77
+
78
+ private sslConfig: SslConfig;
79
+
80
+ constructor(opts?: { configFile?: string; serviceName?: string }) {
81
+ // Load SSL config from env vars / options
82
+ this.sslConfig = new SslConfig();
83
+ this.sslEnabled = this.sslConfig.enabled;
84
+ this.sslCertPath = this.sslConfig.certPath;
85
+ this.sslKeyPath = this.sslConfig.keyPath;
86
+ this.domain = this.sslConfig.domain;
87
+
88
+ // Auth defaults from env vars
89
+ this.basicAuthUser = process.env['SWML_BASIC_AUTH_USER'] ?? null;
90
+ this.basicAuthPassword = process.env['SWML_BASIC_AUTH_PASSWORD'] ?? null;
91
+
92
+ // Load from config file if available
93
+ if (opts?.configFile) {
94
+ this.loadFromConfigFile(opts.configFile);
95
+ }
96
+ }
97
+
98
+ private loadFromConfigFile(filePath: string): void {
99
+ try {
100
+ const loader = new ConfigLoader(filePath);
101
+ const ssl = loader.get('security.ssl') as Record<string, unknown> | undefined;
102
+ if (ssl) {
103
+ if (ssl['enabled'] !== undefined) this.sslEnabled = !!ssl['enabled'];
104
+ if (typeof ssl['certPath'] === 'string') this.sslCertPath = ssl['certPath'];
105
+ if (typeof ssl['keyPath'] === 'string') this.sslKeyPath = ssl['keyPath'];
106
+ if (typeof ssl['domain'] === 'string') this.domain = ssl['domain'];
107
+ }
108
+ const auth = loader.get('security.basicAuth') as Record<string, unknown> | undefined;
109
+ if (auth) {
110
+ if (typeof auth['user'] === 'string') this.basicAuthUser = auth['user'];
111
+ if (typeof auth['password'] === 'string') this.basicAuthPassword = auth['password'];
112
+ }
113
+ } catch {
114
+ // Config file load failures are non-fatal
115
+ }
116
+ }
117
+
118
+ /** Get basic auth credentials from security config, or null if not configured. */
119
+ getBasicAuth(): [string, string] | null {
120
+ if (this.basicAuthUser && this.basicAuthPassword) {
121
+ return [this.basicAuthUser, this.basicAuthPassword];
122
+ }
123
+ return null;
124
+ }
125
+
126
+ /** Validate that SSL cert and key files are present when SSL is enabled. */
127
+ validateSslConfig(): [boolean, string | null] {
128
+ if (!this.sslEnabled) return [true, null];
129
+ if (!this.sslCertPath) return [false, 'SSL cert path not configured'];
130
+ if (!this.sslKeyPath) return [false, 'SSL key path not configured'];
131
+ return this.sslConfig.isConfigured() ? [true, null] : [false, 'SSL cert or key file not found'];
132
+ }
133
+ }
134
+
135
+ // ── Callback type ──────────────────────────────────────────────────────
136
+
137
+ /** Callback invoked per-request to dynamically build SWML. */
138
+ export type OnRequestCallback = (
139
+ queryParams: Record<string, string>,
140
+ bodyParams: Record<string, unknown>,
141
+ headers: Record<string, string>,
142
+ ) => SwmlBuilder | Promise<SwmlBuilder>;
143
+
144
+ // RoutingCallback is owned by AgentBase.ts; SWMLService uses a structurally
145
+ // compatible local alias to avoid an import cycle and stay independent.
146
+ type RoutingCallback = (
147
+ requestBody: Record<string, unknown>,
148
+ ) => string | null | undefined | Promise<string | null | undefined>;
149
+
150
+ // ── Options ────────────────────────────────────────────────────────────
151
+
152
+ /** Configuration options for SWMLService. */
153
+ export interface SWMLServiceOptions {
154
+ /**
155
+ * Service display name.
156
+ * Required to match Python SDK where `name` is a positional required parameter.
157
+ */
158
+ name: string;
159
+ /** HTTP route path (default '/'). */
160
+ route?: string;
161
+ /** Host to bind the web server to (default '0.0.0.0'). */
162
+ host?: string;
163
+ /** Port to bind the web server to (default PORT env var or 3000). */
164
+ port?: number;
165
+ /** Basic auth credentials as [username, password]. */
166
+ basicAuth?: [string, string];
167
+ /** Path to a JSON Schema file for verb validation. */
168
+ schemaPath?: string;
169
+ /** Path to a security configuration file. */
170
+ configFile?: string;
171
+ /** Enable schema validation (default true). Can also be disabled via SWML_SKIP_SCHEMA_VALIDATION=true. */
172
+ schemaValidation?: boolean;
173
+ }
174
+
175
+ // ── SWMLService class ──────────────────────────────────────────────────
176
+
177
+ /** HTTP service that serves non-AI SWML documents built from verb methods. */
178
+ export class SWMLService {
179
+ /** Service display name. */
180
+ readonly name: string;
181
+ /** HTTP route path. */
182
+ readonly route: string;
183
+ /** Host the server binds to. */
184
+ readonly host: string;
185
+ /** Port the server binds to. */
186
+ readonly port: number;
187
+
188
+ /** Structured logger, exposed for subclass access. Mirrors Python's public `self.log`. */
189
+ readonly log: Logger;
190
+
191
+ /** Unified security configuration. Mirrors Python's `self.security`. */
192
+ readonly security: SecurityConfig;
193
+ /** Whether SSL is enabled. Mirrors Python's `self.ssl_enabled`. */
194
+ readonly sslEnabled: boolean;
195
+ /** Domain name for SSL. Mirrors Python's `self.domain`. */
196
+ readonly domain: string | undefined;
197
+ /** Path to SSL certificate. Mirrors Python's `self.ssl_cert_path`. */
198
+ readonly sslCertPath: string | undefined;
199
+ /** Path to SSL private key. Mirrors Python's `self.ssl_key_path`. */
200
+ readonly sslKeyPath: string | undefined;
201
+
202
+ /** Schema validation utilities. Mirrors Python's `self.schema_utils`. */
203
+ readonly schemaUtils: SchemaUtils;
204
+ /** Custom verb handler registry. Mirrors Python's `self.verb_registry`. */
205
+ readonly verbRegistry: VerbHandlerRegistry;
206
+
207
+ private swmlBuilder: SwmlBuilder;
208
+ private _app: Hono;
209
+ private _server: Server | null = null;
210
+ private onRequestCallback?: OnRequestCallback;
211
+ private authCredentials?: [string, string];
212
+ private authSource: 'provided' | 'environment' | 'auto-generated' = 'auto-generated';
213
+ private _proxyUrlBase: string | null = process.env['SWML_PROXY_URL_BASE'] ?? null;
214
+ private _proxyUrlBaseFromEnv = !!process.env['SWML_PROXY_URL_BASE'];
215
+ private _routingCallbacks = new Map<string, RoutingCallback>();
216
+
217
+ constructor(opts: SWMLServiceOptions);
218
+ /** @deprecated Prefer passing an options object with a required `name`. The no-arg form defaults name to 'swml-service'. */
219
+ constructor(opts?: Partial<SWMLServiceOptions>);
220
+ constructor(opts?: Partial<SWMLServiceOptions>) {
221
+ this.name = opts?.name ?? 'swml-service';
222
+ this.route = opts?.route ?? '/';
223
+ this.host = opts?.host ?? '0.0.0.0';
224
+ this.port = opts?.port ?? parseInt(process.env['PORT'] ?? '3000', 10);
225
+
226
+ // Logger — public to match Python's `self.log`
227
+ this.log = getLogger('SWMLService');
228
+
229
+ // Security configuration
230
+ this.security = new SecurityConfig({
231
+ configFile: opts?.configFile,
232
+ serviceName: this.name,
233
+ });
234
+ this.sslEnabled = this.security.sslEnabled;
235
+ this.domain = this.security.domain ?? undefined;
236
+ this.sslCertPath = this.security.sslCertPath ?? undefined;
237
+ this.sslKeyPath = this.security.sslKeyPath ?? undefined;
238
+
239
+ // Schema utils — pass through schemaPath so callers can supply a custom schema file.
240
+ // Mirrors Python's SchemaUtils(schema_path, schema_validation=...) call in SWMLService.__init__.
241
+ const skipValidation = opts?.schemaValidation === false || process.env['SWML_SKIP_SCHEMA_VALIDATION'] === 'true';
242
+ this.schemaUtils = new SchemaUtils({
243
+ skipValidation,
244
+ ...(opts?.schemaPath !== undefined ? { schemaPath: opts.schemaPath } : {}),
245
+ });
246
+
247
+ // Verb handler registry
248
+ this.verbRegistry = new VerbHandlerRegistry();
249
+
250
+ // Auth resolution: provided > env > security config > generated
251
+ // Track whether auth was explicitly provided (enforced on HTTP) vs auto-generated (available but not enforced)
252
+ let enforceAuth = false;
253
+ if (opts?.basicAuth) {
254
+ this.authCredentials = opts.basicAuth;
255
+ this.authSource = 'provided';
256
+ enforceAuth = true;
257
+ } else {
258
+ const envUser = process.env['SWML_BASIC_AUTH_USER'];
259
+ const envPass = process.env['SWML_BASIC_AUTH_PASSWORD'];
260
+ if (envUser && envPass) {
261
+ this.authCredentials = [envUser, envPass];
262
+ this.authSource = 'environment';
263
+ enforceAuth = true;
264
+ } else {
265
+ const fromConfig = this.security.getBasicAuth();
266
+ if (fromConfig) {
267
+ this.authCredentials = fromConfig;
268
+ this.authSource = 'environment';
269
+ enforceAuth = true;
270
+ } else {
271
+ // Auto-generate credentials like AgentBase does
272
+ const username = this.name.replace(/[^a-zA-Z0-9_-]/g, '_');
273
+ this.authCredentials = [username, randomBytes(16).toString('hex')];
274
+ this.authSource = 'auto-generated';
275
+ // Not enforced on HTTP — available via getBasicAuthCredentials()
276
+ }
277
+ }
278
+ }
279
+
280
+ this.swmlBuilder = new SwmlBuilder();
281
+ this._app = new Hono();
282
+
283
+ // Security headers
284
+ this._app.use('*', async (c, next) => {
285
+ await next();
286
+ c.res.headers.set('X-Content-Type-Options', 'nosniff');
287
+ c.res.headers.set('X-Frame-Options', 'DENY');
288
+ c.res.headers.set('X-XSS-Protection', '1; mode=block');
289
+ c.res.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');
290
+ c.res.headers.set('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");
291
+ c.res.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
292
+ });
293
+
294
+ // CORS — credentials only when origin is explicitly configured (wildcard + credentials violates spec)
295
+ const corsOrigins = process.env['SWML_CORS_ORIGINS'];
296
+ const corsOrigin = corsOrigins ? corsOrigins.split(',').map((o: string) => o.trim()) : '*';
297
+ const corsCredentials = corsOrigin !== '*';
298
+ this._app.use('*', cors({ origin: corsOrigin, credentials: corsCredentials }));
299
+
300
+ // Basic auth — only enforced when explicitly provided or from env, not auto-generated
301
+ if (enforceAuth && this.authCredentials) {
302
+ const [user, pass] = this.authCredentials;
303
+ this._app.use('*', basicAuth({ username: user, password: pass }));
304
+ }
305
+
306
+ // Health endpoints
307
+ this._app.get('/health', (c) => c.json({ status: 'ok' }));
308
+ this._app.get('/ready', (c) => c.json({ status: 'ready' }));
309
+
310
+ // Main SWML endpoint — serves on both GET and POST
311
+ const handler = async (c: any) => {
312
+ let doc: Record<string, unknown>;
313
+
314
+ // Always parse request params so onRequest() hook and onRequestCallback
315
+ // can both receive them (mirrors Python's _handle_request param extraction).
316
+ const url = new URL(c.req.url);
317
+ const queryParams: Record<string, string> = {};
318
+ url.searchParams.forEach((v, k) => { queryParams[k] = v; });
319
+
320
+ let bodyParams: Record<string, unknown> = {};
321
+ if (c.req.method === 'POST') {
322
+ try {
323
+ bodyParams = await c.req.json();
324
+ } catch {
325
+ // empty body is fine
326
+ }
327
+ }
328
+
329
+ const headers: Record<string, string> = {};
330
+ c.req.raw.headers.forEach((v: string, k: string) => { headers[k] = v; });
331
+
332
+ // Protected override hook (mirrors Python's on_request subclass pattern).
333
+ // Try onRequest() first; if it returns a SwmlBuilder use that document.
334
+ const hookResult = this.onRequest(queryParams, bodyParams, headers);
335
+ if (hookResult !== null) {
336
+ doc = hookResult.getDocument();
337
+ } else if (this.onRequestCallback) {
338
+ const builder = await this.onRequestCallback(queryParams, bodyParams, headers);
339
+ doc = builder.getDocument();
340
+ } else {
341
+ doc = this.swmlBuilder.getDocument();
342
+ }
343
+
344
+ return c.json(doc);
345
+ };
346
+
347
+ const routePath = this.route === '/' ? '/' : this.route;
348
+ this._app.get(routePath, handler);
349
+ this._app.post(routePath, handler);
350
+
351
+ // Register routing callback endpoints dynamically in getApp/run
352
+ }
353
+
354
+ // ── Properties (getters) ─────────────────────────────────────────────
355
+
356
+ /**
357
+ * Check if full JSON Schema validation is enabled.
358
+ * Mirrors Python's `@property full_validation_enabled`.
359
+ * @returns True if schema-based verb validation is active.
360
+ */
361
+ get fullValidationEnabled(): boolean {
362
+ // SchemaUtils in TS doesn't expose a direct 'full_validation_available' flag,
363
+ // but if the schema was loaded and validation is not skipped, it's available.
364
+ // We check by attempting to see if schema has verbs loaded.
365
+ try {
366
+ return this.schemaUtils.getVerbNames().length > 0;
367
+ } catch {
368
+ return false;
369
+ }
370
+ }
371
+
372
+ // ── SwmlBuilder delegation ────────────────────────────────────────
373
+
374
+ /**
375
+ * Get the underlying SwmlBuilder for direct manipulation.
376
+ * @returns The SwmlBuilder instance.
377
+ */
378
+ getBuilder(): SwmlBuilder {
379
+ return this.swmlBuilder;
380
+ }
381
+
382
+ /**
383
+ * Add a verb to the SWML document.
384
+ * @param name - Verb name (e.g., 'answer', 'play', 'hangup').
385
+ * @param config - Verb configuration.
386
+ * @returns This service for chaining.
387
+ */
388
+ addVerb(name: string, config: unknown): this {
389
+ this.swmlBuilder.addVerb(name, config);
390
+ return this;
391
+ }
392
+
393
+ /**
394
+ * Add a new named section to the SWML document.
395
+ * Mirrors Python's `add_section()`.
396
+ * @param sectionName - Name of the section to create.
397
+ * @returns This service for chaining.
398
+ */
399
+ addSection(sectionName: string): this {
400
+ const doc = this.swmlBuilder.getDocument() as { sections: Record<string, unknown[]> };
401
+ if (!(sectionName in doc.sections)) {
402
+ doc.sections[sectionName] = [];
403
+ }
404
+ return this;
405
+ }
406
+
407
+ /**
408
+ * Add a verb to a specific named section.
409
+ * Mirrors Python's `add_verb_to_section()`.
410
+ * @param sectionName - Target section name (auto-created if missing).
411
+ * @param verbName - Verb name.
412
+ * @param config - Verb configuration.
413
+ * @returns This service for chaining.
414
+ */
415
+ addVerbToSection(sectionName: string, verbName: string, config: unknown): this {
416
+ this.swmlBuilder.addVerbToSection(sectionName, verbName, config);
417
+ return this;
418
+ }
419
+
420
+ /**
421
+ * Reset the SWML document to an empty state.
422
+ * Mirrors Python's `reset_document()`.
423
+ * @returns This service for chaining.
424
+ */
425
+ resetDocument(): this {
426
+ this.swmlBuilder.reset();
427
+ return this;
428
+ }
429
+
430
+ /**
431
+ * Render the SWML document as a JSON object.
432
+ * @returns The SWML document.
433
+ */
434
+ renderSwml(): Record<string, unknown> {
435
+ return this.swmlBuilder.getDocument();
436
+ }
437
+
438
+ /**
439
+ * Get the SWML document as a dictionary.
440
+ * Alias for `renderSwml()` that matches Python's `get_document()` name.
441
+ * @returns The SWML document.
442
+ */
443
+ getDocument(): Record<string, unknown> {
444
+ return this.swmlBuilder.getDocument();
445
+ }
446
+
447
+ /**
448
+ * Render the SWML document as a JSON string.
449
+ * Mirrors Python's `render_document()`.
450
+ * @returns JSON-encoded SWML document.
451
+ */
452
+ renderDocument(): string {
453
+ return this.swmlBuilder.renderDocument();
454
+ }
455
+
456
+ // ── Verb handler registration ────────────────────────────────────────
457
+
458
+ /**
459
+ * Register a custom verb handler.
460
+ * Mirrors Python's `register_verb_handler()`.
461
+ * @param handler - The verb handler to register.
462
+ */
463
+ registerVerbHandler(handler: SWMLVerbHandler): void {
464
+ this.verbRegistry.registerHandler(handler);
465
+ }
466
+
467
+ // ── Routing callbacks ────────────────────────────────────────────────
468
+
469
+ /**
470
+ * Register a routing callback at a given path.
471
+ * When a POST request arrives at `path`, the callback is invoked with the
472
+ * parsed request body. If it returns a string, the response is a 307 redirect
473
+ * to that route; if it returns null, normal SWML serving continues.
474
+ * Mirrors Python's `register_routing_callback()`.
475
+ *
476
+ * @param callbackFn - Callback receiving the request body and returning a route or null.
477
+ * @param path - HTTP path for the callback (default '/sip').
478
+ */
479
+ registerRoutingCallback(
480
+ callbackFn: RoutingCallback,
481
+ path: string = '/sip',
482
+ ): void {
483
+ // Normalize: ensure leading /, strip trailing /
484
+ let normalized = path.replace(/\/+$/, '');
485
+ if (!normalized.startsWith('/')) {
486
+ normalized = `/${normalized}`;
487
+ }
488
+ this.log.info(`Registering routing callback at ${normalized}`);
489
+ this._routingCallbacks.set(normalized, callbackFn);
490
+
491
+ // Install an endpoint on the Hono app for this callback path
492
+ const routeHandler = async (c: any) => {
493
+ let body: Record<string, unknown> = {};
494
+ if (c.req.method === 'POST') {
495
+ try {
496
+ body = await c.req.json();
497
+ } catch {
498
+ // empty body
499
+ }
500
+ }
501
+
502
+ const route = callbackFn(body);
503
+ if (route !== null) {
504
+ return c.redirect(route, 307);
505
+ }
506
+
507
+ // No redirect — serve normal SWML
508
+ const doc = this.swmlBuilder.getDocument();
509
+ return c.json(doc);
510
+ };
511
+
512
+ this._app.get(normalized, routeHandler);
513
+ this._app.post(normalized, routeHandler);
514
+ }
515
+
516
+ // ── Static utilities ─────────────────────────────────────────────────
517
+
518
+ /**
519
+ * Extract the SIP username from a request body's call.to field.
520
+ * Mirrors Python's `@staticmethod extract_sip_username()`.
521
+ * @param requestBody - The parsed request body containing call information.
522
+ * @returns The extracted SIP username, or null if not found.
523
+ */
524
+ static extractSipUsername(requestBody: Record<string, unknown>): string | null {
525
+ try {
526
+ const call = requestBody?.['call'] as Record<string, unknown> | undefined;
527
+ const toField = call?.['to'] as string | undefined;
528
+ if (!toField) return null;
529
+
530
+ // Handle SIP URIs like "sip:username@domain" or "sips:username@domain"
531
+ if (toField.startsWith('sip:') || toField.startsWith('sips:')) {
532
+ let uri = toField.replace(/^sips?:/, '');
533
+ const atIdx = uri.indexOf('@');
534
+ if (atIdx > 0) return uri.substring(0, atIdx);
535
+ return uri;
536
+ }
537
+ // Handle TEL URIs like "tel:+1234567890"
538
+ if (toField.startsWith('tel:')) {
539
+ return toField.substring(4);
540
+ }
541
+ // Otherwise return the whole 'to' field
542
+ return toField;
543
+ } catch {
544
+ return null;
545
+ }
546
+ }
547
+
548
+ // ── Dynamic request callback ──────────────────────────────────────
549
+
550
+ /**
551
+ * Protected override hook called on every inbound SWML request.
552
+ * Mirrors Python SDK's `on_request(request_data, callback_path)` subclass
553
+ * override pattern. Subclasses return a `SwmlBuilder` to use for this
554
+ * request, or `null` to fall through to `setOnRequestCallback` or the
555
+ * static builder.
556
+ *
557
+ * Default implementation returns `null` (no-op), preserving existing
558
+ * behaviour for classes that do not override.
559
+ *
560
+ * @param queryParams - URL query parameters from the request.
561
+ * @param bodyParams - Parsed POST body (empty object for GET requests).
562
+ * @param headers - HTTP request headers.
563
+ * @param callbackPath - The callback sub-path being handled, if any.
564
+ * @returns A `SwmlBuilder` whose document is sent as the response, or
565
+ * `null` to delegate to the next handler in the chain.
566
+ */
567
+ protected onRequest(
568
+ _queryParams: Record<string, string>,
569
+ _bodyParams: Record<string, unknown>,
570
+ _headers: Record<string, string>,
571
+ _callbackPath?: string,
572
+ ): SwmlBuilder | null {
573
+ return null;
574
+ }
575
+
576
+ /**
577
+ * Set a callback invoked per-request to dynamically build SWML.
578
+ * When set, the static SwmlBuilder is ignored and the callback's
579
+ * returned SwmlBuilder is used instead.
580
+ * @param cb - Callback receiving query params, body params, and headers.
581
+ * @returns This service for chaining.
582
+ */
583
+ setOnRequestCallback(cb: OnRequestCallback): this {
584
+ this.onRequestCallback = cb;
585
+ return this;
586
+ }
587
+
588
+ // ── Auth ──────────────────────────────────────────────────────────
589
+
590
+ /**
591
+ * Get the basic-auth credentials used by this service.
592
+ * Mirrors Python's `get_basic_auth_credentials()`.
593
+ * @param includeSource - When true, a third element indicating the credential source is appended.
594
+ * @returns A tuple of [username, password] or [username, password, source].
595
+ */
596
+ getBasicAuthCredentials(includeSource?: false): [string, string];
597
+ getBasicAuthCredentials(includeSource: true): [string, string, 'provided' | 'environment' | 'auto-generated'];
598
+ getBasicAuthCredentials(includeSource?: boolean): [string, string] | [string, string, 'provided' | 'environment' | 'auto-generated'] {
599
+ const creds = this.authCredentials ?? ['', ''];
600
+ if (includeSource) return [...creds, this.authSource];
601
+ return creds;
602
+ }
603
+
604
+ // ── Proxy ─────────────────────────────────────────────────────────
605
+
606
+ /**
607
+ * Manually set the proxy base URL used for webhook URL generation.
608
+ * Mirrors Python's `manual_set_proxy_url()`.
609
+ * @param url - The external-facing base URL (trailing slashes are stripped).
610
+ * @returns This service for chaining.
611
+ */
612
+ manualSetProxyUrl(url: string): this {
613
+ if (url) {
614
+ this._proxyUrlBase = url.replace(/\/+$/, '');
615
+ this._proxyUrlBaseFromEnv = false;
616
+ this.log.info(`Proxy URL manually set to ${this._proxyUrlBase}`);
617
+ }
618
+ return this;
619
+ }
620
+
621
+ // ── HTTP ──────────────────────────────────────────────────────────
622
+
623
+ /**
624
+ * Get the Hono application for mounting or testing.
625
+ * This is the TypeScript equivalent of Python's `as_router()`, which returns
626
+ * a FastAPI `APIRouter`. Both expose the underlying app/router so callers can
627
+ * mount it into a larger framework. Use `asRouter()` when porting Python code
628
+ * that calls `as_router()` directly.
629
+ * @returns The configured Hono app.
630
+ */
631
+ getApp(): Hono {
632
+ return this._app;
633
+ }
634
+
635
+ /**
636
+ * Alias for `getApp()`. Provided for cross-SDK consistency with Python's
637
+ * `as_router()` method — allows Python callers porting to TypeScript to use
638
+ * the familiar name without changes.
639
+ * @returns The configured Hono app.
640
+ */
641
+ asRouter(): Hono {
642
+ return this.getApp();
643
+ }
644
+
645
+ /**
646
+ * Start the HTTP server.
647
+ * Matches Python's `serve()` parameters including SSL options.
648
+ *
649
+ * @param host - Hostname (default: this.host or '0.0.0.0').
650
+ * @param port - Port (default: this.port or 3000).
651
+ * @param opts - Optional SSL/TLS configuration overrides.
652
+ */
653
+ async run(
654
+ host?: string,
655
+ port?: number,
656
+ opts?: {
657
+ sslCert?: string;
658
+ sslKey?: string;
659
+ sslEnabled?: boolean;
660
+ domain?: string;
661
+ },
662
+ ): Promise<void> {
663
+ if (process.env['SWAIG_CLI_MODE'] === 'true') return;
664
+
665
+ const h = host ?? this.host;
666
+ const p = port ?? this.port;
667
+
668
+ // Determine effective SSL state (param > instance > env)
669
+ const effectiveSslEnabled = opts?.sslEnabled ?? this.sslEnabled;
670
+ const effectiveSslCert = opts?.sslCert ?? this.sslCertPath;
671
+ const effectiveSslKey = opts?.sslKey ?? this.sslKeyPath;
672
+
673
+ if (effectiveSslEnabled && effectiveSslCert && effectiveSslKey) {
674
+ // HTTPS mode
675
+ const { readFileSync } = await import('node:fs');
676
+ const { createServer } = await import('node:https');
677
+ const { getRequestListener } = await import('@hono/node-server');
678
+
679
+ const serverOpts = {
680
+ cert: readFileSync(effectiveSslCert, 'utf-8'),
681
+ key: readFileSync(effectiveSslKey, 'utf-8'),
682
+ };
683
+
684
+ this.log.info(`${this.name} starting on https://${h}:${p}${this.route} (SSL enabled)`);
685
+ const listener = getRequestListener(this._app.fetch);
686
+ this._server = createServer(serverOpts, listener) as unknown as Server;
687
+ this._server.listen(p, h);
688
+ } else {
689
+ // HTTP mode
690
+ const { serve } = await import('@hono/node-server');
691
+ this.log.info(`${this.name} starting on http://${h}:${p}${this.route}`);
692
+ this._server = serve({ fetch: this._app.fetch, port: p, hostname: h }) as unknown as Server;
693
+ }
694
+ }
695
+
696
+ /**
697
+ * Start the HTTP server. Alias for `run()` provided for cross-SDK
698
+ * consistency with Python's `serve()` method — callers porting from
699
+ * Python can use this name without changes.
700
+ *
701
+ * All parameters are forwarded unchanged to `run()`.
702
+ */
703
+ async serve(...args: Parameters<SWMLService['run']>): Promise<void> {
704
+ return this.run(...args);
705
+ }
706
+
707
+ /**
708
+ * Stop the HTTP server.
709
+ * Mirrors Python's `stop()`.
710
+ */
711
+ stop(): void {
712
+ if (this._server) {
713
+ this._server.close();
714
+ this._server = null;
715
+ }
716
+ }
717
+ }