@lobu/gateway 3.0.9 → 3.0.13

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 (212) hide show
  1. package/dist/api/platform.d.ts.map +1 -1
  2. package/dist/api/platform.js +7 -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/connections/chat-instance-manager.d.ts.map +1 -1
  12. package/dist/connections/chat-instance-manager.js +2 -1
  13. package/dist/connections/chat-instance-manager.js.map +1 -1
  14. package/dist/connections/interaction-bridge.d.ts +9 -2
  15. package/dist/connections/interaction-bridge.d.ts.map +1 -1
  16. package/dist/connections/interaction-bridge.js +121 -261
  17. package/dist/connections/interaction-bridge.js.map +1 -1
  18. package/dist/gateway/index.js +1 -1
  19. package/dist/gateway/index.js.map +1 -1
  20. package/dist/interactions.d.ts +9 -43
  21. package/dist/interactions.d.ts.map +1 -1
  22. package/dist/interactions.js +10 -52
  23. package/dist/interactions.js.map +1 -1
  24. package/dist/routes/public/agent.d.ts +4 -0
  25. package/dist/routes/public/agent.d.ts.map +1 -1
  26. package/dist/routes/public/agent.js +21 -0
  27. package/dist/routes/public/agent.js.map +1 -1
  28. package/dist/services/core-services.d.ts.map +1 -1
  29. package/dist/services/core-services.js +4 -0
  30. package/dist/services/core-services.js.map +1 -1
  31. package/package.json +9 -9
  32. package/src/__tests__/agent-config-routes.test.ts +0 -254
  33. package/src/__tests__/agent-history-routes.test.ts +0 -72
  34. package/src/__tests__/agent-routes.test.ts +0 -68
  35. package/src/__tests__/agent-schedules-routes.test.ts +0 -59
  36. package/src/__tests__/agent-settings-store.test.ts +0 -323
  37. package/src/__tests__/bedrock-model-catalog.test.ts +0 -40
  38. package/src/__tests__/bedrock-openai-service.test.ts +0 -157
  39. package/src/__tests__/bedrock-provider-module.test.ts +0 -56
  40. package/src/__tests__/chat-instance-manager-slack.test.ts +0 -204
  41. package/src/__tests__/chat-response-bridge.test.ts +0 -131
  42. package/src/__tests__/config-memory-plugins.test.ts +0 -92
  43. package/src/__tests__/config-request-store.test.ts +0 -127
  44. package/src/__tests__/connection-routes.test.ts +0 -144
  45. package/src/__tests__/core-services-store-selection.test.ts +0 -92
  46. package/src/__tests__/docker-deployment.test.ts +0 -1211
  47. package/src/__tests__/embedded-deployment.test.ts +0 -342
  48. package/src/__tests__/grant-store.test.ts +0 -148
  49. package/src/__tests__/http-proxy.test.ts +0 -281
  50. package/src/__tests__/instruction-service.test.ts +0 -37
  51. package/src/__tests__/link-buttons.test.ts +0 -112
  52. package/src/__tests__/lobu.test.ts +0 -32
  53. package/src/__tests__/mcp-config-service.test.ts +0 -347
  54. package/src/__tests__/mcp-proxy.test.ts +0 -694
  55. package/src/__tests__/message-handler-bridge.test.ts +0 -17
  56. package/src/__tests__/model-selection.test.ts +0 -172
  57. package/src/__tests__/oauth-templates.test.ts +0 -39
  58. package/src/__tests__/platform-adapter-slack-send.test.ts +0 -114
  59. package/src/__tests__/platform-helpers-model-resolution.test.ts +0 -253
  60. package/src/__tests__/provider-inheritance.test.ts +0 -212
  61. package/src/__tests__/routes/cli-auth.test.ts +0 -337
  62. package/src/__tests__/routes/interactions.test.ts +0 -121
  63. package/src/__tests__/secret-proxy.test.ts +0 -85
  64. package/src/__tests__/session-manager.test.ts +0 -572
  65. package/src/__tests__/setup.ts +0 -133
  66. package/src/__tests__/skill-and-mcp-registry.test.ts +0 -203
  67. package/src/__tests__/slack-routes.test.ts +0 -161
  68. package/src/__tests__/system-config-resolver.test.ts +0 -75
  69. package/src/__tests__/system-message-limiter.test.ts +0 -89
  70. package/src/__tests__/system-skills-service.test.ts +0 -362
  71. package/src/__tests__/transcription-service.test.ts +0 -222
  72. package/src/__tests__/utils/rate-limiter.test.ts +0 -102
  73. package/src/__tests__/worker-connection-manager.test.ts +0 -497
  74. package/src/__tests__/worker-job-router.test.ts +0 -722
  75. package/src/api/index.ts +0 -1
  76. package/src/api/platform.ts +0 -292
  77. package/src/api/response-renderer.ts +0 -157
  78. package/src/auth/agent-metadata-store.ts +0 -168
  79. package/src/auth/api-auth-middleware.ts +0 -69
  80. package/src/auth/api-key-provider-module.ts +0 -213
  81. package/src/auth/base-provider-module.ts +0 -201
  82. package/src/auth/bedrock/provider-module.ts +0 -110
  83. package/src/auth/chatgpt/chatgpt-oauth-module.ts +0 -185
  84. package/src/auth/chatgpt/device-code-client.ts +0 -218
  85. package/src/auth/chatgpt/index.ts +0 -1
  86. package/src/auth/claude/oauth-module.ts +0 -280
  87. package/src/auth/cli/token-service.ts +0 -249
  88. package/src/auth/external/client.ts +0 -560
  89. package/src/auth/external/device-code-client.ts +0 -235
  90. package/src/auth/mcp/config-service.ts +0 -420
  91. package/src/auth/mcp/proxy.ts +0 -1086
  92. package/src/auth/mcp/string-substitution.ts +0 -17
  93. package/src/auth/mcp/tool-cache.ts +0 -90
  94. package/src/auth/oauth/base-client.ts +0 -267
  95. package/src/auth/oauth/client.ts +0 -153
  96. package/src/auth/oauth/credentials.ts +0 -7
  97. package/src/auth/oauth/providers.ts +0 -69
  98. package/src/auth/oauth/state-store.ts +0 -150
  99. package/src/auth/oauth-templates.ts +0 -179
  100. package/src/auth/provider-catalog.ts +0 -220
  101. package/src/auth/provider-model-options.ts +0 -41
  102. package/src/auth/settings/agent-settings-store.ts +0 -565
  103. package/src/auth/settings/auth-profiles-manager.ts +0 -216
  104. package/src/auth/settings/index.ts +0 -12
  105. package/src/auth/settings/model-preference-store.ts +0 -52
  106. package/src/auth/settings/model-selection.ts +0 -135
  107. package/src/auth/settings/resolved-settings-view.ts +0 -298
  108. package/src/auth/settings/template-utils.ts +0 -44
  109. package/src/auth/settings/token-service.ts +0 -88
  110. package/src/auth/system-env-store.ts +0 -98
  111. package/src/auth/user-agents-store.ts +0 -68
  112. package/src/channels/binding-service.ts +0 -214
  113. package/src/channels/index.ts +0 -4
  114. package/src/cli/gateway.ts +0 -1312
  115. package/src/cli/index.ts +0 -74
  116. package/src/commands/built-in-commands.ts +0 -80
  117. package/src/commands/command-dispatcher.ts +0 -94
  118. package/src/commands/command-reply-adapters.ts +0 -27
  119. package/src/config/file-loader.ts +0 -618
  120. package/src/config/index.ts +0 -588
  121. package/src/config/network-allowlist.ts +0 -71
  122. package/src/connections/chat-instance-manager.ts +0 -1284
  123. package/src/connections/chat-response-bridge.ts +0 -618
  124. package/src/connections/index.ts +0 -7
  125. package/src/connections/interaction-bridge.ts +0 -831
  126. package/src/connections/message-handler-bridge.ts +0 -440
  127. package/src/connections/platform-auth-methods.ts +0 -15
  128. package/src/connections/types.ts +0 -84
  129. package/src/gateway/connection-manager.ts +0 -291
  130. package/src/gateway/index.ts +0 -698
  131. package/src/gateway/job-router.ts +0 -201
  132. package/src/gateway-main.ts +0 -200
  133. package/src/index.ts +0 -41
  134. package/src/infrastructure/queue/index.ts +0 -12
  135. package/src/infrastructure/queue/queue-producer.ts +0 -148
  136. package/src/infrastructure/queue/redis-queue.ts +0 -361
  137. package/src/infrastructure/queue/types.ts +0 -133
  138. package/src/infrastructure/redis/system-message-limiter.ts +0 -94
  139. package/src/interactions/config-request-store.ts +0 -198
  140. package/src/interactions.ts +0 -363
  141. package/src/lobu.ts +0 -311
  142. package/src/metrics/prometheus.ts +0 -159
  143. package/src/modules/module-system.ts +0 -179
  144. package/src/orchestration/base-deployment-manager.ts +0 -900
  145. package/src/orchestration/deployment-utils.ts +0 -98
  146. package/src/orchestration/impl/docker-deployment.ts +0 -620
  147. package/src/orchestration/impl/embedded-deployment.ts +0 -268
  148. package/src/orchestration/impl/index.ts +0 -8
  149. package/src/orchestration/impl/k8s/deployment.ts +0 -1061
  150. package/src/orchestration/impl/k8s/helpers.ts +0 -610
  151. package/src/orchestration/impl/k8s/index.ts +0 -1
  152. package/src/orchestration/index.ts +0 -333
  153. package/src/orchestration/message-consumer.ts +0 -584
  154. package/src/orchestration/scheduled-wakeup.ts +0 -704
  155. package/src/permissions/approval-policy.ts +0 -36
  156. package/src/permissions/grant-store.ts +0 -219
  157. package/src/platform/file-handler.ts +0 -66
  158. package/src/platform/link-buttons.ts +0 -57
  159. package/src/platform/renderer-utils.ts +0 -44
  160. package/src/platform/response-renderer.ts +0 -84
  161. package/src/platform/unified-thread-consumer.ts +0 -194
  162. package/src/platform.ts +0 -318
  163. package/src/proxy/http-proxy.ts +0 -752
  164. package/src/proxy/proxy-manager.ts +0 -81
  165. package/src/proxy/secret-proxy.ts +0 -402
  166. package/src/proxy/token-refresh-job.ts +0 -143
  167. package/src/routes/internal/audio.ts +0 -141
  168. package/src/routes/internal/device-auth.ts +0 -652
  169. package/src/routes/internal/files.ts +0 -226
  170. package/src/routes/internal/history.ts +0 -69
  171. package/src/routes/internal/images.ts +0 -127
  172. package/src/routes/internal/interactions.ts +0 -84
  173. package/src/routes/internal/middleware.ts +0 -23
  174. package/src/routes/internal/schedule.ts +0 -226
  175. package/src/routes/internal/types.ts +0 -22
  176. package/src/routes/openapi-auto.ts +0 -239
  177. package/src/routes/public/agent-access.ts +0 -23
  178. package/src/routes/public/agent-config.ts +0 -675
  179. package/src/routes/public/agent-history.ts +0 -422
  180. package/src/routes/public/agent-schedules.ts +0 -296
  181. package/src/routes/public/agent.ts +0 -1086
  182. package/src/routes/public/agents.ts +0 -373
  183. package/src/routes/public/channels.ts +0 -191
  184. package/src/routes/public/cli-auth.ts +0 -896
  185. package/src/routes/public/connections.ts +0 -574
  186. package/src/routes/public/landing.ts +0 -16
  187. package/src/routes/public/oauth.ts +0 -147
  188. package/src/routes/public/settings-auth.ts +0 -104
  189. package/src/routes/public/slack.ts +0 -173
  190. package/src/routes/shared/agent-ownership.ts +0 -101
  191. package/src/routes/shared/token-verifier.ts +0 -34
  192. package/src/services/bedrock-model-catalog.ts +0 -217
  193. package/src/services/bedrock-openai-service.ts +0 -658
  194. package/src/services/core-services.ts +0 -1072
  195. package/src/services/image-generation-service.ts +0 -257
  196. package/src/services/instruction-service.ts +0 -318
  197. package/src/services/mcp-registry.ts +0 -94
  198. package/src/services/platform-helpers.ts +0 -287
  199. package/src/services/session-manager.ts +0 -262
  200. package/src/services/settings-resolver.ts +0 -74
  201. package/src/services/system-config-resolver.ts +0 -89
  202. package/src/services/system-skills-service.ts +0 -229
  203. package/src/services/transcription-service.ts +0 -684
  204. package/src/session.ts +0 -110
  205. package/src/spaces/index.ts +0 -1
  206. package/src/spaces/space-resolver.ts +0 -17
  207. package/src/stores/in-memory-agent-store.ts +0 -403
  208. package/src/stores/redis-agent-store.ts +0 -279
  209. package/src/utils/public-url.ts +0 -44
  210. package/src/utils/rate-limiter.ts +0 -94
  211. package/tsconfig.json +0 -33
  212. package/tsconfig.tsbuildinfo +0 -1
