agent-bridge-qwenwork 1.0.12 → 1.0.14

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.
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MAX_TOTAL_ATTACHMENT_BYTES = exports.MAX_ATTACHMENTS = exports.MAX_ATTACHMENT_BYTES = void 0;
4
+ exports.detectImageContentType = detectImageContentType;
5
+ exports.attachmentFilename = attachmentFilename;
6
+ exports.validateAttachment = validateAttachment;
7
+ exports.validateAttachments = validateAttachments;
8
+ exports.asAttachments = asAttachments;
9
+ exports.MAX_ATTACHMENT_BYTES = 32 * 1024 * 1024;
10
+ exports.MAX_ATTACHMENTS = 8;
11
+ exports.MAX_TOTAL_ATTACHMENT_BYTES = 64 * 1024 * 1024;
12
+ function detectImageContentType(data) {
13
+ if (data.length >= 8 && data.slice(0, 8).every((value, index) => value === [137, 80, 78, 71, 13, 10, 26, 10][index]))
14
+ return "image/png";
15
+ if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff)
16
+ return "image/jpeg";
17
+ if (data.length >= 12 && String.fromCharCode(...data.slice(0, 4)) === "RIFF" && String.fromCharCode(...data.slice(8, 12)) === "WEBP")
18
+ return "image/webp";
19
+ return undefined;
20
+ }
21
+ function attachmentFilename(filename) {
22
+ if (typeof filename !== "string" || /[\u0000-\u001f\u007f]/.test(filename))
23
+ throw new Error("附件文件名无效");
24
+ const name = filename.split(/[\\/]/).pop() ?? "";
25
+ if (!name.trim() || name === "." || name === "..")
26
+ throw new Error("附件文件名无效");
27
+ return name;
28
+ }
29
+ function validateAttachment(item) {
30
+ if (!item || !(item.data instanceof Uint8Array) || item.data.byteLength === 0)
31
+ throw new Error("附件内容不能为空");
32
+ if (item.data.byteLength > exports.MAX_ATTACHMENT_BYTES)
33
+ throw new Error("单个附件不能超过 32 MiB");
34
+ attachmentFilename(item.filename);
35
+ if (item.kind !== "image" && item.kind !== "file")
36
+ throw new Error("附件类型无效");
37
+ if (typeof item.contentType !== "string" || !/^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+$/.test(item.contentType))
38
+ throw new Error("附件 MIME 类型无效");
39
+ if (item.kind === "image") {
40
+ const detected = detectImageContentType(item.data);
41
+ if (!detected || detected !== item.contentType.toLowerCase())
42
+ throw new Error("图片内容与 MIME 类型不一致");
43
+ }
44
+ }
45
+ function validateAttachments(items) {
46
+ if (!items)
47
+ return;
48
+ if (!Array.isArray(items))
49
+ throw new Error("附件列表无效");
50
+ if (items.length > exports.MAX_ATTACHMENTS)
51
+ throw new Error("单条消息最多包含 8 个附件");
52
+ let total = 0;
53
+ for (const item of items) {
54
+ validateAttachment(item);
55
+ total += item.data.byteLength;
56
+ }
57
+ if (total > exports.MAX_TOTAL_ATTACHMENT_BYTES)
58
+ throw new Error("单条消息附件总大小不能超过 64 MiB");
59
+ }
60
+ function asAttachments(images) {
61
+ return (images ?? []).map((image) => ({ ...image, kind: "image" }));
62
+ }
@@ -6,8 +6,11 @@ exports.verifyQwenHeartbeatReply = verifyQwenHeartbeatReply;
6
6
  exports.isQwenHeartbeatReplyComplete = isQwenHeartbeatReplyComplete;
7
7
  exports.isQwenApiUnavailableReply = isQwenApiUnavailableReply;
8
8
  exports.isQwenBridgeHealthPrompt = isQwenBridgeHealthPrompt;
9
+ exports.normalizeQwenImageUrl = normalizeQwenImageUrl;
10
+ exports.decodeQwenDataImage = decodeQwenDataImage;
9
11
  const node_crypto_1 = require("node:crypto");
10
12
  const cdp_draft_1 = require("../cdp-draft");
13
+ const attachments_1 = require("../../attachments");
11
14
  exports.assistantMessageSelector = '[data-message-id][data-part-type="text"]:not([data-conversation-user-text="true"])';
