agent-bridge-qwenwork 1.0.21 → 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.
package/dist/src-ts/agent.js
CHANGED
|
@@ -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,65 +204,113 @@ 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
|
-
|
|
208
|
-
|
|
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
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
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.
|
|
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
|
-
|
|
244
|
+
catch (error) {
|
|
245
|
+
// CDP 断开时清理也可能失败,保留最初的发送错误。
|
|
246
|
+
try {
|
|
247
|
+
await this.cleanupAttachments(addedIds);
|
|
248
|
+
}
|
|
249
|
+
catch { /* 清理失败不能覆盖原错。 */ }
|
|
250
|
+
throw error;
|
|
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)} 秒);桌面任务未被停止`);
|
|
244
282
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
if (
|
|
257
|
-
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
return
|
|
283
|
+
catch (error) {
|
|
284
|
+
if (error instanceof agent_1.AgentOperationError)
|
|
285
|
+
throw error;
|
|
286
|
+
throw new agent_1.AgentOperationError(code, stage, error);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
async permissionStatus(sessionUrl) {
|
|
290
|
+
try {
|
|
291
|
+
if (await this.evaluate("typeof window !== 'undefined' && Boolean(window.electronTRPC)") !== true)
|
|
292
|
+
return;
|
|
293
|
+
const chatId = new URL(sessionUrl).searchParams.get("chat");
|
|
294
|
+
if (!chatId)
|
|
295
|
+
return;
|
|
296
|
+
const response = await this.trpc("agent.getAllStreamingStates", "query", {});
|
|
297
|
+
const states = response.result?.data?.json;
|
|
298
|
+
if (!Array.isArray(states))
|
|
299
|
+
return;
|
|
300
|
+
for (const state of states) {
|
|
301
|
+
if (typeof state?.chatId !== "string" || !chatId.endsWith(state.chatId) || !state.chatId || !Array.isArray(state.pendingInteractions))
|
|
302
|
+
continue;
|
|
303
|
+
for (const interaction of state.pendingInteractions) {
|
|
304
|
+
if (interaction?.kind !== "permission")
|
|
305
|
+
continue;
|
|
306
|
+
const input = interaction.toolInput;
|
|
307
|
+
const details = [interaction.toolName, input?.operation, input?.path].filter(value => typeof value === "string").join(" · ");
|
|
308
|
+
return `QWEN_PERMISSION_REQUIRED:千问办公正在等待权限确认(${details});请在千问桌面中确认或拒绝,当前任务未被停止`;
|
|
309
|
+
}
|
|
262
310
|
}
|
|
263
311
|
}
|
|
264
|
-
|
|
312
|
+
catch { /* 旧版客户端不支持该只读接口时,保留原始超时信息。 */ }
|
|
313
|
+
return;
|
|
265
314
|
}
|
|
266
315
|
async injectAttachments(items) {
|
|
267
316
|
const files = items.map(item => {
|
|
@@ -458,11 +507,23 @@ class QwenCdpClient {
|
|
|
458
507
|
pending.resolve(message);
|
|
459
508
|
}
|
|
460
509
|
async ensureVisible() {
|
|
461
|
-
|
|
510
|
+
try {
|
|
511
|
+
await this.evaluate(`(async () => {
|
|
462
512
|
if (document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问桌面端正在生成回复');
|
|
463
513
|
// 隐藏窗口会暂停消息渲染,使桌面端的提交前检查一直等不到确认。
|
|
464
514
|
if (document.hidden && typeof window.desktopApi?.focusMainWindow === 'function') await window.desktopApi.focusMainWindow();
|
|
465
515
|
})()`);
|
|
516
|
+
}
|
|
517
|
+
catch (error) {
|
|
518
|
+
let permission;
|
|
519
|
+
try {
|
|
520
|
+
permission = await this.permissionStatus(String(await this.evaluate("location.href")));
|
|
521
|
+
}
|
|
522
|
+
catch { /* 断线时保留原始错误。 */ }
|
|
523
|
+
if (permission)
|
|
524
|
+
throw new Error(permission);
|
|
525
|
+
throw error;
|
|
526
|
+
}
|
|
466
527
|
}
|
|
467
528
|
recoverDraft() {
|
|
468
529
|
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);
|
|
@@ -489,8 +550,12 @@ class QwenCdpClient {
|
|
|
489
550
|
}
|
|
490
551
|
async evaluate(expression) {
|
|
491
552
|
const response = await this.cdp("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
|
|
492
|
-
if (response.
|
|
493
|
-
throw new Error(
|
|
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
|
+
}
|
|
494
559
|
return response.result?.result?.value;
|
|
495
560
|
}
|
|
496
561
|
async trpc(path, type, input) {
|
|
@@ -2,17 +2,15 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.QwenworkPlugin = exports.qwenworkManifest = void 0;
|
|
4
4
|
exports.createQwenworkPlugin = createQwenworkPlugin;
|
|
5
|
-
const
|
|
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");
|
|
10
9
|
const desktop_launch_1 = require("../desktop-launch");
|
|
11
10
|
const session_history_1 = require("./session-history");
|
|
12
|
-
const CHAT_HEARTBEAT_INTERVAL_MS = 2 * 60 * 60_000;
|
|
13
11
|
exports.qwenworkManifest = {
|
|
14
12
|
id: "qwenwork",
|
|
15
|
-
version: "1.0.
|
|
13
|
+
version: "1.0.23",
|
|
16
14
|
displayName: "千问办公",
|
|
17
15
|
entry: "dist/index.js",
|
|
18
16
|
apiVersion: "1",
|
|
@@ -44,10 +42,8 @@ class QwenworkPlugin {
|
|
|
44
42
|
state = "stopped";
|
|
45
43
|
message = "";
|
|
46
44
|
healthIntervalMs;
|
|
47
|
-
restartDesktop;
|
|
48
45
|
healthTimer;
|
|
49
46
|
recovery;
|
|
50
|
-
restart;
|
|
51
47
|
context;
|
|
52
48
|
checking = false;
|
|
53
49
|
failures = 0;
|
|
@@ -62,7 +58,6 @@ class QwenworkPlugin {
|
|
|
62
58
|
this.configuredCdpPort = options.cdpPort;
|
|
63
59
|
this.configuredHttpPort = options.httpPort;
|
|
64
60
|
this.healthIntervalMs = options.healthIntervalMs ?? 30_000;
|
|
65
|
-
this.restartDesktop = options.restartDesktop;
|
|
66
61
|
}
|
|
67
62
|
async activate(context) {
|
|
68
63
|
if (this.state === "ready")
|
|
@@ -101,26 +96,6 @@ class QwenworkPlugin {
|
|
|
101
96
|
workspace: typeof config.workspace === "string" ? config.workspace : undefined,
|
|
102
97
|
});
|
|
103
98
|
this.client = client;
|
|
104
|
-
this.restart = async () => {
|
|
105
|
-
if (config.autoStart === false)
|
|
106
|
-
throw new Error("千问自动启动已禁用");
|
|
107
|
-
if (process.platform !== "win32")
|
|
108
|
-
throw new Error("仅支持在 Windows 上自动重启千问办公");
|
|
109
|
-
const executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
|
|
110
|
-
if (!executable)
|
|
111
|
-
throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
|
|
112
|
-
context.logger?.info("正在自动重启千问办公", { executablePath: executable });
|
|
113
|
-
await (0, node_util_1.promisify)(node_child_process_1.execFile)("taskkill", ["/IM", "QwenWorkCN.exe", "/T", "/F"], { timeout: 10_000 }).catch(() => undefined);
|
|
114
|
-
await (0, desktop_launch_1.launchAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], async () => {
|
|
115
|
-
try {
|
|
116
|
-
await client.connect();
|
|
117
|
-
}
|
|
118
|
-
catch (error) {
|
|
119
|
-
client.close();
|
|
120
|
-
throw error;
|
|
121
|
-
}
|
|
122
|
-
}, asNumber(config.startupTimeoutMs, 60_000));
|
|
123
|
-
};
|
|
124
99
|
try {
|
|
125
100
|
await client.connect();
|
|
126
101
|
}
|
|
@@ -139,7 +114,7 @@ class QwenworkPlugin {
|
|
|
139
114
|
}
|
|
140
115
|
}
|
|
141
116
|
}
|
|
142
|
-
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)), {
|
|
143
118
|
onLog: (message) => context.logger?.info(message),
|
|
144
119
|
onExchange: (direction, text, peer, agentAid) => context.logger?.info("千问通信", { direction, text, peer, agentAid }),
|
|
145
120
|
});
|
|
@@ -202,7 +177,7 @@ class QwenworkPlugin {
|
|
|
202
177
|
return { text: "千问办公已创建新会话", sessionId };
|
|
203
178
|
});
|
|
204
179
|
}
|
|
205
|
-
async complete(prompt, timeoutMs, signal) {
|
|
180
|
+
async complete(prompt, timeoutMs, signal, onMessage) {
|
|
206
181
|
if (this.relayTarget) {
|
|
207
182
|
const response = await this.callPlugin(this.relayTarget, { task: prompt, timeoutMs });
|
|
208
183
|
return response.text;
|
|
@@ -212,9 +187,9 @@ class QwenworkPlugin {
|
|
|
212
187
|
try {
|
|
213
188
|
if (!this.client.connected())
|
|
214
189
|
throw new Error("千问 CDP 已断开,等待空闲后自动恢复");
|
|
215
|
-
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);
|
|
216
191
|
if ((0, cdp_client_1.isQwenApiUnavailableReply)(reply))
|
|
217
|
-
throw new Error("
|
|
192
|
+
throw new agent_1.AgentOperationError("QWEN_REMOTE_ERROR", "等待千问办公回复", new Error("千问生成接口不可用;桌面未提供具体服务端错误码,CDP 仍连接,未重启或重新提交任务"));
|
|
218
193
|
this.failures = 0;
|
|
219
194
|
this.state = "ready";
|
|
220
195
|
this.message = "";
|
|
@@ -241,10 +216,10 @@ class QwenworkPlugin {
|
|
|
241
216
|
if (request.attachments?.length && (!this.client.attachmentInput || !this.client.complete))
|
|
242
217
|
throw new Error("千问当前客户端不支持附件输入");
|
|
243
218
|
const response = this.client.complete
|
|
244
|
-
? 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)
|
|
245
220
|
: { text: await this.complete(request.task, request.timeoutMs ?? 240_000) };
|
|
246
221
|
if ((0, cdp_client_1.isQwenApiUnavailableReply)(response.text))
|
|
247
|
-
throw new Error("
|
|
222
|
+
throw new agent_1.AgentOperationError("QWEN_REMOTE_ERROR", "等待千问办公回复", new Error("千问生成接口不可用;桌面未提供具体服务端错误码,CDP 仍连接,未重启或重新提交任务"));
|
|
248
223
|
this.failures = 0;
|
|
249
224
|
this.state = "ready";
|
|
250
225
|
this.message = "";
|
|
@@ -287,45 +262,19 @@ class QwenworkPlugin {
|
|
|
287
262
|
this.pluginStatus = undefined;
|
|
288
263
|
}
|
|
289
264
|
startHealthWatch() {
|
|
290
|
-
if (this.relayTarget ||
|
|
265
|
+
if (this.relayTarget || !this.client || this.healthTimer)
|
|
291
266
|
return;
|
|
292
267
|
this.healthTimer = setInterval(() => { void this.checkHealth(); }, this.healthIntervalMs);
|
|
293
268
|
this.healthTimer.unref();
|
|
294
269
|
}
|
|
295
270
|
async checkHealth() {
|
|
296
|
-
if (this.checking || this.busy || this.recovery || this.state === "stopped" ||
|
|
271
|
+
if (this.checking || this.busy || this.recovery || this.state === "stopped" || !this.client)
|
|
297
272
|
return;
|
|
298
|
-
const client = this.client;
|
|
299
273
|
this.checking = true;
|
|
300
274
|
await this.enqueue(async () => {
|
|
301
275
|
try {
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
if (!client.connected()) {
|
|
305
|
-
await this.recover();
|
|
306
|
-
return;
|
|
307
|
-
}
|
|
308
|
-
if (client.chatHeartbeat && (!this.lastHeartbeatAttempt || Date.now() - Date.parse(this.lastHeartbeatAttempt) >= CHAT_HEARTBEAT_INTERVAL_MS)) {
|
|
309
|
-
this.lastHeartbeatAttempt = new Date().toISOString();
|
|
310
|
-
await client.chatHeartbeat();
|
|
311
|
-
this.lastHeartbeat = new Date().toISOString();
|
|
312
|
-
this.state = "ready";
|
|
313
|
-
this.message = "";
|
|
314
|
-
}
|
|
315
|
-
else {
|
|
316
|
-
await client.healthCheck?.();
|
|
317
|
-
}
|
|
318
|
-
if (this.stopped)
|
|
319
|
-
return;
|
|
320
|
-
this.failures = 0;
|
|
321
|
-
}
|
|
322
|
-
catch (error) {
|
|
323
|
-
if (this.stopped)
|
|
324
|
-
return;
|
|
325
|
-
this.state = "degraded";
|
|
326
|
-
this.message = error instanceof Error ? error.message : String(error);
|
|
327
|
-
this.context?.logger?.error(`千问心跳失败:${this.message}`);
|
|
328
|
-
if (++this.failures >= 2 && !client.connected())
|
|
276
|
+
// 健康轮询只看连接状态,不发对话或 CDP 探测,避免打断桌面任务。
|
|
277
|
+
if (!this.stopped && !this.busy && !this.client?.connected())
|
|
329
278
|
await this.recover();
|
|
330
279
|
}
|
|
331
280
|
finally {
|
|
@@ -343,15 +292,9 @@ class QwenworkPlugin {
|
|
|
343
292
|
return;
|
|
344
293
|
this.recovery = (async () => {
|
|
345
294
|
this.state = "starting";
|
|
346
|
-
this.context?.logger?.info("
|
|
295
|
+
this.context?.logger?.info("千问 CDP 自动重连开始", { reason: this.message });
|
|
347
296
|
client.close();
|
|
348
|
-
if (this.restartDesktop)
|
|
349
|
-
await this.restartDesktop();
|
|
350
|
-
else if (this.restart)
|
|
351
|
-
await this.restart();
|
|
352
297
|
await client.connect();
|
|
353
|
-
if (client.chatHeartbeat)
|
|
354
|
-
this.lastHeartbeatAttempt = new Date().toISOString();
|
|
355
298
|
await this.verifyConnection(client);
|
|
356
299
|
if (this.stopped) {
|
|
357
300
|
client.close();
|
|
@@ -360,24 +303,20 @@ class QwenworkPlugin {
|
|
|
360
303
|
this.state = "ready";
|
|
361
304
|
this.message = "";
|
|
362
305
|
this.failures = 0;
|
|
363
|
-
if (client.chatHeartbeat)
|
|
364
|
-
this.lastHeartbeat = new Date().toISOString();
|
|
365
306
|
this.restarts += 1;
|
|
366
|
-
this.context?.logger?.info("
|
|
307
|
+
this.context?.logger?.info("千问 CDP 自动重连成功", { restarts: this.restarts });
|
|
367
308
|
})().catch((error) => {
|
|
368
309
|
if (this.stopped)
|
|
369
310
|
return;
|
|
370
311
|
this.state = "failed";
|
|
371
312
|
this.message = error instanceof Error ? error.message : String(error);
|
|
372
|
-
this.context?.logger?.error(
|
|
313
|
+
this.context?.logger?.error(`千问 CDP 重连失败,桌面未重启,下次空闲检查重试:${this.message}`);
|
|
373
314
|
}).finally(() => { this.recovery = undefined; });
|
|
374
315
|
return this.recovery;
|
|
375
316
|
}
|
|
376
317
|
async verifyConnection(client) {
|
|
377
|
-
if (client.
|
|
378
|
-
|
|
379
|
-
else
|
|
380
|
-
await client.healthCheck?.();
|
|
318
|
+
if (!client.connected())
|
|
319
|
+
throw new Error("千问 CDP 连接恢复失败");
|
|
381
320
|
}
|
|
382
321
|
enqueue(operation) {
|
|
383
322
|
const run = this.requestQueue.then(operation, operation);
|
|
@@ -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.
|
|
115
|
-
|
|
116
|
-
|
|
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
|
-
|
|
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