@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,1093 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { AgentBase } from '../src/AgentBase.js';
3
+ import { FunctionResult } from '../src/FunctionResult.js';
4
+ import { ContextBuilder } from '../src/ContextBuilder.js';
5
+ import { DataMap } from '../src/DataMap.js';
6
+ import { SkillBase, type SkillToolDefinition } from '../src/skills/SkillBase.js';
7
+
8
+ describe('AgentBase', () => {
9
+ function createAgent(opts?: Partial<Parameters<typeof AgentBase.prototype.setPromptText>[0]>) {
10
+ return new AgentBase({ name: 'test-agent', route: '/test', ...opts } as any);
11
+ }
12
+
13
+ it('renders basic SWML with prompt', () => {
14
+ const agent = createAgent();
15
+ agent.setPromptText('You are a helpful assistant');
16
+ const swml = JSON.parse(agent.renderSwml());
17
+ expect(swml.version).toBe('1.0.0');
18
+ const main = swml.sections.main;
19
+ // Should have answer + ai verbs
20
+ expect(main.length).toBe(2);
21
+ expect(main[0]).toHaveProperty('answer');
22
+ expect(main[1]).toHaveProperty('ai');
23
+ expect(main[1].ai.prompt.text).toBe('You are a helpful assistant');
24
+ });
25
+
26
+ it('renders SWML without auto-answer', () => {
27
+ const agent = new AgentBase({ name: 'test', route: '/test', autoAnswer: false });
28
+ agent.setPromptText('hello');
29
+ const swml = JSON.parse(agent.renderSwml());
30
+ const main = swml.sections.main;
31
+ // Should only have AI verb, no answer
32
+ expect(main.length).toBe(1);
33
+ expect(main[0]).toHaveProperty('ai');
34
+ });
35
+
36
+ it('renders SWML with recording enabled', () => {
37
+ const agent = new AgentBase({ name: 'test', route: '/test', recordCall: true });
38
+ agent.setPromptText('hello');
39
+ const swml = JSON.parse(agent.renderSwml());
40
+ const main = swml.sections.main;
41
+ // answer + record_call + ai
42
+ expect(main.length).toBe(3);
43
+ expect(main[1]).toHaveProperty('record_call');
44
+ expect(main[1].record_call.format).toBe('mp4');
45
+ });
46
+
47
+ it('includes tools in SWAIG', () => {
48
+ const agent = createAgent();
49
+ agent.setPromptText('hello');
50
+ agent.defineTool({
51
+ name: 'get_time',
52
+ description: 'Get the current time',
53
+ parameters: {},
54
+ handler: () => new FunctionResult('The time is 12:00'),
55
+ });
56
+ const swml = JSON.parse(agent.renderSwml());
57
+ const ai = swml.sections.main[1].ai;
58
+ expect(ai.SWAIG).toBeDefined();
59
+ expect(ai.SWAIG.functions.length).toBe(1);
60
+ expect(ai.SWAIG.functions[0].function).toBe('get_time');
61
+ expect(ai.SWAIG.defaults).toBeDefined();
62
+ expect(ai.SWAIG.defaults.web_hook_url).toContain('/swaig');
63
+ });
64
+
65
+ it('includes DataMap tools in SWAIG', () => {
66
+ const agent = createAgent();
67
+ agent.setPromptText('hello');
68
+ const dm = new DataMap('get_weather')
69
+ .purpose('Get weather')
70
+ .parameter('location', 'string', 'City', { required: true })
71
+ .webhook('GET', 'https://api.weather.com?q=${location}')
72
+ .output(new FunctionResult('Temp: ${response.temp}'));
73
+
74
+ agent.registerSwaigFunction(dm.toSwaigFunction());
75
+ const swml = JSON.parse(agent.renderSwml());
76
+ const fns = swml.sections.main[1].ai.SWAIG.functions;
77
+ expect(fns.length).toBe(1);
78
+ expect(fns[0].function).toBe('get_weather');
79
+ expect(fns[0].data_map).toBeDefined();
80
+ });
81
+
82
+ it('sets post prompt', () => {
83
+ const agent = createAgent();
84
+ agent.setPromptText('hello');
85
+ agent.setPostPrompt('Summarize the call');
86
+ const swml = JSON.parse(agent.renderSwml());
87
+ const ai = swml.sections.main[1].ai;
88
+ expect(ai.post_prompt.text).toBe('Summarize the call');
89
+ expect(ai.post_prompt_url).toBeDefined();
90
+ });
91
+
92
+ it('adds hints, languages, pronunciation', () => {
93
+ const agent = createAgent();
94
+ agent.setPromptText('hello');
95
+ agent.addHints(['Cabby', 'SignalWire']);
96
+ agent.addLanguage({ name: 'English', code: 'en-US', voice: 'rachel' });
97
+ agent.addPronunciation({ replace: 'SW', with: 'SignalWire' });
98
+ const swml = JSON.parse(agent.renderSwml());
99
+ const ai = swml.sections.main[1].ai;
100
+ expect(ai.hints).toEqual(['Cabby', 'SignalWire']);
101
+ expect(ai.languages.length).toBe(1);
102
+ expect(ai.pronounce.length).toBe(1);
103
+ });
104
+
105
+ it('sets params and global data', () => {
106
+ const agent = createAgent();
107
+ agent.setPromptText('hello');
108
+ agent.setParam('temperature', 0.5);
109
+ agent.setGlobalData({ name: 'John' });
110
+ const swml = JSON.parse(agent.renderSwml());
111
+ const ai = swml.sections.main[1].ai;
112
+ expect(ai.params.temperature).toBe(0.5);
113
+ expect(ai.global_data.name).toBe('John');
114
+ });
115
+
116
+ it('setPromptLlmParams merges into prompt', () => {
117
+ const agent = createAgent();
118
+ agent.setPromptText('hello');
119
+ agent.setPromptLlmParams({ temperature: 0.3, top_p: 0.9 });
120
+ const swml = JSON.parse(agent.renderSwml());
121
+ const prompt = swml.sections.main[1].ai.prompt;
122
+ expect(prompt.temperature).toBe(0.3);
123
+ expect(prompt.top_p).toBe(0.9);
124
+ expect(prompt.text).toBe('hello');
125
+ });
126
+
127
+ it('pre-answer, post-answer, post-ai verbs', () => {
128
+ const agent = createAgent();
129
+ agent.setPromptText('hello');
130
+ agent.addPreAnswerVerb('play', { urls: ['ring:us'], auto_answer: false });
131
+ agent.addPostAnswerVerb('play', { url: 'say:Welcome!' });
132
+ agent.addPostAiVerb('hangup', {});
133
+ const swml = JSON.parse(agent.renderSwml());
134
+ const main = swml.sections.main;
135
+ // pre-answer play + answer + post-answer play + ai + post-ai hangup
136
+ expect(main.length).toBe(5);
137
+ expect(main[0]).toHaveProperty('play');
138
+ expect(main[1]).toHaveProperty('answer');
139
+ expect(main[2]).toHaveProperty('play');
140
+ expect(main[3]).toHaveProperty('ai');
141
+ expect(main[4]).toHaveProperty('hangup');
142
+ });
143
+
144
+ it('native functions included in SWAIG', () => {
145
+ const agent = new AgentBase({ name: 'test', route: '/test', nativeFunctions: ['check_time'] });
146
+ agent.setPromptText('hello');
147
+ agent.defineTool({
148
+ name: 'fn',
149
+ description: 'd',
150
+ parameters: {},
151
+ handler: () => new FunctionResult('ok'),
152
+ });
153
+ const swml = JSON.parse(agent.renderSwml());
154
+ expect(swml.sections.main[1].ai.SWAIG.native_functions).toEqual(['check_time']);
155
+ });
156
+
157
+ it('function includes', () => {
158
+ const agent = createAgent();
159
+ agent.setPromptText('hello');
160
+ agent.addFunctionInclude('https://example.com/fns', ['fn1']);
161
+ agent.defineTool({
162
+ name: 'fn',
163
+ description: 'd',
164
+ parameters: {},
165
+ handler: () => new FunctionResult('ok'),
166
+ });
167
+ const swml = JSON.parse(agent.renderSwml());
168
+ expect(swml.sections.main[1].ai.SWAIG.includes).toHaveLength(1);
169
+ });
170
+
171
+ it('contexts system', () => {
172
+ const agent = createAgent();
173
+ agent.setPromptText('You are a quiz master');
174
+ const ctx = agent.defineContexts();
175
+ const def = ctx.addContext('default');
176
+ def.addStep('greeting', { task: 'Greet the user' })
177
+ .setStepCriteria('User has been greeted')
178
+ .setValidSteps(['quiz']);
179
+ def.addStep('quiz', { task: 'Ask a quiz question' });
180
+ const swml = JSON.parse(agent.renderSwml());
181
+ const ai = swml.sections.main[1].ai;
182
+ expect(ai.contexts).toBeDefined();
183
+ expect(ai.contexts.default.steps.length).toBe(2);
184
+ });
185
+
186
+ it('getFullUrl returns correct URL', () => {
187
+ const agent = new AgentBase({ name: 'test', route: '/myagent', port: 5000 });
188
+ const url = agent.getFullUrl();
189
+ expect(url).toContain('localhost:5000/myagent');
190
+ });
191
+
192
+ it('getFullUrl with auth', () => {
193
+ const agent = new AgentBase({ name: 'test', route: '/test', basicAuth: ['user', 'pass'] });
194
+ const url = agent.getFullUrl(true);
195
+ expect(url).toContain('user:pass@');
196
+ });
197
+
198
+ it('getBasicAuthCredentials', () => {
199
+ const agent = new AgentBase({ name: 'test', route: '/test', basicAuth: ['u', 'p'] });
200
+ expect(agent.getBasicAuthCredentials()).toEqual(['u', 'p']);
201
+ });
202
+
203
+ it('promptAddSection builds POM prompt', () => {
204
+ const agent = createAgent();
205
+ agent.promptAddSection('Role', { body: 'You are a helper' });
206
+ agent.promptAddSection('Rules', { bullets: ['Be nice'] });
207
+ const prompt = agent.getPrompt();
208
+ expect(prompt).toContain('Role');
209
+ expect(prompt).toContain('You are a helper');
210
+ expect(prompt).toContain('- Be nice');
211
+ });
212
+
213
+ it('renders multiple calls independently', () => {
214
+ const agent = createAgent();
215
+ agent.setPromptText('hello');
216
+ const swml1 = agent.renderSwml();
217
+ const swml2 = agent.renderSwml();
218
+ // Both should be valid JSON
219
+ expect(JSON.parse(swml1).version).toBe('1.0.0');
220
+ expect(JSON.parse(swml2).version).toBe('1.0.0');
221
+ });
222
+
223
+ // ── Auth source tracking ────────────────────────────────────────────
224
+
225
+ it('getBasicAuthCredentials returns source=provided when given explicitly', () => {
226
+ const agent = new AgentBase({ name: 'test', route: '/test', basicAuth: ['u', 'p'] });
227
+ const [user, pass, source] = agent.getBasicAuthCredentials(true);
228
+ expect(user).toBe('u');
229
+ expect(pass).toBe('p');
230
+ expect(source).toBe('provided');
231
+ });
232
+
233
+ it('getBasicAuthCredentials returns source=generated when auto-generated', () => {
234
+ const savedUser = process.env['SWML_BASIC_AUTH_USER'];
235
+ const savedPass = process.env['SWML_BASIC_AUTH_PASSWORD'];
236
+ delete process.env['SWML_BASIC_AUTH_USER'];
237
+ delete process.env['SWML_BASIC_AUTH_PASSWORD'];
238
+ try {
239
+ const agent = new AgentBase({ name: 'test', route: '/test' });
240
+ const [user, , source] = agent.getBasicAuthCredentials(true);
241
+ expect(user).toBe('test');
242
+ expect(source).toBe('auto-generated');
243
+ } finally {
244
+ if (savedUser) process.env['SWML_BASIC_AUTH_USER'] = savedUser;
245
+ if (savedPass) process.env['SWML_BASIC_AUTH_PASSWORD'] = savedPass;
246
+ }
247
+ });
248
+
249
+ it('getBasicAuthCredentials without source returns tuple of 2', () => {
250
+ const agent = new AgentBase({ name: 'test', route: '/test', basicAuth: ['u', 'p'] });
251
+ const result = agent.getBasicAuthCredentials();
252
+ expect(result).toHaveLength(2);
253
+ expect(result).toEqual(['u', 'p']);
254
+ });
255
+
256
+ // ── Security headers ───────────────────────────────────────────────
257
+
258
+ it('includes security headers in responses', async () => {
259
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
260
+ agent.setPromptText('hello');
261
+ const app = agent.getApp();
262
+ const res = await app.request('/health');
263
+ expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff');
264
+ expect(res.headers.get('X-Frame-Options')).toBe('DENY');
265
+ expect(res.headers.get('X-XSS-Protection')).toBe('1; mode=block');
266
+ expect(res.headers.get('Referrer-Policy')).toBe('strict-origin-when-cross-origin');
267
+ });
268
+
269
+ // ── CORS ──────────────────────────────────────────────────────────
270
+
271
+ it('responds to CORS preflight', async () => {
272
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
273
+ const app = agent.getApp();
274
+ const res = await app.request('/health', {
275
+ method: 'OPTIONS',
276
+ headers: {
277
+ 'Origin': 'https://example.com',
278
+ 'Access-Control-Request-Method': 'POST',
279
+ },
280
+ });
281
+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*');
282
+ });
283
+
284
+ // ── Debug events ──────────────────────────────────────────────────
285
+
286
+ it('enableDebugEvents injects debug_webhook_url in SWML', () => {
287
+ const agent = createAgent();
288
+ agent.setPromptText('hello');
289
+ agent.enableDebugEvents(2);
290
+ const swml = JSON.parse(agent.renderSwml());
291
+ const ai = swml.sections.main[1].ai;
292
+ expect(ai.debug_webhook_url).toBeDefined();
293
+ expect(ai.debug_webhook_url).toContain('/debug_events');
294
+ expect(ai.debug_webhook_level).toBe(2);
295
+ });
296
+
297
+ it('debug events endpoint responds to POST', async () => {
298
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
299
+ agent.enableDebugEvents();
300
+ const app = agent.getApp();
301
+ const res = await app.request('/debug_events', {
302
+ method: 'POST',
303
+ headers: {
304
+ 'Authorization': 'Basic ' + btoa('u:p'),
305
+ 'Content-Type': 'application/json',
306
+ },
307
+ body: JSON.stringify({ event: 'test' }),
308
+ });
309
+ expect(res.status).toBe(200);
310
+ const body = await res.json();
311
+ expect(body.ok).toBe(true);
312
+ });
313
+
314
+ it('no debug_webhook_url when debug events not enabled', () => {
315
+ const agent = createAgent();
316
+ agent.setPromptText('hello');
317
+ const swml = JSON.parse(agent.renderSwml());
318
+ const ai = swml.sections.main[1].ai;
319
+ expect(ai.debug_webhook_url).toBeUndefined();
320
+ expect(ai.debug_webhook_level).toBeUndefined();
321
+ });
322
+
323
+ // ── Tool introspection ──────────────────────────────────────────────
324
+
325
+ it('getRegisteredTools lists all tools', () => {
326
+ const agent = createAgent();
327
+ agent.defineTool({
328
+ name: 'fn1',
329
+ description: 'Function 1',
330
+ parameters: { x: { type: 'string' } },
331
+ handler: () => new FunctionResult('ok'),
332
+ });
333
+ agent.defineTool({
334
+ name: 'fn2',
335
+ description: 'Function 2',
336
+ parameters: {},
337
+ handler: () => new FunctionResult('ok'),
338
+ });
339
+ const tools = agent.getRegisteredTools();
340
+ expect(tools).toHaveLength(2);
341
+ expect(tools[0].name).toBe('fn1');
342
+ expect(tools[1].name).toBe('fn2');
343
+ });
344
+
345
+ it('getTool returns a SwaigFunction', () => {
346
+ const agent = createAgent();
347
+ agent.defineTool({
348
+ name: 'my_fn',
349
+ description: 'My function',
350
+ parameters: {},
351
+ handler: () => new FunctionResult('ok'),
352
+ });
353
+ const tool = agent.getTool('my_fn');
354
+ expect(tool).toBeDefined();
355
+ expect(tool!.name).toBe('my_fn');
356
+ });
357
+
358
+ it('getTool returns undefined for missing tool', () => {
359
+ const agent = createAgent();
360
+ expect(agent.getTool('nope')).toBeUndefined();
361
+ });
362
+
363
+ // ── Pass 1: Agent Enhancements ────────────────────────────────────
364
+
365
+ it('getName returns the agent name', () => {
366
+ const agent = new AgentBase({ name: 'my-agent', route: '/test' });
367
+ expect(agent.getName()).toBe('my-agent');
368
+ });
369
+
370
+ it('agentId defaults to random hex', () => {
371
+ const agent = createAgent();
372
+ expect(agent.agentId).toBeDefined();
373
+ expect(typeof agent.agentId).toBe('string');
374
+ expect(agent.agentId.length).toBe(16); // 8 bytes hex
375
+ });
376
+
377
+ it('agentId can be provided via options', () => {
378
+ const agent = new AgentBase({ name: 'test', route: '/test', agentId: 'custom-id-123' } as any);
379
+ expect(agent.agentId).toBe('custom-id-123');
380
+ });
381
+
382
+ it('clearPreAnswerVerbs removes pre-answer verbs', () => {
383
+ const agent = createAgent();
384
+ agent.setPromptText('hello');
385
+ agent.addPreAnswerVerb('play', { url: 'ring:us' });
386
+ agent.addPreAnswerVerb('play', { url: 'ring:uk' });
387
+ agent.clearPreAnswerVerbs();
388
+ const swml = JSON.parse(agent.renderSwml());
389
+ const main = swml.sections.main;
390
+ // Should only have answer + ai, no pre-answer verbs
391
+ expect(main.length).toBe(2);
392
+ expect(main[0]).toHaveProperty('answer');
393
+ });
394
+
395
+ it('clearPostAnswerVerbs removes post-answer verbs', () => {
396
+ const agent = createAgent();
397
+ agent.setPromptText('hello');
398
+ agent.addPostAnswerVerb('play', { url: 'say:Welcome' });
399
+ agent.clearPostAnswerVerbs();
400
+ const swml = JSON.parse(agent.renderSwml());
401
+ const main = swml.sections.main;
402
+ expect(main.length).toBe(2);
403
+ });
404
+
405
+ it('clearPostAiVerbs removes post-ai verbs', () => {
406
+ const agent = createAgent();
407
+ agent.setPromptText('hello');
408
+ agent.addPostAiVerb('hangup', {});
409
+ agent.clearPostAiVerbs();
410
+ const swml = JSON.parse(agent.renderSwml());
411
+ const main = swml.sections.main;
412
+ expect(main.length).toBe(2);
413
+ });
414
+
415
+ it('clear*Verbs methods return this for chaining', () => {
416
+ const agent = createAgent();
417
+ const result = agent.clearPreAnswerVerbs().clearPostAnswerVerbs().clearPostAiVerbs();
418
+ expect(result).toBe(agent);
419
+ });
420
+
421
+ it('suppressLogs option suppresses log output', async () => {
422
+ // We test that no error is thrown; the actual suppression is tested in Logger tests
423
+ const { suppressAllLogs: suppress } = await import('../src/Logger.js');
424
+ suppress(false); // reset
425
+ const agent = new AgentBase({ name: 'test', route: '/test', suppressLogs: true } as any);
426
+ expect(agent).toBeDefined();
427
+ suppress(false); // cleanup
428
+ });
429
+
430
+ // ── Security env vars ─────────────────────────────────────────────
431
+
432
+ it('request size limit returns 413 for oversized requests', async () => {
433
+ const saved = process.env['SWML_MAX_REQUEST_SIZE'];
434
+ process.env['SWML_MAX_REQUEST_SIZE'] = '50'; // 50 bytes
435
+ try {
436
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
437
+ agent.setPromptText('hello');
438
+ const app = agent.getApp();
439
+ const res = await app.request('/', {
440
+ method: 'POST',
441
+ headers: {
442
+ 'Authorization': 'Basic ' + btoa('u:p'),
443
+ 'Content-Type': 'application/json',
444
+ 'Content-Length': '100000',
445
+ },
446
+ body: JSON.stringify({ data: 'x'.repeat(100000) }),
447
+ });
448
+ expect(res.status).toBe(413);
449
+ } finally {
450
+ if (saved) process.env['SWML_MAX_REQUEST_SIZE'] = saved;
451
+ else delete process.env['SWML_MAX_REQUEST_SIZE'];
452
+ }
453
+ });
454
+
455
+ it('SWML_ALLOWED_HOSTS blocks disallowed hosts', async () => {
456
+ const saved = process.env['SWML_ALLOWED_HOSTS'];
457
+ process.env['SWML_ALLOWED_HOSTS'] = 'allowed.example.com, other.test';
458
+ try {
459
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
460
+ agent.setPromptText('hello');
461
+ const app = agent.getApp();
462
+
463
+ // Disallowed host
464
+ const res = await app.request('http://evil.example.com/', {
465
+ method: 'POST',
466
+ headers: {
467
+ 'Authorization': 'Basic ' + btoa('u:p'),
468
+ 'Content-Type': 'application/json',
469
+ 'Host': 'evil.example.com',
470
+ },
471
+ body: '{}',
472
+ });
473
+ expect(res.status).toBe(403);
474
+ const body = await res.json();
475
+ expect(body.error).toContain('host not allowed');
476
+ } finally {
477
+ if (saved) process.env['SWML_ALLOWED_HOSTS'] = saved;
478
+ else delete process.env['SWML_ALLOWED_HOSTS'];
479
+ }
480
+ });
481
+
482
+ it('SWML_ALLOWED_HOSTS allows matching hosts', async () => {
483
+ const saved = process.env['SWML_ALLOWED_HOSTS'];
484
+ process.env['SWML_ALLOWED_HOSTS'] = 'allowed.example.com, other.test';
485
+ try {
486
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
487
+ agent.setPromptText('hello');
488
+ const app = agent.getApp();
489
+
490
+ // Allowed host
491
+ const res = await app.request('http://allowed.example.com/', {
492
+ method: 'POST',
493
+ headers: {
494
+ 'Authorization': 'Basic ' + btoa('u:p'),
495
+ 'Content-Type': 'application/json',
496
+ 'Host': 'allowed.example.com',
497
+ },
498
+ body: '{}',
499
+ });
500
+ expect(res.status).toBe(200);
501
+ } finally {
502
+ if (saved) process.env['SWML_ALLOWED_HOSTS'] = saved;
503
+ else delete process.env['SWML_ALLOWED_HOSTS'];
504
+ }
505
+ });
506
+
507
+ it('SWML_RATE_LIMIT returns 429 when exceeded', async () => {
508
+ const saved = process.env['SWML_RATE_LIMIT'];
509
+ process.env['SWML_RATE_LIMIT'] = '2'; // 2 requests per minute
510
+ try {
511
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
512
+ agent.setPromptText('hello');
513
+ const app = agent.getApp();
514
+
515
+ const makeReq = () => app.request('/', {
516
+ method: 'POST',
517
+ headers: {
518
+ 'Authorization': 'Basic ' + btoa('u:p'),
519
+ 'Content-Type': 'application/json',
520
+ 'X-Forwarded-For': '1.2.3.4',
521
+ },
522
+ body: '{}',
523
+ });
524
+
525
+ // First two should succeed
526
+ const r1 = await makeReq();
527
+ expect(r1.status).toBe(200);
528
+ const r2 = await makeReq();
529
+ expect(r2.status).toBe(200);
530
+
531
+ // Third should be rate limited
532
+ const r3 = await makeReq();
533
+ expect(r3.status).toBe(429);
534
+ const body = await r3.json();
535
+ expect(body.error).toContain('Rate limit');
536
+ } finally {
537
+ if (saved) process.env['SWML_RATE_LIMIT'] = saved;
538
+ else delete process.env['SWML_RATE_LIMIT'];
539
+ }
540
+ });
541
+
542
+ // ── Pass 4: Tool lifecycle + defineTools + onFunctionCall ───────
543
+
544
+ it('defineTools is not called automatically — subclass calls it explicitly', () => {
545
+ let defineToolsCalled = false;
546
+ class MyAgent extends AgentBase {
547
+ constructor(opts: Parameters<typeof AgentBase.prototype.constructor>[0]) {
548
+ super(opts as any);
549
+ this.defineTools();
550
+ }
551
+ protected override defineTools(): void {
552
+ defineToolsCalled = true;
553
+ this.defineTool({
554
+ name: 'auto_tool',
555
+ description: 'Auto-registered tool',
556
+ parameters: {},
557
+ handler: () => new FunctionResult('auto'),
558
+ });
559
+ }
560
+ }
561
+ const agent = new MyAgent({ name: 'test', route: '/test' });
562
+ expect(defineToolsCalled).toBe(true);
563
+ expect(agent.getTool('auto_tool')).toBeDefined();
564
+ });
565
+
566
+ it('PROMPT_SECTIONS static property applies prompt sections', () => {
567
+ class PromptAgent extends AgentBase {
568
+ static PROMPT_SECTIONS = [
569
+ { title: 'Role', body: 'You are a test agent' },
570
+ { title: 'Rules', bullets: ['Be helpful', 'Be concise'] },
571
+ ];
572
+ }
573
+ const agent = new PromptAgent({ name: 'test', route: '/test' });
574
+ const prompt = agent.getPrompt();
575
+ expect(prompt).toContain('Role');
576
+ expect(prompt).toContain('You are a test agent');
577
+ expect(prompt).toContain('Be helpful');
578
+ });
579
+
580
+ it('onFunctionCall hook is invoked when SWAIG function called', async () => {
581
+ const calls: string[] = [];
582
+ class HookAgent extends AgentBase {
583
+ onFunctionCall(name: string, _args: Record<string, unknown>, _rawData: Record<string, unknown>): void {
584
+ calls.push(name);
585
+ }
586
+ }
587
+ const agent = new HookAgent({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
588
+ agent.defineTool({
589
+ name: 'test_fn',
590
+ description: 'Test',
591
+ parameters: {},
592
+ handler: () => new FunctionResult('ok'),
593
+ });
594
+ const app = agent.getApp();
595
+ const res = await app.request('/swaig', {
596
+ method: 'POST',
597
+ headers: {
598
+ 'Authorization': 'Basic ' + btoa('u:p'),
599
+ 'Content-Type': 'application/json',
600
+ },
601
+ body: JSON.stringify({ function: 'test_fn', argument: {} }),
602
+ });
603
+ expect(res.status).toBe(200);
604
+ expect(calls).toContain('test_fn');
605
+ });
606
+
607
+ it('validateBasicAuth hook default returns true', () => {
608
+ const agent = createAgent();
609
+ expect(agent.validateBasicAuth('any', 'pass')).toBe(true);
610
+ });
611
+
612
+ it('CORS origin defaults to *', async () => {
613
+ const saved = process.env['SWML_CORS_ORIGINS'];
614
+ delete process.env['SWML_CORS_ORIGINS'];
615
+ try {
616
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
617
+ const app = agent.getApp();
618
+ const res = await app.request('/health', {
619
+ method: 'OPTIONS',
620
+ headers: {
621
+ 'Origin': 'https://example.com',
622
+ 'Access-Control-Request-Method': 'POST',
623
+ },
624
+ });
625
+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*');
626
+ } finally {
627
+ if (saved) process.env['SWML_CORS_ORIGINS'] = saved;
628
+ }
629
+ });
630
+
631
+ // ── Pass 5: Skills integration ──────────────────────────────────
632
+
633
+ it('addSkill registers skill tools and prompt sections', async () => {
634
+ class TestSkill extends SkillBase {
635
+ static override SKILL_NAME = 'test_skill';
636
+ static override SKILL_DESCRIPTION = 'Test';
637
+ getTools(): SkillToolDefinition[] {
638
+ return [{
639
+ name: 'skill_tool',
640
+ description: 'Skill tool',
641
+ handler: () => new FunctionResult('skill result'),
642
+ }];
643
+ }
644
+ getPromptSections() { return [{ title: 'Skill Info', body: 'From test skill' }]; }
645
+ getHints() { return ['skill hint']; }
646
+ }
647
+
648
+ const agent = createAgent();
649
+ agent.setPromptText('base prompt');
650
+ await agent.addSkill(new TestSkill());
651
+
652
+ expect(agent.getTool('skill_tool')).toBeDefined();
653
+ expect(agent.hasSkill('test_skill')).toBe(true);
654
+ expect(agent.listSkills()).toHaveLength(1);
655
+ });
656
+
657
+ it('removeSkill removes a skill', async () => {
658
+ class RemoveSkill extends SkillBase {
659
+ static override SKILL_NAME = 'removable';
660
+ static override SKILL_DESCRIPTION = 'Test';
661
+ getTools(): SkillToolDefinition[] { return []; }
662
+ }
663
+
664
+ const agent = createAgent();
665
+ const skill = new RemoveSkill();
666
+ await agent.addSkill(skill);
667
+ expect(agent.hasSkill('removable')).toBe(true);
668
+ await agent.removeSkill(skill.instanceId);
669
+ expect(agent.hasSkill('removable')).toBe(false);
670
+ });
671
+
672
+ it('addSkill returns this for chaining', async () => {
673
+ class ChainSkill extends SkillBase {
674
+ static override SKILL_NAME = 'chain';
675
+ static override SKILL_DESCRIPTION = 'Test';
676
+ getTools(): SkillToolDefinition[] { return []; }
677
+ }
678
+
679
+ const agent = createAgent();
680
+ const result = await agent.addSkill(new ChainSkill());
681
+ expect(result).toBe(agent);
682
+ });
683
+
684
+ it('listSkills returns empty when no skills', () => {
685
+ const agent = createAgent();
686
+ expect(agent.listSkills()).toHaveLength(0);
687
+ });
688
+
689
+ it('hasSkill returns false when no skills', () => {
690
+ const agent = createAgent();
691
+ expect(agent.hasSkill('nope')).toBe(false);
692
+ });
693
+
694
+ // ── Security remediation tests ─────────────────────────────────────
695
+
696
+ it('setParams with __proto__ key does NOT pollute Object prototype', () => {
697
+ const agent = createAgent();
698
+ agent.setParams({ __proto__: { polluted: true }, temperature: 0.7 });
699
+ expect(({} as any).polluted).toBeUndefined();
700
+ // Normal key should still work
701
+ const swml = JSON.parse(agent.renderSwml());
702
+ // params are in AI config
703
+ const ai = swml.sections.main.find((v: any) => v.ai)?.ai;
704
+ expect(ai?.params?.temperature).toBe(0.7);
705
+ });
706
+
707
+ it('CORS wildcard sets credentials: false', async () => {
708
+ const saved = process.env['SWML_CORS_ORIGINS'];
709
+ delete process.env['SWML_CORS_ORIGINS'];
710
+ try {
711
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
712
+ const app = agent.getApp();
713
+ const res = await app.request('/health', {
714
+ method: 'GET',
715
+ headers: { 'Origin': 'https://example.com' },
716
+ });
717
+ // When origin is *, credentials should not be included
718
+ const credHeader = res.headers.get('Access-Control-Allow-Credentials');
719
+ expect(credHeader).toBeNull();
720
+ } finally {
721
+ if (saved) process.env['SWML_CORS_ORIGINS'] = saved;
722
+ }
723
+ });
724
+
725
+ it('invalid port throws', () => {
726
+ expect(() => new AgentBase({ name: 'test', route: '/', port: 0 })).toThrow('Invalid port');
727
+ expect(() => new AgentBase({ name: 'test', route: '/', port: 99999 })).toThrow('Invalid port');
728
+ expect(() => new AgentBase({ name: 'test', route: '/', port: NaN })).toThrow('Invalid port');
729
+ });
730
+
731
+ it('NaN content-length returns 413', async () => {
732
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
733
+ agent.setPromptText('hello');
734
+ const app = agent.getApp();
735
+ const res = await app.request('/', {
736
+ method: 'POST',
737
+ headers: {
738
+ 'Authorization': 'Basic ' + btoa('u:p'),
739
+ 'Content-Type': 'application/json',
740
+ 'Content-Length': 'not-a-number',
741
+ },
742
+ body: '{}',
743
+ });
744
+ expect(res.status).toBe(413);
745
+ });
746
+
747
+ it('SWAIG handler error returns friendly message without internal details', async () => {
748
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
749
+ agent.defineTool({
750
+ name: 'crash_fn',
751
+ description: 'Will crash',
752
+ parameters: {},
753
+ handler: () => { throw new Error('secret internal error details'); },
754
+ });
755
+ const app = agent.getApp();
756
+ const res = await app.request('/swaig', {
757
+ method: 'POST',
758
+ headers: {
759
+ 'Authorization': 'Basic ' + btoa('u:p'),
760
+ 'Content-Type': 'application/json',
761
+ },
762
+ body: JSON.stringify({ function: 'crash_fn', argument: {} }),
763
+ });
764
+ expect(res.status).toBe(200);
765
+ const body = await res.json();
766
+ // SwaigFunction.execute catches errors and returns a friendly message
767
+ expect(JSON.stringify(body)).not.toContain('secret internal error details');
768
+ expect(body.response).toContain('try again');
769
+ });
770
+
771
+ it('CSP and Permissions-Policy headers are present', async () => {
772
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
773
+ agent.setPromptText('hello');
774
+ const app = agent.getApp();
775
+ const res = await app.request('/health');
776
+ expect(res.headers.get('Content-Security-Policy')).toContain("default-src 'none'");
777
+ expect(res.headers.get('Permissions-Policy')).toContain('camera=()');
778
+ });
779
+
780
+ it('rejects function names longer than 128 chars', async () => {
781
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
782
+ agent.setPromptText('hello');
783
+ const app = agent.getApp();
784
+ const longName = 'x'.repeat(129);
785
+ const res = await app.request('/swaig', {
786
+ method: 'POST',
787
+ headers: {
788
+ 'Authorization': 'Basic ' + btoa('u:p'),
789
+ 'Content-Type': 'application/json',
790
+ },
791
+ body: JSON.stringify({ function: longName, argument: {} }),
792
+ });
793
+ expect(res.status).toBe(400);
794
+ const body = await res.json();
795
+ expect(body.error).toBe('Invalid function name');
796
+ });
797
+
798
+ it('function-not-found log does not expose available_functions', async () => {
799
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
800
+ agent.setPromptText('hello');
801
+ agent.defineTool({
802
+ name: 'real_tool',
803
+ description: 'A tool',
804
+ parameters: {},
805
+ handler: () => new FunctionResult('ok'),
806
+ });
807
+ const app = agent.getApp();
808
+ const res = await app.request('/swaig', {
809
+ method: 'POST',
810
+ headers: {
811
+ 'Authorization': 'Basic ' + btoa('u:p'),
812
+ 'Content-Type': 'application/json',
813
+ },
814
+ body: JSON.stringify({ function: 'nonexistent_fn', argument: {} }),
815
+ });
816
+ expect(res.status).toBe(404);
817
+ // The response should not leak the list of available functions
818
+ const text = await res.text();
819
+ expect(text).not.toContain('real_tool');
820
+ });
821
+
822
+ it('invalid token returns 200 with FunctionResult (not 403)', async () => {
823
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
824
+ agent.defineTool({
825
+ name: 'secure_fn',
826
+ description: 'Secure function',
827
+ parameters: {},
828
+ handler: () => new FunctionResult('ok'),
829
+ secure: true,
830
+ });
831
+ const app = agent.getApp();
832
+
833
+ // Missing token
834
+ const res1 = await app.request('/swaig', {
835
+ method: 'POST',
836
+ headers: {
837
+ 'Authorization': 'Basic ' + btoa('u:p'),
838
+ 'Content-Type': 'application/json',
839
+ },
840
+ body: JSON.stringify({ function: 'secure_fn', argument: {} }),
841
+ });
842
+ expect(res1.status).toBe(200);
843
+ const body1 = await res1.json();
844
+ expect(body1.response).toContain('security token');
845
+
846
+ // Invalid token
847
+ const res2 = await app.request('/swaig?__token=bogus_token', {
848
+ method: 'POST',
849
+ headers: {
850
+ 'Authorization': 'Basic ' + btoa('u:p'),
851
+ 'Content-Type': 'application/json',
852
+ },
853
+ body: JSON.stringify({ function: 'secure_fn', argument: {} }),
854
+ });
855
+ expect(res2.status).toBe(200);
856
+ const body2 = await res2.json();
857
+ expect(body2.response).toContain('security token');
858
+ });
859
+
860
+ it('rejects function names with invalid characters', async () => {
861
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
862
+ agent.setPromptText('hello');
863
+ const app = agent.getApp();
864
+
865
+ // SQL injection attempt
866
+ const res1 = await app.request('/swaig', {
867
+ method: 'POST',
868
+ headers: {
869
+ 'Authorization': 'Basic ' + btoa('u:p'),
870
+ 'Content-Type': 'application/json',
871
+ },
872
+ body: JSON.stringify({ function: 'valid_fn; DROP TABLE', argument: {} }),
873
+ });
874
+ expect(res1.status).toBe(400);
875
+
876
+ // Names starting with numbers
877
+ const res2 = await app.request('/swaig', {
878
+ method: 'POST',
879
+ headers: {
880
+ 'Authorization': 'Basic ' + btoa('u:p'),
881
+ 'Content-Type': 'application/json',
882
+ },
883
+ body: JSON.stringify({ function: '123invalid', argument: {} }),
884
+ });
885
+ expect(res2.status).toBe(400);
886
+
887
+ // Valid names should pass the format check (still 404 since not registered)
888
+ const res3 = await app.request('/swaig', {
889
+ method: 'POST',
890
+ headers: {
891
+ 'Authorization': 'Basic ' + btoa('u:p'),
892
+ 'Content-Type': 'application/json',
893
+ },
894
+ body: JSON.stringify({ function: 'valid_fn_name', argument: {} }),
895
+ });
896
+ expect(res3.status).toBe(404); // not registered, but passed format validation
897
+ });
898
+
899
+ it('non-object argument is coerced to empty object', async () => {
900
+ const captured: Record<string, unknown>[] = [];
901
+ const agent = new AgentBase({ name: 'test', route: '/', basicAuth: ['u', 'p'] });
902
+ agent.defineTool({
903
+ name: 'arg_test',
904
+ description: 'Test args',
905
+ parameters: {},
906
+ handler: (_args, _params, _body) => {
907
+ captured.push(_args);
908
+ return new FunctionResult('ok');
909
+ },
910
+ });
911
+ const app = agent.getApp();
912
+
913
+ // String argument
914
+ const res1 = await app.request('/swaig', {
915
+ method: 'POST',
916
+ headers: {
917
+ 'Authorization': 'Basic ' + btoa('u:p'),
918
+ 'Content-Type': 'application/json',
919
+ },
920
+ body: JSON.stringify({ function: 'arg_test', argument: 'not-an-object' }),
921
+ });
922
+ expect(res1.status).toBe(200);
923
+
924
+ // Array argument
925
+ const res2 = await app.request('/swaig', {
926
+ method: 'POST',
927
+ headers: {
928
+ 'Authorization': 'Basic ' + btoa('u:p'),
929
+ 'Content-Type': 'application/json',
930
+ },
931
+ body: JSON.stringify({ function: 'arg_test', argument: [1, 2, 3] }),
932
+ });
933
+ expect(res2.status).toBe(200);
934
+
935
+ // Null argument
936
+ const res3 = await app.request('/swaig', {
937
+ method: 'POST',
938
+ headers: {
939
+ 'Authorization': 'Basic ' + btoa('u:p'),
940
+ 'Content-Type': 'application/json',
941
+ },
942
+ body: JSON.stringify({ function: 'arg_test', argument: null }),
943
+ });
944
+ expect(res3.status).toBe(200);
945
+
946
+ // All non-object arguments should be coerced to {}
947
+ expect(captured.length).toBe(3);
948
+ for (const args of captured) {
949
+ expect(args).toEqual({});
950
+ }
951
+ });
952
+
953
+ // ── defineTypedTool ─────────────────────────────────────────────────
954
+
955
+ it('defineTypedTool registers tool with inferred schema', () => {
956
+ const agent = createAgent();
957
+ agent.setPromptText('hello');
958
+ agent.defineTypedTool({
959
+ name: 'get_weather',
960
+ description: 'Get weather for a city',
961
+ handler: (city: string, days = 5) => new FunctionResult(`Weather for ${city}, ${days} days`),
962
+ });
963
+ const tool = agent.getTool('get_weather');
964
+ expect(tool).toBeDefined();
965
+ expect(tool!.isTypedHandler).toBe(true);
966
+ expect(tool!.parameters['city']).toBeDefined();
967
+ expect(tool!.parameters['city']).toEqual({ type: 'string', description: 'The city parameter' });
968
+ expect(tool!.parameters['days']).toEqual({ type: 'integer', description: 'The days parameter' });
969
+ expect(tool!.required).toEqual(['city']);
970
+ });
971
+
972
+ it('defineTypedTool handler receives named params', async () => {
973
+ const agent = createAgent();
974
+ const captured: unknown[] = [];
975
+ agent.defineTypedTool({
976
+ name: 'greet',
977
+ description: 'Greet someone',
978
+ handler: (name: string, excited = false) => {
979
+ captured.push(name, excited);
980
+ return new FunctionResult('hi');
981
+ },
982
+ });
983
+ const tool = agent.getTool('greet');
984
+ await tool!.execute({ name: 'Alice', excited: true });
985
+ expect(captured).toEqual(['Alice', true]);
986
+ });
987
+
988
+ it('defineTypedTool explicit parameters override inference', () => {
989
+ const agent = createAgent();
990
+ agent.defineTypedTool({
991
+ name: 'custom',
992
+ description: 'Custom tool',
993
+ parameters: { location: { type: 'string', description: 'Location' } },
994
+ required: ['location'],
995
+ handler: (location: string) => new FunctionResult(`Got ${location}`),
996
+ });
997
+ const tool = agent.getTool('custom');
998
+ expect(tool).toBeDefined();
999
+ expect(tool!.parameters['location']).toEqual({ type: 'string', description: 'Location' });
1000
+ // Should not have inferred params
1001
+ expect(tool!.parameters['city']).toBeUndefined();
1002
+ });
1003
+
1004
+ it('defineTypedTool SWML output includes tool', () => {
1005
+ const agent = createAgent();
1006
+ agent.setPromptText('hello');
1007
+ agent.defineTypedTool({
1008
+ name: 'lookup',
1009
+ description: 'Look up info',
1010
+ handler: (query: string) => new FunctionResult(`Found: ${query}`),
1011
+ });
1012
+ const swml = JSON.parse(agent.renderSwml());
1013
+ const fns = swml.sections.main[1].ai.SWAIG.functions;
1014
+ expect(fns.length).toBe(1);
1015
+ expect(fns[0].function).toBe('lookup');
1016
+ expect(fns[0].parameters.properties.query).toBeDefined();
1017
+ });
1018
+
1019
+ it('auto-generated password is 32 hex chars', () => {
1020
+ const savedUser = process.env['SWML_BASIC_AUTH_USER'];
1021
+ const savedPass = process.env['SWML_BASIC_AUTH_PASSWORD'];
1022
+ delete process.env['SWML_BASIC_AUTH_USER'];
1023
+ delete process.env['SWML_BASIC_AUTH_PASSWORD'];
1024
+ try {
1025
+ const agent = new AgentBase({ name: 'test-auto-pass', route: '/' });
1026
+ const [, pass] = agent.getBasicAuthCredentials();
1027
+ expect(pass.length).toBe(32);
1028
+ expect(/^[0-9a-f]{32}$/.test(pass)).toBe(true);
1029
+ } finally {
1030
+ if (savedUser) process.env['SWML_BASIC_AUTH_USER'] = savedUser;
1031
+ if (savedPass) process.env['SWML_BASIC_AUTH_PASSWORD'] = savedPass;
1032
+ }
1033
+ });
1034
+
1035
+ describe('validateToolToken', () => {
1036
+ it('returns false for an unknown function', () => {
1037
+ const agent = createAgent();
1038
+ expect(agent.validateToolToken('missing', 'tok', 'call-1')).toBe(false);
1039
+ });
1040
+
1041
+ it('returns true for a registered non-secure function without consulting SessionManager', () => {
1042
+ const agent = createAgent();
1043
+ agent.defineTool({
1044
+ name: 'insecure_tool',
1045
+ description: 'no auth needed',
1046
+ parameters: {},
1047
+ handler: () => new FunctionResult('ok'),
1048
+ secure: false,
1049
+ });
1050
+
1051
+ // Fail loudly if SessionManager is consulted — non-secure tools must short-circuit.
1052
+ const sm = (agent as any).sessionManager;
1053
+ const orig = sm.validateToolToken.bind(sm);
1054
+ sm.validateToolToken = () => {
1055
+ throw new Error('SessionManager.validateToolToken must not be called for non-secure tools');
1056
+ };
1057
+ try {
1058
+ expect(agent.validateToolToken('insecure_tool', '', '')).toBe(true);
1059
+ } finally {
1060
+ sm.validateToolToken = orig;
1061
+ }
1062
+ });
1063
+
1064
+ it('returns true for a registered secure function with a valid token', () => {
1065
+ const agent = createAgent();
1066
+ agent.defineTool({
1067
+ name: 'secure_tool',
1068
+ description: 'auth required',
1069
+ parameters: {},
1070
+ handler: () => new FunctionResult('ok'),
1071
+ secure: true,
1072
+ });
1073
+
1074
+ const sm = (agent as any).sessionManager;
1075
+ const callId = 'call-abc';
1076
+ const token = sm.createToolToken('secure_tool', callId);
1077
+ expect(agent.validateToolToken('secure_tool', token, callId)).toBe(true);
1078
+ });
1079
+
1080
+ it('returns false for a registered secure function with an invalid token', () => {
1081
+ const agent = createAgent();
1082
+ agent.defineTool({
1083
+ name: 'secure_tool',
1084
+ description: 'auth required',
1085
+ parameters: {},
1086
+ handler: () => new FunctionResult('ok'),
1087
+ secure: true,
1088
+ });
1089
+
1090
+ expect(agent.validateToolToken('secure_tool', 'bogus-token', 'call-xyz')).toBe(false);
1091
+ });
1092
+ });
1093
+ });