ai-helper-agent 2.7.9 → 2.8.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/dist/assets/{agent-store-CuK2pMqc.js → agent-store-DDZKtEZX.js} +1 -1
- package/dist/assets/background.js +71 -71
- package/dist/assets/{chat-export-BjO4Cgaj.js → chat-export-CvuuXVcS.js} +1 -1
- package/dist/assets/{markdown-render-BIVttniD.js → markdown-render-ljX8y3-8.js} +3 -3
- package/dist/assets/options.js +1 -1
- package/dist/assets/{session-store-XFFEUHgS.js → session-store-BWuBHdD6.js} +2 -2
- package/dist/assets/side_panel.css +1 -1
- package/dist/assets/side_panel.js +356 -341
- package/dist/assets/{utils-qEM6ytxe.js → utils-BMzWhLj7.js} +1 -1
- package/dist/assets/{version-CeLsZH0f.js → version-Bvlnn3Va.js} +1 -1
- package/dist/assets/workspace-manager-DqpRol8n.js +1 -0
- package/dist/manifest.json +1 -1
- package/dist/options.html +1 -1
- package/dist/side_panel.html +6 -6
- package/package.json +1 -1
- package/src/dir-browse.js +321 -0
- package/src/directory-picker.js +99 -5
- package/src/locales/en.json +10 -3
- package/src/locales/zh.json +10 -3
- package/src/server.js +201 -52
- package/src/version-compat.js +112 -0
- package/dist/assets/workspace-manager-C4IYPHx6.js +0 -1
package/src/directory-picker.js
CHANGED
|
@@ -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, {
|
|
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
|
-
* -
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
package/src/locales/en.json
CHANGED
|
@@ -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",
|
|
@@ -28,8 +33,10 @@
|
|
|
28
33
|
"missingPathsParam": "Missing paths parameter or empty array",
|
|
29
34
|
"missingPathOrPaths": "Missing path or paths parameter",
|
|
30
35
|
"processNotFound": "Process does not exist or has ended",
|
|
31
|
-
"
|
|
32
|
-
"
|
|
36
|
+
"updateFailed": "Update failed. Please retry later; if it keeps failing, update the extension first",
|
|
37
|
+
"updateTargetInvalid": "Invalid update target format (expected e.g. ~2.7.10). Please update the extension first",
|
|
38
|
+
"agentNewerThanPlugin": "Agent v{agent} is newer than the extension (extension compatible up to {target}). Downgrade blocked. Please update the extension first",
|
|
39
|
+
"noCompatibleVersion": "No agent version compatible with the current extension was found on npm (minor range {target}). Please update the extension first",
|
|
33
40
|
"bodyTooLarge": "Request body too large",
|
|
34
41
|
"invalidJson": "Request body is not valid JSON",
|
|
35
42
|
"readRequestFailed": "Failed to read request",
|
|
@@ -84,7 +91,6 @@
|
|
|
84
91
|
"urlImportFailed": "URL import failed: {message}",
|
|
85
92
|
"mcpCommandBlocked": "MCP command blocked: {reason}",
|
|
86
93
|
"readResourceFailed": "Failed to read resource: {message}",
|
|
87
|
-
"npmInstallExitCode": "npm install exit code: {code}",
|
|
88
94
|
"invalidConfigKey": "Invalid config key: {key}",
|
|
89
95
|
"stdoutTruncated": "stdout output exceeded 5MB limit, truncated",
|
|
90
96
|
"commandTimeout": "Command timed out",
|
|
@@ -138,6 +144,7 @@
|
|
|
138
144
|
"shuttingDown": "Agent is shutting down...",
|
|
139
145
|
"restarting": "Agent is restarting...",
|
|
140
146
|
"updateSuccess": "Update successful, Agent is restarting...",
|
|
147
|
+
"updateAlreadyLatest": "Already at the latest compatible version v{version}",
|
|
141
148
|
"workdirSwitched": "Working directory switched",
|
|
142
149
|
"workdirBoundToSession": "Bound to this session only (other sessions are unaffected)",
|
|
143
150
|
"workdirUnbound": "This session now follows the agent default directory",
|
package/src/locales/zh.json
CHANGED
|
@@ -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 参数",
|
|
@@ -28,8 +33,10 @@
|
|
|
28
33
|
"missingPathsParam": "缺少 paths 参数或为空数组",
|
|
29
34
|
"missingPathOrPaths": "缺少 path 或 paths 参数",
|
|
30
35
|
"processNotFound": "进程不存在或已结束",
|
|
31
|
-
"
|
|
32
|
-
"
|
|
36
|
+
"updateFailed": "更新失败,请稍后重试;若持续失败,请先更新插件端后再试",
|
|
37
|
+
"updateTargetInvalid": "更新目标版本格式无效(需形如 ~2.7.10),请先更新插件端后再试",
|
|
38
|
+
"agentNewerThanPlugin": "当前代理端 v{agent} 比插件端更新(插件端兼容至 {target}),已阻止降级。请先更新插件端,再更新代理端",
|
|
39
|
+
"noCompatibleVersion": "npm 上没有找到与当前插件兼容的代理版本({target} 同小版本范围)。请先更新插件端,再更新代理端",
|
|
33
40
|
"bodyTooLarge": "请求体过大",
|
|
34
41
|
"invalidJson": "请求体不是有效的 JSON",
|
|
35
42
|
"readRequestFailed": "读取请求失败",
|
|
@@ -84,7 +91,6 @@
|
|
|
84
91
|
"urlImportFailed": "URL 导入失败: {message}",
|
|
85
92
|
"mcpCommandBlocked": "MCP 命令被拦截: {reason}",
|
|
86
93
|
"readResourceFailed": "读取资源失败: {message}",
|
|
87
|
-
"npmInstallExitCode": "npm install 退出码: {code}",
|
|
88
94
|
"invalidConfigKey": "无效配置项: {key}",
|
|
89
95
|
"stdoutTruncated": "stdout 输出超过 5MB 上限,已截断",
|
|
90
96
|
"commandTimeout": "命令执行超时",
|
|
@@ -138,6 +144,7 @@
|
|
|
138
144
|
"shuttingDown": "Agent 正在关闭...",
|
|
139
145
|
"restarting": "Agent 正在重启...",
|
|
140
146
|
"updateSuccess": "更新成功,Agent 正在重启...",
|
|
147
|
+
"updateAlreadyLatest": "当前已是兼容范围内的最新版本 v{version}",
|
|
141
148
|
"workdirSwitched": "工作目录已切换",
|
|
142
149
|
"workdirBoundToSession": "已绑定到本会话(其他会话不受影响)",
|
|
143
150
|
"workdirUnbound": "本会话已恢复跟随代理默认目录",
|
package/src/server.js
CHANGED
|
@@ -29,6 +29,14 @@ import { getAsrConfig } from './asr/config.js';
|
|
|
29
29
|
import { warmupAsrEngines, closeOfflinePool } from './asr/offline-pool.js';
|
|
30
30
|
import { memoryRouter } from './memory/routes.js';
|
|
31
31
|
import { stopProcessTree } from './process-tree.js';
|
|
32
|
+
import {
|
|
33
|
+
parseTargetRange,
|
|
34
|
+
buildFallbackTarget,
|
|
35
|
+
compareVersions,
|
|
36
|
+
isMajorMinorAhead,
|
|
37
|
+
isUpdateAvailable,
|
|
38
|
+
parseNpmViewVersions
|
|
39
|
+
} from './version-compat.js';
|
|
32
40
|
import {
|
|
33
41
|
initializeMcpRegistry,
|
|
34
42
|
shutdownMcpRegistry,
|
|
@@ -62,9 +70,13 @@ import { setSkillExecutorLang } from './skill/executor.js';
|
|
|
62
70
|
import { setMarkdownLoaderLang } from './skill/markdown-loader.js';
|
|
63
71
|
import { setMcpClientLang } from './mcp/client.js';
|
|
64
72
|
import { getRequestI18n, t, parseAcceptLanguage } from './i18n.js';
|
|
65
|
-
import { pickDirectoryNative } from './directory-picker.js';
|
|
73
|
+
import { pickDirectoryNative, cancelPickDirectory } from './directory-picker.js';
|
|
74
|
+
import { buildBrowsePayload, BrowseError, createBrowseRateLimiter } from './dir-browse.js';
|
|
66
75
|
import { extractImagesHandler } from './documents/routes.js';
|
|
67
76
|
|
|
77
|
+
// 目录浏览频控:按配对扩展(extId)限速,防止被刷成目录枚举器
|
|
78
|
+
const browseRateLimiter = createBrowseRateLimiter();
|
|
79
|
+
|
|
68
80
|
// Server-level i18n helper (uses env/CLI language)
|
|
69
81
|
const serverLang = parseAcceptLanguage();
|
|
70
82
|
const ln = (key, params) => t(serverLang, `server.${key}`, params);
|
|
@@ -312,6 +324,45 @@ function parseBody(req) {
|
|
|
312
324
|
});
|
|
313
325
|
}
|
|
314
326
|
|
|
327
|
+
/**
|
|
328
|
+
* 执行 npm 命令并收集输出
|
|
329
|
+
* 非 Windows 下以独立进程组运行,超时整树终止,避免 SIGTERM 只杀 shell 留下孤儿 npm
|
|
330
|
+
* @param {string[]} args - npm 参数(纯静态或经严格校验,不含用户原始输入)
|
|
331
|
+
* @param {number} timeoutMs - 超时毫秒数
|
|
332
|
+
* @returns {Promise<{success: boolean, code?: number, error?: string, stdout: string, stderr: string}>}
|
|
333
|
+
*/
|
|
334
|
+
function runNpmCommand(args, timeoutMs) {
|
|
335
|
+
return new Promise((resolvePromise) => {
|
|
336
|
+
const isWin = process.platform === 'win32';
|
|
337
|
+
const npm = spawn(isWin ? 'npm.cmd' : 'npm', args, {
|
|
338
|
+
shell: isWin,
|
|
339
|
+
detached: !isWin,
|
|
340
|
+
env: { ...process.env },
|
|
341
|
+
windowsHide: true
|
|
342
|
+
});
|
|
343
|
+
const stdout = [];
|
|
344
|
+
const stderr = [];
|
|
345
|
+
npm.stdout.on('data', d => stdout.push(d.toString()));
|
|
346
|
+
npm.stderr.on('data', d => stderr.push(d.toString()));
|
|
347
|
+
|
|
348
|
+
let settled = false;
|
|
349
|
+
let timer = null;
|
|
350
|
+
const finish = (result) => {
|
|
351
|
+
if (settled) return;
|
|
352
|
+
settled = true;
|
|
353
|
+
if (timer) clearTimeout(timer);
|
|
354
|
+
resolvePromise(result);
|
|
355
|
+
};
|
|
356
|
+
npm.on('error', (err) => finish({ success: false, error: err.message, stdout: '', stderr: '' }));
|
|
357
|
+
timer = setTimeout(() => {
|
|
358
|
+
finish({ success: false, error: 'timeout', stdout: stdout.join(''), stderr: stderr.join('') });
|
|
359
|
+
stopProcessTree(npm, { graceMs: 5000 }).catch(() => {});
|
|
360
|
+
}, timeoutMs);
|
|
361
|
+
timer.unref();
|
|
362
|
+
npm.on('close', (code) => finish({ success: code === 0, code, stdout: stdout.join(''), stderr: stderr.join('') }));
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
315
366
|
/**
|
|
316
367
|
* 解析 multipart/form-data,提取文件数据
|
|
317
368
|
* @param {http.IncomingMessage} req
|
|
@@ -755,7 +806,33 @@ export function startServer() {
|
|
|
755
806
|
return;
|
|
756
807
|
}
|
|
757
808
|
|
|
809
|
+
// 检测当前插件兼容区间内是否有可升级的 Agent 版本(只读,不安装/不重启)
|
|
810
|
+
// 老版本 Agent 没有该路由会返回 404,插件端静默降级为不展示更新角标
|
|
811
|
+
if (req.method === 'GET' && pathname === '/api/agent/update/check') {
|
|
812
|
+
const rawTarget = (url.searchParams.get('target') || '').trim();
|
|
813
|
+
const range = parseTargetRange(rawTarget);
|
|
814
|
+
if (!range) {
|
|
815
|
+
return jsonResponse(res, 400, { success: false, error: t('error.updateTargetInvalid') });
|
|
816
|
+
}
|
|
817
|
+
const viewResult = await runNpmCommand(['view', `ai-helper-agent@${range.raw}`, 'version', '--json'], 15000);
|
|
818
|
+
const latest = viewResult.success ? parseNpmViewVersions(viewResult.stdout) : '';
|
|
819
|
+
if (!latest) {
|
|
820
|
+
logError('update_check_failed', (viewResult.stderr || viewResult.error || 'no matching version').slice(-300));
|
|
821
|
+
}
|
|
822
|
+
return jsonResponse(res, 200, {
|
|
823
|
+
success: true,
|
|
824
|
+
current: AGENT_VERSION,
|
|
825
|
+
target: range.version,
|
|
826
|
+
latest,
|
|
827
|
+
available: isUpdateAvailable(AGENT_VERSION, latest)
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
|
|
758
831
|
// 更新并重启 Agent(需认证)
|
|
832
|
+
// 只允许在插件下发的兼容区间内更新(target 形如 "~2.7.10"):
|
|
833
|
+
// 由 npm 解析到同一 major.minor 下的最高 patch,避免应用市场插件端滞后时
|
|
834
|
+
// 被更新到插件无法识别的新 minor/major 版本。
|
|
835
|
+
// 老插件不传 target 时回落为 "~当前代理版本",只做同小版本 patch 升级。
|
|
759
836
|
if (req.method === 'POST' && pathname === '/api/agent/update') {
|
|
760
837
|
if (agentOperationInProgress) {
|
|
761
838
|
return jsonResponse(res, 409, { success: false, error: t('error.operationInProgress') });
|
|
@@ -768,9 +845,39 @@ export function startServer() {
|
|
|
768
845
|
const wait = Math.ceil((OPERATION_COOLDOWN_MS - (Date.now() - lastOperationTime)) / 1000);
|
|
769
846
|
return jsonResponse(res, 429, { success: false, error: t('error.tooFrequent', { wait }) });
|
|
770
847
|
}
|
|
848
|
+
|
|
849
|
+
let body;
|
|
850
|
+
try { body = await parseBody(req); }
|
|
851
|
+
catch (err) { return jsonResponse(res, 400, { success: false, error: err.message }); }
|
|
852
|
+
|
|
853
|
+
// target 由插件按自身版本下发,仅接受 "~x.y.z":~ 区间把升级锁在同一 major.minor 内
|
|
854
|
+
const rawTarget = typeof body.target === 'string' ? body.target.trim() : '';
|
|
855
|
+
let target = rawTarget;
|
|
856
|
+
let range = parseTargetRange(rawTarget);
|
|
857
|
+
let legacyFallback = false;
|
|
858
|
+
if (!target) {
|
|
859
|
+
// 兼容未传 target 的老插件:锚定代理自身 major.minor,只做同小版本 patch 升级。
|
|
860
|
+
// 老插件无法表达兼容范围,用自身小版本最保守——不跨 minor、不降级,
|
|
861
|
+
// 也避免直接升 latest 把老插件带到它无法识别的 major 版本。
|
|
862
|
+
target = buildFallbackTarget(AGENT_VERSION);
|
|
863
|
+
range = parseTargetRange(target);
|
|
864
|
+
legacyFallback = true;
|
|
865
|
+
}
|
|
866
|
+
if (!range) {
|
|
867
|
+
return jsonResponse(res, 400, { success: false, error: t('error.updateTargetInvalid') });
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// 降级保护:已安装 Agent 的 major.minor 高于插件版本时,不允许用旧区间覆盖
|
|
871
|
+
if (isMajorMinorAhead(AGENT_VERSION, range.version)) {
|
|
872
|
+
return jsonResponse(res, 409, {
|
|
873
|
+
success: false,
|
|
874
|
+
error: t('error.agentNewerThanPlugin', { agent: AGENT_VERSION, target: range.version })
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
|
|
771
878
|
agentOperationInProgress = true;
|
|
772
879
|
lastOperationTime = Date.now();
|
|
773
|
-
logSystem('update', { reason: 'api_request', extId });
|
|
880
|
+
logSystem('update', { reason: 'api_request', extId, target, legacyFallback });
|
|
774
881
|
|
|
775
882
|
const agentScript = resolve(process.argv[1]);
|
|
776
883
|
const restartPort = config.port || 18910;
|
|
@@ -780,59 +887,42 @@ export function startServer() {
|
|
|
780
887
|
|
|
781
888
|
// 同步执行 npm 全局安装,完成后才返回结果(前端能收到真实成功/失败)
|
|
782
889
|
(async () => {
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
const
|
|
890
|
+
// 1) 先解析区间内的最高版本;区间无匹配时 view 失败,提示先升级插件
|
|
891
|
+
const viewResult = await runNpmCommand(['view', `ai-helper-agent@${target}`, 'version', '--json'], 20000);
|
|
892
|
+
const resolved = viewResult.success ? parseNpmViewVersions(viewResult.stdout) : '';
|
|
893
|
+
if (!resolved) {
|
|
894
|
+
agentOperationInProgress = false;
|
|
895
|
+
lastOperationTime = 0; // 解析失败属空操作,不占用冷却
|
|
896
|
+
logError('update_resolve_failed', (viewResult.stderr || viewResult.error || 'no matching version').slice(-500));
|
|
897
|
+
jsonResponse(res, 200, {
|
|
898
|
+
success: false,
|
|
899
|
+
error: t('error.noCompatibleVersion', { target: target.slice(1) })
|
|
900
|
+
});
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
786
903
|
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
windowsHide: true
|
|
799
|
-
});
|
|
800
|
-
npm.stdout.on('data', d => npmOutput.push(d.toString().trim()));
|
|
801
|
-
npm.stderr.on('data', d => npmOutput.push(d.toString().trim()));
|
|
802
|
-
|
|
803
|
-
let settled = false;
|
|
804
|
-
let timer = null;
|
|
805
|
-
const finish = (result) => {
|
|
806
|
-
if (settled) return;
|
|
807
|
-
settled = true;
|
|
808
|
-
if (timer) clearTimeout(timer);
|
|
809
|
-
resolvePromise(result);
|
|
810
|
-
};
|
|
811
|
-
npm.on('error', (err) => finish({ success: false, error: err.message }));
|
|
812
|
-
|
|
813
|
-
// 超时保护(90s),防止 npm 卡住导致前端长等待;终止整棵进程树防孤儿(R1)
|
|
814
|
-
timer = setTimeout(() => {
|
|
815
|
-
finish({ success: false, error: t('error.npmInstallTimeout') });
|
|
816
|
-
stopProcessTree(npm, { graceMs: 5000 }).catch(() => {});
|
|
817
|
-
}, 90000);
|
|
818
|
-
timer.unref();
|
|
819
|
-
|
|
820
|
-
npm.on('close', (code) => {
|
|
821
|
-
finish({ success: code === 0, code });
|
|
822
|
-
});
|
|
904
|
+
// 已是区间内最新(或已装版本更高):不重复安装与重启,避免同 minor 内降级
|
|
905
|
+
// 老插件不传 target 时保持原语义(安装并重启),否则它会把 upToDate 误当成“正在重启”
|
|
906
|
+
if (!legacyFallback && compareVersions(resolved, AGENT_VERSION) <= 0) {
|
|
907
|
+
agentOperationInProgress = false;
|
|
908
|
+
lastOperationTime = 0;
|
|
909
|
+
logSystem('update_skipped', { version: resolved, current: AGENT_VERSION });
|
|
910
|
+
jsonResponse(res, 200, {
|
|
911
|
+
success: true,
|
|
912
|
+
upToDate: true,
|
|
913
|
+
version: resolved,
|
|
914
|
+
message: t('message.updateAlreadyLatest', { version: resolved })
|
|
823
915
|
});
|
|
824
|
-
|
|
825
|
-
if (!npmSuccess) {
|
|
826
|
-
npmError = result.error || t('error.npmInstallExitCode', { code: result.code });
|
|
827
|
-
}
|
|
828
|
-
} catch (err) {
|
|
829
|
-
npmError = err.message;
|
|
916
|
+
return;
|
|
830
917
|
}
|
|
831
918
|
|
|
832
|
-
|
|
919
|
+
// 2) 安装解析出的精确版本,避免安装时再次解析到更新的版本
|
|
920
|
+
// 不指定 --registry,继承用户环境配置(公司内网/外网自适应)
|
|
921
|
+
const result = await runNpmCommand(['install', '-g', `ai-helper-agent@${resolved}`, '--no-audit', '--no-fund'], 90000);
|
|
922
|
+
if (!result.success) {
|
|
833
923
|
// 更新失败:不重启,保持老进程运行,提示用户手动执行
|
|
834
924
|
agentOperationInProgress = false; // 重置防重入标志,允许后续重试
|
|
835
|
-
logError('update_npm_failed',
|
|
925
|
+
logError('update_npm_failed', (result.error || result.stderr || '').slice(-500));
|
|
836
926
|
jsonResponse(res, 200, {
|
|
837
927
|
success: false,
|
|
838
928
|
error: t('error.updateFailed')
|
|
@@ -841,8 +931,8 @@ export function startServer() {
|
|
|
841
931
|
}
|
|
842
932
|
|
|
843
933
|
// 更新成功:返回响应并触发两阶段重启
|
|
844
|
-
logSystem('update_success', {
|
|
845
|
-
jsonResponse(res, 200, { success: true, message: t('message.updateSuccess') });
|
|
934
|
+
logSystem('update_success', { from: AGENT_VERSION, to: resolved });
|
|
935
|
+
jsonResponse(res, 200, { success: true, version: resolved, legacyFallback, message: t('message.updateSuccess') });
|
|
846
936
|
|
|
847
937
|
// spawn 两阶段重启包装器
|
|
848
938
|
const child = spawn(process.execPath, [
|
|
@@ -1218,6 +1308,22 @@ export function startServer() {
|
|
|
1218
1308
|
}
|
|
1219
1309
|
}
|
|
1220
1310
|
|
|
1311
|
+
// === 取消正在等待的系统原生目录选择框 ===
|
|
1312
|
+
// 弹窗最长可挂 180s:期间关闭侧边栏/断开的请求若不清理,旧窗口会一直占着 inFlight,
|
|
1313
|
+
// 后续点击全部只能拿到 busy(观感就是「点了没反应」)。显式取消让 busy 变成可恢复状态。
|
|
1314
|
+
// 与 pick-directory 保持同一来源门控:远端无法打开本机弹窗,也不应能取消本机用户的弹窗。
|
|
1315
|
+
if (pathname === '/api/config/pick-directory/cancel' && req.method === 'POST') {
|
|
1316
|
+
const remoteIp = req.socket.remoteAddress || '';
|
|
1317
|
+
const isLocal = remoteIp === '127.0.0.1' || remoteIp === '::1' || remoteIp === '::ffff:127.0.0.1' || remoteIp === 'localhost';
|
|
1318
|
+
if (!isLocal) {
|
|
1319
|
+
logSecurity('pick_directory_cancel_remote_blocked', { remote: remoteIp, extId });
|
|
1320
|
+
return jsonResponse(res, 200, { success: false, cancelled: false, available: false, error: 'remote-source' });
|
|
1321
|
+
}
|
|
1322
|
+
const result = await cancelPickDirectory();
|
|
1323
|
+
if (result.success) logSystem('directory_pick_cancelled', { extId });
|
|
1324
|
+
return jsonResponse(res, 200, result);
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1221
1327
|
// === 弹出系统原生目录选择框(仅限本机来源) ===
|
|
1222
1328
|
// 仅本机(loopback)代理有意义:远端机器可能无桌面环境,弹窗用户也看不到;
|
|
1223
1329
|
// 且工作目录本就是代理端机器的路径,浏览器侧选择框语义上也不成立。
|
|
@@ -1231,7 +1337,10 @@ export function startServer() {
|
|
|
1231
1337
|
}
|
|
1232
1338
|
// 这是全服务里唯一可能耗时数分钟的端点(等用户选目录):客户端很可能在此期间
|
|
1233
1339
|
// 关闭侧边栏/断开。向已销毁的 res 写入会触发流错误,因此统一走安全响应。
|
|
1340
|
+
let finished = false;
|
|
1234
1341
|
const respond = (payload) => {
|
|
1342
|
+
if (finished) return;
|
|
1343
|
+
finished = true;
|
|
1235
1344
|
if (res.writableEnded || res.destroyed) return;
|
|
1236
1345
|
try {
|
|
1237
1346
|
jsonResponse(res, 200, payload);
|
|
@@ -1239,14 +1348,23 @@ export function startServer() {
|
|
|
1239
1348
|
try { logError('config', 'pick_directory_respond_failed', { error: err.message }); } catch { /* 日志失败不影响进程 */ }
|
|
1240
1349
|
}
|
|
1241
1350
|
};
|
|
1351
|
+
// 客户端断开(关闭侧边栏 / 刷新 / fetch abort):立刻强杀子进程并注意不要写已销毁的 res。
|
|
1352
|
+
// 否则旧窗口会一直占着 inFlight,后续点击只能拿到 busy,且用户桌面会残留一个无人管的弹窗
|
|
1353
|
+
res.on('close', () => {
|
|
1354
|
+
if (finished) return;
|
|
1355
|
+
finished = true;
|
|
1356
|
+
Promise.resolve(cancelPickDirectory()).catch(() => { /* 取消失败无需上报 */ });
|
|
1357
|
+
try { logSystem('directory_pick_aborted', { extId }); } catch { /* 日志失败不影响进程 */ }
|
|
1358
|
+
});
|
|
1242
1359
|
try {
|
|
1243
1360
|
const title = typeof body.title === 'string' ? body.title.slice(0, 120) : '';
|
|
1244
1361
|
// pickDirectoryNative 内部已做多后端兜底、超时强杀与异常吸收,此处只会拿到结果对象
|
|
1245
1362
|
const result = await pickDirectoryNative(title);
|
|
1246
1363
|
if (result.success && result.path) {
|
|
1247
1364
|
logSystem('directory_picked', { path: result.path, backend: result.backend || '', extId });
|
|
1248
|
-
} else if (!result.success && result.error !== 'busy') {
|
|
1365
|
+
} else if (!result.success && result.error !== 'busy' && result.error !== 'cancelled') {
|
|
1249
1366
|
// busy 是并发保护的正常分支(已有窗口在等),不算失败
|
|
1367
|
+
// cancelled 是客户端主动取消/断开,也不是失败
|
|
1250
1368
|
// 其余记录各后端真实失败原因(无桌面会话 / 被安全策略拦截 / 超时等),
|
|
1251
1369
|
// 用户端只看得到摘要,完整 attempts 落到日志里备查
|
|
1252
1370
|
// environment 快照记录父进程环境特征(SystemRoot/pathStartsWithPosix/stdoutIsTTY):
|
|
@@ -1378,6 +1496,37 @@ export function startServer() {
|
|
|
1378
1496
|
return jsonResponse(res, 200, { success: true, size: buf.length, path: check.resolved });
|
|
1379
1497
|
}
|
|
1380
1498
|
|
|
1499
|
+
// 浏览目录(工作目录选择用):只读、只列目录,不受 checkPath 沙箱约束;
|
|
1500
|
+
// 供侧边栏内置目录浏览器使用,远端代理同样可用(不依赖系统原生弹窗)。
|
|
1501
|
+
if (pathname === '/api/fs/browse') {
|
|
1502
|
+
const verdict = browseRateLimiter.consume(extId);
|
|
1503
|
+
if (!verdict.allowed) {
|
|
1504
|
+
const wait = Math.max(1, Math.ceil(verdict.retryAfterMs / 1000));
|
|
1505
|
+
return jsonResponse(res, 429, {
|
|
1506
|
+
success: false,
|
|
1507
|
+
error: 'rate_limited',
|
|
1508
|
+
message: t('error.tooFrequent', { wait }),
|
|
1509
|
+
});
|
|
1510
|
+
}
|
|
1511
|
+
try {
|
|
1512
|
+
const result = await buildBrowsePayload({
|
|
1513
|
+
rawPath: typeof body.path === 'string' ? body.path : '',
|
|
1514
|
+
});
|
|
1515
|
+
logFs('browse', {
|
|
1516
|
+
path: result.path || '(roots)',
|
|
1517
|
+
entryCount: result.entries.length,
|
|
1518
|
+
truncated: result.truncated,
|
|
1519
|
+
});
|
|
1520
|
+
return jsonResponse(res, 200, result);
|
|
1521
|
+
} catch (err) {
|
|
1522
|
+
if (err instanceof BrowseError) {
|
|
1523
|
+
return jsonResponse(res, err.httpStatus, { success: false, error: err.code, message: t(err.messageKey) });
|
|
1524
|
+
}
|
|
1525
|
+
logError('fs', 'browse_failed', { error: err && err.message ? err.message : String(err) });
|
|
1526
|
+
return jsonResponse(res, 500, { success: false, error: t('error.browseFailed') });
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1381
1530
|
// 列出目录
|
|
1382
1531
|
if (pathname === '/api/fs/list') {
|
|
1383
1532
|
const dirPath = body.path || '.';
|