agent-bridge-qwenwork 1.0.11 → 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("请求已取消"));
@@ -71,6 +95,7 @@ class QwenCdpClient {
71
95
  verifyQwenHeartbeatReply(token, reply);
72
96
  }
73
97
  async createSession(_name) {
98
+ await this.ensureVisible();
74
99
  await this.recoverDraft();
75
100
  const snapshot = `(() => ({ url: location.href, messages: document.querySelectorAll('[data-message-id]').length, input: document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? null, blank: Boolean(document.querySelector('.new-task-model-selector')) }))()`;
76
101
  const before = await this.evaluate(snapshot);
@@ -144,11 +169,15 @@ class QwenCdpClient {
144
169
  });
145
170
  }
146
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) {
147
175
  if (expectedReply) {
148
176
  const draft = await this.evaluate(`document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? ''`);
149
177
  if (typeof draft === "string" && draft.trim() && !isQwenBridgeHealthPrompt(draft))
150
178
  throw new Error("千问输入框有用户草稿,跳过后台健康检测");
151
179
  }
180
+ await this.ensureVisible();
152
181
  await this.recoverDraft();
153
182
  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"]')); })()`);
154
183
  if (!ready)
@@ -181,11 +210,43 @@ class QwenCdpClient {
181
210
  previousReply = reply;
182
211
  if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
183
212
  throw new Error("千问生成接口不可用");
184
- if (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)
185
- 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
+ }
186
217
  }
187
218
  throw new Error("千问办公 UI 超时未返回回复");
188
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
+ }
189
250
  onMessage(raw) {
190
251
  let message;
191
252
  try {
@@ -202,6 +263,13 @@ class QwenCdpClient {
202
263
  this.pending.delete(message.id);
203
264
  pending.resolve(message);
204
265
  }
266
+ async ensureVisible() {
267
+ await this.evaluate(`(async () => {
268
+ if (document.querySelector('button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问桌面端正在生成回复');
269
+ // 隐藏窗口会暂停消息渲染,使桌面端的提交前检查一直等不到确认。
270
+ if (document.hidden && typeof window.desktopApi?.focusMainWindow === 'function') await window.desktopApi.focusMainWindow();
271
+ })()`);
272
+ }
205
273
  recoverDraft() {
206
274
  return (0, cdp_draft_1.recoverCdpDraft)(this.evaluate.bind(this), exports.inputSelector, 'button[aria-label="停止生成"],button[aria-label="Stop generating"]', this.options.dataDir);
207
275
  }
@@ -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.11",
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.11",
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.11",
3
+ "version": "1.0.13",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",