agent-bridge-qwenwork 1.0.20 → 1.0.22

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.
@@ -3,10 +3,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.findWindowsExecutable = findWindowsExecutable;
4
4
  exports.findExecutableInTree = findExecutableInTree;
5
5
  exports.launchAndWait = launchAndWait;
6
+ exports.launchManagedAndWait = launchManagedAndWait;
7
+ exports.restartOwnedAndWait = restartOwnedAndWait;
8
+ exports.terminateWindowsDesktop = terminateWindowsDesktop;
9
+ exports.terminateOwnedProcess = terminateOwnedProcess;
10
+ exports.findChatgptExecutable = findChatgptExecutable;
6
11
  exports.waitFor = waitFor;
12
+ const node_child_process_1 = require("node:child_process");
7
13
  const promises_1 = require("node:fs/promises");
8
14
  const node_fs_1 = require("node:fs");
9
15
  const node_path_1 = require("node:path");
16
+ const node_util_1 = require("node:util");
17
+ const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
10
18
  const versionDirectory = /^(?:app[-_ ]?)?v?\d+(?:[.-]\d+)+$/i;
11
19
  /** 在 Windows 常见安装目录中查找桌面程序,避免依赖单一盘符。 */
12
20
  async function findWindowsExecutable(fileName, configured) {
@@ -31,8 +39,11 @@ async function findWindowsExecutable(fileName, configured) {
31
39
  }
32
40
  if (process.platform !== "win32")
33
41
  return undefined;
34
- const pattern = /doubao|豆包|qwen|qwwork|千问/i;
42
+ const pattern = /doubao|豆包|qwen|qwwork|千问|deepseek|harness|dsh/i;
35
43
  const roots = [...new Set([
44
+ process.env.DSH_INSTALL_DIR,
45
+ "D:\\Programs\\DeepSeek Harness",
46
+ "D:\\DSH",
36
47
  process.env.LOCALAPPDATA && (0, node_path_1.join)(process.env.LOCALAPPDATA, "Programs"),
37
48
  process.env.ProgramFiles,
38
49
  process.env["ProgramFiles(x86)"],
@@ -83,6 +94,87 @@ async function launchAndWait(executable, args, connect, timeoutMs, launch = (fil
83
94
  child.unref();
84
95
  return waitFor(connect, timeoutMs, 250);
85
96
  }
97
+ 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 })) {
98
+ if (profileDirectory)
99
+ await (0, promises_1.mkdir)(profileDirectory, { recursive: true });
100
+ const child = launch(executable, profileDirectory ? [...args, `--user-data-dir=${profileDirectory}`] : args);
101
+ child.unref();
102
+ onProcess(child);
103
+ try {
104
+ return await waitFor(connect, timeoutMs, 250);
105
+ }
106
+ catch (error) {
107
+ await terminateOwnedProcess(child).catch(() => undefined);
108
+ onProcess(undefined);
109
+ throw error;
110
+ }
111
+ }
112
+ async function restartOwnedAndWait(child, executable, args, profileDirectory, connect, timeoutMs, onProcess) {
113
+ await terminateOwnedProcess(child);
114
+ onProcess(undefined);
115
+ return launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess);
116
+ }
117
+ /** 仅在用户确认重启后清理同一用户、同一安装路径的桌面进程。 */
118
+ async function terminateWindowsDesktop(executable) {
119
+ if (process.platform !== "win32")
120
+ return [];
121
+ const script = `
122
+ $ErrorActionPreference = 'Stop'
123
+ $target = '${(0, node_path_1.resolve)(executable).replace(/'/g, "''")}'
124
+ $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
125
+ $processes = @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -ieq $target } | Where-Object { (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid })
126
+ $ids = @($processes.ProcessId)
127
+ $roots = @($processes | Where-Object { $ids -notcontains $_.ParentProcessId })
128
+ foreach ($item in $roots) {
129
+ $current = Get-CimInstance Win32_Process -Filter "ProcessId=$($item.ProcessId)"
130
+ if (-not $current -or $current.CreationDate -ne $item.CreationDate) { continue }
131
+ & taskkill.exe /PID $item.ProcessId /T /F | Out-Null
132
+ if ($LASTEXITCODE -ne 0 -and (Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue)) { throw "无法结束桌面进程 $($item.ProcessId)" }
133
+ $remaining = Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue
134
+ if ($remaining -and -not $remaining.WaitForExit(10000)) { throw "等待桌面进程退出超时 $($item.ProcessId)" }
135
+ }
136
+ ConvertTo-Json -Compress -InputObject @($roots | ForEach-Object { [int]$_.ProcessId })
137
+ `;
138
+ const { stdout } = await execFileAsync("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 30_000, windowsHide: true });
139
+ return JSON.parse(stdout.trim());
140
+ }
141
+ async function terminateOwnedProcess(child, platform = process.platform, run = async (file, args) => execFileAsync(file, args, { timeout: 10_000 })) {
142
+ const pid = child?.pid;
143
+ if (!Number.isSafeInteger(pid) || !pid || child?.exitCode !== null && child?.exitCode !== undefined || child?.signalCode)
144
+ return;
145
+ if (platform === "win32") {
146
+ try {
147
+ await run("taskkill.exe", ["/PID", String(pid), "/T", "/F"]);
148
+ }
149
+ catch (error) {
150
+ if (!child.exitCode && !child.signalCode && error.code !== "ESRCH")
151
+ throw error;
152
+ }
153
+ }
154
+ else {
155
+ try {
156
+ process.kill(pid, "SIGTERM");
157
+ }
158
+ catch (error) {
159
+ if (error.code !== "ESRCH")
160
+ throw error;
161
+ }
162
+ }
163
+ }
164
+ async function findChatgptExecutable(configured) {
165
+ if (configured?.trim() && (0, node_fs_1.existsSync)((0, node_path_1.resolve)(configured)))
166
+ return (0, node_path_1.resolve)(configured);
167
+ if (process.platform !== "win32")
168
+ return undefined;
169
+ const script = "$candidates = foreach ($package in (Get-AppxPackage | Where-Object { $_.Name -like 'OpenAI.Codex*' })) { $appDir = Join-Path $package.InstallLocation 'app'; $path = Join-Path $appDir 'ChatGPT.exe'; if (-not (Test-Path -LiteralPath $path)) { $path = Get-ChildItem -LiteralPath $appDir -Filter 'ChatGPT*.exe' -File -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName }; if ($path) { [pscustomobject]@{ Version = [version]$package.Version; Executable = $path } } }; $candidate = $candidates | Sort-Object Version -Descending | Select-Object -First 1; if ($candidate) { $candidate.Executable }";
170
+ try {
171
+ const { stdout } = await execFileAsync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], { timeout: 10_000 });
172
+ return stdout.trim().split(/\r?\n/).at(-1)?.trim() || undefined;
173
+ }
174
+ catch {
175
+ return undefined;
176
+ }
177
+ }
86
178
  async function waitFor(action, timeoutMs, intervalMs = 500) {
87
179
  const deadline = Date.now() + timeoutMs;
88
180
  let last;
@@ -97,4 +189,3 @@ async function waitFor(action, timeoutMs, intervalMs = 500) {
97
189
  }
98
190
  throw last instanceof Error ? last : new Error("桌面程序启动超时");
99
191
  }
