agent-bridge-qwenwork 1.0.4 → 1.0.6
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/README.md +9 -1
- package/config.schema.json +2 -2
- package/dist/src-ts/plugins/desktop-launch.js +13 -2
- package/dist/src-ts/plugins/qwenwork/cdp-client.js +94 -25
- package/dist/src-ts/plugins/qwenwork/index.js +193 -6
- package/dist/src-ts/plugins/qwenwork/openai-adapter.js +12 -2
- package/package.json +1 -1
- package/plugin.json +2 -2
package/README.md
CHANGED
|
@@ -2,4 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
供 `mu-agent-bridge` 使用的千问办公插件。核心包已内置此插件;独立包适用于单独发布和安装。
|
|
4
4
|
|
|
5
|
-
安装:`npm install -g agent-bridge-qwenwork`。插件需要 Windows 千问办公开启 CDP 端口 `
|
|
5
|
+
安装:`npm install -g agent-bridge-qwenwork`。插件需要 Windows 千问办公开启 CDP 端口 `9228`。
|
|
6
|
+
|
|
7
|
+
`executablePath` 配置保存在独立状态目录,插件升级和重启会继续使用。千问桌面升级后,若路径指向带版本号的目录,插件会从同一安装位置查找最高版本的可执行文件;即使旧版本仍保留,也会启动新版。非版本目录中的固定路径仍优先使用;路径失效时再扫描常见安装目录。重载千问插件后,运行日志会显示实际启动的 `executablePath`。
|
|
8
|
+
|
|
9
|
+
后台每 30 秒检查主页面与连接,每 30 分钟发送一条带随机校验码的真实测试消息。首次启动及恢复后也必须完成真实对话,只有千问原样返回本次校验码才判定可用。失败先标记降级,连续两次失败后自动重启千问并重连 CDP,恢复后还必须通过真实回复验证。AUN、飞书和 HTTP 共用请求队列,恢复不修改 AID 或 owner 配置。`autoStart: false` 禁止自动启动和重启。
|
|
10
|
+
|
|
11
|
+
请求超时或明确返回“API不可用”时立即恢复,已经发送的任务不自动重发,避免重复执行。健康接口 `/api/plugins/qwenwork/health` 的 `lastHeartbeat` 表示最近真实对话验证通过时间,同时返回 `restarts` 和 `recovering`;日志可搜索“千问真实对话心跳通过”“千问心跳失败”“千问自动恢复成功”。自动恢复会结束千问进程及其子进程,可能打断该应用中手动进行的任务;daemon 应在已登录的 Windows 用户桌面会话运行。
|
|
12
|
+
|
|
13
|
+
真实心跳会消耗模型额度,并在当前千问聊天会话留下检测消息;它通过与用户请求相同的发送和取回回复路径运行。云端故障、账号额度不足或登录过期仍可能需要修复服务或账号,验证失败期间不会报告健康。
|
package/config.schema.json
CHANGED
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
"type": "object",
|
|
4
4
|
"properties": {
|
|
5
5
|
"aid": { "type": "string", "description": "复用的 EvolCore 已有 AID" },
|
|
6
|
-
"cdpPort": { "type": "integer", "minimum": 1, "maximum": 65535, "default":
|
|
6
|
+
"cdpPort": { "type": "integer", "minimum": 1, "maximum": 65535, "default": 9228 },
|
|
7
7
|
"httpPort": { "type": "integer", "minimum": 0, "maximum": 65535, "default": 17893 },
|
|
8
8
|
"subChatId": { "type": "string" },
|
|
9
9
|
"chatId": { "type": "string" },
|
|
10
10
|
"workspace": { "type": "string" },
|
|
11
|
-
"executablePath": { "type": "string", "description": "QwenWorkCN.exe
|
|
11
|
+
"executablePath": { "type": "string", "description": "QwenWorkCN.exe 路径,失效时自动查找新版本" },
|
|
12
12
|
"autoStart": { "type": "boolean", "default": true, "description": "CDP 未连接时自动启动千问办公" },
|
|
13
13
|
"startupTimeoutMs": { "type": "integer", "minimum": 1000, "default": 30000 },
|
|
14
14
|
"timeoutMs": { "type": "integer", "minimum": 1000, "default": 240000 },
|
|
@@ -9,8 +9,17 @@ const node_fs_1 = require("node:fs");
|
|
|
9
9
|
const node_path_1 = require("node:path");
|
|
10
10
|
/** 在 Windows 常见安装目录中查找桌面程序,避免依赖单一盘符。 */
|
|
11
11
|
async function findWindowsExecutable(fileName, configured) {
|
|
12
|
-
if (configured?.trim())
|
|
13
|
-
|
|
12
|
+
if (configured?.trim()) {
|
|
13
|
+
const configuredPath = (0, node_path_1.resolve)(configured);
|
|
14
|
+
// 千问升级会保留或删除旧版本目录,从同一安装位置重新定位新版。
|
|
15
|
+
if (fileName.toLowerCase() === "qwenworkcn.exe" && /^v?\d+(?:[.-]\d+)+$/i.test((0, node_path_1.basename)((0, node_path_1.dirname)(configuredPath)))) {
|
|
16
|
+
const latest = await findExecutableInTree((0, node_path_1.dirname)((0, node_path_1.dirname)(configuredPath)), fileName, /^/, 1);
|
|
17
|
+
if (latest)
|
|
18
|
+
return latest;
|
|
19
|
+
}
|
|
20
|
+
if ((0, node_fs_1.existsSync)(configuredPath))
|
|
21
|
+
return configuredPath;
|
|
22
|
+
}
|
|
14
23
|
if (process.platform !== "win32")
|
|
15
24
|
return undefined;
|
|
16
25
|
const pattern = /doubao|豆包|qwen|qwwork|千问/i;
|
|
@@ -38,6 +47,8 @@ async function search(directory, fileName, pattern, depth, insideProduct) {
|
|
|
38
47
|
return (0, node_path_1.join)(directory, entry.name);
|
|
39
48
|
if (depth <= 0)
|
|
40
49
|
return undefined;
|
|
50
|
+
// 按数字比较版本目录,避免 1.2.5 排在 1.2.10 之前。
|
|
51
|
+
entries.sort((left, right) => right.name.localeCompare(left.name, "en", { numeric: true }));
|
|
41
52
|
for (const entry of entries)
|
|
42
53
|
if (entry.isDirectory() && !entry.name.startsWith(".") && (insideProduct || pattern.test(entry.name) || /^(?:Program Files(?: \(x86\))?|Programs)$/i.test(entry.name))) {
|
|
43
54
|
const found = await search((0, node_path_1.join)(directory, entry.name), fileName, pattern, depth - 1, insideProduct || pattern.test(entry.name));
|
|
@@ -2,12 +2,26 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.QwenCdpClient = exports.inputSelector = exports.assistantMessageSelector = void 0;
|
|
4
4
|
exports.freshAssistantMessages = freshAssistantMessages;
|
|
5
|
-
|
|
5
|
+
exports.verifyQwenHeartbeatReply = verifyQwenHeartbeatReply;
|
|
6
|
+
exports.isQwenHeartbeatReplyComplete = isQwenHeartbeatReplyComplete;
|
|
7
|
+
exports.isQwenApiUnavailableReply = isQwenApiUnavailableReply;
|
|
8
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
9
|
exports.assistantMessageSelector = '[data-message-id][data-part-type="text"]:not([data-conversation-user-text="true"])';
|
|
7
10
|
exports.inputSelector = '.chat-input-editor-text[contenteditable="true"]';
|
|
8
11
|
function freshAssistantMessages(beforeIds, messages) {
|
|
9
12
|
return messages.filter((message) => Boolean(message.id) && !beforeIds.has(message.id) && Boolean(message.text?.trim()));
|
|
10
13
|
}
|
|
14
|
+
function verifyQwenHeartbeatReply(expected, actual) {
|
|
15
|
+
if (!isQwenHeartbeatReplyComplete(actual, expected))
|
|
16
|
+
throw new Error(`真实对话心跳未通过:期望 ${expected},实际 ${actual.slice(0, 120)}`);
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
function isQwenHeartbeatReplyComplete(reply, expected) {
|
|
20
|
+
return reply.trim() === expected;
|
|
21
|
+
}
|
|
22
|
+
function isQwenApiUnavailableReply(reply) {
|
|
23
|
+
return /^(?:API|接口)\s*(?:暂时)?不可用[。.!!]?$/i.test(reply.trim());
|
|
24
|
+
}
|
|
11
25
|
function wait(ms, signal) {
|
|
12
26
|
if (signal?.aborted)
|
|
13
27
|
return Promise.reject(new Error("请求已取消"));
|
|
@@ -19,7 +33,7 @@ function wait(ms, signal) {
|
|
|
19
33
|
}, { once: true });
|
|
20
34
|
});
|
|
21
35
|
}
|
|
22
|
-
/** CDP/tRPC
|
|
36
|
+
/** 千问桌面客户端的 CDP/tRPC 通信。 */
|
|
23
37
|
class QwenCdpClient {
|
|
24
38
|
socket;
|
|
25
39
|
sequence = 0;
|
|
@@ -35,14 +49,36 @@ class QwenCdpClient {
|
|
|
35
49
|
fetchImpl: options.fetchImpl,
|
|
36
50
|
};
|
|
37
51
|
}
|
|
38
|
-
connected() { return
|
|
52
|
+
connected() { return this.socket?.readyState === WebSocket.OPEN; }
|
|
53
|
+
async healthCheck() {
|
|
54
|
+
if (!this.socket)
|
|
55
|
+
throw new Error("千问 CDP 尚未连接");
|
|
56
|
+
const result = await this.evaluate(`(() => Boolean(window.electronTRPC && document.querySelector(${JSON.stringify(exports.inputSelector)})))()`);
|
|
57
|
+
if (result !== true)
|
|
58
|
+
throw new Error("千问主页面或输入框无响应");
|
|
59
|
+
}
|
|
60
|
+
async chatHeartbeat() {
|
|
61
|
+
await this.healthCheck();
|
|
62
|
+
const token = `MAB_QWEN_${(0, node_crypto_1.randomUUID)().slice(0, 8).toUpperCase()}`;
|
|
63
|
+
const reply = await this.direct(`这是后台健康检测。请只回复 ${token},不要添加任何其它文字。`, 45_000, undefined, token);
|
|
64
|
+
verifyQwenHeartbeatReply(token, reply);
|
|
65
|
+
}
|
|
66
|
+
async createSession(_name) {
|
|
67
|
+
const snapshot = `(() => ({ url: location.href, messages: document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)}).length, input: Boolean(document.querySelector(${JSON.stringify(exports.inputSelector)})) }))()`;
|
|
68
|
+
const before = await this.evaluate(snapshot);
|
|
69
|
+
const clicked = await this.evaluate(`(() => { const button = document.querySelector('button[aria-label="新任务"]'); if (!button || button.disabled || button.getAttribute('aria-disabled') === 'true') return false; button.click(); return true; })()`);
|
|
70
|
+
if (clicked !== true)
|
|
71
|
+
throw new Error("千问新任务入口未找到或不可用");
|
|
72
|
+
await this.waitFor(`(() => { const state = ${snapshot}; return state.input && state.messages === 0 && state.url !== ${JSON.stringify(before.url)}; })()`, "千问新会话状态校验失败");
|
|
73
|
+
}
|
|
39
74
|
async connect() {
|
|
40
|
-
if (this.
|
|
75
|
+
if (this.connected())
|
|
41
76
|
return;
|
|
77
|
+
this.close();
|
|
42
78
|
const fetchImpl = this.options.fetchImpl ?? fetch;
|
|
43
79
|
let response;
|
|
44
80
|
try {
|
|
45
|
-
response = await fetchImpl(`http://127.0.0.1:${this.options.port}/json
|
|
81
|
+
response = await fetchImpl(`http://127.0.0.1:${this.options.port}/json`, { signal: AbortSignal.timeout(this.options.timeoutMs) });
|
|
46
82
|
}
|
|
47
83
|
catch (error) {
|
|
48
84
|
const code = error?.cause?.code ?? String(error);
|
|
@@ -55,24 +91,34 @@ class QwenCdpClient {
|
|
|
55
91
|
?? targets.find((target) => target.type === "page" && (target.url ?? "").includes("index.html"));
|
|
56
92
|
if (!page?.webSocketDebuggerUrl)
|
|
57
93
|
throw new Error(`未找到千问主窗口 target(客户端是否以 --remote-debugging-port=${this.options.port} 启动?)`);
|
|
58
|
-
|
|
59
|
-
this.socket
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
94
|
+
const socket = new WebSocket(page.webSocketDebuggerUrl);
|
|
95
|
+
this.socket = socket;
|
|
96
|
+
socket.onmessage = (event) => this.onMessage(String(event.data));
|
|
97
|
+
socket.onclose = () => { if (this.socket === socket)
|
|
98
|
+
this.close(); };
|
|
99
|
+
try {
|
|
100
|
+
await new Promise((resolve, reject) => {
|
|
101
|
+
const timer = setTimeout(() => { reject(new Error("CDP WebSocket 连接超时")); }, this.options.timeoutMs);
|
|
102
|
+
socket.onopen = () => { clearTimeout(timer); resolve(); };
|
|
103
|
+
socket.onerror = () => { clearTimeout(timer); reject(new Error("CDP WebSocket 连接失败")); };
|
|
104
|
+
});
|
|
105
|
+
await this.evaluate(`(() => {
|
|
106
|
+
if (!window.__ts_bridge_resps) {
|
|
107
|
+
window.__ts_bridge_resps = [];
|
|
108
|
+
window.electronTRPC.onMessage(message => window.__ts_bridge_resps.push(message));
|
|
109
|
+
}
|
|
110
|
+
return 'ok';
|
|
111
|
+
})()`);
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
this.close();
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
72
117
|
}
|
|
73
118
|
close() {
|
|
74
|
-
this.socket
|
|
119
|
+
const socket = this.socket;
|
|
75
120
|
this.socket = undefined;
|
|
121
|
+
socket?.close();
|
|
76
122
|
for (const pending of this.pending.values())
|
|
77
123
|
pending.reject(new Error("CDP 已关闭"));
|
|
78
124
|
this.pending.clear();
|
|
@@ -85,7 +131,7 @@ class QwenCdpClient {
|
|
|
85
131
|
cwd: this.options.workspace,
|
|
86
132
|
});
|
|
87
133
|
}
|
|
88
|
-
async direct(text, timeoutMs = 240_000, signal) {
|
|
134
|
+
async direct(text, timeoutMs = 240_000, signal, expectedReply) {
|
|
89
135
|
const snapshot = await this.evaluate(`JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })))`);
|
|
90
136
|
const before = JSON.parse(snapshot || "[]");
|
|
91
137
|
const beforeIds = new Set(before.map((message) => message.id).filter((id) => Boolean(id)));
|
|
@@ -114,7 +160,9 @@ class QwenCdpClient {
|
|
|
114
160
|
const reply = fresh.at(-1)?.text.trim() ?? "";
|
|
115
161
|
stablePolls = reply && reply === previousReply ? stablePolls + 1 : 0;
|
|
116
162
|
previousReply = reply;
|
|
117
|
-
if (reply && stablePolls >= 3)
|
|
163
|
+
if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
|
|
164
|
+
throw new Error("千问生成接口不可用");
|
|
165
|
+
if (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)
|
|
118
166
|
return reply;
|
|
119
167
|
}
|
|
120
168
|
throw new Error("千问办公 UI 超时未返回回复");
|
|
@@ -139,9 +187,21 @@ class QwenCdpClient {
|
|
|
139
187
|
if (!this.socket)
|
|
140
188
|
throw new Error("CDP 尚未连接");
|
|
141
189
|
const id = ++this.sequence;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
190
|
+
return new Promise((resolve, reject) => {
|
|
191
|
+
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`CDP ${method} 超时`)); }, timeoutMs);
|
|
192
|
+
this.pending.set(id, {
|
|
193
|
+
resolve: (value) => { clearTimeout(timer); resolve(value); },
|
|
194
|
+
reject: (error) => { clearTimeout(timer); reject(error); },
|
|
195
|
+
});
|
|
196
|
+
try {
|
|
197
|
+
this.socket.send(JSON.stringify({ id, method, params }));
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
this.pending.delete(id);
|
|
201
|
+
clearTimeout(timer);
|
|
202
|
+
reject(error);
|
|
203
|
+
}
|
|
204
|
+
});
|
|
145
205
|
}
|
|
146
206
|
async evaluate(expression) {
|
|
147
207
|
const response = await this.cdp("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true });
|
|
@@ -168,5 +228,14 @@ class QwenCdpClient {
|
|
|
168
228
|
}
|
|
169
229
|
throw new Error(`tRPC ${path} 超时`);
|
|
170
230
|
}
|
|
231
|
+
async waitFor(expression, message) {
|
|
232
|
+
const deadline = Date.now() + this.options.timeoutMs;
|
|
233
|
+
while (Date.now() < deadline) {
|
|
234
|
+
if (await this.evaluate(expression))
|
|
235
|
+
return;
|
|
236
|
+
await wait(200);
|
|
237
|
+
}
|
|
238
|
+
throw new Error(message);
|
|
239
|
+
}
|
|
171
240
|
}
|
|
172
241
|
exports.QwenCdpClient = QwenCdpClient;
|
|
@@ -2,6 +2,8 @@
|
|
|
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
7
|
const openai_adapter_1 = require("./openai-adapter");
|
|
6
8
|
const cdp_client_1 = require("./cdp-client");
|
|
7
9
|
const plugin_1 = require("../../plugin");
|
|
@@ -20,9 +22,10 @@ exports.qwenworkManifest = {
|
|
|
20
22
|
function asNumber(value, fallback) {
|
|
21
23
|
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
22
24
|
}
|
|
23
|
-
/**
|
|
25
|
+
/** 千问插件由后台守护,所有通道共用请求队列和恢复流程。 */
|
|
24
26
|
class QwenworkPlugin {
|
|
25
27
|
manifest = exports.qwenworkManifest;
|
|
28
|
+
sessionOperations = [];
|
|
26
29
|
injectedClient;
|
|
27
30
|
client;
|
|
28
31
|
adapter;
|
|
@@ -36,15 +39,31 @@ class QwenworkPlugin {
|
|
|
36
39
|
requestQueue = Promise.resolve();
|
|
37
40
|
state = "stopped";
|
|
38
41
|
message = "";
|
|
42
|
+
healthIntervalMs;
|
|
43
|
+
restartDesktop;
|
|
44
|
+
healthTimer;
|
|
45
|
+
recovery;
|
|
46
|
+
restart;
|
|
47
|
+
context;
|
|
48
|
+
checking = false;
|
|
49
|
+
failures = 0;
|
|
50
|
+
lastHeartbeat;
|
|
51
|
+
restarts = 0;
|
|
52
|
+
busy = false;
|
|
53
|
+
stopped = true;
|
|
39
54
|
constructor(options = {}) {
|
|
40
55
|
this.injectedClient = options.client;
|
|
41
56
|
this.configuredCdpPort = options.cdpPort;
|
|
42
57
|
this.configuredHttpPort = options.httpPort;
|
|
58
|
+
this.healthIntervalMs = options.healthIntervalMs ?? 30_000;
|
|
59
|
+
this.restartDesktop = options.restartDesktop;
|
|
43
60
|
}
|
|
44
61
|
async activate(context) {
|
|
45
62
|
if (this.state === "ready")
|
|
46
63
|
return;
|
|
47
64
|
this.state = "starting";
|
|
65
|
+
this.stopped = false;
|
|
66
|
+
this.context = context;
|
|
48
67
|
try {
|
|
49
68
|
const config = context.config;
|
|
50
69
|
const relayTarget = config.relayTarget;
|
|
@@ -64,6 +83,27 @@ class QwenworkPlugin {
|
|
|
64
83
|
workspace: typeof config.workspace === "string" ? config.workspace : undefined,
|
|
65
84
|
});
|
|
66
85
|
this.client = client;
|
|
86
|
+
this.restart = async () => {
|
|
87
|
+
if (config.autoStart === false)
|
|
88
|
+
throw new Error("千问自动启动已禁用");
|
|
89
|
+
if (process.platform !== "win32")
|
|
90
|
+
throw new Error("仅支持在 Windows 上自动重启千问办公");
|
|
91
|
+
const executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
|
|
92
|
+
if (!executable)
|
|
93
|
+
throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
|
|
94
|
+
context.logger?.info("正在自动重启千问办公", { executablePath: executable });
|
|
95
|
+
await (0, node_util_1.promisify)(node_child_process_1.execFile)("taskkill", ["/IM", "QwenWorkCN.exe", "/T", "/F"], { timeout: 10_000 }).catch(() => undefined);
|
|
96
|
+
await (0, desktop_launch_1.launchAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], async () => {
|
|
97
|
+
try {
|
|
98
|
+
await client.connect();
|
|
99
|
+
await client.healthCheck?.();
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
client.close();
|
|
103
|
+
throw error;
|
|
104
|
+
}
|
|
105
|
+
}, asNumber(config.startupTimeoutMs, 60_000));
|
|
106
|
+
};
|
|
67
107
|
try {
|
|
68
108
|
await client.connect();
|
|
69
109
|
}
|
|
@@ -73,7 +113,7 @@ class QwenworkPlugin {
|
|
|
73
113
|
const executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
|
|
74
114
|
if (!executable)
|
|
75
115
|
throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
|
|
76
|
-
context.logger?.info(
|
|
116
|
+
context.logger?.info(`正在启动千问办公,等待 CDP ${this.activeCdpPort}`, { executablePath: executable });
|
|
77
117
|
try {
|
|
78
118
|
await (0, desktop_launch_1.launchAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], () => client.connect(), typeof config.startupTimeoutMs === "number" ? config.startupTimeoutMs : 30_000);
|
|
79
119
|
}
|
|
@@ -86,6 +126,7 @@ class QwenworkPlugin {
|
|
|
86
126
|
onLog: (message) => context.logger?.info(message),
|
|
87
127
|
onExchange: (direction, text, peer, agentAid) => context.logger?.info("千问通信", { direction, text, peer, agentAid }),
|
|
88
128
|
});
|
|
129
|
+
this.sessionOperations = this.client?.createSession ? ["new"] : [];
|
|
89
130
|
if (context.http) {
|
|
90
131
|
this.registerRoutes(context.http);
|
|
91
132
|
}
|
|
@@ -94,8 +135,10 @@ class QwenworkPlugin {
|
|
|
94
135
|
if (this.configuredHttpPort > 0)
|
|
95
136
|
await this.adapter.listen(this.configuredHttpPort);
|
|
96
137
|
}
|
|
97
|
-
this.state = "ready";
|
|
138
|
+
this.state = this.client?.chatHeartbeat ? "starting" : "ready";
|
|
98
139
|
this.message = "";
|
|
140
|
+
this.startHealthWatch();
|
|
141
|
+
void this.checkHealth();
|
|
99
142
|
}
|
|
100
143
|
catch (error) {
|
|
101
144
|
this.state = "failed";
|
|
@@ -108,9 +151,10 @@ class QwenworkPlugin {
|
|
|
108
151
|
async deactivate(_reason) {
|
|
109
152
|
await this.cleanup();
|
|
110
153
|
this.state = "stopped";
|
|
154
|
+
this.stopped = true;
|
|
111
155
|
}
|
|
112
156
|
async health() {
|
|
113
|
-
const details = { cdpPort: this.activeCdpPort ?? exports.qwenworkManifest.defaults.cdpPort, httpPort: this.configuredHttpPort ?? exports.qwenworkManifest.defaults.httpPort };
|
|
157
|
+
const details = { cdpPort: this.activeCdpPort ?? exports.qwenworkManifest.defaults.cdpPort, httpPort: this.configuredHttpPort ?? exports.qwenworkManifest.defaults.httpPort, lastHeartbeat: this.lastHeartbeat, restarts: this.restarts, recovering: Boolean(this.recovery) };
|
|
114
158
|
if (this.state === "ready" && this.relayTarget && this.pluginStatus?.(this.relayTarget) !== "ready")
|
|
115
159
|
return { status: "degraded", message: "DSH 中继目标未就绪", details: { ...details, relayTarget: this.relayTarget } };
|
|
116
160
|
if (this.state === "ready" && this.client && !this.client.connected())
|
|
@@ -118,11 +162,30 @@ class QwenworkPlugin {
|
|
|
118
162
|
return { status: this.state, ...(this.message ? { message: this.message } : {}), details };
|
|
119
163
|
}
|
|
120
164
|
async handle(request) {
|
|
121
|
-
if (this.
|
|
165
|
+
if (this.recovery)
|
|
166
|
+
await this.recovery;
|
|
167
|
+
if (this.state === "stopped" || (!this.relayTarget && !this.client))
|
|
122
168
|
throw new Error("qwenwork 插件未就绪");
|
|
123
169
|
const text = await this.enqueue(() => this.complete(request.task, request.timeoutMs ?? 240_000));
|
|
124
170
|
return { text };
|
|
125
171
|
}
|
|
172
|
+
async controlSession(request) {
|
|
173
|
+
if (request.operation !== "new")
|
|
174
|
+
throw new Error(`千问办公不支持会话操作:${String(request.operation)}`);
|
|
175
|
+
const sessionId = request.sessionId?.trim();
|
|
176
|
+
if (!sessionId)
|
|
177
|
+
throw new Error("千问办公新会话缺少 sessionId");
|
|
178
|
+
if (this.busy || this.recovery)
|
|
179
|
+
throw new Error("千问办公当前忙,无法创建新会话");
|
|
180
|
+
if (!this.client?.createSession)
|
|
181
|
+
throw new Error("千问办公当前传输不支持新建会话");
|
|
182
|
+
if (!this.client.connected())
|
|
183
|
+
throw new Error("千问办公 CDP 未连接");
|
|
184
|
+
return this.enqueue(async () => {
|
|
185
|
+
await this.client.createSession(request.name);
|
|
186
|
+
return { text: "千问办公已创建新会话", sessionId };
|
|
187
|
+
});
|
|
188
|
+
}
|
|
126
189
|
async complete(prompt, timeoutMs, signal) {
|
|
127
190
|
if (this.relayTarget) {
|
|
128
191
|
const response = await this.callPlugin(this.relayTarget, { task: prompt, timeoutMs });
|
|
@@ -130,7 +193,34 @@ class QwenworkPlugin {
|
|
|
130
193
|
}
|
|
131
194
|
if (!this.client)
|
|
132
195
|
throw new Error("qwenwork 插件未就绪");
|
|
133
|
-
|
|
196
|
+
if (this.recovery)
|
|
197
|
+
await this.recovery;
|
|
198
|
+
this.busy = true;
|
|
199
|
+
try {
|
|
200
|
+
if (this.state !== "ready")
|
|
201
|
+
await this.recover();
|
|
202
|
+
if (this.state !== "ready")
|
|
203
|
+
throw new Error(this.message || "千问正在恢复");
|
|
204
|
+
const reply = await this.client.direct(prompt, timeoutMs, signal);
|
|
205
|
+
if ((0, cdp_client_1.isQwenApiUnavailableReply)(reply))
|
|
206
|
+
throw new Error("千问生成接口不可用,已触发后台恢复");
|
|
207
|
+
this.failures = 0;
|
|
208
|
+
this.state = "ready";
|
|
209
|
+
this.message = "";
|
|
210
|
+
return reply;
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
if (!signal?.aborted) {
|
|
214
|
+
this.failures = 2;
|
|
215
|
+
this.message = error instanceof Error ? error.message : String(error);
|
|
216
|
+
this.state = "degraded";
|
|
217
|
+
await this.recover();
|
|
218
|
+
}
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
finally {
|
|
222
|
+
this.busy = false;
|
|
223
|
+
}
|
|
134
224
|
}
|
|
135
225
|
registerRoutes(http) {
|
|
136
226
|
if (!this.adapter)
|
|
@@ -143,6 +233,13 @@ class QwenworkPlugin {
|
|
|
143
233
|
}
|
|
144
234
|
}
|
|
145
235
|
async cleanup() {
|
|
236
|
+
if (this.healthTimer)
|
|
237
|
+
clearInterval(this.healthTimer);
|
|
238
|
+
this.healthTimer = undefined;
|
|
239
|
+
this.state = "stopped";
|
|
240
|
+
this.stopped = true;
|
|
241
|
+
if (this.recovery)
|
|
242
|
+
await this.recovery;
|
|
146
243
|
for (const dispose of this.disposers.splice(0))
|
|
147
244
|
dispose();
|
|
148
245
|
await this.adapter?.close();
|
|
@@ -153,6 +250,96 @@ class QwenworkPlugin {
|
|
|
153
250
|
this.callPlugin = undefined;
|
|
154
251
|
this.pluginStatus = undefined;
|
|
155
252
|
}
|
|
253
|
+
startHealthWatch() {
|
|
254
|
+
if (this.relayTarget || !this.client?.healthCheck || this.healthTimer)
|
|
255
|
+
return;
|
|
256
|
+
this.healthTimer = setInterval(() => { void this.checkHealth(); }, this.healthIntervalMs);
|
|
257
|
+
this.healthTimer.unref();
|
|
258
|
+
}
|
|
259
|
+
async checkHealth() {
|
|
260
|
+
if (this.checking || this.busy || this.recovery || this.state === "stopped" || !this.client?.healthCheck)
|
|
261
|
+
return;
|
|
262
|
+
const client = this.client;
|
|
263
|
+
this.checking = true;
|
|
264
|
+
await this.enqueue(async () => {
|
|
265
|
+
try {
|
|
266
|
+
if (this.stopped)
|
|
267
|
+
return;
|
|
268
|
+
if (this.failures >= 2) {
|
|
269
|
+
await this.recover();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (client.chatHeartbeat && this.state === "ready" && this.lastHeartbeat && Date.now() - Date.parse(this.lastHeartbeat) < 30 * 60_000) {
|
|
273
|
+
await client.healthCheck?.();
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
if (client.chatHeartbeat)
|
|
277
|
+
await client.chatHeartbeat();
|
|
278
|
+
else
|
|
279
|
+
await client.healthCheck?.();
|
|
280
|
+
if (this.stopped)
|
|
281
|
+
return;
|
|
282
|
+
this.lastHeartbeat = new Date().toISOString();
|
|
283
|
+
this.failures = 0;
|
|
284
|
+
this.state = "ready";
|
|
285
|
+
this.message = "";
|
|
286
|
+
if (client.chatHeartbeat)
|
|
287
|
+
this.context?.logger?.info("千问真实对话心跳通过", { verifiedAt: this.lastHeartbeat });
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
if (this.stopped)
|
|
291
|
+
return;
|
|
292
|
+
this.state = "degraded";
|
|
293
|
+
this.message = error instanceof Error ? error.message : String(error);
|
|
294
|
+
this.context?.logger?.error(`千问心跳失败:${this.message}`);
|
|
295
|
+
if (++this.failures >= 2)
|
|
296
|
+
await this.recover();
|
|
297
|
+
}
|
|
298
|
+
finally {
|
|
299
|
+
this.checking = false;
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
async recover() {
|
|
304
|
+
if (this.recovery)
|
|
305
|
+
return this.recovery;
|
|
306
|
+
if (this.stopped)
|
|
307
|
+
return;
|
|
308
|
+
this.recovery = (async () => {
|
|
309
|
+
this.state = "starting";
|
|
310
|
+
this.context?.logger?.info("千问自动恢复开始", { reason: this.message });
|
|
311
|
+
this.client?.close();
|
|
312
|
+
if (this.restartDesktop)
|
|
313
|
+
await this.restartDesktop();
|
|
314
|
+
else if (this.restart)
|
|
315
|
+
await this.restart();
|
|
316
|
+
const client = this.client;
|
|
317
|
+
if (!client)
|
|
318
|
+
throw new Error("千问客户端未初始化");
|
|
319
|
+
await client.connect();
|
|
320
|
+
if (client.chatHeartbeat)
|
|
321
|
+
await client.chatHeartbeat();
|
|
322
|
+
else
|
|
323
|
+
await client.healthCheck?.();
|
|
324
|
+
if (this.stopped) {
|
|
325
|
+
client.close();
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
this.state = "ready";
|
|
329
|
+
this.message = "";
|
|
330
|
+
this.failures = 0;
|
|
331
|
+
this.restarts += 1;
|
|
332
|
+
this.lastHeartbeat = new Date().toISOString();
|
|
333
|
+
this.context?.logger?.info("千问自动恢复成功", { restarts: this.restarts });
|
|
334
|
+
})().catch((error) => {
|
|
335
|
+
if (this.stopped)
|
|
336
|
+
return;
|
|
337
|
+
this.state = "failed";
|
|
338
|
+
this.message = error instanceof Error ? error.message : String(error);
|
|
339
|
+
this.context?.logger?.error(`千问自动恢复失败,下次心跳继续重试:${this.message}`);
|
|
340
|
+
}).finally(() => { this.recovery = undefined; });
|
|
341
|
+
return this.recovery;
|
|
342
|
+
}
|
|
156
343
|
enqueue(operation) {
|
|
157
344
|
const run = this.requestQueue.then(operation, operation);
|
|
158
345
|
this.requestQueue = run.then(() => undefined, () => undefined);
|
|
@@ -37,7 +37,7 @@ async function readBody(req) {
|
|
|
37
37
|
}
|
|
38
38
|
return Buffer.concat(chunks).toString("utf8");
|
|
39
39
|
}
|
|
40
|
-
/** OpenAI
|
|
40
|
+
/** 千问办公与平台路由共用的 OpenAI 兼容 HTTP 适配器。 */
|
|
41
41
|
class OpenAIAdapter {
|
|
42
42
|
complete;
|
|
43
43
|
model;
|
|
@@ -72,6 +72,16 @@ class OpenAIAdapter {
|
|
|
72
72
|
json(res, 404, { error: { message: "Not found", type: "invalid_request_error" } });
|
|
73
73
|
return;
|
|
74
74
|
}
|
|
75
|
+
const session = req.headers["x-evolcore-session-id"];
|
|
76
|
+
if (session !== undefined) {
|
|
77
|
+
for (const name of ["x-evolcore-session-id", "x-aun-peer", "x-evolcore-agent-aid"]) {
|
|
78
|
+
const value = req.headers[name];
|
|
79
|
+
if (value !== undefined && (typeof value !== "string" || !value.trim() || value.length > 256 || /[\x00-\x1f\x7f-\x9f]/.test(value))) {
|
|
80
|
+
json(res, 400, { error: { message: `${name} 必须是 1 到 256 个字符且不含控制字符的字符串`, type: "invalid_request_error" } });
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
75
85
|
const abort = new AbortController();
|
|
76
86
|
const peer = req.headers["x-aun-peer"];
|
|
77
87
|
const peerId = typeof peer === "string" && peer.length <= 256 ? peer : undefined;
|
|
@@ -90,7 +100,7 @@ class OpenAIAdapter {
|
|
|
90
100
|
}
|
|
91
101
|
this.onLog?.(`chat request model=${payload.model ?? this.model} stream=${Boolean(payload.stream)}`);
|
|
92
102
|
this.onExchange?.("request", prompt, peerId, agentAid);
|
|
93
|
-
const content = await this.complete(prompt, abort.signal);
|
|
103
|
+
const content = await this.complete(prompt, abort.signal, typeof session === "string" ? { sessionId: session, peerId, agentAid } : undefined);
|
|
94
104
|
this.onExchange?.("reply", content, peerId, agentAid);
|
|
95
105
|
if (abort.signal.aborted || res.destroyed)
|
|
96
106
|
return;
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "qwenwork",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"type": "agent",
|
|
5
5
|
"displayName": "千问办公",
|
|
6
6
|
"entry": "dist/src-ts/plugins/qwenwork/index.js",
|
|
@@ -12,5 +12,5 @@
|
|
|
12
12
|
"health"
|
|
13
13
|
],
|
|
14
14
|
"configSchema": "config.schema.json",
|
|
15
|
-
"clientDownloadUrl": "https://
|
|
15
|
+
"clientDownloadUrl": "https://qwenwork.cn/download"
|
|
16
16
|
}
|