ai-helper-agent 2.4.8 → 2.5.0

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.
Files changed (44) hide show
  1. package/README.md +33 -1
  2. package/README.zh-CN.md +33 -1
  3. package/bin/agent.js +78 -0
  4. package/dist/assets/{agent-store-BTqZ3_7C.js → agent-store-D0oEv0PW.js} +1 -1
  5. package/dist/assets/background.js +4 -4
  6. package/dist/assets/{chat-export-BE9AcllU.js → chat-export-MTTSSIwM.js} +1 -1
  7. package/dist/assets/content.js +28 -28
  8. package/dist/assets/i18n-Br_sF5pb.js +49 -0
  9. package/dist/assets/{markdown-render-BhfoP_jE.js → markdown-render-Dq5F_dqP.js} +2 -2
  10. package/dist/assets/{model-profiles-BlsZEsSZ.js → model-profiles-BdQaV4EZ.js} +1 -1
  11. package/dist/assets/{options-Dir2xv8X.css → options-JtYgxtsc.css} +1 -1
  12. package/dist/assets/options.js +297 -238
  13. package/dist/assets/{page-snapshot-renderer-2AUkuzX_.js → page-snapshot-renderer-Cl0qk7U1.js} +1 -1
  14. package/dist/assets/{session-store-Xg-R-TyE.js → session-store-KkrAlIc6.js} +3 -3
  15. package/dist/assets/side_panel.css +1 -1
  16. package/dist/assets/side_panel.js +174 -174
  17. package/dist/assets/{utils-CTRffrs-.js → utils-ZJjxSlg_.js} +1 -1
  18. package/dist/assets/{version-D_5kiJwl.js → version-C0CY79zF.js} +1 -1
  19. package/dist/manifest.json +1 -1
  20. package/dist/offscreen/offscreen.js +8 -8
  21. package/dist/options.html +38 -4
  22. package/dist/side_panel.html +25 -7
  23. package/dist/voice-capture-worklet.js +47 -0
  24. package/package.json +4 -1
  25. package/src/asr/config.js +155 -0
  26. package/src/asr/detect.js +215 -0
  27. package/src/asr/engine.js +347 -0
  28. package/src/asr/install.js +439 -0
  29. package/src/asr/model-catalog.js +207 -0
  30. package/src/asr/model-download.js +461 -0
  31. package/src/asr/model-pack.js +398 -0
  32. package/src/asr/offline-pool.js +283 -0
  33. package/src/asr/offline-worker.js +97 -0
  34. package/src/asr/probe-child.mjs +31 -0
  35. package/src/asr/routes.js +385 -0
  36. package/src/asr/session.js +435 -0
  37. package/src/asr/transcribe.js +310 -0
  38. package/src/directory-picker.js +157 -45
  39. package/src/locales/cli.json +26 -0
  40. package/src/locales/en.json +22 -1
  41. package/src/locales/zh.json +22 -1
  42. package/src/rag/install.js +60 -2
  43. package/src/server.js +136 -2
  44. package/dist/assets/i18n-DBVIgrwQ.js +0 -49
@@ -1,14 +1,18 @@
1
- // agent/src/directory-picker.js - 系统原生目录选择框(多后端兜底 + 完整诊断)
1
+ // agent/src/directory-picker.js - 系统原生目录选择框(多后端兜底 + 窗口可见性探测)
2
2
  //
3
3
  // 供扩展端「切换工作目录」弹窗的「浏览…」按钮调用,仅本机代理(loopback)才有意义:
4
4
  // 工作目录本就是代理端机器上的路径,远端弹窗用户也看不到(server.js 另有来源 IP 门控)。
5
5
  //
6
- // Windows 企业环境里「点了没窗口」的常见成因:
7
- // 1) Defender ASR「Block execution of potentially obfuscated scripts」拦截 -EncodedCommand
8
- // 2) Constrained Language Mode / AppLocker 拦截 Add-Type 加载 .NET 程序集
9
- // 3) 从 Git Bash 等非原生终端启动时 PATH / 环境变量被改写,PATH 查找不到 powershell.exe
10
- // 因此按「内联 -Command(绝对路径)→ EncodedCommand → cscript + WSH」顺序兜底,
11
- // 每个后端的失败原因都记录在 attempts 里;全部失败时把摘要回传给扩展端,避免“不知道怎么回事”。
6
+ // 实测发现:Windows 上从 CMD 启动 agent 时能弹窗,从 PowerShell / Git Bash 启动时弹不出来。
7
+ // 这说明 powershell.exe + System.Windows.Forms 这条通道本身可用(不是企业策略拦截),
8
+ // 问题在父进程环境/进程属性差异。为此这里的兜底必须满足两条:
9
+ // 1) 一个后端「窗口没出现」时不能在原地等满 120s,必须快速切到下一个后端;
10
+ // 2) 命令查找不能依赖 PATH,也不能依赖环境变量名的大小写。
11
+ //
12
+ // 后端按序尝试(Windows):
13
+ // powershell-inline(内联 -Command)→ powershell-encoded(-EncodedCommand)→ cscript-vbs(WSH)
14
+ // 每个后端在弹出窗口前先输出 SHOWN_MARKER:收到标记说明窗口已经走到 ShowDialog,
15
+ // 收不到说明进程卡在更早的阶段(加载程序集/创建窗口失败),此时杀掉进程换下一个后端。
12
16
  //
13
17
  // 稳定性约束(任何一条都不允许打破,否则会拖垮常驻的 agent 进程):
14
18
  // - 本模块对外只 resolve 结果对象,绝不 reject / 绝不抛异常
@@ -20,10 +24,16 @@ import fs from 'fs';
20
24
  import os from 'os';
21
25
  import path from 'path';
22
26
 