100
- const node_child_process_1 = require("node:child_process");
@@ -261,7 +261,34 @@ class QwenCdpClient {
261
261
  return { text: reply, ...(attachments.length ? { attachments } : {}) };
262
262
  }
263
263
  }
264
- throw new Error("千问办公 UI 超时未返回回复");
264
+ const permission = await this.permissionStatus(sessionUrl);
265
+ throw new Error(permission ?? `QWEN_REPLY_TIMEOUT:千问办公 UI 超时未返回回复(已等待 ${Math.round(timeoutMs / 1000)} 秒);桌面任务未被停止`);
266
+ }
267
+ async permissionStatus(sessionUrl) {
268
+ try {
269
+ if (await this.evaluate("typeof window !== 'undefined' && Boolean(window.electronTRPC)") !== true)
270
+ return;
271
+ const chatId = new URL(sessionUrl).searchParams.get("chat");
272
+ if (!chatId)
273
+ return;
274
+ const response = await this.trpc("agent.getAllStreamingStates", "query", {});
275
+ const states = response.result?.data?.json;
276
+ if (!Array.isArray(states))
277
+ return;
278
+ for (const state of states) {
279
+ if (typeof state?.chatId !== "string" || !chatId.endsWith(state.chatId) || !state.chatId || !Array.isArray(state.pendingInteractions))
280
+ continue;
281
+ for (const interaction of state.pendingInteractions) {
282
+ if (interaction?.kind !== "permission")
283
+ continue;
284
+ const input = interaction.toolInput;
285
+ const details = [interaction.toolName, input?.operation, input?.path].filter(value => typeof value === "string").join(" · ");
286
+ return `QWEN_PERMISSION_REQUIRED:千问办公正在等待权限确认(${details});请在千问桌面中确认或拒绝,当前任务未被停止`;
287
+ }
288
+ }
289
+ }
290
+ catch { /* 旧版客户端不支持该只读接口时,保留原始超时信息。 */ }
291
+ return;
265
292
  }
