agent-bridge-qwenwork 1.0.30 → 1.0.35

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.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.desktopLaunchEnvironment = desktopLaunchEnvironment;
4
4
  exports.findWindowsExecutable = findWindowsExecutable;
5
+ exports.isWindowsExecutableRunning = isWindowsExecutableRunning;
5
6
  exports.findExecutableInTree = findExecutableInTree;
6
7
  exports.findChromeExecutable = findChromeExecutable;
7
8
  exports.launchAndWait = launchAndWait;
@@ -63,9 +64,6 @@ async function findWindowsExecutable(fileName, configured, run = execFileAsync)
63
64
  let root = (0, node_path_1.dirname)(configuredPath);
64
65
  while (/^(?:app|launcher|doubao_update)$/i.test((0, node_path_1.basename)(root)) || versionDirectory.test((0, node_path_1.basename)(root)))
65
66
  root = (0, node_path_1.dirname)(root);
66
- const updated = (0, node_path_1.join)(root, "Doubao_update", fileName);
67
- if ((0, node_fs_1.existsSync)(updated))
68
- return updated;
69
67
  const latest = await findExecutableInTree(root, fileName, /^/, 3);
70
68
  if (latest)
71
69
  return latest;
@@ -102,6 +100,17 @@ async function findWindowsExecutable(fileName, configured, run = execFileAsync)
102
100
  }
103
101
  return undefined;
104
102
  }
