@lobu/gateway 3.0.8 → 3.0.12

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 (219) hide show
  1. package/dist/api/platform.d.ts.map +1 -1
  2. package/dist/api/platform.js +8 -26
  3. package/dist/api/platform.js.map +1 -1
  4. package/dist/auth/mcp/proxy.d.ts +14 -0
  5. package/dist/auth/mcp/proxy.d.ts.map +1 -1
  6. package/dist/auth/mcp/proxy.js +149 -13
  7. package/dist/auth/mcp/proxy.js.map +1 -1
  8. package/dist/cli/gateway.d.ts.map +1 -1
  9. package/dist/cli/gateway.js +29 -0
  10. package/dist/cli/gateway.js.map +1 -1
  11. package/dist/cli/index.js +2 -2
  12. package/dist/cli/index.js.map +1 -1
  13. package/dist/connections/chat-instance-manager.d.ts.map +1 -1
  14. package/dist/connections/chat-instance-manager.js +2 -1
  15. package/dist/connections/chat-instance-manager.js.map +1 -1
  16. package/dist/connections/interaction-bridge.d.ts +9 -2
  17. package/dist/connections/interaction-bridge.d.ts.map +1 -1
  18. package/dist/connections/interaction-bridge.js +132 -230
  19. package/dist/connections/interaction-bridge.js.map +1 -1
  20. package/dist/connections/message-handler-bridge.d.ts.map +1 -1
  21. package/dist/connections/message-handler-bridge.js +44 -26
  22. package/dist/connections/message-handler-bridge.js.map +1 -1
  23. package/dist/interactions.d.ts +9 -43
  24. package/dist/interactions.d.ts.map +1 -1
  25. package/dist/interactions.js +10 -52
  26. package/dist/interactions.js.map +1 -1
  27. package/dist/orchestration/base-deployment-manager.js +7 -7
  28. package/dist/orchestration/base-deployment-manager.js.map +1 -1
  29. package/dist/platform/unified-thread-consumer.d.ts.map +1 -1
  30. package/dist/platform/unified-thread-consumer.js +38 -34
  31. package/dist/platform/unified-thread-consumer.js.map +1 -1
  32. package/dist/routes/public/agent.d.ts +4 -0
  33. package/dist/routes/public/agent.d.ts.map +1 -1
  34. package/dist/routes/public/agent.js +21 -0
  35. package/dist/routes/public/agent.js.map +1 -1
  36. package/dist/services/core-services.d.ts.map +1 -1
  37. package/dist/services/core-services.js +4 -0
  38. package/dist/services/core-services.js.map +1 -1
  39. package/package.json +2 -2
  40. package/src/__tests__/agent-config-routes.test.ts +0 -254
  41. package/src/__tests__/agent-history-routes.test.ts +0 -72
  42. package/src/__tests__/agent-routes.test.ts +0 -68
  43. package/src/__tests__/agent-schedules-routes.test.ts +0 -59
  44. package/src/__tests__/agent-settings-store.test.ts +0 -323
  45. package/src/__tests__/bedrock-model-catalog.test.ts +0 -40
  46. package/src/__tests__/bedrock-openai-service.test.ts +0 -157
  47. package/src/__tests__/bedrock-provider-module.test.ts +0 -56
  48. package/src/__tests__/chat-instance-manager-slack.test.ts +0 -204
  49. package/src/__tests__/chat-response-bridge.test.ts +0 -131
  50. package/src/__tests__/config-memory-plugins.test.ts +0 -92
  51. package/src/__tests__/config-request-store.test.ts +0 -127
  52. package/src/__tests__/connection-routes.test.ts +0 -144
  53. package/src/__tests__/core-services-store-selection.test.ts +0 -92
  54. package/src/__tests__/docker-deployment.test.ts +0 -1211
  55. package/src/__tests__/embedded-deployment.test.ts +0 -342
  56. package/src/__tests__/grant-store.test.ts +0 -148
  57. package/src/__tests__/http-proxy.test.ts +0 -281
  58. package/src/__tests__/instruction-service.test.ts +0 -37
  59. package/src/__tests__/link-buttons.test.ts +0 -112
  60. package/src/__tests__/lobu.test.ts +0 -32
  61. package/src/__tests__/mcp-config-service.test.ts +0 -347
  62. package/src/__tests__/mcp-proxy.test.ts +0 -694
  63. package/src/__tests__/message-handler-bridge.test.ts +0 -17
  64. package/src/__tests__/model-selection.test.ts +0 -172
  65. package/src/__tests__/oauth-templates.test.ts +0 -39
  66. package/src/__tests__/platform-adapter-slack-send.test.ts +0 -114
  67. package/src/__tests__/platform-helpers-model-resolution.test.ts +0 -253
  68. package/src/__tests__/provider-inheritance.test.ts +0 -212
  69. package/src/__tests__/routes/cli-auth.test.ts +0 -337
  70. package/src/__tests__/routes/interactions.test.ts +0 -121
  71. package/src/__tests__/secret-proxy.test.ts +0 -85
  72. package/src/__tests__/session-manager.test.ts +0 -572
  73. package/src/__tests__/setup.ts +0 -133
  74. package/src/__tests__/skill-and-mcp-registry.test.ts +0 -203
  75. package/src/__tests__/slack-routes.test.ts +0 -161
  76. package/src/__tests__/system-config-resolver.test.ts +0 -75
  77. package/src/__tests__/system-message-limiter.test.ts +0 -89
  78. package/src/__tests__/system-skills-service.test.ts +0 -362
  79. package/src/__tests__/transcription-service.test.ts +0 -222
  80. package/src/__tests__/utils/rate-limiter.test.ts +0 -102
  81. package/src/__tests__/worker-connection-manager.test.ts +0 -497
  82. package/src/__tests__/worker-job-router.test.ts +0 -722
  83. package/src/api/index.ts +0 -1
  84. package/src/api/platform.ts +0 -292
  85. package/src/api/response-renderer.ts +0 -157
  86. package/src/auth/agent-metadata-store.ts +0 -168
  87. package/src/auth/api-auth-middleware.ts +0 -69
  88. package/src/auth/api-key-provider-module.ts +0 -213
  89. package/src/auth/base-provider-module.ts +0 -201
  90. package/src/auth/bedrock/provider-module.ts +0 -110
  91. package/src/auth/chatgpt/chatgpt-oauth-module.ts +0 -185
  92. package/src/auth/chatgpt/device-code-client.ts +0 -218
  93. package/src/auth/chatgpt/index.ts +0 -1
  94. package/src/auth/claude/oauth-module.ts +0 -280
  95. package/src/auth/cli/token-service.ts +0 -249
  96. package/src/auth/external/client.ts +0 -560
  97. package/src/auth/external/device-code-client.ts +0 -235
  98. package/src/auth/mcp/config-service.ts +0 -420
  99. package/src/auth/mcp/proxy.ts +0 -1086
  100. package/src/auth/mcp/string-substitution.ts +0 -17
  101. package/src/auth/mcp/tool-cache.ts +0 -90
  102. package/src/auth/oauth/base-client.ts +0 -267
  103. package/src/auth/oauth/client.ts +0 -153
  104. package/src/auth/oauth/credentials.ts +0 -7
  105. package/src/auth/oauth/providers.ts +0 -69
  106. package/src/auth/oauth/state-store.ts +0 -150
  107. package/src/auth/oauth-templates.ts +0 -179
  108. package/src/auth/provider-catalog.ts +0 -220
  109. package/src/auth/provider-model-options.ts +0 -41
  110. package/src/auth/settings/agent-settings-store.ts +0 -565
  111. package/src/auth/settings/auth-profiles-manager.ts +0 -216
  112. package/src/auth/settings/index.ts +0 -12
  113. package/src/auth/settings/model-preference-store.ts +0 -52
  114. package/src/auth/settings/model-selection.ts +0 -135
  115. package/src/auth/settings/resolved-settings-view.ts +0 -298
  116. package/src/auth/settings/template-utils.ts +0 -44
  117. package/src/auth/settings/token-service.ts +0 -88
  118. package/src/auth/system-env-store.ts +0 -98
  119. package/src/auth/user-agents-store.ts +0 -68
  120. package/src/channels/binding-service.ts +0 -214
  121. package/src/channels/index.ts +0 -4
  122. package/src/cli/gateway.ts +0 -1312
  123. package/src/cli/index.ts +0 -74
  124. package/src/commands/built-in-commands.ts +0 -80
  125. package/src/commands/command-dispatcher.ts +0 -94
  126. package/src/commands/command-reply-adapters.ts +0 -27
  127. package/src/config/file-loader.ts +0 -618
  128. package/src/config/index.ts +0 -588
  129. package/src/config/network-allowlist.ts +0 -71
  130. package/src/connections/chat-instance-manager.ts +0 -1284
  131. package/src/connections/chat-response-bridge.ts +0 -618
  132. package/src/connections/index.ts +0 -7
  133. package/src/connections/interaction-bridge.ts +0 -831
  134. package/src/connections/message-handler-bridge.ts +0 -415
  135. package/src/connections/platform-auth-methods.ts +0 -15
  136. package/src/connections/types.ts +0 -84
  137. package/src/gateway/connection-manager.ts +0 -291
  138. package/src/gateway/index.ts +0 -698
  139. package/src/gateway/job-router.ts +0 -201
  140. package/src/gateway-main.ts +0 -200
  141. package/src/index.ts +0 -41
  142. package/src/infrastructure/queue/index.ts +0 -12
  143. package/src/infrastructure/queue/queue-producer.ts +0 -148
  144. package/src/infrastructure/queue/redis-queue.ts +0 -361
  145. package/src/infrastructure/queue/types.ts +0 -133
  146. package/src/infrastructure/redis/system-message-limiter.ts +0 -94
  147. package/src/interactions/config-request-store.ts +0 -198
  148. package/src/interactions.ts +0 -363
  149. package/src/lobu.ts +0 -311
  150. package/src/metrics/prometheus.ts +0 -159
  151. package/src/modules/module-system.ts +0 -179
  152. package/src/orchestration/base-deployment-manager.ts +0 -900
  153. package/src/orchestration/deployment-utils.ts +0 -98
  154. package/src/orchestration/impl/docker-deployment.ts +0 -620
  155. package/src/orchestration/impl/embedded-deployment.ts +0 -268
  156. package/src/orchestration/impl/index.ts +0 -8
  157. package/src/orchestration/impl/k8s/deployment.ts +0 -1061
  158. package/src/orchestration/impl/k8s/helpers.ts +0 -610
  159. package/src/orchestration/impl/k8s/index.ts +0 -1
  160. package/src/orchestration/index.ts +0 -333
  161. package/src/orchestration/message-consumer.ts +0 -584
  162. package/src/orchestration/scheduled-wakeup.ts +0 -704
  163. package/src/permissions/approval-policy.ts +0 -36
  164. package/src/permissions/grant-store.ts +0 -219
  165. package/src/platform/file-handler.ts +0 -66
  166. package/src/platform/link-buttons.ts +0 -57
  167. package/src/platform/renderer-utils.ts +0 -44
  168. package/src/platform/response-renderer.ts +0 -84
  169. package/src/platform/unified-thread-consumer.ts +0 -187
  170. package/src/platform.ts +0 -318
  171. package/src/proxy/http-proxy.ts +0 -752
  172. package/src/proxy/proxy-manager.ts +0 -81
  173. package/src/proxy/secret-proxy.ts +0 -402
  174. package/src/proxy/token-refresh-job.ts +0 -143
  175. package/src/routes/internal/audio.ts +0 -141
  176. package/src/routes/internal/device-auth.ts +0 -652
  177. package/src/routes/internal/files.ts +0 -226
  178. package/src/routes/internal/history.ts +0 -69
  179. package/src/routes/internal/images.ts +0 -127
  180. package/src/routes/internal/interactions.ts +0 -84
  181. package/src/routes/internal/middleware.ts +0 -23
  182. package/src/routes/internal/schedule.ts +0 -226
  183. package/src/routes/internal/types.ts +0 -22
  184. package/src/routes/openapi-auto.ts +0 -239
  185. package/src/routes/public/agent-access.ts +0 -23
  186. package/src/routes/public/agent-config.ts +0 -675
  187. package/src/routes/public/agent-history.ts +0 -422
  188. package/src/routes/public/agent-schedules.ts +0 -296
  189. package/src/routes/public/agent.ts +0 -1086
  190. package/src/routes/public/agents.ts +0 -373
  191. package/src/routes/public/channels.ts +0 -191
  192. package/src/routes/public/cli-auth.ts +0 -896
  193. package/src/routes/public/connections.ts +0 -574
  194. package/src/routes/public/landing.ts +0 -16
  195. package/src/routes/public/oauth.ts +0 -147
  196. package/src/routes/public/settings-auth.ts +0 -104
  197. package/src/routes/public/slack.ts +0 -173
  198. package/src/routes/shared/agent-ownership.ts +0 -101
  199. package/src/routes/shared/token-verifier.ts +0 -34
  200. package/src/services/bedrock-model-catalog.ts +0 -217
  201. package/src/services/bedrock-openai-service.ts +0 -658
  202. package/src/services/core-services.ts +0 -1072
  203. package/src/services/image-generation-service.ts +0 -257
  204. package/src/services/instruction-service.ts +0 -318
  205. package/src/services/mcp-registry.ts +0 -94
  206. package/src/services/platform-helpers.ts +0 -287
  207. package/src/services/session-manager.ts +0 -262
  208. package/src/services/settings-resolver.ts +0 -74
  209. package/src/services/system-config-resolver.ts +0 -89
  210. package/src/services/system-skills-service.ts +0 -229
  211. package/src/services/transcription-service.ts +0 -684
  212. package/src/session.ts +0 -110
  213. package/src/spaces/index.ts +0 -1
  214. package/src/spaces/space-resolver.ts +0 -17
  215. package/src/stores/in-memory-agent-store.ts +0 -403
  216. package/src/stores/redis-agent-store.ts +0 -279
  217. package/src/utils/public-url.ts +0 -44
  218. package/src/utils/rate-limiter.ts +0 -94
  219. package/tsconfig.json +0 -33
@@ -1,831 +0,0 @@
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
- }