agent-bridge-qwenwork 1.0.15 → 1.0.20

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
@@ -8,8 +8,12 @@
8
8
 
9
9
  后台每 30 秒检查主页面与 CDP 连接,空闲时每 2 小时最多发送一条带随机校验码的真实测试消息。首次启动及 CDP 恢复后必须完成真实对话,只有千问原样返回本次校验码才判定可用。任务或 `/new` 执行期间不发送检测消息、不执行恢复。普通 API/UI 错误或健康通信失败但 CDP 仍连接时只标记降级;只有 CDP 已断开才允许自动重启千问并重连。AUN、飞书和 HTTP 共用请求队列,恢复不修改 AID 或 owner 配置。`autoStart: false` 禁止自动启动和重启。
10
10
 
11
+ 原生历史读取目前明确不支持:已核验的 CDP/tRPC 客户端只有任务提交等操作,没有只读会话枚举或历史读取接口。插件不会猜测 RPC、把配置中的 `chatId`/`subChatId` 当作当前身份,也不会为读取历史而点击、切换或发送内容;`sessionHistory` 的 scope 固定为本插件配置的 CDP 端口。中继、忙碌、恢复中、离线或未就绪时会返回对应拒绝原因。
12
+
11
13
  请求超时或明确返回“API不可用”时只结束本次请求,已经发送的任务不自动重发,避免重复执行。健康接口 `/api/plugins/qwenwork/health` 的 `lastHeartbeat` 表示最近真实对话验证通过时间,同时返回 `restarts` 和 `recovering`;日志可搜索“千问真实对话心跳通过”“千问心跳失败”“千问自动恢复成功”。自动恢复只在 CDP 断开且当前无任务时结束千问进程及其子进程;daemon 应在已登录的 Windows 用户桌面会话运行。
12
14
 
13
15
  `/new` 在已确认的空白新任务页可重复执行。远程消息和 `/new` 遇到输入框残留时,先将原文、页面地址和时间追加到插件数据目录的 `draft-recovery.jsonl`,再通过编辑器原生删除操作清理;备份失败、内容发生变化或正在生成回复时不清理。后台心跳只清理桥接自己的检测文本,遇到普通用户草稿则跳过。发送消息会点击桌面端“发送消息”按钮并确认输入框清空,避免仅按 Enter 后消息仍停留在输入框。真实通信失败后保持降级,普通 CDP 检查通过不会把状态改回就绪,须有真实回复或真实对话心跳通过。
14
16
 
15
17
  真实心跳会消耗模型额度,并在当前千问聊天会话留下检测消息;它通过与用户请求相同的发送和取回回复路径运行。云端故障、账号额度不足或登录过期仍可能需要修复服务或账号,验证失败期间不会报告健康。
18
+
19
+ 文件、图片、视频附件经桌面原生上传入口送入本轮任务;回传只采集本轮助手通过“已展示最终文件”工具声明的产物,不扫描普通正文中的任意路径。图片按内容去重,视频以 `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.cdp("Input.insertText", { text });
206
- 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; })()`);
207
- if (sent !== true)
208
- throw new Error("千问发送按钮未就绪或输入校验失败,未发送消息");
209
- await this.waitFor(`(() => { const input = document.querySelector(${JSON.stringify(exports.inputSelector)}); return Boolean(input && !input.innerText.trim()); })()`, "千问未确认消息已提交");
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
- if (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3) {
223
- const attachments = expectedReply ? [] : await this.readImages(beforeIds);
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 readImages(beforeIds) {
230
- const collectImages = `(() => {
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 link of (message.querySelectorAll?.('a[href^="file://"]') ?? [])) files.push({ address: link.getAttribute('href'), filename: link.innerText || '' });
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.evaluate(collectImages) ?? "[]");
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.evaluate(`(async () => {
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('千问图片过大'); chunks.push(item.value); } }
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
- attachments.push({ kind: "image", data, filename, contentType });
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 });
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);
288
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)
@@ -360,6 +512,14 @@ class QwenCdpClient {
360
512
  }
361
513
  throw new Error(`tRPC ${path} 超时`);
362
514
  }
