agent-bridge-qwenwork 1.0.22 → 1.0.23

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.
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentError = void 0;
3
+ exports.AgentOperationError = exports.AgentError = void 0;
4
+ exports.errorDetails = errorDetails;
4
5
  class AgentError extends Error {
5
6
  constructor(message, options) {
6
7
  super(message, options);
@@ -8,3 +9,26 @@ class AgentError extends Error {
8
9
  }
9
10
  }
10
11
  exports.AgentError = AgentError;
12
+ /** 保留底层错误码,避免只留下 fetch failed 或超时这类表层提示。 */
13
+ function errorDetails(error) {
14
+ const parts = [];
15
+ const seen = new Set();
16
+ for (let current = error; current && !seen.has(current) && seen.size < 5;) {
17
+ seen.add(current);
18
+ const value = current;
19
+ const message = typeof value.message === "string" ? value.message : String(current);
20
+ parts.push(`${message}${value.code ? `(${String(value.code)})` : ""}`);
21
+ current = value.cause;
22
+ }
23
+ return parts.join(";原因:") || String(error);
24
+ }
25
+ class AgentOperationError extends AgentError {
26
+ code;
27
+ stage;
28
+ constructor(code, stage, cause) {
29
+ super(`${code}:${stage}失败:${errorDetails(cause)}`, { cause });
30
+ this.code = code;
31
+ this.stage = stage;
32
+ }
33
+ }
34
+ exports.AgentOperationError = AgentOperationError;
@@ -11,6 +11,7 @@ exports.decodeQwenDataImage = decodeQwenDataImage;
11
11
  exports.parseQwenFinalFileDetails = parseQwenFinalFileDetails;
12
12
  const node_crypto_1 = require("node:crypto");
13
13
  const cdp_draft_1 = require("../cdp-draft");
14
+ const agent_1 = require("../../agent");
14
15
  const attachments_1 = require("../../attachments");
15
16
  exports.assistantMessageSelector = '[data-message-id][data-part-type="text"]:not([data-conversation-user-text="true"])';
16
17
  exports.inputSelector = '.chat-input-editor-text[contenteditable="true"]';
@@ -203,66 +204,87 @@ class QwenCdpClient {
203
204
  async direct(text, timeoutMs = 240_000, signal, expectedReply) {
204
205
  return (await this.complete(text, timeoutMs, signal, expectedReply)).text;
205
206
  }
206
- async complete(text, timeoutMs = 240_000, signal, expectedReply, attachments) {
207
- (0, attachments_1.validateAttachments)(attachments);
208
- if (expectedReply) {
209
- const draft = await this.evaluate(`document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? ''`);
210
- if (typeof draft === "string" && draft.trim() && !isQwenBridgeHealthPrompt(draft))
211
- throw new Error("千问输入框有用户草稿,跳过后台健康检测");
212
- }
213
- await this.ensureVisible();
214
- await this.recoverDraft();
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"]')); })()`);
216
- if (!ready)
217
- throw new Error("千问输入框含有未发送内容或正在生成回复,未发送新消息");
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 })))`);
219
- const before = JSON.parse(snapshot || "[]");
220
- const beforeIds = new Set(before.map((message) => message.id).filter((id) => Boolean(id)));
221
- const focused = await this.evaluate(`(() => {
222
- const element = document.querySelector(${JSON.stringify(exports.inputSelector)});
223
- if (!element) return false;
224
- element.focus();
225
- return true;
226
- })()`);
227
- if (!focused)
228
- throw new Error("千问输入框未找到");
229
- const addedIds = attachments?.length ? await this.injectAttachments(attachments) : [];
207
+ async complete(text, timeoutMs = 240_000, signal, expectedReply, attachments, onMessage) {
208
+ let stage = "准备千问办公桌面任务";
209
+ let code = "QWEN_TASK_FAILED";
230
210
  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 断开时清理也可能失败,保留最初的发送错误。
211
+ (0, attachments_1.validateAttachments)(attachments);
212
+ if (expectedReply) {
213
+ const draft = await this.evaluate(`document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? ''`);
214
+ if (typeof draft === "string" && draft.trim() && !isQwenBridgeHealthPrompt(draft))
215
+ throw new Error("千问输入框有用户草稿,跳过后台健康检测");
216
+ }
217
+ await this.ensureVisible();
218
+ await this.recoverDraft();
219
+ 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"]')); })()`);
220
+ if (!ready)
221
+ throw new Error("千问输入框含有未发送内容或正在生成回复,未发送新消息");
222
+ const snapshot = await this.evaluate(`JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })))`);
223
+ const before = JSON.parse(snapshot || "[]");
224
+ const beforeIds = new Set(before.map((message) => message.id).filter((id) => Boolean(id)));
225
+ const focused = await this.evaluate(`(() => {
226
+ const element = document.querySelector(${JSON.stringify(exports.inputSelector)});
227
+ if (!element) return false;
228
+ element.focus();
229
+ return true;
230
+ })()`);
231
+ if (!focused)
232
+ throw new Error("千问输入框未找到");
233
+ stage = "向千问办公上传入站附件(任务尚未提交)";
234
+ const addedIds = attachments?.length ? await this.injectAttachments(attachments) : [];
235
+ stage = "向千问办公提交任务(尚未确认发送)";
236
+ code = "QWEN_SUBMIT_FAILED";
239
237
  try {
240
- await this.cleanupAttachments(addedIds);
238
+ await this.cdp("Input.insertText", { text });
239
+ 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; })()`);
240
+ if (sent !== true)
241
+ throw new Error("千问发送按钮未就绪或输入校验失败,未发送消息");
242
+ await this.waitFor(`(() => { const input = document.querySelector(${JSON.stringify(exports.inputSelector)}); return Boolean(input && !input.innerText.trim()); })()`, "千问未确认消息已提交");
241
243
  }
242
- catch { /* 清理失败不能覆盖原错。 */ }
243
- throw error;
244
- }
245
- const sessionUrl = String(await this.evaluate("location.href"));
246
- let previousReply = "";
247
- let stablePolls = 0;
248
- const deadline = Date.now() + timeoutMs;
249
- while (Date.now() < deadline) {
250
- await wait(2_000, signal);
251
- const messagesJson = await this.evaluate(`JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })))`);
252
- const fresh = freshAssistantMessages(beforeIds, JSON.parse(messagesJson || "[]"));
253
- const reply = fresh.at(-1)?.text.trim() ?? "";
254
- stablePolls = reply && reply === previousReply ? stablePolls + 1 : 0;
255
- previousReply = reply;
256
- if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
257
- throw new Error("千问生成接口不可用");
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);
261
- return { text: reply, ...(attachments.length ? { attachments } : {}) };
244
+ catch (error) {
245
+ // CDP 断开时清理也可能失败,保留最初的发送错误。
246
+ try {
247
+ await this.cleanupAttachments(addedIds);
248
+ }
249
+ catch { /* 清理失败不能覆盖原错。 */ }
250
+ throw error;
262
251
  }
252
+ const sessionUrl = String(await this.evaluate("location.href"));
253
+ stage = "等待千问办公回复(任务已提交,桌面未被停止)";
254
+ code = "QWEN_REPLY_FAILED";
255
+ let previousReply = "";
256
+ let stablePolls = 0;
257
+ const forwarded = new Set();
258
+ const deadline = Date.now() + timeoutMs;
259
+ while (Date.now() < deadline) {
260
+ await wait(2_000, signal);
261
+ const messagesJson = await this.evaluate(`JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })))`);
262
+ const fresh = freshAssistantMessages(beforeIds, JSON.parse(messagesJson || "[]"));
263
+ const reply = fresh.at(-1)?.text.trim() ?? "";
264
+ stablePolls = reply && reply === previousReply ? stablePolls + 1 : 0;
265
+ previousReply = reply;
266
+ if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
267
+ throw new Error("QWEN_REMOTE_ERROR:千问生成接口不可用;桌面仅返回通用错误,未提供服务端错误码;CDP 仍连接,未重启或重新提交任务");
268
+ const generating = await this.evaluate(`Boolean(document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]'))`);
269
+ if (!generating && (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)) {
270
+ stage = "读取千问办公已完成任务的产物(尚未上传 AUN FS)";
271
+ code = "QWEN_ARTIFACT_READ_FAILED";
272
+ const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl);
273
+ return { text: reply, ...(attachments.length ? { attachments } : {}) };
274
+ }
275
+ if (onMessage && generating && reply && stablePolls >= 1 && !forwarded.has(reply) && !isQwenApiUnavailableReply(reply)) {
276
+ await onMessage(reply);
277
+ forwarded.add(reply);
278
+ }
279
+ }
280
+ const permission = await this.permissionStatus(sessionUrl);
281
+ throw new Error(permission ?? `QWEN_REPLY_TIMEOUT:千问办公 UI 超时未返回回复(已等待 ${Math.round(timeoutMs / 1000)} 秒);桌面任务未被停止`);
282
+ }
283
+ catch (error) {
284
+ if (error instanceof agent_1.AgentOperationError)
285
+ throw error;
286
+ throw new agent_1.AgentOperationError(code, stage, error);
263
287
  }