@@ -1,618 +0,0 @@
1
- /**
2
- * Chat response bridge — handles outbound responses from workers back through Chat SDK.
3
- * Covers platform-specific markdown handling and message chunking.
4
- */
5
-
6
- import { unlink } from "node:fs/promises";
7
- import { resolve } from "node:path";
8
- import { createLogger } from "@lobu/core";
9
- import type { ThreadResponsePayload } from "../infrastructure/queue";
10
- import { extractSettingsLinkButtons } from "../platform/link-buttons";
11
- import { chunkMessage, delay } from "../platform/renderer-utils";
12
- import type { ResponseRenderer } from "../platform/response-renderer";
13
- import type { ChatInstanceManager } from "./chat-instance-manager";
14
- import { storeOutgoingHistory } from "./message-handler-bridge";
15
-
16
- const logger = createLogger("chat-response-bridge");
17
-
18
- function shouldBufferUntilCompletion(platform: string): boolean {
19
- return platform === "telegram";
20
- }
21
-
22
- const MESSAGE_CHUNK_SIZE = 4096;
23
- const CHUNK_DELAY_MS = 500;
24
-
25
- /**
26
- * Format message content for the target platform.
27
- * Keep everything inside Chat SDK's supported PostableMessage shapes.
28
- * The Telegram adapter understands markdown itself; passing `{ html: ... }`
29
- * causes Chat SDK to reject the payload after the adapter has already sent it.
30
- */
31
- function formatForPlatform(
32
- text: string,
33
- platform: string
34
- ): { markdown: string } {
35
- void platform;
36
- return { markdown: text };
37
- }
38
-
39
- /**
40
- * Streaming state for progressive message editing.
41
- */
42
- interface StreamState {
43
- buffer: string;
44
- sentMessage: any | null; // SentMessage from Chat SDK
45
- lastEditTime: number;
46
- editTimer?: NodeJS.Timeout;
47
- }
48
-
49
- const EDIT_INTERVAL_MS = 2000;
50
-
51
- interface ResponseContext {
52
- connectionId: string;
53
- instance: any;
54
- channelId: string;
55
- platform: string;
56
- }
57
-
58
- /**
59
- * ChatResponseBridge implements ResponseRenderer so it can be plugged into
60
- * the unified thread consumer alongside legacy platform renderers.
61
- */
62
- export class ChatResponseBridge implements ResponseRenderer {
63
- private streams = new Map<string, StreamState>();
64
-
65
- constructor(private manager: ChatInstanceManager) {}
66
-
67
- private extractResponseContext(
68
- payload: ThreadResponsePayload
69
- ): ResponseContext | null {
70
- const connectionId = (payload.platformMetadata as any)?.connectionId;
71
- if (!connectionId) return null;
72
-
73
- const instance = this.manager.getInstance(connectionId);
74
- if (!instance) return null;
75
-
76
- const channelId =
77
- (payload.platformMetadata as any)?.chatId ??
78
- (payload.platformMetadata as any)?.responseChannel ??
79
- payload.channelId;
80
-
81
- return {
82
- connectionId,
83
- instance,
84
- channelId,
85
- platform: instance.connection.platform,
86
- };
87
- }
88
-
89
- /**
90
- * Check if this payload belongs to a Chat SDK connection.
91
- * Returns false if the connection is not managed — the caller should fall through to legacy.
92
- */
93
- canHandle(data: ThreadResponsePayload): boolean {
94
- const connectionId = (data.platformMetadata as any)?.connectionId;
95
- return !!connectionId && this.manager.has(connectionId);
96
- }
97
-
98
- async handleDelta(
99
- payload: ThreadResponsePayload,
100
- sessionKey: string
101
- ): Promise<string | null> {
102
- void sessionKey;
103
- if (payload.delta === undefined) return null;
104
-
105
- const ctx = this.extractResponseContext(payload);
106
- if (!ctx) return null;
107
-
108
- const { connectionId, instance, channelId } = ctx;
109
- const key = `${channelId}:${payload.conversationId}`;
110
- const shouldBuffer = shouldBufferUntilCompletion(ctx.platform);
111
-
112
- let stream = this.streams.get(key);
113
-
114
- if (!stream) {
115
- if (shouldBuffer) {
116
- this.streams.set(key, {
117
- buffer: payload.delta,
118
- sentMessage: null,
119
- lastEditTime: Date.now(),
120
- });
121
- return null;
122
- }
123
-
124
- // First delta — send initial message
125
- try {
126
- const target = await this.resolveTarget(
127
- instance,
128
- channelId,
129
- payload.conversationId,
130
- (payload.platformMetadata as any)?.responseThreadId
131
- );
132
-
133
- if (target) {
134
- const sentMessage = await target.post(
135
- formatForPlatform(payload.delta, ctx.platform) as any
136
- );
137
- stream = {
138
- buffer: payload.delta,
139
- sentMessage,
140
- lastEditTime: Date.now(),
141
- };
142
- this.streams.set(key, stream);
143
- }
144
- } catch (error) {
145
- logger.warn(
146
- { connectionId, error: String(error) },
147
- "Failed to send initial delta"
148
- );
149
- // Clean up orphaned stream entry if it was set before the failure
150
- this.streams.delete(key);
151
- }
152
- return null;
153
- }
154
-
155
- // Append delta
156
- if (payload.isFullReplacement) {
157
- stream.buffer = payload.delta;
158
- } else {
159
- stream.buffer += payload.delta;
160
- }
161
-
162
- if (shouldBuffer) {
163
- return null;
164
- }
165
-
166
- // Throttle edits
167
- const now = Date.now();
168
- if (now - stream.lastEditTime >= EDIT_INTERVAL_MS) {
169
- await this.editStreamMessage(stream, connectionId, ctx.platform);
170
- } else if (!stream.editTimer) {
171
- stream.editTimer = setTimeout(
172
- async () => {
173
- // Guard against race: stream may have been deleted by handleCompletion
174
- // between when this timer was scheduled and when it fires.
175
- const current = this.streams.get(key);
176
- if (!current) return;
177
- current.editTimer = undefined;
178
- await this.editStreamMessage(current, connectionId, ctx.platform);
179
- },
180
- EDIT_INTERVAL_MS - (now - stream.lastEditTime)
181
- );
182
- }
183
-
184
- return null;
185
- }
186
-
187
- async handleCompletion(
188
- payload: ThreadResponsePayload,
189
- _sessionKey: string
190
- ): Promise<void> {
191
- const ctx = this.extractResponseContext(payload);
192
- if (!ctx) return;
193
-
194
- const { connectionId, instance, channelId } = ctx;
195
- const key = `${channelId}:${payload.conversationId}`;
196
-
197
- const stream = this.streams.get(key);
198
- if (stream) {
199
- // Clear edit timer before deleting to prevent stale timer callbacks
200
- if (stream.editTimer) {
201
- clearTimeout(stream.editTimer);
202
- stream.editTimer = undefined;
203
- }
204
-
205
- if (stream.buffer.trim()) {
206
- await this.sendFinalMessage(
207
- stream,
208
- instance,
209
- channelId,
210
- payload.conversationId,
211
- connectionId,
212
- (payload.platformMetadata as any)?.responseThreadId
213
- );
214
- }
215
-
216
- this.streams.delete(key);
217
- }
218
-
219
- // Gap 1: Store outgoing response in history
220
- if (stream?.buffer.trim()) {
221
- const redis = this.manager.getServices().getQueue().getRedisClient();
222
- await storeOutgoingHistory(redis, connectionId, channelId, stream.buffer);
223
- }
224
-
225
- // Session reset: clear Redis history and delete session file
226
- if ((payload.platformMetadata as any)?.sessionReset) {
227
- const agentId = (payload.platformMetadata as any)?.agentId;
228
- try {
229
- const redis = this.manager.getServices().getQueue().getRedisClient();
230
- await redis.del(`chat:history:${connectionId}:${channelId}`);
231
- logger.info(
232
- { connectionId, channelId },
233
- "Cleared chat history for session reset"
234
- );
235
- } catch (error) {
236
- logger.warn(
237
- { error: String(error) },
238
- "Failed to clear chat history on session reset"
239
- );
240
- }
241
- if (agentId) {
242
- try {
243
- const sessionPath = resolve(
244
- "workspaces",
245
- agentId,
246
- ".openclaw",
247
- "session.jsonl"
248
- );
249
- await unlink(sessionPath);
250
- logger.info(
251
- { agentId, sessionPath },
252
- "Deleted session file for session reset"
253
- );
254
- } catch (error) {
255
- // File may not exist — that's fine
256
- logger.debug(
257
- { agentId, error: String(error) },
258
- "No session file to delete on reset"
259
- );
260
- }
261
- }
262
- }
263
-
264
- logger.info(
265
- {
266
- connectionId,
267
- channelId,
268
- conversationId: payload.conversationId,
269
- },
270
- "Response completed via Chat SDK bridge"
271
- );
272
- }
273
-
274
- async handleError(
275
- payload: ThreadResponsePayload,
276
- _sessionKey: string
277
- ): Promise<void> {
278
- if (!payload.error) return;
279
-
280
- const ctx = this.extractResponseContext(payload);
281
- if (!ctx) return;
282
-
283
- const { connectionId, instance, channelId } = ctx;
284
- const key = `${channelId}:${payload.conversationId}`;
285
-
286
- // Clean up stream
287
- const stream = this.streams.get(key);
288
- if (stream?.editTimer) clearTimeout(stream.editTimer);
289
- this.streams.delete(key);
290
-
291
- // For known error codes, render user-facing guidance without sending users
292
- // to the retired end-user settings UI.
293
- if (payload.errorCode === "NO_MODEL_CONFIGURED") {
294
- payload.error =
295
- "No model configured. Provider setup is not available in the end-user chat flow yet. Ask an admin to connect a provider for the base agent.";
296
- }
297
-
298
- // Fallback: plain text error via Chat SDK
299
- try {
300
- const target = await this.resolveTarget(
301
- instance,
302
- channelId,
303
- payload.conversationId,
304
- (payload.platformMetadata as any)?.responseThreadId
305
- );
306
- if (target) {
307
- await target.post(`Error: ${payload.error}`);
308
- }
309
- } catch (error) {
310
- logger.error(
311
- { connectionId, error: String(error) },
312
- "Failed to send error message"
313
- );
314
- }
315
- }
316
-
317
- async handleStatusUpdate(payload: ThreadResponsePayload): Promise<void> {
318
- const ctx = this.extractResponseContext(payload);
319
- if (!ctx) return;
320
-
321
- const { instance, channelId } = ctx;
322
-
323
- // Show typing indicator
324
- try {
325
- const target = await this.resolveTarget(
326
- instance,
327
- channelId,
328
- payload.conversationId,
329
- (payload.platformMetadata as any)?.responseThreadId
330
- );
331
- if (target) {
332
- await target.startTyping?.("Processing...");
333
- }
334
- } catch {
335
- // best effort
336
- }
337
- }
338
-
339
- async handleEphemeral(payload: ThreadResponsePayload): Promise<void> {
340
- if (!payload.content) return;
341
-
342
- const ctx = this.extractResponseContext(payload);
343
- if (!ctx) return;
344
-
345
- const { connectionId, instance, channelId } = ctx;
346
-
347
- try {
348
- const target = await this.resolveTarget(
349
- instance,
350
- channelId,
351
- payload.conversationId,
352
- (payload.platformMetadata as any)?.responseThreadId
353
- );
354
- if (target) {
355
- const { processedContent, linkButtons } = extractSettingsLinkButtons(
356
- payload.content
357
- );
358
-
359
- if (linkButtons.length > 0) {
360
- try {
361
- const { Actions, Card, CardText, LinkButton } = await import(
362
- "chat"
363
- );
364
- const card = Card({
365
- children: [
366
- CardText(processedContent),
367
- Actions(
368
- linkButtons.map((button) =>
369
- LinkButton({ url: button.url, label: button.text })
370
- )
371
- ),
372
- ],
373
- });
374
- await target.post({
375
- card,
376
- fallbackText: `${processedContent}\n\n${linkButtons.map((button) => `${button.text}: ${button.url}`).join("\n")}`,
377
- });
378
- return;
379
- } catch (error) {
380
- logger.warn(
381
- { connectionId, error: String(error) },
382
- "Failed to render ephemeral settings button"
383
- );
384
- const fallbackText = `${processedContent}\n\n${linkButtons.map((button) => `${button.text}: ${button.url}`).join("\n")}`;
385
- await target.post(fallbackText.trim());
386
- return;
387
- }
388
- }
389
-
390
- await target.post(processedContent);
391
- }
392
- } catch (error) {
393
- logger.error(
394
- { connectionId, error: String(error) },
395
- "Failed to send ephemeral message"
396
- );
397
- }
398
- }
399
-
400
- // --- Private ---
401
-
402
- private async editStreamMessage(
403
- stream: StreamState,
404
- connectionId: string,
405
- platform = ""
406
- ): Promise<void> {
407
- if (!stream.sentMessage?.edit) return;
408
- try {
409
- await stream.sentMessage.edit(
410
- formatForPlatform(stream.buffer, platform) as any
411
- );
412
- stream.lastEditTime = Date.now();
413
- } catch (error) {
414
- logger.debug(
415
- { connectionId, error: String(error) },
416
- "Failed to edit stream message"
417
- );
418
- }
419
- }
420
-
421
- private async sendFinalMessage(
422
- stream: StreamState,
423
- instance: any,
424
- channelId: string,
425
- conversationId: string,
426
- connectionId: string,
427
- responseThreadId?: string
428
- ): Promise<void> {
429
- const shouldBuffer = shouldBufferUntilCompletion(
430
- instance.connection.platform
431
- );
432
- const target = await this.resolveTarget(
433
- instance,
434
- channelId,
435
- conversationId,
436
- responseThreadId
437
- );
438
- if (!target) {
439
- logger.warn(
440
- {
441
- connectionId,
442
- channelId,
443
- conversationId,
444
- platform: instance.connection.platform,
445
- },
446
- "resolveTarget returned null — response will not be delivered"
447
- );
448
- return;
449
- }
450
-
451
- logger.info(
452
- {
453
- connectionId,
454
- channelId,
455
- platform: instance.connection.platform,
456
- bufferLength: stream.buffer.length,
457
- shouldBuffer,
458
- },
459
- "sendFinalMessage: about to post"
460
- );
461
-
462
- const platform = instance.connection.platform;
463
-
464
- if (stream.buffer.length <= MESSAGE_CHUNK_SIZE) {
465
- try {
466
- if (!shouldBuffer && stream.sentMessage?.edit) {
467
- await stream.sentMessage.edit(
468
- formatForPlatform(stream.buffer, platform) as any
469
- );
470
- } else {
471
- const result = await target.post(
472
- formatForPlatform(stream.buffer, platform) as any
473
- );
474
- logger.info(
475
- {
476
- connectionId,
477
- channelId,
478
- resultId: result?.id,
479
- resultThreadId: result?.threadId,
480
- },
481
- "sendFinalMessage: post succeeded"
482
- );
483
- }
484
- } catch (error) {
485
- logger.warn(
486
- { connectionId, error: String(error) },
487
- "Failed final message send/edit"
488
- );
489
- // Retry as plain text (no markdown) so the user still sees the response
490
- try {
491
- if (!shouldBuffer && stream.sentMessage?.edit) {
492
- await stream.sentMessage.edit(stream.buffer);
493
- } else {
494
- await target.post(stream.buffer);
495
- }
496
- logger.info(
497
- { connectionId, channelId },
498
- "sendFinalMessage: plain-text fallback succeeded"
499
- );
500
- } catch {
501
- // give up
502
- }
503
- }
504
- return;
505
- }
506
-
507
- const chunks = chunkMessage(stream.buffer, MESSAGE_CHUNK_SIZE);
508
- if (chunks.length === 0) return;
509
- const [firstChunk, ...remainingChunks] = chunks;
510
- if (!firstChunk) return;
511
-
512
- try {
513
- if (!shouldBuffer && stream.sentMessage?.edit) {
514
- await stream.sentMessage.edit(
515
- formatForPlatform(firstChunk, platform) as any
516
- );
517
- } else {
518
- await target.post(formatForPlatform(firstChunk, platform) as any);
519
- }
520
- } catch (error) {
521
- logger.debug(
522
- { connectionId, error: String(error) },
523
- "Failed to send first final chunk"
524
- );
525
- try {
526
- if (!shouldBuffer && stream.sentMessage?.edit) {
527
- await stream.sentMessage.edit(firstChunk);
528
- } else {
529
- await target.post(firstChunk);
530
- }
531
- } catch {
532
- // give up on first chunk
533
- }
534
- }
535
-
536
- for (let i = 0; i < remainingChunks.length; i++) {
537
- const chunk = remainingChunks[i]!;
538
- try {
539
- await target.post(formatForPlatform(chunk, platform) as any);
540
- } catch (error) {
541
- logger.debug(
542
- { connectionId, error: String(error) },
543
- "Failed to send chunk"
544
- );
545
- try {
546
- await target.post(chunk);
547
- } catch {
548
- // give up on this chunk
549
- }
550
- }
551
- if (i < remainingChunks.length - 1) {
552
- await delay(CHUNK_DELAY_MS);
553
- }
554
- }
555
- }
556
-
557
- private async resolveTarget(
558
- instance: any,
559
- channelId: string,
560
- conversationId?: string,
561
- responseThreadId?: string
562
- ): Promise<any | null> {
563
- const platform = instance.connection.platform;
564
- const chat = instance.chat;
565
-
566
- // If we have a full thread ID (e.g. telegram:{chatId}:{topicId}), use
567
- // createThread so the response lands in the correct forum topic.
568
- if (responseThreadId) {
569
- const adapter = chat.getAdapter?.(platform);
570
- const createThread = (chat as any).createThread;
571
- if (adapter && typeof createThread === "function") {
572
- try {
573
- const thread = await createThread.call(
574
- chat,
575
- adapter,
576
- responseThreadId,
577
- {},
578
- false
579
- );
580
- if (thread) return thread;
581
- } catch (error) {
582
- logger.debug(
583
- { platform, responseThreadId, error: String(error) },
584
- "createThread from responseThreadId failed, falling back"
585
- );
586
- }
587
- }
588
- }
589
-
590
- if (!conversationId || conversationId === channelId) {
591
- const channelKey = `${platform}:${channelId}`;
592
- const channel = chat.channel?.(channelKey);
593
- if (channel) {
594
- return channel;
595
- }
596
- logger.warn(
597
- {
598
- platform,
599
- channelId,
600
- channelKey,
601
- conversationId,
602
- hasChannelFn: !!chat.channel,
603
- },
604
- "chat.channel() returned null for DM"
605
- );
606
- }
607
-
608
- const thread =
609
- (await chat.getThread?.(platform, channelId, conversationId)) ?? null;
610
- if (!thread) {
611
- logger.warn(
612
- { platform, channelId, conversationId, hasGetThread: !!chat.getThread },
613
- "chat.getThread() also returned null"
614
- );
615
- }
616
- return thread;
617
- }
618
- }
@@ -1,7 +0,0 @@
1
- export { ChatInstanceManager } from "./chat-instance-manager";
2
- export { ChatResponseBridge } from "./chat-response-bridge";
3
- export type {
4
- ConnectionSettings,
5
- PlatformAdapterConfig,
6
- PlatformConnection,
7
- } from "./types";