266
293
  async injectAttachments(items) {
267
294
  const files = items.map(item => {
@@ -458,11 +485,23 @@ class QwenCdpClient {
458
485
  pending.resolve(message);
459
486
  }
460
487
  async ensureVisible() {
461
- await this.evaluate(`(async () => {
488
+ try {
489
+ await this.evaluate(`(async () => {
462
490
  if (document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问桌面端正在生成回复');
463
491
  // 隐藏窗口会暂停消息渲染,使桌面端的提交前检查一直等不到确认。
464
492
  if (document.hidden && typeof window.desktopApi?.focusMainWindow === 'function') await window.desktopApi.focusMainWindow();
465
493
  })()`);
494
+ }
495
+ catch (error) {
496
+ let permission;
497
+ try {
498
+ permission = await this.permissionStatus(String(await this.evaluate("location.href")));
499
+ }
500
+ catch { /* 断线时保留原始错误。 */ }
501
+ if (permission)
502
+ throw new Error(permission);
503
+ throw error;
504
+ }
466
505
  }
467
506
  recoverDraft() {
468
507
  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);
@@ -9,10 +9,9 @@ const cdp_client_1 = require("./cdp-client");
9
9
  const plugin_1 = require("../../plugin");
10
10
  const desktop_launch_1 = require("../desktop-launch");
11
11
  const session_history_1 = require("./session-history");
12
- const CHAT_HEARTBEAT_INTERVAL_MS = 2 * 60 * 60_000;
13
12
  exports.qwenworkManifest = {
14
13
  id: "qwenwork",
15
- version: "1.0.20",
14
+ version: "1.0.22",
16
15
  displayName: "千问办公",
17
16
  entry: "dist/index.js",
18
17
  apiVersion: "1",
@@ -293,39 +292,13 @@ class QwenworkPlugin {
293
292
  this.healthTimer.unref();
294
293
  }
295
294
  async checkHealth() {
296
- if (this.checking || this.busy || this.recovery || this.state === "stopped" || (!this.client?.healthCheck && !this.client?.chatHeartbeat))
295
+ if (this.checking || this.busy || this.recovery || this.state === "stopped" || !this.client)
297
296
  return;
298
- const client = this.client;
299
297
  this.checking = true;
300
298
  await this.enqueue(async () => {
301
299
  try {
302
- if (this.stopped || this.busy)
303
- return;
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())
300
+ // 健康轮询只看连接状态,不发对话或 CDP 探测,避免打断桌面任务。
301
+ if (!this.stopped && !this.busy && !this.client?.connected())
329
302
  await this.recover();
330
303
  }
331
304
  finally {
@@ -350,8 +323,6 @@ class QwenworkPlugin {
350
323
  else if (this.restart)
351
324
  await this.restart();
352
325
  await client.connect();
353
- if (client.chatHeartbeat)
354
- this.lastHeartbeatAttempt = new Date().toISOString();
355
326
  await this.verifyConnection(client);
356
327
  if (this.stopped) {
357
328
  client.close();
@@ -360,8 +331,6 @@ class QwenworkPlugin {
360
331
  this.state = "ready";
361
332
  this.message = "";
362
333
  this.failures = 0;
363
- if (client.chatHeartbeat)
364
- this.lastHeartbeat = new Date().toISOString();
365
334
  this.restarts += 1;
366
335
  this.context?.logger?.info("千问自动恢复成功", { restarts: this.restarts });
367
336
  })().catch((error) => {
@@ -374,10 +343,8 @@ class QwenworkPlugin {
374
343
  return this.recovery;
375
344
  }
376
345
  async verifyConnection(client) {
377
- if (client.chatHeartbeat)
378
- await client.chatHeartbeat();
379
- else
380
- await client.healthCheck?.();
346
+ if (!client.connected())
347
+ throw new Error("千问 CDP 连接恢复失败");
381
348
  }
382
349
  enqueue(operation) {
383
350
  const run = this.requestQueue.then(operation, operation);
@@ -73,13 +73,11 @@ class OpenAIAdapter {
73
73
  return;
74
74
  }
75
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
- }
76
+ for (const name of ["x-evolcore-session-id", "x-aun-peer", "x-evolcore-agent-aid"]) {
77
+ const value = req.headers[name];
78
+ if (value !== undefined && (typeof value !== "string" || !value.trim() || value.length > 256 || /[\x00-\x1f\x7f-\x9f]/.test(value))) {
79
+ json(res, 400, { error: { message: `${name} 必须是 1 到 256 个字符且不含控制字符的字符串`, type: "invalid_request_error" } });
80
+ return;
83
81
  }
84
82
  }
85
83
  const abort = new AbortController();
@@ -100,7 +98,8 @@ class OpenAIAdapter {
100
98
  }
101
99
  this.onLog?.(`chat request model=${payload.model ?? this.model} stream=${Boolean(payload.stream)}`);
102
100
  this.onExchange?.("request", prompt, peerId, agentAid);
103
- const content = await this.complete(prompt, abort.signal, typeof session === "string" ? { sessionId: session, peerId, agentAid } : undefined);
101
+ 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);
104
103
  this.onExchange?.("reply", content, peerId, agentAid);
105
104
  if (abort.signal.aborted || res.destroyed)
106
105
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-bridge-qwenwork",
3
- "version": "1.0.20",
3
+ "version": "1.0.22",
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.20",
3
+ "version": "1.0.22",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",