264
- const permission = await this.permissionStatus(sessionUrl);
265
- throw new Error(permission ?? `QWEN_REPLY_TIMEOUT:千问办公 UI 超时未返回回复(已等待 ${Math.round(timeoutMs / 1000)} 秒);桌面任务未被停止`);
266
288
  }
267
289
  async permissionStatus(sessionUrl) {
268
290
  try {
@@ -528,8 +550,12 @@ class QwenCdpClient {
528
550
  }
529
551
  async evaluate(expression) {
530
552
  const response = await this.cdp("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
531
- if (response.result?.exceptionDetails)
532
- throw new Error(`页面 JS 异常: ${JSON.stringify(response.result.exceptionDetails).slice(0, 300)}`);
553
+ if (response.error)
554
+ throw new Error(`千问 CDP Runtime.evaluate 失败:${response.error.message ?? response.error.code}`);
555
+ if (response.result?.exceptionDetails) {
556
+ const details = response.result.exceptionDetails;
557
+ throw new Error(`千问页面 JS 异常:${details.exception?.description ?? details.text ?? JSON.stringify(details)}`);
558
+ }
533
559
  return response.result?.result?.value;
534
560
  }
535
561
  async trpc(path, type, input) {
@@ -2,8 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.QwenworkPlugin = exports.qwenworkManifest = void 0;
4
4
  exports.createQwenworkPlugin = createQwenworkPlugin;
5
- const node_child_process_1 = require("node:child_process");
6
- const node_util_1 = require("node:util");
5
+ const agent_1 = require("../../agent");
7
6
  const openai_adapter_1 = require("./openai-adapter");
8
7
  const cdp_client_1 = require("./cdp-client");
9
8
  const plugin_1 = require("../../plugin");
@@ -11,7 +10,7 @@ const desktop_launch_1 = require("../desktop-launch");
11
10
  const session_history_1 = require("./session-history");
12
11
  exports.qwenworkManifest = {
13
12
  id: "qwenwork",
14
- version: "1.0.22",
13
+ version: "1.0.23",
15
14
  displayName: "千问办公",
16
15
  entry: "dist/index.js",
17
16
  apiVersion: "1",
@@ -43,10 +42,8 @@ class QwenworkPlugin {
43
42
  state = "stopped";
44
43
  message = "";
45
44
  healthIntervalMs;
46
- restartDesktop;
47
45
  healthTimer;
48
46
  recovery;
49
- restart;
50
47
  context;
51
48
  checking = false;
52
49
  failures = 0;
@@ -61,7 +58,6 @@ class QwenworkPlugin {
61
58
  this.configuredCdpPort = options.cdpPort;
62
59
  this.configuredHttpPort = options.httpPort;
63
60
  this.healthIntervalMs = options.healthIntervalMs ?? 30_000;
64
- this.restartDesktop = options.restartDesktop;
65
61
  }
66
62
  async activate(context) {
67
63
  if (this.state === "ready")
@@ -100,26 +96,6 @@ class QwenworkPlugin {
100
96
  workspace: typeof config.workspace === "string" ? config.workspace : undefined,
101
97
  });
102
98
  this.client = client;
103
- this.restart = async () => {
104
- if (config.autoStart === false)
105
- throw new Error("千问自动启动已禁用");
106
- if (process.platform !== "win32")
107
- throw new Error("仅支持在 Windows 上自动重启千问办公");
108
- const executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
109
- if (!executable)
110
- throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
111
- context.logger?.info("正在自动重启千问办公", { executablePath: executable });
112
- await (0, node_util_1.promisify)(node_child_process_1.execFile)("taskkill", ["/IM", "QwenWorkCN.exe", "/T", "/F"], { timeout: 10_000 }).catch(() => undefined);
113
- await (0, desktop_launch_1.launchAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], async () => {
114
- try {
115
- await client.connect();
116
- }
117
- catch (error) {
118
- client.close();
119
- throw error;
120
- }
121
- }, asNumber(config.startupTimeoutMs, 60_000));
122
- };
123
99
  try {
124
100
  await client.connect();
125
101
  }
@@ -138,7 +114,7 @@ class QwenworkPlugin {
138
114
  }
139
115
  }
140
116
  }
141
- this.adapter = new openai_adapter_1.OpenAIAdapter((prompt, signal) => this.enqueueTask(() => this.complete(prompt, asNumber(config.timeoutMs, 240_000), signal)), {
117
+ this.adapter = new openai_adapter_1.OpenAIAdapter((prompt, signal, _context, onMessage) => this.enqueueTask(() => this.complete(prompt, asNumber(config.timeoutMs, 240_000), signal, onMessage)), {
142
118
  onLog: (message) => context.logger?.info(message),
143
119
  onExchange: (direction, text, peer, agentAid) => context.logger?.info("千问通信", { direction, text, peer, agentAid }),
144
120
  });
@@ -201,7 +177,7 @@ class QwenworkPlugin {
201
177
  return { text: "千问办公已创建新会话", sessionId };
202
178
  });
203
179
  }
204
- async complete(prompt, timeoutMs, signal) {
180
+ async complete(prompt, timeoutMs, signal, onMessage) {
205
181
  if (this.relayTarget) {
206
182
  const response = await this.callPlugin(this.relayTarget, { task: prompt, timeoutMs });
207
183
  return response.text;
@@ -211,9 +187,9 @@ class QwenworkPlugin {
211
187
  try {
212
188
  if (!this.client.connected())
213
189
  throw new Error("千问 CDP 已断开,等待空闲后自动恢复");
214
- const reply = await this.client.direct(prompt, timeoutMs, signal);
190
+ const reply = this.client.complete ? (await this.client.complete(prompt, timeoutMs, signal, undefined, undefined, onMessage)).text : await this.client.direct(prompt, timeoutMs, signal);
215
191
  if ((0, cdp_client_1.isQwenApiUnavailableReply)(reply))
216
- throw new Error("千问生成接口不可用");
192
+ throw new agent_1.AgentOperationError("QWEN_REMOTE_ERROR", "等待千问办公回复", new Error("千问生成接口不可用;桌面未提供具体服务端错误码,CDP 仍连接,未重启或重新提交任务"));
217
193
  this.failures = 0;
218
194
  this.state = "ready";
219
195
  this.message = "";
@@ -240,10 +216,10 @@ class QwenworkPlugin {
240
216
  if (request.attachments?.length && (!this.client.attachmentInput || !this.client.complete))
241
217
  throw new Error("千问当前客户端不支持附件输入");
242
218
  const response = this.client.complete
243
- ? await this.client.complete(request.task, request.timeoutMs ?? 240_000, undefined, undefined, request.attachments)
219
+ ? await this.client.complete(request.task, request.timeoutMs ?? 240_000, undefined, undefined, request.attachments, request.onMessage)
244
220
  : { text: await this.complete(request.task, request.timeoutMs ?? 240_000) };
245
221
  if ((0, cdp_client_1.isQwenApiUnavailableReply)(response.text))
246
- throw new Error("千问生成接口不可用");
222
+ throw new agent_1.AgentOperationError("QWEN_REMOTE_ERROR", "等待千问办公回复", new Error("千问生成接口不可用;桌面未提供具体服务端错误码,CDP 仍连接,未重启或重新提交任务"));
247
223
  this.failures = 0;
248
224
  this.state = "ready";
249
225
  this.message = "";
@@ -286,7 +262,7 @@ class QwenworkPlugin {
286
262
  this.pluginStatus = undefined;
287
263
  }
288
264
  startHealthWatch() {
289
- if (this.relayTarget || (!this.client?.healthCheck && !this.client?.chatHeartbeat) || this.healthTimer)
265
+ if (this.relayTarget || !this.client || this.healthTimer)
290
266
  return;
291
267
  this.healthTimer = setInterval(() => { void this.checkHealth(); }, this.healthIntervalMs);
292
268
  this.healthTimer.unref();
@@ -316,12 +292,8 @@ class QwenworkPlugin {
316
292
  return;
317
293
  this.recovery = (async () => {
318
294
  this.state = "starting";
319
- this.context?.logger?.info("千问自动恢复开始", { reason: this.message });
295
+ this.context?.logger?.info("千问 CDP 自动重连开始", { reason: this.message });
320
296
  client.close();
321
- if (this.restartDesktop)
322
- await this.restartDesktop();
323
- else if (this.restart)
324
- await this.restart();
325
297
  await client.connect();
326
298
  await this.verifyConnection(client);
327
299
  if (this.stopped) {
@@ -332,13 +304,13 @@ class QwenworkPlugin {
332
304
  this.message = "";
333
305
  this.failures = 0;
334
306
  this.restarts += 1;
335
- this.context?.logger?.info("千问自动恢复成功", { restarts: this.restarts });
307
+ this.context?.logger?.info("千问 CDP 自动重连成功", { restarts: this.restarts });
336
308
  })().catch((error) => {
337
309
  if (this.stopped)
338
310
  return;
339
311
  this.state = "failed";
340
312
  this.message = error instanceof Error ? error.message : String(error);
341
- this.context?.logger?.error(`千问自动恢复失败,下次心跳继续重试:${this.message}`);
313
+ this.context?.logger?.error(`千问 CDP 重连失败,桌面未重启,下次空闲检查重试:${this.message}`);
342
314
  }).finally(() => { this.recovery = undefined; });
343
315
  return this.recovery;
344
316
  }
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OpenAIAdapter = void 0;
4
4
  exports.messageText = messageText;
5
+ const agent_1 = require("../../agent");
5
6
  const node_http_1 = require("node:http");
6
7
  const node_crypto_1 = require("node:crypto");
7
8
  function json(res, status, value) {
@@ -88,6 +89,9 @@ class OpenAIAdapter {
88
89
  const onClose = () => { if (!res.writableEnded)
89
90
  abort.abort(); };
90
91
  res.once("close", onClose);
92
+ let heartbeat;
93
+ let emit;
94
+ let finish;
91
95
  try {
92
96
  const payload = JSON.parse(await readBody(req));
93
97
  const lastUser = [...(payload.messages ?? [])].reverse().find((message) => message.role === "user");
@@ -99,21 +103,37 @@ class OpenAIAdapter {
99
103
  this.onLog?.(`chat request model=${payload.model ?? this.model} stream=${Boolean(payload.stream)}`);
100
104
  this.onExchange?.("request", prompt, peerId, agentAid);
101
105
  const hasSessionContext = typeof session === "string" || peerId !== undefined || agentAid !== undefined;
102
- const content = await this.complete(prompt, abort.signal, hasSessionContext ? { sessionId: typeof session === "string" ? session : "", peerId, agentAid } : undefined);
103
- this.onExchange?.("reply", content, peerId, agentAid);
104
- if (abort.signal.aborted || res.destroyed)
105
- return;
106
106
  const now = Math.floor(Date.now() / 1000);
107
107
  const id = `chatcmpl-${(0, node_crypto_1.randomUUID)()}`;
108
108
  const model = payload.model ?? this.model;
109
+ const forwarded = new Set();
109
110
  if (payload.stream) {
110
111
  res.statusCode = 200;
111
112
  res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
112
113
  res.setHeader("Cache-Control", "no-cache");
113
114
  res.setHeader("Connection", "keep-alive");
114
- res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: now, model, choices: [{ index: 0, delta: { role: "assistant", content }, finish_reason: null }] })}\n\n`);
115
- res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: now, model, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\n`);
116
- res.end("data: [DONE]\n\n");
115
+ res.flushHeaders();
116
+ const chunk = (delta, finish_reason) => {
117
+ if (!abort.signal.aborted && !res.destroyed)
118
+ res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created: now, model, choices: [{ index: 0, delta, finish_reason }] })}\n\n`);
119
+ };
120
+ emit = text => { if (text.trim() && !forwarded.has(text)) {
121
+ chunk({ role: "assistant", content: `${forwarded.size ? "\n\n" : ""}${text}` }, null);
122
+ forwarded.add(text);
123
+ } };
124
+ finish = () => { chunk({}, "stop"); res.end("data: [DONE]\n\n"); };
125
+ // 只保持 HTTP 连接,不探测或操作桌面任务。
126
+ heartbeat = setInterval(() => { if (!res.destroyed && !abort.signal.aborted)
127
+ res.write(": keep-alive\n\n"); }, 15_000);
128
+ heartbeat.unref();
129
+ }
130
+ const content = await this.complete(prompt, abort.signal, hasSessionContext ? { sessionId: typeof session === "string" ? session : "", peerId, agentAid } : undefined, payload.stream ? async (text) => { emit?.(text); } : undefined);
131
+ this.onExchange?.("reply", content, peerId, agentAid);
132
+ if (abort.signal.aborted || res.destroyed)
133
+ return;
134
+ if (emit && finish) {
135
+ emit(content);
136
+ finish();
117
137
  return;
118
138
  }
119
139
  json(res, 200, {
@@ -126,9 +146,19 @@ class OpenAIAdapter {
126
146
  this.onExchange?.("error", error instanceof Error ? error.message : String(error), peerId, agentAid);
127
147
  if (abort.signal.aborted || res.destroyed)
128
148
  return;
129
- json(res, 500, { error: { message: error instanceof Error ? error.message : String(error), type: "server_error" } });
149
+ const details = (0, agent_1.errorDetails)(error);
150
+ if (emit && finish) {
151
+ emit(`任务处理失败:${details}`);
152
+ finish();
153
+ }
154
+ else {
155
+ const operation = error;
156
+ json(res, operation.stage ? 422 : 500, { error: { message: details, type: operation.stage ? "agent_task_error" : "server_error", ...(operation.code ? { code: operation.code } : {}) } });
157
+ }
130
158
  }
131
159
  finally {
160
+ if (heartbeat)
161
+ clearInterval(heartbeat);
132
162
  res.off("close", onClose);
133
163
  }
134
164
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-bridge-qwenwork",
3
- "version": "1.0.22",
3
+ "version": "1.0.23",
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.22",
3
+ "version": "1.0.23",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",