agent-bridge-qwenwork 1.0.15 → 1.0.16
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/README.md
CHANGED
|
@@ -13,3 +13,5 @@
|
|
|
13
13
|
`/new` 在已确认的空白新任务页可重复执行。远程消息和 `/new` 遇到输入框残留时,先将原文、页面地址和时间追加到插件数据目录的 `draft-recovery.jsonl`,再通过编辑器原生删除操作清理;备份失败、内容发生变化或正在生成回复时不清理。后台心跳只清理桥接自己的检测文本,遇到普通用户草稿则跳过。发送消息会点击桌面端“发送消息”按钮并确认输入框清空,避免仅按 Enter 后消息仍停留在输入框。真实通信失败后保持降级,普通 CDP 检查通过不会把状态改回就绪,须有真实回复或真实对话心跳通过。
|
|
14
14
|
|
|
15
15
|
真实心跳会消耗模型额度,并在当前千问聊天会话留下检测消息;它通过与用户请求相同的发送和取回回复路径运行。云端故障、账号额度不足或登录过期仍可能需要修复服务或账号,验证失败期间不会报告健康。
|
|
16
|
+
|
|
17
|
+
文件、图片、视频附件经桌面原生上传入口送入本轮任务;回传只采集本轮助手通过“已展示最终文件”工具声明的产物,不扫描普通正文中的任意路径。图片按内容去重,视频以 `video/*` 文件附件交给 AUN,使用分块读取避免大视频导致 CDP 断连。单条最多 8 个附件,单个不超过 32 MiB、合计不超过 64 MiB;实际可处理的格式及内容理解能力由桌面端和模型决定。验证证据见仓库的 `docs/verification/2026-10-20-qwenwork-media.md`。
|
|
@@ -7,10 +7,19 @@ exports.waitFor = waitFor;
|
|
|
7
7
|
const promises_1 = require("node:fs/promises");
|
|
8
8
|
const node_fs_1 = require("node:fs");
|
|
9
9
|
const node_path_1 = require("node:path");
|
|
10
|
+
const versionDirectory = /^(?:app[-_ ]?)?v?\d+(?:[.-]\d+)+$/i;
|
|
10
11
|
/** 在 Windows 常见安装目录中查找桌面程序,避免依赖单一盘符。 */
|
|
11
12
|
async function findWindowsExecutable(fileName, configured) {
|
|
12
13
|
if (configured?.trim()) {
|
|
13
14
|
const configuredPath = (0, node_path_1.resolve)(configured);
|
|
15
|
+
if (fileName.toLowerCase() === "doubao.exe") {
|
|
16
|
+
let root = (0, node_path_1.dirname)(configuredPath);
|
|
17
|
+
while (/^app$/i.test((0, node_path_1.basename)(root)) || versionDirectory.test((0, node_path_1.basename)(root)))
|
|
18
|
+
root = (0, node_path_1.dirname)(root);
|
|
19
|
+
const latest = await findExecutableInTree(root, fileName, /^/, 3);
|
|
20
|
+
if (latest)
|
|
21
|
+
return latest;
|
|
22
|
+
}
|
|
14
23
|
// 千问升级会保留或删除旧版本目录,从同一安装位置重新定位新版。
|
|
15
24
|
if (fileName.toLowerCase() === "qwenworkcn.exe" && /^v?\d+(?:[.-]\d+)+$/i.test((0, node_path_1.basename)((0, node_path_1.dirname)(configuredPath)))) {
|
|
16
25
|
const latest = await findExecutableInTree((0, node_path_1.dirname)((0, node_path_1.dirname)(configuredPath)), fileName, /^/, 1);
|
|
@@ -42,6 +51,16 @@ async function findExecutableInTree(directory, fileName, pattern, depth) {
|
|
|
42
51
|
async function search(directory, fileName, pattern, depth, insideProduct) {
|
|
43
52
|
try {
|
|
44
53
|
const entries = await (0, promises_1.readdir)(directory, { withFileTypes: true });
|
|
54
|
+
// 豆包上层文件是启动器,优先查找新版目录或 app 中的实际程序。
|
|
55
|
+
if (insideProduct && depth > 0 && fileName.toLowerCase() === "doubao.exe") {
|
|
56
|
+
const versions = entries.filter(entry => entry.isDirectory() && (versionDirectory.test(entry.name) || /^app$/i.test(entry.name)));
|
|
57
|
+
versions.sort((left, right) => right.name.replace(/^\D+/, "").localeCompare(left.name.replace(/^\D+/, ""), "en", { numeric: true }));
|
|
58
|
+
for (const entry of versions) {
|
|
59
|
+
const found = await search((0, node_path_1.join)(directory, entry.name), fileName, pattern, depth - 1, true);
|
|
60
|
+
if (found)
|
|
61
|
+
return found;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
45
64
|
for (const entry of entries)
|
|
46
65
|
if (entry.isFile() && insideProduct && entry.name.toLowerCase() === fileName.toLowerCase())
|
|
47
66
|
return (0, node_path_1.join)(directory, entry.name);
|
|
@@ -8,6 +8,7 @@ exports.isQwenApiUnavailableReply = isQwenApiUnavailableReply;
|
|
|
8
8
|
exports.isQwenBridgeHealthPrompt = isQwenBridgeHealthPrompt;
|
|
9
9
|
exports.normalizeQwenImageUrl = normalizeQwenImageUrl;
|
|
10
10
|
exports.decodeQwenDataImage = decodeQwenDataImage;
|
|
11
|
+
exports.parseQwenFinalFileDetails = parseQwenFinalFileDetails;
|
|
11
12
|
const node_crypto_1 = require("node:crypto");
|
|
12
13
|
const cdp_draft_1 = require("../cdp-draft");
|
|
13
14
|
const attachments_1 = require("../../attachments");
|
|
@@ -45,7 +46,7 @@ function normalizeQwenImageUrl(address) {
|
|
|
45
46
|
}
|
|
46
47
|
if (/^\/\//.test(decoded) || /^[\\/]{2}/.test(decoded))
|
|
47
48
|
return undefined;
|
|
48
|
-
const path = decoded.replaceAll("\\", "/").replace(/^\/+/, "");
|
|
49
|
+
const path = decoded.replaceAll("\\", "/").replace(/\/{2,}/g, "/").replace(/^\/+/, "");
|
|
49
50
|
if (!/^[A-Za-z]:\//.test(path))
|
|
50
51
|
return undefined;
|
|
51
52
|
const url = new URL(`file:///${path}`);
|
|
@@ -61,6 +62,27 @@ function decodeQwenDataImage(address) {
|
|
|
61
62
|
const contentType = (0, attachments_1.detectImageContentType)(data);
|
|
62
63
|
return contentType && contentType === match[1].toLowerCase() ? { data, contentType } : undefined;
|
|
63
64
|
}
|
|
65
|
+
/** 只解析“已展示最终文件”工具自己的 JSON 参数,不读取消息正文中的路径。 */
|
|
66
|
+
function parseQwenFinalFileDetails(value) {
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(value);
|
|
69
|
+
if (!Array.isArray(parsed.files))
|
|
70
|
+
return [];
|
|
71
|
+
return parsed.files.flatMap((item) => {
|
|
72
|
+
if (typeof item?.file_path !== "string")
|
|
73
|
+
return [];
|
|
74
|
+
const path = item.file_path.trim();
|
|
75
|
+
if (!/^[A-Za-z]:[\\/][^\0]*$/.test(path))
|
|
76
|
+
return [];
|
|
77
|
+
const filename = path.replaceAll("\\", "/").split("/").pop() ?? "";
|
|
78
|
+
const address = normalizeQwenImageUrl(`file://${path}`);
|
|
79
|
+
return address && filename ? [{ address, filename }] : [];
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return [];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
64
86
|
function wait(ms, signal) {
|
|
65
87
|
if (signal?.aborted)
|
|
66
88
|
return Promise.reject(new Error("请求已取消"));
|
|
@@ -74,6 +96,7 @@ function wait(ms, signal) {
|
|
|
74
96
|
}
|
|
75
97
|
/** 千问桌面客户端的 CDP/tRPC 通信。 */
|
|
76
98
|
class QwenCdpClient {
|
|
99
|
+
attachmentInput = true;
|
|
77
100
|
socket;
|
|
78
101
|
sequence = 0;
|
|
79
102
|
pending = new Map();
|
|
@@ -180,7 +203,8 @@ class QwenCdpClient {
|
|
|
180
203
|
async direct(text, timeoutMs = 240_000, signal, expectedReply) {
|
|
181
204
|
return (await this.complete(text, timeoutMs, signal, expectedReply)).text;
|
|
182
205
|
}
|
|
183
|
-
async complete(text, timeoutMs = 240_000, signal, expectedReply) {
|
|
206
|
+
async complete(text, timeoutMs = 240_000, signal, expectedReply, attachments) {
|
|
207
|
+
(0, attachments_1.validateAttachments)(attachments);
|
|
184
208
|
if (expectedReply) {
|
|
185
209
|
const draft = await this.evaluate(`document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? ''`);
|
|
186
210
|
if (typeof draft === "string" && draft.trim() && !isQwenBridgeHealthPrompt(draft))
|
|
@@ -188,7 +212,7 @@ class QwenCdpClient {
|
|
|
188
212
|
}
|
|
189
213
|
await this.ensureVisible();
|
|
190
214
|
await this.recoverDraft();
|
|
191
|
-
const ready = await this.evaluate(`(() => { const input = document.querySelector(${JSON.stringify(exports.inputSelector)}); return Boolean(input && !input.innerText.trim() && !document.querySelector('button[aria-label="停止生成"],button[aria-label="Stop generating"]')); })()`);
|
|
215
|
+
const ready = await this.evaluate(`(() => { const input = document.querySelector(${JSON.stringify(exports.inputSelector)}); return Boolean(input && !input.innerText.trim() && !document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')); })()`);
|
|
192
216
|
if (!ready)
|
|
193
217
|
throw new Error("千问输入框含有未发送内容或正在生成回复,未发送新消息");
|
|
194
218
|
const snapshot = await this.evaluate(`JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })))`);
|
|
@@ -202,11 +226,23 @@ class QwenCdpClient {
|
|
|
202
226
|
})()`);
|
|
203
227
|
if (!focused)
|
|
204
228
|
throw new Error("千问输入框未找到");
|
|
205
|
-
await this.
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
229
|
+
const addedIds = attachments?.length ? await this.injectAttachments(attachments) : [];
|
|
230
|
+
try {
|
|
231
|
+
await this.cdp("Input.insertText", { text });
|
|
232
|
+
const sent = await this.evaluate(`(() => { const input = document.querySelector(${JSON.stringify(exports.inputSelector)}); const button = document.querySelector('button[aria-label="发送消息"]'); if (!input || input.innerText.trim() !== ${JSON.stringify(text.trim())} || !button || button.disabled || button.getAttribute('aria-disabled') === 'true') return false; button.click(); return true; })()`);
|
|
233
|
+
if (sent !== true)
|
|
234
|
+
throw new Error("千问发送按钮未就绪或输入校验失败,未发送消息");
|
|
235
|
+
await this.waitFor(`(() => { const input = document.querySelector(${JSON.stringify(exports.inputSelector)}); return Boolean(input && !input.innerText.trim()); })()`, "千问未确认消息已提交");
|
|
236
|
+
}
|
|
237
|
+
catch (error) {
|
|
238
|
+
// CDP 断开时清理也可能失败,保留最初的发送错误。
|
|
239
|
+
try {
|
|
240
|
+
await this.cleanupAttachments(addedIds);
|
|
241
|
+
}
|
|
242
|
+
catch { /* 清理失败不能覆盖原错。 */ }
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
const sessionUrl = String(await this.evaluate("location.href"));
|
|
210
246
|
let previousReply = "";
|
|
211
247
|
let stablePolls = 0;
|
|
212
248
|
const deadline = Date.now() + timeoutMs;
|
|
@@ -219,26 +255,101 @@ class QwenCdpClient {
|
|
|
219
255
|
previousReply = reply;
|
|
220
256
|
if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
|
|
221
257
|
throw new Error("千问生成接口不可用");
|
|
222
|
-
|
|
223
|
-
|
|
258
|
+
const generating = await this.evaluate(`Boolean(document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]'))`);
|
|
259
|
+
if (!generating && (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)) {
|
|
260
|
+
const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl);
|
|
224
261
|
return { text: reply, ...(attachments.length ? { attachments } : {}) };
|
|
225
262
|
}
|
|
226
263
|
}
|
|
227
264
|
throw new Error("千问办公 UI 超时未返回回复");
|
|
228
265
|
}
|
|
229
|
-
async
|
|
230
|
-
const
|
|
266
|
+
async injectAttachments(items) {
|
|
267
|
+
const files = items.map(item => {
|
|
268
|
+
const original = (0, attachments_1.attachmentFilename)(item.filename);
|
|
269
|
+
const dot = original.lastIndexOf(".");
|
|
270
|
+
const suffix = `-mab-${(0, node_crypto_1.randomUUID)()}`;
|
|
271
|
+
const filename = dot > 0 ? `${original.slice(0, dot)}${suffix}${original.slice(dot)}` : `${original}${suffix}`;
|
|
272
|
+
return { filename, contentType: item.contentType, data: Buffer.from(item.data).toString("base64") };
|
|
273
|
+
});
|
|
274
|
+
const result = await this.evaluate(`(async () => {
|
|
275
|
+
const editor = document.querySelector(${JSON.stringify(exports.inputSelector)});
|
|
276
|
+
if (!editor) throw new Error('千问附件输入框未找到');
|
|
277
|
+
const key = Object.keys(editor).find(key => key.startsWith('__reactFiber'));
|
|
278
|
+
let props;
|
|
279
|
+
for (let fiber = editor[key]; fiber; fiber = fiber.return) {
|
|
280
|
+
if (typeof fiber.memoizedProps?.onAddAttachments === 'function') { props = fiber.memoizedProps; break; }
|
|
281
|
+
}
|
|
282
|
+
if (!props) throw new Error('千问当前页面不支持附件输入');
|
|
283
|
+
const existing = [...(props.files ?? []), ...(props.images ?? []), ...(props.slashAddedFiles ?? [])];
|
|
284
|
+
if (existing.length) throw new Error('千问输入框已有附件,未发送消息');
|
|
285
|
+
const cleanupAdded = (ids, names = []) => {
|
|
286
|
+
const currentEditor = document.querySelector(${JSON.stringify(exports.inputSelector)});
|
|
287
|
+
const currentKey = Object.keys(currentEditor ?? {}).find(key => key.startsWith('__reactFiber'));
|
|
288
|
+
let current;
|
|
289
|
+
for (let fiber = currentKey && currentEditor ? currentEditor[currentKey] : null; fiber; fiber = fiber.return) {
|
|
290
|
+
if (typeof fiber.memoizedProps?.onAddAttachments === 'function') { current = fiber.memoizedProps; break; }
|
|
291
|
+
}
|
|
292
|
+
if (!current) return;
|
|
293
|
+
for (const item of current.images ?? []) if (ids.includes(item.id) || names.includes(item.filename)) current.onRemoveImage?.(item.id);
|
|
294
|
+
for (const item of current.files ?? []) if (ids.includes(item.id) || names.includes(item.filename)) current.onRemoveFile?.(item.id);
|
|
295
|
+
};
|
|
296
|
+
const files = ${JSON.stringify(files)}.map(item => {
|
|
297
|
+
const binary = atob(item.data); const bytes = new Uint8Array(binary.length);
|
|
298
|
+
for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index);
|
|
299
|
+
return new File([bytes], item.filename, { type: item.contentType });
|
|
300
|
+
});
|
|
301
|
+
let uploaded;
|
|
302
|
+
try { uploaded = await props.onAddAttachments(files); }
|
|
303
|
+
catch (error) {
|
|
304
|
+
try { cleanupAdded([], files.map(file => file.name)); } catch { /* 保留原生上传错误。 */ }
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
const added = [...(uploaded?.images ?? []), ...(uploaded?.files ?? [])];
|
|
308
|
+
const ids = added.map(item => item.id).filter(id => typeof id === 'string');
|
|
309
|
+
if (added.length !== files.length || ids.length !== files.length || added.some(item => item.isLoading)) {
|
|
310
|
+
try { cleanupAdded(ids, files.map(file => file.name)); } catch { /* 保留附件确认错误。 */ }
|
|
311
|
+
throw new Error('千问附件上传未确认,未发送消息');
|
|
312
|
+
}
|
|
313
|
+
return ids;
|
|
314
|
+
})()`);
|
|
315
|
+
if (!Array.isArray(result))
|
|
316
|
+
throw new Error("千问附件上传未确认,未发送消息");
|
|
317
|
+
return result;
|
|
318
|
+
}
|
|
319
|
+
async cleanupAttachments(ids) {
|
|
320
|
+
if (!ids.length)
|
|
321
|
+
return;
|
|
322
|
+
await this.evaluate(`(() => {
|
|
323
|
+
const editor = document.querySelector(${JSON.stringify(exports.inputSelector)}); if (!editor) return;
|
|
324
|
+
const key = Object.keys(editor).find(key => key.startsWith('__reactFiber')); const ids = ${JSON.stringify(ids)};
|
|
325
|
+
for (let fiber = editor[key]; fiber; fiber = fiber.return) {
|
|
326
|
+
const props = fiber.memoizedProps; if (typeof props?.onAddAttachments !== 'function') continue;
|
|
327
|
+
for (const item of props.images ?? []) if (ids.includes(item.id)) props.onRemoveImage?.(item.id);
|
|
328
|
+
for (const item of props.files ?? []) if (ids.includes(item.id)) props.onRemoveFile?.(item.id);
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
})()`);
|
|
332
|
+
}
|
|
333
|
+
async readArtifacts(beforeIds, sessionUrl) {
|
|
334
|
+
const collectArtifacts = `(() => {
|
|
335
|
+
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
231
336
|
const before = new Set(${JSON.stringify([...beforeIds])}); const files = [];
|
|
232
337
|
for (const part of document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})) {
|
|
233
338
|
if (before.has(part.getAttribute('data-message-id'))) continue;
|
|
234
339
|
const message = part.closest?.('[data-assistant-message-id]') || part;
|
|
235
340
|
for (const image of (message.querySelectorAll?.('img[src^="data:image/"]') ?? [])) files.push({ address: image.getAttribute('src'), filename: image.getAttribute('alt') || '' });
|
|
236
|
-
for (const
|
|
341
|
+
for (const button of (message.querySelectorAll?.('button') ?? [])) {
|
|
342
|
+
if (!button.innerText.includes('已展示最终文件')) continue;
|
|
343
|
+
for (const detail of (button.parentElement?.parentElement?.querySelectorAll?.('pre[data-slot="tool-input-details"]') ?? [])) {
|
|
344
|
+
files.push({ details: detail.textContent || '' });
|
|
345
|
+
}
|
|
346
|
+
}
|
|
237
347
|
}
|
|
238
348
|
return JSON.stringify(files);
|
|
239
349
|
})()`;
|
|
240
350
|
// 工具区域由 React 异步展开,点击和读取必须分开执行。
|
|
241
351
|
await this.evaluate(`(() => {
|
|
352
|
+
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
242
353
|
const before = new Set(${JSON.stringify([...beforeIds])});
|
|
243
354
|
for (const part of document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})) {
|
|
244
355
|
if (before.has(part.getAttribute('data-message-id'))) continue;
|
|
@@ -251,12 +362,13 @@ class QwenCdpClient {
|
|
|
251
362
|
})()`);
|
|
252
363
|
let encoded = "[]";
|
|
253
364
|
for (let attempt = 0; attempt < 12; attempt++) {
|
|
254
|
-
encoded = String(await this.
|
|
365
|
+
encoded = String(await this.evaluateArtifactResult(collectArtifacts, sessionUrl) ?? "[]");
|
|
255
366
|
if (encoded !== "[]")
|
|
256
367
|
break;
|
|
257
368
|
await wait(250);
|
|
258
369
|
}
|
|
259
370
|
const files = [...new Map(JSON.parse(encoded || "[]")
|
|
371
|
+
.flatMap((item) => item.details ? parseQwenFinalFileDetails(item.details) : [item])
|
|
260
372
|
.map((item) => [item.address, item]).filter(([address]) => typeof address === "string")).values()];
|
|
261
373
|
const dataImages = files.map((item) => ({ ...item, image: decodeQwenDataImage(item.address) })).filter((item) => Boolean(item.image));
|
|
262
374
|
const addresses = files.map((item) => normalizeQwenImageUrl(item.address)).filter((value) => Boolean(value)).slice(0, Math.max(0, attachments_1.MAX_ATTACHMENTS - dataImages.length));
|
|
@@ -265,30 +377,70 @@ class QwenCdpClient {
|
|
|
265
377
|
(0, attachments_1.validateAttachments)(attachments);
|
|
266
378
|
return attachments;
|
|
267
379
|
}
|
|
268
|
-
const downloaded = await this.
|
|
380
|
+
const downloaded = await this.evaluateArtifactResult(`(async () => {
|
|
381
|
+
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
269
382
|
const urls = ${JSON.stringify(addresses)}; const result = []; let total = 0;
|
|
270
383
|
for (const url of urls) {
|
|
271
384
|
const response = await fetch(url); if (!response.ok || !response.body) continue;
|
|
272
385
|
const reader = response.body.getReader(); const chunks = []; let size = 0;
|
|
273
|
-
try { for (;;) { const item = await reader.read(); if (item.done) break; size += item.value.byteLength; total += item.value.byteLength; if (size > ${attachments_1.MAX_ATTACHMENT_BYTES} || total > ${attachments_1.MAX_TOTAL_ATTACHMENT_BYTES}) throw new Error('
|
|
386
|
+
try { for (;;) { const item = await reader.read(); if (item.done) break; size += item.value.byteLength; total += item.value.byteLength; if (size > ${attachments_1.MAX_ATTACHMENT_BYTES} || total > ${attachments_1.MAX_TOTAL_ATTACHMENT_BYTES}) throw new Error('千问附件过大'); chunks.push(item.value); } }
|
|
274
387
|
finally { reader.releaseLock(); }
|
|
275
388
|
const bytes = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; }
|
|
276
389
|
let binary = ''; for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
|
|
277
390
|
result.push({ url, data: btoa(binary), contentType: response.headers.get('content-type')?.split(';')[0] || '' });
|
|
278
391
|
}
|
|
279
392
|
return result;
|
|
280
|
-
})()
|
|
393
|
+
})()`, sessionUrl);
|
|
281
394
|
for (const item of downloaded) {
|
|
282
395
|
const data = new Uint8Array(Buffer.from(item.data, "base64"));
|
|
283
396
|
const contentType = (0, attachments_1.detectImageContentType)(data);
|
|
284
|
-
if (!contentType)
|
|
285
|
-
continue;
|
|
286
397
|
const filename = (0, attachments_1.attachmentFilename)(decodeURIComponent(new URL(item.url).pathname.split("/").pop() || `qwen-${(0, node_crypto_1.randomUUID)()}.jpg`));
|
|
287
|
-
|
|
398
|
+
const mime = contentType ?? (item.contentType.startsWith("image/") ? "application/octet-stream" : item.contentType || "application/octet-stream");
|
|
399
|
+
attachments.push({ kind: contentType ? "image" : "file", data, filename, contentType: mime });
|
|
288
400
|
}
|
|
401
|
+
const unique = new Map();
|
|
402
|
+
for (const item of attachments) {
|
|
403
|
+
const hash = (0, node_crypto_1.createHash)("sha256").update(item.data).digest("hex");
|
|
404
|
+
unique.set(`${item.kind}:${hash}`, item);
|
|
405
|
+
}
|
|
406
|
+
attachments.splice(0, attachments.length, ...unique.values());
|
|
289
407
|
(0, attachments_1.validateAttachments)(attachments);
|
|
290
408
|
return attachments;
|
|
291
409
|
}
|
|
410
|
+
/** 将页面结果留在本轮临时缓存,避免图片或视频超过 CDP 单条响应上限。 */
|
|
411
|
+
async evaluateArtifactResult(expression, sessionUrl) {
|
|
412
|
+
const cacheKey = `__mab_qwen_artifacts_${(0, node_crypto_1.randomUUID)()}`;
|
|
413
|
+
const maxLength = Math.ceil(attachments_1.MAX_TOTAL_ATTACHMENT_BYTES / 3) * 4 + 1_048_576;
|
|
414
|
+
try {
|
|
415
|
+
const length = await this.evaluate(`(async () => {
|
|
416
|
+
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
417
|
+
const encoded = JSON.stringify(await (${expression}));
|
|
418
|
+
if (typeof encoded !== 'string' || encoded.length > ${maxLength}) throw new Error('千问附件结果过大或无效');
|
|
419
|
+
window[${JSON.stringify(cacheKey)}] = encoded;
|
|
420
|
+
return encoded.length;
|
|
421
|
+
})()`);
|
|
422
|
+
if (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0 || length > maxLength)
|
|
423
|
+
throw new Error("千问附件编码长度无效");
|
|
424
|
+
const parts = [];
|
|
425
|
+
for (let offset = 0; offset < length; offset += 262_144) {
|
|
426
|
+
const end = Math.min(offset + 262_144, length);
|
|
427
|
+
const part = await this.evaluate(`(() => {
|
|
428
|
+
if (location.href !== ${JSON.stringify(sessionUrl)}) throw new Error('千问会话已切换,停止采集附件');
|
|
429
|
+
return window[${JSON.stringify(cacheKey)}]?.slice(${offset}, ${end});
|
|
430
|
+
})()`);
|
|
431
|
+
if (typeof part !== "string" || part.length !== end - offset)
|
|
432
|
+
throw new Error("千问附件分块读取不完整");
|
|
433
|
+
parts.push(part);
|
|
434
|
+
}
|
|
435
|
+
return JSON.parse(parts.join(""));
|
|
436
|
+
}
|
|
437
|
+
finally {
|
|
438
|
+
try {
|
|
439
|
+
await this.evaluate(`delete window[${JSON.stringify(cacheKey)}]`);
|
|
440
|
+
}
|
|
441
|
+
catch { /* 断连时保留原始错误。 */ }
|
|
442
|
+
}
|
|
443
|
+
}
|
|
292
444
|
onMessage(raw) {
|
|
293
445
|
let message;
|
|
294
446
|
try {
|
|
@@ -307,13 +459,13 @@ class QwenCdpClient {
|
|
|
307
459
|
}
|
|
308
460
|
async ensureVisible() {
|
|
309
461
|
await this.evaluate(`(async () => {
|
|
310
|
-
if (document.querySelector('button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问桌面端正在生成回复');
|
|
462
|
+
if (document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问桌面端正在生成回复');
|
|
311
463
|
// 隐藏窗口会暂停消息渲染,使桌面端的提交前检查一直等不到确认。
|
|
312
464
|
if (document.hidden && typeof window.desktopApi?.focusMainWindow === 'function') await window.desktopApi.focusMainWindow();
|
|
313
465
|
})()`);
|
|
314
466
|
}
|
|
315
467
|
recoverDraft() {
|
|
316
|
-
return (0, cdp_draft_1.recoverCdpDraft)(this.evaluate.bind(this), exports.inputSelector, 'button[aria-label="停止生成"],button[aria-label="Stop generating"]', this.options.dataDir);
|
|
468
|
+
return (0, cdp_draft_1.recoverCdpDraft)(this.evaluate.bind(this), exports.inputSelector, 'button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]', this.options.dataDir);
|
|
317
469
|
}
|
|
318
470
|
async cdp(method, params = {}, timeoutMs = this.options.timeoutMs) {
|
|
319
471
|
if (!this.socket)
|
|
@@ -11,7 +11,7 @@ const desktop_launch_1 = require("../desktop-launch");
|
|
|
11
11
|
const CHAT_HEARTBEAT_INTERVAL_MS = 2 * 60 * 60_000;
|
|
12
12
|
exports.qwenworkManifest = {
|
|
13
13
|
id: "qwenwork",
|
|
14
|
-
version: "1.0.
|
|
14
|
+
version: "1.0.16",
|
|
15
15
|
displayName: "千问办公",
|
|
16
16
|
entry: "dist/index.js",
|
|
17
17
|
apiVersion: "1",
|
|
@@ -26,6 +26,7 @@ function asNumber(value, fallback) {
|
|
|
26
26
|
/** 千问插件由后台守护,所有通道共用请求队列和恢复流程。 */
|
|
27
27
|
class QwenworkPlugin {
|
|
28
28
|
manifest = exports.qwenworkManifest;
|
|
29
|
+
get attachmentInput() { return Boolean(this.relayTarget || this.client?.attachmentInput); }
|
|
29
30
|
sessionOperations = [];
|
|
30
31
|
injectedClient;
|
|
31
32
|
client;
|
|
@@ -226,8 +227,10 @@ class QwenworkPlugin {
|
|
|
226
227
|
try {
|
|
227
228
|
if (!this.client.connected())
|
|
228
229
|
throw new Error("千问 CDP 已断开,等待空闲后自动恢复");
|
|
230
|
+
if (request.attachments?.length && (!this.client.attachmentInput || !this.client.complete))
|
|
231
|
+
throw new Error("千问当前客户端不支持附件输入");
|
|
229
232
|
const response = this.client.complete
|
|
230
|
-
? await this.client.complete(request.task, request.timeoutMs ?? 240_000)
|
|
233
|
+
? await this.client.complete(request.task, request.timeoutMs ?? 240_000, undefined, undefined, request.attachments)
|
|
231
234
|
: { text: await this.complete(request.task, request.timeoutMs ?? 240_000) };
|
|
232
235
|
if ((0, cdp_client_1.isQwenApiUnavailableReply)(response.text))
|
|
233
236
|
throw new Error("千问生成接口不可用");
|
package/package.json
CHANGED