@lobu/gateway 2.8.0 → 3.0.6

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 (175) hide show
  1. package/package.json +2 -2
  2. package/src/__tests__/agent-config-routes.test.ts +254 -0
  3. package/src/__tests__/agent-history-routes.test.ts +72 -0
  4. package/src/__tests__/agent-routes.test.ts +68 -0
  5. package/src/__tests__/agent-schedules-routes.test.ts +59 -0
  6. package/src/__tests__/agent-settings-store.test.ts +323 -0
  7. package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
  8. package/src/__tests__/chat-response-bridge.test.ts +131 -0
  9. package/src/__tests__/config-memory-plugins.test.ts +92 -0
  10. package/src/__tests__/config-request-store.test.ts +127 -0
  11. package/src/__tests__/connection-routes.test.ts +144 -0
  12. package/src/__tests__/core-services-store-selection.test.ts +92 -0
  13. package/src/__tests__/docker-deployment.test.ts +1211 -0
  14. package/src/__tests__/embedded-deployment.test.ts +342 -0
  15. package/src/__tests__/grant-store.test.ts +148 -0
  16. package/src/__tests__/http-proxy.test.ts +281 -0
  17. package/src/__tests__/instruction-service.test.ts +37 -0
  18. package/src/__tests__/link-buttons.test.ts +112 -0
  19. package/src/__tests__/lobu.test.ts +32 -0
  20. package/src/__tests__/mcp-config-service.test.ts +347 -0
  21. package/src/__tests__/mcp-proxy.test.ts +696 -0
  22. package/src/__tests__/message-handler-bridge.test.ts +17 -0
  23. package/src/__tests__/model-selection.test.ts +172 -0
  24. package/src/__tests__/oauth-templates.test.ts +39 -0
  25. package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
  26. package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
  27. package/src/__tests__/provider-inheritance.test.ts +212 -0
  28. package/src/__tests__/routes/cli-auth.test.ts +337 -0
  29. package/src/__tests__/routes/interactions.test.ts +121 -0
  30. package/src/__tests__/secret-proxy.test.ts +85 -0
  31. package/src/__tests__/session-manager.test.ts +572 -0
  32. package/src/__tests__/setup.ts +133 -0
  33. package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
  34. package/src/__tests__/slack-routes.test.ts +161 -0
  35. package/src/__tests__/system-config-resolver.test.ts +75 -0
  36. package/src/__tests__/system-message-limiter.test.ts +89 -0
  37. package/src/__tests__/system-skills-service.test.ts +362 -0
  38. package/src/__tests__/transcription-service.test.ts +222 -0
  39. package/src/__tests__/utils/rate-limiter.test.ts +102 -0
  40. package/src/__tests__/worker-connection-manager.test.ts +497 -0
  41. package/src/__tests__/worker-job-router.test.ts +722 -0
  42. package/src/api/index.ts +1 -0
  43. package/src/api/platform.ts +292 -0
  44. package/src/api/response-renderer.ts +157 -0
  45. package/src/auth/agent-metadata-store.ts +168 -0
  46. package/src/auth/api-auth-middleware.ts +69 -0
  47. package/src/auth/api-key-provider-module.ts +213 -0
  48. package/src/auth/base-provider-module.ts +201 -0
  49. package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
  50. package/src/auth/chatgpt/device-code-client.ts +218 -0
  51. package/src/auth/chatgpt/index.ts +1 -0
  52. package/src/auth/claude/oauth-module.ts +280 -0
  53. package/src/auth/cli/token-service.ts +249 -0
  54. package/src/auth/external/client.ts +560 -0
  55. package/src/auth/external/device-code-client.ts +225 -0
  56. package/src/auth/mcp/config-service.ts +392 -0
  57. package/src/auth/mcp/proxy.ts +1088 -0
  58. package/src/auth/mcp/string-substitution.ts +17 -0
  59. package/src/auth/mcp/tool-cache.ts +90 -0
  60. package/src/auth/oauth/base-client.ts +267 -0
  61. package/src/auth/oauth/client.ts +153 -0
  62. package/src/auth/oauth/credentials.ts +7 -0
  63. package/src/auth/oauth/providers.ts +69 -0
  64. package/src/auth/oauth/state-store.ts +150 -0
  65. package/src/auth/oauth-templates.ts +179 -0
  66. package/src/auth/provider-catalog.ts +220 -0
  67. package/src/auth/provider-model-options.ts +41 -0
  68. package/src/auth/settings/agent-settings-store.ts +565 -0
  69. package/src/auth/settings/auth-profiles-manager.ts +216 -0
  70. package/src/auth/settings/index.ts +12 -0
  71. package/src/auth/settings/model-preference-store.ts +52 -0
  72. package/src/auth/settings/model-selection.ts +135 -0
  73. package/src/auth/settings/resolved-settings-view.ts +298 -0
  74. package/src/auth/settings/template-utils.ts +44 -0
  75. package/src/auth/settings/token-service.ts +88 -0
  76. package/src/auth/system-env-store.ts +98 -0
  77. package/src/auth/user-agents-store.ts +68 -0
  78. package/src/channels/binding-service.ts +214 -0
  79. package/src/channels/index.ts +4 -0
  80. package/src/cli/gateway.ts +1304 -0
  81. package/src/cli/index.ts +74 -0
  82. package/src/commands/built-in-commands.ts +80 -0
  83. package/src/commands/command-dispatcher.ts +94 -0
  84. package/src/commands/command-reply-adapters.ts +27 -0
  85. package/src/config/file-loader.ts +618 -0
  86. package/src/config/index.ts +588 -0
  87. package/src/config/network-allowlist.ts +71 -0
  88. package/src/connections/chat-instance-manager.ts +1284 -0
  89. package/src/connections/chat-response-bridge.ts +618 -0
  90. package/src/connections/index.ts +7 -0
  91. package/src/connections/interaction-bridge.ts +831 -0
  92. package/src/connections/message-handler-bridge.ts +415 -0
  93. package/src/connections/platform-auth-methods.ts +15 -0
  94. package/src/connections/types.ts +84 -0
  95. package/src/gateway/connection-manager.ts +291 -0
  96. package/src/gateway/index.ts +700 -0
  97. package/src/gateway/job-router.ts +201 -0
  98. package/src/gateway-main.ts +200 -0
  99. package/src/index.ts +41 -0
  100. package/src/infrastructure/queue/index.ts +12 -0
  101. package/src/infrastructure/queue/queue-producer.ts +148 -0
  102. package/src/infrastructure/queue/redis-queue.ts +361 -0
  103. package/src/infrastructure/queue/types.ts +133 -0
  104. package/src/infrastructure/redis/system-message-limiter.ts +94 -0
  105. package/src/interactions/config-request-store.ts +198 -0
  106. package/src/interactions.ts +363 -0
  107. package/src/lobu.ts +311 -0
  108. package/src/metrics/prometheus.ts +159 -0
  109. package/src/modules/module-system.ts +179 -0
  110. package/src/orchestration/base-deployment-manager.ts +900 -0
  111. package/src/orchestration/deployment-utils.ts +98 -0
  112. package/src/orchestration/impl/docker-deployment.ts +620 -0
  113. package/src/orchestration/impl/embedded-deployment.ts +268 -0
  114. package/src/orchestration/impl/index.ts +8 -0
  115. package/src/orchestration/impl/k8s/deployment.ts +1061 -0
  116. package/src/orchestration/impl/k8s/helpers.ts +610 -0
  117. package/src/orchestration/impl/k8s/index.ts +1 -0
  118. package/src/orchestration/index.ts +333 -0
  119. package/src/orchestration/message-consumer.ts +584 -0
  120. package/src/orchestration/scheduled-wakeup.ts +704 -0
  121. package/src/permissions/approval-policy.ts +36 -0
  122. package/src/permissions/grant-store.ts +219 -0
  123. package/src/platform/file-handler.ts +66 -0
  124. package/src/platform/link-buttons.ts +57 -0
  125. package/src/platform/renderer-utils.ts +44 -0
  126. package/src/platform/response-renderer.ts +84 -0
  127. package/src/platform/unified-thread-consumer.ts +187 -0
  128. package/src/platform.ts +318 -0
  129. package/src/proxy/http-proxy.ts +752 -0
  130. package/src/proxy/proxy-manager.ts +81 -0
  131. package/src/proxy/secret-proxy.ts +402 -0
  132. package/src/proxy/token-refresh-job.ts +143 -0
  133. package/src/routes/internal/audio.ts +141 -0
  134. package/src/routes/internal/device-auth.ts +566 -0
  135. package/src/routes/internal/files.ts +226 -0
  136. package/src/routes/internal/history.ts +69 -0
  137. package/src/routes/internal/images.ts +127 -0
  138. package/src/routes/internal/interactions.ts +84 -0
  139. package/src/routes/internal/middleware.ts +23 -0
  140. package/src/routes/internal/schedule.ts +226 -0
  141. package/src/routes/internal/types.ts +22 -0
  142. package/src/routes/openapi-auto.ts +239 -0
  143. package/src/routes/public/agent-access.ts +23 -0
  144. package/src/routes/public/agent-config.ts +675 -0
  145. package/src/routes/public/agent-history.ts +422 -0
  146. package/src/routes/public/agent-schedules.ts +296 -0
  147. package/src/routes/public/agent.ts +1086 -0
  148. package/src/routes/public/agents.ts +373 -0
  149. package/src/routes/public/channels.ts +191 -0
  150. package/src/routes/public/cli-auth.ts +883 -0
  151. package/src/routes/public/connections.ts +574 -0
  152. package/src/routes/public/landing.ts +16 -0
  153. package/src/routes/public/oauth.ts +147 -0
  154. package/src/routes/public/settings-auth.ts +104 -0
  155. package/src/routes/public/slack.ts +173 -0
  156. package/src/routes/shared/agent-ownership.ts +101 -0
  157. package/src/routes/shared/token-verifier.ts +34 -0
  158. package/src/services/core-services.ts +1053 -0
  159. package/src/services/image-generation-service.ts +257 -0
  160. package/src/services/instruction-service.ts +318 -0
  161. package/src/services/mcp-registry.ts +94 -0
  162. package/src/services/platform-helpers.ts +287 -0
  163. package/src/services/session-manager.ts +262 -0
  164. package/src/services/settings-resolver.ts +74 -0
  165. package/src/services/system-config-resolver.ts +90 -0
  166. package/src/services/system-skills-service.ts +229 -0
  167. package/src/services/transcription-service.ts +684 -0
  168. package/src/session.ts +110 -0
  169. package/src/spaces/index.ts +1 -0
  170. package/src/spaces/space-resolver.ts +17 -0
  171. package/src/stores/in-memory-agent-store.ts +403 -0
  172. package/src/stores/redis-agent-store.ts +279 -0
  173. package/src/utils/public-url.ts +44 -0
  174. package/src/utils/rate-limiter.ts +94 -0
  175. package/tsconfig.json +33 -0