515
+ /** 仅开放已核实的会话历史只读查询,不允许从历史 provider 调用 mutation。 */
516
+ async queryHistory(path, input) {
517
+ const result = await this.trpc(path, "query", input);
518
+ const envelope = result;
519
+ if (envelope?.result?.type === "data")
520
+ return envelope.result.data?.json;
521
+ throw new Error(envelope?.result?.error?.json?.message ?? `千问历史查询 ${path} 失败`);
522
+ }
363
523
  async waitFor(expression, message) {
364
524
  const deadline = Date.now() + this.options.timeoutMs;
365
525
  while (Date.now() < deadline) {
@@ -8,10 +8,11 @@ const openai_adapter_1 = require("./openai-adapter");
8
8
  const cdp_client_1 = require("./cdp-client");
9
9
  const plugin_1 = require("../../plugin");
10
10
  const desktop_launch_1 = require("../desktop-launch");
11
+ const session_history_1 = require("./session-history");
11
12
  const CHAT_HEARTBEAT_INTERVAL_MS = 2 * 60 * 60_000;
12
13
  exports.qwenworkManifest = {
13
14
  id: "qwenwork",
14
- version: "1.0.15",
15
+ version: "1.0.20",
15
16
  displayName: "千问办公",
16
17
  entry: "dist/index.js",
17
18
  apiVersion: "1",
@@ -26,6 +27,8 @@ function asNumber(value, fallback) {
26
27
  /** 千问插件由后台守护,所有通道共用请求队列和恢复流程。 */
27
28
  class QwenworkPlugin {
28
29
  manifest = exports.qwenworkManifest;
30
+ sessionHistory;
31
+ get attachmentInput() { return Boolean(this.relayTarget || this.client?.attachmentInput); }
29
32
  sessionOperations = [];
30
33
  injectedClient;
31
34
  client;
@@ -80,6 +83,15 @@ class QwenworkPlugin {
80
83
  this.callPlugin = context.callPlugin;
81
84
  this.pluginStatus = context.pluginStatus;
82
85
  this.activeCdpPort = (0, plugin_1.resolveRuntimePort)(config, context.runtime, "qwenwork", "QWEN_CDP_PORT", this.configuredCdpPort ?? exports.qwenworkManifest.defaults.cdpPort);
86
+ this.sessionHistory = new session_history_1.QwenworkSessionHistoryProvider({
87
+ scope: `qwenwork:cdp:${this.activeCdpPort}`,
88
+ unavailableReason: () => this.relayTarget ? "千问办公中继模式不支持原生历史读取" : this.busy ? "千问办公当前忙,暂不读取历史" : this.recovery ? "千问办公正在恢复,暂不读取历史" : this.client && !this.client.connected() ? "千问办公当前离线,暂不读取历史" : this.state !== "ready" ? "千问办公当前未就绪,暂不读取历史" : "",
89
+ query: async (path, input) => {
90
+ if (!this.client?.queryHistory)
91
+ throw new Error("当前千问客户端没有只读会话查询能力");
92
+ return this.client.queryHistory(path, input);
93
+ },
94
+ });
83
95
  if (!this.relayTarget) {
84
96
  const client = this.injectedClient ?? new cdp_client_1.QwenCdpClient({
85
97
  port: this.activeCdpPort,
@@ -226,8 +238,10 @@ class QwenworkPlugin {
226
238
  try {
227
239
  if (!this.client.connected())
228
240
  throw new Error("千问 CDP 已断开,等待空闲后自动恢复");
241
+ if (request.attachments?.length && (!this.client.attachmentInput || !this.client.complete))
242
+ throw new Error("千问当前客户端不支持附件输入");
229
243
  const response = this.client.complete
230
- ? await this.client.complete(request.task, request.timeoutMs ?? 240_000)
244
+ ? await this.client.complete(request.task, request.timeoutMs ?? 240_000, undefined, undefined, request.attachments)
231
245
  : { text: await this.complete(request.task, request.timeoutMs ?? 240_000) };
232
246
  if ((0, cdp_client_1.isQwenApiUnavailableReply)(response.text))
233
247
  throw new Error("千问生成接口不可用");
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QwenworkSessionHistoryProvider = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const MAX_SESSIONS = 1000;
6
+ const MAX_MESSAGE_PAGES = 20;
7
+ const MESSAGE_PAGE_SIZE = 100;
8
+ const MAX_READ_TURNS = MAX_MESSAGE_PAGES * MESSAGE_PAGE_SIZE;
9
+ function object(value) {
10
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
11
+ }
12
+ function rows(value) {
13
+ if (!Array.isArray(value))
14
+ return { rows: [], malformed: true };
15
+ const valid = value.filter((item) => typeof object(item)?.id === "string");
16
+ return { rows: valid, malformed: valid.length !== value.length };
17
+ }
18
+ function asTime(value) {
19
+ const time = value instanceof Date ? value.toISOString() : typeof value === "string" ? value : undefined;
20
+ return time && Number.isFinite(Date.parse(time)) ? new Date(time).toISOString() : undefined;
21
+ }
22
+ function subChats(value) {
23
+ const chat = object(value);
24
+ if (!Array.isArray(chat?.subChats))
25
+ return { rows: [], malformed: true };
26
+ const valid = chat.subChats.filter((item) => typeof object(item)?.id === "string");
27
+ return { rows: valid, malformed: valid.length !== chat.subChats.length };
28
+ }
29
+ function sessionFromChat(chat) {
30
+ const updatedAt = asTime(chat.updatedAt);
31
+ return { id: chat.id, title: typeof chat.name === "string" && chat.name.trim() ? chat.name.trim() : "未命名会话", ...(updatedAt ? { updatedAt } : {}) };
32
+ }
33
+ function fingerprint(value) {
34
+ return (0, node_crypto_1.createHash)("sha256").update(JSON.stringify(value)).digest("hex");
35
+ }
36
+ /** 千问桌面端内置数据库的只读 tRPC 会话接口。 */
37
+ class QwenworkSessionHistoryProvider {
38
+ mode = "all";
39
+ scope;
40
+ limitation = "读取千问桌面端可列出的任务及其 sub-chat;每个会话最多读取 20 页消息。";
41
+ unavailableReason;
42
+ query;
43
+ cursors = new Map();
44
+ constructor(options) {
45
+ this.scope = options.scope;
46
+ this.unavailableReason = options.unavailableReason;
47
+ this.query = options.query;
48
+ }
49
+ async listSessions(query) {
50
+ if (!this.available())
51
+ return { supported: false, reason: this.unavailableReason() };
52
+ const cursor = this.resolveCursor(query.cursor, "list");
53
+ if (!cursor)
54
+ return { supported: false, reason: "千问会话目录游标无效或已过期,请重新列举" };
55
+ try {
56
+ const [active, archived, deleted] = await Promise.all([
57
+ this.query("chats.list", {}), this.query("chats.listArchived", {}), this.query("chats.listDeleted", {}),
58
+ ]);
59
+ const parsedLists = [rows(active), rows(archived), rows(deleted)];
60
+ if (parsedLists.some(result => result.malformed && result.rows.length === 0))
61
+ return { supported: false, reason: "千问会话目录返回了无法识别的结构" };
62
+ const combined = new Map();
63
+ for (const chat of parsedLists.flatMap(result => result.rows))
64
+ combined.set(chat.id, chat);
65
+ const all = [...combined.values()].sort((a, b) => (asTime(b.updatedAt) ?? "").localeCompare(asTime(a.updatedAt) ?? ""));
66
+ const dataFingerprint = fingerprint(all);
67
+ if (query.cursor && cursor.fingerprint !== dataFingerprint)
68
+ return { supported: false, reason: "千问会话目录在分页期间发生变化,请重新列举" };
69
+ const capReached = all.length > MAX_SESSIONS;
70
+ const limited = all.slice(0, MAX_SESSIONS);
71
+ const limit = Math.max(1, Math.min(100, Math.floor(query.limit) || 50));
72
+ const page = limited.slice(cursor.offset, cursor.offset + limit);
73
+ const nextOffset = cursor.offset + page.length;
74
+ const nextCursor = nextOffset < limited.length ? this.createCursor({ kind: "list", offset: nextOffset, fingerprint: dataFingerprint }) : undefined;
75
+ const missingReasons = [];
76
+ if (parsedLists.some(result => result.malformed))
77
+ missingReasons.push("千问会话目录含有无法识别的条目");
78
+ if (capReached)
79
+ missingReasons.push(`千问会话超过 ${MAX_SESSIONS} 项读取上限`);
80
+ if (page.some(chat => !asTime(chat.updatedAt)))
81
+ missingReasons.push("部分会话缺少有效更新时间,无法判断是否属于今天");
82
+ return {
83
+ supported: true,
84
+ sessions: page.map(sessionFromChat),
85
+ ...(nextCursor ? { nextCursor } : {}),
86
+ complete: !capReached && missingReasons.length === 0,
87
+ missingReasons,
88
+ readAt: new Date().toISOString(),
89
+ };
90
+ }
91
+ catch {
92
+ return { supported: false, reason: "千问会话目录只读查询失败" };
93
+ }
94
+ }
95
+ async readSession(query) {
96
+ if (!this.available())
97
+ return { supported: false, reason: this.unavailableReason() };
98
+ const since = query.since === undefined ? undefined : asTime(query.since);
99
+ if (query.since !== undefined && !since)
100
+ return { supported: false, reason: "千问 since 时间格式无效" };
101
+ const cursor = this.resolveCursor(query.cursor, "read", query.sessionId, since);
102
+ if (!cursor)
103
+ return { supported: false, reason: "千问消息游标无效或已过期,请重新读取会话" };
104
+ try {
105
+ const rawChat = await this.query("chats.get", { id: query.sessionId });
106
+ const chat = object(rawChat);
107
+ if (!chat || chat.id !== query.sessionId)
108
+ return { supported: false, reason: "千问会话不存在或已不可读取" };
109
+ const parsedChildren = subChats(chat);
110
+ const children = parsedChildren.rows;
111
+ const missingReasons = [];
112
+ if (parsedChildren.malformed)
113
+ missingReasons.push("千问 sub-chat 目录缺失或含有无法识别的条目");
114
+ const turns = [];
115
+ const fingerprintMessages = [];
116
+ for (const child of children) {
117
+ let beforeSequence;
118
+ let pageCount = 0;
119
+ let moreBefore = false;
120
+ while (pageCount < MAX_MESSAGE_PAGES) {
121
+ const input = { subChatId: child.id, limit: MESSAGE_PAGE_SIZE, ...(beforeSequence === undefined ? {} : { beforeSequence }) };
122
+ const result = object(await this.query("chats.listBySubChat", input));
123
+ const messages = Array.isArray(result?.messages) ? result.messages : undefined;
124
+ if (!messages) {
125
+ missingReasons.push(`sub-chat ${child.id} 消息列表格式无效`);
126
+ fingerprintMessages.push({ subChatId: child.id, malformed: true, response: result });
127
+ break;
128
+ }
129
+ fingerprintMessages.push({ subChatId: child.id, beforeSequence, result });
130
+ for (const rawMessage of messages) {
131
+ const message = object(rawMessage);
132
+ if (!message) {
133
+ missingReasons.push(`sub-chat ${child.id} 含有无法识别的消息`);
134
+ continue;
135
+ }
136
+ if (message.role !== "user" && message.role !== "assistant")
137
+ continue;
138
+ const time = asTime(message.createdAt);
139
+ if (!time)
140
+ missingReasons.push(`消息 ${String(message.id ?? "未知 ID")} 缺少有效创建时间`);
141
+ if (since && time && Date.parse(time) < Date.parse(since))
142
+ continue;
143
+ if (!Array.isArray(message.parts)) {
144
+ missingReasons.push(`消息 ${String(message.id ?? "未知 ID")} 的 parts 格式无效`);
145
+ continue;
146
+ }
147
+ const visibleParts = [];
148
+ let malformedParts = false;
149
+ for (const rawPart of message.parts) {
150
+ const part = object(rawPart);
151
+ if (!part || typeof part.type !== "string") {
152
+ malformedParts = true;
153
+ continue;
154
+ }
155
+ if (part.type === "text") {
156
+ if (typeof part.text !== "string")
157
+ malformedParts = true;
158
+ else
159
+ visibleParts.push(part.text);
160
+ }
161
+ else if (part.type === "data-file") {
162
+ visibleParts.push(`[附件:${typeof part.filename === "string" ? part.filename : "附件"}]`);
163
+ }
164
+ else if (part.type === "artifact") {
165
+ visibleParts.push(`[文件产物:${typeof part.fileName === "string" ? part.fileName : typeof part.mediaType === "string" ? part.mediaType : "产物"}]`);
166
+ }
167
+ else if (part.type.startsWith("tool-") || ["reasoning", "tool-call", "tool-Thinking", "thinking"].includes(part.type)) {
168
+ // 思考过程和工具调用属于执行细节,不作为用户可见正文。
169
+ }
170
+ else {
171
+ malformedParts = true;
172
+ }
173
+ }
174
+ if (malformedParts)
175
+ missingReasons.push(`消息 ${String(message.id ?? "未知 ID")} 含有无法识别的 parts`);
176
+ const text = visibleParts.join("\n").trim();
177
+ if (!text)
178
+ continue;
179
+ turns.push({ role: message.role, text, ...(typeof message.id === "string" ? { id: message.id } : {}), ...(time ? { time } : {}) });
180
+ }
181
+ pageCount++;
182
+ moreBefore = result?.hasMoreBefore === true;
183
+ if (!moreBefore)
184
+ break;
185
+ const oldest = Number(result?.oldestSequence);
186
+ if (!Number.isSafeInteger(oldest) || oldest < 0 || beforeSequence === oldest) {
187
+ missingReasons.push(`sub-chat ${child.id} 消息分页游标无效`);
188
+ break;
189
+ }
190
+ beforeSequence = oldest;
191
+ }
192
+ if (pageCount === MAX_MESSAGE_PAGES && moreBefore)
193
+ missingReasons.push(`sub-chat ${child.id} 超过 ${MAX_MESSAGE_PAGES} 页读取上限`);
194
+ }
195
+ const unique = new Map();
196
+ for (const turn of turns)
197
+ unique.set(turn.id ?? `${turn.role}:${turn.time ?? ""}:${turn.text}`, turn);
198
+ const allTurns = [...unique.values()].sort((a, b) => (a.time ?? "").localeCompare(b.time ?? "") || (a.id ?? "").localeCompare(b.id ?? ""));
199
+ if (allTurns.length > MAX_READ_TURNS)
200
+ missingReasons.push(`千问会话消息超过 ${MAX_READ_TURNS} 条读取上限`);
201
+ const limitedTurns = allTurns.slice(0, MAX_READ_TURNS);
202
+ const dataFingerprint = fingerprint({ chat, messages: fingerprintMessages });
203
+ if (query.cursor && cursor.fingerprint !== dataFingerprint)
204
+ return { supported: false, reason: "千问会话正文在分页期间发生变化,请重新读取会话" };
205
+ const limit = Math.max(1, Math.min(200, Math.floor(query.limit) || 100));
206
+ const pageTurns = limitedTurns.slice(cursor.offset, cursor.offset + limit);
207
+ const nextOffset = cursor.offset + pageTurns.length;
208
+ const nextCursor = nextOffset < limitedTurns.length ? this.createCursor({ kind: "read", offset: nextOffset, fingerprint: dataFingerprint, sessionId: query.sessionId, ...(since ? { since } : {}) }) : undefined;
209
+ return {
210
+ supported: true,
211
+ session: sessionFromChat(chat),
212
+ turns: pageTurns,
213
+ ...(nextCursor ? { nextCursor } : {}),
214
+ complete: missingReasons.length === 0,
215
+ missingReasons: [...new Set(missingReasons)],
216
+ readAt: new Date().toISOString(),
217
+ };
218
+ }
219
+ catch {
220
+ return { supported: false, reason: "千问会话正文只读查询失败" };
221
+ }
222
+ }
223
+ resolveCursor(token, kind, sessionId, since) {
224
+ const now = Date.now();
225
+ for (const [key, value] of this.cursors)
226
+ if (value.expires <= now)
227
+ this.cursors.delete(key);
228
+ if (token === undefined)
229
+ return { kind, offset: 0, fingerprint: "", ...(sessionId ? { sessionId } : {}), ...(since ? { since } : {}), expires: now + 5 * 60_000 };
230
+ const cursor = this.cursors.get(token);
231
+ if (!cursor || cursor.kind !== kind || cursor.sessionId !== sessionId || cursor.since !== since)
232
+ return undefined;
233
+ this.cursors.delete(token);
234
+ return cursor;
235
+ }
236
+ createCursor(cursor) {
237
+ if (this.cursors.size >= 1000)
238
+ this.cursors.delete(this.cursors.keys().next().value);
239
+ const token = `qwen:${(0, node_crypto_1.randomUUID)()}`;
240
+ this.cursors.set(token, { ...cursor, expires: Date.now() + 5 * 60_000 });
241
+ return token;
242
+ }
243
+ available() { return !this.unavailableReason(); }
244
+ }
245
+ exports.QwenworkSessionHistoryProvider = QwenworkSessionHistoryProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-bridge-qwenwork",
3
- "version": "1.0.15",
3
+ "version": "1.0.20",
4
4
  "description": "agent-bridge 的千问办公插件。",
5
5
  "keywords": [
6
6
  "mu-agent-bridge-plugin",
package/plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "qwenwork",
3
- "version": "1.0.15",
3
+ "version": "1.0.20",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",