ai-helper-agent 2.4.7 → 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.
- package/README.md +33 -1
- package/README.zh-CN.md +33 -1
- package/bin/agent.js +78 -0
- package/dist/assets/{agent-store-Wu4cQfi-.js → agent-store-D0oEv0PW.js} +1 -1
- package/dist/assets/background.js +5 -5
- package/dist/assets/chat-export-MTTSSIwM.js +37 -0
- package/dist/assets/content.js +41 -30
- package/dist/assets/{dist-LQPh1k0y.js → dist-BUuoW_84.js} +1 -1
- package/dist/assets/i18n-Br_sF5pb.js +49 -0
- package/dist/assets/{markdown-render-DsMFYJ7j.js → markdown-render-Dq5F_dqP.js} +2 -2
- package/dist/assets/{model-profiles-DWY7gG5H.js → model-profiles-BdQaV4EZ.js} +1 -1
- package/dist/assets/{options-Dir2xv8X.css → options-JtYgxtsc.css} +1 -1
- package/dist/assets/options.js +297 -238
- package/dist/assets/{page-snapshot-renderer-C0SlAjsY.js → page-snapshot-renderer-Cl0qk7U1.js} +1 -1
- package/dist/assets/{session-store-Dtfmjrt-.js → session-store-KkrAlIc6.js} +3 -3
- package/dist/assets/side_panel.css +1 -1
- package/dist/assets/side_panel.js +400 -400
- package/dist/assets/{utils-S-aJS9gf.js → utils-ZJjxSlg_.js} +1 -1
- package/dist/assets/{version-CcGQQNRR.js → version-C0CY79zF.js} +1 -1
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +9 -9
- package/dist/options.html +38 -4
- package/dist/side_panel.html +25 -7
- package/dist/voice-capture-worklet.js +47 -0
- package/package.json +4 -1
- package/src/asr/config.js +155 -0
- package/src/asr/detect.js +215 -0
- package/src/asr/engine.js +347 -0
- package/src/asr/install.js +439 -0
- package/src/asr/model-catalog.js +207 -0
- package/src/asr/model-download.js +461 -0
- package/src/asr/model-pack.js +398 -0
- package/src/asr/offline-pool.js +283 -0
- package/src/asr/offline-worker.js +97 -0
- package/src/asr/probe-child.mjs +31 -0
- package/src/asr/routes.js +385 -0
- package/src/asr/session.js +435 -0
- package/src/asr/transcribe.js +310 -0
- package/src/directory-picker.js +549 -70
- package/src/locales/cli.json +26 -0
- package/src/locales/en.json +22 -1
- package/src/locales/zh.json +22 -1
- package/src/rag/install.js +60 -2
- package/src/server.js +168 -7
- package/dist/assets/chat-export-DYpi1VYc.js +0 -37
- package/dist/assets/i18n-DkQH7l0R.js +0 -49
package/src/directory-picker.js
CHANGED
|
@@ -1,67 +1,367 @@
|
|
|
1
|
-
// agent/src/directory-picker.js -
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// agent/src/directory-picker.js - 系统原生目录选择框(多后端兜底 + 窗口可见性探测)
|
|
2
|
+
//
|
|
3
|
+
// 供扩展端「切换工作目录」弹窗的「浏览…」按钮调用,仅本机代理(loopback)才有意义:
|
|
4
|
+
// 工作目录本就是代理端机器上的路径,远端弹窗用户也看不到(server.js 另有来源 IP 门控)。
|
|
5
|
+
//
|
|
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
|
+
// 收不到说明进程卡在更早的阶段(加载程序集/创建窗口失败),此时杀掉进程换下一个后端。
|
|
16
|
+
//
|
|
17
|
+
// 稳定性约束(任何一条都不允许打破,否则会拖垮常驻的 agent 进程):
|
|
18
|
+
// - 本模块对外只 resolve 结果对象,绝不 reject / 绝不抛异常
|
|
19
|
+
// - 子进程有超时强杀 + 强杀后兜底 settle,保证请求不会永久悬挂
|
|
20
|
+
// - 子进程输出有长度上限,防止异常命令刷爆内存
|
|
21
|
+
// - 同一时刻只允许一个选择框,连点不会拉起多个窗口
|
|
4
22
|
import { spawn } from 'child_process';
|
|
23
|
+
import fs from 'fs';
|
|
24
|
+
import os from 'os';
|
|
25
|
+
import path from 'path';
|
|
5
26
|
|
|
6
|
-
//
|
|
27
|
+
// 用户不选时的最长等待
|
|
7
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;
|
|
33
|
+
// 强杀后等待 close 的兜底时长:某些后端被杀后不触发 close,不能因此让请求挂着
|
|
34
|
+
const KILL_SETTLE_MS = 2000;
|
|
35
|
+
// 窗口已进入显示流程的标记(子进程 stdout 中出现即认为窗口会出现)
|
|
36
|
+
const SHOWN_MARKER = '@@AI_HELPER_PICK_SHOWN@@';
|
|
37
|
+
// 单个子进程输出上限(字符)
|
|
38
|
+
const MAX_STREAM_CHARS = 64 * 1024;
|
|
39
|
+
// 回传给扩展端的错误摘要上限(toast 能展示的长度)
|
|
40
|
+
const MAX_ERROR_CHARS = 300;
|
|
41
|
+
const DEFAULT_TITLE = 'Select folder';
|
|
42
|
+
|
|
43
|
+
/** 清理标题:去掉会破坏脚本/参数的字符(各后端都把标题拼进脚本或参数) */
|
|
44
|
+
function sanitizeTitle(title) {
|
|
45
|
+
return String(title || '')
|
|
46
|
+
.replace(/["'\\`\r\n\t]/g, ' ')
|
|
47
|
+
.replace(/\s+/g, ' ')
|
|
48
|
+
.trim()
|
|
49
|
+
.slice(0, 120) || DEFAULT_TITLE;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function toBase64Utf8(text) {
|
|
53
|
+
return Buffer.from(String(text), 'utf8').toString('base64');
|
|
54
|
+
}
|
|
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
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 解析 Windows 可执行文件的绝对路径
|
|
78
|
+
* 优先用 %SystemRoot%(大小写不敏感)拼绝对路径,彻底摆脱 Git Bash/MSYS 对 PATH 的改写;
|
|
79
|
+
* 取不到时退回裸命令名,交由 PATH 查找。
|
|
80
|
+
*/
|
|
81
|
+
function resolveWindowsExe(name, env) {
|
|
82
|
+
const root = readEnvVar(env, 'SystemRoot') || readEnvVar(env, 'windir');
|
|
83
|
+
if (root) {
|
|
84
|
+
// 混用 / 与 \ 会让部分 Windows API 解析失败,统一成反斜杠
|
|
85
|
+
const normalizedRoot = String(root).replace(/\//g, '\\');
|
|
86
|
+
if (name === 'powershell') {
|
|
87
|
+
return path.win32.join(normalizedRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
88
|
+
}
|
|
89
|
+
if (name === 'cscript') {
|
|
90
|
+
return path.win32.join(normalizedRoot, 'System32', 'cscript.exe');
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return `${name}.exe`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 解析可用于落临时文件的目录
|
|
98
|
+
* Windows 下优先 %LOCALAPPDATA%\Temp:从 Git Bash 等 MSYS 终端启动时 TEMP/TMP 可能被改写成
|
|
99
|
+
* POSIX 形式(/tmp),直接用 os.tmpdir() 会落到不可写的盘根,导致 VBS 兜底后端静默失效。
|
|
100
|
+
*/
|
|
101
|
+
export function resolveTmpDir(platform, env = process.env) {
|
|
102
|
+
if (platform === 'win32') {
|
|
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');
|
|
106
|
+
// 只接受驱动器绝对路径,避开 MSYS 风格的 /tmp
|
|
107
|
+
if (tmp && /^[A-Za-z]:[\\/]/.test(tmp)) return tmp;
|
|
108
|
+
}
|
|
109
|
+
return os.tmpdir();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Windows PowerShell 脚本主体(共享给 -Command / -EncodedCommand 两个后端)
|
|
114
|
+
* - 标题以 base64 传入并在脚本内解码:内联调用时命令行可保持纯 ASCII,避开代码页乱码
|
|
115
|
+
* - 选中路径以 UTF-8 base64 写 stdout:避开中文 Windows 控制台 GBK 输出被按 UTF-8 解码的乱码
|
|
116
|
+
* - 弹出窗口前先输出 SHOWN_MARKER:让调用方能区分「窗口没出现」与「用户还没选」
|
|
117
|
+
* - owner 窗口只用于置顶,拿不到句柄时退回无 owner 调用,不能因此判定整体失败
|
|
118
|
+
* - 退出码约定:0=选中 / 2=用户取消 / 1=异常(异常信息写 stderr)
|
|
119
|
+
*/
|
|
120
|
+
function buildPowerShellScript(title) {
|
|
121
|
+
const titleB64 = toBase64Utf8(sanitizeTitle(title));
|
|
122
|
+
return [
|
|
123
|
+
`$t = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${titleB64}'))`,
|
|
124
|
+
// 注意:各行以 ';' 拼接,块起始行必须直接跟首条语句,不能留下 `{;` 这样的空语句
|
|
125
|
+
'$ErrorActionPreference = \'Stop\'; try { Add-Type -AssemblyName System.Windows.Forms',
|
|
126
|
+
'$f = New-Object System.Windows.Forms.FolderBrowserDialog',
|
|
127
|
+
'$f.Description = $t',
|
|
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 }',
|
|
135
|
+
'exit 2',
|
|
136
|
+
'} catch { [Console]::Error.Write($_.Exception.GetType().Name + \': \' + $_.Exception.Message); exit 1 }',
|
|
137
|
+
].join('; ');
|
|
138
|
+
}
|
|
8
139
|
|
|
9
140
|
/**
|
|
10
|
-
*
|
|
141
|
+
* VBScript 兜底后端:走 WSH + Shell.Application.BrowseForFolder
|
|
142
|
+
* 与 PowerShell 完全不同的执行通道(不受 PowerShell 执行策略/语言模式影响),
|
|
143
|
+
* 是 -Command 与 -EncodedCommand 双双失效时的第三通路。
|
|
144
|
+
* 脚本本身保持纯 ASCII(英文标题),避免 .vbs 文件编码解析问题;
|
|
145
|
+
* 选中路径写入临时文件(FSO Unicode = UTF-16LE),读回时不依赖控制台代码页。
|
|
146
|
+
*/
|
|
147
|
+
function buildVbsScript(outputFile) {
|
|
148
|
+
const safeOut = String(outputFile).replace(/"/g, '""');
|
|
149
|
+
return [
|
|
150
|
+
'Option Explicit',
|
|
151
|
+
'On Error Resume Next',
|
|
152
|
+
'Dim sh, folder, picked, fso, ts',
|
|
153
|
+
'picked = ""',
|
|
154
|
+
'Set sh = CreateObject("Shell.Application")',
|
|
155
|
+
'If Err.Number <> 0 Then WScript.Quit 1',
|
|
156
|
+
'Err.Clear',
|
|
157
|
+
`WScript.Echo "${SHOWN_MARKER}"`,
|
|
158
|
+
'Set folder = sh.BrowseForFolder(0, "Select working directory", 65, 0)',
|
|
159
|
+
'If Err.Number <> 0 Then WScript.Quit 1',
|
|
160
|
+
'Err.Clear',
|
|
161
|
+
'If Not folder Is Nothing Then',
|
|
162
|
+
' If Not folder.Self Is Nothing Then picked = folder.Self.Path',
|
|
163
|
+
'End If',
|
|
164
|
+
'Set fso = CreateObject("Scripting.FileSystemObject")',
|
|
165
|
+
'If Err.Number <> 0 Then WScript.Quit 1',
|
|
166
|
+
'Err.Clear',
|
|
167
|
+
`Set ts = fso.OpenTextFile("${safeOut}", 2, True, -1)`,
|
|
168
|
+
'If Err.Number <> 0 Then WScript.Quit 1',
|
|
169
|
+
'ts.Write picked',
|
|
170
|
+
'ts.Close',
|
|
171
|
+
'WScript.Quit 0',
|
|
172
|
+
'',
|
|
173
|
+
].join('\r\n');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** 规整选中路径:去首尾空白与尾部分隔符(根目录 "/" 与 "C:\\" 除外) */
|
|
177
|
+
export function normalizePickedPath(raw) {
|
|
178
|
+
let p = String(raw || '').trim();
|
|
179
|
+
while (p.length > 3 && /[\\/]$/.test(p)) p = p.slice(0, -1);
|
|
180
|
+
if (/^[A-Za-z]:$/.test(p)) p += '\\';
|
|
181
|
+
return p;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 路径合理性校验:排除乱码与控制字符(base64 误解码时会出现) */
|
|
185
|
+
function looksLikePath(value) {
|
|
186
|
+
const s = String(value || '').trim();
|
|
187
|
+
if (!s || s.length > 4096) return false;
|
|
188
|
+
if (/[\u0000-\u001f\ufffd]/.test(s)) return false;
|
|
189
|
+
return /[\\/]/.test(s);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** PowerShell 后端:stdout 为 UTF-8 base64 编码的路径(SHOWN_MARKER 行会被自动跳过) */
|
|
193
|
+
function decodePowerShellOutput(stdout) {
|
|
194
|
+
const raw = String(stdout || '').trim();
|
|
195
|
+
if (!raw) return '';
|
|
196
|
+
// 只取最后一行非空内容(防止任何前缀噪声)
|
|
197
|
+
const lines = raw.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
198
|
+
for (let i = lines.length - 1; i >= 0; i -= 1) {
|
|
199
|
+
const line = lines[i];
|
|
200
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(line) || line.length < 8) continue;
|
|
201
|
+
try {
|
|
202
|
+
const decoded = Buffer.from(line, 'base64').toString('utf8').trim();
|
|
203
|
+
if (looksLikePath(decoded)) return normalizePickedPath(decoded);
|
|
204
|
+
} catch { /* 非法 base64:继续找下一行 */ }
|
|
205
|
+
}
|
|
206
|
+
return '';
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** VBS 后端:路径写在临时文件里(FSO 以 UTF-16LE 写入,可能带 BOM) */
|
|
210
|
+
function readPickedFile(file) {
|
|
211
|
+
try {
|
|
212
|
+
if (!fs.existsSync(file)) return '';
|
|
213
|
+
let text = fs.readFileSync(file, 'utf16le');
|
|
214
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
|
|
215
|
+
const trimmed = text.trim();
|
|
216
|
+
return looksLikePath(trimmed) ? normalizePickedPath(trimmed) : '';
|
|
217
|
+
} catch {
|
|
218
|
+
return '';
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 构造各平台的目录选择执行计划(按顺序尝试)
|
|
224
|
+
* 每个条目:{ backend, kind, command, args?, expectShown, prepare? }
|
|
225
|
+
* - expectShown:该后端会在弹窗前输出 SHOWN_MARKER,可据此判定「窗口没出现」
|
|
226
|
+
* - prepare() 用于需要落临时文件的后端,返回 { args, decode, cleanup, meta } 或 null(准备失败)
|
|
11
227
|
* @param {string} title - 选择框提示文案
|
|
12
228
|
* @param {string} [platform] - 平台标识(默认 process.platform,测试可注入)
|
|
13
|
-
* @
|
|
229
|
+
* @param {object} [options] - { env, tmpDir }
|
|
230
|
+
* @returns {Array<object>}
|
|
14
231
|
*/
|
|
15
|
-
export function
|
|
16
|
-
|
|
17
|
-
const
|
|
232
|
+
export function buildPickPlan(title, platform = process.platform, options = {}) {
|
|
233
|
+
const env = options.env || process.env;
|
|
234
|
+
const tmpDir = options.tmpDir || resolveTmpDir(platform, env);
|
|
235
|
+
const safeTitle = sanitizeTitle(title);
|
|
18
236
|
|
|
19
237
|
if (platform === 'darwin') {
|
|
20
|
-
return {
|
|
238
|
+
return [{
|
|
239
|
+
backend: 'osascript',
|
|
240
|
+
kind: 'posix',
|
|
241
|
+
expectShown: false,
|
|
21
242
|
command: 'osascript',
|
|
22
243
|
args: ['-e', `POSIX path of (choose folder with prompt "${safeTitle}")`],
|
|
23
|
-
|
|
244
|
+
decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
|
|
245
|
+
}];
|
|
24
246
|
}
|
|
25
247
|
|
|
26
248
|
if (platform === 'win32') {
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
249
|
+
const psExe = resolveWindowsExe('powershell', env);
|
|
250
|
+
const cscriptExe = resolveWindowsExe('cscript', env);
|
|
251
|
+
const psScript = buildPowerShellScript(title);
|
|
252
|
+
const psCommon = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-STA'];
|
|
253
|
+
|
|
254
|
+
return [
|
|
255
|
+
{
|
|
256
|
+
// 后端 1:内联 -Command。脚本刻意不含双引号,避免 Node 参数转义与 PowerShell 解析冲突;
|
|
257
|
+
// 同时不经过 -EncodedCommand,绕开 ASR「可疑混淆脚本」规则的拦截。
|
|
258
|
+
backend: 'powershell-inline',
|
|
259
|
+
kind: 'powershell',
|
|
260
|
+
expectShown: true,
|
|
261
|
+
command: psExe,
|
|
262
|
+
args: [...psCommon, '-Command', psScript],
|
|
263
|
+
decode: (r) => decodePowerShellOutput(r.stdout),
|
|
264
|
+
},
|
|
265
|
+
{
|
|
266
|
+
// 后端 2:-EncodedCommand(base64 UTF-16LE),兼容极端转义场景,但可能被安全策略拦
|
|
267
|
+
backend: 'powershell-encoded',
|
|
268
|
+
kind: 'powershell',
|
|
269
|
+
expectShown: true,
|
|
270
|
+
command: psExe,
|
|
271
|
+
args: [...psCommon, '-EncodedCommand', Buffer.from(psScript, 'utf16le').toString('base64')],
|
|
272
|
+
decode: (r) => decodePowerShellOutput(r.stdout),
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
// 后端 3:cscript + WSH。完全独立的执行通道,用来覆盖 PowerShell 通道整体不可用的情况
|
|
276
|
+
backend: 'cscript-vbs',
|
|
277
|
+
kind: 'vbs',
|
|
278
|
+
expectShown: true,
|
|
279
|
+
command: cscriptExe,
|
|
280
|
+
prepare() {
|
|
281
|
+
try {
|
|
282
|
+
const dir = fs.mkdtempSync(path.join(tmpDir, 'ai-helper-pick-'));
|
|
283
|
+
const scriptFile = path.join(dir, 'pick.vbs');
|
|
284
|
+
const outputFile = path.join(dir, 'picked.txt');
|
|
285
|
+
fs.writeFileSync(scriptFile, buildVbsScript(outputFile), 'utf8');
|
|
286
|
+
return {
|
|
287
|
+
args: ['//nologo', '//B', scriptFile],
|
|
288
|
+
decode: () => readPickedFile(outputFile),
|
|
289
|
+
cleanup() {
|
|
290
|
+
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* 目录已被清理 */ }
|
|
291
|
+
},
|
|
292
|
+
meta: { scriptFile, outputFile },
|
|
293
|
+
};
|
|
294
|
+
} catch {
|
|
295
|
+
// 临时目录不可写(只读环境/权限受限):跳过该后端,不影响其它后端
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
},
|
|
300
|
+
];
|
|
41
301
|
}
|
|
42
302
|
|
|
43
303
|
// Linux / 其他:zenity 优先,kdialog 回退
|
|
44
|
-
return
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
304
|
+
return [
|
|
305
|
+
{
|
|
306
|
+
backend: 'zenity',
|
|
307
|
+
kind: 'posix',
|
|
308
|
+
expectShown: false,
|
|
309
|
+
command: 'zenity',
|
|
310
|
+
args: ['--file-selection', '--directory', `--title=${safeTitle}`],
|
|
311
|
+
decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
backend: 'kdialog',
|
|
315
|
+
kind: 'posix',
|
|
316
|
+
expectShown: false,
|
|
48
317
|
command: 'kdialog',
|
|
49
318
|
args: ['--getexistingdirectory', '~', '--title', safeTitle],
|
|
319
|
+
decode: (r) => (looksLikePath(r.stdout) ? normalizePickedPath(r.stdout) : ''),
|
|
50
320
|
},
|
|
51
|
-
|
|
321
|
+
];
|
|
52
322
|
}
|
|
53
323
|
|
|
54
|
-
/**
|
|
55
|
-
function
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
324
|
+
/** 兼容旧调用:返回首选后端 */
|
|
325
|
+
export function buildPickCommand(title, platform = process.platform, options = {}) {
|
|
326
|
+
return buildPickPlan(title, platform, options)[0];
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** 子进程退出语义 → 统一结果:严格区分「用户取消」与「失败原因」,失败时携带诊断信息 */
|
|
330
|
+
function classifyPickResult(runResult, item) {
|
|
331
|
+
const picked = item.decode ? item.decode(runResult) : '';
|
|
332
|
+
if (picked) return { success: true, path: picked, available: true };
|
|
333
|
+
|
|
334
|
+
const code = runResult.code;
|
|
335
|
+
const errText = String(runResult.stderr || '').trim();
|
|
336
|
+
|
|
337
|
+
if (item.kind === 'powershell' || item.kind === 'vbs') {
|
|
338
|
+
// 退出码是我们自己脚本约定的:2=取消;0=对话框正常关闭但没选
|
|
339
|
+
if (code === 2 || code === 0) return { success: true, path: null, available: true };
|
|
340
|
+
return {
|
|
341
|
+
success: false,
|
|
342
|
+
path: null,
|
|
343
|
+
available: true,
|
|
344
|
+
exitCode: code ?? null,
|
|
345
|
+
error: `exit ${code === null || code === undefined ? 'unknown' : code}${errText ? `: ${errText}` : '(无 stderr)'}`,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
// POSIX:无 stderr 的非零退出、或 stderr 明确是取消 → 视为用户取消
|
|
350
|
+
if (!errText) return { success: true, path: null, available: true };
|
|
351
|
+
if (/cancel|取消|-128/i.test(errText)) return { success: true, path: null, available: true };
|
|
352
|
+
return { success: false, path: null, available: true, exitCode: code ?? null, error: errText };
|
|
59
353
|
}
|
|
60
354
|
|
|
61
355
|
/**
|
|
62
|
-
* 运行单个选择命令,收集 stdout
|
|
356
|
+
* 运行单个选择命令,收集 stdout/stderr
|
|
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}>}
|
|
63
361
|
*/
|
|
64
|
-
function runPickOnce(command, args,
|
|
362
|
+
function runPickOnce(command, args, opts, spawnImpl) {
|
|
363
|
+
const timeoutMs = opts.timeoutMs;
|
|
364
|
+
const shownTimeoutMs = opts.expectShown ? opts.shownTimeoutMs : 0;
|
|
65
365
|
return new Promise((resolve) => {
|
|
66
366
|
let child;
|
|
67
367
|
try {
|
|
@@ -71,64 +371,243 @@ function runPickOnce(command, args, timeoutMs, spawnImpl) {
|
|
|
71
371
|
return;
|
|
72
372
|
}
|
|
73
373
|
let stdout = '';
|
|
374
|
+
let stderr = '';
|
|
74
375
|
let timedOut = false;
|
|
376
|
+
let shown = !shownTimeoutMs;
|
|
75
377
|
let settled = false;
|
|
378
|
+
let timer = null;
|
|
379
|
+
let shownTimer = null;
|
|
380
|
+
// 强杀时预期的结论(noWindow/超时):被杀进程通常会立刻触发 close,
|
|
381
|
+
// close 分支必须把这层结论合并进去,否则「窗口没出现」会被误当成普通退出
|
|
382
|
+
let pendingExtra = null;
|
|
76
383
|
const finish = (result) => {
|
|
77
384
|
if (settled) return;
|
|
78
385
|
settled = true;
|
|
79
|
-
clearTimeout(timer);
|
|
386
|
+
if (timer) clearTimeout(timer);
|
|
387
|
+
if (shownTimer) clearTimeout(shownTimer);
|
|
80
388
|
resolve(result);
|
|
81
389
|
};
|
|
82
|
-
|
|
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
|
+
};
|
|
396
|
+
timer = setTimeout(() => {
|
|
83
397
|
timedOut = true;
|
|
84
|
-
|
|
398
|
+
killAndSettle({ timedOut: true, shown });
|
|
85
399
|
}, timeoutMs);
|
|
86
|
-
|
|
87
|
-
|
|
400
|
+
if (shownTimeoutMs) {
|
|
401
|
+
// 窗口迟迟不出现:立刻杀掉换下一个后端,而不是干等满 120s
|
|
402
|
+
shownTimer = setTimeout(() => {
|
|
403
|
+
if (shown) return;
|
|
404
|
+
killAndSettle({ noWindow: true, shown: false });
|
|
405
|
+
}, shownTimeoutMs);
|
|
406
|
+
}
|
|
407
|
+
// 管道自身的 error(EPIPE/ECONNRESET,进程被杀或管道先行关闭时可能出现)必须监听:
|
|
408
|
+
// EventEmitter 的 'error' 事件若无监听者会被抛成 uncaughtException
|
|
409
|
+
child.stdout?.on?.('error', () => {});
|
|
410
|
+
child.stderr?.on?.('error', () => {});
|
|
411
|
+
child.stdout?.on?.('data', (chunk) => {
|
|
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
|
+
}
|
|
417
|
+
});
|
|
418
|
+
child.stderr?.on?.('data', (chunk) => {
|
|
419
|
+
if (stderr.length < MAX_STREAM_CHARS) stderr += chunk.toString();
|
|
420
|
+
});
|
|
88
421
|
// spawn 失败(命令不存在等)以异步 error 事件呈现
|
|
89
422
|
child.on?.('error', (err) => finish({ spawnError: true, stderr: String(err?.message || err) }));
|
|
90
|
-
child.on?.('close', (code) => finish({ code, stdout, stderr
|
|
423
|
+
child.on?.('close', (code) => finish({ code, stdout, stderr, timedOut, shown, ...(pendingExtra || {}) }));
|
|
91
424
|
});
|
|
92
425
|
}
|
|
93
426
|
|
|
427
|
+
/** 把各后端失败原因压缩成一行摘要,供 toast 与日志使用 */
|
|
428
|
+
function summarizeAttempts(attempts) {
|
|
429
|
+
const text = attempts
|
|
430
|
+
.filter((a) => a && a.error)
|
|
431
|
+
.map((a) => `${a.backend}: ${a.error}`)
|
|
432
|
+
.join(' | ');
|
|
433
|
+
return text.length > MAX_ERROR_CHARS ? `${text.slice(0, MAX_ERROR_CHARS)}…` : text;
|
|
434
|
+
}
|
|
435
|
+
|
|
94
436
|
/**
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
* @param {object} [options] - spawnImpl(测试注入)/ timeoutMs / platform(测试注入)/ hasDisplay(测试注入,Linux 无图形会话判定)
|
|
98
|
-
* @returns {Promise<{success: boolean, path: string|null, available: boolean, error?: string}>}
|
|
99
|
-
* - 选中:{ success: true, path, available: true }
|
|
100
|
-
* - 用户取消:{ success: true, path: null, available: true }
|
|
101
|
-
* - 环境不支持(命令不存在/无图形会话):{ success: false, path: null, available: false }
|
|
102
|
-
* - 超时等其他错误:{ success: false, path: null, available: true, error }
|
|
437
|
+
* 环境快照:失败时随结果返回,便于在没有 Windows 测试机的情况下定位
|
|
438
|
+
* (stdoutIsTTY 是判断「父终端是 mintty 还是 conhost」的关键信号)
|
|
103
439
|
*/
|
|
104
|
-
|
|
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
|
+
|
|
453
|
+
/** 进行中的选择:同一时刻只允许一个窗口,避免连点拉起多个弹窗把 agent 拖住 */
|
|
454
|
+
let inFlight = null;
|
|
455
|
+
|
|
456
|
+
async function doPickDirectory(title, options) {
|
|
457
|
+
const platform = options.platform ?? process.platform;
|
|
458
|
+
const env = options.env || process.env;
|
|
105
459
|
const spawnImpl = options.spawnImpl || spawn;
|
|
106
460
|
const timeoutMs = options.timeoutMs ?? PICK_TIMEOUT_MS;
|
|
107
|
-
const
|
|
108
|
-
const
|
|
461
|
+
const shownTimeoutMs = options.shownTimeoutMs ?? SHOWN_TIMEOUT_MS;
|
|
462
|
+
const totalBudgetMs = options.totalBudgetMs ?? PICK_TOTAL_BUDGET_MS;
|
|
463
|
+
const startedAt = Date.now();
|
|
109
464
|
|
|
110
465
|
// 无图形会话的 Linux 直接降级(zenity/kdialog 起不来,只会白白报错)
|
|
111
|
-
if (platform === 'linux'
|
|
112
|
-
|
|
466
|
+
if (platform === 'linux') {
|
|
467
|
+
const hasDisplay = options.hasDisplay ?? Boolean(readEnvVar(env, 'DISPLAY') || readEnvVar(env, 'WAYLAND_DISPLAY'));
|
|
468
|
+
if (!hasDisplay) {
|
|
469
|
+
return { success: false, path: null, available: false, error: 'no-display', attempts: [] };
|
|
470
|
+
}
|
|
113
471
|
}
|
|
114
472
|
|
|
115
|
-
const plan =
|
|
116
|
-
const
|
|
473
|
+
const plan = buildPickPlan(title, platform, { env, tmpDir: options.tmpDir });
|
|
474
|
+
const environment = buildEnvironmentSnapshot(platform, env, plan);
|
|
475
|
+
|
|
476
|
+
const attempts = [];
|
|
477
|
+
let lastTimeout = null;
|
|
478
|
+
|
|
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
|
+
}
|
|
117
487
|
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
488
|
+
let prepared = null;
|
|
489
|
+
try {
|
|
490
|
+
prepared = item.prepare
|
|
491
|
+
? item.prepare()
|
|
492
|
+
: { args: item.args, decode: item.decode, cleanup: null, meta: null };
|
|
493
|
+
} catch (err) {
|
|
494
|
+
attempts.push({ backend: item.backend, error: `prepare-failed: ${err?.message || err}` });
|
|
495
|
+
continue;
|
|
123
496
|
}
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
497
|
+
if (!prepared) {
|
|
498
|
+
attempts.push({ backend: item.backend, error: 'prepare-failed: 临时文件不可写' });
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
try {
|
|
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
|
+
|
|
510
|
+
if (r.spawnError) {
|
|
511
|
+
// 该命令不可用(未安装/路径不对/无法执行),记录原因后尝试下一个后端
|
|
512
|
+
attempts.push({ backend: item.backend, error: `spawn-failed: ${String(r.stderr || '').slice(0, 160)}` });
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (r.noWindow) {
|
|
516
|
+
// 进程活着但窗口始终没出现(加载程序集失败/会话无桌面等):换下一个后端,不在这里干等
|
|
517
|
+
attempts.push({ backend: item.backend, error: `no-window-in-${shownTimeoutMs}ms` });
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (r.timedOut) {
|
|
521
|
+
// 能走到这里说明窗口已经进入显示流程,是用户没在时限内选完
|
|
522
|
+
lastTimeout = {
|
|
523
|
+
backend: item.backend,
|
|
524
|
+
detail: String(r.stderr || '').trim().slice(0, 160),
|
|
525
|
+
};
|
|
526
|
+
attempts.push({ backend: item.backend, error: 'timeout: 窗口已显示但未在时限内返回' });
|
|
527
|
+
// 窗口已经出现,继续拉第二个窗口会让人困惑,直接结束
|
|
528
|
+
break;
|
|
529
|
+
}
|
|
530
|
+
const result = classifyPickResult(r, { kind: item.kind, decode: prepared.decode });
|
|
531
|
+
if (result.success) {
|
|
532
|
+
return { ...result, backend: item.backend, attempts };
|
|
533
|
+
}
|
|
534
|
+
attempts.push({ backend: item.backend, exitCode: r.code ?? null, error: result.error });
|
|
535
|
+
} catch (err) {
|
|
536
|
+
// 单个后端内的任何意外都不能中断整体流程,更不能冒泡到 HTTP 层
|
|
537
|
+
attempts.push({ backend: item.backend, error: `unexpected: ${err?.message || err}` });
|
|
538
|
+
} finally {
|
|
539
|
+
try { prepared.cleanup?.(); } catch { /* 清理失败不影响结果 */ }
|
|
127
540
|
}
|
|
128
|
-
// 空输出(无论退出码):用户取消选择
|
|
129
|
-
return { success: true, path: null, available: true };
|
|
130
541
|
}
|
|
131
542
|
|
|
132
|
-
|
|
133
|
-
|
|
543
|
+
const summary = summarizeAttempts(attempts);
|
|
544
|
+
if (lastTimeout) {
|
|
545
|
+
return {
|
|
546
|
+
success: false,
|
|
547
|
+
path: null,
|
|
548
|
+
available: true,
|
|
549
|
+
error: 'timeout',
|
|
550
|
+
backend: lastTimeout.backend,
|
|
551
|
+
detail: lastTimeout.detail || '',
|
|
552
|
+
attempts,
|
|
553
|
+
diagnostics: summary,
|
|
554
|
+
environment,
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
// 全部后端都没能弹出窗口:区分「根本没有可用工具」与「工具在但执行失败」
|
|
558
|
+
const noTool = plan.length > 0 && attempts.length === plan.length
|
|
559
|
+
&& attempts.every((a) => String(a.error || '').startsWith('spawn-failed'));
|
|
560
|
+
return {
|
|
561
|
+
success: false,
|
|
562
|
+
path: null,
|
|
563
|
+
available: false,
|
|
564
|
+
error: noTool ? `no-dialog-tool: ${summary}` : `all-backends-failed: ${summary}`,
|
|
565
|
+
attempts,
|
|
566
|
+
diagnostics: summary,
|
|
567
|
+
environment,
|
|
568
|
+
};
|
|
134
569
|
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* 弹出系统原生目录选择框
|
|
573
|
+
* @param {string} [title] - 选择框提示文案
|
|
574
|
+
* @param {object} [options] - spawnImpl / timeoutMs / shownTimeoutMs / totalBudgetMs / platform /
|
|
575
|
+
* env / tmpDir / hasDisplay(均可注入,便于测试)
|
|
576
|
+
* @returns {Promise<{success: boolean, path: string|null, available: boolean, backend?: string,
|
|
577
|
+
* error?: string, attempts?: Array<object>, diagnostics?: string, environment?: object}>}
|
|
578
|
+
* - 选中:{ success: true, path, available: true, backend }
|
|
579
|
+
* - 用户取消:{ success: true, path: null, available: true }
|
|
580
|
+
* - 环境不支持:{ success: false, path: null, available: false, error: 'no-dialog-tool: …' | 'no-display' }
|
|
581
|
+
* - 后端都失败:{ success: false, path: null, available: false, error: 'all-backends-failed: …', attempts }
|
|
582
|
+
* - 超时:{ success: false, path: null, available: true, error: 'timeout', attempts }
|
|
583
|
+
* - 已有窗口在等待:{ success: false, path: null, available: true, error: 'busy' }
|
|
584
|
+
* 本函数永不 reject。
|
|
585
|
+
*/
|
|
586
|
+
export async function pickDirectoryNative(title = '', options = {}) {
|
|
587
|
+
if (inFlight) {
|
|
588
|
+
return { success: false, path: null, available: true, error: 'busy', attempts: [] };
|
|
589
|
+
}
|
|
590
|
+
inFlight = doPickDirectory(title, options || {});
|
|
591
|
+
try {
|
|
592
|
+
return await inFlight;
|
|
593
|
+
} catch (err) {
|
|
594
|
+
// 极限兜底:任何漏网异常都转成结果对象,绝不让 HTTP 层 500 或进程崩溃
|
|
595
|
+
return {
|
|
596
|
+
success: false,
|
|
597
|
+
path: null,
|
|
598
|
+
available: true,
|
|
599
|
+
error: `internal: ${err?.message || err}`,
|
|
600
|
+
attempts: [],
|
|
601
|
+
};
|
|
602
|
+
} finally {
|
|
603
|
+
inFlight = null;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/** 测试用:查询是否有选择框正在等待 */
|
|
608
|
+
export function isPickInFlight() {
|
|
609
|
+
return Boolean(inFlight);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** 测试用:窗口标记常量 */
|
|
613
|
+
export const SHOWN_MARKER_FOR_TEST = SHOWN_MARKER;
|