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