agent-bridge-qwenwork 1.0.28 → 1.0.31

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()) {
@@ -24,9 +63,6 @@ async function findWindowsExecutable(fileName, configured, run = execFileAsync)
24
63
  let root = (0, node_path_1.dirname)(configuredPath);
25
64
  while (/^(?:app|launcher|doubao_update)$/i.test((0, node_path_1.basename)(root)) || versionDirectory.test((0, node_path_1.basename)(root)))
26
65
  root = (0, node_path_1.dirname)(root);
27
- const updated = (0, node_path_1.join)(root, "Doubao_update", fileName);
28
- if ((0, node_fs_1.existsSync)(updated))
29
- return updated;
30
66
  const latest = await findExecutableInTree(root, fileName, /^/, 3);
31
67
  if (latest)
32
68
  return latest;
@@ -96,14 +132,17 @@ async function resolveRegisteredCandidate(fileName, candidate) {
96
132
  async function findExecutableInTree(directory, fileName, pattern, depth) {
97
133
  return search(directory, fileName, pattern, depth, pattern.test(directory));
98
134
  }
135
+ function findChromeExecutable() {
136
+ return ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/opt/google/chrome/chrome"].find(node_fs_1.existsSync);
137
+ }
99
138
  async function search(directory, fileName, pattern, depth, insideProduct) {
100
139
  try {
101
140
  const entries = await (0, promises_1.readdir)(directory, { withFileTypes: true });
102
- // 豆包上层文件是启动器,优先查找新版目录或 app 中的实际程序。
141
+ // 豆包更新临时目录可能尚未安装完整,优先使用版本目录或 app 中的客户端。
103
142
  if (insideProduct && depth > 0 && fileName.toLowerCase() === "doubao.exe") {
104
143
  const versions = entries.filter(entry => entry.isDirectory() && (versionDirectory.test(entry.name) || /^(?:app|doubao_update)$/i.test(entry.name)));
105
144
  versions.sort((left, right) => {
106
- const rank = (name) => /^doubao_update$/i.test(name) ? 2 : /^app$/i.test(name) ? 0 : 1;
145
+ const rank = (name) => /^doubao_update$/i.test(name) ? 0 : /^app$/i.test(name) ? 1 : 2;
107
146
  return rank(right.name) - rank(left.name) || right.name.replace(/^\D+/, "").localeCompare(left.name.replace(/^\D+/, ""), "en", { numeric: true });
108
147
  });
109
148
  for (const entry of versions) {
@@ -129,12 +168,12 @@ async function search(directory, fileName, pattern, depth, insideProduct) {
129
168
  catch { /* 无权限或目录在扫描期间消失时继续查找 */ }
130
169
  return undefined;
131
170
  }
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 })) {
171
+ 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
172
  const child = launch(executable, args);
134
173
  child.unref();
135
174
  return waitFor(connect, timeoutMs, 250);
136
175
  }
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 })) {
176
+ 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
177
  if (profileDirectory)
139
178
  await (0, promises_1.mkdir)(profileDirectory, { recursive: true });
140
179
  const child = launch(executable, profileDirectory ? [...args, `--user-data-dir=${profileDirectory}`] : args);
@@ -161,17 +200,66 @@ async function restartOwnedAndWait(child, executable, args, profileDirectory, co
161
200
  onProcess(undefined);
162
201
  return launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess);
163
202
  }