12
15
  exports.inputSelector = '.chat-input-editor-text[contenteditable="true"]';
13
16
  function freshAssistantMessages(beforeIds, messages) {
@@ -28,6 +31,36 @@ function isQwenApiUnavailableReply(reply) {
28
31
  function isQwenBridgeHealthPrompt(text) {
29
32
  return /^这是后台健康检测。请只回复 MAB_QWEN_[A-Z0-9]+,不要添加任何其它文字。$/.test(text.trim());
30
33
  }
34
+ /** 千问返回的 file://D:%5C... 链接不是标准 URL,统一转换为本地文件 URL。 */
35
+ function normalizeQwenImageUrl(address) {
36
+ if (typeof address !== "string" || !address.toLowerCase().startsWith("file://"))
37
+ return undefined;
38
+ const raw = address.slice(7);
39
+ let decoded;
40
+ try {
41
+ decoded = decodeURIComponent(raw);
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ if (/^\/\//.test(decoded) || /^[\\/]{2}/.test(decoded))
47
+ return undefined;
48
+ const path = decoded.replaceAll("\\", "/").replace(/^\/+/, "");
49
+ if (!/^[A-Za-z]:\//.test(path))
50
+ return undefined;
51
+ const url = new URL(`file:///${path}`);
52
+ if (url.hostname || url.search || url.hash)
53
+ return undefined;
54
+ return url.href;
55
+ }
56
+ function decodeQwenDataImage(address) {
57
+ const match = /^data:(image\/(?:png|jpeg|webp));base64,([A-Za-z0-9+/=]+)$/i.exec(address);
58
+ if (!match)
59
+ return undefined;
60
+ const data = new Uint8Array(Buffer.from(match[2], "base64"));
61
+ const contentType = (0, attachments_1.detectImageContentType)(data);
62
+ return contentType && contentType === match[1].toLowerCase() ? { data, contentType } : undefined;
63
+ }
31
64
  function wait(ms, signal) {
32
65
  if (signal?.aborted)
33
66
  return Promise.reject(new Error("请求已取消"));
@@ -145,6 +178,9 @@ class QwenCdpClient {
145
178
  });
146
179
  }
147
180
  async direct(text, timeoutMs = 240_000, signal, expectedReply) {
181
+ return (await this.complete(text, timeoutMs, signal, expectedReply)).text;
182
+ }
183
+ async complete(text, timeoutMs = 240_000, signal, expectedReply) {
148
184
  if (expectedReply) {
149
185
  const draft = await this.evaluate(`document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? ''`);
150
186
  if (typeof draft === "string" && draft.trim() && !isQwenBridgeHealthPrompt(draft))
@@ -183,11 +219,58 @@ class QwenCdpClient {
183
219
  previousReply = reply;
184
220
  if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
185
221
  throw new Error("千问生成接口不可用");
186
- if (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)
187
- return reply;
222
+ if (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3) {
223
+ const attachments = expectedReply ? [] : await this.readImages(beforeIds);
224
+ return { text: reply, ...(attachments.length ? { attachments } : {}) };
225
+ }
188
226
  }
189
227
  throw new Error("千问办公 UI 超时未返回回复");
190
228
  }
229
+ async readImages(beforeIds) {
230
+ const encoded = await this.evaluate(`(() => {
231
+ const before = new Set(${JSON.stringify([...beforeIds])}); const files = [];
232
+ for (const part of document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})) {
233
+ if (before.has(part.getAttribute('data-message-id'))) continue;
234
+ const message = part.closest?.('[data-assistant-message-id]') || part;
235
+ for (const button of (message.querySelectorAll?.('button') ?? [])) if (button.innerText.includes('已展示最终文件')) button.click();
236
+ for (const image of (message.querySelectorAll?.('img[src^="data:image/"]') ?? [])) files.push({ address: image.getAttribute('src'), filename: image.getAttribute('alt') || '' });
237
+ for (const link of (message.querySelectorAll?.('a[href]') ?? [])) files.push({ address: link.getAttribute('href'), filename: link.innerText || '' });
238
+ }
239
+ return JSON.stringify(files);
240
+ })()`);
241
+ const files = [...new Map(JSON.parse(encoded || "[]")
242
+ .map((item) => [item.address, item]).filter(([address]) => typeof address === "string")).values()];
243
+ const dataImages = files.map((item) => ({ ...item, image: decodeQwenDataImage(item.address) })).filter((item) => Boolean(item.image));
244
+ const addresses = files.map((item) => normalizeQwenImageUrl(item.address)).filter((value) => Boolean(value)).slice(0, Math.max(0, attachments_1.MAX_ATTACHMENTS - dataImages.length));
245
+ const attachments = dataImages.map((item) => ({ kind: "image", data: item.image.data, filename: (0, attachments_1.attachmentFilename)(item.filename || `qwen-${(0, node_crypto_1.randomUUID)()}.jpg`), contentType: item.image.contentType }));
246
+ if (!addresses.length) {
247
+ (0, attachments_1.validateAttachments)(attachments);
248
+ return attachments;
249
+ }
250
+ const downloaded = await this.evaluate(`(async () => {
251
+ const urls = ${JSON.stringify(addresses)}; const result = []; let total = 0;
252
+ for (const url of urls) {
253
+ const response = await fetch(url); if (!response.ok || !response.body) continue;
254
+ const reader = response.body.getReader(); const chunks = []; let size = 0;
255
+ 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); } }
256
+ finally { reader.releaseLock(); }
257
+ const bytes = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; }
258
+ let binary = ''; for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
259
+ result.push({ url, data: btoa(binary), contentType: response.headers.get('content-type')?.split(';')[0] || '' });
260
+ }
261
+ return result;
262
+ })()`);
263
+ for (const item of downloaded) {
264
+ const data = new Uint8Array(Buffer.from(item.data, "base64"));
265
+ const contentType = (0, attachments_1.detectImageContentType)(data);
266
+ if (!contentType)
267
+ continue;
268
+ const filename = (0, attachments_1.attachmentFilename)(decodeURIComponent(new URL(item.url).pathname.split("/").pop() || `qwen-${(0, node_crypto_1.randomUUID)()}.jpg`));
269
+ attachments.push({ kind: "image", data, filename, contentType });
270
+ }
271
+ (0, attachments_1.validateAttachments)(attachments);
272
+ return attachments;
273
+ }
191
274
  onMessage(raw) {
192
275
  let message;
193
276
  try {
@@ -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.12",
14
+ version: "1.0.14",
15
15
  displayName: "千问办公",
16
16
  entry: "dist/index.js",
17
17
  apiVersion: "1",
@@ -171,8 +171,7 @@ class QwenworkPlugin {
171
171
  await this.recovery;
172
172
  if (this.state === "stopped" || (!this.relayTarget && !this.client))
173
173
  throw new Error("qwenwork 插件未就绪");
174
- const text = await this.enqueueTask(() => this.complete(request.task, request.timeoutMs ?? 240_000));
175
- return { text };
174
+ return this.enqueueTask(() => this.completeRequest(request));
176
175
  }
177
176
  async controlSession(request) {
178
177
  if (request.operation !== "new")
@@ -218,6 +217,32 @@ class QwenworkPlugin {
218
217
  throw error;
219
218
  }
220
219
  }
220
+ async completeRequest(request) {
221
+ if (this.relayTarget) {
222
+ return this.callPlugin(this.relayTarget, request);
223
+ }
224
+ if (!this.client)
225
+ throw new Error("qwenwork 插件未就绪");
226
+ try {
227
+ if (!this.client.connected())
228
+ throw new Error("千问 CDP 已断开,等待空闲后自动恢复");
229
+ const response = this.client.complete
230
+ ? await this.client.complete(request.task, request.timeoutMs ?? 240_000)
231
+ : { text: await this.complete(request.task, request.timeoutMs ?? 240_000) };
232
+ if ((0, cdp_client_1.isQwenApiUnavailableReply)(response.text))
233
+ throw new Error("千问生成接口不可用");
234
+ this.failures = 0;
235
+ this.state = "ready";
236
+ this.message = "";
237
+ return response;
238
+ }
239
+ catch (error) {
240
+ this.message = error instanceof Error ? error.message : String(error);
241
+ this.failures = this.client.connected() ? 0 : 2;
242
+ this.state = "degraded";
243
+ throw error;
244
+ }
245
+ }
221
246
  registerRoutes(http) {
222
247
  if (!this.adapter)
223
248
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-bridge-qwenwork",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
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.12",
3
+ "version": "1.0.14",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",