23
- // 选择框悬挂超时:用户长时间不选视为放弃,避免子进程常驻
27
+ // 用户不选时的最长等待
24
28
  const PICK_TIMEOUT_MS = 120 * 1000;
29
+ // 「窗口是否真的弹出来」的判定时限:超时即认为该后端不可用,立刻换下一个
30
+ const SHOWN_TIMEOUT_MS = 12 * 1000;
31
+ // 整次选择的总预算:3 个后端串行时不能无限拖长(扩展端 200s 兜底在此之后)
32
+ const PICK_TOTAL_BUDGET_MS = 180 * 1000;
25
33
  // 强杀后等待 close 的兜底时长:某些后端被杀后不触发 close,不能因此让请求挂着
26
34
  const KILL_SETTLE_MS = 2000;
35
+ // 窗口已进入显示流程的标记(子进程 stdout 中出现即认为窗口会出现)
36
+ const SHOWN_MARKER = '@@AI_HELPER_PICK_SHOWN@@';
27
37
  // 单个子进程输出上限(字符)
28
38
  const MAX_STREAM_CHARS = 64 * 1024;
29
39
  // 回传给扩展端的错误摘要上限(toast 能展示的长度)
@@ -43,19 +53,41 @@ function toBase64Utf8(text) {
43
53
  return Buffer.from(String(text), 'utf8').toString('base64');
44
54
  }
45
55
 
56
+ /**
57
+ * 大小写不敏感地读环境变量
58
+ * Windows 环境变量名不区分大小写,但 Node 的 process.env 是普通 JS 对象(区分大小写):
59
+ * 不同终端下同一个变量可能是 SystemRoot / SYSTEMROOT / systemroot,
60
+ * 只认一种写法会让绝对路径解析失败并静默退化到 PATH 查找(Git Bash 下 PATH 是 POSIX 形式,必然找不到)。
61
+ */
62
+ export function readEnvVar(env, name) {
63
+ if (!env || !name) return '';
64
+ const direct = env[name];
65
+ if (typeof direct === 'string' && direct) return direct;
66
+ const lower = name.toLowerCase();
67
+ for (const key of Object.keys(env)) {
68
+ if (key.toLowerCase() === lower) {
69
+ const value = env[key];
70
+ if (typeof value === 'string' && value) return value;
71
+ }
72
+ }
73
+ return '';
74
+ }
75
+
46
76
  /**
47
77
  * 解析 Windows 可执行文件的绝对路径
48
- * 优先用 %SystemRoot% 拼绝对路径,彻底摆脱 Git Bash/MSYS 对 PATH 与环境变量的改写;
49
- * 取不到 SystemRoot 时退回裸命令名,交由 PATH 查找。
78
+ * 优先用 %SystemRoot%(大小写不敏感)拼绝对路径,彻底摆脱 Git Bash/MSYS 对 PATH 的改写;
79
+ * 取不到时退回裸命令名,交由 PATH 查找。
50
80
  */
