agent-bridge-qwenwork 1.0.27 → 1.0.30
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,21 +1,60 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.desktopLaunchEnvironment = desktopLaunchEnvironment;
|
|
3
4
|
exports.findWindowsExecutable = findWindowsExecutable;
|
|
4
5
|
exports.findExecutableInTree = findExecutableInTree;
|
|
6
|
+
exports.findChromeExecutable = findChromeExecutable;
|
|
5
7
|
exports.launchAndWait = launchAndWait;
|
|
6
8
|
exports.launchManagedAndWait = launchManagedAndWait;
|
|
7
9
|
exports.restartOwnedAndWait = restartOwnedAndWait;
|
|
10
|
+
exports.selectDesktopPort = selectDesktopPort;
|
|
11
|
+
exports.prepareDesktopPort = prepareDesktopPort;
|
|
8
12
|
exports.terminateWindowsDesktop = terminateWindowsDesktop;
|
|
9
13
|
exports.terminateOwnedProcess = terminateOwnedProcess;
|
|
10
14
|
exports.findChatgptExecutable = findChatgptExecutable;
|
|
11
15
|
exports.waitFor = waitFor;
|
|
12
16
|
const node_child_process_1 = require("node:child_process");
|
|
17
|
+
const node_net_1 = require("node:net");
|
|
13
18
|
const promises_1 = require("node:fs/promises");
|
|
14
19
|
const node_fs_1 = require("node:fs");
|
|
15
20
|
const node_path_1 = require("node:path");
|
|
16
21
|
const node_util_1 = require("node:util");
|
|
17
22
|
const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
|
|
18
23
|
const versionDirectory = /^(?:app[-_ ]?)?v?\d+(?:[.-]\d+)+$/i;
|
|
24
|
+
function desktopLaunchEnvironment(env = process.env, readText = path => (0, node_fs_1.readFileSync)(path, "utf8")) {
|
|
25
|
+
if (process.platform !== "linux")
|
|
26
|
+
return env;
|
|
27
|
+
const display = env.DISPLAY?.match(/:(\d+)(?:\.\d+)?$/)?.[1];
|
|
28
|
+
try {
|
|
29
|
+
const busDirectory = (0, node_path_1.join)(env.HOME ?? "", ".config", "ibus", "bus");
|
|
30
|
+
const files = (0, node_fs_1.readdirSync)(busDirectory).filter(file => /-unix-\d+$/.test(file));
|
|
31
|
+
files.sort((a, b) => Number(b.endsWith(`-unix-${display}`)) - Number(a.endsWith(`-unix-${display}`)));
|
|
32
|
+
for (const file of files) {
|
|
33
|
+
try {
|
|
34
|
+
const bus = Object.fromEntries(readText((0, node_path_1.join)(busDirectory, file)).split(/\r?\n/).filter(line => line.includes("=")).map(line => {
|
|
35
|
+
const separator = line.indexOf("=");
|
|
36
|
+
return [line.slice(0, separator), line.slice(separator + 1)];
|
|
37
|
+
}));
|
|
38
|
+
if (!/^\d+$/.test(bus.IBUS_DAEMON_PID ?? "") || !bus.IBUS_ADDRESS)
|
|
39
|
+
continue;
|
|
40
|
+
const daemonEnv = Object.fromEntries(readText(`/proc/${bus.IBUS_DAEMON_PID}/environ`).split("\0").filter(line => line.includes("=")).map(line => {
|
|
41
|
+
const separator = line.indexOf("=");
|
|
42
|
+
return [line.slice(0, separator), line.slice(separator + 1)];
|
|
43
|
+
}));
|
|
44
|
+
if (!daemonEnv.DBUS_SESSION_BUS_ADDRESS || !daemonEnv.DISPLAY)
|
|
45
|
+
continue;
|
|
46
|
+
return { ...env, DISPLAY: daemonEnv.DISPLAY, DBUS_SESSION_BUS_ADDRESS: daemonEnv.DBUS_SESSION_BUS_ADDRESS, IBUS_ADDRESS: bus.IBUS_ADDRESS, GTK_IM_MODULE: "ibus", QT_IM_MODULE: "ibus", XMODIFIERS: "@im=ibus" };
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return env;
|
|
55
|
+
}
|
|
56
|
+
return env;
|
|
57
|
+
}
|
|
19
58
|
/** 先从 Windows 注册信息和开始菜单解析,失败时再查常见安装目录。 */
|
|
20
59
|
async function findWindowsExecutable(fileName, configured, run = execFileAsync) {
|
|
21
60
|
if (configured?.trim()) {
|
|
@@ -45,7 +84,7 @@ async function findWindowsExecutable(fileName, configured, run = execFileAsync)
|
|
|
45
84
|
const registered = await findRegisteredWindowsExecutable(fileName, run);
|
|
46
85
|
if (registered)
|
|
47
86
|
return registered;
|
|
48
|
-
const pattern = /doubao|豆包|qwen|qwwork|千问|deepseek|harness|dsh/i;
|
|
87
|
+
const pattern = /doubao|豆包|qwen|qwwork|千问|deepseek|harness|dsh|zcode/i;
|
|
49
88
|
const roots = [...new Set([
|
|
50
89
|
process.env.DSH_INSTALL_DIR,
|
|
51
90
|
"D:\\Programs\\DeepSeek Harness",
|
|
@@ -65,7 +104,7 @@ async function findWindowsExecutable(fileName, configured, run = execFileAsync)
|
|
|
65
104
|
}
|
|
66
105
|
async function findRegisteredWindowsExecutable(fileName, run) {
|
|
67
106
|
const target = fileName.replace(/'/g, "''");
|
|
68
|
-
const script = `$ErrorActionPreference='SilentlyContinue';$target='${target}'
|
|
107
|
+
const script = `$ErrorActionPreference='SilentlyContinue';[Console]::OutputEncoding=[Text.Encoding]::UTF8;$target='${target}'
|
|
69
108
|
function Emit-Path($value){if(-not $value){return};$value=[Environment]::ExpandEnvironmentVariables(([string]$value).Trim());if($value.StartsWith('"')){$end=$value.IndexOf('"',1);if($end -gt 1){$value=$value.Substring(1,$end-1)}}elseif($value -match '^(\S+?\.exe)(?:\s|$)'){$value=$Matches[1]};if($value -match '(?i)\.exe$'){[Console]::WriteLine($value)}}
|
|
70
109
|
$keys=@("HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\$target","HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\$target","HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\App Paths\\$target","HKCU:\\Software\\Classes\\Applications\\$target\\shell\\open\\command","HKLM:\\Software\\Classes\\Applications\\$target\\shell\\open\\command")
|
|
71
110
|
foreach($key in $keys){$item=Get-Item $key -ErrorAction SilentlyContinue;if($item){Emit-Path $item.GetValue('')}}
|
|
@@ -96,6 +135,9 @@ async function resolveRegisteredCandidate(fileName, candidate) {
|
|
|
96
135
|
async function findExecutableInTree(directory, fileName, pattern, depth) {
|
|
97
136
|
return search(directory, fileName, pattern, depth, pattern.test(directory));
|
|
98
137
|
}
|
|
138
|
+
function findChromeExecutable() {
|
|
139
|
+
return ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"].find(node_fs_1.existsSync);
|
|
140
|
+
}
|
|
99
141
|
async function search(directory, fileName, pattern, depth, insideProduct) {
|
|
100
142
|
try {
|
|
101
143
|
const entries = await (0, promises_1.readdir)(directory, { withFileTypes: true });
|
|
@@ -129,18 +171,25 @@ async function search(directory, fileName, pattern, depth, insideProduct) {
|
|
|
129
171
|
catch { /* 无权限或目录在扫描期间消失时继续查找 */ }
|
|
130
172
|
return undefined;
|
|
131
173
|
}
|
|
132
|
-
async function launchAndWait(executable, args, connect, timeoutMs, launch = (file, argv) => (0, node_child_process_1.spawn)(file, argv, { detached: true, stdio: "ignore", windowsHide: false })) {
|
|
174
|
+
async function launchAndWait(executable, args, connect, timeoutMs, launch = (file, argv) => (0, node_child_process_1.spawn)(file, argv, { env: desktopLaunchEnvironment(), detached: true, stdio: "ignore", windowsHide: false })) {
|
|
133
175
|
const child = launch(executable, args);
|
|
134
176
|
child.unref();
|
|
135
177
|
return waitFor(connect, timeoutMs, 250);
|
|
136
178
|
}
|
|
137
|
-
async function launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess, launch = (file, argv) => (0, node_child_process_1.spawn)(file, argv, { detached: true, stdio: "ignore", windowsHide: false })) {
|
|
179
|
+
async function launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess, launch = (file, argv) => (0, node_child_process_1.spawn)(file, argv, { env: desktopLaunchEnvironment(), detached: true, stdio: "ignore", windowsHide: false })) {
|
|
138
180
|
if (profileDirectory)
|
|
139
181
|
await (0, promises_1.mkdir)(profileDirectory, { recursive: true });
|
|
140
182
|
const child = launch(executable, profileDirectory ? [...args, `--user-data-dir=${profileDirectory}`] : args);
|
|
183
|
+
// 先等待 spawn,避免异步 error 终止 daemon 或在启动失败后继续轮询。
|
|
184
|
+
const events = child;
|
|
185
|
+
const started = typeof events.once === "function" ? new Promise((resolve, reject) => {
|
|
186
|
+
events.once("error", reject);
|
|
187
|
+
events.once("spawn", resolve);
|
|
188
|
+
}) : Promise.resolve();
|
|
141
189
|
child.unref();
|
|
142
190
|
onProcess(child);
|
|
143
191
|
try {
|
|
192
|
+
await started;
|
|
144
193
|
return await waitFor(connect, timeoutMs, 250);
|
|
145
194
|
}
|
|
146
195
|
catch (error) {
|
|
@@ -154,17 +203,64 @@ async function restartOwnedAndWait(child, executable, args, profileDirectory, co
|
|
|
154
203
|
onProcess(undefined);
|
|
155
204
|
return launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess);
|
|
156
205
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
206
|
+
async function selectDesktopPort(preferred) {
|
|
207
|
+
const available = (port) => new Promise(resolve => {
|
|
208
|
+
const server = (0, node_net_1.createServer)();
|
|
209
|
+
server.once("error", () => resolve(false));
|
|
210
|
+
server.listen(port, "127.0.0.1", () => server.close(error => resolve(!error)));
|
|
211
|
+
});
|
|
212
|
+
if (await available(preferred))
|
|
213
|
+
return preferred;
|
|
214
|
+
return new Promise((resolve, reject) => {
|
|
215
|
+
const server = (0, node_net_1.createServer)();
|
|
216
|
+
server.once("error", reject);
|
|
217
|
+
server.listen(0, "127.0.0.1", () => {
|
|
218
|
+
const address = server.address();
|
|
219
|
+
server.close(error => error ? reject(error) : address && typeof address !== "string" ? resolve(address.port) : reject(new Error("无法分配桌面 CDP 端口")));
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
/** 启动桥接桌面前清理同一安装路径的旧实例,再选择可用 CDP 端口。 */
|
|
224
|
+
async function prepareDesktopPort(executable, preferred, platform = process.platform, terminate = terminateWindowsDesktop) {
|
|
225
|
+
if (platform === "win32")
|
|
226
|
+
await terminate(executable);
|
|
227
|
+
return selectDesktopPort(preferred);
|
|
228
|
+
}
|
|
229
|
+
/** 只清理同一用户、同一安装路径且带 CDP 启动参数的桌面进程。 */
|
|
230
|
+
async function terminateWindowsDesktop(executable, keepPort, platform = process.platform, run = execFileAsync) {
|
|
231
|
+
if (platform !== "win32")
|
|
160
232
|
return [];
|
|
233
|
+
if (keepPort !== undefined && (!Number.isInteger(keepPort) || keepPort < 1 || keepPort > 65535))
|
|
234
|
+
throw new Error("要保留的桌面 CDP 端口无效");
|
|
161
235
|
const script = `
|
|
162
236
|
$ErrorActionPreference = 'Stop'
|
|
237
|
+
$ProgressPreference = 'SilentlyContinue'
|
|
238
|
+
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
|
163
239
|
$target = '${(0, node_path_1.resolve)(executable).replace(/'/g, "''")}'
|
|
164
240
|
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
|
165
|
-
$
|
|
241
|
+
$all = @(Get-CimInstance Win32_Process)
|
|
242
|
+
$processes = @($all | Where-Object { $_.ExecutablePath -ieq $target -and $_.CommandLine -match '(?i)(?:^|[\\s"])--remote-debugging-(?:port|address)(?:=|\\s|")' } | Where-Object { (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid })
|
|
166
243
|
$ids = @($processes.ProcessId)
|
|
167
244
|
$roots = @($processes | Where-Object { $ids -notcontains $_.ParentProcessId })
|
|
245
|
+
${keepPort === undefined ? "" : `
|
|
246
|
+
# 保留有效 CDP 所属进程树,只结束同安装路径的其它重复实例。
|
|
247
|
+
$owners = @(Get-NetTCPConnection -State Listen -LocalPort ${keepPort} | Select-Object -ExpandProperty OwningProcess -Unique)
|
|
248
|
+
if ($owners.Count -ne 1) { throw '无法确认有效 CDP 端口的唯一进程,未清理桌面实例' }
|
|
249
|
+
$byId = @{}; foreach ($item in $all) { $byId[[int]$item.ProcessId] = $item }
|
|
250
|
+
$current = $byId[[int]$owners[0]]
|
|
251
|
+
$keepRoot = $null
|
|
252
|
+
$visited = @{}
|
|
253
|
+
while ($current -and -not $visited.ContainsKey([int]$current.ProcessId)) {
|
|
254
|
+
$visited[[int]$current.ProcessId] = $true
|
|
255
|
+
if ($roots.ProcessId -contains $current.ProcessId) { $keepRoot = $current; break }
|
|
256
|
+
$parent = $byId[[int]$current.ParentProcessId]
|
|
257
|
+
if ($parent -and $parent.CreationDate -gt $current.CreationDate) { break }
|
|
258
|
+
$current = $parent
|
|
259
|
+
}
|
|
260
|
+
if (-not $keepRoot) { throw '无法保留有效 CDP 对应的同用户桌面进程树,未清理桌面实例' }
|
|
261
|
+
$roots = @($roots | Where-Object { $_.ProcessId -ne $keepRoot.ProcessId })
|
|
262
|
+
`}
|
|
263
|
+
$terminated = @()
|
|
168
264
|
foreach ($item in $roots) {
|
|
169
265
|
$current = Get-CimInstance Win32_Process -Filter "ProcessId=$($item.ProcessId)"
|
|
170
266
|
if (-not $current -or $current.CreationDate -ne $item.CreationDate) { continue }
|
|
@@ -172,10 +268,11 @@ foreach ($item in $roots) {
|
|
|
172
268
|
if ($LASTEXITCODE -ne 0 -and (Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue)) { throw "无法结束桌面进程 $($item.ProcessId)" }
|
|
173
269
|
$remaining = Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue
|
|
174
270
|
if ($remaining -and -not $remaining.WaitForExit(10000)) { throw "等待桌面进程退出超时 $($item.ProcessId)" }
|
|
271
|
+
$terminated += [int]$item.ProcessId
|
|
175
272
|
}
|
|
176
|
-
ConvertTo-Json -Compress -InputObject @($
|
|
273
|
+
ConvertTo-Json -Compress -InputObject @($terminated)
|
|
177
274
|
`;
|
|
178
|
-
const { stdout } = await
|
|
275
|
+
const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 30_000, windowsHide: true });
|
|
179
276
|
return JSON.parse(stdout.trim());
|
|
180
277
|
}
|
|
181
278
|
async function terminateOwnedProcess(child, platform = process.platform, run = async (file, args) => execFileAsync(file, args, { timeout: 10_000 })) {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.readinessDefinition = void 0;
|
|
4
|
+
exports.createReadinessAbility = createReadinessAbility;
|
|
5
|
+
const definition = { path: "agent/status/readiness", name: "Agent 就绪状态", summary: "读取 Agent 当前是否就绪。", contract_revision: "1", params_schema: { type: "object", properties: {}, additionalProperties: false }, result_schema: { type: "object", required: ["status"], properties: { status: { type: "string", enum: ["ready", "degraded", "failed"] } }, additionalProperties: false }, effects: ["state.read"], auth_required: true, require_confirm: true, idempotency: "keyed", allowed_modes: ["explicit"], aggregation: "none", dedupe_retention_seconds: 3600 };
|
|
6
|
+
exports.readinessDefinition = definition;
|
|
7
|
+
function createReadinessAbility(health) { return { definition, handler: async (params) => { if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).length)
|
|
8
|
+
throw new Error("readiness 参数必须为空对象"); const status = (await health()).status; return { status: status === "ready" || status === "failed" ? status : "degraded" }; } }; }
|
|
@@ -113,6 +113,7 @@ class QwenCdpClient {
|
|
|
113
113
|
dataDir: options.dataDir,
|
|
114
114
|
};
|
|
115
115
|
}
|
|
116
|
+
setPort(port) { this.options.port = port; }
|
|
116
117
|
connected() { return this.socket?.readyState === WebSocket.OPEN; }
|
|
117
118
|
async healthCheck() {
|
|
118
119
|
if (!this.socket)
|
|
@@ -309,7 +310,7 @@ class QwenCdpClient {
|
|
|
309
310
|
let seenGenerating = false;
|
|
310
311
|
let stoppedPolls = 0;
|
|
311
312
|
const forwarded = new Set();
|
|
312
|
-
|
|
313
|
+
let deadline = Date.now() + timeoutMs;
|
|
313
314
|
while (Date.now() < deadline || signal?.aborted) {
|
|
314
315
|
// 上游取消不停止桌面生成;确认结束前保留插件队列。
|
|
315
316
|
await wait(2_000);
|
|
@@ -318,6 +319,8 @@ class QwenCdpClient {
|
|
|
318
319
|
const messages = JSON.parse(messagesJson || "[]");
|
|
319
320
|
const fresh = freshAssistantMessages(beforeIds, messages);
|
|
320
321
|
const reply = fresh.at(-1)?.text.trim() ?? "";
|
|
322
|
+
if (reply && reply !== previousReply)
|
|
323
|
+
deadline = Date.now() + timeoutMs;
|
|
321
324
|
stablePolls = reply && reply === previousReply ? stablePolls + 1 : 0;
|
|
322
325
|
previousReply = reply;
|
|
323
326
|
if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
|
|
@@ -10,9 +10,10 @@ const cdp_client_1 = require("./cdp-client");
|
|
|
10
10
|
const plugin_1 = require("../../plugin");
|
|
11
11
|
const desktop_launch_1 = require("../desktop-launch");
|
|
12
12
|
const session_history_1 = require("./session-history");
|
|
13
|
+
const ability_1 = require("./ability");
|
|
13
14
|
exports.qwenworkManifest = {
|
|
14
15
|
id: "qwenwork",
|
|
15
|
-
version: "1.0.
|
|
16
|
+
version: "1.0.30",
|
|
16
17
|
displayName: "千问办公",
|
|
17
18
|
entry: "dist/index.js",
|
|
18
19
|
apiVersion: "1",
|
|
@@ -30,6 +31,7 @@ function validModelSessionId(value) {
|
|
|
30
31
|
/** 千问插件由后台守护,所有通道共用请求队列和恢复流程。 */
|
|
31
32
|
class QwenworkPlugin {
|
|
32
33
|
manifest = exports.qwenworkManifest;
|
|
34
|
+
abilities = [(0, ability_1.createReadinessAbility)(() => this.health())];
|
|
33
35
|
get modelProvider() {
|
|
34
36
|
if (this.relayTarget || !this.client?.complete || !this.client.createSession || !this.client.activateSession)
|
|
35
37
|
return undefined;
|
|
@@ -125,17 +127,19 @@ class QwenworkPlugin {
|
|
|
125
127
|
workspace: typeof config.workspace === "string" ? config.workspace : undefined,
|
|
126
128
|
});
|
|
127
129
|
this.client = client;
|
|
130
|
+
let executable;
|
|
128
131
|
try {
|
|
129
132
|
await client.connect();
|
|
130
133
|
}
|
|
131
134
|
catch (first) {
|
|
132
135
|
if (config.autoStart === false || this.injectedClient || process.platform !== "win32")
|
|
133
136
|
throw first;
|
|
134
|
-
|
|
137
|
+
executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
|
|
135
138
|
if (!executable)
|
|
136
139
|
throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
|
|
137
140
|
context.logger?.info(`正在启动千问办公,等待 CDP ${this.activeCdpPort}`, { executablePath: executable });
|
|
138
|
-
await
|
|
141
|
+
this.activeCdpPort = await (0, desktop_launch_1.prepareDesktopPort)(executable, this.activeCdpPort);
|
|
142
|
+
client.setPort?.(this.activeCdpPort);
|
|
139
143
|
try {
|
|
140
144
|
await (0, desktop_launch_1.launchAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], () => client.connect(), typeof config.startupTimeoutMs === "number" ? config.startupTimeoutMs : 30_000);
|
|
141
145
|
}
|
|
@@ -143,6 +147,11 @@ class QwenworkPlugin {
|
|
|
143
147
|
throw new Error(`已启动千问办公,但 CDP ${this.activeCdpPort} 未就绪:${error instanceof Error ? error.message : String(error)}`);
|
|
144
148
|
}
|
|
145
149
|
}
|
|
150
|
+
if (config.autoStart !== false && !this.injectedClient && process.platform === "win32") {
|
|
151
|
+
executable ??= await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
|
|
152
|
+
if (executable)
|
|
153
|
+
await (0, desktop_launch_1.terminateWindowsDesktop)(executable, this.activeCdpPort);
|
|
154
|
+
}
|
|
146
155
|
}
|
|
147
156
|
this.adapter = new openai_adapter_1.OpenAIAdapter((prompt, signal, _context, onMessage) => this.enqueueTask(() => this.complete(prompt, asNumber(config.timeoutMs, 240_000), signal, onMessage)), {
|
|
148
157
|
onLog: (message) => context.logger?.info(message),
|
|
@@ -170,8 +179,8 @@ class QwenworkPlugin {
|
|
|
170
179
|
throw error;
|
|
171
180
|
}
|
|
172
181
|
}
|
|
173
|
-
async deactivate(reason) {
|
|
174
|
-
const reloadDesktop = reason === "reload" && Boolean(this.client) && !this.relayTarget;
|
|
182
|
+
async deactivate(reason, options) {
|
|
183
|
+
const reloadDesktop = !options?.preserveDesktop && reason === "reload" && Boolean(this.client) && !this.relayTarget;
|
|
175
184
|
await this.cleanup();
|
|
176
185
|
if (reloadDesktop) {
|
|
177
186
|
if (this.restartDesktopHook)
|
|
@@ -191,8 +200,6 @@ class QwenworkPlugin {
|
|
|
191
200
|
return { status: this.state, ...(this.message ? { message: this.message } : {}), details };
|
|
192
201
|
}
|
|
193
202
|
async handle(request) {
|
|
194
|
-
if (this.recovery)
|
|
195
|
-
await this.recovery;
|
|
196
203
|
if (this.state === "stopped" || (!this.relayTarget && !this.client))
|
|
197
204
|
throw new Error("qwenwork 插件未就绪");
|
|
198
205
|
return this.enqueueTask(() => this.completeRequest(request));
|
|
@@ -207,9 +214,8 @@ class QwenworkPlugin {
|
|
|
207
214
|
throw new Error("千问办公当前忙,无法创建新会话");
|
|
208
215
|
if (!this.client?.createSession)
|
|
209
216
|
throw new Error("千问办公当前传输不支持新建会话");
|
|
210
|
-
if (!this.client.connected())
|
|
211
|
-
throw new Error("千问办公 CDP 未连接");
|
|
212
217
|
return this.enqueueTask(async () => {
|
|
218
|
+
await this.ensureConnected();
|
|
213
219
|
await this.client.createSession(request.name);
|
|
214
220
|
return { text: "千问办公已创建新会话", sessionId };
|
|
215
221
|
});
|
|
@@ -222,8 +228,7 @@ class QwenworkPlugin {
|
|
|
222
228
|
if (!this.client)
|
|
223
229
|
throw new Error("qwenwork 插件未就绪");
|
|
224
230
|
try {
|
|
225
|
-
|
|
226
|
-
throw new Error("千问 CDP 已断开,等待空闲后自动恢复");
|
|
231
|
+
await this.ensureConnected(signal);
|
|
227
232
|
const reply = this.client.complete ? (await this.client.complete(prompt, timeoutMs, signal, undefined, undefined, onMessage)).text : await this.client.direct(prompt, timeoutMs, signal);
|
|
228
233
|
if ((0, cdp_client_1.isQwenApiUnavailableReply)(reply))
|
|
229
234
|
throw new agent_1.AgentOperationError("QWEN_REMOTE_ERROR", "等待千问办公回复", new Error("千问生成接口不可用;桌面未提供具体服务端错误码,CDP 仍连接,未重启或重新提交任务"));
|
|
@@ -233,7 +238,7 @@ class QwenworkPlugin {
|
|
|
233
238
|
return reply;
|
|
234
239
|
}
|
|
235
240
|
catch (error) {
|
|
236
|
-
if (!signal?.aborted) {
|
|
241
|
+
if (!this.stopped && !signal?.aborted) {
|
|
237
242
|
this.message = error instanceof Error ? error.message : String(error);
|
|
238
243
|
this.failures = this.client.connected() ? 0 : 2;
|
|
239
244
|
this.state = "degraded";
|
|
@@ -248,8 +253,10 @@ class QwenworkPlugin {
|
|
|
248
253
|
if (!this.client)
|
|
249
254
|
throw new Error("qwenwork 插件未就绪");
|
|
250
255
|
try {
|
|
251
|
-
if (!this.client.connected())
|
|
252
|
-
throw new Error("千问 CDP
|
|
256
|
+
if (modelRequest && !this.client.connected())
|
|
257
|
+
throw new Error("千问 CDP 已断开,模型请求不会启动或重启桌面");
|
|
258
|
+
if (!modelRequest)
|
|
259
|
+
await this.ensureConnected(request.signal);
|
|
253
260
|
if (request.attachments?.length && (!this.client.attachmentInput || !this.client.complete))
|
|
254
261
|
throw new Error("千问当前客户端不支持附件输入");
|
|
255
262
|
const timeoutMs = request.timeoutMs ?? asNumber(this.context?.config.timeoutMs, 240_000);
|
|
@@ -264,7 +271,7 @@ class QwenworkPlugin {
|
|
|
264
271
|
return response;
|
|
265
272
|
}
|
|
266
273
|
catch (error) {
|
|
267
|
-
if (!request.signal?.aborted && !modelRequest) {
|
|
274
|
+
if (!this.stopped && !request.signal?.aborted && !modelRequest) {
|
|
268
275
|
this.message = error instanceof Error ? error.message : String(error);
|
|
269
276
|
this.failures = this.client.connected() ? 0 : 2;
|
|
270
277
|
this.state = "degraded";
|
|
@@ -383,9 +390,26 @@ class QwenworkPlugin {
|
|
|
383
390
|
});
|
|
384
391
|
}
|
|
385
392
|
async recover() {
|
|
393
|
+
if (this.stopped || this.busy)
|
|
394
|
+
return;
|
|
395
|
+
try {
|
|
396
|
+
await this.reconnect();
|
|
397
|
+
}
|
|
398
|
+
catch { /* 失败已记录,留待下次空闲检查。 */ }
|
|
399
|
+
}
|
|
400
|
+
async ensureConnected(signal) {
|
|
401
|
+
signal?.throwIfAborted();
|
|
402
|
+
if (this.stopped || !this.client)
|
|
403
|
+
throw new Error("qwenwork 插件未就绪");
|
|
404
|
+
await this.reconnect();
|
|
405
|
+
signal?.throwIfAborted();
|
|
406
|
+
if (this.stopped)
|
|
407
|
+
throw new Error("qwenwork 插件未就绪");
|
|
408
|
+
}
|
|
409
|
+
async reconnect() {
|
|
386
410
|
if (this.recovery)
|
|
387
411
|
return this.recovery;
|
|
388
|
-
if (this.stopped
|
|
412
|
+
if (this.stopped)
|
|
389
413
|
return;
|
|
390
414
|
const client = this.client;
|
|
391
415
|
if (!client || client.connected())
|
|
@@ -406,11 +430,12 @@ class QwenworkPlugin {
|
|
|
406
430
|
this.restarts += 1;
|
|
407
431
|
this.context?.logger?.info("千问 CDP 自动重连成功", { restarts: this.restarts });
|
|
408
432
|
})().catch((error) => {
|
|
409
|
-
if (this.stopped)
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
433
|
+
if (!this.stopped) {
|
|
434
|
+
this.state = "failed";
|
|
435
|
+
this.message = error instanceof Error ? error.message : String(error);
|
|
436
|
+
this.context?.logger?.error(`千问 CDP 重连失败,桌面未重启,下次空闲检查重试:${this.message}`);
|
|
437
|
+
}
|
|
438
|
+
throw error;
|
|
414
439
|
}).finally(() => { this.recovery = undefined; });
|
|
415
440
|
return this.recovery;
|
|
416
441
|
}
|
package/package.json
CHANGED