ai-helper-agent 2.7.8 → 2.7.10

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.
@@ -0,0 +1,321 @@
1
+ // 目录浏览(工作目录选择用):只读、只列目录,不做路径沙箱校验。
2
+ // 与 /api/fs/list 的职责分开:后者面向文件面板(返回文件与 stat),受 workdir / allowedPaths 约束;
3
+ // 而「切换工作目录」必须能浏览沙箱之外的目录,且只需要目录名。
4
+ // 本模块不 spawn 任何子进程,因此不受 Windows 终端类型 / 桌面会话影响。
5
+
6
+ import fs from 'fs';
7
+ import { readdir, stat } from 'fs/promises';
8
+ import os from 'os';
9
+ import path from 'path';
10
+
11
+ export const MAX_BROWSE_ENTRIES = 5000;
12
+ export const BROWSE_TIMEOUT_MS = 5000;
13
+ export const MAX_BROWSE_PATH_LENGTH = 4096;
14
+ // 符号链接解析并发上限:避免大量链接(pnpm 等)逐个串行等待,
15
+ // 同时避免一次性打开过多文件句柄。
16
+ export const LINK_STAT_CONCURRENCY = 16;
17
+ // 根节点(盘符)探测缓存:Windows 每次 existsSync 都可能命中不可达的映射驱动器,
18
+ // 深层导航不需要重复探测,短 TTL 内复用结果。
19
+ export const ROOTS_CACHE_TTL_MS = 10_000;
20
+
21
+ // 机器码 + 本地化 message key + HTTP 状态码;由 server.js 统一转换成响应
22
+ export class BrowseError extends Error {
23
+ constructor(code, messageKey, httpStatus, detail = '') {
24
+ super(detail || code);
25
+ this.name = 'BrowseError';
26
+ this.code = code;
27
+ this.messageKey = messageKey;
28
+ this.httpStatus = httpStatus;
29
+ }
30
+ }
31
+
32
+ function pathApiFor(platform) {
33
+ return platform === 'win32' ? path.win32 : path.posix;
34
+ }
35
+
36
+ function joinFor(platform, base, name) {
37
+ return pathApiFor(platform).join(base, name);
38
+ }
39
+
40
+ function withTimeout(promise, timeoutMs) {
41
+ if (!timeoutMs || timeoutMs <= 0) return promise;
42
+ return new Promise((resolve, reject) => {
43
+ const timer = setTimeout(() => {
44
+ reject(new BrowseError('timeout', 'error.browseTimeout', 504));
45
+ }, timeoutMs);
46
+ promise.then(
47
+ (value) => { clearTimeout(timer); resolve(value); },
48
+ (err) => { clearTimeout(timer); reject(err); }
49
+ );
50
+ });
51
+ }
52
+
53
+ function mapFsError(err) {
54
+ if (err instanceof BrowseError) return err;
55
+ const code = err && err.code;
56
+ if (code === 'ENOENT') return new BrowseError('path_not_found', 'error.dirNotFound', 404);
57
+ if (code === 'ENOTDIR') return new BrowseError('not_a_directory', 'error.pathNotDir', 400);
58
+ if (code === 'EACCES' || code === 'EPERM') return new BrowseError('permission_denied', 'error.browsePermissionDenied', 403);
59
+ if (code === 'ENAMETOOLONG') return new BrowseError('path_too_long', 'error.browsePathTooLong', 400);
60
+ return new BrowseError('browse_failed', 'error.browseFailed', 500, err && err.message ? err.message : '');
61
+ }
62
+
63
+ /**
64
+ * 规范化浏览路径。
65
+ * - 空值返回 null(表示请求根节点集合)
66
+ * - 支持 ~ 前缀展开(仅前缀,不做 shell 展开)
67
+ * - 必须是绝对路径;统一分隔符;去掉根之外的尾部斜杠
68
+ */
69
+ export function normalizeBrowsePath(rawPath, options = {}) {
70
+ const platform = options.platform || process.platform;
71
+ const homeDir = options.homeDir || os.homedir();
72
+ if (rawPath === undefined || rawPath === null) return null;
73
+
74
+ let raw = String(rawPath);
75
+ if (!raw.trim()) return null;
76
+ raw = raw.trim();
77
+ // 用户从资源管理器复制时可能带引号
78
+ if ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'"))) {
79
+ raw = raw.slice(1, -1).trim();
80
+ }
81
+ if (!raw) return null;
82
+ if (raw.includes('\0')) throw new BrowseError('bad_path', 'error.browseBadPath', 400);
83
+ if (raw.length > MAX_BROWSE_PATH_LENGTH) throw new BrowseError('path_too_long', 'error.browsePathTooLong', 400);
84
+
85
+ if (raw === '~') {
86
+ raw = homeDir;
87
+ } else if (raw.startsWith('~/') || raw.startsWith('~\\')) {
88
+ raw = pathApiFor(platform).join(homeDir, raw.slice(2));
89
+ }
90
+
91
+ const P = pathApiFor(platform);
92
+
93
+ // Windows 下 /c/Users 这类 MSYS 风格路径会被 resolve 成当前盘下的 \Users,属于静默错误,直接拒绝
94
+ if (platform === 'win32' && /^\/[A-Za-z](\/|$)/.test(raw)) {
95
+ throw new BrowseError('bad_path', 'error.browseBadPath', 400);
96
+ }
97
+
98
+ if (!P.isAbsolute(raw)) {
99
+ throw new BrowseError('bad_path', 'error.browseBadPath', 400);
100
+ }
101
+
102
+ let resolved = P.resolve(raw);
103
+ if (resolved.length > MAX_BROWSE_PATH_LENGTH) {
104
+ throw new BrowseError('path_too_long', 'error.browsePathTooLong', 400);
105
+ }
106
+
107
+ const root = P.parse(resolved).root;
108
+ if (resolved !== root) {
109
+ while (resolved.length > root.length && /[\\/]$/.test(resolved)) {
110
+ resolved = resolved.slice(0, -1);
111
+ }
112
+ }
113
+ return resolved;
114
+ }
115
+
116
+ /**
117
+ * 根节点集合:Windows 为可用盘符 + 主目录,POSIX 为 / + 主目录。
118
+ * existsImpl 可注入,便于在非 Windows 环境测试盘符逻辑。
119
+ */
120
+ export function listRoots(options = {}) {
121
+ const platform = options.platform || process.platform;
122
+ const homeDir = options.homeDir || os.homedir();
123
+ const existsImpl = options.existsImpl || fs.existsSync;
124
+ const roots = [];
125
+
126
+ if (platform === 'win32') {
127
+ for (let i = 0; i < 26; i += 1) {
128
+ const letter = String.fromCharCode(65 + i);
129
+ const rootPath = `${letter}:\\`;
130
+ let ok = false;
131
+ try { ok = Boolean(existsImpl(rootPath)); } catch { ok = false; }
132
+ if (ok) roots.push({ name: `${letter}:`, path: rootPath, kind: 'drive' });
133
+ }
134
+ } else {
135
+ roots.push({ name: '/', path: '/', kind: 'root' });
136
+ }
137
+
138
+ if (homeDir && !roots.some((item) => item.path === homeDir)) {
139
+ roots.push({ name: '~', path: homeDir, kind: 'home' });
140
+ }
141
+ return roots;
142
+ }
143
+
144
+ /**
145
+ * 列出单层子目录(不递归)。只返回目录;符号链接解析后必须是目录才返回。
146
+ */
147
+ export async function listChildDirs(absPath, options = {}) {
148
+ const platform = options.platform || process.platform;
149
+ const timeoutMs = options.timeoutMs === undefined ? BROWSE_TIMEOUT_MS : options.timeoutMs;
150
+ const maxEntries = options.maxEntries === undefined ? MAX_BROWSE_ENTRIES : options.maxEntries;
151
+
152
+ let dirents;
153
+ try {
154
+ dirents = await withTimeout(readdir(absPath, { withFileTypes: true }), timeoutMs);
155
+ } catch (err) {
156
+ throw mapFsError(err);
157
+ }
158
+
159
+ const dirs = [];
160
+ const links = [];
161
+ for (const dirent of dirents) {
162
+ const name = dirent.name;
163
+ if (!name) continue;
164
+ if (dirent.isDirectory()) {
165
+ dirs.push({ name, path: joinFor(platform, absPath, name), kind: 'dir', link: false });
166
+ continue;
167
+ }
168
+ if (dirent.isSymbolicLink()) links.push({ name, fullPath: joinFor(platform, absPath, name) });
169
+ }
170
+
171
+ // 链接/目录联接:解析目标后仍必须是目录;断链或无权访问则跳过。
172
+ // 有界并发 + 整层总预算:单个链接超时按「剩余预算」递减,避免大量链接
173
+ // 把单次列目录拖成 N × timeoutMs(前端 8s 已经超时,服务端却还在跑)。
174
+ if (links.length) {
175
+ const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : 0;
176
+ let cursor = 0;
177
+ const worker = async () => {
178
+ for (;;) {
179
+ const index = cursor;
180
+ cursor += 1;
181
+ if (index >= links.length) return;
182
+ const remaining = deadline ? deadline - Date.now() : 0;
183
+ if (deadline && remaining <= 0) return;
184
+ const item = links[index];
185
+ try {
186
+ const target = await withTimeout(stat(item.fullPath), remaining || timeoutMs);
187
+ if (target.isDirectory()) {
188
+ dirs.push({ name: item.name, path: item.fullPath, kind: 'dir', link: true });
189
+ }
190
+ } catch {
191
+ // 断链 / 目标不可读 / 超时:不返回
192
+ }
193
+ }
194
+ };
195
+ const workers = Array.from(
196
+ { length: Math.min(LINK_STAT_CONCURRENCY, links.length) },
197
+ () => worker(),
198
+ );
199
+ await Promise.all(workers);
200
+ }
201
+
202
+ // 名称升序,大小写不敏感;完全相同时按原名兜底,保证稳定
203
+ dirs.sort((a, b) => {
204
+ const byLower = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
205
+ return byLower !== 0 ? byLower : a.name.localeCompare(b.name);
206
+ });
207
+
208
+ const truncated = dirs.length > maxEntries;
209
+ return {
210
+ entries: truncated ? dirs.slice(0, maxEntries) : dirs,
211
+ truncated,
212
+ };
213
+ }
214
+
215
+ export function parentOf(absPath, platform = process.platform) {
216
+ const P = pathApiFor(platform);
217
+ const parent = P.dirname(absPath);
218
+ return parent === absPath ? null : parent;
219
+ }
220
+
221
+ let rootsCache = null; // { key, at, roots }
222
+
223
+ /** 清空根节点缓存(测试用;盘符变化在 TTL 内自动过期) */
224
+ export function resetRootsCache() {
225
+ rootsCache = null;
226
+ }
227
+
228
+ /**
229
+ * 带 TTL 的根节点探测:每次浏览请求都同步探测 Windows 盘符代价很高,
230
+ * 深层导航复用短时间内的结果;显式注入 existsImpl 时不缓存(测试/特殊场景)。
231
+ */
232
+ function cachedRoots(options = {}) {
233
+ const platform = options.platform || process.platform;
234
+ const homeDir = options.homeDir || os.homedir();
235
+ if (options.existsImpl) {
236
+ return listRoots({ platform, homeDir, existsImpl: options.existsImpl });
237
+ }
238
+ const key = `${platform}|${homeDir}`;
239
+ const now = Date.now();
240
+ if (rootsCache && rootsCache.key === key && now - rootsCache.at < ROOTS_CACHE_TTL_MS) {
241
+ return rootsCache.roots;
242
+ }
243
+ const roots = listRoots({ platform, homeDir });
244
+ rootsCache = { key, at: now, roots };
245
+ return roots;
246
+ }
247
+
248
+ /**
249
+ * 组装 /api/fs/browse 的响应体。
250
+ * rawPath 为空时返回根节点集合(entries 为空)。
251
+ */
252
+ export async function buildBrowsePayload(options = {}) {
253
+ const platform = options.platform || process.platform;
254
+ const homeDir = options.homeDir || os.homedir();
255
+ const roots = cachedRoots({ platform, homeDir, existsImpl: options.existsImpl });
256
+
257
+ const rawPath = options.rawPath;
258
+ const normalized = normalizeBrowsePath(rawPath, { platform, homeDir });
259
+ if (!normalized) {
260
+ return {
261
+ success: true,
262
+ path: null,
263
+ parent: null,
264
+ platform,
265
+ entries: [],
266
+ roots,
267
+ truncated: false,
268
+ };
269
+ }
270
+
271
+ const { entries, truncated } = await listChildDirs(normalized, {
272
+ platform,
273
+ timeoutMs: options.timeoutMs,
274
+ maxEntries: options.maxEntries,
275
+ });
276
+
277
+ return {
278
+ success: true,
279
+ path: normalized,
280
+ parent: parentOf(normalized, platform),
281
+ platform,
282
+ entries,
283
+ roots,
284
+ truncated,
285
+ };
286
+ }
287
+
288
+ /**
289
+ * 简单滑动窗口频控:每 key 在 windowMs 内最多 limit 次。
290
+ * 正常点击速率远低于阈值;这里主要用于防止被刷成目录枚举器。
291
+ */
292
+ export function createBrowseRateLimiter(options = {}) {
293
+ const limit = options.limit === undefined ? 30 : options.limit;
294
+ const windowMs = options.windowMs === undefined ? 10000 : options.windowMs;
295
+ const now = options.now || (() => Date.now());
296
+ const buckets = new Map();
297
+
298
+ return {
299
+ consume(key) {
300
+ const bucketKey = String(key || 'anonymous');
301
+ const ts = now();
302
+ const recent = (buckets.get(bucketKey) || []).filter((t) => ts - t < windowMs);
303
+ if (recent.length >= limit) {
304
+ const retryAfterMs = Math.max(0, windowMs - (ts - recent[0]));
305
+ buckets.set(bucketKey, recent);
306
+ return { allowed: false, retryAfterMs };
307
+ }
308
+ recent.push(ts);
309
+ buckets.set(bucketKey, recent);
310
+ if (buckets.size > 10000) {
311
+ for (const [k, list] of buckets) {
312
+ if (!list.length || ts - list[list.length - 1] >= windowMs) buckets.delete(k);
313
+ }
314
+ }
315
+ return { allowed: true, retryAfterMs: 0 };
316
+ },
317
+ reset() {
318
+ buckets.clear();
319
+ },
320
+ };
321
+ }
@@ -354,6 +354,18 @@ function classifyPickResult(runResult, item) {
354
354
  error: `decode-failed: ${residue.slice(0, 160)}`,
355
355
  };
