@lobu/gateway 3.0.5 → 3.0.7

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,618 @@
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
+ }
@@ -0,0 +1,7 @@
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";