zcode-pro 1.6.2 → 1.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/README.en.md +3 -2
- package/README.md +3 -2
- package/dist/inject.js +1428 -240
- package/package.json +2 -2
- package/src/host/helper.mjs +360 -37
- package/src/host/mcp-bridge.mjs +488 -0
- package/src/host/session-import/index.mjs +140 -0
- package/src/host/session-import/sources.mjs +839 -0
- package/src/host/session-import/util.mjs +239 -0
- package/src/host/session-import/write.mjs +405 -0
- package/src/host/session-import/zstd.mjs +68 -0
- package/src/host/taskIndex.mjs +374 -0
- package/src/inject/core.js +118 -13
- package/src/inject/features/idle-reclaim.js +48 -23
- package/src/inject/features/plugin-updates.js +58 -0
- package/src/inject/features/session-import.js +367 -0
- package/src/inject/features/session-link.js +3 -1
- package/src/inject/features/session-switch.js +10 -7
- package/src/inject/features/settings-dialog.js +92 -15
- package/src/inject/features/status-bar.js +88 -36
- package/src/inject/features/subagent-icon.js +472 -0
- package/src/inject/features/turn-usage.js +89 -32
- package/src/inject/features/ws-running.js +40 -10
- package/src/inject/index.js +2 -0
- package/src/inject/ui.js +10 -0
package/src/host/helper.mjs
CHANGED
|
@@ -11,14 +11,17 @@ 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, 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, 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';
|
|
18
18
|
import { resolveZcodeExecutable, resolveDataRootDir } from './paths.mjs';
|
|
19
19
|
import { skillStats, DEFAULT_METADATA_BUDGET } from './skill-stats.mjs';
|
|
20
|
+
import { listImportSessions, runImport } from './session-import/index.mjs';
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
// 会话导入(/import/list、/import/run):把外部 CLI 的历史会话写成 ZCode 任务。
|
|
23
|
+
|
|
24
|
+
const VERSION = '1.7.0';
|
|
22
25
|
|
|
23
26
|
// 全局提示词固定在用户主目录:官方加载器按 HOME/USERPROFILE 拼 .zcode/AGENTS.md,
|
|
24
27
|
// 不读 ZCODE_DATA_BASE_DIR(数据根迁走时全局指令仍在原位)。
|
|
@@ -301,12 +304,14 @@ export function defaultConfig() {
|
|
|
301
304
|
sessionSwitch: true, // 会话快捷切换(alt+z 上次会话;按住 alt x/c 弹窗导航,类 alt+tab)
|
|
302
305
|
titleLock: true, // 会话名锁定:手动重命名过的会话不被运行时推送的自动标题覆盖(侧栏钉回索引库中的名字)
|
|
303
306
|
wsRunningSpin: true, // 折叠项目运行提示:折叠后其中仍有会话运行时项目图标旋转
|
|
307
|
+
subagentIcon: true, // 子代理运行提示:任务行空闲图标位与折叠项目图标显示机器人(subagent-icon.js)
|
|
304
308
|
idleReclaim: true, // 空闲项目内存回收:长时间无活动的项目释放其会话进程(时长 idleReclaimMinutes)
|
|
305
309
|
toolbarIcons: true, // 侧栏菜单并入顶栏:新建任务/搜索/自动化/插件市场收成顶栏图标按钮(原菜单隐藏,点击转发)
|
|
306
310
|
pinnedCollapse: true, // 已置顶分区可折叠:标题可点折叠/展开任务列表(状态记 localStorage)
|
|
307
311
|
tableCopy: true, // 表格工具条"复制表格"按钮:富文本剪贴板,粘贴即表格(table-copy.js)
|
|
308
312
|
sessionLink: true, // 会话 ID 显示为任务名链接:聊天里的 sess_/session_ 显示为任务名,点击切换(session-link.js)
|
|
309
313
|
composerProvider: true, // 输入框模型名前显示供应商名(composer-provider.js)
|
|
314
|
+
sessionImport: true, // 导入会话:把 Codex/Claude Code/dsh/pi 的历史会话复制成 ZCode 任务
|
|
310
315
|
},
|
|
311
316
|
// 空闲项目内存回收的判定时长(分钟,1–1440):项目无运行中会话、无后台命令
|
|
312
317
|
// 且非当前选中,持续满该时长后释放其会话进程
|
|
@@ -595,18 +600,65 @@ function readBody(req, limitBytes = 1 << 20) {
|
|
|
595
600
|
}
|
|
596
601
|
|
|
597
602
|
// 软件代理(设置弹窗“代理”标签页):helper 发起的网络访问(zcode CLI→git、pip、
|
|
598
|
-
// WebDAV 同步)按用途(proxyScopes
|
|
599
|
-
//
|
|
603
|
+
// WebDAV 同步)按用途(proxyScopes)走这里。activeProxyUrl 只存手填代理;没填时
|
|
604
|
+
// 按需读 Windows 系统代理(带短缓存,Clash 开关后能自动跟上)。
|
|
600
605
|
let activeProxyUrl = '';
|
|
601
606
|
let activeProxyScopes = { plugins: true, deps: true, sync: false };
|
|
607
|
+
let systemProxyCache = { url: '', at: 0 };
|
|
608
|
+
|
|
609
|
+
// ProxyServer 的值有两种写法:host:port,或 http=host:port;https=host:port。
|
|
610
|
+
// 取 https(没有就取 http),补上协议。导出以便测试。
|
|
611
|
+
export function parseWindowsProxyServer(raw) {
|
|
612
|
+
if (!raw) return '';
|
|
613
|
+
const clean = (s) => String(s).trim().replace(/^"|"$/g, '').trim();
|
|
614
|
+
let v = clean(raw);
|
|
615
|
+
if (v.includes('=')) {
|
|
616
|
+
const parts = {};
|
|
617
|
+
for (const seg of v.split(';')) {
|
|
618
|
+
const i = seg.indexOf('=');
|
|
619
|
+
if (i > 0) parts[seg.slice(0, i).trim().toLowerCase()] = clean(seg.slice(i + 1));
|
|
620
|
+
}
|
|
621
|
+
v = parts.https || parts.http || '';
|
|
622
|
+
}
|
|
623
|
+
if (!v) return '';
|
|
624
|
+
const url = /^[a-z]+:\/\//i.test(v) ? v : `http://${v}`;
|
|
625
|
+
// 注册表值不做校验会被坏值原样塞进 HTTP_PROXY;和手填代理一样要求 host:port
|
|
626
|
+
return /^https?:\/\/[^\s/]+:\d+$/.test(url) ? url : '';
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// Windows 系统代理(Internet 选项)。没单独配代理时沿用它:新电脑上 Clash 等
|
|
630
|
+
// 工具通常只开系统代理,用户不会再为单个应用填一遍地址。
|
|
631
|
+
function windowsSystemProxy() {
|
|
632
|
+
if (process.platform !== 'win32') return '';
|
|
633
|
+
const query = (name) => {
|
|
634
|
+
const r = spawnSync('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', '/v', name],
|
|
635
|
+
{ encoding: 'utf8', windowsHide: true, timeout: 5000 });
|
|
636
|
+
const m = new RegExp(`${name}\\s+REG_(?:DWORD|SZ)\\s+(.+)`, 'i').exec(r.stdout || '');
|
|
637
|
+
return m ? m[1].trim() : '';
|
|
638
|
+
};
|
|
639
|
+
if (!/^0x0*1$/i.test(query('ProxyEnable'))) return '';
|
|
640
|
+
return parseWindowsProxyServer(query('ProxyServer'));
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// 生效代理:手填优先;没填时读 Windows 系统代理并缓存 30 秒。Clash 在 ZCode
|
|
644
|
+
// 之后启动或退出时能自动跟上,又不会每次请求都跑 reg。
|
|
645
|
+
function effectiveProxyUrl() {
|
|
646
|
+
if (activeProxyUrl) return activeProxyUrl;
|
|
647
|
+
if (Date.now() - systemProxyCache.at > 30_000) {
|
|
648
|
+
systemProxyCache = { url: windowsSystemProxy(), at: Date.now() };
|
|
649
|
+
}
|
|
650
|
+
return systemProxyCache.url;
|
|
651
|
+
}
|
|
602
652
|
|
|
603
653
|
// scope:'plugins'(插件市场)/ 'deps'(headroom、rtk)/ 'sync'(WebDAV 同步);
|
|
604
654
|
// 'none' 表示这次调用与下载无关(headroom 生命周期钩子等),永不注入下载代理
|
|
605
655
|
function proxyEnv(extra = {}, scope = 'deps') {
|
|
606
|
-
if (scope === 'none' || !
|
|
656
|
+
if (scope === 'none' || !activeProxyScopes[scope]) return extra;
|
|
657
|
+
const proxy = effectiveProxyUrl();
|
|
658
|
+
if (!proxy) return extra;
|
|
607
659
|
return {
|
|
608
|
-
HTTP_PROXY:
|
|
609
|
-
http_proxy:
|
|
660
|
+
HTTP_PROXY: proxy, HTTPS_PROXY: proxy,
|
|
661
|
+
http_proxy: proxy, https_proxy: proxy,
|
|
610
662
|
...extra,
|
|
611
663
|
};
|
|
612
664
|
}
|
|
@@ -614,7 +666,7 @@ function proxyEnv(extra = {}, scope = 'deps') {
|
|
|
614
666
|
// 该用途当前是否走代理:同步按 proxyUrl 参数传给 webdav(curl 路径用,
|
|
615
667
|
// fetch 兜底路径不认代理环境变量)
|
|
616
668
|
function proxyUrlFor(scope) {
|
|
617
|
-
return activeProxyScopes[scope] ?
|
|
669
|
+
return activeProxyScopes[scope] ? effectiveProxyUrl() : '';
|
|
618
670
|
}
|
|
619
671
|
|
|
620
672
|
// 智能起名诊断日志:追加到 <dataRoot>/zcodepro.log(与启动诊断同文件),超 512KB
|
|
@@ -863,6 +915,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
863
915
|
return;
|
|
864
916
|
}
|
|
865
917
|
activeProxyUrl = current.proxy;
|
|
918
|
+
if (!current.proxy) systemProxyCache = { url: '', at: 0 }; // 清空手填后立即重读系统代理
|
|
866
919
|
}
|
|
867
920
|
if (body && typeof body === 'object' && body.proxyScopes && typeof body.proxyScopes === 'object') {
|
|
868
921
|
// 代理生效范围按单项提交(每个开关只改自己那项),即时生效
|
|
@@ -1320,6 +1373,29 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1320
1373
|
: { ok: true, available: false, projects: [], deletedRoots: [] });
|
|
1321
1374
|
return;
|
|
1322
1375
|
}
|
|
1376
|
+
if (req.method === 'POST' && url.pathname === '/import/list') {
|
|
1377
|
+
const body = await readBody(req);
|
|
1378
|
+
const result = await listImportSessions({
|
|
1379
|
+
dataRoot,
|
|
1380
|
+
source: body && body.source,
|
|
1381
|
+
showAll: !!(body && body.showAll),
|
|
1382
|
+
search: String((body && body.search) || '').slice(0, 200),
|
|
1383
|
+
roots: Array.isArray(body && body.roots) ? body.roots.filter((r) => typeof r === 'string').slice(0, 20) : [],
|
|
1384
|
+
});
|
|
1385
|
+
json(res, result.ok ? 200 : 400, result);
|
|
1386
|
+
return;
|
|
1387
|
+
}
|
|
1388
|
+
if (req.method === 'POST' && url.pathname === '/import/run') {
|
|
1389
|
+
const body = await readBody(req);
|
|
1390
|
+
const result = await runImport({
|
|
1391
|
+
dataRoot,
|
|
1392
|
+
source: body && body.source,
|
|
1393
|
+
items: body && body.items,
|
|
1394
|
+
projectId: (body && body.projectId) || null,
|
|
1395
|
+
});
|
|
1396
|
+
json(res, result.ok ? 200 : 400, result);
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1323
1399
|
if (req.method === 'GET' && url.pathname === '/task-statuses') {
|
|
1324
1400
|
// 批量会话终态 + 标题:注入侧剔除 syncer 卡滞的误报、alt+r 弹窗显示
|
|
1325
1401
|
// 折叠项目会话标题都用它。读不到时 available=false,调用方按未确认处理
|
|
@@ -1331,6 +1407,45 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1331
1407
|
: { ok: true, available: false, statuses: {} });
|
|
1332
1408
|
return;
|
|
1333
1409
|
}
|
|
1410
|
+
if (req.method === 'GET' && url.pathname === '/sessions-activity') {
|
|
1411
|
+
// 子会话最近活动时间(毫秒):子代理 running 记录的新鲜度校验,
|
|
1412
|
+
// 长时间没动静的僵死记录不亮机器人(subagent-icon.js)
|
|
1413
|
+
const ids = (url.searchParams.get('ids') || '')
|
|
1414
|
+
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
|
|
1415
|
+
const activity = ids.length ? await listSessionsActivity(dataRoot, ids) : {};
|
|
1416
|
+
json(res, 200, { ok: true, activity });
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
if (req.method === 'GET' && url.pathname === '/workspace-sessions') {
|
|
1420
|
+
// 某工作区的任务会话 id(任务索引反查):折叠项目行扫子代理运行状态的候选清单
|
|
1421
|
+
const path = url.searchParams.get('path') || '';
|
|
1422
|
+
const ids = path ? await listWorkspaceTaskIds(dataRoot, path) : [];
|
|
1423
|
+
json(res, 200, { ok: true, ids });
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
if (req.method === 'GET' && url.pathname === '/subagent-children') {
|
|
1427
|
+
// 会话的子代理子会话及最近活动时间(含嵌套):子代理判活的主信号——
|
|
1428
|
+
// 应用的运行记录会把还在跑的长跑子代理误记为结束(subagent-icon.js)
|
|
1429
|
+
const ids = (url.searchParams.get('ids') || '')
|
|
1430
|
+
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
|
|
1431
|
+
const children = ids.length ? await listSubagentChildrenActivity(dataRoot, ids) : [];
|
|
1432
|
+
json(res, 200, { ok: true, children });
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
if (req.method === 'GET' && url.pathname === '/background-bash') {
|
|
1436
|
+
// 后台 bash 任务在跑清单(进程握着的日志文件反查会话):终端图标的信号,
|
|
1437
|
+
// 纯文件系统扫描,不拉会话快照(快照会 resume 会话,见 scanBackgroundBash)
|
|
1438
|
+
json(res, 200, scanBackgroundBash());
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
if (req.method === 'GET' && url.pathname === '/project-unread') {
|
|
1442
|
+
// 项目"真未读"任务数(排除错误态):项目行蓝色未读徽标忽略红色错误行
|
|
1443
|
+
const ids = (url.searchParams.get('ids') || '')
|
|
1444
|
+
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 100);
|
|
1445
|
+
const unread = ids.length ? await listProjectsUnread(dataRoot, ids) : {};
|
|
1446
|
+
json(res, 200, unread === null ? { ok: false } : { ok: true, unread });
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1334
1449
|
if (req.method === 'GET' && url.pathname === '/projects') {
|
|
1335
1450
|
const settings = readSettings(settingsFile);
|
|
1336
1451
|
const projects = (settings.recentProjects || []).map((p) => {
|
|
@@ -1699,6 +1814,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1699
1814
|
ok: true, config, file, hook,
|
|
1700
1815
|
pluginVersion: vm ? vm[1] : null,
|
|
1701
1816
|
usage: headroomUsageScan(dataRoot),
|
|
1817
|
+
serena: serenaScan(),
|
|
1702
1818
|
...(await headroomBinaryInfo()),
|
|
1703
1819
|
});
|
|
1704
1820
|
return;
|
|
@@ -1767,6 +1883,16 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1767
1883
|
}
|
|
1768
1884
|
json(res, 200, { ok: true, usage: headroomUsageScan(dataRoot), changed: r.changed });
|
|
1769
1885
|
return;
|
|
1886
|
+
} else if (body && typeof body.serena === 'boolean') {
|
|
1887
|
+
// Serena 开关:写/删 ~/.zcode/cli/config.json 的 mcp.servers.serena,
|
|
1888
|
+
// ZCode 新会话启动时加载该 MCP 服务器(当前会话不重连,重启会话后生效)
|
|
1889
|
+
const r = setSerenaEnabled(body.serena);
|
|
1890
|
+
if (!r.ok) {
|
|
1891
|
+
json(res, 500, { ok: false, code: r.code, error: r.error });
|
|
1892
|
+
return;
|
|
1893
|
+
}
|
|
1894
|
+
json(res, 200, { ok: true, serena: r.serena });
|
|
1895
|
+
return;
|
|
1770
1896
|
} else if (body && body.cancelUpgrade === true) {
|
|
1771
1897
|
json(res, 200, { ok: true, upgrade: cancelHeadroomUpgrade() });
|
|
1772
1898
|
return;
|
|
@@ -1808,7 +1934,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1808
1934
|
return;
|
|
1809
1935
|
}
|
|
1810
1936
|
} else {
|
|
1811
|
-
json(res, 400, { ok: false, code: 'invalid-request', error: 'body 需包含 action/backend/power/usage/interval 之一' });
|
|
1937
|
+
json(res, 400, { ok: false, code: 'invalid-request', error: 'body 需包含 action/backend/power/usage/serena/interval 之一' });
|
|
1812
1938
|
return;
|
|
1813
1939
|
}
|
|
1814
1940
|
let config = null;
|
|
@@ -1859,7 +1985,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1859
1985
|
// —— 软件代理连通性检测:经 curl -x 走代理访问插件市场/本体升级实际要用的站点 ——
|
|
1860
1986
|
if (req.method === 'POST' && url.pathname === '/proxy/test') {
|
|
1861
1987
|
const body = await readBody(req);
|
|
1862
|
-
const proxy = typeof body?.proxy === 'string' && body.proxy.trim() ? body.proxy.trim() :
|
|
1988
|
+
const proxy = typeof body?.proxy === 'string' && body.proxy.trim() ? body.proxy.trim() : effectiveProxyUrl();
|
|
1863
1989
|
if (!proxy) {
|
|
1864
1990
|
json(res, 400, { ok: false, code: 'proxy-not-set', error: '请先填写代理地址' });
|
|
1865
1991
|
return;
|
|
@@ -2125,14 +2251,28 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2125
2251
|
const sessionId = /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(rawSid) ? rawSid : '';
|
|
2126
2252
|
// turns=0 跳过分钟桶聚合(状态栏只读 global,不白建每轮桶)
|
|
2127
2253
|
const wantTurns = url.searchParams.get('turns') !== '0';
|
|
2128
|
-
|
|
2254
|
+
// 会话树 trace:速率把同树子代理的调用算进来
|
|
2255
|
+
const treeTrace = sessionId ? await sessionTrace(dataRoot, sessionId) : '';
|
|
2256
|
+
const { global, recentTurns } = collectUsageStats(sessionId, wantTurns, treeTrace);
|
|
2257
|
+
// 官方口径的会话汇总(主轮请求/累计输入输出/平均命中/树口径净生成速率):状态栏会话组用
|
|
2258
|
+
const mu = sessionId ? await listSessionModelUsage(dataRoot, sessionId, treeTrace) : null;
|
|
2129
2259
|
// 任务总数 60 秒缓存:状态栏每 2 秒请求一次,不必每次开关 SQLite
|
|
2130
2260
|
if (Date.now() - tasksCountAt > 60_000) {
|
|
2131
2261
|
tasksCountAt = Date.now();
|
|
2132
2262
|
tasksCountCache = await countTasks(dataRoot);
|
|
2133
2263
|
}
|
|
2134
2264
|
global.tasks = tasksCountCache;
|
|
2135
|
-
json(res, 200, { ok: true, global, recentTurns });
|
|
2265
|
+
json(res, 200, { ok: true, global, recentTurns, ...(mu ? { sessionSummary: mu.summary } : {}) });
|
|
2266
|
+
return;
|
|
2267
|
+
}
|
|
2268
|
+
// —— 每轮用量(turn-usage.js):优先官方 turn_usage 每轮汇总,没有这张表时
|
|
2269
|
+
// 回退到 model_usage 主轮请求明细(旧版 ZCode 兼容) ——
|
|
2270
|
+
if (req.method === 'GET' && url.pathname === '/stats/turns') {
|
|
2271
|
+
const rawSid = url.searchParams.get('session') || '';
|
|
2272
|
+
const sessionId = /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(rawSid) ? rawSid : '';
|
|
2273
|
+
const turns = await listSessionTurnUsage(dataRoot, sessionId);
|
|
2274
|
+
const mu = turns || await listSessionModelUsage(dataRoot, sessionId);
|
|
2275
|
+
json(res, 200, { ok: true, rounds: mu.rounds, summary: mu.summary, ...(turns ? { turnMode: true, live: turns.live } : {}) });
|
|
2136
2276
|
return;
|
|
2137
2277
|
}
|
|
2138
2278
|
if (req.method === 'GET' && url.pathname === '/plugins/status') {
|
|
@@ -2140,9 +2280,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2140
2280
|
// 同一个市场目录会互相删对方的中间目录(ENOENT/坏目录)。
|
|
2141
2281
|
// 有更新任务在跑/排队时整个跳过(任务自身会做市场同步并刷新时间戳),
|
|
2142
2282
|
// 状态页轮询不排队等待、不能被长任务挂住;检查与入队在同一同步段内完成
|
|
2283
|
+
let marketAdd = null;
|
|
2143
2284
|
if (!pluginsUpdateJobs.size) {
|
|
2144
2285
|
await runPluginsQueued(async () => {
|
|
2145
|
-
await ensureZcodePluginsMarketplace();
|
|
2286
|
+
marketAdd = await ensureZcodePluginsMarketplace();
|
|
2146
2287
|
if (Date.now() - lastMarketplaceSync > 30 * 60 * 1000) {
|
|
2147
2288
|
await ensureZcodePluginsCloneFresh();
|
|
2148
2289
|
await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
|
|
@@ -2152,7 +2293,14 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2152
2293
|
}
|
|
2153
2294
|
const status = pluginUpdateStatus();
|
|
2154
2295
|
if (!status) {
|
|
2155
|
-
|
|
2296
|
+
// 带上市场添加失败的真实原因:新机器最常见的是连不上 GitHub / 没装 Git,
|
|
2297
|
+
// 设置面板和启动检查都靠这条信息提示用户,别再只给一句“读取失败”
|
|
2298
|
+
const failed = marketAdd && !marketAdd.ok ? marketAdd : null;
|
|
2299
|
+
json(res, 500, {
|
|
2300
|
+
ok: false,
|
|
2301
|
+
code: failed?.code || 'plugins-status',
|
|
2302
|
+
error: failed?.error || '读取插件清单失败(未安装过 zcode-plugins 市场?)',
|
|
2303
|
+
});
|
|
2156
2304
|
return;
|
|
2157
2305
|
}
|
|
2158
2306
|
json(res, 200, { ok: true, ...status });
|
|
@@ -2216,9 +2364,19 @@ let tasksCountCache = 0; // 任务总数缓存(/stats/usage 高频轮询,60
|
|
|
2216
2364
|
// ~/.zcode/cli/rollout/model-io-*.jsonl 每行一次模型调用;usage 字段有两种键风格
|
|
2217
2365
|
// (协议 camelCase 与原始 snake_case),两种都解析。文件小(个位数、每会话一个),
|
|
2218
2366
|
// 按 mtime+size 缓存只重读变过的文件;聚合结果含按日分桶(本地时区)供“今日”用
|
|
2219
|
-
const usageFileCache = new Map(); // 文件名 → { mtime, size, recs: [{at, ts, ms, in, out, cacheRead, session}] }
|
|
2367
|
+
const usageFileCache = new Map(); // 文件名 → { mtime, size, ino, goneAt, recs: [{at, ts, ms, in, out, cacheRead, session, trace}] }
|
|
2220
2368
|
// 测试缝:覆盖 rollout 记录目录(scripts/test-usage-stats.mjs 用假数据跑真实聚合)
|
|
2221
2369
|
let rolloutDirOverride = '';
|
|
2370
|
+
// 被滚动删除的会话文件,其解析记录在缓存里的保留时长
|
|
2371
|
+
const ROLLOUT_KEEP_MS = 2 * 3600_000;
|
|
2372
|
+
// 测试用:换目录即作废全部缓存,假数据与真实记录不混算
|
|
2373
|
+
export function setRolloutDirForTest(dir) {
|
|
2374
|
+
rolloutDirOverride = dir || '';
|
|
2375
|
+
usageFileCache.clear();
|
|
2376
|
+
rolloutRecsCache = null;
|
|
2377
|
+
rolloutSig = '';
|
|
2378
|
+
statsResultCache = { sig: '', key: '', result: null };
|
|
2379
|
+
}
|
|
2222
2380
|
// 记录合并结果缓存:文件签名(名称+mtime+size)没变就直接复用上次合并好的记录
|
|
2223
2381
|
let rolloutSig = '';
|
|
2224
2382
|
let rolloutRecsCache = null;
|
|
@@ -2289,6 +2447,7 @@ function parseRolloutLines(text) {
|
|
|
2289
2447
|
in: input, out: output,
|
|
2290
2448
|
cacheRead,
|
|
2291
2449
|
session: String(d.sessionId || ''),
|
|
2450
|
+
trace: String(d.traceId || ''), // 会话树(父会话+子代理)共享同一 trace
|
|
2292
2451
|
});
|
|
2293
2452
|
}
|
|
2294
2453
|
consumed += isTail ? Buffer.byteLength(line, 'utf8') : lineBytes;
|
|
@@ -2307,10 +2466,17 @@ function rolloutRecords() {
|
|
|
2307
2466
|
rolloutRecsCache = null;
|
|
2308
2467
|
return [];
|
|
2309
2468
|
}
|
|
2310
|
-
//
|
|
2469
|
+
// 官方会滚动删除会话文件(运行中的会话也会被删了重建,窗口期数据不断档),
|
|
2470
|
+
// 被删文件的解析记录在缓存里再留 ROLLOUT_KEEP_MS:速率停在最后的值而不是归零,
|
|
2471
|
+
// 累计数也不缩水;超时才淘汰,别让长跑进程无限积压(受控泄漏)
|
|
2311
2472
|
const nameSet = new Set(names); // Set 判定:文件数上千时 names.includes 是 O(F²)
|
|
2312
|
-
for (const k of usageFileCache
|
|
2313
|
-
if (
|
|
2473
|
+
for (const [k, v] of usageFileCache) {
|
|
2474
|
+
if (nameSet.has(k)) { v.goneAt = 0; continue; }
|
|
2475
|
+
if (!v.goneAt) { v.goneAt = Date.now(); continue; }
|
|
2476
|
+
if (Date.now() - v.goneAt > ROLLOUT_KEEP_MS) {
|
|
2477
|
+
usageFileCache.delete(k);
|
|
2478
|
+
rolloutSig = ''; // 记录变少了:作废合并缓存,强制重建
|
|
2479
|
+
}
|
|
2314
2480
|
}
|
|
2315
2481
|
const recs = [];
|
|
2316
2482
|
// 先取各文件 stat 并算签名:签名没变直接复用上次合并好的记录。shortcut:
|
|
@@ -2324,14 +2490,16 @@ function rolloutRecords() {
|
|
|
2324
2490
|
for (const [name, st] of stats) {
|
|
2325
2491
|
const full = join(dir, name);
|
|
2326
2492
|
const cached = usageFileCache.get(name);
|
|
2327
|
-
if (cached && cached.mtime === st.mtimeMs && cached.size === st.size) {
|
|
2493
|
+
if (cached && cached.mtime === st.mtimeMs && cached.size === st.size && cached.ino === st.ino) {
|
|
2328
2494
|
for (const r of cached.recs) recs.push(r); // 不用展开语法:单文件 13 万条会 RangeError
|
|
2329
2495
|
continue;
|
|
2330
2496
|
}
|
|
2331
2497
|
// 追加式增量解析:jsonl 只追加(流式输出期间当前会话文件持续增长,整文件
|
|
2332
2498
|
// 重读重解析一次可达数十毫秒)。从上次已完整解析的偏移续读新增部分;末行
|
|
2333
|
-
//
|
|
2334
|
-
|
|
2499
|
+
// 若是写入中途的半行会被丢弃且偏移不推进,下次变化时重读该行。
|
|
2500
|
+
// inode 也要求一致:文件被滚动删除后同名重建,旧偏移对不上新内容,
|
|
2501
|
+
// 续读会把半截 JSON 当坏行丢掉(实测运行中的会话也会被删了重建)
|
|
2502
|
+
if (cached && st.size > cached.size && st.mtimeMs >= cached.mtimeMs && cached.ino === st.ino) {
|
|
2335
2503
|
const fd = openSync(full, 'r');
|
|
2336
2504
|
let tail = '';
|
|
2337
2505
|
try {
|
|
@@ -2343,6 +2511,7 @@ function rolloutRecords() {
|
|
|
2343
2511
|
usageFileCache.set(name, {
|
|
2344
2512
|
mtime: st.mtimeMs,
|
|
2345
2513
|
size: cached.size + completeBytes,
|
|
2514
|
+
ino: st.ino,
|
|
2346
2515
|
recs: cached.recs.concat(added),
|
|
2347
2516
|
});
|
|
2348
2517
|
for (const r of cached.recs) recs.push(r);
|
|
@@ -2359,15 +2528,35 @@ function rolloutRecords() {
|
|
|
2359
2528
|
// 同样只把已完整解析的字节数记为偏移
|
|
2360
2529
|
parsedBytes = Math.min(r.completeBytes, Buffer.byteLength(text, 'utf8'));
|
|
2361
2530
|
} catch { /* 文件读失败跳过 */ }
|
|
2362
|
-
|
|
2531
|
+
// 同名重建(inode 变了):旧记录并进来——那是该会话真实发生过的调用;
|
|
2532
|
+
// 同 inode 的全量重读(截断等)仍整体替换
|
|
2533
|
+
const prior = cached && cached.ino !== st.ino ? cached.recs : [];
|
|
2534
|
+
usageFileCache.set(name, { mtime: st.mtimeMs, size: parsedBytes, ino: st.ino, recs: prior.concat(parsed) });
|
|
2535
|
+
for (const r of prior) recs.push(r);
|
|
2363
2536
|
for (const r of parsed) recs.push(r);
|
|
2364
2537
|
}
|
|
2538
|
+
// 已被滚动删除的文件:保留窗内的解析记录继续参与聚合
|
|
2539
|
+
for (const [k, v] of usageFileCache) {
|
|
2540
|
+
if (nameSet.has(k)) continue;
|
|
2541
|
+
for (const r of v.recs) recs.push(r);
|
|
2542
|
+
}
|
|
2365
2543
|
rolloutSig = sig;
|
|
2366
2544
|
rolloutRecsCache = recs;
|
|
2367
2545
|
return recs;
|
|
2368
2546
|
}
|
|
2369
2547
|
|
|
2370
|
-
|
|
2548
|
+
// 会话 → trace_id(官方 db.sqlite 的 session 表,父子会话树共享同一 trace):
|
|
2549
|
+
// 命中即缓存(会话的 trace 写入后不变);查不到不缓存,下轮再试
|
|
2550
|
+
const traceBySession = new Map();
|
|
2551
|
+
async function sessionTrace(dataRoot, sessionId) {
|
|
2552
|
+
if (traceBySession.has(sessionId)) return traceBySession.get(sessionId);
|
|
2553
|
+
const m = await listSessionsTrace(dataRoot, [sessionId]);
|
|
2554
|
+
const trace = m[sessionId] || '';
|
|
2555
|
+
if (trace) traceBySession.set(sessionId, trace);
|
|
2556
|
+
return trace;
|
|
2557
|
+
}
|
|
2558
|
+
|
|
2559
|
+
export function collectUsageStats(sessionId, wantTurns = true, treeTrace = '') {
|
|
2371
2560
|
const recs = rolloutRecords();
|
|
2372
2561
|
// 分钟桶只服务每轮统计(turn-usage 带 session 拉取),状态栏请求带 turns=0
|
|
2373
2562
|
// 跳过:省掉全记录分桶与 60 桶序列化(大记录集下每请求几十毫秒)
|
|
@@ -2376,7 +2565,7 @@ function collectUsageStats(sessionId, wantTurns = true) {
|
|
|
2376
2565
|
const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
|
|
2377
2566
|
// 记录没变(文件签名相同)+ 查询口径没变时直接复用上次聚合结果:锚定速率是
|
|
2378
2567
|
// 记录的纯函数(锚 = 最新完成时刻,不随请求时刻移动),跨午夜才要重算"今日"
|
|
2379
|
-
const cacheKey = `${sessionId || ''}|${wantTurns ? 1 : 0}|${todayKey}`;
|
|
2568
|
+
const cacheKey = `${sessionId || ''}|${wantTurns ? 1 : 0}|${treeTrace}|${todayKey}`;
|
|
2380
2569
|
if (statsResultCache.sig === rolloutSig && statsResultCache.key === cacheKey && statsResultCache.result) {
|
|
2381
2570
|
return statsResultCache.result;
|
|
2382
2571
|
}
|
|
@@ -2387,14 +2576,18 @@ function collectUsageStats(sessionId, wantTurns = true) {
|
|
|
2387
2576
|
// 最近 60 秒速率(状态栏 tokRate 项):token 按调用耗时摊到时间轴(完成
|
|
2388
2577
|
// 时刻往前 durationMs 一段),按窗口重叠比例折算,长调用完成瞬间不会出现
|
|
2389
2578
|
// 假尖峰。窗口以该口径最新一条记录的完成时刻为锚、往前 60 秒——回答结束
|
|
2390
|
-
//
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
//
|
|
2579
|
+
// 后锚不再移动,速率自然停在最后的值:不衰减归零;有新调用完成锚前移、
|
|
2580
|
+
// 数值刷新。文件被官方滚动删除后靠保留窗内的缓存记录维持显示
|
|
2581
|
+
//(shortcut: 重启/热替换后只剩存活文件的记录,全删完速率归零,等官方出持久数据源再换)。
|
|
2582
|
+
// 统计范围:带 ?session= 按会话树算——本会话 + 同 trace 的子代理会话
|
|
2583
|
+
//(子代理的模型调用是这个会话真实发生的输出,只算本会话 id 会让派了
|
|
2584
|
+
// 子代理的会话速率归零),treeTrace 查不到时退化为只算本会话;
|
|
2585
|
+
// 不带 ?session= 则全局。与每轮桶不同,辅助小调用也计入(它们是真实消耗)
|
|
2586
|
+
const inTree = (r) => !sessionId || r.session === sessionId || (!!treeTrace && r.trace === treeTrace);
|
|
2394
2587
|
const winMs = 60_000;
|
|
2395
2588
|
let anchor = 0;
|
|
2396
2589
|
for (const r of recs) {
|
|
2397
|
-
if (Number.isFinite(r.ts) && (
|
|
2590
|
+
if (Number.isFinite(r.ts) && inTree(r)) anchor = Math.max(anchor, r.ts);
|
|
2398
2591
|
}
|
|
2399
2592
|
const anchorFuture = anchor > Date.now(); // 未来时间戳:钳制值依赖请求时刻,结果不能缓存
|
|
2400
2593
|
anchor = Math.min(anchor, Date.now()); // 未来时间戳(时钟回拨等)别把锚拉到未来
|
|
@@ -2412,7 +2605,7 @@ function collectUsageStats(sessionId, wantTurns = true) {
|
|
|
2412
2605
|
if (day === todayKey) { global.todayTokens += total; global.todayOut += r.out; }
|
|
2413
2606
|
}
|
|
2414
2607
|
const end = r.ts;
|
|
2415
|
-
if (Number.isFinite(end) && (
|
|
2608
|
+
if (Number.isFinite(end) && inTree(r)) {
|
|
2416
2609
|
const dur = Math.max(r.ms || 0, 1); // 无耗时字段的旧记录按 1ms 点事件计
|
|
2417
2610
|
const overlap = Math.min(end, anchor) - Math.max(end - dur, anchor - winMs);
|
|
2418
2611
|
if (overlap > 0) {
|
|
@@ -3207,6 +3400,55 @@ export async function scanIdleBusy(paths, dataRoot) {
|
|
|
3207
3400
|
}
|
|
3208
3401
|
|
|
3209
3402
|
// Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
|
|
3403
|
+
// 后台 bash 任务扫描:运行中的任务进程把 /tmp/zcode-bash-*/<会话id>/call_*-stdout.log
|
|
3404
|
+
// 握在 stdout/stderr 上(实测 fd/1、fd/2),日志路径就带会话 id——按"有进程握着
|
|
3405
|
+
// 该文件"判定在跑,纯文件系统读取,不惊动会话进程。不能走会话快照:快照会把
|
|
3406
|
+
// 会话 resume 起来,逐会话轮询快照曾造成整夜 6600 次/小时 resume、内存暴涨。
|
|
3407
|
+
// 返回 { ok, jobs: [{ sessionId, jobId }] };平台不支持(无 /proc 且无 lsof)时 ok=false
|
|
3408
|
+
export function scanBackgroundBash(tmpDir = '/tmp', procDir = '/proc') {
|
|
3409
|
+
let files;
|
|
3410
|
+
try {
|
|
3411
|
+
files = new Map(); // 日志绝对路径 → { sessionId, jobId }
|
|
3412
|
+
for (const d of readdirSync(tmpDir)) {
|
|
3413
|
+
if (!d.startsWith('zcode-bash-')) continue;
|
|
3414
|
+
let sessDirs;
|
|
3415
|
+
try { sessDirs = readdirSync(join(tmpDir, d)); } catch { continue; }
|
|
3416
|
+
for (const sess of sessDirs) {
|
|
3417
|
+
if (!/^sess/.test(sess)) continue;
|
|
3418
|
+
let names;
|
|
3419
|
+
try { names = readdirSync(join(tmpDir, d, sess)); } catch { continue; }
|
|
3420
|
+
for (const n of names) {
|
|
3421
|
+
const m = n.match(/^call_(.+)-stdout\.log$/);
|
|
3422
|
+
if (m) files.set(join(tmpDir, d, sess, n), { sessionId: sess, jobId: m[1] });
|
|
3423
|
+
}
|
|
3424
|
+
}
|
|
3425
|
+
}
|
|
3426
|
+
} catch { return { ok: false, jobs: [] }; }
|
|
3427
|
+
if (!files.size) return { ok: true, jobs: [] };
|
|
3428
|
+
const hit = new Map(); // 文件 → 记录(同一任务的 stdout/stderr 两个 fd 去重)
|
|
3429
|
+
try {
|
|
3430
|
+
// Linux:/proc/*/fd/{1,2} 的符号链接命中即在跑
|
|
3431
|
+
for (const p of readdirSync(procDir)) {
|
|
3432
|
+
if (!/^\d+$/.test(p)) continue;
|
|
3433
|
+
for (const fd of ['1', '2']) {
|
|
3434
|
+
let target;
|
|
3435
|
+
try { target = readlinkSync(join(procDir, p, 'fd', fd)); } catch { continue; }
|
|
3436
|
+
const rec = files.get(target);
|
|
3437
|
+
if (rec) hit.set(target, rec);
|
|
3438
|
+
}
|
|
3439
|
+
}
|
|
3440
|
+
} catch {
|
|
3441
|
+
// 无 /proc(macOS):lsof -t 判文件是否被占用
|
|
3442
|
+
for (const f of files.keys()) {
|
|
3443
|
+
let r;
|
|
3444
|
+
try { r = spawnSync('lsof', ['-t', '--', f], { encoding: 'utf8', timeout: 3000 }); } catch { return { ok: false, jobs: [] }; }
|
|
3445
|
+
if (r.error) return { ok: false, jobs: [] };
|
|
3446
|
+
if ((r.stdout || '').trim()) hit.set(f, files.get(f));
|
|
3447
|
+
}
|
|
3448
|
+
}
|
|
3449
|
+
return { ok: true, jobs: [...hit.values()] };
|
|
3450
|
+
}
|
|
3451
|
+
|
|
3210
3452
|
function scanIdleBusyLinux(paths) {
|
|
3211
3453
|
let pids;
|
|
3212
3454
|
try { pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d)); }
|
|
@@ -4729,6 +4971,67 @@ export function parseHeadroomStatus(text) {
|
|
|
4729
4971
|
const HEADROOM_DIRECT_URL = 'https://open.bigmodel.cn/api/anthropic';
|
|
4730
4972
|
const HEADROOM_LOCAL_URL_RE = /^http:\/\/127\.0\.0\.1:\d+\/?$/;
|
|
4731
4973
|
|
|
4974
|
+
// —— Serena(语义代码分析 MCP):headroom 标签页的启用开关 ——
|
|
4975
|
+
// 开关写 ~/.zcode/cli/config.json 的 mcp.servers.serena,ZCode 新会话启动时加载,
|
|
4976
|
+
// 会话内即可用 find_symbol / find_referencing_symbols 等语义检索代替整文件读取。
|
|
4977
|
+
// 默认关闭:配置里没有 serena 条目就是关闭,不再另设布尔键。
|
|
4978
|
+
// 启动参数取 headroom 的 serena 集成:PyPI serena-agent 预编译 wheel(git 源码构建
|
|
4979
|
+
// 在部分文件系统下失败),--open-web-dashboard False 免得每次启动弹浏览器面板。
|
|
4980
|
+
// --project $CWD 把项目根钉在会话工作区($CWD 由桥替换成工作目录):不往上找
|
|
4981
|
+
// .git/.serena,谁的 home 有没有假项目都不影响(--project-from-cwd 往上撞到 home 的
|
|
4982
|
+
// .git 就把整个 home 当项目,各人 home 不同、没法逐台清);多仓库/多工作区父目录则由
|
|
4983
|
+
// agent 调 activate_project 挑具体那个。
|
|
4984
|
+
// 服务经 mcp-bridge.mjs 拉起:同一项目的多个会话共用一份 serena(一份语言服务器,不再
|
|
4985
|
+
// 互抢工作区、不会写坏缓存),不同项目各一份;空闲 30 分钟自退、最多保温 2 份、语言服
|
|
4986
|
+
// 务器起不来时自动清坏缓存。
|
|
4987
|
+
const SERENA_SERVICE_ARGS = ['--from', 'serena-agent', 'serena', 'start-mcp-server',
|
|
4988
|
+
'--project', '$CWD', '--context', 'ide-assistant', '--open-web-dashboard', 'False'];
|
|
4989
|
+
|
|
4990
|
+
function serenaServerSpec() {
|
|
4991
|
+
// 桥本身用 ZCode 自带的 Node 运行时跑(同 bin/zcode-pro 的做法,用户机器不用装 node);
|
|
4992
|
+
// 解析不到可执行文件时退回 PATH 的 node
|
|
4993
|
+
let command = 'node';
|
|
4994
|
+
try { command = resolveZcodeExecutable() || command; } catch { /* 找不到就用 PATH 的 node */ }
|
|
4995
|
+
const uvx = findBinFile(['uvx'], [join(homedir(), '.local', 'bin', 'uvx'), '/usr/local/bin/uvx', '/usr/bin/uvx'])
|
|
4996
|
+
|| 'uvx';
|
|
4997
|
+
const bridge = join(dirname(fileURLToPath(import.meta.url)), 'mcp-bridge.mjs');
|
|
4998
|
+
return {
|
|
4999
|
+
type: 'stdio',
|
|
5000
|
+
command,
|
|
5001
|
+
args: [bridge, '--', uvx, ...SERENA_SERVICE_ARGS],
|
|
5002
|
+
env: { ELECTRON_RUN_AS_NODE: '1', MCP_BRIDGE_IDLE_MS: '1800000' },
|
|
5003
|
+
timeoutMs: 60000,
|
|
5004
|
+
};
|
|
5005
|
+
}
|
|
5006
|
+
|
|
5007
|
+
export function serenaScan() {
|
|
5008
|
+
// cli/config.json 固定按主目录定位(同 /zcode-config),不跟 ZCODE_DATA_BASE_DIR 迁移
|
|
5009
|
+
const cfg = readZcodeConfig(join(zcodeDataRoot(), 'cli', 'config.json'));
|
|
5010
|
+
return { enabled: !!(cfg.mcp && cfg.mcp.servers && cfg.mcp.servers.serena) };
|
|
5011
|
+
}
|
|
5012
|
+
|
|
5013
|
+
// 切换 Serena:enable=true 写入 mcp.servers.serena,false 删掉该键。
|
|
5014
|
+
// 只动 serena 一个键,其它 MCP(如 mastergo)原样保留。
|
|
5015
|
+
export function setSerenaEnabled(enable) {
|
|
5016
|
+
const file = join(zcodeDataRoot(), 'cli', 'config.json');
|
|
5017
|
+
let cfg;
|
|
5018
|
+
try {
|
|
5019
|
+
cfg = JSON.parse(readFileSync(file, 'utf8'));
|
|
5020
|
+
} catch {
|
|
5021
|
+
// 文件存在但解析失败时拒绝写入:按空对象重写会把 provider 等配置清掉
|
|
5022
|
+
if (existsSync(file)) return { ok: false, code: 'serena-config-unreadable', error: 'ZCode 配置文件无法解析,已中止写入' };
|
|
5023
|
+
cfg = {};
|
|
5024
|
+
}
|
|
5025
|
+
const mcp = (cfg.mcp && typeof cfg.mcp === 'object' && !Array.isArray(cfg.mcp)) ? { ...cfg.mcp } : {};
|
|
5026
|
+
const servers = (mcp.servers && typeof mcp.servers === 'object' && !Array.isArray(mcp.servers)) ? { ...mcp.servers } : {};
|
|
5027
|
+
if (enable) servers.serena = serenaServerSpec();
|
|
5028
|
+
else delete servers.serena;
|
|
5029
|
+
mcp.servers = servers;
|
|
5030
|
+
cfg.mcp = mcp;
|
|
5031
|
+
writeJsonAtomic(file, cfg);
|
|
5032
|
+
return { ok: true, serena: serenaScan() };
|
|
5033
|
+
}
|
|
5034
|
+
|
|
4732
5035
|
// 扫描 v2/config.json(provider.<id>.options.baseURL)与 v2/provider_config.json
|
|
4733
5036
|
// (providerRules[].config.api.baseUrl),统计当前走本地代理的条目数
|
|
4734
5037
|
export function headroomUsageScan(dataRoot) {
|
|
@@ -4922,9 +5225,8 @@ export function pluginUpdateStatus() {
|
|
|
4922
5225
|
// 读 known_marketplaces.json 判断,缺失则跑 plugins marketplace add;add 退出后
|
|
4923
5226
|
// 验证登记结果,未登记则回退 git clone 到本地走目录源——node 26 下 CLI 的 GitHub
|
|
4924
5227
|
// 归档解包会挂死并以退出码 0 静默退出,add 看似成功、登记表却没写,不能只信退出码。
|
|
4925
|
-
//
|
|
4926
|
-
//
|
|
4927
|
-
let lastMarketplaceAddFail = 0;
|
|
5228
|
+
// 不做失败冷却:用户可能刚配好代理就要重试,限制次数只会让人以为一直装不上。
|
|
5229
|
+
// 返回 null = 已存在无需处理,{ ok } = 本次执行结果。
|
|
4928
5230
|
|
|
4929
5231
|
// 目录源回退的 git 克隆位置(sources/ 对 CLI 是无关目录,不干扰它自己的缓存布局)
|
|
4930
5232
|
function zcodePluginsSourceDir() {
|
|
@@ -4971,14 +5273,35 @@ async function addZcodePluginsMarketplaceFromClone() {
|
|
|
4971
5273
|
return runZcodeCli(['plugins', 'marketplace', 'add', zcodePluginsSourceDir()], 120000);
|
|
4972
5274
|
}
|
|
4973
5275
|
|
|
5276
|
+
// 市场添加失败的分类与提示:新机器常见两类原因——没装 Git、连不上 GitHub。
|
|
5277
|
+
// 提示放最前:toast 是单行截断,放末尾会被长长的命令错误挤掉;独立的 code 让
|
|
5278
|
+
// 英文界面也能显示对应说明(errText 对已登录的错误码用 errEn 文案)。
|
|
5279
|
+
export function marketplaceAddFailure(raw) {
|
|
5280
|
+
const text = String(raw || '');
|
|
5281
|
+
if (/spawn git ENOENT/i.test(text)) {
|
|
5282
|
+
return { code: 'plugins-market-git', hint: '本机没有 Git,且直连 GitHub 失败;请安装 Git,或在 ZCode Pro 设置 → 代理 填写代理地址后重试。' };
|
|
5283
|
+
}
|
|
5284
|
+
if (/fetch failed|ENOTFOUND|ECONN|ETIMEDOUT|Failed to materialize|Failed to connect|Could not (?:connect|resolve)|unable to access/i.test(text)) {
|
|
5285
|
+
return { code: 'plugins-market-network', hint: '当前网络访问不了 GitHub;如需要代理,请在 ZCode Pro 设置 → 代理 填写代理地址后重试。' };
|
|
5286
|
+
}
|
|
5287
|
+
return { code: '', hint: '' };
|
|
5288
|
+
}
|
|
5289
|
+
|
|
4974
5290
|
export async function ensureZcodePluginsMarketplace() {
|
|
4975
5291
|
if (zcodePluginsMarketplaceRegistered()) return null;
|
|
4976
|
-
if (Date.now() - lastMarketplaceAddFail < 30 * 60 * 1000) return { ok: false, cached: true, error: '上次添加市场失败,30 分钟内不再自动重试' };
|
|
4977
5292
|
let r = await runZcodeCli(['plugins', 'marketplace', 'add', ZCODE_PLUGINS_MARKETPLACE_SOURCE], 120000);
|
|
4978
5293
|
if (!zcodePluginsMarketplaceRegistered()) r = await addZcodePluginsMarketplaceFromClone();
|
|
4979
5294
|
const ok = r.ok && zcodePluginsMarketplaceRegistered();
|
|
4980
|
-
|
|
4981
|
-
return { ok, output: r.output, error:
|
|
5295
|
+
const raw = r.error || 'marketplace add 未生效:登记表里没有该市场';
|
|
5296
|
+
if (ok) return { ok, output: r.output, error: raw };
|
|
5297
|
+
const failure = marketplaceAddFailure(raw);
|
|
5298
|
+
const detail = raw.length > 300 ? `${raw.slice(0, 300)}…` : raw;
|
|
5299
|
+
return {
|
|
5300
|
+
ok,
|
|
5301
|
+
output: r.output,
|
|
5302
|
+
code: failure.code || undefined,
|
|
5303
|
+
error: failure.hint ? `${failure.hint} ${detail}` : detail,
|
|
5304
|
+
};
|
|
4982
5305
|
}
|
|
4983
5306
|
|
|
4984
5307
|
// /plugins/update 并发控制:启动自动更新、打开设置弹窗时的自动触发、手动按钮、
|
|
@@ -5018,7 +5341,7 @@ async function runPluginsUpdateJob(body) {
|
|
|
5018
5341
|
if (added) steps.push({ step: 'marketplace add', ok: added.ok, output: added.output || added.error });
|
|
5019
5342
|
if (added && !added.ok) {
|
|
5020
5343
|
// 市场没登记上时 update 必然报 Marketplace not found,别让它冒头顶掉真实错误
|
|
5021
|
-
return { status: 500, payload: { ok: false, code: 'plugins-update', error: added.error || added.output || 'marketplace add 失败', steps } };
|
|
5344
|
+
return { status: 500, payload: { ok: false, code: added.code || 'plugins-update', error: added.error || added.output || 'marketplace add 失败', steps } };
|
|
5022
5345
|
}
|
|
5023
5346
|
const pull = await ensureZcodePluginsCloneFresh();
|
|
5024
5347
|
const sync = await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
|