356
356
  }
357
+ // 退出码说「取消」,但全程没观测到窗口标记:窗口根本没画出来,
358
+ // 用户没有机会点任何按钮。这种情况必须报 no-window 而不是「用户取消」,
359
+ // 否则表现为「点击后毫无反应」——本模块最典型的静默失败。
360
+ if (item.expectShown && !runResult.shown) {
361
+ return {
362
+ success: false,
363
+ path: null,
364
+ available: true,
365
+ exitCode: code ?? null,
366
+ error: 'no-window',
367
+ };
368
+ }
357
369
  return { success: true, path: null, available: true };
358
370
  }
359
371
  return {
@@ -412,6 +424,13 @@ function runPickOnce(command, args, opts, spawnImpl) {
412
424
  try { child.kill(); } catch { /* 进程可能已退出 */ }
413
425
  setTimeout(() => finish({ code: null, stdout, stderr, ...extra }), KILL_SETTLE_MS);
414
426
  };
427
+ // 把「结束当前子进程」的能力交给调用方:显式取消 / 客户端断开时用它,
428
+ // 否则旧窗口会一直占着 inFlight,后续请求全部只能是 busy
429
+ if (typeof opts.onSpawn === 'function') {
430
+ try {
431
+ opts.onSpawn({ child, kill: killAndSettle });
432
+ } catch { /* 注册失败不影响正常流程 */ }
433
+ }
415
434
  timer = setTimeout(() => {
416
435
  timedOut = true;
417
436
  killAndSettle({ timedOut: true, shown });
@@ -471,8 +490,11 @@ function buildEnvironmentSnapshot(platform, env, plan) {
471
490
 
472
491
  /** 进行中的选择:同一时刻只允许一个窗口,避免连点拉起多个弹窗把 agent 拖住 */
473
492
  let inFlight = null;
493
+ /** inFlight 的开始时间与「取消句柄」:busy 时回传已等待时长,并允许显式取消 */
494
+ let inFlightStartedAt = 0;
495
+ let currentRun = null;
474
496
 
475
- async function doPickDirectory(title, options) {
497
+ async function doPickDirectory(title, options, controls = {}) {
476
498
  const platform = options.platform ?? process.platform;
477
499
  const env = options.env || process.env;
478
500
  const spawnImpl = options.spawnImpl || spawn;
@@ -494,8 +516,14 @@ async function doPickDirectory(title, options) {
494
516
 
495
517
  const attempts = [];
496
518
  let lastTimeout = null;
519
+ // 取消后的统一结论:显式取消 / 连接断开都走这里,客户端据此区分「不是用户取消」
520
+ const cancelledResult = () => ({
521
+ success: false, path: null, available: true, error: 'cancelled', cancelled: true, attempts,
522
+ });
497
523
 
498
524
  for (const item of plan) {
525
+ // 取消请求可能发生在后端切换之间:一旦收到就不再拉起新窗口
526
+ if (controls.cancelled) return cancelledResult();
499
527
  // 总预算控制:串行三后端最坏情况下也不能无限拖长
500
528
  const elapsed = Date.now() - startedAt;
501
529
  const remaining = totalBudgetMs - elapsed;
@@ -524,6 +552,12 @@ async function doPickDirectory(title, options) {
524
552
  shownTimeoutMs: Math.min(shownTimeoutMs, remaining),
525
553
  timeoutMs: Math.min(timeoutMs, remaining),
526
554
  expectShown: Boolean(item.expectShown),
555
+ // 记录当前子进程的终止句柄,供 cancelPickDirectory / 连接断开时强杀
556
+ onSpawn: (handle) => {
557
+ controls.killCurrent = handle.kill;
558
+ // 极端时序:取消请求早于 spawn 完成时,立刻收尾而不是让窗口弹出来
559
+ if (controls.cancelled) handle.kill({ cancelled: true });
560
+ },
527
561
  }, spawnImpl);
528
562
 
529
563
  if (r.spawnError) {
@@ -531,6 +565,10 @@ async function doPickDirectory(title, options) {
531
565
  attempts.push({ backend: item.backend, error: `spawn-failed: ${String(r.stderr || '').slice(0, 160)}` });
532
566
  continue;
533
567
  }
568
+ if (r.cancelled) {
569
+ attempts.push({ backend: item.backend, error: 'cancelled: 已取消(不只是用户取消选择)' });
570
+ return cancelledResult();
571
+ }
534
572
  if (r.noWindow) {
535
573
  // 进程活着但窗口始终没出现(加载程序集失败/会话无桌面等):换下一个后端,不在这里干等
536
574
  attempts.push({ backend: item.backend, error: `no-window-in-${shownTimeoutMs}ms` });
@@ -546,7 +584,17 @@ async function doPickDirectory(title, options) {
546
584
  // 窗口已经出现,继续拉第二个窗口会让人困惑,直接结束
547
585
  break;
548
586
  }
549
- const result = classifyPickResult(r, { kind: item.kind, decode: prepared.decode });
587
+ const result = classifyPickResult(r, {
588
+ kind: item.kind,
589
+ decode: prepared.decode,
590
+ expectShown: Boolean(item.expectShown),
591
+ });
592
+ if (!result.success && result.error === 'no-window') {
593
+ // 进程按「取消」退出,但窗口标记从未出现:用户根本没看到窗口。
594
+ // 不能当作用户取消收场,换下一个后端继续尝试
595
+ attempts.push({ backend: item.backend, exitCode: r.code ?? null, error: 'no-window: 窗口未出现即退出' });
596
+ continue;
597
+ }
550
598
  if (result.success) {
551
599
  return { ...result, backend: item.backend, attempts };
552
600
  }
@@ -555,6 +603,7 @@ async function doPickDirectory(title, options) {
555
603
  // 单个后端内的任何意外都不能中断整体流程,更不能冒泡到 HTTP 层
556
604
  attempts.push({ backend: item.backend, error: `unexpected: ${err?.message || err}` });
557
605
  } finally {
606
+ controls.killCurrent = null;
558
607
  try { prepared.cleanup?.(); } catch { /* 清理失败不影响结果 */ }
559
608
  }
560
609
  }
@@ -600,14 +649,38 @@ async function doPickDirectory(title, options) {
600
649
  * - 环境不支持:{ success: false, path: null, available: false, error: 'no-dialog-tool: …' | 'no-display' }
601
650
  * - 后端都失败:{ success: false, path: null, available: false, error: 'all-backends-failed: …', attempts }
602
651
  * - 超时:{ success: false, path: null, available: true, error: 'timeout', attempts }
603
- * - 已有窗口在等待:{ success: false, path: null, available: true, error: 'busy' }
652
+ * - 被取消(显式 cancel / 客户端断开):{ success: false, path: null, available: true, error: 'cancelled' }
653
+ * - 已有窗口在等待:{ success: false, path: null, available: true, error: 'busy',
654
+ * cancellable: true, elapsedMs }(可调 cancelPickDirectory() 取消旧窗口后重试)
604
655
  * 本函数永不 reject。
605
656
  */
606
657
  export async function pickDirectoryNative(title = '', options = {}) {
607
658
  if (inFlight) {
608
- return { success: false, path: null, available: true, error: 'busy', attempts: [] };
659
+ // busy 必须是「可取消」的:旧窗口最长可挂 180s,期间所有点击都会落到这里。
660
+ // 回传 cancellable + elapsedMs,让客户端能显式取消并重试,而不是死等或反复点
661
+ return {
662
+ success: false,
663
+ path: null,
664
+ available: true,
665
+ error: 'busy',
666
+ cancellable: true,
667
+ elapsedMs: Math.max(0, Date.now() - (inFlightStartedAt || Date.now())),
668
+ attempts: [],
669
+ };
609
670
  }
610
- inFlight = doPickDirectory(title, options || {});
671
+ const controls = { cancelled: false, killCurrent: null };
672
+ inFlightStartedAt = Date.now();
673
+ inFlight = doPickDirectory(title, options || {}, controls);
674
+ // 取消句柄挂在当前运行上:killCurrent 在每次 spawn 后更新,取消时强杀
675
+ currentRun = {
676
+ promise: inFlight,
677
+ cancel() {
678
+ controls.cancelled = true;
679
+ if (typeof controls.killCurrent === 'function') {
680
+ try { controls.killCurrent({ cancelled: true }); } catch { /* 进程可能已退出 */ }
681
+ }
682
+ },
683
+ };
611
684
  try {
612
685
  return await inFlight;
613
686
  } catch (err) {
@@ -621,9 +694,30 @@ export async function pickDirectoryNative(title = '', options = {}) {
621
694
  };
622
695
  } finally {
623
696
  inFlight = null;
697
+ inFlightStartedAt = 0;
698
+ currentRun = null;
624
699
  }
625
700
  }
626
701
 
702
+ /**
703
+ * 取消正在等待的目录选择框(显式取消 / 客户端断开时调用)
704
+ * 会强杀当前子进程并等待本次 pick 收尾,保证取消返回后 inFlight 已释放,
705
+ * 客户端可以立刻重试而不是继续拿到 busy。
706
+ * 本函数永不 reject。
707
+ * @returns {Promise<{success: boolean, cancelled: boolean, error?: string}>}
708
+ */
709
+ export async function cancelPickDirectory() {
710
+ const run = currentRun;
711
+ if (!run) return { success: false, cancelled: false, error: 'not-running' };
712
+ try {
713
+ run.cancel();
714
+ } catch { /* 取消本身不应抛异常 */ }
715
+ try {
716
+ await run.promise;
717
+ } catch { /* 结果由原请求方处理 */ }
718
+ return { success: true, cancelled: true };
719
+ }
720
+
627
721
  /** 测试用:查询是否有选择框正在等待 */
628
722
  export function isPickInFlight() {
629
723
  return Boolean(inFlight);
@@ -20,6 +20,11 @@
20
20
  "dirNotFound": "Directory does not exist",
21
21
  "pathIsDir": "Path is a directory",
22
22
  "pathNotDir": "Path is not a directory",
23
+ "browseBadPath": "Invalid directory path; use an absolute native path on the Agent host",
24
+ "browsePathTooLong": "Directory path is too long",
25
+ "browsePermissionDenied": "Access denied to this directory (insufficient Agent process permissions)",
26
+ "browseTimeout": "Timed out while reading the directory",
27
+ "browseFailed": "Failed to read the directory",
23
28
  "fileOrDirNotFound": "File/directory does not exist",
24
29
  "dirExists": "Directory already exists",
25
30
  "missingPathOrNewName": "Missing path or newName parameter",
@@ -20,6 +20,11 @@
20
20
  "dirNotFound": "目录不存在",
21
21
  "pathIsDir": "路径是目录",
22
22
  "pathNotDir": "路径不是目录",
23
+ "browseBadPath": "目录路径无效,请使用 Agent 主机的原生绝对路径",
24
+ "browsePathTooLong": "目录路径过长",
25
+ "browsePermissionDenied": "无权访问该目录(当前 Agent 进程权限不足)",
26
+ "browseTimeout": "读取目录超时",
27
+ "browseFailed": "读取目录失败",
23
28
  "fileOrDirNotFound": "文件/目录不存在",
24
29
  "dirExists": "目录已存在",
25
30
  "missingPathOrNewName": "缺少 path 或 newName 参数",
package/src/server.js CHANGED
@@ -62,9 +62,13 @@ import { setSkillExecutorLang } from './skill/executor.js';
62
62
  import { setMarkdownLoaderLang } from './skill/markdown-loader.js';
63
63
  import { setMcpClientLang } from './mcp/client.js';
64
64
  import { getRequestI18n, t, parseAcceptLanguage } from './i18n.js';
65
- import { pickDirectoryNative } from './directory-picker.js';
65
+ import { pickDirectoryNative, cancelPickDirectory } from './directory-picker.js';
66
+ import { buildBrowsePayload, BrowseError, createBrowseRateLimiter } from './dir-browse.js';
66
67
  import { extractImagesHandler } from './documents/routes.js';
67
68
 
69
+ // 目录浏览频控:按配对扩展(extId)限速,防止被刷成目录枚举器
70
+ const browseRateLimiter = createBrowseRateLimiter();
71
+
68
72
  // Server-level i18n helper (uses env/CLI language)
69
73
  const serverLang = parseAcceptLanguage();
70
74
  const ln = (key, params) => t(serverLang, `server.${key}`, params);
@@ -1218,6 +1222,22 @@ export function startServer() {
1218
1222
  }
1219
1223
  }
1220
1224
 
1225
+ // === 取消正在等待的系统原生目录选择框 ===
1226
+ // 弹窗最长可挂 180s:期间关闭侧边栏/断开的请求若不清理,旧窗口会一直占着 inFlight,
1227
+ // 后续点击全部只能拿到 busy(观感就是「点了没反应」)。显式取消让 busy 变成可恢复状态。
1228
+ // 与 pick-directory 保持同一来源门控:远端无法打开本机弹窗,也不应能取消本机用户的弹窗。
1229
+ if (pathname === '/api/config/pick-directory/cancel' && req.method === 'POST') {
1230
+ const remoteIp = req.socket.remoteAddress || '';
1231
+ const isLocal = remoteIp === '127.0.0.1' || remoteIp === '::1' || remoteIp === '::ffff:127.0.0.1' || remoteIp === 'localhost';
1232
+ if (!isLocal) {
1233
+ logSecurity('pick_directory_cancel_remote_blocked', { remote: remoteIp, extId });
1234
+ return jsonResponse(res, 200, { success: false, cancelled: false, available: false, error: 'remote-source' });
1235
+ }
1236
+ const result = await cancelPickDirectory();
1237
+ if (result.success) logSystem('directory_pick_cancelled', { extId });
1238
+ return jsonResponse(res, 200, result);
1239
+ }
1240
+
1221
1241
  // === 弹出系统原生目录选择框(仅限本机来源) ===
1222
1242
  // 仅本机(loopback)代理有意义:远端机器可能无桌面环境,弹窗用户也看不到;
1223
1243
  // 且工作目录本就是代理端机器的路径,浏览器侧选择框语义上也不成立。
@@ -1231,7 +1251,10 @@ export function startServer() {
1231
1251
  }
1232
1252
  // 这是全服务里唯一可能耗时数分钟的端点(等用户选目录):客户端很可能在此期间
1233
1253
  // 关闭侧边栏/断开。向已销毁的 res 写入会触发流错误,因此统一走安全响应。
1254
+ let finished = false;
1234
1255
  const respond = (payload) => {
1256
+ if (finished) return;
1257
+ finished = true;
1235
1258
  if (res.writableEnded || res.destroyed) return;
1236
1259
  try {
1237
1260
  jsonResponse(res, 200, payload);
@@ -1239,14 +1262,23 @@ export function startServer() {
1239
1262
  try { logError('config', 'pick_directory_respond_failed', { error: err.message }); } catch { /* 日志失败不影响进程 */ }
1240
1263
  }
1241
1264
  };
1265
+ // 客户端断开(关闭侧边栏 / 刷新 / fetch abort):立刻强杀子进程并注意不要写已销毁的 res。
1266
+ // 否则旧窗口会一直占着 inFlight,后续点击只能拿到 busy,且用户桌面会残留一个无人管的弹窗
1267
+ res.on('close', () => {
1268
+ if (finished) return;
1269
+ finished = true;
1270
+ Promise.resolve(cancelPickDirectory()).catch(() => { /* 取消失败无需上报 */ });
1271
+ try { logSystem('directory_pick_aborted', { extId }); } catch { /* 日志失败不影响进程 */ }
1272
+ });
1242
1273
  try {
1243
1274
  const title = typeof body.title === 'string' ? body.title.slice(0, 120) : '';
1244
1275
  // pickDirectoryNative 内部已做多后端兜底、超时强杀与异常吸收,此处只会拿到结果对象
1245
1276
  const result = await pickDirectoryNative(title);
1246
1277
  if (result.success && result.path) {
1247
1278
  logSystem('directory_picked', { path: result.path, backend: result.backend || '', extId });
1248
- } else if (!result.success && result.error !== 'busy') {
1279
+ } else if (!result.success && result.error !== 'busy' && result.error !== 'cancelled') {
1249
1280
  // busy 是并发保护的正常分支(已有窗口在等),不算失败
1281
+ // cancelled 是客户端主动取消/断开,也不是失败
1250
1282
  // 其余记录各后端真实失败原因(无桌面会话 / 被安全策略拦截 / 超时等),
1251
1283
  // 用户端只看得到摘要,完整 attempts 落到日志里备查
1252
1284
  // environment 快照记录父进程环境特征(SystemRoot/pathStartsWithPosix/stdoutIsTTY):
@@ -1378,6 +1410,37 @@ export function startServer() {
1378
1410
  return jsonResponse(res, 200, { success: true, size: buf.length, path: check.resolved });
1379
1411
  }
1380
1412
 
1413
+ // 浏览目录(工作目录选择用):只读、只列目录,不受 checkPath 沙箱约束;
1414
+ // 供侧边栏内置目录浏览器使用,远端代理同样可用(不依赖系统原生弹窗)。
1415
+ if (pathname === '/api/fs/browse') {
1416
+ const verdict = browseRateLimiter.consume(extId);
1417
+ if (!verdict.allowed) {
1418
+ const wait = Math.max(1, Math.ceil(verdict.retryAfterMs / 1000));
1419
+ return jsonResponse(res, 429, {
1420
+ success: false,
1421
+ error: 'rate_limited',
1422
+ message: t('error.tooFrequent', { wait }),
1423
+ });
1424
+ }
1425
+ try {
1426
+ const result = await buildBrowsePayload({
1427
+ rawPath: typeof body.path === 'string' ? body.path : '',
1428
+ });
1429
+ logFs('browse', {
1430
+ path: result.path || '(roots)',
1431
+ entryCount: result.entries.length,
1432
+ truncated: result.truncated,
1433
+ });
1434
+ return jsonResponse(res, 200, result);
1435
+ } catch (err) {
1436
+ if (err instanceof BrowseError) {
1437
+ return jsonResponse(res, err.httpStatus, { success: false, error: err.code, message: t(err.messageKey) });
1438
+ }
1439
+ logError('fs', 'browse_failed', { error: err && err.message ? err.message : String(err) });
1440
+ return jsonResponse(res, 500, { success: false, error: t('error.browseFailed') });
1441
+ }
1442
+ }
1443
+
1381
1444
  // 列出目录
1382
1445
  if (pathname === '/api/fs/list') {
1383
1446
  const dirPath = body.path || '.';
@@ -1 +0,0 @@
1
- import{r as e}from"./chunk-CMxvf4Kt.js";import{a as t,c as n,l as r}from"./i18n-NkRsFRG_.js";import{b as i}from"./model-profiles-DH6uFSiB.js";import{b as a,jt as o}from"./session-store-BXelxKzG.js";var s=e({PICK_DIRECTORY_CLIENT_TIMEOUT_MS:()=>j,buildAgentHeaders:()=>x,createDir:()=>Y,deleteFs:()=>q,downloadFile:()=>L,downloadFileStream:()=>U,downloadFileStreamWithProgress:()=>W,downloadFiles:()=>R,downloadFilesStream:()=>G,downloadFilesStreamWithProgress:()=>K,formatFileSize:()=>u,formatTime:()=>d,getAgentConfig:()=>w,getAgentStatusDetail:()=>O,getFileIcon:()=>l,getFileInfo:()=>Z,getHomeDir:()=>E,getMimeType:()=>h,getPreviewType:()=>p,getWorkspaceRoot:()=>T,isImageFile:()=>m,listDirectory:()=>P,moveFs:()=>X,pickDirectory:()=>M,readFileContent:()=>F,removeAllowedPath:()=>A,renameFs:()=>J,resetWorkspaceRoot:()=>D,searchFilesRemote:()=>V,supportsPreview:()=>f,switchWorkspace:()=>k,writeFileContent:()=>I});t(`zh`,{workspaceMgr:{agentNotPairedDetail:`Agent 未配对,请先在设置中完成配对`,agentNotPaired:`Agent 未配对`,requestFailed:`请求失败: {message}`,downloadFailed:`下载失败`,cancelled:`已取消`}}),t(`en`,{workspaceMgr:{agentNotPairedDetail:`Agent not paired. Please complete pairing in Settings first.`,agentNotPaired:`Agent not paired`,requestFailed:`Request failed: {message}`,downloadFailed:`Download failed`,cancelled:`Cancelled`}});var c={txt:`📄`,md:`📝`,json:`📋`,js:`📜`,mjs:`📜`,ts:`📘`,jsx:`⚛️`,tsx:`⚛️`,html:`🌐`,htm:`🌐`,css:`🎨`,scss:`🎨`,less:`🎨`,xml:`📰`,yaml:`📰`,yml:`📰`,py:`🐍`,java:`☕`,c:`⚙️`,cpp:`⚙️`,h:`⚙️`,go:`🔹`,rs:`🦀`,rb:`💎`,php:`🐘`,sql:`🗄️`,sh:`💻`,bash:`💻`,zsh:`💻`,cfg:`⚙️`,ini:`⚙️`,toml:`⚙️`,conf:`⚙️`,log:`📊`,csv:`📊`,tsv:`📊`,env:`🔒`,vue:`💚`,svelte:`🧡`,astro:`🚀`,rtf:`📄`,svg:`🖼️`,png:`🖼️`,jpg:`🖼️`,jpeg:`🖼️`,gif:`🖼️`,webp:`🖼️`,bmp:`🖼️`,ico:`🖼️`,pdf:`📕`,doc:`📘`,docx:`📘`,xls:`📗`,xlsx:`📗`,ppt:`📙`,pptx:`📙`,zip:`📦`,gz:`📦`,tar:`📦`,rar:`📦`,"7z":`📦`,mp3:`🎵`,wav:`🎵`,mp4:`🎬`,webm:`🎬`,avi:`🎬`};function l(e,t){return t===`directory`?`📁`:c[(e.split(`.`).pop()||``).toLowerCase()]||`📄`}function u(e){if(e===0)return`0 B`;if(e==null)return`—`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=1024,r=Math.floor(Math.log(e)/Math.log(n));return`${(e/n**r).toFixed(r===0?0:1)} ${t[r]}`}function d(e){return e?new Date(e).toLocaleString(`zh-CN`,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):`—`}function f(e){let t=(e.split(`.`).pop()||``).toLowerCase();return new Set(`txt.md.json.js.mjs.ts.jsx.tsx.html.htm.css.scss.less.xml.yaml.yml.py.java.c.cpp.h.go.rs.rb.php.sql.sh.bash.zsh.cfg.ini.toml.conf.log.csv.tsv.env.vue.svelte.astro.rtf.svg.pdf.docx.pptx.xlsx.xls.png.jpg.jpeg.gif.webp.bmp.ico.mp4.webm.ogg.m4v.mov.mp3.wav.m4a.aac.flac.opus`.split(`.`)).has(t)}function p(e){let t=(e.split(`.`).pop()||``).toLowerCase();return t===`pdf`?`pdf`:t===`docx`?`docx`:t===`xlsx`||t===`xls`?`xlsx`:t===`pptx`?`pptx`:new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`]).has(t)?`image`:new Set([`mp4`,`webm`,`ogg`,`m4v`,`mov`]).has(t)?`video`:new Set([`mp3`,`wav`,`m4a`,`aac`,`flac`,`opus`]).has(t)?`audio`:`text`}function m(e){let t=(e.split(`.`).pop()||``).toLowerCase();return new Set([`png`,`jpg`,`jpeg`,`gif`,`webp`,`bmp`,`ico`,`svg`]).has(t)}function h(e){return{txt:`text/plain`,md:`text/markdown`,json:`application/json`,js:`application/javascript`,html:`text/html`,css:`text/css`,xml:`application/xml`,yaml:`text/yaml`,yml:`text/yaml`,csv:`text/csv`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`,pdf:`application/pdf`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,mp4:`video/mp4`,webm:`video/webm`,ogg:`video/ogg`,m4v:`video/x-m4v`,mov:`video/quicktime`,mp3:`audio/mpeg`,wav:`audio/wav`,m4a:`audio/mp4`,aac:`audio/aac`,flac:`audio/flac`,opus:`audio/ogg`}[(e.split(`.`).pop()||``).toLowerCase()]||`text/plain`}var g=null,_=null,v=null,y=null;function b(){try{return a?.activeSessionId||null}catch{return null}}function x(e,t=b()){let n={Authorization:`Bearer ${e.token}`};return t&&(n[`X-AIH-Session-Id`]=t),n}function S(e){if(e instanceof TypeError)return!0;let t=String(e&&e.message||``).toLowerCase();return t.includes(`failed to fetch`)||t.includes(`load failed`)||t.includes(`networkerror`)}function C(e,t){let n=t&&t.message;S(t)?r.debug(`[WorkspaceManager] ${e} skipped (agent unreachable):`,n):r.warn(`[WorkspaceManager] ${e} failed:`,n)}async function w(){if(y&&y.url&&y.token)return y;try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=e.pairedAgents||[],n=e.activeAgentId;if(!n||t.length===0)return null;let r=t.find(e=>e.id===n)||t[0];return r?(y={id:r.id,url:r.url,token:i(r.token)},y):null}catch(e){return r.warn(`[WorkspaceManager] getAgentconfiguration failed:`,e.message),null}}async function T(e){let t=e===void 0?b():e,n=await w(),r=`${t||``}::${n?.id||n?.url||``}`;if(g&&_===r)return g;if(!n)return null;try{let e=await fetch(`${n.url}/api/status/detail`,{headers:x(n,t)});if(e.ok){let t=await e.json();if(t.success&&t.workdir)return g=t.workdir,_=r,g}}catch(e){C(`get workingdirectory`,e)}return null}async function E(){if(v)return v;let e=await w();if(!e)return null;try{let t=await fetch(`${e.url}/api/status/detail`,{headers:{Authorization:`Bearer ${e.token}`}});if(t.ok){let e=await t.json();if(e.success&&e.homeDir)return v=e.homeDir,v}}catch(e){C(`get homedir`,e)}return null}function D(){g=null,_=null,v=null,y=null,o()}async function O(e){let t=e===void 0?b():e,n=await w();if(!n)return null;try{let e=await fetch(`${n.url}/api/status/detail`,{headers:x(n,t)});if(e.ok){let t=await e.json();if(t.success)return t}}catch(e){C(`get statusdetailcase`,e)}return null}async function k(e,t={}){let n=t.sessionId===void 0?b():t.sessionId,r={workdir:e,scope:n?`session`:`global`};n&&(r.sessionId=n);let i=await N(`/api/config/workdir`,r,n);return i.success&&D(),i}async function A(e){return N(`/api/config/allowed-paths/remove`,{path:e})}var j=200*1e3;async function M(){let e=await w();if(!e)return{success:!1,available:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let t=new AbortController,r=setTimeout(()=>t.abort(),j);try{let n=await fetch(`${e.url}/api/config/pick-directory`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.token}`},body:JSON.stringify({}),signal:t.signal});if(n.status===404)return{success:!1,path:null,available:!1,outdated:!0};let r=await n.json();return r&&typeof r==`object`?r:{success:!1,path:null,available:!0,error:`bad-response`}}catch(e){return e&&e.name===`AbortError`?{success:!1,path:null,available:!0,error:`client-timeout`}:{success:!1,path:null,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}finally{clearTimeout(r)}}async function N(e,t={},r=void 0){let i=await w();if(!i)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};let a=r===void 0?b():r;try{return await(await fetch(`${i.url}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,...x(i,a)},body:JSON.stringify(t)})).json()}catch(e){return{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function P(e){return N(`/api/fs/list`,{path:e||`.`})}async function F(e){return N(`/api/fs/read`,{path:e})}async function I(e,t){return N(`/api/fs/write`,{path:e,content:t})}async function L(e){return N(`/api/fs/download`,{path:e})}async function R(e){return N(`/api/fs/download-multi`,{paths:e})}function z(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function B(e){return e?!!(e.startsWith(`/`)||/^[a-zA-Z]:[\\/]/.test(e)||/^(\\\\|\/\/)[^\\/]+[\\/]/.test(e)):!1}async function V(e,t,n=200){let r=await N(`/api/fs/search_files`,{path:e,pattern:`*${t}*`,recursive:!0,maxResults:n});return r.success?(r.results||[]).map(t=>{let n=z(B(t.path)?t.path:`${e}/${t.path}`),r=n.substring(0,n.lastIndexOf(`/`));return{name:t.name,type:t.type||`file`,size:t.size,mtime:t.mtime,fullPath:n,matchPath:r}}):[]}function H(e,t){if(!e)return t;let n=e.match(/filename\*=UTF-8''(.+?)(?:;|$)/)||e.match(/filename="(.+?)"/);return n?decodeURIComponent(n[1]):t}async function U(e){let t=await w();if(!t)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};try{let r=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...x(t)},body:JSON.stringify({path:e})});return r.ok?{success:!0,blob:await r.blob(),name:H(r.headers.get(`Content-Disposition`),e.split(/[\\/]/).pop()),mimeType:r.headers.get(`Content-Type`)}:{success:!1,error:(await r.json().catch(()=>({error:r.statusText}))).error||n(`workspaceMgr.downloadFailed`)}}catch(e){return{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function W(e,t,r){let i=await w();if(!i)return{success:!1,error:n(`workspaceMgr.agentNotPaired`)};try{let a=await fetch(`${i.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...x(i)},body:JSON.stringify({path:e}),signal:r});if(!a.ok)return{success:!1,error:(await a.json().catch(()=>({error:a.statusText}))).error||n(`workspaceMgr.downloadFailed`)};let o=parseInt(a.headers.get(`Content-Length`)||`0`,10),s=a.body.getReader();r&&r.addEventListener(`abort`,()=>{try{s.cancel()}catch{}});let c=[],l=0;for(;;){let{done:e,value:n}=await s.read();if(e)break;c.push(n),l+=n.length,t&&o>0&&t({loaded:l,total:o,percent:Math.round(l/o*100)})}return{success:!0,blob:new Blob(c),name:H(a.headers.get(`Content-Disposition`),e.split(/[\\/]/).pop()),mimeType:a.headers.get(`Content-Type`)}}catch(e){return e.name===`AbortError`?{success:!1,error:n(`workspaceMgr.cancelled`),aborted:!0}:{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function G(e){let t=await w();if(!t)return{success:!1,error:n(`workspaceMgr.agentNotPairedDetail`)};try{let r=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...x(t)},body:JSON.stringify({paths:e})});return r.ok?{success:!0,blob:await r.blob(),name:H(r.headers.get(`Content-Disposition`),`workspace.zip`),mimeType:r.headers.get(`Content-Type`)}:{success:!1,error:(await r.json().catch(()=>({error:r.statusText}))).error||n(`workspaceMgr.downloadFailed`)}}catch(e){return{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function K(e,t,r){let i=await w();if(!i)return{success:!1,error:n(`workspaceMgr.agentNotPaired`)};try{let a=await fetch(`${i.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...x(i)},body:JSON.stringify({paths:e}),signal:r});if(!a.ok)return{success:!1,error:(await a.json().catch(()=>({error:a.statusText}))).error||n(`workspaceMgr.downloadFailed`)};let o=parseInt(a.headers.get(`Content-Length`)||`0`,10),s=a.body.getReader();r&&r.addEventListener(`abort`,()=>{try{s.cancel()}catch{}});let c=[],l=0;for(;;){let{done:e,value:n}=await s.read();if(e)break;c.push(n),l+=n.length,t&&o>0&&t({loaded:l,total:o,percent:Math.round(l/o*100)})}return{success:!0,blob:new Blob(c),name:H(a.headers.get(`Content-Disposition`),`workspace.zip`),mimeType:a.headers.get(`Content-Type`)}}catch(e){return e.name===`AbortError`?{success:!1,error:n(`workspaceMgr.cancelled`),aborted:!0}:{success:!1,error:n(`workspaceMgr.requestFailed`,{message:e.message})}}}async function q(e){return N(`/api/fs/delete`,{path:e})}async function J(e,t){return N(`/api/fs/rename`,{path:e,newName:t})}async function Y(e){return N(`/api/fs/mkdir`,{path:e})}async function X(e,t){return N(`/api/fs/move`,{path:e,destDir:t})}async function Z(e){return N(`/api/fs/stat`,{path:e})}export{D as C,s as D,k as E,I as O,J as S,f as T,P as _,G as a,F as b,d as c,l as d,Z as f,T as g,p as h,W as i,w as l,h as m,Y as n,K as o,E as p,U as r,u as s,x as t,O as u,X as v,V as w,A as x,M as y};