@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,831 @@
1
+ import { createLogger } from "@lobu/core";
2
+ import type Redis from "ioredis";
3
+ import type { AgentSettingsStore } from "../auth/settings/agent-settings-store";
4
+ import type {
5
+ InteractionService,
6
+ PostedConfigRequest,
7
+ PostedGrantRequest,
8
+ PostedLinkButton,
9
+ PostedPackageRequest,
10
+ PostedQuestion,
11
+ PostedStatusMessage,
12
+ } from "../interactions";
13
+ import {
14
+ applyPendingConfigRequest,
15
+ deletePendingConfigRequest,
16
+ getPendingConfigRequest,
17
+ } from "../interactions/config-request-store";
18
+ import type { GrantStore } from "../permissions/grant-store";
19
+ import type { ChatInstanceManager } from "./chat-instance-manager";
20
+ import type { PlatformConnection } from "./types";
21
+
22
+ const logger = createLogger("chat-interaction-bridge");
23
+
24
+ async function postWithFallback(
25
+ thread: any,
26
+ primary: { card: any; fallbackText: string },
27
+ connectionId: string,
28
+ context: string
29
+ ): Promise<void> {
30
+ try {
31
+ await thread.post(primary);
32
+ } catch (error) {
33
+ logger.warn(
34
+ { connectionId, error: String(error) },
35
+ `Failed to post ${context}`
36
+ );
37
+ try {
38
+ await thread.post(primary.fallbackText);
39
+ } catch {
40
+ // give up
41
+ }
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Send a message with inline keyboard buttons via the Telegram Bot API.
47
+ * Used for interactive elements (grant/package requests, questions) since
48
+ * the Chat SDK does not support Telegram's inline keyboard natively.
49
+ */
50
+ async function sendTelegramInlineKeyboard(
51
+ botToken: string,
52
+ chatId: string,
53
+ text: string,
54
+ buttons: Array<Array<{ text: string; callback_data: string }>>
55
+ ): Promise<boolean> {
56
+ try {
57
+ const res = await fetch(
58
+ `https://api.telegram.org/bot${botToken}/sendMessage`,
59
+ {
60
+ method: "POST",
61
+ headers: { "Content-Type": "application/json" },
62
+ body: JSON.stringify({
63
+ chat_id: chatId,
64
+ text,
65
+ reply_markup: { inline_keyboard: buttons },
66
+ }),
67
+ }
68
+ );
69
+ return res.ok;
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
75
+ const GRANT_REQUEST_TTL = 5 * 60_000; // 5 minutes
76
+ const GRANT_REQUEST_REDIS_TTL = 300; // 5 minutes in seconds
77
+ const GRANT_REQUEST_KEY_PREFIX = "pending-grant:";
78
+
79
+ async function storePendingGrant(
80
+ redis: Redis,
81
+ grantRequestId: string,
82
+ agentId: string,
83
+ domains: string[]
84
+ ): Promise<void> {
85
+ const key = `${GRANT_REQUEST_KEY_PREFIX}${grantRequestId}`;
86
+ await redis.set(
87
+ key,
88
+ JSON.stringify({ agentId, domains }),
89
+ "EX",
90
+ GRANT_REQUEST_REDIS_TTL
91
+ );
92
+ }
93
+
94
+ async function getPendingGrant(
95
+ redis: Redis,
96
+ grantRequestId: string
97
+ ): Promise<{ agentId: string; domains: string[] } | null> {
98
+ const key = `${GRANT_REQUEST_KEY_PREFIX}${grantRequestId}`;
99
+ const raw = await redis.get(key);
100
+ if (!raw) return null;
101
+ try {
102
+ return JSON.parse(raw);
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+
108
+ async function deletePendingGrant(
109
+ redis: Redis,
110
+ grantRequestId: string
111
+ ): Promise<void> {
112
+ await redis.del(`${GRANT_REQUEST_KEY_PREFIX}${grantRequestId}`);
113
+ }
114
+
115
+ export function registerInteractionBridge(
116
+ interactionService: InteractionService,
117
+ manager: ChatInstanceManager,
118
+ connection: PlatformConnection,
119
+ chat: any,
120
+ grantStore?: GrantStore,
121
+ agentSettingsStore?: AgentSettingsStore
122
+ ): () => void {
123
+ const { id: connectionId, platform } = connection;
124
+
125
+ // Per-connection state (avoids cross-contamination between connections)
126
+ const handledEvents = new Set<string>();
127
+ const activeTimers = new Set<NodeJS.Timeout>();
128
+ function markHandled(id: string): void {
129
+ handledEvents.add(id);
130
+ const timer = setTimeout(() => {
131
+ handledEvents.delete(id);
132
+ activeTimers.delete(timer);
133
+ }, 30_000);
134
+ activeTimers.add(timer);
135
+ }
136
+ const pendingQuestionOptions = new Map<string, string[]>();
137
+
138
+ const onQuestionCreated = async (event: PostedQuestion) => {
139
+ try {
140
+ if (!shouldHandle(event, platform, connectionId, manager)) return;
141
+ if (handledEvents.has(event.id)) return;
142
+ markHandled(event.id);
143
+
144
+ if (platform === "telegram") {
145
+ const botToken = manager.getConnectionConfigSecret(
146
+ connectionId,
147
+ "botToken"
148
+ );
149
+ if (botToken) {
150
+ pendingQuestionOptions.set(event.id, [...event.options]);
151
+ const optionTimer = setTimeout(() => {
152
+ pendingQuestionOptions.delete(event.id);
153
+ activeTimers.delete(optionTimer);
154
+ }, GRANT_REQUEST_TTL);
155
+ activeTimers.add(optionTimer);
156
+ const buttons = event.options.map((option, i) => [
157
+ {
158
+ text: option,
159
+ callback_data: `question:${event.id}:${i}`,
160
+ },
161
+ ]);
162
+ const sent = await sendTelegramInlineKeyboard(
163
+ botToken,
164
+ event.channelId,
165
+ event.question,
166
+ buttons
167
+ );
168
+ if (sent) return;
169
+ logger.warn(
170
+ { connectionId },
171
+ "Telegram inline keyboard failed for question, falling back"
172
+ );
173
+ }
174
+ }
175
+
176
+ const thread = await resolveThread(
177
+ manager,
178
+ connectionId,
179
+ event.channelId,
180
+ event.conversationId
181
+ );
182
+ if (!thread) return;
183
+
184
+ const { Card, CardText, Actions, Button } = await import("chat");
185
+ const buttons = event.options.map((option, i) =>
186
+ Button({
187
+ id: `question:${event.id}:${i}`,
188
+ label: option,
189
+ value: option,
190
+ })
191
+ );
192
+ const card = Card({
193
+ children: [CardText(event.question), Actions(buttons)],
194
+ });
195
+ const fallbackText = `${event.question}\n${event.options.map((o, i) => `${i + 1}. ${o}`).join("\n")}`;
196
+ await postWithFallback(
197
+ thread,
198
+ { card, fallbackText },
199
+ connectionId,
200
+ "question interaction"
201
+ );
202
+ } catch (error) {
203
+ logger.error(
204
+ { connectionId, error: String(error) },
205
+ "Unhandled error in question:created handler"
206
+ );
207
+ }
208
+ };
209
+
210
+ const redis = manager.getServices().getQueue().getRedisClient();
211
+
212
+ const onGrantRequested = async (event: PostedGrantRequest) => {
213
+ try {
214
+ if (!shouldHandle(event, platform, connectionId, manager)) return;
215
+ if (handledEvents.has(event.id)) return;
216
+ markHandled(event.id);
217
+
218
+ // Store pending grant in Redis so it survives pod restarts / multi-replica
219
+ try {
220
+ await storePendingGrant(redis, event.id, event.agentId, event.domains);
221
+ } catch (error) {
222
+ logger.error(
223
+ { grantRequestId: event.id, error: String(error) },
224
+ "Failed to store pending grant in Redis"
225
+ );
226
+ }
227
+
228
+ const domainList = event.domains.join(", ");
229
+ const text = `Access Request\nDomains: ${domainList}\nReason: ${event.reason}`;
230
+
231
+ if (platform === "telegram") {
232
+ const botToken = manager.getConnectionConfigSecret(
233
+ connectionId,
234
+ "botToken"
235
+ );
236
+ if (botToken) {
237
+ const sent = await sendTelegramInlineKeyboard(
238
+ botToken,
239
+ event.channelId,
240
+ text,
241
+ [
242
+ [
243
+ { text: "Approve", callback_data: `grant:${event.id}:approve` },
244
+ { text: "Deny", callback_data: `grant:${event.id}:deny` },
245
+ ],
246
+ ]
247
+ );
248
+ if (sent) return;
249
+ logger.warn(
250
+ { connectionId },
251
+ "Telegram inline keyboard failed for grant, falling back"
252
+ );
253
+ }
254
+ }
255
+
256
+ const thread = await resolveThread(
257
+ manager,
258
+ connectionId,
259
+ event.channelId,
260
+ event.conversationId
261
+ );
262
+ if (!thread) return;
263
+
264
+ const { Card, CardText, Actions, Button } = await import("chat");
265
+ const card = Card({
266
+ children: [
267
+ CardText(
268
+ `*Access Request*\nDomains: ${domainList}\nReason: ${event.reason}`
269
+ ),
270
+ Actions([
271
+ Button({
272
+ id: `grant:${event.id}:approve`,
273
+ label: "Approve",
274
+ style: "primary",
275
+ value: "approve",
276
+ }),
277
+ Button({
278
+ id: `grant:${event.id}:deny`,
279
+ label: "Deny",
280
+ style: "danger",
281
+ value: "deny",
282
+ }),
283
+ ]),
284
+ ],
285
+ });
286
+ await postWithFallback(
287
+ thread,
288
+ { card, fallbackText: text },
289
+ connectionId,
290
+ "grant interaction with buttons"
291
+ );
292
+ } catch (error) {
293
+ logger.error(
294
+ { connectionId, error: String(error) },
295
+ "Unhandled error in grant:requested handler"
296
+ );
297
+ }
298
+ };
299
+
300
+ const onPackageRequested = async (event: PostedPackageRequest) => {
301
+ try {
302
+ if (!shouldHandle(event, platform, connectionId, manager)) return;
303
+ if (handledEvents.has(event.id)) return;
304
+ markHandled(event.id);
305
+
306
+ const pkgList = event.packages.join(", ");
307
+ const text = `Package Install Request\nPackages: ${pkgList}\nReason: ${event.reason}`;
308
+
309
+ if (platform === "telegram") {
310
+ const botToken = manager.getConnectionConfigSecret(
311
+ connectionId,
312
+ "botToken"
313
+ );
314
+ if (botToken) {
315
+ const sent = await sendTelegramInlineKeyboard(
316
+ botToken,
317
+ event.channelId,
318
+ text,
319
+ [
320
+ [
321
+ {
322
+ text: "Approve",
323
+ callback_data: `package:${event.id}:approve`,
324
+ },
325
+ {
326
+ text: "Deny",
327
+ callback_data: `package:${event.id}:deny`,
328
+ },
329
+ ],
330
+ ]
331
+ );
332
+ if (sent) return;
333
+ logger.warn(
334
+ { connectionId },
335
+ "Telegram inline keyboard failed for package request, falling back"
336
+ );
337
+ }
338
+ }
339
+
340
+ const thread = await resolveThread(
341
+ manager,
342
+ connectionId,
343
+ event.channelId,
344
+ event.conversationId
345
+ );
346
+ if (!thread) return;
347
+
348
+ const { Card, CardText, Actions, Button } = await import("chat");
349
+ const card = Card({
350
+ children: [
351
+ CardText(
352
+ `*Package Install Request*\nPackages: ${pkgList}\nReason: ${event.reason}`
353
+ ),
354
+ Actions([
355
+ Button({
356
+ id: `package:${event.id}:approve`,
357
+ label: "Approve",
358
+ style: "primary",
359
+ value: "approve",
360
+ }),
361
+ Button({
362
+ id: `package:${event.id}:deny`,
363
+ label: "Deny",
364
+ style: "danger",
365
+ value: "deny",
366
+ }),
367
+ ]),
368
+ ],
369
+ });
370
+ await postWithFallback(
371
+ thread,
372
+ { card, fallbackText: text },
373
+ connectionId,
374
+ "package request interaction with buttons"
375
+ );
376
+ } catch (error) {
377
+ logger.error(
378
+ { connectionId, error: String(error) },
379
+ "Unhandled error in package:requested handler"
380
+ );
381
+ }
382
+ };
383
+
384
+ const onConfigRequested = async (event: PostedConfigRequest) => {
385
+ try {
386
+ if (!shouldHandle(event, platform, connectionId, manager)) return;
387
+ if (handledEvents.has(event.id)) return;
388
+ markHandled(event.id);
389
+
390
+ if (platform === "telegram") {
391
+ const botToken = manager.getConnectionConfigSecret(
392
+ connectionId,
393
+ "botToken"
394
+ );
395
+ if (botToken) {
396
+ const sent = await sendTelegramInlineKeyboard(
397
+ botToken,
398
+ event.channelId,
399
+ event.text,
400
+ [
401
+ [
402
+ {
403
+ text: "Approve",
404
+ callback_data: `config:${event.id}:approve`,
405
+ },
406
+ {
407
+ text: "Deny",
408
+ callback_data: `config:${event.id}:deny`,
409
+ },
410
+ ],
411
+ ]
412
+ );
413
+ if (sent) return;
414
+ logger.warn(
415
+ { connectionId },
416
+ "Telegram inline keyboard failed for config request, falling back"
417
+ );
418
+ }
419
+ }
420
+
421
+ const thread = await resolveThread(
422
+ manager,
423
+ connectionId,
424
+ event.channelId,
425
+ event.conversationId
426
+ );
427
+ if (!thread) return;
428
+
429
+ const { Card, CardText, Actions, Button } = await import("chat");
430
+ const card = Card({
431
+ children: [
432
+ CardText(event.text),
433
+ Actions([
434
+ Button({
435
+ id: `config:${event.id}:approve`,
436
+ label: "Approve",
437
+ style: "primary",
438
+ value: "approve",
439
+ }),
440
+ Button({
441
+ id: `config:${event.id}:deny`,
442
+ label: "Deny",
443
+ style: "danger",
444
+ value: "deny",
445
+ }),
446
+ ]),
447
+ ],
448
+ });
449
+ await postWithFallback(
450
+ thread,
451
+ { card, fallbackText: event.text },
452
+ connectionId,
453
+ "config request interaction with buttons"
454
+ );
455
+ } catch (error) {
456
+ logger.error(
457
+ { connectionId, error: String(error) },
458
+ "Unhandled error in config:requested handler"
459
+ );
460
+ }
461
+ };
462
+
463
+ const onLinkButtonCreated = async (event: PostedLinkButton) => {
464
+ try {
465
+ if (!shouldHandle(event, platform, connectionId, manager)) return;
466
+ if (handledEvents.has(event.id)) return;
467
+ markHandled(event.id);
468
+
469
+ const thread = await resolveThread(
470
+ manager,
471
+ connectionId,
472
+ event.channelId,
473
+ event.conversationId
474
+ );
475
+ if (!thread) return;
476
+
477
+ const { Card, CardText, Actions, LinkButton } = await import("chat");
478
+ const linkButton = LinkButton({
479
+ url: event.url,
480
+ label: event.label,
481
+ });
482
+ const card = Card({
483
+ children: [CardText(event.label), Actions([linkButton])],
484
+ });
485
+ const fallbackText = `${event.label}: ${event.url}`;
486
+ await postWithFallback(
487
+ thread,
488
+ { card, fallbackText },
489
+ connectionId,
490
+ "link button interaction"
491
+ );
492
+ } catch (error) {
493
+ logger.error(
494
+ { connectionId, error: String(error) },
495
+ "Unhandled error in link-button:created handler"
496
+ );
497
+ }
498
+ };
499
+
500
+ const onStatusMessageCreated = async (event: PostedStatusMessage) => {
501
+ try {
502
+ if (!shouldHandle(event, platform, connectionId, manager)) return;
503
+ if (handledEvents.has(event.id)) return;
504
+ markHandled(event.id);
505
+
506
+ const thread = await resolveThread(
507
+ manager,
508
+ connectionId,
509
+ event.channelId,
510
+ event.conversationId
511
+ );
512
+ if (!thread) return;
513
+
514
+ try {
515
+ await thread.post(event.text);
516
+ } catch (error) {
517
+ logger.warn(
518
+ { connectionId, error: String(error) },
519
+ "Failed to post status message interaction"
520
+ );
521
+ }
522
+ } catch (error) {
523
+ logger.error(
524
+ { connectionId, error: String(error) },
525
+ "Unhandled error in status-message:created handler"
526
+ );
527
+ }
528
+ };
529
+
530
+ interactionService.on("question:created", onQuestionCreated);
531
+ interactionService.on("grant:requested", onGrantRequested);
532
+ interactionService.on("package:requested", onPackageRequested);
533
+ interactionService.on("config:requested", onConfigRequested);
534
+ interactionService.on("link-button:created", onLinkButtonCreated);
535
+ interactionService.on("status-message:created", onStatusMessageCreated);
536
+
537
+ registerActionHandlers(
538
+ chat,
539
+ connection,
540
+ redis,
541
+ grantStore,
542
+ agentSettingsStore,
543
+ pendingQuestionOptions
544
+ );
545
+
546
+ logger.info({ connectionId, platform }, "Interaction bridge registered");
547
+
548
+ return () => {
549
+ interactionService.off("question:created", onQuestionCreated);
550
+ interactionService.off("grant:requested", onGrantRequested);
551
+ interactionService.off("package:requested", onPackageRequested);
552
+ interactionService.off("config:requested", onConfigRequested);
553
+ interactionService.off("link-button:created", onLinkButtonCreated);
554
+ interactionService.off("status-message:created", onStatusMessageCreated);
555
+ for (const timer of activeTimers) {
556
+ clearTimeout(timer);
557
+ }
558
+ activeTimers.clear();
559
+ handledEvents.clear();
560
+ pendingQuestionOptions.clear();
561
+ logger.info({ connectionId, platform }, "Interaction bridge unregistered");
562
+ };
563
+ }
564
+
565
+ function registerActionHandlers(
566
+ chat: any,
567
+ connection: PlatformConnection,
568
+ redis: Redis,
569
+ grantStore: GrantStore | undefined,
570
+ agentSettingsStore: AgentSettingsStore | undefined,
571
+ pendingQuestionOptions: Map<string, string[]>
572
+ ): void {
573
+ chat.onAction(async (event: any) => {
574
+ const actionId: string = event.actionId ?? "";
575
+ const value: string = event.value ?? "";
576
+ const thread = event.thread;
577
+
578
+ if (!thread || !actionId) return;
579
+
580
+ // Handle grant approval/denial — persist to GrantStore before echoing
581
+ if (actionId.startsWith("grant:")) {
582
+ const parts = actionId.split(":");
583
+ const grantRequestId = parts[1];
584
+ const decision = parts[2]; // "approve" or "deny"
585
+
586
+ if (grantRequestId && grantStore) {
587
+ try {
588
+ const pending = await getPendingGrant(redis, grantRequestId);
589
+ if (pending) {
590
+ const approved = decision === "approve";
591
+ try {
592
+ for (const domain of pending.domains) {
593
+ await grantStore.grant(
594
+ pending.agentId,
595
+ domain,
596
+ null,
597
+ !approved
598
+ );
599
+ }
600
+ logger.info(
601
+ {
602
+ grantRequestId,
603
+ agentId: pending.agentId,
604
+ domains: pending.domains,
605
+ approved,
606
+ },
607
+ "Grant request resolved via button"
608
+ );
609
+ } catch (error) {
610
+ logger.error(
611
+ { grantRequestId, error: String(error) },
612
+ "Failed to persist grant decision"
613
+ );
614
+ }
615
+ await deletePendingGrant(redis, grantRequestId).catch(
616
+ /* best effort */ () => undefined
617
+ );
618
+ } else {
619
+ logger.warn(
620
+ { grantRequestId },
621
+ "No pending grant found in Redis — may have expired"
622
+ );
623
+ }
624
+ } catch (error) {
625
+ logger.error(
626
+ { grantRequestId, error: String(error) },
627
+ "Redis error looking up pending grant"
628
+ );
629
+ }
630
+ }
631
+
632
+ // Echo human-readable decision back to thread so the worker receives it
633
+ const responseText = decision === "approve" ? "approve" : "deny";
634
+ try {
635
+ await thread.post(responseText);
636
+ } catch (error) {
637
+ logger.debug(
638
+ { connectionId: connection.id, error: String(error) },
639
+ "Failed to post grant action response"
640
+ );
641
+ }
642
+ return;
643
+ }
644
+
645
+ if (actionId.startsWith("config:")) {
646
+ const parts = actionId.split(":");
647
+ const configRequestId = parts[1];
648
+ const decision = parts[2];
649
+
650
+ if (configRequestId && decision === "approve" && !agentSettingsStore) {
651
+ try {
652
+ await thread.post("failed to apply requested configuration change");
653
+ } catch {
654
+ // best effort
655
+ }
656
+ return;
657
+ }
658
+
659
+ if (configRequestId && decision === "approve" && agentSettingsStore) {
660
+ try {
661
+ const pending = await getPendingConfigRequest(redis, configRequestId);
662
+ if (pending) {
663
+ await applyPendingConfigRequest(
664
+ agentSettingsStore,
665
+ grantStore,
666
+ pending
667
+ );
668
+ await deletePendingConfigRequest(redis, configRequestId).catch(
669
+ () => undefined
670
+ );
671
+ logger.info(
672
+ {
673
+ configRequestId,
674
+ agentId: pending.agentId,
675
+ },
676
+ "Config request resolved via button"
677
+ );
678
+ }
679
+ } catch (error) {
680
+ logger.error(
681
+ { configRequestId, error: String(error) },
682
+ "Failed to apply config request"
683
+ );
684
+ try {
685
+ await thread.post("failed to apply requested configuration change");
686
+ } catch {
687
+ // best effort
688
+ }
689
+ return;
690
+ }
691
+ } else if (configRequestId) {
692
+ await deletePendingConfigRequest(redis, configRequestId).catch(
693
+ () => undefined
694
+ );
695
+ }
696
+
697
+ try {
698
+ await thread.post(decision === "approve" ? "approve" : "deny");
699
+ } catch (error) {
700
+ logger.debug(
701
+ { connectionId: connection.id, error: String(error) },
702
+ "Failed to post config action response"
703
+ );
704
+ }
705
+ return;
706
+ }
707
+
708
+ // Handle package install approval/denial
709
+ if (actionId.startsWith("package:")) {
710
+ const decision = actionId.split(":")[2] || value || "";
711
+ const responseText = decision || "";
712
+ try {
713
+ await thread.post(responseText);
714
+ } catch (error) {
715
+ logger.debug(
716
+ { connectionId: connection.id, error: String(error) },
717
+ "Failed to post package action response"
718
+ );
719
+ }
720
+ return;
721
+ }
722
+
723
+ // Handle question responses
724
+ if (actionId.startsWith("question:")) {
725
+ const [, questionId, optionIndex] = actionId.split(":");
726
+ const optionIdx = Number.parseInt(optionIndex || "", 10);
727
+ const responseText =
728
+ value ||
729
+ (questionId &&
730
+ Number.isFinite(optionIdx) &&
731
+ pendingQuestionOptions.get(questionId)?.[optionIdx]
732
+ ? pendingQuestionOptions.get(questionId)![optionIdx]!
733
+ : optionIndex || "");
734
+ if (questionId) {
735
+ pendingQuestionOptions.delete(questionId);
736
+ }
737
+ try {
738
+ await thread.post(responseText);
739
+ } catch (error) {
740
+ logger.debug(
741
+ { connectionId: connection.id, error: String(error) },
742
+ "Failed to post action response"
743
+ );
744
+ }
745
+ }
746
+ });
747
+ }
748
+
749
+ function shouldHandle(
750
+ event: { teamId?: string; channelId: string; connectionId?: string },
751
+ platform: string,
752
+ connectionId: string,
753
+ manager: ChatInstanceManager
754
+ ): boolean {
755
+ if (!manager.has(connectionId)) {
756
+ logger.debug(
757
+ { connectionId, eventConnectionId: event.connectionId },
758
+ "shouldHandle: manager does not have connection"
759
+ );
760
+ return false;
761
+ }
762
+ if (event.connectionId && event.connectionId !== connectionId) {
763
+ return false;
764
+ }
765
+ if (event.teamId === "api") {
766
+ logger.debug({ connectionId }, "shouldHandle: skipping api teamId");
767
+ return false;
768
+ }
769
+ const instance = manager.getInstance(connectionId);
770
+ if (!instance) {
771
+ logger.debug({ connectionId }, "shouldHandle: no instance found");
772
+ return false;
773
+ }
774
+ const matches = instance.connection.platform === platform;
775
+ logger.debug({ connectionId, platform, matches }, "shouldHandle: result");
776
+ if (!matches) {
777
+ logger.debug(
778
+ {
779
+ connectionId,
780
+ instancePlatform: instance.connection.platform,
781
+ eventPlatform: platform,
782
+ },
783
+ "shouldHandle: platform mismatch"
784
+ );
785
+ }
786
+ return matches;
787
+ }
788
+
789
+ async function resolveThread(
790
+ manager: ChatInstanceManager,
791
+ connectionId: string,
792
+ channelId: string,
793
+ conversationId: string
794
+ ): Promise<any | null> {
795
+ const instance = manager.getInstance(connectionId);
796
+ if (!instance) {
797
+ logger.debug({ connectionId }, "resolveThread: no instance for connection");
798
+ return null;
799
+ }
800
+
801
+ try {
802
+ const chat = instance.chat;
803
+ const adapterKey = instance.connection.platform;
804
+
805
+ // For DMs where conversationId === channelId, use channel directly
806
+ // (matches resolveTarget fallback in chat-response-bridge)
807
+ if (!conversationId || conversationId === channelId) {
808
+ const channel = chat.channel?.(`${adapterKey}:${channelId}`);
809
+ if (channel) return channel;
810
+ }
811
+
812
+ const thread = await chat.getThread?.(
813
+ adapterKey,
814
+ channelId,
815
+ conversationId
816
+ );
817
+ if (!thread) {
818
+ logger.debug(
819
+ { connectionId, adapterKey, channelId, conversationId },
820
+ "resolveThread: getThread returned null"
821
+ );
822
+ }
823
+ return thread ?? null;
824
+ } catch (error) {
825
+ logger.debug(
826
+ { connectionId, channelId, conversationId, error: String(error) },
827
+ "Failed to resolve thread for interaction"
828
+ );
829
+ return null;
830
+ }
831
+ }