@lobu/gateway 2.8.0 → 3.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/__tests__/agent-config-routes.test.ts +254 -0
- package/src/__tests__/agent-history-routes.test.ts +72 -0
- package/src/__tests__/agent-routes.test.ts +68 -0
- package/src/__tests__/agent-schedules-routes.test.ts +59 -0
- package/src/__tests__/agent-settings-store.test.ts +323 -0
- package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
- package/src/__tests__/chat-response-bridge.test.ts +131 -0
- package/src/__tests__/config-memory-plugins.test.ts +92 -0
- package/src/__tests__/config-request-store.test.ts +127 -0
- package/src/__tests__/connection-routes.test.ts +144 -0
- package/src/__tests__/core-services-store-selection.test.ts +92 -0
- package/src/__tests__/docker-deployment.test.ts +1211 -0
- package/src/__tests__/embedded-deployment.test.ts +342 -0
- package/src/__tests__/grant-store.test.ts +148 -0
- package/src/__tests__/http-proxy.test.ts +281 -0
- package/src/__tests__/instruction-service.test.ts +37 -0
- package/src/__tests__/link-buttons.test.ts +112 -0
- package/src/__tests__/lobu.test.ts +32 -0
- package/src/__tests__/mcp-config-service.test.ts +347 -0
- package/src/__tests__/mcp-proxy.test.ts +696 -0
- package/src/__tests__/message-handler-bridge.test.ts +17 -0
- package/src/__tests__/model-selection.test.ts +172 -0
- package/src/__tests__/oauth-templates.test.ts +39 -0
- package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
- package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
- package/src/__tests__/provider-inheritance.test.ts +212 -0
- package/src/__tests__/routes/cli-auth.test.ts +337 -0
- package/src/__tests__/routes/interactions.test.ts +121 -0
- package/src/__tests__/secret-proxy.test.ts +85 -0
- package/src/__tests__/session-manager.test.ts +572 -0
- package/src/__tests__/setup.ts +133 -0
- package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
- package/src/__tests__/slack-routes.test.ts +161 -0
- package/src/__tests__/system-config-resolver.test.ts +75 -0
- package/src/__tests__/system-message-limiter.test.ts +89 -0
- package/src/__tests__/system-skills-service.test.ts +362 -0
- package/src/__tests__/transcription-service.test.ts +222 -0
- package/src/__tests__/utils/rate-limiter.test.ts +102 -0
- package/src/__tests__/worker-connection-manager.test.ts +497 -0
- package/src/__tests__/worker-job-router.test.ts +722 -0
- package/src/api/index.ts +1 -0
- package/src/api/platform.ts +292 -0
- package/src/api/response-renderer.ts +157 -0
- package/src/auth/agent-metadata-store.ts +168 -0
- package/src/auth/api-auth-middleware.ts +69 -0
- package/src/auth/api-key-provider-module.ts +213 -0
- package/src/auth/base-provider-module.ts +201 -0
- package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
- package/src/auth/chatgpt/device-code-client.ts +218 -0
- package/src/auth/chatgpt/index.ts +1 -0
- package/src/auth/claude/oauth-module.ts +280 -0
- package/src/auth/cli/token-service.ts +249 -0
- package/src/auth/external/client.ts +560 -0
- package/src/auth/external/device-code-client.ts +225 -0
- package/src/auth/mcp/config-service.ts +392 -0
- package/src/auth/mcp/proxy.ts +1088 -0
- package/src/auth/mcp/string-substitution.ts +17 -0
- package/src/auth/mcp/tool-cache.ts +90 -0
- package/src/auth/oauth/base-client.ts +267 -0
- package/src/auth/oauth/client.ts +153 -0
- package/src/auth/oauth/credentials.ts +7 -0
- package/src/auth/oauth/providers.ts +69 -0
- package/src/auth/oauth/state-store.ts +150 -0
- package/src/auth/oauth-templates.ts +179 -0
- package/src/auth/provider-catalog.ts +220 -0
- package/src/auth/provider-model-options.ts +41 -0
- package/src/auth/settings/agent-settings-store.ts +565 -0
- package/src/auth/settings/auth-profiles-manager.ts +216 -0
- package/src/auth/settings/index.ts +12 -0
- package/src/auth/settings/model-preference-store.ts +52 -0
- package/src/auth/settings/model-selection.ts +135 -0
- package/src/auth/settings/resolved-settings-view.ts +298 -0
- package/src/auth/settings/template-utils.ts +44 -0
- package/src/auth/settings/token-service.ts +88 -0
- package/src/auth/system-env-store.ts +98 -0
- package/src/auth/user-agents-store.ts +68 -0
- package/src/channels/binding-service.ts +214 -0
- package/src/channels/index.ts +4 -0
- package/src/cli/gateway.ts +1304 -0
- package/src/cli/index.ts +74 -0
- package/src/commands/built-in-commands.ts +80 -0
- package/src/commands/command-dispatcher.ts +94 -0
- package/src/commands/command-reply-adapters.ts +27 -0
- package/src/config/file-loader.ts +618 -0
- package/src/config/index.ts +588 -0
- package/src/config/network-allowlist.ts +71 -0
- package/src/connections/chat-instance-manager.ts +1284 -0
- package/src/connections/chat-response-bridge.ts +618 -0
- package/src/connections/index.ts +7 -0
- package/src/connections/interaction-bridge.ts +831 -0
- package/src/connections/message-handler-bridge.ts +415 -0
- package/src/connections/platform-auth-methods.ts +15 -0
- package/src/connections/types.ts +84 -0
- package/src/gateway/connection-manager.ts +291 -0
- package/src/gateway/index.ts +700 -0
- package/src/gateway/job-router.ts +201 -0
- package/src/gateway-main.ts +200 -0
- package/src/index.ts +41 -0
- package/src/infrastructure/queue/index.ts +12 -0
- package/src/infrastructure/queue/queue-producer.ts +148 -0
- package/src/infrastructure/queue/redis-queue.ts +361 -0
- package/src/infrastructure/queue/types.ts +133 -0
- package/src/infrastructure/redis/system-message-limiter.ts +94 -0
- package/src/interactions/config-request-store.ts +198 -0
- package/src/interactions.ts +363 -0
- package/src/lobu.ts +311 -0
- package/src/metrics/prometheus.ts +159 -0
- package/src/modules/module-system.ts +179 -0
- package/src/orchestration/base-deployment-manager.ts +900 -0
- package/src/orchestration/deployment-utils.ts +98 -0
- package/src/orchestration/impl/docker-deployment.ts +620 -0
- package/src/orchestration/impl/embedded-deployment.ts +268 -0
- package/src/orchestration/impl/index.ts +8 -0
- package/src/orchestration/impl/k8s/deployment.ts +1061 -0
- package/src/orchestration/impl/k8s/helpers.ts +610 -0
- package/src/orchestration/impl/k8s/index.ts +1 -0
- package/src/orchestration/index.ts +333 -0
- package/src/orchestration/message-consumer.ts +584 -0
- package/src/orchestration/scheduled-wakeup.ts +704 -0
- package/src/permissions/approval-policy.ts +36 -0
- package/src/permissions/grant-store.ts +219 -0
- package/src/platform/file-handler.ts +66 -0
- package/src/platform/link-buttons.ts +57 -0
- package/src/platform/renderer-utils.ts +44 -0
- package/src/platform/response-renderer.ts +84 -0
- package/src/platform/unified-thread-consumer.ts +187 -0
- package/src/platform.ts +318 -0
- package/src/proxy/http-proxy.ts +752 -0
- package/src/proxy/proxy-manager.ts +81 -0
- package/src/proxy/secret-proxy.ts +402 -0
- package/src/proxy/token-refresh-job.ts +143 -0
- package/src/routes/internal/audio.ts +141 -0
- package/src/routes/internal/device-auth.ts +566 -0
- package/src/routes/internal/files.ts +226 -0
- package/src/routes/internal/history.ts +69 -0
- package/src/routes/internal/images.ts +127 -0
- package/src/routes/internal/interactions.ts +84 -0
- package/src/routes/internal/middleware.ts +23 -0
- package/src/routes/internal/schedule.ts +226 -0
- package/src/routes/internal/types.ts +22 -0
- package/src/routes/openapi-auto.ts +239 -0
- package/src/routes/public/agent-access.ts +23 -0
- package/src/routes/public/agent-config.ts +675 -0
- package/src/routes/public/agent-history.ts +422 -0
- package/src/routes/public/agent-schedules.ts +296 -0
- package/src/routes/public/agent.ts +1086 -0
- package/src/routes/public/agents.ts +373 -0
- package/src/routes/public/channels.ts +191 -0
- package/src/routes/public/cli-auth.ts +883 -0
- package/src/routes/public/connections.ts +574 -0
- package/src/routes/public/landing.ts +16 -0
- package/src/routes/public/oauth.ts +147 -0
- package/src/routes/public/settings-auth.ts +104 -0
- package/src/routes/public/slack.ts +173 -0
- package/src/routes/shared/agent-ownership.ts +101 -0
- package/src/routes/shared/token-verifier.ts +34 -0
- package/src/services/core-services.ts +1053 -0
- package/src/services/image-generation-service.ts +257 -0
- package/src/services/instruction-service.ts +318 -0
- package/src/services/mcp-registry.ts +94 -0
- package/src/services/platform-helpers.ts +287 -0
- package/src/services/session-manager.ts +262 -0
- package/src/services/settings-resolver.ts +74 -0
- package/src/services/system-config-resolver.ts +90 -0
- package/src/services/system-skills-service.ts +229 -0
- package/src/services/transcription-service.ts +684 -0
- package/src/session.ts +110 -0
- package/src/spaces/index.ts +1 -0
- package/src/spaces/space-resolver.ts +17 -0
- package/src/stores/in-memory-agent-store.ts +403 -0
- package/src/stores/redis-agent-store.ts +279 -0
- package/src/utils/public-url.ts +44 -0
- package/src/utils/rate-limiter.ts +94 -0
- 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
|
+
}
|