@@ -0,0 +1,362 @@
1
+ import { afterEach, describe, expect, test } from "bun:test";
2
+ import { SystemSkillsService } from "../services/system-skills-service";
3
+
4
+ const testConfig = {
5
+ skills: [
6
+ {
7
+ id: "github",
8
+ name: "GitHub",
9
+ description: "GitHub integration",
10
+ mcpServers: [
11
+ {
12
+ id: "github-mcp",
13
+ name: "GitHub MCP",
14
+ url: "https://github-mcp.example.com",
15
+ },
16
+ ],
17
+ nixPackages: ["git"],
18
+ permissions: ["github.com", "api.github.com"],
19
+ },
20
+ {
21
+ id: "owletto",
22
+ name: "Owletto",
23
+ description: "Owletto embedded",
24
+ hidden: true,
25
+ mcpServers: [
26
+ { id: "owletto-mcp", url: "https://owletto.example.com/mcp" },
27
+ ],
28
+ },
29
+ ],
30
+ };
31
+
32
+ let fetchCallCount = 0;
33
+ const originalFetch = globalThis.fetch;
34
+
35
+ function setupMockFetch(config: unknown, statusCode = 200) {
36
+ fetchCallCount = 0;
37
+ globalThis.fetch = async () => {
38
+ fetchCallCount++;
39
+ return new Response(JSON.stringify(config), {
40
+ status: statusCode,
41
+ headers: { "Content-Type": "application/json" },
42
+ });
43
+ };
44
+ }
45
+
46
+ afterEach(() => {
47
+ globalThis.fetch = originalFetch;
48
+ fetchCallCount = 0;
49
+ });
50
+
51
+ describe("SystemSkillsService", () => {
52
+ test("loads config from HTTP URL and maps skills correctly", async () => {
53
+ setupMockFetch(testConfig);
54
+ const service = new SystemSkillsService("https://example.com/skills.json");
55
+ const skills = await service.getSystemSkills();
56
+
57
+ expect(skills).toHaveLength(2);
58
+ expect(skills[0]).toEqual({
59
+ repo: "system/github",
60
+ name: "GitHub",
61
+ description: "GitHub integration",
62
+ enabled: true,
63
+ system: true,
64
+ mcpServers: [
65
+ {
66
+ id: "github-mcp",
67
+ name: "GitHub MCP",
68
+ url: "https://github-mcp.example.com",
69
+ },
70
+ ],
71
+ nixPackages: ["git"],
72
+ permissions: ["github.com", "api.github.com"],
73
+ });
74
+ expect(skills[1]).toEqual({
75
+ repo: "system/owletto",
76
+ name: "Owletto",
77
+ description: "Owletto embedded",
78
+ enabled: true,
79
+ system: true,
80
+ mcpServers: [
81
+ { id: "owletto-mcp", url: "https://owletto.example.com/mcp" },
82
+ ],
83
+ nixPackages: undefined,
84
+ permissions: undefined,
85
+ });
86
+ });
87
+
88
+ test("returns empty array when fetch fails", async () => {
89
+ setupMockFetch({ error: "not found" }, 500);
90
+ const service = new SystemSkillsService("https://example.com/skills.json");
91
+ const skills = await service.getSystemSkills();
92
+ expect(skills).toEqual([]);
93
+ });
94
+
95
+ test("returns empty array when no configUrl is provided", async () => {
96
+ const service = new SystemSkillsService();
97
+ const skills = await service.getSystemSkills();
98
+ expect(skills).toEqual([]);
99
+ });
100
+
101
+ test("getSearchableSkills filters out hidden entries", async () => {
102
+ setupMockFetch(testConfig);
103
+ const service = new SystemSkillsService("https://example.com/skills.json");
104
+ const skills = await service.getSearchableSkills();
105
+
106
+ expect(skills).toHaveLength(1);
107
+ expect(skills[0].repo).toBe("system/github");
108
+ });
109
+
110
+ test("getRawSystemSkills returns unsubstituted env patterns", async () => {
111
+ const envKey = `__TEST_SSS_KEY_${Date.now()}`;
112
+ process.env[envKey] = "secret123";
113
+ try {
114
+ const configWithEnv = {
115
+ skills: [
116
+ {
117
+ id: "test-skill",
118
+ name: "Test",
119
+ mcpServers: [
120
+ {
121
+ id: "test-mcp",
122
+ url: `https://api.example.com/\${env:${envKey}}`,
123
+ },
124
+ ],
125
+ },
126
+ ],
127
+ };
128
+ setupMockFetch(configWithEnv);
129
+ const service = new SystemSkillsService(
130
+ "https://example.com/skills.json"
131
+ );
132
+
133
+ const raw = await service.getRawSystemSkills();
134
+ expect(raw[0].mcpServers![0].url).toBe(
135
+ `https://api.example.com/\${env:${envKey}}`
136
+ );
137
+
138
+ const substituted = await service.getSystemSkills();
139
+ expect(substituted[0].mcpServers![0].url).toBe(
140
+ "https://api.example.com/secret123"
141
+ );
142
+ } finally {
143
+ delete process.env[envKey];
144
+ }
145
+ });
146
+
147
+ test("env substitution replaces ${env:VAR} with process.env value", async () => {
148
+ const envKey = `__TEST_SSS_API_${Date.now()}`;
149
+ process.env[envKey] = "my-api-key-value";
150
+ try {
151
+ const configWithEnv = {
152
+ skills: [
153
+ {
154
+ id: "env-skill",
155
+ name: "Env Skill",
156
+ mcpServers: [
157
+ {
158
+ id: "env-mcp",
159
+ url: `https://api.example.com/mcp?key=\${env:${envKey}}`,
160
+ },
161
+ ],
162
+ },
163
+ ],
164
+ };
165
+ setupMockFetch(configWithEnv);
166
+ const service = new SystemSkillsService(
167
+ "https://example.com/skills.json"
168
+ );
169
+ const skills = await service.getSystemSkills();
170
+ expect(skills[0].mcpServers![0].url).toBe(
171
+ "https://api.example.com/mcp?key=my-api-key-value"
172
+ );
173
+ } finally {
174
+ delete process.env[envKey];
175
+ }
176
+ });
177
+
178
+ test("unset env var is replaced with empty string", async () => {
179
+ const envKey = `__TEST_SSS_NONEXISTENT_${Date.now()}`;
180
+ delete process.env[envKey];
181
+ const configWithEnv = {
182
+ skills: [
183
+ {
184
+ id: "missing-env",
185
+ name: "Missing Env",
186
+ mcpServers: [
187
+ {
188
+ id: "missing-mcp",
189
+ url: `https://api.example.com/\${env:${envKey}}/path`,
190
+ },
191
+ ],
192
+ },
193
+ ],
194
+ };
195
+ setupMockFetch(configWithEnv);
196
+ const service = new SystemSkillsService("https://example.com/skills.json");
197
+ const skills = await service.getSystemSkills();
198
+ expect(skills[0].mcpServers![0].url).toBe("https://api.example.com//path");
199
+ });
200
+
201
+ test("getProviderConfigs extracts providers by skill id", async () => {
202
+ const configWithProviders = {
203
+ skills: [
204
+ {
205
+ id: "groq",
206
+ name: "Groq",
207
+ providers: [
208
+ {
209
+ displayName: "Groq",
210
+ iconUrl: "https://example.com/groq.png",
211
+ envVarName: "GROQ_API_KEY",
212
+ upstreamBaseUrl: "https://api.groq.com/openai",
213
+ apiKeyInstructions: "Get key from groq.com",
214
+ apiKeyPlaceholder: "gsk_...",
215
+ },
216
+ ],
217
+ },
218
+ {
219
+ id: "no-providers",
220
+ name: "No Providers",
221
+ },
222
+ ],
223
+ };
224
+ setupMockFetch(configWithProviders);
225
+ const service = new SystemSkillsService("https://example.com/skills.json");
226
+ const providers = await service.getProviderConfigs();
227
+
228
+ expect(Object.keys(providers)).toEqual(["groq"]);
229
+ expect(providers.groq.displayName).toBe("Groq");
230
+ expect(providers.groq.envVarName).toBe("GROQ_API_KEY");
231
+ });
232
+
233
+ test("reload clears cache and allows re-fetch", async () => {
234
+ setupMockFetch(testConfig);
235
+ const service = new SystemSkillsService("https://example.com/skills.json");
236
+
237
+ const first = await service.getSystemSkills();
238
+ expect(first).toHaveLength(2);
239
+ expect(fetchCallCount).toBe(1);
240
+
241
+ const updatedConfig = {
242
+ skills: [{ id: "new-skill", name: "New Skill" }],
243
+ };
244
+ setupMockFetch(updatedConfig);
245
+ service.reload();
246
+
247
+ const second = await service.getSystemSkills();
248
+ expect(second).toHaveLength(1);
249
+ expect(second[0].repo).toBe("system/new-skill");
250
+ expect(fetchCallCount).toBe(1);
251
+ });
252
+
253
+ test("reload with new URL uses the new URL", async () => {
254
+ setupMockFetch(testConfig);
255
+ const service = new SystemSkillsService("https://example.com/old.json");
256
+ await service.getSystemSkills();
257
+
258
+ const newConfig = {
259
+ skills: [{ id: "from-new-url", name: "From New URL" }],
260
+ };
261
+ setupMockFetch(newConfig);
262
+ service.reload("https://example.com/new.json");
263
+
264
+ const skills = await service.getSystemSkills();
265
+ expect(skills).toHaveLength(1);
266
+ expect(skills[0].repo).toBe("system/from-new-url");
267
+ });
268
+
269
+ test("caches config and only fetches once", async () => {
270
+ setupMockFetch(testConfig);
271
+ const service = new SystemSkillsService("https://example.com/skills.json");
272
+
273
+ await service.getSystemSkills();
274
+ await service.getSystemSkills();
275
+ await service.getSearchableSkills();
276
+ await service.getProviderConfigs();
277
+
278
+ expect(fetchCallCount).toBe(1);
279
+ });
280
+
281
+ test("getRuntimeSystemSkills returns runtime format with content", async () => {
282
+ setupMockFetch(testConfig);
283
+ const service = new SystemSkillsService("https://example.com/skills.json");
284
+ const runtime = await service.getRuntimeSystemSkills();
285
+
286
+ expect(runtime).toHaveLength(2);
287
+ expect(runtime[0].id).toBe("github");
288
+ expect(runtime[0].repo).toBe("system/github");
289
+ expect(runtime[0].name).toBe("GitHub");
290
+ expect(runtime[0].description).toBe("GitHub integration");
291
+ expect(runtime[0].content).toContain("# GitHub");
292
+ expect(runtime[0].content).toContain("System skill ID: `system/github`");
293
+ expect(runtime[0].content).toContain("## MCP Servers");
294
+ expect(runtime[0].content).toContain("GitHub MCP (`github-mcp`)");
295
+ expect(runtime[0].content).toContain("## Network Permissions");
296
+ expect(runtime[0].content).toContain("github.com, api.github.com");
297
+ expect(runtime[0].content).toContain("## Nix Packages");
298
+ expect(runtime[0].content).toContain("git");
299
+ });
300
+
301
+ test("toSkillConfig passes instructions through", async () => {
302
+ const configWithInstructions = {
303
+ skills: [
304
+ {
305
+ id: "owletto",
306
+ name: "Owletto Memory",
307
+ description: "Long-term memory",
308
+ instructions: "Check memory at conversation start.",
309
+ hidden: true,
310
+ mcpServers: [
311
+ { id: "owletto-mcp", url: "https://owletto.example.com" },
312
+ ],
313
+ },
314
+ {
315
+ id: "github",
316
+ name: "GitHub",
317
+ description: "GitHub integration",
318
+ },
319
+ ],
320
+ };
321
+ setupMockFetch(configWithInstructions);
322
+ const service = new SystemSkillsService("https://example.com/skills.json");
323
+ const skills = await service.getSystemSkills();
324
+
325
+ expect(skills[0].instructions).toBe("Check memory at conversation start.");
326
+ expect(skills[1].instructions).toBeUndefined();
327
+ });
328
+
329
+ test("getRuntimeSystemSkills includes instructions in content and metadata", async () => {
330
+ const configWithInstructions = {
331
+ skills: [
332
+ {
333
+ id: "owletto",
334
+ name: "Owletto Memory",
335
+ description: "Long-term memory",
336
+ instructions: "Check memory at conversation start.",
337
+ mcpServers: [
338
+ { id: "owletto-mcp", url: "https://owletto.example.com" },
339
+ ],
340
+ },
341
+ ],
342
+ };
343
+ setupMockFetch(configWithInstructions);
344
+ const service = new SystemSkillsService("https://example.com/skills.json");
345
+ const runtime = await service.getRuntimeSystemSkills();
346
+
347
+ expect(runtime[0].instructions).toBe("Check memory at conversation start.");
348
+ expect(runtime[0].content).toContain(
349
+ "**Instructions:** Check memory at conversation start."
350
+ );
351
+ expect(runtime[0].content).toContain("Long-term memory");
352
+ });
353
+
354
+ test("getRuntimeSystemSkills without instructions omits instructions block", async () => {
355
+ setupMockFetch(testConfig);
356
+ const service = new SystemSkillsService("https://example.com/skills.json");
357
+ const runtime = await service.getRuntimeSystemSkills();
358
+
359
+ expect(runtime[0].instructions).toBeUndefined();
360
+ expect(runtime[0].content).not.toContain("**Instructions:**");
361
+ });
362
+ });
@@ -0,0 +1,222 @@
1
+ import { afterEach, describe, expect, mock, test } from "bun:test";
2
+ import { TranscriptionService } from "../services/transcription-service";
3
+
4
+ describe("TranscriptionService provider fallback", () => {
5
+ afterEach(() => {
6
+ mock.restore();
7
+ });
8
+
9
+ test("falls back to next configured provider when first fails", async () => {
10
+ const authProfilesManager = {
11
+ getBestProfile: mock(async (_agentId: string, providerId: string) => {
12
+ if (providerId === "chatgpt") {
13
+ return { credential: "openai-key" };
14
+ }
15
+ if (providerId === "gemini") {
16
+ return { credential: "gemini-key" };
17
+ }
18
+ return null;
19
+ }),
20
+ } as any;
21
+
22
+ const service = new TranscriptionService(authProfilesManager);
23
+ const transcribeWithProvider = mock(
24
+ async (_buffer: Buffer, config: any) => {
25
+ if (config.provider === "openai") {
26
+ throw new Error("openai unauthorized");
27
+ }
28
+ return "hello from gemini";
29
+ }
30
+ );
31
+ (service as any).transcribeWithProvider = transcribeWithProvider;
32
+
33
+ const result = await service.transcribe(
34
+ Buffer.from("audio"),
35
+ "agent-1",
36
+ "audio/ogg"
37
+ );
38
+
39
+ expect(transcribeWithProvider).toHaveBeenCalledTimes(2);
40
+ expect("text" in result).toBe(true);
41
+ if ("text" in result) {
42
+ expect(result.text).toBe("hello from gemini");
43
+ expect(result.provider).toBe("gemini");
44
+ }
45
+ });
46
+
47
+ test("returns no-provider error when no auth profiles exist", async () => {
48
+ const authProfilesManager = {
49
+ getBestProfile: mock(async () => null),
50
+ } as any;
51
+ const service = new TranscriptionService(authProfilesManager);
52
+
53
+ const result = await service.transcribe(
54
+ Buffer.from("audio"),
55
+ "agent-2",
56
+ "audio/ogg"
57
+ );
58
+
59
+ expect("error" in result).toBe(true);
60
+ if ("error" in result) {
61
+ expect(result.error).toContain("No transcription provider configured");
62
+ }
63
+ });
64
+
65
+ test("uses config-driven OpenAI-compatible STT provider", async () => {
66
+ const authProfilesManager = {
67
+ getBestProfile: mock(async (_agentId: string, providerId: string) => {
68
+ if (providerId === "openrouter") {
69
+ return { credential: "or-key" };
70
+ }
71
+ return null;
72
+ }),
73
+ } as any;
74
+
75
+ const providerConfigSource = mock(async () => ({
76
+ openrouter: {
77
+ displayName: "OpenRouter",
78
+ iconUrl: "https://example.com/icon.png",
79
+ envVarName: "OPENROUTER_API_KEY",
80
+ upstreamBaseUrl: "https://openrouter.ai/api/v1",
81
+ apiKeyInstructions: "x",
82
+ apiKeyPlaceholder: "x",
83
+ sdkCompat: "openai",
84
+ stt: {
85
+ enabled: true,
86
+ transcriptionPath: "/audio/transcriptions",
87
+ model: "gpt-4o-mini-transcribe",
88
+ },
89
+ },
90
+ }));
91
+
92
+ const service = new TranscriptionService(
93
+ authProfilesManager,
94
+ providerConfigSource
95
+ );
96
+
97
+ const originalFetch = globalThis.fetch;
98
+ globalThis.fetch = mock(
99
+ async (input: RequestInfo | URL, init?: RequestInit) => {
100
+ const url = String(input);
101
+ expect(url).toBe("https://openrouter.ai/api/v1/audio/transcriptions");
102
+ expect((init?.headers as Record<string, string>)?.Authorization).toBe(
103
+ "Bearer or-key"
104
+ );
105
+ return new Response(JSON.stringify({ text: "hello from openrouter" }), {
106
+ status: 200,
107
+ headers: { "Content-Type": "application/json" },
108
+ });
109
+ }
110
+ ) as any;
111
+
112
+ try {
113
+ const result = await service.transcribe(
114
+ Buffer.from("audio"),
115
+ "agent-3",
116
+ "audio/ogg"
117
+ );
118
+ expect("text" in result).toBe(true);
119
+ if ("text" in result) {
120
+ expect(result.text).toBe("hello from openrouter");
121
+ expect(result.provider).toBe("openai");
122
+ }
123
+ } finally {
124
+ globalThis.fetch = originalFetch;
125
+ }
126
+ });
127
+
128
+ test("uses sdkCompat openai STT by default when stt block is missing", async () => {
129
+ const authProfilesManager = {
130
+ getBestProfile: mock(async (_agentId: string, providerId: string) => {
131
+ if (providerId === "openrouter") {
132
+ return { credential: "or-key" };
133
+ }
134
+ return null;
135
+ }),
136
+ } as any;
137
+
138
+ const providerConfigSource = mock(async () => ({
139
+ openrouter: {
140
+ displayName: "OpenRouter",
141
+ iconUrl: "https://example.com/icon.png",
142
+ envVarName: "OPENROUTER_API_KEY",
143
+ upstreamBaseUrl: "https://openrouter.ai/api/v1",
144
+ apiKeyInstructions: "x",
145
+ apiKeyPlaceholder: "x",
146
+ sdkCompat: "openai",
147
+ },
148
+ }));
149
+
150
+ const service = new TranscriptionService(
151
+ authProfilesManager,
152
+ providerConfigSource
153
+ );
154
+
155
+ const originalFetch = globalThis.fetch;
156
+ globalThis.fetch = mock(async (input: RequestInfo | URL) => {
157
+ const url = String(input);
158
+ expect(url).toBe("https://openrouter.ai/api/v1/audio/transcriptions");
159
+ return new Response(JSON.stringify({ text: "default stt works" }), {
160
+ status: 200,
161
+ headers: { "Content-Type": "application/json" },
162
+ });
163
+ }) as any;
164
+
165
+ try {
166
+ const result = await service.transcribe(
167
+ Buffer.from("audio"),
168
+ "agent-4",
169
+ "audio/ogg"
170
+ );
171
+ expect("text" in result).toBe(true);
172
+ if ("text" in result) {
173
+ expect(result.text).toBe("default stt works");
174
+ expect(result.provider).toBe("openai");
175
+ }
176
+ } finally {
177
+ globalThis.fetch = originalFetch;
178
+ }
179
+ });
180
+
181
+ test("respects stt.enabled=false for config-driven providers", async () => {
182
+ const authProfilesManager = {
183
+ getBestProfile: mock(async (_agentId: string, providerId: string) => {
184
+ if (providerId === "openrouter") {
185
+ return { credential: "or-key" };
186
+ }
187
+ return null;
188
+ }),
189
+ } as any;
190
+
191
+ const providerConfigSource = mock(async () => ({
192
+ openrouter: {
193
+ displayName: "OpenRouter",
194
+ iconUrl: "https://example.com/icon.png",
195
+ envVarName: "OPENROUTER_API_KEY",
196
+ upstreamBaseUrl: "https://openrouter.ai/api/v1",
197
+ apiKeyInstructions: "x",
198
+ apiKeyPlaceholder: "x",
199
+ sdkCompat: "openai",
200
+ stt: {
201
+ enabled: false,
202
+ },
203
+ },
204
+ }));
205
+
206
+ const service = new TranscriptionService(
207
+ authProfilesManager,
208
+ providerConfigSource
209
+ );
210
+
211
+ const result = await service.transcribe(
212
+ Buffer.from("audio"),
213
+ "agent-5",
214
+ "audio/ogg"
215
+ );
216
+
217
+ expect("error" in result).toBe(true);
218
+ if ("error" in result) {
219
+ expect(result.error).toContain("No transcription provider configured");
220
+ }
221
+ });
222
+ });
@@ -0,0 +1,102 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { MockRedisClient } from "../../../../core/src/__tests__/fixtures/mock-redis";
3
+ import {
4
+ getClientIp,
5
+ RedisFixedWindowRateLimiter,
6
+ } from "../../utils/rate-limiter";
7
+
8
+ describe("RedisFixedWindowRateLimiter", () => {
9
+ test("allows requests within the window and blocks after the limit", async () => {
10
+ const redis = new MockRedisClient();
11
+ const limiter = new RedisFixedWindowRateLimiter(redis);
12
+
13
+ const first = await limiter.consume({
14
+ key: "rate:test:1",
15
+ limit: 2,
16
+ windowSeconds: 60,
17
+ });
18
+ const second = await limiter.consume({
19
+ key: "rate:test:1",
20
+ limit: 2,
21
+ windowSeconds: 60,
22
+ });
23
+ const third = await limiter.consume({
24
+ key: "rate:test:1",
25
+ limit: 2,
26
+ windowSeconds: 60,
27
+ });
28
+
29
+ expect(first.allowed).toBe(true);
30
+ expect(first.remaining).toBe(1);
31
+ expect(second.allowed).toBe(true);
32
+ expect(second.remaining).toBe(0);
33
+ expect(third.allowed).toBe(false);
34
+ expect(third.retryAfterSeconds).toBeGreaterThan(0);
35
+ });
36
+
37
+ test("resets after the time window", async () => {
38
+ const redis = new MockRedisClient();
39
+ const limiter = new RedisFixedWindowRateLimiter(redis);
40
+
41
+ await limiter.consume({
42
+ key: "rate:test:2",
43
+ limit: 1,
44
+ windowSeconds: 60,
45
+ });
46
+ const blocked = await limiter.consume({
47
+ key: "rate:test:2",
48
+ limit: 1,
49
+ windowSeconds: 60,
50
+ });
51
+ expect(blocked.allowed).toBe(false);
52
+
53
+ redis.advanceTime(61_000);
54
+
55
+ const reset = await limiter.consume({
56
+ key: "rate:test:2",
57
+ limit: 1,
58
+ windowSeconds: 60,
59
+ });
60
+ expect(reset.allowed).toBe(true);
61
+ expect(reset.count).toBe(1);
62
+ });
63
+
64
+ test("reset clears the tracked key", async () => {
65
+ const redis = new MockRedisClient();
66
+ const limiter = new RedisFixedWindowRateLimiter(redis);
67
+
68
+ await limiter.consume({
69
+ key: "rate:test:3",
70
+ limit: 1,
71
+ windowSeconds: 60,
72
+ });
73
+ await limiter.reset("rate:test:3");
74
+
75
+ const next = await limiter.consume({
76
+ key: "rate:test:3",
77
+ limit: 1,
78
+ windowSeconds: 60,
79
+ });
80
+ expect(next.allowed).toBe(true);
81
+ expect(next.count).toBe(1);
82
+ });
83
+ });
84
+
85
+ describe("getClientIp", () => {
86
+ test("prefers x-forwarded-for, then x-real-ip, then unknown", () => {
87
+ expect(
88
+ getClientIp({
89
+ forwardedFor: "203.0.113.1, 10.0.0.1",
90
+ realIp: "198.51.100.1",
91
+ })
92
+ ).toBe("203.0.113.1");
93
+
94
+ expect(
95
+ getClientIp({
96
+ realIp: "198.51.100.1",
97
+ })
98
+ ).toBe("198.51.100.1");
99
+
100
+ expect(getClientIp({})).toBe("unknown");
101
+ });
102
+ });