51
81
  function resolveWindowsExe(name, env) {
52
- const root = (env && (env.SystemRoot || env.windir || env.WINDIR)) || '';
82
+ const root = readEnvVar(env, 'SystemRoot') || readEnvVar(env, 'windir');
53
83
  if (root) {
84
+ // 混用 / 与 \ 会让部分 Windows API 解析失败,统一成反斜杠
85
+ const normalizedRoot = String(root).replace(/\//g, '\\');
54
86
  if (name === 'powershell') {
55
- return path.win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
87
+ return path.win32.join(normalizedRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
56
88
  }
57
89
  if (name === 'cscript') {
58
- return path.win32.join(root, 'System32', 'cscript.exe');
90
+ return path.win32.join(normalizedRoot, 'System32', 'cscript.exe');
59
91
  }
60
92
  }
61
93
  return `${name}.exe`;
@@ -68,9 +100,9 @@ function resolveWindowsExe(name, env) {
68
100
  */
69
101
  export function resolveTmpDir(platform, env = process.env) {
70
102
  if (platform === 'win32') {
71
- const local = env.LOCALAPPDATA || env.LocalAppData;
72
- if (local) return path.win32.join(local, 'Temp');
73
- const tmp = env.TEMP || env.TMP;
103
+ const local = readEnvVar(env, 'LOCALAPPDATA');
104
+ if (local) return path.win32.join(String(local).replace(/\//g, '\\'), 'Temp');
105
+ const tmp = readEnvVar(env, 'TEMP') || readEnvVar(env, 'TMP');
74
106
  // 只接受驱动器绝对路径,避开 MSYS 风格的 /tmp
75
107
  if (tmp && /^[A-Za-z]:[\\/]/.test(tmp)) return tmp;
76
108
  }
@@ -81,33 +113,34 @@ export function resolveTmpDir(platform, env = process.env) {
81
113
  * Windows PowerShell 脚本主体(共享给 -Command / -EncodedCommand 两个后端)
82
114
  * - 标题以 base64 传入并在脚本内解码:内联调用时命令行可保持纯 ASCII,避开代码页乱码
83
115
  * - 选中路径以 UTF-8 base64 写 stdout:避开中文 Windows 控制台 GBK 输出被按 UTF-8 解码的乱码
116
+ * - 弹出窗口前先输出 SHOWN_MARKER:让调用方能区分「窗口没出现」与「用户还没选」
117
+ * - owner 窗口只用于置顶,拿不到句柄时退回无 owner 调用,不能因此判定整体失败
84
118
  * - 退出码约定:0=选中 / 2=用户取消 / 1=异常(异常信息写 stderr)
85
119
  */
86
120
  function buildPowerShellScript(title) {
87
121
  const titleB64 = toBase64Utf8(sanitizeTitle(title));
88
122
  return [
89
- '$ErrorActionPreference = \'Stop\'',
90
123
  `$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${titleB64}'))`,
91
- 'try {',
92
- 'Add-Type -AssemblyName System.Windows.Forms',
124
+ // 注意:各行以 ';' 拼接,块起始行必须直接跟首条语句,不能留下 `{;` 这样的空语句
125
+ '$ErrorActionPreference = \'Stop\'; try { Add-Type -AssemblyName System.Windows.Forms',
93
126
  '$f = New-Object System.Windows.Forms.FolderBrowserDialog',
94
127
  '$f.Description = $t',
95
- '$owner = New-Object System.Windows.Forms.Form',
96
- '$owner.TopMost = $true',
97
- '$null = $owner.Handle',
98
- 'if ($f.ShowDialog($owner) -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($f.SelectedPath))); exit 0 }',
128
+ // owner 只是为了让对话框置顶;某些会话下 Form 句柄创建会失败,这时必须降级而不是整体报错
129
+ '$owner = $null',
130
+ 'try { $owner = New-Object System.Windows.Forms.Form; $owner.TopMost = $true; $null = $owner.Handle } catch { $owner = $null }',
131
+ `[Console]::Out.Write('${SHOWN_MARKER}'); [Console]::Out.Flush()`,
132
+ '$r = $null',
133
+ 'if ($null -ne $owner) { $r = $f.ShowDialog($owner) } else { $r = $f.ShowDialog() }',
134
+ 'if ($r -eq [System.Windows.Forms.DialogResult]::OK) { [Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($f.SelectedPath))); exit 0 }',
99
135
  'exit 2',
100
- '} catch {',
101
- '[Console]::Error.Write($_.Exception.GetType().Name + \': \' + $_.Exception.Message)',
102
- 'exit 1',
103
- '}',
136
+ '} catch { [Console]::Error.Write($_.Exception.GetType().Name + \': \' + $_.Exception.Message); exit 1 }',
104
137
  ].join('; ');
105
138
  }
106
139
 
107
140
  /**
108
141
  * VBScript 兜底后端:走 WSH + Shell.Application.BrowseForFolder
109
142
  * 与 PowerShell 完全不同的执行通道(不受 PowerShell 执行策略/语言模式影响),
110
- * 是 -Command 与 -EncodedCommand 双双被拦时的第三通路。
143
+ * 是 -Command 与 -EncodedCommand 双双失效时的第三通路。
111
144
  * 脚本本身保持纯 ASCII(英文标题),避免 .vbs 文件编码解析问题;
112
145
  * 选中路径写入临时文件(FSO Unicode = UTF-16LE),读回时不依赖控制台代码页。
113
146
  */
@@ -121,6 +154,7 @@ function buildVbsScript(outputFile) {
121
154
  'Set sh = CreateObject("Shell.Application")',
122
155
  'If Err.Number <> 0 Then WScript.Quit 1',
123
156
  'Err.Clear',
157
+ `WScript.Echo "${SHOWN_MARKER}"`,
124
158
  'Set folder = sh.BrowseForFolder(0, "Select working directory", 65, 0)',
125
159
  'If Err.Number <> 0 Then WScript.Quit 1',
126
160
  'Err.Clear',
@@ -155,7 +189,7 @@ function looksLikePath(value) {
155
189
  return /[\\/]/.test(s);
156
190
  }
157
191
 
158
- /** PowerShell 后端:stdout 为 UTF-8 base64 编码的路径 */
192
+ /** PowerShell 后端:stdout 为 UTF-8 base64 编码的路径(SHOWN_MARKER 行会被自动跳过) */
159
193
  function decodePowerShellOutput(stdout) {
160
194
  const raw = String(stdout || '').trim();
161
195
  if (!raw) return '';
@@ -187,9 +221,9 @@ function readPickedFile(file) {
187
221
 
188
222
  /**
189
223
  * 构造各平台的目录选择执行计划(按顺序尝试)
190
- * 每个条目:{ backend, kind, command, args?, prepare? }
224
+ * 每个条目:{ backend, kind, command, args?, expectShown, prepare? }
225
+ * - expectShown:该后端会在弹窗前输出 SHOWN_MARKER,可据此判定「窗口没出现」
191
226
  * - prepare() 用于需要落临时文件的后端,返回 { args, decode, cleanup, meta } 或 null(准备失败)
192
- * - 无 prepare 的条目直接用 args + decode
193
227
  * @param {string} title - 选择框提示文案
194
228
  * @param {string} [platform] - 平台标识(默认 process.platform,测试可注入)
195
229
  * @param {object} [options] - { env, tmpDir }
@@ -204,6 +238,7 @@ export function buildPickPlan(title, platform = process.platform, options = {})
204
238
  return [{
205
239
  backend: 'osascript',
206
240
  kind: 'posix',
241
+ expectShown: false,
207
242
  command: 'osascript',
208
243
  args: ['-e', `POSIX path of (choose folder with prompt "${safeTitle}")`],
209
244
  decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
@@ -222,6 +257,7 @@ export function buildPickPlan(title, platform = process.platform, options = {})
222
257
  // 同时不经过 -EncodedCommand,绕开 ASR「可疑混淆脚本」规则的拦截。
223
258
  backend: 'powershell-inline',
224
259
  kind: 'powershell',
260
+ expectShown: true,
225
261
  command: psExe,
226
262
  args: [...psCommon, '-Command', psScript],
227
263
  decode: (r) => decodePowerShellOutput(r.stdout),
@@ -230,14 +266,16 @@ export function buildPickPlan(title, platform = process.platform, options = {})
230
266
  // 后端 2:-EncodedCommand(base64 UTF-16LE),兼容极端转义场景,但可能被安全策略拦
231
267
  backend: 'powershell-encoded',
232
268
  kind: 'powershell',
269
+ expectShown: true,
233
270
  command: psExe,
234
271
  args: [...psCommon, '-EncodedCommand', Buffer.from(psScript, 'utf16le').toString('base64')],
235
272
  decode: (r) => decodePowerShellOutput(r.stdout),
236
273
  },
237
274
  {
238
- // 后端 3:cscript + WSH。完全独立的执行通道,用来覆盖 PowerShell 被策略整体封杀的情况
275
+ // 后端 3:cscript + WSH。完全独立的执行通道,用来覆盖 PowerShell 通道整体不可用的情况
239
276
  backend: 'cscript-vbs',
240
277
  kind: 'vbs',
278
+ expectShown: true,
241
279
  command: cscriptExe,
242
280
  prepare() {
243
281
  try {
@@ -267,6 +305,7 @@ export function buildPickPlan(title, platform = process.platform, options = {})
267
305
  {
268
306
  backend: 'zenity',
269
307
  kind: 'posix',
308
+ expectShown: false,
270
309
  command: 'zenity',
271
310
  args: ['--file-selection', '--directory', `--title=${safeTitle}`],
272
311
  decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
@@ -274,6 +313,7 @@ export function buildPickPlan(title, platform = process.platform, options = {})
274
313
  {
275
314
  backend: 'kdialog',
276
315
  kind: 'posix',
316
+ expectShown: false,
277
317
  command: 'kdialog',
278
318
  args: ['--getexistingdirectory', '~', '--title', safeTitle],
279
319
  decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
@@ -302,7 +342,7 @@ function classifyPickResult(runResult, item) {
302
342
  path: null,
303
343
  available: true,
304
344
  exitCode: code ?? null,
305
- error: `exit ${code === null || code === undefined ? 'unknown' : code}${errText ? `: ${errText}` : '(无 stderr,可能被安全策略拦截)'}`,
345
+ error: `exit ${code === null || code === undefined ? 'unknown' : code}${errText ? `: ${errText}` : '(无 stderr)'}`,
306
346
  };
307
347
  }
308
348
 
@@ -315,8 +355,13 @@ function classifyPickResult(runResult, item) {
315
355
  /**
316
356
  * 运行单个选择命令,收集 stdout/stderr
317
357
  * spawn 失败(ENOENT 等)、超时、被信号杀死等一律以结果对象返回,不抛异常
358
+ * @param {object} opts - { timeoutMs, shownTimeoutMs, expectShown }
359
+ * @returns {Promise<{code?, stdout?, stderr?, timedOut?: boolean, shown?: boolean,
360
+ * noWindow?: boolean, spawnError?: boolean}>}
318
361
  */
319
- function runPickOnce(command, args, timeoutMs, spawnImpl) {
362
+ function runPickOnce(command, args, opts, spawnImpl) {
363
+ const timeoutMs = opts.timeoutMs;
364
+ const shownTimeoutMs = opts.expectShown ? opts.shownTimeoutMs : 0;
320
365
  return new Promise((resolve) => {
321
366
  let child;
322
367
  try {
@@ -328,33 +373,54 @@ function runPickOnce(command, args, timeoutMs, spawnImpl) {
328
373
  let stdout = '';
329
374
  let stderr = '';
330
375
  let timedOut = false;
376
+ let shown = !shownTimeoutMs;
331
377
  let settled = false;
332
378
  let timer = null;
379
+ let shownTimer = null;
380
+ // 强杀时预期的结论(noWindow/超时):被杀进程通常会立刻触发 close,
381
+ // close 分支必须把这层结论合并进去,否则「窗口没出现」会被误当成普通退出
382
+ let pendingExtra = null;
333
383
  const finish = (result) => {
334
384
  if (settled) return;
335
385
  settled = true;
336
386
  if (timer) clearTimeout(timer);
387
+ if (shownTimer) clearTimeout(shownTimer);
337
388
  resolve(result);
338
389
  };
390
+ // 强杀后兜底 settle:被杀进程若始终不触发 close,也不能让 HTTP 请求挂着
391
+ const killAndSettle = (extra) => {
392
+ pendingExtra = extra;
393
+ try { child.kill(); } catch { /* 进程可能已退出 */ }
394
+ setTimeout(() => finish({ code: null, stdout, stderr, ...extra }), KILL_SETTLE_MS);
395
+ };
339
396
  timer = setTimeout(() => {
340
397
  timedOut = true;
341
- try { child.kill(); } catch { /* 进程可能已退出 */ }
342
- // 兜底 settle:被杀进程若始终不触发 close,也不能让 HTTP 请求挂着
343
- setTimeout(() => finish({ code: null, stdout, stderr, timedOut: true }), KILL_SETTLE_MS);
398
+ killAndSettle({ timedOut: true, shown });
344
399
  }, timeoutMs);
400
+ if (shownTimeoutMs) {
401
+ // 窗口迟迟不出现:立刻杀掉换下一个后端,而不是干等满 120s
402
+ shownTimer = setTimeout(() => {
403
+ if (shown) return;
404
+ killAndSettle({ noWindow: true, shown: false });
405
+ }, shownTimeoutMs);
406
+ }
345
407
  // 管道自身的 error(EPIPE/ECONNRESET,进程被杀或管道先行关闭时可能出现)必须监听:
346
408
  // EventEmitter 的 'error' 事件若无监听者会被抛成 uncaughtException
347
409
  child.stdout?.on?.('error', () => {});
348
410
  child.stderr?.on?.('error', () => {});
349
411
  child.stdout?.on?.('data', (chunk) => {
350
412
  if (stdout.length < MAX_STREAM_CHARS) stdout += chunk.toString();
413
+ if (!shown && stdout.includes(SHOWN_MARKER)) {
414
+ shown = true;
415
+ if (shownTimer) clearTimeout(shownTimer);
416
+ }
351
417
  });
352
418
  child.stderr?.on?.('data', (chunk) => {
353
419
  if (stderr.length < MAX_STREAM_CHARS) stderr += chunk.toString();
354
420
  });
355
421
  // spawn 失败(命令不存在等)以异步 error 事件呈现
356
422
  child.on?.('error', (err) => finish({ spawnError: true, stderr: String(err?.message || err) }));
357
- child.on?.('close', (code) => finish({ code, stdout, stderr, timedOut }));
423
+ child.on?.('close', (code) => finish({ code, stdout, stderr, timedOut, shown, ...(pendingExtra || {}) }));
358
424
  });
359
425
  }
360
426
 
@@ -367,6 +433,23 @@ function summarizeAttempts(attempts) {
367
433
  return text.length > MAX_ERROR_CHARS ? `${text.slice(0, MAX_ERROR_CHARS)}…` : text;
368
434
  }
369
435
 
436
+ /**
437
+ * 环境快照:失败时随结果返回,便于在没有 Windows 测试机的情况下定位
438
+ * (stdoutIsTTY 是判断「父终端是 mintty 还是 conhost」的关键信号)
439
+ */
440
+ function buildEnvironmentSnapshot(platform, env, plan) {
441
+ const pathValue = readEnvVar(env, 'PATH') || readEnvVar(env, 'Path');
442
+ return {
443
+ platform,
444
+ systemRoot: readEnvVar(env, 'SystemRoot') || readEnvVar(env, 'windir') || '(unset)',
445
+ localAppData: readEnvVar(env, 'LOCALAPPDATA') || '(unset)',
446
+ pathStartsWithPosix: Boolean(pathValue) && pathValue.startsWith('/'),
447
+ stdoutIsTTY: Boolean(process.stdout && process.stdout.isTTY),
448
+ tmpDir: resolveTmpDir(platform, env),
449
+ commands: plan.map((p) => p.command),
450
+ };
451
+ }
452
+
370
453
  /** 进行中的选择:同一时刻只允许一个窗口,避免连点拉起多个弹窗把 agent 拖住 */
371
454
  let inFlight = null;
372
455
 
@@ -375,21 +458,33 @@ async function doPickDirectory(title, options) {
375
458
  const env = options.env || process.env;
376
459
  const spawnImpl = options.spawnImpl || spawn;
377
460
  const timeoutMs = options.timeoutMs ?? PICK_TIMEOUT_MS;
461
+ const shownTimeoutMs = options.shownTimeoutMs ?? SHOWN_TIMEOUT_MS;
462
+ const totalBudgetMs = options.totalBudgetMs ?? PICK_TOTAL_BUDGET_MS;
463
+ const startedAt = Date.now();
378
464
 
379
465
  // 无图形会话的 Linux 直接降级(zenity/kdialog 起不来,只会白白报错)
380
466
  if (platform === 'linux') {
381
- const hasDisplay = options.hasDisplay ?? Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
467
+ const hasDisplay = options.hasDisplay ?? Boolean(readEnvVar(env, 'DISPLAY') || readEnvVar(env, 'WAYLAND_DISPLAY'));
382
468
  if (!hasDisplay) {
383
469
  return { success: false, path: null, available: false, error: 'no-display', attempts: [] };
384
470
  }
385
471
  }
386
472
 
387
473
  const plan = buildPickPlan(title, platform, { env, tmpDir: options.tmpDir });
474
+ const environment = buildEnvironmentSnapshot(platform, env, plan);
388
475
 
389
476
  const attempts = [];
390
477
  let lastTimeout = null;
391
478
 
392
479
  for (const item of plan) {
480
+ // 总预算控制:串行三后端最坏情况下也不能无限拖长
481
+ const elapsed = Date.now() - startedAt;
482
+ const remaining = totalBudgetMs - elapsed;
483
+ if (remaining <= 1000) {
484
+ attempts.push({ backend: item.backend, error: 'skipped: 总预算已耗尽' });
485
+ continue;
486
+ }
487
+
393
488
  let prepared = null;
394
489
  try {
395
490
  prepared = item.prepare
@@ -405,20 +500,31 @@ async function doPickDirectory(title, options) {
405
500
  }
406
501
 
407
502
  try {
408
- const r = await runPickOnce(item.command, prepared.args, timeoutMs, spawnImpl);
503
+ const r = await runPickOnce(item.command, prepared.args, {
504
+ // 「窗口未出现」的判定时限不能超过剩余预算
505
+ shownTimeoutMs: Math.min(shownTimeoutMs, remaining),
506
+ timeoutMs: Math.min(timeoutMs, remaining),
507
+ expectShown: Boolean(item.expectShown),
508
+ }, spawnImpl);
509
+
409
510
  if (r.spawnError) {
410
511
  // 该命令不可用(未安装/路径不对/无法执行),记录原因后尝试下一个后端
411
512
  attempts.push({ backend: item.backend, error: `spawn-failed: ${String(r.stderr || '').slice(0, 160)}` });
412
513
  continue;
413
514
  }
515
+ if (r.noWindow) {
516
+ // 进程活着但窗口始终没出现(加载程序集失败/会话无桌面等):换下一个后端,不在这里干等
517
+ attempts.push({ backend: item.backend, error: `no-window-in-${shownTimeoutMs}ms` });
518
+ continue;
519
+ }
414
520
  if (r.timedOut) {
415
- // 进程起来了却没有结果:多见于「窗口被策略挡住/不可见」或用户一直没选
521
+ // 能走到这里说明窗口已经进入显示流程,是用户没在时限内选完
416
522
  lastTimeout = {
417
523
  backend: item.backend,
418
524
  detail: String(r.stderr || '').trim().slice(0, 160),
419
525
  };
420
- attempts.push({ backend: item.backend, error: `timeout${lastTimeout.detail ? `: ${lastTimeout.detail}` : '(窗口未在时限内返回,可能被安全策略拦截或不可见)'}` });
421
- // 超时意味着窗口可能真的弹出来了,不再继续拉第二个窗口
526
+ attempts.push({ backend: item.backend, error: 'timeout: 窗口已显示但未在时限内返回' });
527
+ // 窗口已经出现,继续拉第二个窗口会让人困惑,直接结束
422
528
  break;
423
529
  }
424
530
  const result = classifyPickResult(r, { kind: item.kind, decode: prepared.decode });
@@ -445,6 +551,7 @@ async function doPickDirectory(title, options) {
445
551
  detail: lastTimeout.detail || '',
446
552
  attempts,
447
553
  diagnostics: summary,
554
+ environment,
448
555
  };
449
556
  }
450
557
  // 全部后端都没能弹出窗口:区分「根本没有可用工具」与「工具在但执行失败」
@@ -457,15 +564,17 @@ async function doPickDirectory(title, options) {
457
564
  error: noTool ? `no-dialog-tool: ${summary}` : `all-backends-failed: ${summary}`,
458
565
  attempts,
459
566
  diagnostics: summary,
567
+ environment,
460
568
  };
461
569
  }
462
570
 
463
571
  /**
464
572
  * 弹出系统原生目录选择框
465
573
  * @param {string} [title] - 选择框提示文案
466
- * @param {object} [options] - spawnImpl / timeoutMs / platform / env / tmpDir / hasDisplay(均为可注入,便于测试)
574
+ * @param {object} [options] - spawnImpl / timeoutMs / shownTimeoutMs / totalBudgetMs / platform /
575
+ * env / tmpDir / hasDisplay(均可注入,便于测试)
467
576
  * @returns {Promise<{success: boolean, path: string|null, available: boolean, backend?: string,
468
- * error?: string, attempts?: Array<object>, diagnostics?: string}>}
577
+ * error?: string, attempts?: Array<object>, diagnostics?: string, environment?: object}>}
469
578
  * - 选中:{ success: true, path, available: true, backend }
470
579
  * - 用户取消:{ success: true, path: null, available: true }
471
580
  * - 环境不支持:{ success: false, path: null, available: false, error: 'no-dialog-tool: …' | 'no-display' }
@@ -499,3 +608,6 @@ export async function pickDirectoryNative(title = '', options = {}) {
499
608
  export function isPickInFlight() {
500
609
  return Boolean(inFlight);
501
610
  }
611
+
612
+ /** 测试用:窗口标记常量 */
613
+ export const SHOWN_MARKER_FOR_TEST = SHOWN_MARKER;
@@ -11,6 +11,7 @@
11
11
  "cmdConfig": " config 查看当前配置",
12
12
  "cmdHelp": " help 显示此帮助信息",
13
13
  "cmdRag": " rag 管理 RAG 可选依赖 (status | install)",
14
+ "cmdAsr": " asr 管理语音识别可选依赖 (status | install)",
14
15
  "cmdUpdate": " update 检查并更新到最新版本 (--check 仅检查)",
15
16
  "cmdUninstall": " uninstall 一键卸载代理端",
16
17
  "cmdAutostart": " autostart 开机自启管理 (on | off)",
@@ -72,6 +73,18 @@
72
73
  "ragRestartAdvice": "提示:若多次安装失败,可尝试重启代理服务(aha restart)后再重试。",
73
74
  "ragUnknownSub": "未知的 rag 子命令: {sub}",
74
75
  "ragHelpUsage": "用法: aha rag <status|install>",
76
+ "asrStatusTitle": "======= 语音识别(ASR)能力检测 ========",
77
+ "asrAvailable": "✅ 语音识别依赖已就绪",
78
+ "asrNotAvailable": "❌ 语音识别依赖未安装(可运行 aha asr install 一键安装)",
79
+ "asrProbeError": "探测详情: {reason}",
80
+ "asrInstalling": "正在安装语音识别依赖(sherpa-onnx-node,约 300MB+,可能需要几分钟)...",
81
+ "asrInstallFailed": "语音识别依赖安装失败(退出码 {code})",
82
+ "asrInstallSuccess": "✅ 语音识别依赖安装成功,功能已就绪",
83
+ "asrVerifyFailed": "npm 安装完成,但依赖验证未通过",
84
+ "asrRestartAdvice": "提示:若多次安装失败,可尝试重启代理服务(aha restart)后重试。",
85
+ "asrModelHint": "注意:依赖就绪后还需导入本地模型包(配置页 → 工具箱 → 语音输入 → 选择模型目录)。",
86
+ "asrUnknownSub": "未知的 asr 子命令: {sub}",
87
+ "asrHelpUsage": "用法: aha asr <status|install>",
75
88
  "updateLatest": "已是最新版本 v{version}",
76
89
  "updateAvailable": "发现新版本: v{current} → v{latest}(运行 aha update 更新)",
77
90
  "updateInstalling": "正在更新 v{current} → v{latest}...",
@@ -103,6 +116,7 @@
103
116
  "cmdConfig": " config View current configuration",
104
117
  "cmdHelp": " help Show this help message",
105
118
  "cmdRag": " rag Manage RAG optional dependencies (status | install)",
119
+ "cmdAsr": " asr Manage speech recognition optional dependencies (status | install)",
106
120
  "cmdUpdate": " update Check and update to latest (--check for info only)",
107
121
  "cmdUninstall": " uninstall One-click uninstall agent",
108
122
  "cmdAutostart": " autostart Manage auto-start (on | off)",
@@ -164,6 +178,18 @@
164
178
  "ragRestartAdvice": "Tip: if installation keeps failing, try restarting the agent (aha restart) and retry.",
165
179
  "ragUnknownSub": "Unknown rag subcommand: {sub}",
166
180
  "ragHelpUsage": "Usage: aha rag <status|install>",
181
+ "asrStatusTitle": "======= ASR Capability Check ========",
182
+ "asrAvailable": "✅ Speech recognition dependencies are ready",
183
+ "asrNotAvailable": "❌ Speech recognition dependencies not installed (run 'aha asr install')",
184
+ "asrProbeError": "Probe detail: {reason}",
185
+ "asrInstalling": "Installing speech recognition dependencies (sherpa-onnx-node, 300MB+, may take several minutes)...",
186
+ "asrInstallFailed": "Speech recognition dependency installation failed (exit code {code})",
187
+ "asrInstallSuccess": "✅ Speech recognition dependencies installed successfully",
188
+ "asrVerifyFailed": "npm install completed, but dependency verification failed",
189
+ "asrRestartAdvice": "Tip: if installation keeps failing, restart the agent (aha restart) and retry.",
190
+ "asrModelHint": "Note: local model packs must be imported too (Options -> Toolbox -> Voice Input -> Select model directory).",
191
+ "asrUnknownSub": "Unknown asr subcommand: {sub}",
192
+ "asrHelpUsage": "Usage: aha asr <status|install>",
167
193
  "updateLatest": "Already at latest version v{version}",
168
194
  "updateAvailable": "New version available: v{current} → v{latest} (run aha update)",
169
195
  "updateInstalling": "Updating v{current} → v{latest}...",
@@ -87,7 +87,8 @@
87
87
  "stderrTruncated": "stderr output exceeded 5MB limit, truncated",
88
88
  "ragNotAvailable": "RAG dependencies are not installed or the environment does not meet the requirements. Please install RAG dependencies on the agent side first",
89
89
  "ragInstallInProgress": "RAG dependency installation is in progress, please try again later",
90
- "ragLoadFailed": "Failed to load knowledge base module: {message} (try restarting the agent and retry)"
90
+ "ragLoadFailed": "Failed to load knowledge base module: {message} (try restarting the agent and retry)",
91
+ "asrNotAvailable": "Voice input dependencies are not installed or are being installed. Install them in Options → Toolbox → Voice Input"
91
92
  },
92
93
  "rag": {
93
94
  "nodeVersionLow": "Node.js 22+ is required (current {version}), RAG features are unavailable",
@@ -307,6 +308,26 @@
307
308
  "uncaughtException": "Uncaught exception",
308
309
  "unhandledRejection": "Unhandled Promise rejection"
309
310
  },
311
+ "asr": {
312
+ "depsMissing": "Optional speech recognition dependencies are not installed (Node.js 18+ required). Voice input is unavailable — install them in Options → Toolbox → Voice Input, or run `aha asr install`",
313
+ "depsReady": "Speech recognition dependencies detected",
314
+ "installRunning": "Dependency installation is already running, please retry later",
315
+ "installTimeout": "Dependency installation timed out (10 minutes). Check your network and retry",
316
+ "installAborted": "Dependency installation was aborted (agent stopped or process exited)",
317
+ "installFailed": "Dependency installation failed: {message}",
318
+ "verifyFailed": "npm install finished but dependency verification failed",
319
+ "pickModelDirTitle": "Select a speech model folder (must contain manifest.json)",
320
+ "modelInvalid": "Model pack validation failed: {reason}",
321
+ "invalidModelId": "Invalid model id: {id}",
322
+ "emptyAudio": "Audio payload is empty",
323
+ "invalidAudio": "Failed to decode audio payload",
324
+ "audioTooLarge": "Audio exceeds the size limit (max 5 minutes per recording)",
325
+ "modelMissing": "No usable speech model pack found. Import a finalize model in Options",
326
+ "unsupportedAudio": "Unsupported audio format (PCM WAV only)",
327
+ "transcribeFailed": "Speech recognition failed, please retry",
328
+ "downloadFailed": "Model download failed: {message}",
329
+ "downloadAborted": "Model download aborted (agent stopped or process exited)"
330
+ },
310
331
  "memory": {
311
332
  "missingAction": "Missing action parameter",
312
333
  "missingType": "Missing type parameter",
@@ -87,7 +87,8 @@
87
87
  "stderrTruncated": "stderr 输出超过 5MB 上限,已截断",
88
88
  "ragNotAvailable": "RAG 功能依赖未安装或运行环境不满足要求,请先在代理端安装 RAG 依赖",
89
89
  "ragInstallInProgress": "RAG 依赖安装正在进行中,请稍后再试",
90
- "ragLoadFailed": "知识库模块加载失败: {message}(可尝试重启代理端后重试)"
90
+ "ragLoadFailed": "知识库模块加载失败: {message}(可尝试重启代理端后重试)",
91
+ "asrNotAvailable": "语音输入组件未安装或正在安装中,请先在配置页「工具箱 → 语音输入」安装组件"
91
92
  },
92
93
  "rag": {
93
94
  "nodeVersionLow": "需要 Node.js 22+(当前 {version}),RAG 功能不可用",
@@ -307,6 +308,26 @@
307
308
  "uncaughtException": "未捕获异常",
308
309
  "unhandledRejection": "未处理的 Promise 拒绝"
309
310
  },
311
+ "asr": {
312
+ "depsMissing": "语音识别可选依赖未安装(需 Node.js 18+),语音输入功能不可用(可在配置页「工具箱 → 语音输入」一键安装,或运行 aha asr install)",
313
+ "depsReady": "语音识别可选依赖检测通过",
314
+ "installRunning": "语音识别组件安装已在进行中,请稍后重试",
315
+ "installTimeout": "语音识别组件安装超时(10 分钟),请检查网络后重试",
316
+ "installAborted": "语音识别组件安装已中止(Agent 关闭或进程退出)",
317
+ "installFailed": "语音识别组件安装失败: {message}",
318
+ "verifyFailed": "npm 安装完成,但依赖验证未通过",
319
+ "pickModelDirTitle": "选择语音模型目录(内含 manifest.json)",
320
+ "modelInvalid": "模型包校验未通过: {reason}",
321
+ "invalidModelId": "非法模型 ID: {id}",
322
+ "emptyAudio": "音频内容为空",
323
+ "invalidAudio": "音频数据解析失败",
324
+ "audioTooLarge": "音频超过大小限制(单次录音上限 5 分钟)",
325
+ "modelMissing": "未找到可用的语音模型包,请在配置页导入定稿模型",
326
+ "unsupportedAudio": "不支持的音频格式(仅支持 PCM WAV)",
327
+ "transcribeFailed": "语音识别失败,请重试",
328
+ "downloadFailed": "模型下载失败: {message}",
329
+ "downloadAborted": "模型下载已中止(Agent 关闭或进程退出)"
330
+ },
310
331
  "memory": {
311
332
  "missingAction": "缺少 action 参数",
312
333
  "missingType": "缺少 type 参数",
@@ -66,6 +66,62 @@ export function getRagInstallSpecs() {
66
66
  return RAG_DEPENDENCY_ENTRIES.map(([name, spec]) => `${name}@${spec}`);
67
67
  }
68
68
 
69
+ /**
70
+ * 取 spec 的包名(兼容 scoped:@scope/pkg@^1.0.0 → @scope/pkg)
71
+ * @param {string} spec
72
+ * @returns {string}
73
+ */
74
+ function specName(spec) {
75
+ const idx = spec.lastIndexOf('@');
76
+ return idx > 0 ? spec.slice(0, idx) : spec;
77
+ }
78
+
79
+ /**
80
+ * 读取「对侧」可选组件(ASR 语音输入)曾安装成功的依赖 spec,用于合并安装
81
+ *
82
+ * 背景(实测缺陷):ASR 与 RAG 的可选依赖都以 `npm install --no-save` 装在同一个
83
+ * 包目录里。npm 执行带包名的 install 时会按依赖树重算包目录,把不在本次清单内的
84
+ * 顶层包当作 extraneous 移除——只带自己清单安装,就会把 ASR 整组依赖清掉。
85
+ * 判据用对侧状态文件的 everSucceeded(持久化,不随目录被清而丢失):只要对方曾经
86
+ * 装成功过,就把它的清单一起带上,既避免互相清除,也顺带恢复已被清掉的对方。
87
+ * @returns {string[]}
88
+ */
89
+ function readPeerPreservedSpecs() {
90
+ try {
91
+ const stateFile = join(homedir(), '.ai-helper-agent', 'asr-install-state.json');
92
+ if (!existsSync(stateFile)) return [];
93
+ const state = JSON.parse(readFileSync(stateFile, 'utf-8'));
94
+ if (!state || state.everSucceeded !== true) return [];
95
+ const raw = JSON.parse(readFileSync(join(getAgentRoot(), 'package.json'), 'utf-8'));
96
+ const deps = raw && typeof raw.asrDependencies === 'object' && raw.asrDependencies !== null
97
+ ? raw.asrDependencies
98
+ : {};
99
+ return Object.entries(deps)
100
+ .filter(([name, spec]) => name && typeof spec === 'string' && spec.trim())
101
+ .map(([name, spec]) => `${name}@${spec}`);
102
+ } catch {
103
+ return [];
104
+ }
105
+ }
106
+
107
+ /**
108
+ * 合并本组件清单与对侧保全清单(同名包以本组件 spec 为准,本组件顺序在前)
109
+ * @param {string[]} ownSpecs
110
+ * @param {string[]} peerSpecs
111
+ * @returns {string[]}
112
+ */
113
+ function mergePreservedSpecs(ownSpecs, peerSpecs) {
114
+ const seen = new Set(ownSpecs.map(specName));
115
+ const merged = [...ownSpecs];
116
+ for (const spec of peerSpecs) {
117
+ const name = specName(spec);
118
+ if (!name || seen.has(name)) continue;
119
+ seen.add(name);
120
+ merged.push(spec);
121
+ }
122
+ return merged;
123
+ }
124
+
69
125
  /**
70
126
  * Windows:定位与 node 同目录分布的 npm-cli.js(官方安装器 / nvm-windows 结构)
71
127
  * @param {string} execPath
@@ -91,11 +147,13 @@ function findWinNpmCli(execPath) {
91
147
  export function buildRagInstallCommand(opts = {}) {
92
148
  const isWin = opts.isWin ?? process.platform === 'win32';
93
149
  const execPath = opts.execPath ?? process.execPath;
94
- const specs = opts.specs ?? getRagInstallSpecs();
95
- if (specs.length === 0) {
150
+ const ownSpecs = opts.specs ?? getRagInstallSpecs();
151
+ if (ownSpecs.length === 0) {
96
152
  // 包损坏/被裁剪:拒绝构建(无包名参数的 npm install 会按依赖树重算包目录,不可接受)
97
153
  throw new Error('ragDependencies missing in package.json');
98
154
  }
155
+ // 显式注入 specs(测试/诊断)视为精确清单,不做对侧保全
156
+ const specs = opts.specs ? ownSpecs : mergePreservedSpecs(ownSpecs, readPeerPreservedSpecs());
99
157
  // 如果有探测出的镜像 registry,自动注入(npm -g 用户无 mirrors.json 时此值为 undefined)
100
158
  const registryUrl = opts.registry ?? getRegistryUrl();
101
159
  const baseArgs = ['install', '--no-save', '--no-audit', '--no-fund'];