zcode-pro 1.9.0 → 1.10.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/inject.js +109 -15
- package/package.json +2 -2
- package/src/host/helper.mjs +341 -39
- package/src/host/taskIndex.mjs +114 -18
- package/src/inject/core.js +4 -0
- package/src/inject/features/idle-reclaim.js +31 -5
- package/src/inject/features/settings-dialog.js +6 -4
- package/src/inject/features/subagent-icon.js +113 -19
- package/src/inject/locales/ja.js +2 -0
- package/src/inject/locales/ko.js +2 -0
- package/src/inject/locales/ru.js +2 -0
package/src/host/helper.mjs
CHANGED
|
@@ -11,7 +11,7 @@ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'no
|
|
|
11
11
|
import { homedir, tmpdir, userInfo } from 'node:os';
|
|
12
12
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
13
13
|
import { readSettings, remapSettingsPathsAtomic, isProjectOpenInTabs } from './settings.mjs';
|
|
14
|
-
import { taskIndexPath, probeTaskIndexWritable, remapTaskIndexPaths, taskIndexDriverAvailable, listOverriddenTitles, listTaskWorkspaceMap, listTaskStatuses, listSessionsActivity, listSessionsTrace, listSessionModelUsage, listSessionTurnUsage, listSubagentChildrenActivity, listProjectsUnread, listWorkspaceTaskIds, setTaskTitleIfNotOverridden, setCustomSessionTitle, isTaskTitleOverridden, reconcileCustomTitles, getTaskProviderModel, listVirtualProjects, countTasks, readRecentQa } from './taskIndex.mjs';
|
|
14
|
+
import { taskIndexPath, probeTaskIndexWritable, remapTaskIndexPaths, taskIndexDriverAvailable, listOverriddenTitles, listTaskWorkspaceMap, listTaskStatuses, listSessionsActivity, listSessionsTrace, listSessionModelUsage, listSessionTurnUsage, listSubagentChildrenActivity, listSessionAncestors, listWorkspaceSubagentActivity, listProjectsUnread, listWorkspaceTaskIds, setTaskTitleIfNotOverridden, setCustomSessionTitle, isTaskTitleOverridden, reconcileCustomTitles, getTaskProviderModel, listVirtualProjects, countTasks, readRecentQa } from './taskIndex.mjs';
|
|
15
15
|
import { pickFolderSystem } from './pickFolder.mjs';
|
|
16
16
|
import { reorderTasks } from './taskOrder.mjs';
|
|
17
17
|
import { webdavRequest, webdavPutWithMkcol, webdavHttpText, parseWebdavListing, findCurl } from './webdav.mjs';
|
|
@@ -333,10 +333,16 @@ export function defaultConfig() {
|
|
|
333
333
|
},
|
|
334
334
|
// 空闲项目内存回收的判定时长(分钟,1–1440):项目无运行中会话、无后台命令
|
|
335
335
|
// 且非当前选中,持续满该时长后释放其会话进程
|
|
336
|
-
idleReclaimMinutes:
|
|
336
|
+
idleReclaimMinutes: 10,
|
|
337
|
+
// 旧版的默认 30 会随任意一次保存写进文件:用这个标记区分“旧默认落盘”和
|
|
338
|
+
// 用户显式设置的 30。首次读到没有标记的 30 时迁移到新默认 10
|
|
339
|
+
idleReclaimMinutesMigrated: true,
|
|
337
340
|
// 启动一次性回收的延后分钟(0–1440):应用启动会为每个恢复的项目预热进程,
|
|
338
341
|
// 到点把当时符合条件的项目一次收掉;0 = 启动后尽快回收一次
|
|
339
342
|
idleReclaimStartupMinutes: 5,
|
|
343
|
+
// 子代理活动判定时长(分钟,1–1440):超过该时长没有子代理活动视为结束,
|
|
344
|
+
// 不再查询官方结束记录、不亮机器人图标(subagent-icon.js)
|
|
345
|
+
subagentFreshMinutes: 60,
|
|
340
346
|
// 样式调整(设置弹窗“样式调整”标签页)。null = 不覆盖,跟随应用默认。
|
|
341
347
|
styles: {
|
|
342
348
|
thinkingRowGap: null, // 思考段落间距:“已工作/工作中”过程视图内各行的垂直间距(应用默认 20px)
|
|
@@ -454,11 +460,16 @@ export function loadConfig(configFile) {
|
|
|
454
460
|
configUnreadable = false; // 解析成功就复位:修好文件后自动恢复可写
|
|
455
461
|
const minutes = Number(saved.idleReclaimMinutes);
|
|
456
462
|
const startupMinutes = Number(saved.idleReclaimStartupMinutes);
|
|
463
|
+
const subagentFresh = Number(saved.subagentFreshMinutes);
|
|
464
|
+
// 旧版默认 30 落盘后没有标记:迁移到新默认 10。带标记的 30 是用户显式设置,保留
|
|
465
|
+
const legacyIdle30 = Number(saved.idleReclaimMinutes) === 30 && saved.idleReclaimMinutesMigrated !== true;
|
|
457
466
|
return {
|
|
458
467
|
...defaultConfig(),
|
|
459
468
|
...saved,
|
|
460
|
-
idleReclaimMinutes: Number.isFinite(minutes) && minutes >= 1 ? Math.min(1440, Math.round(minutes)) :
|
|
469
|
+
idleReclaimMinutes: legacyIdle30 ? 10 : (Number.isFinite(minutes) && minutes >= 1 ? Math.min(1440, Math.round(minutes)) : 10),
|
|
470
|
+
idleReclaimMinutesMigrated: true,
|
|
461
471
|
idleReclaimStartupMinutes: Number.isFinite(startupMinutes) && startupMinutes >= 0 ? Math.min(1440, Math.round(startupMinutes)) : 5,
|
|
472
|
+
subagentFreshMinutes: Number.isFinite(subagentFresh) && subagentFresh >= 1 ? Math.min(1440, Math.round(subagentFresh)) : 60,
|
|
462
473
|
features: { ...defaultConfig().features, ...(saved.features || {}) },
|
|
463
474
|
styles: migrateStyles(saved.styles),
|
|
464
475
|
aliases: { ...((saved.aliases && typeof saved.aliases === 'object') ? saved.aliases : {}) },
|
|
@@ -976,6 +987,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
976
987
|
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
977
988
|
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
978
989
|
}
|
|
990
|
+
if (body && typeof body === 'object' && typeof body.subagentFreshMinutes === 'number' && Number.isFinite(body.subagentFreshMinutes)) {
|
|
991
|
+
current.subagentFreshMinutes = Math.min(1440, Math.max(1, Math.round(body.subagentFreshMinutes)));
|
|
992
|
+
}
|
|
979
993
|
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
980
994
|
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
981
995
|
}
|
|
@@ -1459,10 +1473,20 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1459
1473
|
json(res, 200, { ok: true, ids });
|
|
1460
1474
|
return;
|
|
1461
1475
|
}
|
|
1476
|
+
if (req.method === 'GET' && url.pathname === '/workspace-subagent-activity') {
|
|
1477
|
+
// 工作区内子代理会话的最近活动时间(毫秒):空闲回收的子代理保护。
|
|
1478
|
+
// 按会话库 directory 直查,不受 /workspace-sessions 的 30 条/7 天限制;
|
|
1479
|
+
// 读库失败返回 ok:false(调用方按“未知”处理,不当作没有活动)
|
|
1480
|
+
const at = await listWorkspaceSubagentActivity(dataRoot, url.searchParams.get('path') || '');
|
|
1481
|
+
if (at === null) json(res, 200, { ok: false });
|
|
1482
|
+
else json(res, 200, { ok: true, at });
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1462
1485
|
if (req.method === 'GET' && url.pathname === '/subagent-children') {
|
|
1463
1486
|
// 会话的子代理子会话及最近活动时间(含嵌套):子代理判活的主信号——
|
|
1464
|
-
//
|
|
1465
|
-
//
|
|
1487
|
+
// 应用的运行记录会把还在跑的长跑子代理误记为结束;已结束且没有后续活动的
|
|
1488
|
+
// 子代理不返回(last_outcome + turn_usage),否则中断或继续对话后图标会
|
|
1489
|
+
// 一直亮着(subagent-icon.js)
|
|
1466
1490
|
const ids = (url.searchParams.get('ids') || '')
|
|
1467
1491
|
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
|
|
1468
1492
|
const children = ids.length ? await listSubagentChildrenActivity(dataRoot, ids) : [];
|
|
@@ -3640,9 +3664,9 @@ function applyFeaturesPartial(base, partial) {
|
|
|
3640
3664
|
return out;
|
|
3641
3665
|
}
|
|
3642
3666
|
|
|
3643
|
-
// 空闲回收的后台命令判定:项目会话进程(zcode-cli)的子进程里,插件/MCP
|
|
3644
|
-
//
|
|
3645
|
-
//
|
|
3667
|
+
// 空闲回收的后台命令判定:项目会话进程(zcode-cli)的子进程里,插件/MCP、应用
|
|
3668
|
+
// 自身组件与会话自己拉起的空闲 worker 不算活动;其余(应用的 shell 包装 exec/、
|
|
3669
|
+
// 用户直接启动的进程)一律视为仍在运行的后台命令。
|
|
3646
3670
|
// 匹配前把命令行的反斜杠统一为正斜杠,一份模式通吃三平台。
|
|
3647
3671
|
const IDLE_INFRA_CMDLINE = [
|
|
3648
3672
|
'/.zcode/cli/plugins/', // 插件市场安装的 MCP/hooks(vision、headroom、rtk 等)
|
|
@@ -3657,6 +3681,12 @@ const IDLE_INFRA_CMDLINE = [
|
|
|
3657
3681
|
|
|
3658
3682
|
const SCAN_OFF = { ok: true, scan: false, busy: [] };
|
|
3659
3683
|
|
|
3684
|
+
// worker CPU 采样:两次采样之间的墙钟时长不固定(扫描本身也要时间),按实际
|
|
3685
|
+
// 窗口折算成“占单核一半”的阈值。固定 tick 数在慢机器上会变得过于敏感
|
|
3686
|
+
const WORKER_CPU_RATIO = 0.5; // 采样窗口内累计 CPU 超过墙钟的一半 = 判忙
|
|
3687
|
+
const WORKER_CPU_WINDOW_MS = 400; // Linux 采样窗口
|
|
3688
|
+
const WORKER_CPU_DARWIN_WINDOW_MS = 1500; // macOS ps 的 time 精度是秒,窗口要够长
|
|
3689
|
+
|
|
3660
3690
|
function normCmdline(s) {
|
|
3661
3691
|
return String(s || '').replace(/\\/g, '/');
|
|
3662
3692
|
}
|
|
@@ -3752,8 +3782,93 @@ export function scanBackgroundBash(tmpDir = '/tmp', procDir = '/proc') {
|
|
|
3752
3782
|
return { ok: true, jobs: [...hit.values()] };
|
|
3753
3783
|
}
|
|
3754
3784
|
|
|
3785
|
+
// 会话进程会拉起若干 cmdline 为 zcode-cli 的子进程(预热的子代理/会话 worker)。
|
|
3786
|
+
// 它们不是用户命令:只要没有在跑的非基础设施子进程、采样窗口内 CPU 时间也没
|
|
3787
|
+
// 增长,就按基础设施跳过。否则项目一旦用过(拉起过 worker)就会永远被判“有后台
|
|
3788
|
+
// 命令”,空闲回收再也释放不掉。
|
|
3789
|
+
function isAgentWorkerName(name) {
|
|
3790
|
+
return /(^|\/)zcode-cli(\.exe)?$/i.test(String(name || '').trim());
|
|
3791
|
+
}
|
|
3792
|
+
|
|
3793
|
+
// 命令行兜底:进程名不一定保留(可能被改成 node/完整路径),看 argv[0] 是否为
|
|
3794
|
+
// zcode-cli。带引号的路径(含空格)按引号边界取 argv[0]。只用于识别 worker,
|
|
3795
|
+
// 不用于判断用户命令——用户手动跑的 zcode-cli 也会被当成 worker(宁可放过也
|
|
3796
|
+
// 不把空闲项目永远判忙的取舍,见上方注释)
|
|
3797
|
+
export function isAgentWorkerCmdline(cmdline) {
|
|
3798
|
+
const s = String(cmdline || '').trim();
|
|
3799
|
+
let first;
|
|
3800
|
+
if (s.startsWith('"')) {
|
|
3801
|
+
const end = s.indexOf('"', 1);
|
|
3802
|
+
first = end > 0 ? s.slice(1, end) : s.slice(1);
|
|
3803
|
+
} else {
|
|
3804
|
+
first = s.split(/\s+/)[0] || '';
|
|
3805
|
+
}
|
|
3806
|
+
return isAgentWorkerName(first);
|
|
3807
|
+
}
|
|
3808
|
+
|
|
3809
|
+
function procCpuTicks(pid) {
|
|
3810
|
+
try {
|
|
3811
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
3812
|
+
const rest = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
|
3813
|
+
return (Number(rest[11]) || 0) + (Number(rest[12]) || 0);
|
|
3814
|
+
} catch { return null; }
|
|
3815
|
+
}
|
|
3816
|
+
|
|
3817
|
+
function procChildren(pid) {
|
|
3818
|
+
try {
|
|
3819
|
+
return readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8')
|
|
3820
|
+
.split(/\s+/).filter(Boolean).map(Number).filter(Number.isFinite);
|
|
3821
|
+
} catch { return null; }
|
|
3822
|
+
}
|
|
3823
|
+
|
|
3824
|
+
function procZombie(pid) {
|
|
3825
|
+
try {
|
|
3826
|
+
// 状态字段在最后一个 ')' 之后:comm 允许空格和括号,整行找 ") Z " 会被进程名误触发
|
|
3827
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
|
|
3828
|
+
const rest = stat.slice(stat.lastIndexOf(')') + 2).trim();
|
|
3829
|
+
return rest.startsWith('Z');
|
|
3830
|
+
} catch { return false; }
|
|
3831
|
+
}
|
|
3832
|
+
|
|
3833
|
+
// 收集 worker 子树里所有 agent worker 的 pid;遇到非基础设施、非 worker 的
|
|
3834
|
+
// 子进程返回 true(有用户命令在跑)。嵌套子代理也是 zcode-cli,按同一规则递归;
|
|
3835
|
+
// worker 先按名字认(命令行可能为空或含应用安装路径),认不出才看命令行;
|
|
3836
|
+
// 深度超限时保守判忙。
|
|
3837
|
+
function collectAgentWorkerSubtree(pid, out, depth = 0) {
|
|
3838
|
+
if (depth > 4) return true;
|
|
3839
|
+
const kids = procChildren(pid);
|
|
3840
|
+
if (kids === null) return true;
|
|
3841
|
+
for (const kid of kids) {
|
|
3842
|
+
if (procZombie(kid)) continue;
|
|
3843
|
+
let cmd = '';
|
|
3844
|
+
let comm = '';
|
|
3845
|
+
try {
|
|
3846
|
+
cmd = normCmdline(readFileSync(`/proc/${kid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim());
|
|
3847
|
+
comm = readFileSync(`/proc/${kid}/comm`, 'utf8').trim();
|
|
3848
|
+
} catch { continue; }
|
|
3849
|
+
if (isAgentWorkerName(comm) || isAgentWorkerCmdline(cmd)) {
|
|
3850
|
+
out.push(kid);
|
|
3851
|
+
if (collectAgentWorkerSubtree(kid, out, depth + 1)) return true;
|
|
3852
|
+
continue;
|
|
3853
|
+
}
|
|
3854
|
+
if (isInfraCmdline(cmd)) continue;
|
|
3855
|
+
return true;
|
|
3856
|
+
}
|
|
3857
|
+
return false;
|
|
3858
|
+
}
|
|
3859
|
+
|
|
3860
|
+
function sumCpuTicks(pids) {
|
|
3861
|
+
let sum = 0;
|
|
3862
|
+
let seen = false;
|
|
3863
|
+
for (const pid of pids) {
|
|
3864
|
+
const t = procCpuTicks(pid);
|
|
3865
|
+
if (t !== null) { sum += t; seen = true; }
|
|
3866
|
+
}
|
|
3867
|
+
return seen ? sum : null;
|
|
3868
|
+
}
|
|
3869
|
+
|
|
3755
3870
|
// Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
|
|
3756
|
-
function scanIdleBusyLinux(paths) {
|
|
3871
|
+
async function scanIdleBusyLinux(paths) {
|
|
3757
3872
|
let pids;
|
|
3758
3873
|
try { pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d)); }
|
|
3759
3874
|
catch { return SCAN_OFF; }
|
|
@@ -3770,44 +3885,117 @@ function scanIdleBusyLinux(paths) {
|
|
|
3770
3885
|
} catch { /* 进程退出/权限:跳过 */ }
|
|
3771
3886
|
}
|
|
3772
3887
|
const busy = new Set();
|
|
3888
|
+
const workers = []; // 暂无活动的 agent worker:稍后采样 CPU 再定
|
|
3773
3889
|
for (const [cwd, cliPids] of cliPidByCwd) {
|
|
3774
3890
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
3775
3891
|
if (!wantedPaths) continue;
|
|
3776
3892
|
for (const pid of cliPids) {
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3893
|
+
const children = procChildren(pid);
|
|
3894
|
+
if (children === null) {
|
|
3895
|
+
// /proc/<pid> 还在但拿不到子进程列表(内核未开 CONFIG_PROC_CHILDREN 等):
|
|
3896
|
+
// 不能当成“没有子进程”,本轮整体放弃扫描
|
|
3897
|
+
if (existsSync(`/proc/${pid}`)) return SCAN_OFF;
|
|
3898
|
+
continue; // 进程已退出
|
|
3899
|
+
}
|
|
3900
|
+
for (const childPid of children) {
|
|
3901
|
+
if (procZombie(childPid)) continue;
|
|
3783
3902
|
let cmdline = '';
|
|
3784
|
-
let
|
|
3903
|
+
let comm = '';
|
|
3785
3904
|
try {
|
|
3786
3905
|
cmdline = normCmdline(readFileSync(`/proc/${childPid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim());
|
|
3787
|
-
|
|
3788
|
-
zombie = /\) Z /.test(stat);
|
|
3906
|
+
comm = readFileSync(`/proc/${childPid}/comm`, 'utf8').trim();
|
|
3789
3907
|
} catch { continue; }
|
|
3790
|
-
if (
|
|
3791
|
-
|
|
3792
|
-
|
|
3908
|
+
if (isAgentWorkerName(comm) || isAgentWorkerCmdline(cmdline)) {
|
|
3909
|
+
const workerPids = [childPid];
|
|
3910
|
+
if (collectAgentWorkerSubtree(childPid, workerPids)) {
|
|
3911
|
+
for (const wp of wantedPaths) busy.add(wp);
|
|
3912
|
+
break;
|
|
3913
|
+
}
|
|
3914
|
+
const ticks = sumCpuTicks(workerPids);
|
|
3915
|
+
if (ticks !== null) workers.push({ pids: workerPids, ticks, wantedPaths, at: Date.now() });
|
|
3916
|
+
continue;
|
|
3917
|
+
}
|
|
3918
|
+
if (isInfraCmdline(cmdline)) continue;
|
|
3919
|
+
if (!cmdline) {
|
|
3920
|
+
for (const wp of wantedPaths) busy.add(wp); // 认不出的进程宁可误判为忙
|
|
3793
3921
|
break;
|
|
3794
3922
|
}
|
|
3923
|
+
for (const wp of wantedPaths) busy.add(wp); // 认不出的进程宁可误判为忙,也不回收可能在跑命令的项目
|
|
3924
|
+
break;
|
|
3795
3925
|
}
|
|
3796
3926
|
}
|
|
3797
3927
|
}
|
|
3928
|
+
// 空闲 worker 的 CPU 时间应保持不变;按每个 worker 自己的采样窗口折算,
|
|
3929
|
+
// 超过半核才判忙
|
|
3930
|
+
if (workers.length) {
|
|
3931
|
+
await new Promise((resolve) => setTimeout(resolve, WORKER_CPU_WINDOW_MS));
|
|
3932
|
+
for (const w of workers) {
|
|
3933
|
+
const elapsedMs = Math.max(1, Date.now() - w.at);
|
|
3934
|
+
const needTicks = Math.max(1, Math.ceil((elapsedMs / 1000) * 100 * WORKER_CPU_RATIO));
|
|
3935
|
+
const now = sumCpuTicks(w.pids);
|
|
3936
|
+
if (now !== null && now - w.ticks > needTicks) for (const wp of w.wantedPaths) busy.add(wp);
|
|
3937
|
+
}
|
|
3938
|
+
}
|
|
3798
3939
|
return { ok: true, scan: true, busy: [...busy] };
|
|
3799
3940
|
}
|
|
3800
3941
|
|
|
3801
|
-
|
|
3942
|
+
export function parsePsTime(s) {
|
|
3943
|
+
// [[dd-]hh:]mm:ss:macOS ps 的 time 字段。天数前缀单独处理,Number('1-02') 会变 NaN
|
|
3944
|
+
let text = String(s || '').trim();
|
|
3945
|
+
if (!text) return 0;
|
|
3946
|
+
let days = 0;
|
|
3947
|
+
const dash = text.indexOf('-');
|
|
3948
|
+
if (dash > 0) {
|
|
3949
|
+
days = Number(text.slice(0, dash)) || 0;
|
|
3950
|
+
text = text.slice(dash + 1);
|
|
3951
|
+
}
|
|
3952
|
+
const parts = text.split(':');
|
|
3953
|
+
if (!parts.length || parts.length > 3) return 0;
|
|
3954
|
+
let secs = 0;
|
|
3955
|
+
for (const part of parts) {
|
|
3956
|
+
const n = Number(part);
|
|
3957
|
+
if (!Number.isFinite(n)) return 0;
|
|
3958
|
+
secs = secs * 60 + n;
|
|
3959
|
+
}
|
|
3960
|
+
return days * 86400 + secs;
|
|
3961
|
+
}
|
|
3962
|
+
|
|
3963
|
+
function collectDarwinWorkerSubtree(pid, procs, cmdByPid, out, depth = 0) {
|
|
3964
|
+
if (depth > 4) return true;
|
|
3965
|
+
for (const g of procs) {
|
|
3966
|
+
if (g.ppid !== pid || g.stat.includes('Z')) continue;
|
|
3967
|
+
const gc = normCmdline(cmdByPid.get(g.pid) || '');
|
|
3968
|
+
if (isAgentWorkerName(g.comm) || isAgentWorkerCmdline(gc)) {
|
|
3969
|
+
out.push(g.pid);
|
|
3970
|
+
if (collectDarwinWorkerSubtree(g.pid, procs, cmdByPid, out, depth + 1)) return true;
|
|
3971
|
+
continue;
|
|
3972
|
+
}
|
|
3973
|
+
if (isInfraCmdline(gc)) continue;
|
|
3974
|
+
return true;
|
|
3975
|
+
}
|
|
3976
|
+
return false;
|
|
3977
|
+
}
|
|
3978
|
+
|
|
3979
|
+
function sumDarwinCpu(cpuByPid, pids) {
|
|
3980
|
+
let sum = 0;
|
|
3981
|
+
let seen = false;
|
|
3982
|
+
for (const pid of pids) {
|
|
3983
|
+
const v = cpuByPid.get(pid);
|
|
3984
|
+
if (v !== undefined) { sum += v; seen = true; }
|
|
3985
|
+
}
|
|
3986
|
+
return seen ? sum : null;
|
|
3987
|
+
}
|
|
3988
|
+
|
|
3989
|
+
// macOS:ps 拿进程表(pid/父 pid/状态/CPU 时间/名称/命令行),lsof 拿 CLI 进程的工作目录。
|
|
3802
3990
|
// 都是系统自带工具、本用户进程无需提权。任何一个 CLI 的工作目录取不到就本轮放弃
|
|
3803
3991
|
// (scan=false),宁可不动也不猜
|
|
3804
3992
|
async function scanIdleBusyDarwin(paths) {
|
|
3805
|
-
const psInfo = await runCmd('ps', ['-axo', 'pid=,ppid=,stat=,comm=']);
|
|
3993
|
+
const psInfo = await runCmd('ps', ['-axo', 'pid=,ppid=,stat=,time=,comm=']);
|
|
3806
3994
|
if (psInfo.err) return SCAN_OFF;
|
|
3807
3995
|
const procs = [];
|
|
3808
3996
|
for (const line of psInfo.stdout.split('\n')) {
|
|
3809
|
-
const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/);
|
|
3810
|
-
if (m) procs.push({ pid: Number(m[1]), ppid: Number(m[2]), stat: m[3],
|
|
3997
|
+
const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(.+)$/);
|
|
3998
|
+
if (m) procs.push({ pid: Number(m[1]), ppid: Number(m[2]), stat: m[3], cpu: parsePsTime(m[4]), comm: m[5].trim() });
|
|
3811
3999
|
}
|
|
3812
4000
|
const clis = procs.filter((p) => /(^|\/)zcode-cli$/.test(p.comm));
|
|
3813
4001
|
if (!clis.length) return SCAN_OFF; // 定位不到会话进程:可能名称对不上,不猜
|
|
@@ -3819,7 +4007,12 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
3819
4007
|
if (m) cmdByPid.set(Number(m[1]), m[2]);
|
|
3820
4008
|
}
|
|
3821
4009
|
const wantedByCwd = buildWantedByCwd(paths);
|
|
4010
|
+
// 快照第一次 ps 的时刻作为所有 worker 的首次采样时间:逐 CLI 的 lsof 可能
|
|
4011
|
+
// 耗时很久,用 push 时刻会低估采样窗口、放大偶发 CPU 的判定
|
|
4012
|
+
const sampleAt = Date.now();
|
|
4013
|
+
const cpuByPid = new Map(procs.map((p) => [p.pid, p.cpu]));
|
|
3822
4014
|
const busy = new Set();
|
|
4015
|
+
const workers = [];
|
|
3823
4016
|
for (const cli of clis) {
|
|
3824
4017
|
const lsof = await runCmd('lsof', ['-a', '-p', String(cli.pid), '-d', 'cwd', '-Fn', '-w']);
|
|
3825
4018
|
// 与注释的约定一致:任一 CLI 的工作目录取不到就整轮放弃(scan=false)——
|
|
@@ -3832,9 +4025,38 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
3832
4025
|
for (const child of procs) {
|
|
3833
4026
|
if (child.ppid !== cli.pid || child.stat.includes('Z')) continue;
|
|
3834
4027
|
const cmdline = normCmdline(cmdByPid.get(child.pid) || '');
|
|
3835
|
-
if (
|
|
3836
|
-
|
|
3837
|
-
|
|
4028
|
+
if (isAgentWorkerName(child.comm) || isAgentWorkerCmdline(cmdline)) {
|
|
4029
|
+
const workerPids = [child.pid];
|
|
4030
|
+
if (collectDarwinWorkerSubtree(child.pid, procs, cmdByPid, workerPids)) {
|
|
4031
|
+
for (const wp of wantedPaths) busy.add(wp);
|
|
4032
|
+
break;
|
|
4033
|
+
}
|
|
4034
|
+
const cpu = sumDarwinCpu(cpuByPid, workerPids);
|
|
4035
|
+
if (cpu !== null) workers.push({ pids: workerPids, cpu, wantedPaths, at: sampleAt });
|
|
4036
|
+
continue;
|
|
4037
|
+
}
|
|
4038
|
+
if (isInfraCmdline(cmdline)) continue;
|
|
4039
|
+
for (const wp of wantedPaths) busy.add(wp);
|
|
4040
|
+
break;
|
|
4041
|
+
}
|
|
4042
|
+
}
|
|
4043
|
+
if (workers.length) {
|
|
4044
|
+
await new Promise((resolve) => setTimeout(resolve, WORKER_CPU_DARWIN_WINDOW_MS));
|
|
4045
|
+
const again = await runCmd('ps', ['-axo', 'pid=,time=']);
|
|
4046
|
+
if (again.err) {
|
|
4047
|
+
// 二次采样失败:不能确认空闲,保守判忙
|
|
4048
|
+
for (const w of workers) for (const wp of w.wantedPaths) busy.add(wp);
|
|
4049
|
+
} else {
|
|
4050
|
+
const after = new Map();
|
|
4051
|
+
for (const line of again.stdout.split('\n')) {
|
|
4052
|
+
const m = line.trim().match(/^(\d+)\s+(\S+)$/);
|
|
4053
|
+
if (m) after.set(Number(m[1]), parsePsTime(m[2]));
|
|
4054
|
+
}
|
|
4055
|
+
for (const w of workers) {
|
|
4056
|
+
const elapsed = Math.max(0.001, (Date.now() - w.at) / 1000);
|
|
4057
|
+
const needSec = elapsed * WORKER_CPU_RATIO;
|
|
4058
|
+
const now = sumDarwinCpu(after, w.pids);
|
|
4059
|
+
if (now !== null && now - w.cpu > needSec) for (const wp of w.wantedPaths) busy.add(wp);
|
|
3838
4060
|
}
|
|
3839
4061
|
}
|
|
3840
4062
|
}
|
|
@@ -3864,36 +4086,116 @@ async function scanIdleBusyWindows(paths, dataRoot) {
|
|
|
3864
4086
|
name: String(p.Name || ''),
|
|
3865
4087
|
cmdline: normCmdline(p.CommandLine || ''),
|
|
3866
4088
|
}));
|
|
3867
|
-
let
|
|
4089
|
+
let wsRaw = null; // 懒加载:任务 ID → 原样工作区(整表缓存,不在每次查询时重读)
|
|
4090
|
+
// 先扫一遍命令行里出现的会话 id,一次批量问祖先链:CLI 驱动下每个 id 一次
|
|
4091
|
+
// sqlite3 进程,串行查会在多子代理并行时拖慢整轮扫描。只收 zcode-cli 会话
|
|
4092
|
+
// 进程的后代,浏览器/编辑器等无关进程命令行里的 sess_ 字样不进库
|
|
4093
|
+
const cliPids = new Set(procs.filter((p) => /^zcode-cli(\.exe)?$/i.test(p.name)).map((p) => p.pid));
|
|
4094
|
+
const sessIds = new Set();
|
|
4095
|
+
if (cliPids.size) {
|
|
4096
|
+
const ppidByPid = new Map(procs.map((p) => [p.pid, p.ppid]));
|
|
4097
|
+
const underCli = (pid) => {
|
|
4098
|
+
for (let i = 0, cur = pid; i < 8; i++) {
|
|
4099
|
+
if (cliPids.has(cur)) return true;
|
|
4100
|
+
cur = ppidByPid.get(cur) || 0;
|
|
4101
|
+
if (!cur) return false;
|
|
4102
|
+
}
|
|
4103
|
+
return false;
|
|
4104
|
+
};
|
|
4105
|
+
for (const p of procs) {
|
|
4106
|
+
if (!underCli(p.pid)) continue;
|
|
4107
|
+
const m = p.cmdline && p.cmdline.match(/(?:sess|session)_[A-Za-z0-9._-]+/);
|
|
4108
|
+
if (m) sessIds.add(m[0]);
|
|
4109
|
+
if (sessIds.size >= 300) break;
|
|
4110
|
+
}
|
|
4111
|
+
}
|
|
4112
|
+
const ancestorMap = sessIds.size ? await listSessionAncestors(dataRoot, [...sessIds]) : {};
|
|
4113
|
+
const normWs = (v) => {
|
|
4114
|
+
const base = normWinPath(v);
|
|
4115
|
+
try {
|
|
4116
|
+
const real = realpathSync.native(v);
|
|
4117
|
+
if (real) return normWinPath(real);
|
|
4118
|
+
} catch { /* 目录不存在或平台不支持 */ }
|
|
4119
|
+
return base;
|
|
4120
|
+
};
|
|
3868
4121
|
const lookupTaskWs = async (taskId) => {
|
|
3869
|
-
if (
|
|
3870
|
-
|
|
3871
|
-
|
|
3872
|
-
|
|
4122
|
+
if (wsRaw === null) wsRaw = await listTaskWorkspaceMap(dataRoot);
|
|
4123
|
+
if (wsRaw[taskId]) return normWs(wsRaw[taskId]);
|
|
4124
|
+
// 直接查不到(子代理会话、已删根会话):沿父链逐级上溯,取第一个有工作区的
|
|
4125
|
+
for (const node of ancestorMap[taskId] || []) {
|
|
4126
|
+
if (wsRaw[node]) return normWs(wsRaw[node]);
|
|
3873
4127
|
}
|
|
3874
|
-
return
|
|
4128
|
+
return undefined;
|
|
3875
4129
|
};
|
|
3876
4130
|
return classifyIdleBusyWindows(procs, paths, lookupTaskWs);
|
|
3877
4131
|
}
|
|
3878
4132
|
|
|
3879
|
-
// Windows
|
|
4133
|
+
// Windows 路径归一:大小写、分隔符、尾斜杠、\\?\ 长路径前缀。junction/映射盘
|
|
4134
|
+
// 这类别名靠 realpath 兜一层(目录不存在时忽略)
|
|
4135
|
+
export function normWinPath(p) {
|
|
4136
|
+
let s = normCmdline(p).replace(/\/+$/, '').toLowerCase();
|
|
4137
|
+
if (s.startsWith('//?/')) s = s.slice(4);
|
|
4138
|
+
return s;
|
|
4139
|
+
}
|
|
4140
|
+
|
|
4141
|
+
// Windows 判定逻辑(与进程表获取解耦,可直接喂真实 CIM 数据测试)。
|
|
4142
|
+
// 这里只有进程结构可用:拿不到其他进程的工作目录,worker 自己的 CPU 时间也无法
|
|
4143
|
+
// 归属到具体项目,所以不做 CPU 采样(做了只能全量判忙)。worker 正在处理回合但
|
|
4144
|
+
// 没有子进程时与空闲无法区分,这一层依靠调用方的官方活跃会话判定兜底。
|
|
3880
4145
|
export async function classifyIdleBusyWindows(procs, paths, lookupTaskWs) {
|
|
3881
4146
|
const clis = procs.filter((p) => /^zcode-cli(\.exe)?$/i.test(p.name));
|
|
3882
4147
|
if (!clis.length) return SCAN_OFF; // 定位不到会话进程:可能名称对不上,不猜
|
|
3883
4148
|
const reqByNorm = new Map();
|
|
3884
|
-
for (const p of paths)
|
|
4149
|
+
for (const p of paths) {
|
|
4150
|
+
reqByNorm.set(normWinPath(p), p);
|
|
4151
|
+
try {
|
|
4152
|
+
const real = realpathSync.native(p);
|
|
4153
|
+
if (real) reqByNorm.set(normWinPath(real), p);
|
|
4154
|
+
} catch { /* 目录不存在或平台不支持 */ }
|
|
4155
|
+
}
|
|
3885
4156
|
let unattributed = false;
|
|
3886
4157
|
const busy = new Set();
|
|
3887
4158
|
const markByTask = async (taskId) => {
|
|
3888
4159
|
const normWs = await lookupTaskWs(taskId);
|
|
3889
|
-
|
|
4160
|
+
// 归属明确但不在本轮请求的项目里(Windows 会扫全机所有会话进程):与本轮
|
|
4161
|
+
// 判定无关,不能据此把其他项目全部判忙
|
|
4162
|
+
if (!normWs) { unattributed = true; return; }
|
|
4163
|
+
const req = reqByNorm.get(normWs);
|
|
3890
4164
|
if (req) busy.add(req);
|
|
3891
|
-
|
|
4165
|
+
};
|
|
4166
|
+
// worker 子树里的用户命令(嵌套子代理也是 zcode-cli,按同一规则递归);
|
|
4167
|
+
// null = 读不到命令行,按归属不明处理
|
|
4168
|
+
const collectWorkerCommands = (worker, out, depth = 0) => {
|
|
4169
|
+
if (depth > 4) { out.push(null); return; }
|
|
4170
|
+
for (const g of procs) {
|
|
4171
|
+
if (g.ppid !== worker.pid) continue;
|
|
4172
|
+
// 先按名字认 worker:命令行可能为空,也可能是带安装路径(含 Programs/ZCode)的完整路径
|
|
4173
|
+
if (/^zcode-cli(\.exe)?$/i.test(String(g.name || '').trim()) || isAgentWorkerCmdline(g.cmdline)) {
|
|
4174
|
+
collectWorkerCommands(g, out, depth + 1);
|
|
4175
|
+
continue;
|
|
4176
|
+
}
|
|
4177
|
+
if (!g.cmdline) { out.push(null); continue; }
|
|
4178
|
+
if (isInfraCmdline(g.cmdline)) continue;
|
|
4179
|
+
out.push(g.cmdline);
|
|
4180
|
+
}
|
|
3892
4181
|
};
|
|
3893
4182
|
for (const cli of clis) {
|
|
3894
4183
|
for (const child of procs) {
|
|
3895
4184
|
if (child.ppid !== cli.pid) continue;
|
|
3896
|
-
|
|
4185
|
+
// 会话自己的 zcode-cli worker:子树里没有在跑的用户命令时不算用户命令;
|
|
4186
|
+
// 有的话按命令里的会话 id 归属(worker 自己的命令行通常只剩进程名)
|
|
4187
|
+
if (/^zcode-cli(\.exe)?$/i.test(String(child.name || '').trim()) || isAgentWorkerCmdline(child.cmdline)) {
|
|
4188
|
+
const active = [];
|
|
4189
|
+
collectWorkerCommands(child, active);
|
|
4190
|
+
for (const cmd of active) {
|
|
4191
|
+
if (cmd === null) { unattributed = true; continue; }
|
|
4192
|
+
const s = cmd.match(/(?:sess|session)_[A-Za-z0-9._-]+/);
|
|
4193
|
+
if (s) await markByTask(s[0]);
|
|
4194
|
+
else unattributed = true;
|
|
4195
|
+
}
|
|
4196
|
+
continue;
|
|
4197
|
+
}
|
|
4198
|
+
if (isInfraCmdline(child.cmdline || '')) continue;
|
|
3897
4199
|
if (!child.cmdline) { unattributed = true; continue; }
|
|
3898
4200
|
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_);字符集与
|
|
3899
4201
|
// 路由校验的 id 白名单一致(含 . 和 _)——字符类偏窄会在这些字符处截断成
|