agent-bridge-qwenwork 1.0.12 → 1.0.13

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,10 @@ exports.verifyQwenHeartbeatReply = verifyQwenHeartbeatReply;
6
6
  exports.isQwenHeartbeatReplyComplete = isQwenHeartbeatReplyComplete;
7
7
  exports.isQwenApiUnavailableReply = isQwenApiUnavailableReply;
8
8
  exports.isQwenBridgeHealthPrompt = isQwenBridgeHealthPrompt;
9
+ exports.normalizeQwenImageUrl = normalizeQwenImageUrl;
9
10
  const node_crypto_1 = require("node:crypto");
10
11
  const cdp_draft_1 = require("../cdp-draft");
12
+ const attachments_1 = require("../../attachments");
11
13
  exports.assistantMessageSelector = '[data-message-id][data-part-type="text"]:not([data-conversation-user-text="true"])';
12
14
  exports.inputSelector = '.chat-input-editor-text[contenteditable="true"]';
13
15
  function freshAssistantMessages(beforeIds, messages) {
@@ -28,6 +30,28 @@ function isQwenApiUnavailableReply(reply) {
28
30
  function isQwenBridgeHealthPrompt(text) {
29
31
  return /^这是后台健康检测。请只回复 MAB_QWEN_[A-Z0-9]+,不要添加任何其它文字。$/.test(text.trim());
30
32
  }
33
+ /** 千问返回的 file://D:%5C... 链接不是标准 URL,统一转换为本地文件 URL。 */
34
+ function normalizeQwenImageUrl(address) {
35
+ if (typeof address !== "string" || !address.toLowerCase().startsWith("file://"))
36
+ return undefined;
37
+ const raw = address.slice(7);
38
+ let decoded;
39
+ try {
40
+ decoded = decodeURIComponent(raw);
41
+ }
42
+ catch {
43
+ return undefined;
44
+ }
45
+ if (/^\/\//.test(decoded) || /^[\\/]{2}/.test(decoded))
46
+ return undefined;
47
+ const path = decoded.replaceAll("\\", "/").replace(/^\/+/, "");
48
+ if (!/^[A-Za-z]:\//.test(path))
49
+ return undefined;
50
+ const url = new URL(`file:///${path}`);
51
+ if (url.hostname || url.search || url.hash)
52
+ return undefined;
53
+ return url.href;
54
+ }
31
55
  function wait(ms, signal) {
32
56
  if (signal?.aborted)
33
57
  return Promise.reject(new Error("请求已取消"));
@@ -145,6 +169,9 @@ class QwenCdpClient {
145
169
  });
146
170
  }
147
171
  async direct(text, timeoutMs = 240_000, signal, expectedReply) {
172
+ return (await this.complete(text, timeoutMs, signal, expectedReply)).text;
173
+ }
174
+ async complete(text, timeoutMs = 240_000, signal, expectedReply) {
148
175
  if (expectedReply) {
149
176
  const draft = await this.evaluate(`document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? ''`);
150
177
  if (typeof draft === "string" && draft.trim() && !isQwenBridgeHealthPrompt(draft))
@@ -183,11 +210,43 @@ class QwenCdpClient {
183
210
  previousReply = reply;
184
211
  if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
185
212
  throw new Error("千问生成接口不可用");
186
- if (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)
187
- return reply;
213
+ if (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3) {
214
+ const attachments = expectedReply ? [] : await this.readImages(beforeIds);
215
+ return { text: reply, ...(attachments.length ? { attachments } : {}) };
216
+ }
188
217
  }
189
218
  throw new Error("千问办公 UI 超时未返回回复");
190
219
  }
220
+ async readImages(beforeIds) {
221
+ const links = await this.evaluate(`JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].filter(element => ${JSON.stringify([...beforeIds])}.indexOf(element.getAttribute('data-message-id')) < 0).flatMap(element => [...(element.querySelectorAll?.('a[href]') ?? [])].map(a => a.getAttribute('href')).filter(Boolean)))`);
222
+ const addresses = [...new Set(JSON.parse(links || "[]"))].map(normalizeQwenImageUrl).filter((value) => Boolean(value)).slice(0, attachments_1.MAX_ATTACHMENTS);
223
+ if (!addresses.length)
224
+ return [];
225
+ const encoded = await this.evaluate(`(async () => {
226
+ const urls = ${JSON.stringify(addresses)}; const result = []; let total = 0;
227
+ for (const url of urls) {
228
+ const response = await fetch(url); if (!response.ok || !response.body) continue;
229
+ const reader = response.body.getReader(); const chunks = []; let size = 0;
230
+ 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); } }
231
+ finally { reader.releaseLock(); }
232
+ const bytes = new Uint8Array(size); let offset = 0; for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; }
233
+ let binary = ''; for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
234
+ result.push({ url, data: btoa(binary), contentType: response.headers.get('content-type')?.split(';')[0] || '' });
235
+ }
236
+ return result;
237
+ })()`);
238
+ const attachments = [];
239
+ for (const item of encoded) {
240
+ const data = new Uint8Array(Buffer.from(item.data, "base64"));
241
+ const contentType = (0, attachments_1.detectImageContentType)(data);
242
+ if (!contentType)
243
+ continue;
244
+ const filename = (0, attachments_1.attachmentFilename)(decodeURIComponent(new URL(item.url).pathname.split("/").pop() || `qwen-${(0, node_crypto_1.randomUUID)()}.jpg`));
245
+ attachments.push({ kind: "image", data, filename, contentType });
246
+ }
247
+ (0, attachments_1.validateAttachments)(attachments);
248
+ return attachments;
249
+ }
191
250
  onMessage(raw) {
192
251
  let message;
193
252
  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.13",
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.13",
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.13",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",