@lobu/gateway 3.0.5 → 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,1284 @@
1
+ /**
2
+ * ChatInstanceManager — manages Chat SDK instances for API-driven platform connections.
3
+ * Owns Redis persistence, Chat lifecycle, and webhook dispatch.
4
+ */
5
+
6
+ import { randomUUID } from "node:crypto";
7
+ import { createLogger, decrypt, encrypt } from "@lobu/core";
8
+ import type Redis from "ioredis";
9
+ import type { CoreServices, PlatformAdapter } from "../platform";
10
+ import {
11
+ type ConnectionSettings,
12
+ isSecretField,
13
+ type PlatformAdapterConfig,
14
+ type PlatformConnection,
15
+ } from "./types";
16
+
17
+ type HistoryRecord = {
18
+ role: "user" | "assistant";
19
+ content: string;
20
+ authorName?: string;
21
+ timestamp: number;
22
+ };
23
+
24
+ const logger = createLogger("chat-instance-manager");
25
+ const SLACK_SYSTEM_AGENT_PREFIX = "system:connection:slack";
26
+
27
+ export const ADAPTER_FACTORIES: Record<string, (config: any) => Promise<any>> =
28
+ {
29
+ telegram: async (c) =>
30
+ (await import("@chat-adapter/telegram")).createTelegramAdapter(c),
31
+ slack: async (c) =>
32
+ (await import("@chat-adapter/slack")).createSlackAdapter(c),
33
+ discord: async (c) =>
34
+ (await import("@chat-adapter/discord")).createDiscordAdapter(c),
35
+ whatsapp: async (c) =>
36
+ (await import("@chat-adapter/whatsapp")).createWhatsAppAdapter(c),
37
+ teams: async (c) =>
38
+ (await import("@chat-adapter/teams")).createTeamsAdapter(c),
39
+ gchat: async (c) =>
40
+ (await import("@chat-adapter/gchat")).createGoogleChatAdapter(c),
41
+ };
42
+
43
+ interface ManagedInstance {
44
+ connection: PlatformConnection;
45
+ chat: any; // Chat SDK instance
46
+ cleanup?: () => Promise<void>;
47
+ interactionCleanup?: () => void;
48
+ }
49
+
50
+ export class ChatInstanceManager {
51
+ private instances = new Map<string, ManagedInstance>();
52
+ private redis!: Redis;
53
+ private services!: CoreServices;
54
+ private publicGatewayUrl = "";
55
+
56
+ async initialize(services: CoreServices): Promise<void> {
57
+ this.services = services;
58
+ this.redis = services.getQueue().getRedisClient();
59
+ this.publicGatewayUrl = services.getPublicGatewayUrl();
60
+
61
+ // Load all connections from Redis and start active ones
62
+ const connectionIds = await this.redis.smembers("connections:all");
63
+ logger.debug(
64
+ { count: connectionIds.length },
65
+ "Loading connections from Redis"
66
+ );
67
+
68
+ for (const id of connectionIds) {
69
+ try {
70
+ const raw = await this.redis.get(`connection:${id}`);
71
+ if (!raw) {
72
+ await this.redis.srem("connections:all", id);
73
+ continue;
74
+ }
75
+ const connection = JSON.parse(raw) as PlatformConnection;
76
+ try {
77
+ connection.config = this.decryptConfig(connection.config);
78
+ } catch (decryptError) {
79
+ // ENCRYPTION_KEY changed — remove stale connection so the seeder can recreate it
80
+ logger.warn(
81
+ { id, platform: connection.platform, error: String(decryptError) },
82
+ "Removing connection with undecryptable config (ENCRYPTION_KEY changed?)"
83
+ );
84
+ await this.redis.del(`connection:${id}`);
85
+ await this.redis.srem("connections:all", id);
86
+ if (connection.templateAgentId) {
87
+ await this.redis.srem(
88
+ `connections:agent:${connection.templateAgentId}`,
89
+ id
90
+ );
91
+ }
92
+ continue;
93
+ }
94
+
95
+ // Migrate legacy agentId → templateAgentId
96
+ const legacy = connection as PlatformConnection & {
97
+ agentId?: string;
98
+ };
99
+ if (legacy.agentId && !connection.templateAgentId) {
100
+ connection.templateAgentId = legacy.agentId;
101
+ delete legacy.agentId;
102
+ await this.persistConnection(connection);
103
+ logger.info(
104
+ { id, templateAgentId: connection.templateAgentId },
105
+ "Migrated agentId → templateAgentId"
106
+ );
107
+ }
108
+
109
+ // Migrate legacy scope values: "mcp-servers"/"tools" → "skills"
110
+ if (connection.settings?.userConfigScopes?.length) {
111
+ const oldScopes = connection.settings.userConfigScopes as string[];
112
+ const hasLegacy = oldScopes.some(
113
+ (s) => s === "mcp-servers" || s === "tools"
114
+ );
115
+ if (hasLegacy) {
116
+ const migrated = new Set<string>();
117
+ for (const s of oldScopes) {
118
+ if (s === "mcp-servers" || s === "tools") {
119
+ migrated.add("skills");
120
+ } else {
121
+ migrated.add(s);
122
+ }
123
+ }
124
+ connection.settings.userConfigScopes = [...migrated] as any;
125
+ await this.persistConnection(connection);
126
+ logger.info({ id }, "Migrated legacy scopes → skills");
127
+ }
128
+ }
129
+
130
+ if (connection.status === "active") {
131
+ await this.startInstance(connection);
132
+ }
133
+ } catch (error) {
134
+ logger.error({ id, error: String(error) }, "Failed to load connection");
135
+ }
136
+ }
137
+ }
138
+
139
+ async shutdown(): Promise<void> {
140
+ logger.info(
141
+ { count: this.instances.size },
142
+ "Shutting down all connections"
143
+ );
144
+ const shutdownPromises = Array.from(this.instances.values()).map(
145
+ async (instance) => {
146
+ try {
147
+ instance.interactionCleanup?.();
148
+ await instance.cleanup?.();
149
+ } catch (error) {
150
+ logger.error(
151
+ { id: instance.connection.id, error: String(error) },
152
+ "Error shutting down connection"
153
+ );
154
+ }
155
+ }
156
+ );
157
+ await Promise.allSettled(shutdownPromises);
158
+ this.instances.clear();
159
+ }
160
+
161
+ async addConnection(
162
+ platform: string,
163
+ templateAgentId: string | undefined,
164
+ config: PlatformAdapterConfig,
165
+ settings?: ConnectionSettings,
166
+ metadata: Record<string, any> = {}
167
+ ): Promise<PlatformConnection> {
168
+ if (!(platform in ADAPTER_FACTORIES)) {
169
+ throw new Error(`Unsupported platform: ${platform}`);
170
+ }
171
+ if (config.platform !== platform) {
172
+ throw new Error(
173
+ `Config platform mismatch: expected ${platform}, got ${config.platform}`
174
+ );
175
+ }
176
+
177
+ const id = randomUUID().replace(/-/g, "").slice(0, 16);
178
+ const now = Date.now();
179
+
180
+ const connection: PlatformConnection = {
181
+ id,
182
+ platform,
183
+ ...(templateAgentId ? { templateAgentId } : {}),
184
+ config,
185
+ settings: settings ?? { allowGroups: true },
186
+ metadata,
187
+ status: "active",
188
+ createdAt: now,
189
+ updatedAt: now,
190
+ };
191
+
192
+ // Start the Chat SDK instance
193
+ await this.startInstance(connection);
194
+
195
+ // Persist (secrets encrypted)
196
+ await this.persistConnection(connection);
197
+
198
+ logger.info({ id, platform, templateAgentId }, "Connection added");
199
+ return connection;
200
+ }
201
+
202
+ async removeConnection(id: string): Promise<void> {
203
+ const instance = this.instances.get(id);
204
+ if (instance) {
205
+ instance.interactionCleanup?.();
206
+ await instance.cleanup?.();
207
+ this.instances.delete(id);
208
+ }
209
+
210
+ // Clean up Redis
211
+ const raw = await this.redis.get(`connection:${id}`);
212
+ if (raw) {
213
+ const conn = JSON.parse(raw) as PlatformConnection;
214
+ if (conn.templateAgentId) {
215
+ await this.redis.srem(`connections:agent:${conn.templateAgentId}`, id);
216
+ }
217
+ }
218
+ await this.redis.del(`connection:${id}`);
219
+ await this.redis.srem("connections:all", id);
220
+
221
+ logger.info({ id }, "Connection removed");
222
+ }
223
+
224
+ async restartConnection(id: string): Promise<void> {
225
+ const instance = this.instances.get(id);
226
+ if (instance) {
227
+ instance.interactionCleanup?.();
228
+ await instance.cleanup?.();
229
+ this.instances.delete(id);
230
+ }
231
+
232
+ const raw = await this.redis.get(`connection:${id}`);
233
+ if (!raw) throw new Error(`Connection ${id} not found`);
234
+
235
+ const connection = JSON.parse(raw) as PlatformConnection;
236
+ connection.config = this.decryptConfig(connection.config);
237
+ connection.status = "active";
238
+ connection.errorMessage = undefined;
239
+ connection.updatedAt = Date.now();
240
+
241
+ try {
242
+ await this.startInstance(connection);
243
+ } catch (error) {
244
+ // startInstance sets connection.status = "error" — persist so UI reflects it
245
+ await this.persistConnection(connection);
246
+ throw error;
247
+ }
248
+ await this.persistConnection(connection);
249
+
250
+ logger.info({ id }, "Connection restarted");
251
+ }
252
+
253
+ async stopConnection(id: string): Promise<void> {
254
+ const instance = this.instances.get(id);
255
+ if (instance) {
256
+ instance.interactionCleanup?.();
257
+ await instance.cleanup?.();
258
+ this.instances.delete(id);
259
+ }
260
+
261
+ const raw = await this.redis.get(`connection:${id}`);
262
+ if (!raw) throw new Error(`Connection ${id} not found`);
263
+
264
+ const connection = JSON.parse(raw) as PlatformConnection;
265
+ connection.config = this.decryptConfig(connection.config);
266
+ connection.status = "stopped";
267
+ connection.updatedAt = Date.now();
268
+ await this.persistConnection(connection);
269
+
270
+ logger.info({ id }, "Connection stopped");
271
+ }
272
+
273
+ async updateConnection(
274
+ id: string,
275
+ updates: {
276
+ templateAgentId?: string | null;
277
+ config?: PlatformAdapterConfig;
278
+ settings?: ConnectionSettings;
279
+ metadata?: Record<string, any>;
280
+ }
281
+ ): Promise<PlatformConnection> {
282
+ const raw = await this.redis.get(`connection:${id}`);
283
+ if (!raw) throw new Error(`Connection ${id} not found`);
284
+
285
+ const connection = JSON.parse(raw) as PlatformConnection;
286
+ connection.config = this.decryptConfig(connection.config);
287
+
288
+ const needsRestart =
289
+ updates.config !== undefined &&
290
+ JSON.stringify(updates.config) !== JSON.stringify(connection.config);
291
+
292
+ if (updates.templateAgentId !== undefined) {
293
+ // Update agent index — remove old, add new
294
+ if (connection.templateAgentId) {
295
+ await this.redis.srem(
296
+ `connections:agent:${connection.templateAgentId}`,
297
+ id
298
+ );
299
+ }
300
+ if (updates.templateAgentId) {
301
+ connection.templateAgentId = updates.templateAgentId;
302
+ await this.redis.sadd(
303
+ `connections:agent:${connection.templateAgentId}`,
304
+ id
305
+ );
306
+ } else {
307
+ delete connection.templateAgentId;
308
+ }
309
+ }
310
+ if (updates.config !== undefined) {
311
+ const merged = { ...connection.config } as any;
312
+ for (const [key, value] of Object.entries(updates.config)) {
313
+ if (typeof value === "string" && value.startsWith("***")) continue;
314
+ merged[key] = value;
315
+ }
316
+ merged.platform = updates.config.platform;
317
+ connection.config = merged as PlatformAdapterConfig;
318
+ }
319
+ if (updates.settings !== undefined) {
320
+ connection.settings = { ...connection.settings, ...updates.settings };
321
+ }
322
+ if (updates.metadata !== undefined) {
323
+ connection.metadata = {
324
+ ...(connection.metadata || {}),
325
+ ...updates.metadata,
326
+ };
327
+ }
328
+ connection.updatedAt = Date.now();
329
+
330
+ if (needsRestart && connection.status === "active") {
331
+ const instance = this.instances.get(id);
332
+ if (instance) {
333
+ instance.interactionCleanup?.();
334
+ await instance.cleanup?.();
335
+ this.instances.delete(id);
336
+ }
337
+ await this.startInstance(connection);
338
+ } else {
339
+ const instance = this.instances.get(id);
340
+ if (instance) {
341
+ instance.connection = connection;
342
+ }
343
+ }
344
+
345
+ await this.persistConnection(connection);
346
+ return this.sanitizeConnection(connection);
347
+ }
348
+
349
+ async listConnections(filter?: {
350
+ platform?: string;
351
+ templateAgentId?: string;
352
+ }): Promise<PlatformConnection[]> {
353
+ let ids: string[];
354
+ if (filter?.templateAgentId) {
355
+ ids = await this.redis.smembers(
356
+ `connections:agent:${filter.templateAgentId}`
357
+ );
358
+ } else {
359
+ ids = await this.redis.smembers("connections:all");
360
+ }
361
+
362
+ const connections: PlatformConnection[] = [];
363
+ for (const id of ids) {
364
+ const raw = await this.redis.get(`connection:${id}`);
365
+ if (!raw) continue;
366
+ const conn = JSON.parse(raw) as PlatformConnection;
367
+ if (filter?.platform && conn.platform !== filter.platform) continue;
368
+ connections.push(this.sanitizeConnection(conn));
369
+ }
370
+ return connections;
371
+ }
372
+
373
+ async getConnection(id: string): Promise<PlatformConnection | null> {
374
+ const raw = await this.redis.get(`connection:${id}`);
375
+ if (!raw) return null;
376
+ return this.sanitizeConnection(JSON.parse(raw));
377
+ }
378
+
379
+ has(id: string): boolean {
380
+ return this.instances.has(id);
381
+ }
382
+
383
+ getInstance(id: string): ManagedInstance | undefined {
384
+ return this.instances.get(id);
385
+ }
386
+
387
+ /** Get a decrypted secret from a running connection's config. */
388
+ getConnectionConfigSecret(
389
+ connectionId: string,
390
+ field: string
391
+ ): string | undefined {
392
+ const instance = this.instances.get(connectionId);
393
+ if (!instance) return undefined;
394
+ const config = instance.connection.config as Record<string, unknown>;
395
+ const val = config[field];
396
+ return typeof val === "string" ? val : undefined;
397
+ }
398
+
399
+ async handleWebhook(
400
+ connectionId: string,
401
+ request: Request
402
+ ): Promise<Response> {
403
+ const instance = this.instances.get(connectionId);
404
+ if (!instance) {
405
+ return new Response("Connection not found", { status: 404 });
406
+ }
407
+
408
+ const { platform } = instance.connection;
409
+ const webhookHandler = instance.chat.webhooks?.[platform];
410
+ if (!webhookHandler) {
411
+ logger.warn(
412
+ { connectionId, platform },
413
+ "No webhook handler found for platform"
414
+ );
415
+ return new Response("No webhook handler", { status: 404 });
416
+ }
417
+
418
+ try {
419
+ return await webhookHandler(request);
420
+ } catch (error) {
421
+ logger.error(
422
+ { connectionId, platform, error: String(error) },
423
+ "Webhook handling failed"
424
+ );
425
+ return new Response("Internal error", { status: 500 });
426
+ }
427
+ }
428
+
429
+ getServices(): CoreServices {
430
+ return this.services;
431
+ }
432
+
433
+ async findSlackConnectionByTeamId(
434
+ teamId: string
435
+ ): Promise<PlatformConnection | null> {
436
+ const connections = await this.listConnections({ platform: "slack" });
437
+ return (
438
+ connections.find(
439
+ (connection) => connection.metadata?.teamId === teamId
440
+ ) || null
441
+ );
442
+ }
443
+
444
+ async getDefaultSlackConnection(): Promise<PlatformConnection | null> {
445
+ const connections = await this.listConnections({ platform: "slack" });
446
+ if (connections.length === 1) {
447
+ return connections[0] || null;
448
+ }
449
+
450
+ return (
451
+ connections.find((connection) => !connection.metadata?.teamId) || null
452
+ );
453
+ }
454
+
455
+ async ensureSlackWorkspaceConnection(
456
+ teamId: string,
457
+ installation: {
458
+ botToken: string;
459
+ botUserId?: string;
460
+ teamName?: string;
461
+ }
462
+ ): Promise<PlatformConnection> {
463
+ const baseConfig = this.resolveSlackAdapterConfig({
464
+ requireOAuth: true,
465
+ }) as Extract<PlatformAdapterConfig, { platform: "slack" }>;
466
+ const config: PlatformAdapterConfig = {
467
+ ...baseConfig,
468
+ botToken: installation.botToken,
469
+ ...(installation.botUserId ? { botUserId: installation.botUserId } : {}),
470
+ };
471
+ const agentId = `${SLACK_SYSTEM_AGENT_PREFIX}:${teamId}`;
472
+ const metadata = {
473
+ teamId,
474
+ teamName: installation.teamName,
475
+ botUserId: installation.botUserId,
476
+ };
477
+
478
+ const existing = await this.findSlackConnectionByTeamId(teamId);
479
+ if (existing) {
480
+ const updated = await this.updateConnection(existing.id, {
481
+ templateAgentId: agentId,
482
+ config,
483
+ metadata,
484
+ });
485
+ if (!this.has(existing.id)) {
486
+ await this.restartConnection(existing.id);
487
+ }
488
+ return updated;
489
+ }
490
+
491
+ return this.addConnection(
492
+ "slack",
493
+ agentId,
494
+ config,
495
+ { allowGroups: true },
496
+ metadata
497
+ );
498
+ }
499
+
500
+ async completeSlackOAuthInstall(
501
+ request: Request,
502
+ redirectUri?: string
503
+ ): Promise<{
504
+ teamId: string;
505
+ teamName?: string;
506
+ connectionId: string;
507
+ }> {
508
+ const { chat, adapter } = await this.createSlackOAuthChat({
509
+ requireOAuth: true,
510
+ });
511
+
512
+ try {
513
+ const url = new URL(request.url);
514
+ if (redirectUri) {
515
+ url.searchParams.set("redirect_uri", redirectUri);
516
+ }
517
+
518
+ const callbackRequest = new Request(url.toString(), {
519
+ method: request.method,
520
+ headers: request.headers,
521
+ });
522
+
523
+ const { teamId, installation } =
524
+ await adapter.handleOAuthCallback(callbackRequest);
525
+ let connection: PlatformConnection;
526
+ try {
527
+ connection = await this.ensureSlackWorkspaceConnection(
528
+ teamId,
529
+ installation
530
+ );
531
+ } catch (error) {
532
+ await adapter.deleteInstallation(teamId).catch((err) => {
533
+ logger.warn(
534
+ { teamId, error: String(err) },
535
+ "Failed to delete Slack installation after connection error"
536
+ );
537
+ });
538
+ throw error;
539
+ }
540
+
541
+ return {
542
+ teamId,
543
+ teamName: installation.teamName,
544
+ connectionId: connection.id,
545
+ };
546
+ } finally {
547
+ await chat.shutdown().catch((err: unknown) => {
548
+ logger.warn(
549
+ { error: String(err) },
550
+ "Failed to shut down Slack OAuth chat"
551
+ );
552
+ });
553
+ }
554
+ }
555
+
556
+ async handleSlackAppWebhook(request: Request): Promise<Response> {
557
+ const body = await request.text();
558
+ const teamId = this.extractSlackTeamId(
559
+ body,
560
+ request.headers.get("content-type") || ""
561
+ );
562
+
563
+ if (teamId) {
564
+ const connection = await this.findSlackConnectionByTeamId(teamId);
565
+ if (connection) {
566
+ if (!(await this.ensureConnectionRunning(connection.id))) {
567
+ return new Response("Slack connection unavailable", { status: 503 });
568
+ }
569
+ return this.handleWebhook(
570
+ connection.id,
571
+ this.cloneRequestWithBody(request, body)
572
+ );
573
+ }
574
+ }
575
+
576
+ const fallbackConnection = await this.getDefaultSlackConnection();
577
+ if (fallbackConnection) {
578
+ if (!(await this.ensureConnectionRunning(fallbackConnection.id))) {
579
+ return new Response("Slack connection unavailable", { status: 503 });
580
+ }
581
+ return this.handleWebhook(
582
+ fallbackConnection.id,
583
+ this.cloneRequestWithBody(request, body)
584
+ );
585
+ }
586
+
587
+ const { chat, adapter } = await this.createSlackOAuthChat();
588
+ try {
589
+ return await adapter.handleWebhook(
590
+ this.cloneRequestWithBody(request, body)
591
+ );
592
+ } finally {
593
+ await chat.shutdown().catch((err) => {
594
+ logger.warn(
595
+ { error: String(err) },
596
+ "Failed to shut down Slack webhook chat"
597
+ );
598
+ });
599
+ }
600
+ }
601
+
602
+ // --- Private ---
603
+
604
+ private async startInstance(connection: PlatformConnection): Promise<void> {
605
+ try {
606
+ const { Chat } = await import("chat");
607
+ const adapter = await this.createAdapter(connection);
608
+ const stateAdapter = await this.createStateAdapter();
609
+
610
+ const adapterKey = connection.platform;
611
+ const chat = new Chat({
612
+ userName: connection.metadata.botUsername || `bot-${connection.id}`,
613
+ adapters: { [adapterKey]: adapter },
614
+ state: stateAdapter,
615
+ logger: "warn",
616
+ });
617
+
618
+ // Register message handlers (imported lazily to avoid circular deps)
619
+ const { registerMessageHandlers } = await import(
620
+ "./message-handler-bridge"
621
+ );
622
+ const { CommandDispatcher } = await import(
623
+ "../commands/command-dispatcher"
624
+ );
625
+ const commandDispatcher = new CommandDispatcher({
626
+ registry: this.services.getCommandRegistry(),
627
+ channelBindingService: this.services.getChannelBindingService(),
628
+ });
629
+ registerMessageHandlers(
630
+ chat,
631
+ connection,
632
+ this.services,
633
+ this,
634
+ commandDispatcher
635
+ );
636
+
637
+ chat.registerSingleton();
638
+
639
+ // Initialize adapters (starts long-polling for Telegram, etc.)
640
+ await chat.initialize();
641
+
642
+ // Set webhook URL if applicable
643
+ const mode = (connection.config as any).mode ?? "auto";
644
+ const useWebhook =
645
+ mode === "webhook" || (mode === "auto" && !!this.publicGatewayUrl);
646
+ if (useWebhook && this.publicGatewayUrl) {
647
+ const webhookUrl = `${this.publicGatewayUrl}/api/v1/webhooks/${connection.id}`;
648
+ logger.info({ id: connection.id, webhookUrl }, "Setting webhook");
649
+ }
650
+
651
+ const cleanup = async () => {
652
+ try {
653
+ await chat.shutdown();
654
+ } catch {
655
+ // best effort
656
+ }
657
+ };
658
+
659
+ // Populate metadata (bot username etc.) from adapter properties
660
+ if (!connection.metadata.botUsername) {
661
+ try {
662
+ const userName = adapter.userName || adapter.botUsername;
663
+ if (userName) {
664
+ connection.metadata.botUsername = userName;
665
+ await this.updateConnection(connection.id, {
666
+ metadata: { botUsername: userName },
667
+ });
668
+ }
669
+ } catch {
670
+ // non-critical
671
+ }
672
+ }
673
+
674
+ this.instances.set(connection.id, { connection, chat, cleanup });
675
+
676
+ const { registerInteractionBridge } = await import(
677
+ "./interaction-bridge"
678
+ );
679
+ const interactionCleanup = registerInteractionBridge(
680
+ this.services.getInteractionService(),
681
+ this,
682
+ connection,
683
+ chat,
684
+ this.services.getGrantStore(),
685
+ this.services.getAgentSettingsStore()
686
+ );
687
+ this.instances.get(connection.id)!.interactionCleanup =
688
+ interactionCleanup;
689
+
690
+ // Register slash commands with the platform (e.g. Telegram menu)
691
+ this.registerPlatformCommands(connection).catch((err) => {
692
+ logger.warn(
693
+ { id: connection.id, error: String(err) },
694
+ "Failed to register platform commands"
695
+ );
696
+ });
697
+
698
+ logger.info(
699
+ { id: connection.id, platform: connection.platform },
700
+ "Chat instance started"
701
+ );
702
+ } catch (error) {
703
+ connection.status = "error";
704
+ connection.errorMessage = String(error);
705
+ logger.error(
706
+ { id: connection.id, error: String(error) },
707
+ "Failed to start Chat instance"
708
+ );
709
+ throw error;
710
+ }
711
+ }
712
+
713
+ private async createAdapter(connection: PlatformConnection): Promise<any> {
714
+ const factory = ADAPTER_FACTORIES[connection.platform];
715
+ if (!factory) {
716
+ throw new Error(`No adapter factory for: ${connection.platform}`);
717
+ }
718
+ return factory(connection.config);
719
+ }
720
+
721
+ private async createStateAdapter(): Promise<any> {
722
+ const { createIoRedisState } = await import("@chat-adapter/state-ioredis");
723
+ return createIoRedisState({
724
+ client: this.redis,
725
+ keyPrefix: "chat-conn",
726
+ logger: "warn",
727
+ } as any);
728
+ }
729
+
730
+ /**
731
+ * Register slash commands with the platform's native command menu.
732
+ * Currently supports Telegram (setMyCommands) and Slack (via manifest).
733
+ */
734
+ private async registerPlatformCommands(
735
+ connection: PlatformConnection
736
+ ): Promise<void> {
737
+ const commands = this.services
738
+ .getCommandRegistry()
739
+ .getAll()
740
+ .map((cmd) => ({
741
+ command: cmd.name,
742
+ description: cmd.description,
743
+ }));
744
+
745
+ if (connection.platform === "telegram") {
746
+ const botToken = (connection.config as any).botToken;
747
+ if (!botToken) return;
748
+
749
+ const apiBase =
750
+ (connection.config as any).apiBaseUrl || "https://api.telegram.org";
751
+ const resp = await fetch(`${apiBase}/bot${botToken}/setMyCommands`, {
752
+ method: "POST",
753
+ headers: { "Content-Type": "application/json" },
754
+ body: JSON.stringify({ commands }),
755
+ });
756
+
757
+ if (!resp.ok) {
758
+ const text = await resp.text();
759
+ throw new Error(
760
+ `Telegram setMyCommands failed: ${resp.status} ${text}`
761
+ );
762
+ }
763
+
764
+ logger.info(
765
+ { id: connection.id, count: commands.length },
766
+ "Telegram bot commands menu registered"
767
+ );
768
+ }
769
+ }
770
+
771
+ private resolveSlackAdapterConfig(options?: {
772
+ requireOAuth?: boolean;
773
+ }): PlatformAdapterConfig {
774
+ const slackInstance = Array.from(this.instances.values()).find(
775
+ (instance) => instance.connection.platform === "slack"
776
+ );
777
+ const currentConfig = (slackInstance?.connection.config || {}) as Record<
778
+ string,
779
+ any
780
+ >;
781
+
782
+ const signingSecret =
783
+ process.env.SLACK_SIGNING_SECRET || currentConfig.signingSecret;
784
+ const clientId = process.env.SLACK_CLIENT_ID || currentConfig.clientId;
785
+ const clientSecret =
786
+ process.env.SLACK_CLIENT_SECRET || currentConfig.clientSecret;
787
+ const encryptionKey =
788
+ process.env.SLACK_ENCRYPTION_KEY || currentConfig.encryptionKey;
789
+ const installationKeyPrefix =
790
+ process.env.SLACK_INSTALLATION_KEY_PREFIX ||
791
+ currentConfig.installationKeyPrefix;
792
+ const userName =
793
+ process.env.SLACK_BOT_USERNAME ||
794
+ currentConfig.userName ||
795
+ slackInstance?.connection.metadata?.botUsername;
796
+
797
+ if (!signingSecret) {
798
+ throw new Error("Slack signing secret is not configured");
799
+ }
800
+
801
+ if (options?.requireOAuth) {
802
+ if (!clientId || !clientSecret) {
803
+ throw new Error(
804
+ "Slack OAuth is not configured. Set SLACK_CLIENT_ID and SLACK_CLIENT_SECRET."
805
+ );
806
+ }
807
+
808
+ return {
809
+ platform: "slack",
810
+ signingSecret,
811
+ clientId,
812
+ clientSecret,
813
+ ...(encryptionKey ? { encryptionKey } : {}),
814
+ ...(installationKeyPrefix ? { installationKeyPrefix } : {}),
815
+ ...(userName ? { userName } : {}),
816
+ };
817
+ }
818
+
819
+ const botToken = process.env.SLACK_BOT_TOKEN || currentConfig.botToken;
820
+ if (!botToken && (!clientId || !clientSecret)) {
821
+ throw new Error(
822
+ "Slack adapter is not configured. Provide SLACK_BOT_TOKEN or Slack OAuth credentials."
823
+ );
824
+ }
825
+
826
+ return {
827
+ platform: "slack",
828
+ signingSecret,
829
+ ...(botToken ? { botToken } : {}),
830
+ ...(clientId ? { clientId } : {}),
831
+ ...(clientSecret ? { clientSecret } : {}),
832
+ ...(encryptionKey ? { encryptionKey } : {}),
833
+ ...(installationKeyPrefix ? { installationKeyPrefix } : {}),
834
+ ...(userName ? { userName } : {}),
835
+ };
836
+ }
837
+
838
+ private async createSlackOAuthChat(options?: { requireOAuth?: boolean }) {
839
+ const { Chat } = await import("chat");
840
+ const { createSlackAdapter } = await import("@chat-adapter/slack");
841
+
842
+ const adapter = createSlackAdapter(
843
+ this.resolveSlackAdapterConfig(options) as any
844
+ );
845
+ const state = await this.createStateAdapter();
846
+
847
+ const chat = new Chat({
848
+ userName: "lobu-slack-oauth",
849
+ adapters: { slack: adapter },
850
+ state,
851
+ logger: "warn",
852
+ });
853
+
854
+ await chat.initialize();
855
+ return { chat, adapter };
856
+ }
857
+
858
+ private cloneRequestWithBody(request: Request, body: string): Request {
859
+ return new Request(request.url, {
860
+ method: request.method,
861
+ headers: request.headers,
862
+ body:
863
+ request.method === "GET" || request.method === "HEAD"
864
+ ? undefined
865
+ : body,
866
+ });
867
+ }
868
+
869
+ private extractSlackTeamId(body: string, contentType: string): string | null {
870
+ if (contentType.includes("application/x-www-form-urlencoded")) {
871
+ const params = new URLSearchParams(body);
872
+ const directTeamId = params.get("team_id");
873
+ if (directTeamId) {
874
+ return directTeamId;
875
+ }
876
+
877
+ const payloadStr = params.get("payload");
878
+ if (!payloadStr) {
879
+ return null;
880
+ }
881
+
882
+ try {
883
+ const payload = JSON.parse(payloadStr) as {
884
+ team?: { id?: string };
885
+ team_id?: string;
886
+ };
887
+ return payload.team?.id || payload.team_id || null;
888
+ } catch {
889
+ return null;
890
+ }
891
+ }
892
+
893
+ try {
894
+ const payload = JSON.parse(body) as {
895
+ team_id?: string;
896
+ team?: string;
897
+ event?: { team_id?: string; team?: string };
898
+ };
899
+ return (
900
+ payload.team_id ||
901
+ payload.team ||
902
+ payload.event?.team_id ||
903
+ payload.event?.team ||
904
+ null
905
+ );
906
+ } catch {
907
+ return null;
908
+ }
909
+ }
910
+
911
+ private async ensureConnectionRunning(id: string): Promise<boolean> {
912
+ if (this.has(id)) {
913
+ return true;
914
+ }
915
+
916
+ // Don't auto-restart intentionally stopped connections
917
+ const raw = await this.redis.get(`connection:${id}`);
918
+ if (raw) {
919
+ const connection = JSON.parse(raw) as PlatformConnection;
920
+ if (connection.status === "stopped") {
921
+ logger.info({ id }, "Connection is stopped, not auto-restarting");
922
+ return false;
923
+ }
924
+ }
925
+
926
+ try {
927
+ await this.restartConnection(id);
928
+ return this.has(id);
929
+ } catch (error) {
930
+ logger.error(
931
+ { id, error: String(error) },
932
+ "Failed to restart connection"
933
+ );
934
+ return false;
935
+ }
936
+ }
937
+
938
+ private async persistConnection(
939
+ connection: PlatformConnection
940
+ ): Promise<void> {
941
+ const encrypted = {
942
+ ...connection,
943
+ config: this.encryptConfig(connection.config),
944
+ };
945
+ const json = JSON.stringify(encrypted);
946
+
947
+ const pipeline = this.redis
948
+ .pipeline()
949
+ .set(`connection:${connection.id}`, json)
950
+ .sadd("connections:all", connection.id);
951
+
952
+ if (connection.templateAgentId) {
953
+ pipeline.sadd(
954
+ `connections:agent:${connection.templateAgentId}`,
955
+ connection.id
956
+ );
957
+ }
958
+
959
+ await pipeline.exec();
960
+ }
961
+
962
+ private encryptConfig(config: PlatformAdapterConfig): PlatformAdapterConfig {
963
+ const encrypted = { ...config } as any;
964
+ for (const field of Object.keys(encrypted)) {
965
+ if (isSecretField(field) && typeof encrypted[field] === "string") {
966
+ try {
967
+ encrypted[field] = `enc:v1:${encrypt(encrypted[field])}`;
968
+ } catch {
969
+ // encryption not available — store as-is (dev mode)
970
+ }
971
+ }
972
+ }
973
+ return encrypted;
974
+ }
975
+
976
+ private decryptConfig(config: PlatformAdapterConfig): PlatformAdapterConfig {
977
+ const decrypted = { ...config } as any;
978
+ for (const field of Object.keys(decrypted)) {
979
+ const val = decrypted[field];
980
+ if (
981
+ isSecretField(field) &&
982
+ typeof val === "string" &&
983
+ val.startsWith("enc:v1:")
984
+ ) {
985
+ try {
986
+ decrypted[field] = decrypt(val.slice(7));
987
+ } catch {
988
+ throw new Error(
989
+ `Failed to decrypt field "${field}" — ENCRYPTION_KEY may have changed`
990
+ );
991
+ }
992
+ }
993
+ }
994
+ return decrypted;
995
+ }
996
+
997
+ /** Return connection with secrets redacted for API responses. */
998
+ private sanitizeConnection(
999
+ connection: PlatformConnection
1000
+ ): PlatformConnection {
1001
+ const sanitized = {
1002
+ ...connection,
1003
+ config: { ...connection.config } as any,
1004
+ };
1005
+ for (const field of Object.keys(sanitized.config)) {
1006
+ if (isSecretField(field) && sanitized.config[field]) {
1007
+ const val = String(sanitized.config[field]);
1008
+ sanitized.config[field] = `***${val.slice(-4)}`;
1009
+ }
1010
+ }
1011
+ return sanitized;
1012
+ }
1013
+
1014
+ // ============================================================================
1015
+ // Platform adapter methods (used via PlatformRegistry)
1016
+ // ============================================================================
1017
+
1018
+ /**
1019
+ * Create PlatformAdapter objects for each chat platform.
1020
+ * These are lightweight adapters that delegate to this manager.
1021
+ */
1022
+ createPlatformAdapters(): PlatformAdapter[] {
1023
+ return Object.keys(ADAPTER_FACTORIES).map((name) =>
1024
+ this.createPlatformAdapter(name)
1025
+ );
1026
+ }
1027
+
1028
+ private createPlatformAdapter(name: string): PlatformAdapter {
1029
+ return {
1030
+ name,
1031
+ initialize: async () => {
1032
+ /* no-op: lifecycle managed by ChatInstanceManager */
1033
+ },
1034
+ start: async () => {
1035
+ /* no-op: lifecycle managed by ChatInstanceManager */
1036
+ },
1037
+ stop: async () => {
1038
+ /* no-op: lifecycle managed by ChatInstanceManager */
1039
+ },
1040
+ isHealthy: () => true,
1041
+ buildDeploymentMetadata: (
1042
+ conversationId: string,
1043
+ channelId: string,
1044
+ platformMetadata: Record<string, any>
1045
+ ) => ({
1046
+ platform: name,
1047
+ channelId,
1048
+ conversationId,
1049
+ ...(typeof platformMetadata.connectionId === "string"
1050
+ ? { connectionId: platformMetadata.connectionId }
1051
+ : {}),
1052
+ }),
1053
+ extractRoutingInfo: (body: Record<string, unknown>) =>
1054
+ this.extractPlatformRoutingInfo(name, body),
1055
+ sendMessage: (
1056
+ _token: string,
1057
+ message: string,
1058
+ options: {
1059
+ agentId: string;
1060
+ channelId: string;
1061
+ conversationId?: string;
1062
+ teamId: string;
1063
+ files?: Array<{ buffer: Buffer; filename: string }>;
1064
+ }
1065
+ ) => this.sendPlatformMessage(name, message, options),
1066
+ getConversationHistory: (
1067
+ channelId: string,
1068
+ conversationId: string | undefined,
1069
+ limit: number,
1070
+ before: string | undefined
1071
+ ) =>
1072
+ this.getPlatformConversationHistory(
1073
+ name,
1074
+ channelId,
1075
+ conversationId,
1076
+ limit,
1077
+ before
1078
+ ),
1079
+ };
1080
+ }
1081
+
1082
+ private extractPlatformRoutingInfo(
1083
+ name: string,
1084
+ body: Record<string, unknown>
1085
+ ): { channelId: string; conversationId?: string; teamId?: string } | null {
1086
+ if (name === "slack") {
1087
+ const slack = body.slack as
1088
+ | { channel?: string; thread?: string; team?: string }
1089
+ | undefined;
1090
+ if (!slack?.channel) return null;
1091
+ return {
1092
+ channelId: slack.channel,
1093
+ conversationId: slack.thread,
1094
+ teamId: slack.team,
1095
+ };
1096
+ }
1097
+
1098
+ if (name === "telegram") {
1099
+ const telegram = body.telegram as
1100
+ | { chatId?: string | number }
1101
+ | undefined;
1102
+ if (!telegram?.chatId) return null;
1103
+ return {
1104
+ channelId: String(telegram.chatId),
1105
+ conversationId: String(telegram.chatId),
1106
+ };
1107
+ }
1108
+
1109
+ const whatsapp = body.whatsapp as { chat?: string } | undefined;
1110
+ if (!whatsapp?.chat) return null;
1111
+ return {
1112
+ channelId: whatsapp.chat,
1113
+ conversationId: whatsapp.chat,
1114
+ };
1115
+ }
1116
+
1117
+ async sendPlatformMessage(
1118
+ name: string,
1119
+ message: string,
1120
+ options: {
1121
+ agentId: string;
1122
+ channelId: string;
1123
+ conversationId?: string;
1124
+ teamId: string;
1125
+ files?: Array<{ buffer: Buffer; filename: string }>;
1126
+ }
1127
+ ): Promise<{
1128
+ messageId: string;
1129
+ eventsUrl?: string;
1130
+ queued?: boolean;
1131
+ }> {
1132
+ if (options.files?.length) {
1133
+ throw new Error(
1134
+ `Platform "${name}" does not support file uploads via Chat SDK routing yet`
1135
+ );
1136
+ }
1137
+
1138
+ const connection = await this.selectConnectionForPlatform(
1139
+ name,
1140
+ options.channelId,
1141
+ options.teamId
1142
+ );
1143
+ if (!connection) {
1144
+ throw new Error(`No active ${name} connection is available`);
1145
+ }
1146
+
1147
+ const instance = this.getInstance(connection.id);
1148
+ if (!instance) {
1149
+ throw new Error(`Connection ${connection.id} is not running`);
1150
+ }
1151
+
1152
+ const content =
1153
+ name === "slack" ? message : message.replace(/@me\s*/g, "").trim();
1154
+ if (!content) {
1155
+ throw new Error("Cannot send an empty message");
1156
+ }
1157
+
1158
+ const useThread = name === "slack" && !!options.conversationId;
1159
+
1160
+ let sent;
1161
+ if (useThread) {
1162
+ const adapter = instance.chat.getAdapter?.(connection.platform);
1163
+ const createThread = (instance.chat as any).createThread;
1164
+ const threadId = `${connection.platform}:${options.channelId}:${options.conversationId}`;
1165
+ const thread =
1166
+ adapter && typeof createThread === "function"
1167
+ ? await createThread.call(instance.chat, adapter, threadId, {}, false)
1168
+ : null;
1169
+ if (!thread) {
1170
+ throw new Error(`Unable to resolve ${name} thread`);
1171
+ }
1172
+ sent = await thread.post(content);
1173
+ } else {
1174
+ const channel = instance.chat.channel?.(
1175
+ `${connection.platform}:${options.channelId}`
1176
+ );
1177
+ if (!channel) {
1178
+ throw new Error(`Unable to resolve ${name} channel`);
1179
+ }
1180
+ sent = await channel.post(content);
1181
+ }
1182
+
1183
+ return {
1184
+ messageId: String(sent?.id || sent?.messageId || sent?.ts || Date.now()),
1185
+ };
1186
+ }
1187
+
1188
+ async getPlatformConversationHistory(
1189
+ name: string,
1190
+ channelId: string,
1191
+ _conversationId: string | undefined,
1192
+ limit: number,
1193
+ before: string | undefined
1194
+ ): Promise<{
1195
+ messages: Array<{
1196
+ timestamp: string;
1197
+ user: string;
1198
+ text: string;
1199
+ isBot?: boolean;
1200
+ }>;
1201
+ nextCursor: string | null;
1202
+ hasMore: boolean;
1203
+ }> {
1204
+ const connection = await this.selectConnectionForPlatform(name, channelId);
1205
+ if (!connection) {
1206
+ return { messages: [], nextCursor: null, hasMore: false };
1207
+ }
1208
+
1209
+ const redis = this.services.getQueue().getRedisClient();
1210
+ const key = `chat:history:${connection.id}:${channelId}`;
1211
+ const raw = await redis.lrange(key, 0, -1);
1212
+ const parsed: HistoryRecord[] = [];
1213
+ for (const entry of raw) {
1214
+ try {
1215
+ parsed.push(JSON.parse(entry) as HistoryRecord);
1216
+ } catch (err) {
1217
+ logger.warn(
1218
+ { key, error: String(err) },
1219
+ "Skipping corrupt history entry"
1220
+ );
1221
+ }
1222
+ }
1223
+ let entries = parsed;
1224
+
1225
+ if (before) {
1226
+ const cutoff = Date.parse(before);
1227
+ if (!Number.isNaN(cutoff)) {
1228
+ entries = entries.filter(
1229
+ (entry: HistoryRecord) => entry.timestamp < cutoff
1230
+ );
1231
+ }
1232
+ }
1233
+
1234
+ const hasMore = entries.length > limit;
1235
+ const selected = entries.slice(-limit);
1236
+ const nextCursor =
1237
+ hasMore && selected[0]
1238
+ ? new Date(selected[0].timestamp).toISOString()
1239
+ : null;
1240
+
1241
+ return {
1242
+ messages: selected.map((entry: HistoryRecord) => ({
1243
+ timestamp: new Date(entry.timestamp).toISOString(),
1244
+ user:
1245
+ entry.authorName ||
1246
+ (entry.role === "assistant" ? "assistant" : "user"),
1247
+ text: entry.content,
1248
+ isBot: entry.role === "assistant",
1249
+ })),
1250
+ nextCursor,
1251
+ hasMore,
1252
+ };
1253
+ }
1254
+
1255
+ private async selectConnectionForPlatform(
1256
+ name: string,
1257
+ channelId: string,
1258
+ teamId?: string
1259
+ ): Promise<PlatformConnection | null> {
1260
+ const connections = await this.listConnections({ platform: name });
1261
+ const activeConnections = connections.filter((connection) =>
1262
+ this.has(connection.id)
1263
+ );
1264
+ if (activeConnections.length === 0) return null;
1265
+ if (activeConnections.length === 1) return activeConnections[0] || null;
1266
+
1267
+ const teamMatch = activeConnections.find(
1268
+ (connection) => connection.metadata?.teamId === teamId
1269
+ );
1270
+ if (teamMatch) return teamMatch;
1271
+
1272
+ const redis = this.services.getQueue().getRedisClient();
1273
+ for (const connection of activeConnections) {
1274
+ const exists = await redis.exists(
1275
+ `chat:history:${connection.id}:${channelId}`
1276
+ );
1277
+ if (exists === 1) {
1278
+ return connection;
1279
+ }
1280
+ }
1281
+
1282
+ return activeConnections[0] || null;
1283
+ }
1284
+ }