agent-bridge-qwenwork 1.0.28 → 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()) {
@@ -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,12 +171,12 @@ 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);
@@ -161,17 +203,64 @@ async function restartOwnedAndWait(child, executable, args, profileDirectory, co
161
203
  onProcess(undefined);
162
204
  return launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess);
163
205
  }
164
- /** 仅在用户确认重启后清理同一用户、同一安装路径的桌面进程。 */
165
- async function terminateWindowsDesktop(executable) {
166
- if (process.platform !== "win32")
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")
167
232
  return [];
233
+ if (keepPort !== undefined && (!Number.isInteger(keepPort) || keepPort < 1 || keepPort > 65535))
234
+ throw new Error("要保留的桌面 CDP 端口无效");
168
235
  const script = `
169
236
  $ErrorActionPreference = 'Stop'
237
+ $ProgressPreference = 'SilentlyContinue'
238
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
170
239
  $target = '${(0, node_path_1.resolve)(executable).replace(/'/g, "''")}'
171
240
  $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 })
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 })
173
243
  $ids = @($processes.ProcessId)
174
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 = @()
175
264
  foreach ($item in $roots) {
176
265
  $current = Get-CimInstance Win32_Process -Filter "ProcessId=$($item.ProcessId)"
177
266
  if (-not $current -or $current.CreationDate -ne $item.CreationDate) { continue }
@@ -179,10 +268,11 @@ foreach ($item in $roots) {
179
268
  if ($LASTEXITCODE -ne 0 -and (Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue)) { throw "无法结束桌面进程 $($item.ProcessId)" }
180
269
  $remaining = Get-Process -Id $item.ProcessId -ErrorAction SilentlyContinue
181
270
  if ($remaining -and -not $remaining.WaitForExit(10000)) { throw "等待桌面进程退出超时 $($item.ProcessId)" }
271
+ $terminated += [int]$item.ProcessId
182
272
  }
183
- ConvertTo-Json -Compress -InputObject @($roots | ForEach-Object { [int]$_.ProcessId })
273
+ ConvertTo-Json -Compress -InputObject @($terminated)
184
274
  `;
185
- const { stdout } = await execFileAsync("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 30_000, windowsHide: true });
275
+ const { stdout } = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { timeout: 30_000, windowsHide: true });
186
276
  return JSON.parse(stdout.trim());
187
277
  }
188
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
- 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.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
- 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.30",
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.30",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",