164
- /** 仅在用户确认重启后清理同一用户、同一安装路径的桌面进程。 */
165
- async function terminateWindowsDesktop(executable) {
166
- if (process.platform !== "win32")
203
+ async function selectDesktopPort(preferred) {
204
+ const available = (port) => new Promise(resolve => {
205
+ const server = (0, node_net_1.createServer)();
206
+ server.once("error", () => resolve(false));
207
+ server.listen(port, "127.0.0.1", () => server.close(error => resolve(!error)));
208
+ });
209
+ if (await available(preferred))
210
+ return preferred;
211
+ return new Promise((resolve, reject) => {
212
+ const server = (0, node_net_1.createServer)();
213
+ server.once("error", reject);
214
+ server.listen(0, "127.0.0.1", () => {
215
+ const address = server.address();
216
+ server.close(error => error ? reject(error) : address && typeof address !== "string" ? resolve(address.port) : reject(new Error("无法分配桌面 CDP 端口")));
217
+ });
218
+ });
219
+ }
220
+ /** 启动桥接桌面前清理同一安装路径的旧实例,再选择可用 CDP 端口。 */
221
+ async function prepareDesktopPort(executable, preferred, platform = process.platform, terminate = terminateWindowsDesktop) {
222
+ if (platform === "win32")
223
+ await terminate(executable);
224
+ return selectDesktopPort(preferred);
225
+ }
226
+ /** 只清理同一用户、同一安装路径且带 CDP 启动参数的桌面进程。 */
227
+ async function terminateWindowsDesktop(executable, keepPort, platform = process.platform, run = execFileAsync) {
228
+ if (platform !== "win32")
167
229
  return [];
230
+ if (keepPort !== undefined && (!Number.isInteger(keepPort) || keepPort < 1 || keepPort > 65535))
231
+ throw new Error("要保留的桌面 CDP 端口无效");
168
232
  const script = `
169
233
  $ErrorActionPreference = 'Stop'
234
+ $ProgressPreference = 'SilentlyContinue'
235
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
170
236
  $target = '${(0, node_path_1.resolve)(executable).replace(/'/g, "''")}'
171
237
  $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
172
- $processes = @(Get-CimInstance Win32_Process | Where-Object { $_.ExecutablePath -ieq $target } | Where-Object { (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid })
238
+ $all = @(Get-CimInstance Win32_Process)
239
+ $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 })
173
240
  $ids = @($processes.ProcessId)
174
241
  $roots = @($processes | Where-Object { $ids -notcontains $_.ParentProcessId })
242
+ ${keepPort === undefined ? "" : `
243
+ # 保留有效 CDP 所属进程树,只结束同安装路径的其它重复实例。
244
+ try { $owners = @(Get-NetTCPConnection -State Listen -LocalPort ${keepPort} | Select-Object -ExpandProperty OwningProcess -Unique) }
245
+ catch { Write-Output '[]'; return }
246
+ # 端口查询可能被系统网络组件隐藏,不能因此中断有效连接或猜测要结束的进程。
247
+ if ($owners.Count -ne 1 -or $owners[0] -eq 0) { Write-Output '[]'; return }
248
+ $byId = @{}; foreach ($item in $all) { $byId[[int]$item.ProcessId] = $item }
249
+ $current = $byId[[int]$owners[0]]
250
+ $keepRoot = $null
251
+ $visited = @{}
252
+ while ($current -and -not $visited.ContainsKey([int]$current.ProcessId)) {
253
+ $visited[[int]$current.ProcessId] = $true
254
+ if ($roots.ProcessId -contains $current.ProcessId) { $keepRoot = $current; break }
255
+ $parent = $byId[[int]$current.ParentProcessId]
256
+ if ($parent -and $parent.CreationDate -gt $current.CreationDate) { break }
257
+ $current = $parent
258
+ }
259
+ if (-not $keepRoot) { Write-Output '[]'; return }
260
+ $roots = @($roots | Where-Object { $_.ProcessId -ne $keepRoot.ProcessId })
261
+ `}
262
+ $terminated = @()
175
263
  foreach ($item in $roots) {
176
264
  $current = Get-CimInstance Win32_Process -Filter "ProcessId=$($item.ProcessId)"
177
265
  if (-not $current -or $current.CreationDate -ne $item.CreationDate) { continue }
@@ -179,10 +267,11 @@ foreach ($item in $roots) {
179
267
  if ($LASTEXITCODE -ne 0 -and (Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue)) { throw "无法结束桌面进程 $($item.ProcessId)" }
180
268
  $remaining = Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue
181
269
  if ($remaining -and -not $remaining.WaitForExit(10000)) { throw "等待桌面进程退出超时 $($item.ProcessId)" }
270
+ $terminated += [int]$item.ProcessId
182
271
  }
183
- ConvertTo-Json -Compress -InputObject @($roots | ForEach-Object { [int]$_.ProcessId })
272
+ ConvertTo-Json -Compress -InputObject @($terminated)
184
273
  `;
185
- const { stdout } = await execFileAsync("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 30_000, windowsHide: true });
274
+ const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 30_000, windowsHide: true });
186
275
  return JSON.parse(stdout.trim());
187
276
  }
188
277
  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
- const deadline = Date.now() + timeoutMs;
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.28",
16
+ version: "1.0.31",
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
- const executable = await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config.executablePath === "string" ? config.executablePath : undefined);
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 this.restartDesktopProcess(executable);
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),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-bridge-qwenwork",
3
- "version": "1.0.28",
3
+ "version": "1.0.31",
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.28",
3
+ "version": "1.0.31",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",