@dcrays/dcgchat-test 0.2.27 → 0.2.28
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/index.ts +19 -17
- package/package.json +2 -1
- package/src/bot.ts +214 -592
- package/src/channel.ts +113 -178
- package/src/monitor.ts +129 -178
- package/src/{api.ts → request/api.ts} +34 -35
- package/src/request/oss.ts +58 -0
- package/src/request/request.ts +198 -0
- package/src/{userInfo.ts → request/userInfo.ts} +36 -34
- package/src/skill.ts +119 -197
- package/src/tool.ts +109 -113
- package/src/transport.ts +108 -0
- package/src/types.ts +75 -64
- package/src/utils/constant.ts +4 -0
- package/src/utils/global.ts +112 -0
- package/src/utils/log.ts +15 -0
- package/src/utils/searchFile.ts +212 -0
- package/src/connection.ts +0 -11
- package/src/log.ts +0 -46
- package/src/oss.ts +0 -72
- package/src/request.ts +0 -201
- package/src/runtime.ts +0 -40
package/src/bot.ts
CHANGED
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
import fs from
|
|
2
|
-
import path from
|
|
3
|
-
import type {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
} from
|
|
8
|
-
import {
|
|
9
|
-
import
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { generateSignUrl } from "./api.js";
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import type { ReplyPayload } from 'openclaw/plugin-sdk'
|
|
4
|
+
import { createReplyPrefixContext } from 'openclaw/plugin-sdk'
|
|
5
|
+
import type { InboundMessage } from './types.js'
|
|
6
|
+
import { clearSentMediaKeys, getDcgchatRuntime, getOpenClawConfig, getWorkspaceDir, setMsgStatus } from './utils/global.js'
|
|
7
|
+
import { resolveAccount, sendDcgchatMedia } from './channel.js'
|
|
8
|
+
import { generateSignUrl } from './request/api.js'
|
|
9
|
+
import { extractMobookFiles } from './utils/searchFile.js'
|
|
10
|
+
import { createMsgContext, sendChunk, sendFinal, sendText as sendTextMsg, sendError } from './transport.js'
|
|
11
|
+
import { dcgLogger } from './utils/log.js'
|
|
12
|
+
import { emptyToolText } from './utils/constant.js'
|
|
14
13
|
|
|
15
14
|
type MediaInfo = {
|
|
16
|
-
path: string
|
|
17
|
-
fileName: string
|
|
18
|
-
contentType: string
|
|
19
|
-
placeholder: string
|
|
20
|
-
}
|
|
15
|
+
path: string
|
|
16
|
+
fileName: string
|
|
17
|
+
contentType: string
|
|
18
|
+
placeholder: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type TFileInfo = { name: string; url: string }
|
|
21
22
|
|
|
22
|
-
const mediaMaxBytes = 300 * 1024 * 1024
|
|
23
|
+
const mediaMaxBytes = 300 * 1024 * 1024
|
|
23
24
|
|
|
24
25
|
/** Active LLM generation abort controllers, keyed by conversationId */
|
|
25
|
-
const activeGenerations = new Map<string, AbortController>()
|
|
26
|
+
const activeGenerations = new Map<string, AbortController>()
|
|
26
27
|
|
|
27
28
|
/** Abort an in-progress LLM generation for a given conversationId */
|
|
28
29
|
export function abortMobookappGeneration(conversationId: string): void {
|
|
29
|
-
const ctrl = activeGenerations.get(conversationId)
|
|
30
|
-
console.log("🚀 ~ abortMobookappGeneration ~ ctrl:", ctrl)
|
|
30
|
+
const ctrl = activeGenerations.get(conversationId)
|
|
31
31
|
if (ctrl) {
|
|
32
|
-
ctrl.abort()
|
|
33
|
-
activeGenerations.delete(conversationId)
|
|
32
|
+
ctrl.abort()
|
|
33
|
+
activeGenerations.delete(conversationId)
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
|
|
@@ -38,92 +38,71 @@ export function abortMobookappGeneration(conversationId: string): void {
|
|
|
38
38
|
* Extract agentId from conversation_id formatted as "agentId::suffix".
|
|
39
39
|
* Returns null if the conversation_id does not contain the "::" separator.
|
|
40
40
|
*/
|
|
41
|
-
export function extractAgentIdFromConversationId(
|
|
42
|
-
conversationId
|
|
43
|
-
)
|
|
44
|
-
|
|
45
|
-
if (idx <= 0) return null;
|
|
46
|
-
return conversationId.slice(0, idx);
|
|
41
|
+
export function extractAgentIdFromConversationId(conversationId: string): string | null {
|
|
42
|
+
const idx = conversationId.indexOf('::')
|
|
43
|
+
if (idx <= 0) return null
|
|
44
|
+
return conversationId.slice(0, idx)
|
|
47
45
|
}
|
|
48
46
|
|
|
49
|
-
async function resolveMediaFromUrls(
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
): Promise<MediaInfo[]> {
|
|
54
|
-
const core = getDcgchatRuntime();
|
|
55
|
-
const out: MediaInfo[] = [];
|
|
56
|
-
log(
|
|
57
|
-
`dcgchat media: starting resolve for ${files.length} file(s): ${JSON.stringify(files)}`,
|
|
58
|
-
);
|
|
47
|
+
async function resolveMediaFromUrls(files: TFileInfo[], botToken: string): Promise<MediaInfo[]> {
|
|
48
|
+
const core = getDcgchatRuntime()
|
|
49
|
+
const out: MediaInfo[] = []
|
|
50
|
+
dcgLogger(`media: user upload files: ${JSON.stringify(files)}`)
|
|
59
51
|
|
|
60
52
|
for (let i = 0; i < files.length; i++) {
|
|
61
|
-
const file = files[i]
|
|
53
|
+
const file = files[i]
|
|
62
54
|
try {
|
|
63
|
-
let data =
|
|
55
|
+
let data = ''
|
|
64
56
|
if (/^https?:\/\//i.test(file.url)) {
|
|
65
|
-
data = file.url
|
|
57
|
+
data = file.url
|
|
66
58
|
} else {
|
|
67
|
-
data = await generateSignUrl(file.url, botToken)
|
|
59
|
+
data = await generateSignUrl(file.url, botToken)
|
|
68
60
|
}
|
|
69
|
-
|
|
70
|
-
const response = await fetch(data)
|
|
61
|
+
dcgLogger(`media: generateSignUrl: ${data}`)
|
|
62
|
+
const response = await fetch(data)
|
|
71
63
|
if (!response.ok) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
);
|
|
75
|
-
continue;
|
|
64
|
+
dcgLogger?.(`media: ${file.url} fetch failed with HTTP ${response.status}`, 'error')
|
|
65
|
+
continue
|
|
76
66
|
}
|
|
77
|
-
const buffer = Buffer.from(await response.arrayBuffer())
|
|
67
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
78
68
|
|
|
79
|
-
let contentType = response.headers.get(
|
|
69
|
+
let contentType = response.headers.get('content-type') || ''
|
|
80
70
|
if (!contentType) {
|
|
81
|
-
contentType = (await core.media.detectMime({ buffer })) ||
|
|
71
|
+
contentType = (await core.media.detectMime({ buffer })) || ''
|
|
82
72
|
}
|
|
83
|
-
const fileName =
|
|
84
|
-
|
|
85
|
-
const
|
|
86
|
-
buffer,
|
|
87
|
-
contentType,
|
|
88
|
-
"inbound",
|
|
89
|
-
mediaMaxBytes,
|
|
90
|
-
fileName,
|
|
91
|
-
);
|
|
92
|
-
const isImage = contentType.startsWith("image/");
|
|
73
|
+
const fileName = file.name || path.basename(new URL(file.url).pathname) || 'file'
|
|
74
|
+
const saved = await core.channel.media.saveMediaBuffer(buffer, contentType, 'inbound', mediaMaxBytes, fileName)
|
|
75
|
+
const isImage = contentType.startsWith('image/')
|
|
93
76
|
out.push({
|
|
94
77
|
path: saved.path,
|
|
95
78
|
fileName,
|
|
96
|
-
contentType: saved.contentType ||
|
|
97
|
-
placeholder: isImage ?
|
|
98
|
-
})
|
|
79
|
+
contentType: saved.contentType || '',
|
|
80
|
+
placeholder: isImage ? '<media:image>' : '<media:file>'
|
|
81
|
+
})
|
|
99
82
|
} catch (err) {
|
|
100
|
-
|
|
101
|
-
`dcgchat media: [${i + 1}/${files.length}] FAILED to process ${file.url}: ${String(err)}`,
|
|
102
|
-
);
|
|
83
|
+
dcgLogger(`media: ${file.url} FAILED to process: ${String(err)}`, 'error')
|
|
103
84
|
}
|
|
104
85
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
);
|
|
108
|
-
|
|
109
|
-
return out;
|
|
86
|
+
dcgLogger(`media: resolve complete, ${out.length}/${files.length} file(s) succeeded`)
|
|
87
|
+
return out
|
|
110
88
|
}
|
|
111
89
|
|
|
112
|
-
|
|
113
|
-
MediaPath?: string
|
|
114
|
-
MediaFileName?: string
|
|
115
|
-
MediaType?: string
|
|
116
|
-
MediaUrl?: string
|
|
117
|
-
MediaFileNames?: string[]
|
|
118
|
-
MediaPaths?: string[]
|
|
119
|
-
MediaUrls?: string[]
|
|
120
|
-
MediaTypes?: string[]
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const
|
|
125
|
-
const
|
|
126
|
-
const
|
|
90
|
+
type MediaPayload = {
|
|
91
|
+
MediaPath?: string
|
|
92
|
+
MediaFileName?: string
|
|
93
|
+
MediaType?: string
|
|
94
|
+
MediaUrl?: string
|
|
95
|
+
MediaFileNames?: string[]
|
|
96
|
+
MediaPaths?: string[]
|
|
97
|
+
MediaUrls?: string[]
|
|
98
|
+
MediaTypes?: string[]
|
|
99
|
+
}
|
|
100
|
+
function buildMediaPayload(mediaList: MediaInfo[]): MediaPayload {
|
|
101
|
+
if (mediaList.length === 0) return {}
|
|
102
|
+
const first = mediaList[0]
|
|
103
|
+
const mediaFileNames = mediaList.map((m) => m.fileName).filter(Boolean)
|
|
104
|
+
const mediaPaths = mediaList.map((m) => m.path)
|
|
105
|
+
const mediaTypes = mediaList.map((m) => m.contentType).filter(Boolean)
|
|
127
106
|
return {
|
|
128
107
|
MediaPath: first?.path,
|
|
129
108
|
MediaFileName: first?.fileName,
|
|
@@ -132,333 +111,84 @@ function buildMediaPayload(mediaList: MediaInfo[]): {
|
|
|
132
111
|
MediaFileNames: mediaFileNames.length > 0 ? mediaFileNames : undefined,
|
|
133
112
|
MediaPaths: mediaPaths.length > 0 ? mediaPaths : undefined,
|
|
134
113
|
MediaUrls: mediaPaths.length > 0 ? mediaPaths : undefined,
|
|
135
|
-
MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined
|
|
136
|
-
};
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
function resolveReplyMediaList(payload: ReplyPayload): string[] {
|
|
140
|
-
if (payload.mediaUrls?.length) return payload.mediaUrls.filter(Boolean);
|
|
141
|
-
return payload.mediaUrl ? [payload.mediaUrl] : [];
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* 从文本中提取 /mobook 目录下的文件
|
|
147
|
-
* @param {string} text
|
|
148
|
-
* @returns {string[]}
|
|
149
|
-
*/
|
|
150
|
-
const EXT_LIST = [
|
|
151
|
-
// 文档类
|
|
152
|
-
"doc",
|
|
153
|
-
"docx",
|
|
154
|
-
"xls",
|
|
155
|
-
"xlsx",
|
|
156
|
-
"ppt",
|
|
157
|
-
"pptx",
|
|
158
|
-
"pdf",
|
|
159
|
-
"txt",
|
|
160
|
-
"rtf",
|
|
161
|
-
"odt",
|
|
162
|
-
|
|
163
|
-
// 数据/开发
|
|
164
|
-
"json",
|
|
165
|
-
"xml",
|
|
166
|
-
"csv",
|
|
167
|
-
"yaml",
|
|
168
|
-
"yml",
|
|
169
|
-
|
|
170
|
-
// 前端/文本
|
|
171
|
-
"html",
|
|
172
|
-
"htm",
|
|
173
|
-
"md",
|
|
174
|
-
"markdown",
|
|
175
|
-
"css",
|
|
176
|
-
"js",
|
|
177
|
-
"ts",
|
|
178
|
-
|
|
179
|
-
// 图片
|
|
180
|
-
"png",
|
|
181
|
-
"jpg",
|
|
182
|
-
"jpeg",
|
|
183
|
-
"gif",
|
|
184
|
-
"bmp",
|
|
185
|
-
"webp",
|
|
186
|
-
"svg",
|
|
187
|
-
"ico",
|
|
188
|
-
"tiff",
|
|
189
|
-
|
|
190
|
-
// 音频
|
|
191
|
-
"mp3",
|
|
192
|
-
"wav",
|
|
193
|
-
"ogg",
|
|
194
|
-
"aac",
|
|
195
|
-
"flac",
|
|
196
|
-
"m4a",
|
|
197
|
-
|
|
198
|
-
// 视频
|
|
199
|
-
"mp4",
|
|
200
|
-
"avi",
|
|
201
|
-
"mov",
|
|
202
|
-
"wmv",
|
|
203
|
-
"flv",
|
|
204
|
-
"mkv",
|
|
205
|
-
"webm",
|
|
206
|
-
|
|
207
|
-
// 压缩包
|
|
208
|
-
"zip",
|
|
209
|
-
"rar",
|
|
210
|
-
"7z",
|
|
211
|
-
"tar",
|
|
212
|
-
"gz",
|
|
213
|
-
"bz2",
|
|
214
|
-
"xz",
|
|
215
|
-
|
|
216
|
-
// 可执行/程序
|
|
217
|
-
"exe",
|
|
218
|
-
"dmg",
|
|
219
|
-
"pkg",
|
|
220
|
-
"apk",
|
|
221
|
-
"ipa",
|
|
222
|
-
|
|
223
|
-
// 其他常见
|
|
224
|
-
"log",
|
|
225
|
-
"dat",
|
|
226
|
-
"bin",
|
|
227
|
-
];
|
|
228
|
-
|
|
229
|
-
/**
|
|
230
|
-
* 扩展名按长度降序,用于正则交替,避免 xls 抢先匹配 xlsx、htm 抢先匹配 html 等
|
|
231
|
-
*/
|
|
232
|
-
const EXT_SORTED_FOR_REGEX = [...EXT_LIST].sort((a, b) => b.length - a.length);
|
|
233
|
-
|
|
234
|
-
/** 去除控制符、零宽字符等常见脏值 */
|
|
235
|
-
function stripMobookNoise(s: string) {
|
|
236
|
-
return s.replace(/[\u0000-\u001F\u007F\u200B-\u200D\u200E\u200F\uFEFF]/g, "");
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* 从文本中扫描 `/mobook/` 片段,按最长后缀匹配合法扩展名(兜底,不依赖 FILE_NAME 字符集)
|
|
241
|
-
*/
|
|
242
|
-
function collectMobookPathsByScan(text: string, result: Set<string>): void {
|
|
243
|
-
const lower = text.toLowerCase();
|
|
244
|
-
const needle = "/mobook/";
|
|
245
|
-
let from = 0;
|
|
246
|
-
while (from < text.length) {
|
|
247
|
-
const i = lower.indexOf(needle, from);
|
|
248
|
-
if (i < 0) break;
|
|
249
|
-
const start = i + needle.length;
|
|
250
|
-
const tail = text.slice(start);
|
|
251
|
-
const seg = tail.match(/^([^\s\]\)'"}\u3002,,]+)/);
|
|
252
|
-
if (!seg) {
|
|
253
|
-
from = start + 1;
|
|
254
|
-
continue;
|
|
255
|
-
}
|
|
256
|
-
let raw = stripMobookNoise(seg[1]).trim();
|
|
257
|
-
if (!raw || raw.includes("\uFFFD")) {
|
|
258
|
-
from = start + 1;
|
|
259
|
-
continue;
|
|
260
|
-
}
|
|
261
|
-
const low = raw.toLowerCase();
|
|
262
|
-
let matchedExt: string | undefined;
|
|
263
|
-
for (const ext of EXT_SORTED_FOR_REGEX) {
|
|
264
|
-
if (low.endsWith(`.${ext}`)) {
|
|
265
|
-
matchedExt = ext;
|
|
266
|
-
break;
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
if (!matchedExt) {
|
|
270
|
-
from = start + 1;
|
|
271
|
-
continue;
|
|
272
|
-
}
|
|
273
|
-
const base = raw.slice(0, -(matchedExt.length + 1));
|
|
274
|
-
const fileName = `${base}.${matchedExt}`;
|
|
275
|
-
if (isValidFileName(fileName)) {
|
|
276
|
-
result.add(normalizePath(`/mobook/${fileName}`));
|
|
277
|
-
}
|
|
278
|
-
from = start + 1;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
function extractMobookFiles(text = "") {
|
|
283
|
-
if (typeof text !== "string" || !text.trim()) return [];
|
|
284
|
-
const result = new Set<string>();
|
|
285
|
-
// ✅ 扩展名(必须长扩展名优先,见 EXT_SORTED_FOR_REGEX)
|
|
286
|
-
const EXT = `(${EXT_SORTED_FOR_REGEX.join("|")})`;
|
|
287
|
-
// ✅ 文件名字符(增强:支持中文、符号)
|
|
288
|
-
const FILE_NAME = `[\\w\\u4e00-\\u9fa5::《》()()\\-\\s]+?`;
|
|
289
|
-
try {
|
|
290
|
-
// 1️⃣ `xxx.xxx`
|
|
291
|
-
const backtickReg = new RegExp(`\`([^\\\`]+?\\.${EXT})\``, "gi");
|
|
292
|
-
(text.match(backtickReg) || []).forEach((item) => {
|
|
293
|
-
const name = item.replace(/`/g, "").trim();
|
|
294
|
-
if (isValidFileName(name)) {
|
|
295
|
-
result.add(`/mobook/${name}`);
|
|
296
|
-
}
|
|
297
|
-
});
|
|
298
|
-
// 2️⃣ /mobook/xxx.xxx
|
|
299
|
-
const fullPathReg = new RegExp(`/mobook/${FILE_NAME}\\.${EXT}`, "gi");
|
|
300
|
-
(text.match(fullPathReg) || []).forEach((p) => {
|
|
301
|
-
result.add(normalizePath(p));
|
|
302
|
-
});
|
|
303
|
-
// 3️⃣ mobook下的 xxx.xxx
|
|
304
|
-
const inlineReg = new RegExp(`mobook下的\\s*(${FILE_NAME}\\.${EXT})`, "gi");
|
|
305
|
-
(text.match(inlineReg) || []).forEach((item) => {
|
|
306
|
-
const match = item.match(new RegExp(`${FILE_NAME}\\.${EXT}`, "i"));
|
|
307
|
-
if (match && isValidFileName(match[0])) {
|
|
308
|
-
result.add(`/mobook/${match[0].trim()}`);
|
|
309
|
-
}
|
|
310
|
-
});
|
|
311
|
-
// 🆕 4️⃣ **xxx.xxx**
|
|
312
|
-
const boldReg = new RegExp(`\\*\\*(${FILE_NAME}\\.${EXT})\\*\\*`, "gi");
|
|
313
|
-
(text.match(boldReg) || []).forEach((item) => {
|
|
314
|
-
const name = item.replace(/\*\*/g, "").trim();
|
|
315
|
-
if (isValidFileName(name)) {
|
|
316
|
-
result.add(`/mobook/${name}`);
|
|
317
|
-
}
|
|
318
|
-
});
|
|
319
|
-
// 🆕 5️⃣ xxx.xxx (123字节)
|
|
320
|
-
const looseReg = new RegExp(`(${FILE_NAME}\\.${EXT})\\s*\\(`, "gi");
|
|
321
|
-
(text.match(looseReg) || []).forEach((item) => {
|
|
322
|
-
const name = item.replace(/\s*\(.+$/, "").trim();
|
|
323
|
-
if (isValidFileName(name)) {
|
|
324
|
-
result.add(`/mobook/${name}`);
|
|
325
|
-
}
|
|
326
|
-
});
|
|
327
|
-
// 6️⃣ 兜底:绝对路径等 `.../mobook/<文件名>.<扩展名>` + 最长后缀匹配 + 去脏字符
|
|
328
|
-
collectMobookPathsByScan(text, result);
|
|
329
|
-
} catch (e) {
|
|
330
|
-
console.warn("extractMobookFiles error:", e);
|
|
114
|
+
MediaTypes: mediaTypes.length > 0 ? mediaTypes : undefined
|
|
331
115
|
}
|
|
332
|
-
return [...result];
|
|
333
116
|
}
|
|
334
117
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
function isValidFileName(name: string) {
|
|
339
|
-
if (!name) return false;
|
|
340
|
-
const cleaned = stripMobookNoise(name).trim();
|
|
341
|
-
if (!cleaned) return false;
|
|
342
|
-
if (cleaned.includes("\uFFFD")) return false;
|
|
343
|
-
// 过滤异常字符
|
|
344
|
-
if (/[\/\\<>:"|?*]/.test(cleaned)) return false;
|
|
345
|
-
// 长度限制(防止异常长字符串)
|
|
346
|
-
if (cleaned.length > 200) return false;
|
|
347
|
-
return true;
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* 规范路径(去重用)
|
|
352
|
-
*/
|
|
353
|
-
function normalizePath(path: string) {
|
|
354
|
-
return path
|
|
355
|
-
.replace(/\/+/g, "/") // 多斜杠 → 单斜杠
|
|
356
|
-
.replace(/\/$/, ""); // 去掉结尾 /
|
|
118
|
+
function resolveReplyMediaList(payload: ReplyPayload): string[] {
|
|
119
|
+
if (payload.mediaUrls?.length) return payload.mediaUrls.filter(Boolean)
|
|
120
|
+
return payload.mediaUrl ? [payload.mediaUrl] : []
|
|
357
121
|
}
|
|
358
122
|
|
|
359
123
|
/**
|
|
360
124
|
* 处理一条用户消息,调用 Agent 并返回回复
|
|
361
125
|
*/
|
|
362
|
-
export async function handleDcgchatMessage(
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
const
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
const account = resolveAccount(cfg, accountId);
|
|
376
|
-
const userId = msg._userId.toString();
|
|
377
|
-
const text = msg.content.text?.trim();
|
|
126
|
+
export async function handleDcgchatMessage(msg: InboundMessage, accountId: string): Promise<void> {
|
|
127
|
+
const msgCtx = createMsgContext(msg)
|
|
128
|
+
|
|
129
|
+
let completeText = ''
|
|
130
|
+
const config = getOpenClawConfig()
|
|
131
|
+
if (!config) {
|
|
132
|
+
dcgLogger('no config available', 'error')
|
|
133
|
+
return
|
|
134
|
+
}
|
|
135
|
+
const account = resolveAccount(config, accountId)
|
|
136
|
+
const userId = msg._userId.toString()
|
|
137
|
+
const text = msg.content.text?.trim()
|
|
378
138
|
|
|
379
139
|
if (!text) {
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
source: "client",
|
|
384
|
-
// @ts-ignore
|
|
385
|
-
content: {
|
|
386
|
-
bot_token: msg.content.bot_token,
|
|
387
|
-
domain_id: msg.content.domain_id,
|
|
388
|
-
app_id: msg.content.app_id,
|
|
389
|
-
bot_id: msg.content.bot_id,
|
|
390
|
-
agent_id: msg.content.agent_id,
|
|
391
|
-
session_id: msg.content.session_id,
|
|
392
|
-
message_id: msg.content.message_id,
|
|
393
|
-
response: "你需要我帮你做什么呢?",
|
|
394
|
-
},
|
|
395
|
-
});
|
|
396
|
-
return;
|
|
140
|
+
sendTextMsg(msgCtx, '你需要我帮你做什么呢?')
|
|
141
|
+
sendFinal(msgCtx)
|
|
142
|
+
return
|
|
397
143
|
}
|
|
398
144
|
|
|
399
145
|
try {
|
|
400
|
-
const core = getDcgchatRuntime()
|
|
146
|
+
const core = getDcgchatRuntime()
|
|
401
147
|
|
|
402
|
-
const conversationId = msg.content.session_id?.trim()
|
|
148
|
+
const conversationId = msg.content.session_id?.trim()
|
|
403
149
|
|
|
404
150
|
const route = core.channel.routing.resolveAgentRoute({
|
|
405
|
-
cfg,
|
|
151
|
+
cfg: config,
|
|
406
152
|
channel: "dcgchat-test",
|
|
407
153
|
accountId: account.accountId,
|
|
408
|
-
peer: { kind:
|
|
409
|
-
})
|
|
154
|
+
peer: { kind: 'direct', id: conversationId }
|
|
155
|
+
})
|
|
410
156
|
|
|
411
157
|
// If conversation_id encodes an agentId prefix ("agentId::suffix"), override the route.
|
|
412
|
-
const embeddedAgentId = extractAgentIdFromConversationId(conversationId)
|
|
413
|
-
const effectiveAgentId = embeddedAgentId ?? route.agentId
|
|
158
|
+
const embeddedAgentId = extractAgentIdFromConversationId(conversationId)
|
|
159
|
+
const effectiveAgentId = embeddedAgentId ?? route.agentId
|
|
414
160
|
const effectiveSessionKey = embeddedAgentId
|
|
415
161
|
? `agent:${embeddedAgentId}:mobook:direct:${conversationId}`.toLowerCase()
|
|
416
|
-
: route.sessionKey
|
|
162
|
+
: route.sessionKey
|
|
417
163
|
|
|
418
164
|
const agentEntry =
|
|
419
|
-
effectiveAgentId && effectiveAgentId !==
|
|
420
|
-
|
|
421
|
-
: undefined;
|
|
422
|
-
const agentDisplayName =
|
|
423
|
-
agentEntry?.name ??
|
|
424
|
-
(effectiveAgentId && effectiveAgentId !== "main"
|
|
425
|
-
? effectiveAgentId
|
|
426
|
-
: undefined);
|
|
165
|
+
effectiveAgentId && effectiveAgentId !== 'main' ? config.agents?.list?.find((a) => a.id === effectiveAgentId) : undefined
|
|
166
|
+
const agentDisplayName = agentEntry?.name ?? (effectiveAgentId && effectiveAgentId !== 'main' ? effectiveAgentId : undefined)
|
|
427
167
|
|
|
428
168
|
// Abort any existing generation for this conversation, then start a new one
|
|
429
|
-
const existingCtrl = activeGenerations.get(conversationId)
|
|
430
|
-
if (existingCtrl) existingCtrl.abort()
|
|
431
|
-
const genCtrl = new AbortController()
|
|
432
|
-
const genSignal = genCtrl.signal
|
|
433
|
-
activeGenerations.set(conversationId, genCtrl)
|
|
169
|
+
const existingCtrl = activeGenerations.get(conversationId)
|
|
170
|
+
if (existingCtrl) existingCtrl.abort()
|
|
171
|
+
const genCtrl = new AbortController()
|
|
172
|
+
const genSignal = genCtrl.signal
|
|
173
|
+
activeGenerations.set(conversationId, genCtrl)
|
|
434
174
|
|
|
435
175
|
// 处理用户上传的文件
|
|
436
|
-
const files = msg.content.files ?? []
|
|
437
|
-
let mediaPayload: Record<string, unknown> = {}
|
|
176
|
+
const files = msg.content.files ?? []
|
|
177
|
+
let mediaPayload: Record<string, unknown> = {}
|
|
438
178
|
if (files.length > 0) {
|
|
439
|
-
const mediaList = await resolveMediaFromUrls(
|
|
440
|
-
|
|
441
|
-
msg.content.bot_token,
|
|
442
|
-
log,
|
|
443
|
-
);
|
|
444
|
-
mediaPayload = buildMediaPayload(mediaList);
|
|
445
|
-
log(
|
|
446
|
-
`dcgchat[${accountId}]: media resolved ${mediaList.length}/${files.length} file(s), payload=${JSON.stringify(mediaList)}`,
|
|
447
|
-
);
|
|
179
|
+
const mediaList = await resolveMediaFromUrls(files, msg.content.bot_token)
|
|
180
|
+
mediaPayload = buildMediaPayload(mediaList)
|
|
448
181
|
}
|
|
449
182
|
|
|
450
|
-
const envelopeOptions =
|
|
451
|
-
|
|
452
|
-
// const messageBody = `${userId}: ${text}`;
|
|
453
|
-
// 补充消息
|
|
454
|
-
const messageBody = text;
|
|
183
|
+
const envelopeOptions = core.channel.reply.resolveEnvelopeFormatOptions(config)
|
|
184
|
+
const messageBody = text
|
|
455
185
|
const bodyFormatted = core.channel.reply.formatAgentEnvelope({
|
|
456
|
-
channel:
|
|
186
|
+
channel: '书灵墨宝',
|
|
457
187
|
from: userId,
|
|
458
188
|
timestamp: new Date(),
|
|
459
189
|
envelope: envelopeOptions,
|
|
460
|
-
body: messageBody
|
|
461
|
-
})
|
|
190
|
+
body: messageBody
|
|
191
|
+
})
|
|
462
192
|
|
|
463
193
|
const ctxPayload = core.channel.reply.finalizeInboundContext({
|
|
464
194
|
Body: bodyFormatted,
|
|
@@ -468,260 +198,152 @@ export async function handleDcgchatMessage(params: {
|
|
|
468
198
|
To: conversationId,
|
|
469
199
|
SessionKey: effectiveSessionKey,
|
|
470
200
|
AccountId: route.accountId,
|
|
471
|
-
ChatType:
|
|
201
|
+
ChatType: 'direct',
|
|
472
202
|
SenderName: agentDisplayName,
|
|
473
203
|
SenderId: userId,
|
|
474
|
-
Provider: "dcgchat-test"
|
|
475
|
-
Surface: "dcgchat-test"
|
|
204
|
+
Provider: "dcgchat-test",
|
|
205
|
+
Surface: "dcgchat-test",
|
|
476
206
|
MessageSid: msg.content.message_id,
|
|
477
207
|
Timestamp: Date.now(),
|
|
478
208
|
WasMentioned: true,
|
|
479
209
|
CommandAuthorized: true,
|
|
480
|
-
OriginatingChannel: "dcgchat-test"
|
|
210
|
+
OriginatingChannel: "dcgchat-test",
|
|
481
211
|
OriginatingTo: `user:${userId}`,
|
|
482
|
-
...mediaPayload
|
|
483
|
-
})
|
|
484
|
-
|
|
485
|
-
log(`dcgchat[${accountId}]: ctxPayload=${JSON.stringify(ctxPayload)}`);
|
|
212
|
+
...mediaPayload
|
|
213
|
+
})
|
|
486
214
|
|
|
487
215
|
const sentMediaKeys = new Set<string>()
|
|
488
216
|
const getMediaKey = (url: string) => url.split(/[\\/]/).pop() ?? url
|
|
489
|
-
let
|
|
217
|
+
let streamedTextLen = 0
|
|
490
218
|
|
|
491
219
|
const prefixContext = createReplyPrefixContext({
|
|
492
|
-
cfg,
|
|
493
|
-
agentId: effectiveAgentId ??
|
|
220
|
+
cfg: config,
|
|
221
|
+
agentId: effectiveAgentId ?? '',
|
|
494
222
|
channel: "dcgchat-test",
|
|
495
|
-
accountId: account.accountId
|
|
496
|
-
})
|
|
497
|
-
|
|
498
|
-
const { dispatcher, replyOptions, markDispatchIdle } =
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
)
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
)
|
|
512
|
-
}
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
});
|
|
223
|
+
accountId: account.accountId
|
|
224
|
+
})
|
|
225
|
+
|
|
226
|
+
const { dispatcher, replyOptions, markDispatchIdle, markRunComplete } = core.channel.reply.createReplyDispatcherWithTyping({
|
|
227
|
+
responsePrefix: prefixContext.responsePrefix,
|
|
228
|
+
responsePrefixContextProvider: prefixContext.responsePrefixContextProvider,
|
|
229
|
+
humanDelay: core.channel.reply.resolveHumanDelayConfig(config, route.agentId),
|
|
230
|
+
onReplyStart: async () => {},
|
|
231
|
+
deliver: async (payload: ReplyPayload, info) => {
|
|
232
|
+
dcgLogger(`[deliver]: kind=${info.kind}, text=${payload.text?.length ?? 0} chars`)
|
|
233
|
+
// Media from the outbound pipeline (post-streaming)
|
|
234
|
+
const mediaList = resolveReplyMediaList(payload)
|
|
235
|
+
for (const mediaUrl of mediaList) {
|
|
236
|
+
const key = getMediaKey(mediaUrl)
|
|
237
|
+
if (sentMediaKeys.has(key)) continue
|
|
238
|
+
sentMediaKeys.add(key)
|
|
239
|
+
await sendDcgchatMedia({ msgCtx, mediaUrl, text: '' })
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
onError: (err: unknown, info: { kind: string }) => {
|
|
243
|
+
dcgLogger(`${info.kind} reply failed: ${String(err)}`, 'error')
|
|
244
|
+
},
|
|
245
|
+
onIdle: () => {}
|
|
246
|
+
})
|
|
520
247
|
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
await core.channel.reply.dispatchReplyFromConfig({
|
|
526
|
-
ctx: ctxPayload,
|
|
527
|
-
cfg,
|
|
528
|
-
dispatcher,
|
|
529
|
-
replyOptions: {
|
|
530
|
-
...replyOptions,
|
|
531
|
-
onModelSelected: prefixContext.onModelSelected
|
|
532
|
-
},
|
|
533
|
-
});
|
|
534
|
-
} else {
|
|
535
|
-
log(
|
|
536
|
-
`dcgchat[${accountId}]: dispatching to agent (session=${route.sessionKey})`,
|
|
537
|
-
);
|
|
248
|
+
let wasAborted = false
|
|
249
|
+
try {
|
|
250
|
+
if (emptyToolText.includes(text?.trim())) {
|
|
251
|
+
dcgLogger(`dispatching /new`)
|
|
538
252
|
await core.channel.reply.dispatchReplyFromConfig({
|
|
539
253
|
ctx: ctxPayload,
|
|
540
|
-
cfg,
|
|
254
|
+
cfg: config,
|
|
255
|
+
dispatcher,
|
|
256
|
+
replyOptions: {
|
|
257
|
+
...replyOptions,
|
|
258
|
+
onModelSelected: prefixContext.onModelSelected
|
|
259
|
+
}
|
|
260
|
+
})
|
|
261
|
+
} else {
|
|
262
|
+
dcgLogger(`dispatching to agent (session=${route.sessionKey})`)
|
|
263
|
+
await core.channel.reply.dispatchReplyFromConfig({
|
|
264
|
+
ctx: ctxPayload,
|
|
265
|
+
cfg: config,
|
|
541
266
|
dispatcher,
|
|
542
267
|
replyOptions: {
|
|
543
268
|
...replyOptions,
|
|
544
269
|
abortSignal: genSignal,
|
|
545
270
|
onModelSelected: prefixContext.onModelSelected,
|
|
546
271
|
onPartialReply: async (payload: ReplyPayload) => {
|
|
547
|
-
|
|
548
|
-
`dcgchat[${accountId}][deliver]: received chunk, text length=${payload.text?.length || 0}`,
|
|
549
|
-
);
|
|
272
|
+
// Accumulate full text
|
|
550
273
|
if (payload.text) {
|
|
551
|
-
completeText = payload.text
|
|
552
|
-
}
|
|
553
|
-
const mediaList = resolveReplyMediaList(payload);
|
|
554
|
-
if (mediaList.length > 0) {
|
|
555
|
-
for (let i = 0; i < mediaList.length; i++) {
|
|
556
|
-
const mediaUrl = mediaList[i];
|
|
557
|
-
const key = getMediaKey(mediaUrl);
|
|
558
|
-
if (sentMediaKeys.has(key)) continue;
|
|
559
|
-
sentMediaKeys.add(key);
|
|
560
|
-
await sendDcgchatMedia({
|
|
561
|
-
cfg,
|
|
562
|
-
accountId,
|
|
563
|
-
log,
|
|
564
|
-
mediaUrl,
|
|
565
|
-
text: "",
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
log(
|
|
569
|
-
`dcgchat[${accountId}][deliver]: sent ${mediaList.length} media file(s) through channel adapter`,
|
|
570
|
-
);
|
|
274
|
+
completeText = payload.text
|
|
571
275
|
}
|
|
276
|
+
// --- Streaming text chunks ---
|
|
572
277
|
if (payload.text) {
|
|
573
|
-
const
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
)
|
|
578
|
-
|
|
579
|
-
messageType: "openclaw_bot_chat",
|
|
580
|
-
_userId: msg._userId,
|
|
581
|
-
source: "client",
|
|
582
|
-
content: {
|
|
583
|
-
bot_token: msg.content.bot_token,
|
|
584
|
-
domain_id: msg.content.domain_id,
|
|
585
|
-
app_id: msg.content.app_id,
|
|
586
|
-
bot_id: msg.content.bot_id,
|
|
587
|
-
agent_id: msg.content.agent_id,
|
|
588
|
-
session_id: msg.content.session_id,
|
|
589
|
-
message_id: msg.content.message_id,
|
|
590
|
-
response: nextTextChunk,
|
|
591
|
-
state: "chunk",
|
|
592
|
-
},
|
|
593
|
-
});
|
|
594
|
-
log(
|
|
595
|
-
`dcgchat[${accountId}][deliver]: chunk sent successfully`,
|
|
596
|
-
);
|
|
278
|
+
const delta = payload.text.startsWith(completeText.slice(0, streamedTextLen))
|
|
279
|
+
? payload.text.slice(streamedTextLen)
|
|
280
|
+
: payload.text
|
|
281
|
+
if (delta.trim()) {
|
|
282
|
+
sendChunk(msgCtx, delta)
|
|
283
|
+
dcgLogger(`[stream]: chunk ${delta.length} chars to user ${msg._userId} ${delta.slice(0, 100)}`)
|
|
597
284
|
}
|
|
598
|
-
|
|
599
|
-
}
|
|
600
|
-
|
|
285
|
+
streamedTextLen = payload.text.length
|
|
286
|
+
}
|
|
287
|
+
// --- Media from payload ---
|
|
288
|
+
const mediaList = resolveReplyMediaList(payload)
|
|
289
|
+
for (const mediaUrl of mediaList) {
|
|
290
|
+
const key = getMediaKey(mediaUrl)
|
|
291
|
+
if (sentMediaKeys.has(key)) continue
|
|
292
|
+
sentMediaKeys.add(key)
|
|
293
|
+
await sendDcgchatMedia({ msgCtx, mediaUrl, text: '' })
|
|
601
294
|
}
|
|
602
|
-
}
|
|
603
|
-
}
|
|
604
|
-
})
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
})
|
|
605
298
|
}
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
`dcgchat[${accountId}]: dispatchReplyFromConfig error: ${String(err)}`,
|
|
620
|
-
);
|
|
621
|
-
}
|
|
622
|
-
} finally {
|
|
623
|
-
if (activeGenerations.get(conversationId) === genCtrl) {
|
|
624
|
-
activeGenerations.delete(conversationId);
|
|
625
|
-
}
|
|
626
|
-
if (wasAborted) {
|
|
627
|
-
//TODO:是否需要发消息给移动端,通知停止生成
|
|
628
|
-
}
|
|
299
|
+
} catch (err: unknown) {
|
|
300
|
+
if (genSignal.aborted) {
|
|
301
|
+
wasAborted = true
|
|
302
|
+
dcgLogger(` generation aborted for conversationId=${conversationId}`)
|
|
303
|
+
} else if (err instanceof Error && err.name === 'AbortError') {
|
|
304
|
+
wasAborted = true
|
|
305
|
+
dcgLogger(` generation aborted for conversationId=${conversationId}`)
|
|
306
|
+
} else {
|
|
307
|
+
dcgLogger(` dispatchReplyFromConfig error: ${String(err)}`, 'error')
|
|
308
|
+
}
|
|
309
|
+
} finally {
|
|
310
|
+
if (activeGenerations.get(conversationId) === genCtrl) {
|
|
311
|
+
activeGenerations.delete(conversationId)
|
|
629
312
|
}
|
|
313
|
+
}
|
|
630
314
|
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
if (
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
);
|
|
640
|
-
continue;
|
|
641
|
-
}
|
|
642
|
-
if (!fs.existsSync(url)) {
|
|
643
|
-
url = path.join(getWorkspaceDir(), url);
|
|
644
|
-
if (!fs.existsSync(url)) {
|
|
645
|
-
log(
|
|
646
|
-
`dcgchat[${accountId}]: mobookFiles file not found, skipping: ${url}`,
|
|
647
|
-
);
|
|
648
|
-
continue;
|
|
649
|
-
}
|
|
315
|
+
markRunComplete()
|
|
316
|
+
markDispatchIdle()
|
|
317
|
+
if (!emptyToolText.includes(text?.trim())) {
|
|
318
|
+
for (const file of extractMobookFiles(completeText)) {
|
|
319
|
+
let resolved = file
|
|
320
|
+
if (!fs.existsSync(resolved)) {
|
|
321
|
+
resolved = path.join(getWorkspaceDir(), file)
|
|
322
|
+
if (!fs.existsSync(resolved)) return
|
|
650
323
|
}
|
|
651
|
-
|
|
652
|
-
await sendDcgchatMedia({
|
|
653
|
-
cfg,
|
|
654
|
-
accountId,
|
|
655
|
-
log,
|
|
656
|
-
mediaUrl: url,
|
|
657
|
-
text: "",
|
|
658
|
-
});
|
|
324
|
+
await sendDcgchatMedia({ msgCtx, mediaUrl: resolved, text: '' })
|
|
659
325
|
}
|
|
660
|
-
|
|
661
|
-
`dcgchat[${accountId}][deliver]: sent ${mobookFiles.length} media file(s) through channel adapter`,
|
|
662
|
-
);
|
|
326
|
+
sendFinal(msgCtx)
|
|
663
327
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
messageType: "openclaw_bot_chat",
|
|
667
|
-
_userId: msg._userId,
|
|
668
|
-
source: "client",
|
|
669
|
-
content: {
|
|
670
|
-
bot_token: msg.content.bot_token,
|
|
671
|
-
domain_id: msg.content.domain_id,
|
|
672
|
-
app_id: msg.content.app_id,
|
|
673
|
-
bot_id: msg.content.bot_id,
|
|
674
|
-
agent_id: msg.content.agent_id,
|
|
675
|
-
session_id: msg.content.session_id,
|
|
676
|
-
message_id: msg.content.message_id,
|
|
677
|
-
response: "",
|
|
678
|
-
state: "final",
|
|
679
|
-
},
|
|
680
|
-
});
|
|
681
|
-
|
|
682
|
-
setMsgStatus("finished");
|
|
683
|
-
textChunk = "";
|
|
684
|
-
log(`dcgchat[${accountId}]: final state sent`);
|
|
685
|
-
|
|
686
|
-
markDispatchIdle();
|
|
687
|
-
log(`dcgchat[${accountId}]: message handling complete`);
|
|
328
|
+
clearSentMediaKeys(msg.content.message_id)
|
|
329
|
+
setMsgStatus('finished')
|
|
688
330
|
|
|
689
331
|
// Record session metadata
|
|
690
|
-
const storePath = core.channel.session.resolveStorePath(
|
|
332
|
+
const storePath = core.channel.session.resolveStorePath(config.session?.store)
|
|
691
333
|
core.channel.session
|
|
692
334
|
.recordInboundSession({
|
|
693
335
|
storePath,
|
|
694
336
|
sessionKey: effectiveSessionKey,
|
|
695
337
|
ctx: ctxPayload,
|
|
696
338
|
onRecordError: (err) => {
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
);
|
|
700
|
-
},
|
|
339
|
+
dcgLogger(` session record error: ${String(err)}`, 'error')
|
|
340
|
+
}
|
|
701
341
|
})
|
|
702
342
|
.catch((err: unknown) => {
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
);
|
|
706
|
-
});
|
|
343
|
+
dcgLogger(` recordInboundSession failed: ${String(err)}`, 'error')
|
|
344
|
+
})
|
|
707
345
|
} catch (err) {
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
messageType: "openclaw_bot_chat",
|
|
711
|
-
_userId: msg._userId,
|
|
712
|
-
source: "client",
|
|
713
|
-
content: {
|
|
714
|
-
bot_token: msg.content.bot_token,
|
|
715
|
-
domain_id: msg.content.domain_id,
|
|
716
|
-
app_id: msg.content.app_id,
|
|
717
|
-
bot_id: msg.content.bot_id,
|
|
718
|
-
agent_id: msg.content.agent_id,
|
|
719
|
-
session_id: msg.content.session_id,
|
|
720
|
-
message_id: msg.content.message_id,
|
|
721
|
-
response: `[错误] ${err instanceof Error ? err.message : String(err)}`,
|
|
722
|
-
state: "final",
|
|
723
|
-
},
|
|
724
|
-
});
|
|
346
|
+
dcgLogger(` handle message failed: ${String(err)}`, 'error')
|
|
347
|
+
sendError(msgCtx, err instanceof Error ? err.message : String(err))
|
|
725
348
|
}
|
|
726
349
|
}
|
|
727
|
-
|