103
+ async function isWindowsExecutableRunning(executable, platform = process.platform, run = execFileAsync) {
104
+ if (platform !== "win32")
105
+ return false;
106
+ const target = (0, node_path_1.resolve)(executable).replace(/'/g, "''");
107
+ const script = `$ErrorActionPreference='Stop';$target='${target}';$running=Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -ieq $target } | Select-Object -First 1;if($running){'true'}else{'false'}`;
108
+ const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 10_000, windowsHide: true });
109
+ const result = stdout.trim().toLowerCase();
110
+ if (result !== "true" && result !== "false")
111
+ throw new Error("无法确认桌面进程状态,已跳过自动启动");
112
+ return result === "true";
113
+ }
105
114
  async function findRegisteredWindowsExecutable(fileName, run) {
106
115
  const target = fileName.replace(/'/g, "''");
107
116
  const script = `$ErrorActionPreference='SilentlyContinue';[Console]::OutputEncoding=[Text.Encoding]::UTF8;$target='${target}'
@@ -141,11 +150,11 @@ function findChromeExecutable() {
141
150
  async function search(directory, fileName, pattern, depth, insideProduct) {
142
151
  try {
143
152
  const entries = await (0, promises_1.readdir)(directory, { withFileTypes: true });
144
- // 豆包上层文件是启动器,优先查找新版目录或 app 中的实际程序。
153
+ // 豆包更新临时目录可能尚未安装完整,优先使用版本目录或 app 中的客户端。
145
154
  if (insideProduct && depth > 0 && fileName.toLowerCase() === "doubao.exe") {
146
155
  const versions = entries.filter(entry => entry.isDirectory() && (versionDirectory.test(entry.name) || /^(?:app|doubao_update)$/i.test(entry.name)));
147
156
  versions.sort((left, right) => {
148
- const rank = (name) => /^doubao_update$/i.test(name) ? 2 : /^app$/i.test(name) ? 0 : 1;
157
+ const rank = (name) => /^doubao_update$/i.test(name) ? 0 : /^app$/i.test(name) ? 1 : 2;
149
158
  return rank(right.name) - rank(left.name) || right.name.replace(/^\D+/, "").localeCompare(left.name.replace(/^\D+/, ""), "en", { numeric: true });
150
159
  });
151
160
  for (const entry of versions) {
@@ -226,7 +235,7 @@ async function prepareDesktopPort(executable, preferred, platform = process.plat
226
235
  await terminate(executable);
227
236
  return selectDesktopPort(preferred);
228
237
  }
229
- /** 只清理同一用户、同一安装路径且带 CDP 启动参数的桌面进程。 */
238
+ /** 清理同一用户、同一安装路径的桌面进程;千问还需接管无参数的单实例主进程。 */
230
239
  async function terminateWindowsDesktop(executable, keepPort, platform = process.platform, run = execFileAsync) {
231
240
  if (platform !== "win32")
232
241
  return [];
@@ -239,13 +248,16 @@ $ProgressPreference = 'SilentlyContinue'
239
248
  $target = '${(0, node_path_1.resolve)(executable).replace(/'/g, "''")}'
240
249
  $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
241
250
  $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 })
251
+ $isQwen = [IO.Path]::GetFileName($target) -ieq 'QwenWorkCN.exe'
252
+ $processes = @($all | Where-Object { $_.ExecutablePath -ieq $target -and (($isQwen -and $_.CommandLine -notmatch '(?i)--type=|browser-extension-relay-worker') -or (-not $isQwen -and $_.CommandLine -match '(?i)(?:^|[\\s"])--remote-debugging-(?:port|address)(?:=|\\s|")')) } | Where-Object { (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid })
243
253
  $ids = @($processes.ProcessId)
244
254
  $roots = @($processes | Where-Object { $ids -notcontains $_.ParentProcessId })
245
255
  ${keepPort === undefined ? "" : `
246
256
  # 保留有效 CDP 所属进程树,只结束同安装路径的其它重复实例。
247
- $owners = @(Get-NetTCPConnection -State Listen -LocalPort ${keepPort} | Select-Object -ExpandProperty OwningProcess -Unique)
248
- if ($owners.Count -ne 1) { throw '无法确认有效 CDP 端口的唯一进程,未清理桌面实例' }
257
+ try { $owners = @(Get-NetTCPConnection -State Listen -LocalPort ${keepPort} | Select-Object -ExpandProperty OwningProcess -Unique) }
258
+ catch { Write-Output '[]'; return }
259
+ # 端口查询可能被系统网络组件隐藏,不能因此中断有效连接或猜测要结束的进程。
260
+ if ($owners.Count -ne 1 -or $owners[0] -eq 0) { Write-Output '[]'; return }
249
261
  $byId = @{}; foreach ($item in $all) { $byId[[int]$item.ProcessId] = $item }
250
262
  $current = $byId[[int]$owners[0]]
251
263
  $keepRoot = $null
@@ -257,7 +269,7 @@ while ($current -and -not $visited.ContainsKey([int]$current.ProcessId)) {
257
269
  if ($parent -and $parent.CreationDate -gt $current.CreationDate) { break }
258
270
  $current = $parent
259
271
  }
260
- if (-not $keepRoot) { throw '无法保留有效 CDP 对应的同用户桌面进程树,未清理桌面实例' }
272
+ if (-not $keepRoot) { Write-Output '[]'; return }
261
273
  $roots = @($roots | Where-Object { $_.ProcessId -ne $keepRoot.ProcessId })
262
274
  `}
263
275
  $terminated = @()
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createGeneratedAbilities = createGeneratedAbilities;
4
+ const generated = [];
5
+ function createGeneratedAbilities() {
6
+ return generated.filter(item => item.enabled).map(item => item.ability);
7
+ }
@@ -2,7 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.readinessDefinition = void 0;
4
4
  exports.createReadinessAbility = createReadinessAbility;
5
+ exports.createQwenworkAbilities = createQwenworkAbilities;
6
+ const generated_1 = require("./generated");
5
7
  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
8
  exports.readinessDefinition = definition;
7
9
  function createReadinessAbility(health) { return { definition, handler: async (params) => { if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).length)
8
10
  throw new Error("readiness 参数必须为空对象"); const status = (await health()).status; return { status: status === "ready" || status === "failed" ? status : "degraded" }; } }; }
11
+ function createQwenworkAbilities(health) {
12
+ return [createReadinessAbility(health), ...(0, generated_1.createGeneratedAbilities)()];
13
+ }
@@ -141,7 +141,8 @@ class QwenCdpClient {
141
141
  const clicked = await this.evaluate(`(() => { if (document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText.trim() || document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问当前有未发送内容或正在生成回复,不能新建会话'); const button = document.querySelector('button[aria-label="新任务"]'); if (!button || button.disabled || button.getAttribute('aria-disabled') === 'true') return false; button.click(); return true; })()`);
142
142
  if (clicked !== true)
143
143
  throw new Error("千问新任务入口未找到或不可用");
144
- await this.waitFor(`(() => { const state = ${snapshot}; return state.input !== null && state.input.trim() === '' && state.messages === 0 && state.url !== ${JSON.stringify(before.url)}; })()`, "千问新会话状态校验失败");
144
+ // 千问通过内部状态切换新任务页,URL 不一定变化。
145
+ await this.waitFor(`(() => { const state = ${snapshot}; return state.input !== null && state.input.trim() === '' && state.messages === 0 && state.blank; })()`, "千问新会话状态校验失败");
145
146
  return this.currentSessionId();
146
147
  }
147
148
  async currentSessionId() {
@@ -13,7 +13,7 @@ const session_history_1 = require("./session-history");
13
13
  const ability_1 = require("./ability");
14
14
  exports.qwenworkManifest = {
15
15
  id: "qwenwork",
16
- version: "1.0.30",
16
+ version: "1.0.35",
17
17
  displayName: "千问办公",
18
18
  entry: "dist/index.js",
19
19
  apiVersion: "1",
@@ -31,7 +31,7 @@ function validModelSessionId(value) {
31
31
  /** 千问插件由后台守护,所有通道共用请求队列和恢复流程。 */
32
32
  class QwenworkPlugin {
33
33
  manifest = exports.qwenworkManifest;
34
- abilities = [(0, ability_1.createReadinessAbility)(() => this.health())];
34
+ abilities = (0, ability_1.createQwenworkAbilities)(() => this.health());
35
35
  get modelProvider() {
36
36
  if (this.relayTarget || !this.client?.complete || !this.client.createSession || !this.client.activateSession)
37
37
  return undefined;
@@ -108,6 +108,7 @@ class QwenworkPlugin {
108
108
  this.relayTarget = relayTarget === "dsh" ? relayTarget : undefined;
109
109
  this.callPlugin = context.callPlugin;
110
110
  this.pluginStatus = context.pluginStatus;
111
+ let startupError = "";
111
112
  this.activeCdpPort = (0, plugin_1.resolveRuntimePort)(config, context.runtime, "qwenwork", "QWEN_CDP_PORT", this.configuredCdpPort ?? exports.qwenworkManifest.defaults.cdpPort);
112
113
  this.sessionHistory = new session_history_1.QwenworkSessionHistoryProvider({
113
114
  scope: `qwenwork:cdp:${this.activeCdpPort}`,
@@ -127,28 +128,26 @@ class QwenworkPlugin {
127
128
  workspace: typeof config.workspace === "string" ? config.workspace : undefined,
128
129
  });
129
130
  this.client = client;
130
- let executable;
131
131
  try {
132
132
  await client.connect();
133
133
  }
134
134
  catch (first) {
135
- if (config.autoStart === false || this.injectedClient || process.platform !== "win32")
135
+ if (!this.canStartDesktop())
136
136
  throw first;
137
- executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
138
- if (!executable)
139
- throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
140
- context.logger?.info(`正在启动千问办公,等待 CDP ${this.activeCdpPort}`, { executablePath: executable });
141
- this.activeCdpPort = await (0, desktop_launch_1.prepareDesktopPort)(executable, this.activeCdpPort);
142
- client.setPort?.(this.activeCdpPort);
143
137
  try {
144
- await (0, desktop_launch_1.launchAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], () => client.connect(), typeof config.startupTimeoutMs === "number" ? config.startupTimeoutMs : 30_000);
138
+ await this.startDesktop(client);
145
139
  }
146
140
  catch (error) {
147
- throw new Error(`已启动千问办公,但 CDP ${this.activeCdpPort} 未就绪:${error instanceof Error ? error.message : String(error)}`);
141
+ if (!(error instanceof agent_1.AgentOperationError) || error.code !== "QWEN_CDP_START_FAILED")
142
+ throw error;
143
+ // 保留插件实例和定时器,避免一次启动超时后永远失去自动恢复。
144
+ startupError = `千问办公启动未就绪,等待空闲后自动恢复:${error.message}`;
145
+ client.close();
146
+ context.logger?.error(startupError);
148
147
  }
149
148
  }
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);
149
+ if (!startupError && config.autoStart !== false && !this.injectedClient && process.platform === "win32") {
150
+ const executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
152
151
  if (executable)
153
152
  await (0, desktop_launch_1.terminateWindowsDesktop)(executable, this.activeCdpPort);
154
153
  }
@@ -166,8 +165,8 @@ class QwenworkPlugin {
166
165
  if (this.configuredHttpPort > 0)
167
166
  await this.adapter.listen(this.configuredHttpPort);
168
167
  }
169
- this.state = "ready";
170
- this.message = "";
168
+ this.state = startupError ? "degraded" : "ready";
169
+ this.message = startupError;
171
170
  this.startHealthWatch();
172
171
  void this.checkHealth();
173
172
  }
@@ -364,7 +363,7 @@ class QwenworkPlugin {
364
363
  const config = this.context?.config;
365
364
  const executable = configuredExecutable ?? await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config?.executablePath === "string" ? config.executablePath : undefined);
366
365
  if (!executable)
367
- throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
366
+ throw new agent_1.AgentOperationError("DESKTOP_EXECUTABLE_NOT_FOUND", "启动桌面程序", new Error("未找到 QwenWorkCN.exe,请配置 executablePath"));
368
367
  const processIds = await (0, desktop_launch_1.terminateWindowsDesktop)(executable);
369
368
  this.context?.logger?.info("千问办公重载前已清理旧进程,将以 CDP 模式启动", { processIds, executable });
370
369
  }
@@ -418,7 +417,24 @@ class QwenworkPlugin {
418
417
  this.state = "starting";
419
418
  this.context?.logger?.info("千问 CDP 自动重连开始", { reason: this.message });
420
419
  client.close();
421
- await client.connect();
420
+ try {
421
+ await client.connect();
422
+ }
423
+ catch (first) {
424
+ if (this.stopped) {
425
+ client.close();
426
+ return;
427
+ }
428
+ if (!this.canStartDesktop())
429
+ throw first;
430
+ this.context?.logger?.info("千问 CDP 重连失败,准备重启桌面", { error: first instanceof Error ? first.message : String(first) });
431
+ try {
432
+ await this.startDesktop(client);
433
+ }
434
+ catch (restartError) {
435
+ throw new Error(`${first instanceof Error ? first.message : String(first)};千问桌面重启失败:${restartError instanceof Error ? restartError.message : String(restartError)}`);
436
+ }
437
+ }
422
438
  await this.verifyConnection(client);
423
439
  if (this.stopped) {
424
440
  client.close();
@@ -433,12 +449,44 @@ class QwenworkPlugin {
433
449
  if (!this.stopped) {
434
450
  this.state = "failed";
435
451
  this.message = error instanceof Error ? error.message : String(error);
436
- this.context?.logger?.error(`千问 CDP 重连失败,桌面未重启,下次空闲检查重试:${this.message}`);
452
+ this.context?.logger?.error(`千问 CDP 重连失败,下次空闲检查重试:${this.message}`);
437
453
  }
438
454
  throw error;
439
455
  }).finally(() => { this.recovery = undefined; });
440
456
  return this.recovery;
441
457
  }
458
+ canStartDesktop() {
459
+ return this.context?.config.autoStart !== false && Boolean(this.restartDesktopHook || (!this.injectedClient && process.platform === "win32"));
460
+ }
461
+ async startDesktop(client) {
462
+ if (this.restartDesktopHook) {
463
+ try {
464
+ await this.restartDesktopHook();
465
+ await client.connect();
466
+ }
467
+ catch (error) {
468
+ throw new agent_1.AgentOperationError("QWEN_CDP_START_FAILED", "启动千问办公 CDP", error);
469
+ }
470
+ return;
471
+ }
472
+ const config = this.context?.config;
473
+ const executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config?.executablePath === "string" ? config.executablePath : undefined);
474
+ if (!executable)
475
+ throw new agent_1.AgentOperationError("DESKTOP_EXECUTABLE_NOT_FOUND", "启动桌面程序", new Error("未找到 QwenWorkCN.exe,请配置 executablePath"));
476
+ if (this.stopped)
477
+ return;
478
+ this.activeCdpPort = await (0, desktop_launch_1.prepareDesktopPort)(executable, this.activeCdpPort ?? exports.qwenworkManifest.defaults.cdpPort);
479
+ if (this.stopped)
480
+ return;
481
+ client.setPort?.(this.activeCdpPort);
482
+ this.context?.logger?.info(`正在启动千问办公,等待 CDP ${this.activeCdpPort}`, { executablePath: executable });
483
+ try {
484
+ await (0, desktop_launch_1.launchManagedAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], undefined, () => client.connect(), typeof config?.startupTimeoutMs === "number" ? config.startupTimeoutMs : 30_000, () => { });
485
+ }
486
+ catch (error) {
487
+ throw new agent_1.AgentOperationError("QWEN_CDP_START_FAILED", "启动千问办公 CDP", error);
488
+ }
489
+ }
442
490
  async verifyConnection(client) {
443
491
  if (!client.connected())
444
492
  throw new Error("千问 CDP 连接恢复失败");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-bridge-qwenwork",
3
- "version": "1.0.30",
3
+ "version": "1.0.35",
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.30",
3
+ "version": "1.0.35",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",