zcode-pro 1.8.2 → 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/README.en.md +1 -1
- package/README.md +1 -1
- package/dist/inject.js +3485 -144
- package/package.json +2 -2
- package/src/host/helper.mjs +762 -65
- package/src/host/taskIndex.mjs +123 -4
- package/src/inject/core.js +153 -21
- package/src/inject/features/auto-continue.js +574 -0
- package/src/inject/features/auto-rename.js +3 -3
- package/src/inject/features/idle-reclaim.js +31 -5
- package/src/inject/features/newtab-panels.js +10 -4
- package/src/inject/features/session-switch.js +170 -11
- package/src/inject/features/settings-dialog.js +123 -37
- package/src/inject/features/status-bar.js +25 -20
- package/src/inject/features/subagent-icon.js +114 -18
- package/src/inject/features/title-gen.js +3 -3
- package/src/inject/features/title-lock.js +2 -2
- package/src/inject/features/turn-usage.js +49 -15
- package/src/inject/index.js +2 -0
- package/src/inject/locales/ja.js +772 -0
- package/src/inject/locales/ko.js +772 -0
- package/src/inject/locales/ru.js +772 -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';
|
|
@@ -41,6 +41,11 @@ function defaultVisionFile() {
|
|
|
41
41
|
return join(homedir(), '.zcode', 'zcode-vision.json');
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// 自动继续(回合失败/截断自动续接)的配置:设置页“自动继续”标签读写此文件
|
|
45
|
+
function defaultAutoContinueFile() {
|
|
46
|
+
return join(homedir(), '.zcode', 'auto-continue.json');
|
|
47
|
+
}
|
|
48
|
+
|
|
44
49
|
// rtk 插件的状态目录(钩子按 ${RTK_DIR:-~/.zcode-rtk} 解析,这里保持一致)
|
|
45
50
|
function defaultRtkDir() {
|
|
46
51
|
return process.env.RTK_DIR || join(homedir(), '.zcode-rtk');
|
|
@@ -328,10 +333,16 @@ export function defaultConfig() {
|
|
|
328
333
|
},
|
|
329
334
|
// 空闲项目内存回收的判定时长(分钟,1–1440):项目无运行中会话、无后台命令
|
|
330
335
|
// 且非当前选中,持续满该时长后释放其会话进程
|
|
331
|
-
idleReclaimMinutes:
|
|
336
|
+
idleReclaimMinutes: 10,
|
|
337
|
+
// 旧版的默认 30 会随任意一次保存写进文件:用这个标记区分“旧默认落盘”和
|
|
338
|
+
// 用户显式设置的 30。首次读到没有标记的 30 时迁移到新默认 10
|
|
339
|
+
idleReclaimMinutesMigrated: true,
|
|
332
340
|
// 启动一次性回收的延后分钟(0–1440):应用启动会为每个恢复的项目预热进程,
|
|
333
341
|
// 到点把当时符合条件的项目一次收掉;0 = 启动后尽快回收一次
|
|
334
342
|
idleReclaimStartupMinutes: 5,
|
|
343
|
+
// 子代理活动判定时长(分钟,1–1440):超过该时长没有子代理活动视为结束,
|
|
344
|
+
// 不再查询官方结束记录、不亮机器人图标(subagent-icon.js)
|
|
345
|
+
subagentFreshMinutes: 60,
|
|
335
346
|
// 样式调整(设置弹窗“样式调整”标签页)。null = 不覆盖,跟随应用默认。
|
|
336
347
|
styles: {
|
|
337
348
|
thinkingRowGap: null, // 思考段落间距:“已工作/工作中”过程视图内各行的垂直间距(应用默认 20px)
|
|
@@ -449,11 +460,16 @@ export function loadConfig(configFile) {
|
|
|
449
460
|
configUnreadable = false; // 解析成功就复位:修好文件后自动恢复可写
|
|
450
461
|
const minutes = Number(saved.idleReclaimMinutes);
|
|
451
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;
|
|
452
466
|
return {
|
|
453
467
|
...defaultConfig(),
|
|
454
468
|
...saved,
|
|
455
|
-
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,
|
|
456
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,
|
|
457
473
|
features: { ...defaultConfig().features, ...(saved.features || {}) },
|
|
458
474
|
styles: migrateStyles(saved.styles),
|
|
459
475
|
aliases: { ...((saved.aliases && typeof saved.aliases === 'object') ? saved.aliases : {}) },
|
|
@@ -971,6 +987,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
971
987
|
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
972
988
|
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
973
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
|
+
}
|
|
974
993
|
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
975
994
|
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
976
995
|
}
|
|
@@ -1454,9 +1473,20 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1454
1473
|
json(res, 200, { ok: true, ids });
|
|
1455
1474
|
return;
|
|
1456
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
|
+
}
|
|
1457
1485
|
if (req.method === 'GET' && url.pathname === '/subagent-children') {
|
|
1458
1486
|
// 会话的子代理子会话及最近活动时间(含嵌套):子代理判活的主信号——
|
|
1459
|
-
//
|
|
1487
|
+
// 应用的运行记录会把还在跑的长跑子代理误记为结束;已结束且没有后续活动的
|
|
1488
|
+
// 子代理不返回(last_outcome + turn_usage),否则中断或继续对话后图标会
|
|
1489
|
+
// 一直亮着(subagent-icon.js)
|
|
1460
1490
|
const ids = (url.searchParams.get('ids') || '')
|
|
1461
1491
|
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
|
|
1462
1492
|
const children = ids.length ? await listSubagentChildrenActivity(dataRoot, ids) : [];
|
|
@@ -1544,7 +1574,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1544
1574
|
}
|
|
1545
1575
|
// —— 智能起名:配置读写 + 供应商列表 + 生成并写库 ——
|
|
1546
1576
|
if (req.method === 'GET' && url.pathname === '/title-gen') {
|
|
1547
|
-
|
|
1577
|
+
// 注入层带上它当前实际使用的界面语言:官方 setting.json 的语言切换有时
|
|
1578
|
+
// 不会立刻落盘,只靠文件判断会把日语界面当成英文
|
|
1579
|
+
const loc = titleGenLocaleKey(url.searchParams.get('locale')) || titleGenLocale();
|
|
1580
|
+
json(res, 200, { ok: true, titleGen: loadConfig(configFile).titleGen, defaultPrompt: titleGenDefaultPrompt(loc) });
|
|
1548
1581
|
return;
|
|
1549
1582
|
}
|
|
1550
1583
|
if (req.method === 'POST' && url.pathname === '/title-gen') {
|
|
@@ -1612,9 +1645,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1612
1645
|
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_),两种都认,
|
|
1613
1646
|
// 否则新形式会话的标题永远不会写入数据库
|
|
1614
1647
|
const sessId = typeof body?.sessId === 'string' && /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(body.sessId) ? body.sessId : '';
|
|
1648
|
+
const loc = titleGenLocaleKey(body?.locale) || '';
|
|
1615
1649
|
let title;
|
|
1616
1650
|
try {
|
|
1617
|
-
title = await generateTitleWith(cfg, text, dataRoot, sessId);
|
|
1651
|
+
title = await generateTitleWith(cfg, text, dataRoot, sessId, loc);
|
|
1618
1652
|
} catch (err) {
|
|
1619
1653
|
titleGenLog(dataRoot, `generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1620
1654
|
throw err; // 交给外层统一 500
|
|
@@ -1663,8 +1697,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1663
1697
|
return;
|
|
1664
1698
|
}
|
|
1665
1699
|
let title;
|
|
1700
|
+
const loc = titleGenLocaleKey(body?.locale) || '';
|
|
1666
1701
|
try {
|
|
1667
|
-
title = await generateTitleWith(cfg, material, dataRoot, sessId);
|
|
1702
|
+
title = await generateTitleWith(cfg, material, dataRoot, sessId, loc);
|
|
1668
1703
|
} catch (err) {
|
|
1669
1704
|
titleGenLog(dataRoot, `rename-generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1670
1705
|
throw err; // 交给外层统一 500
|
|
@@ -1729,6 +1764,266 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1729
1764
|
json(res, 200, { ok: true, config: cfg });
|
|
1730
1765
|
return;
|
|
1731
1766
|
}
|
|
1767
|
+
// auto-continue 配置已知键按类型收窄(文件缺失/键非法 → 跳过该项,由消费方回默认)
|
|
1768
|
+
function sanitizeAutoContinueConfig(raw) {
|
|
1769
|
+
const out = {};
|
|
1770
|
+
if (typeof raw.enabled === 'boolean') out.enabled = raw.enabled;
|
|
1771
|
+
if (typeof raw.continueText === 'string') out.continueText = raw.continueText.slice(0, 2000);
|
|
1772
|
+
if (raw.maxRetries !== undefined) out.maxRetries = clampInt(raw.maxRetries, 1, 50, 8);
|
|
1773
|
+
if (raw.cooldownBaseSec !== undefined) out.cooldownBaseSec = clampInt(raw.cooldownBaseSec, 0, 600, 10);
|
|
1774
|
+
if (raw.cooldownFactor !== undefined) out.cooldownFactor = clampInt(raw.cooldownFactor, 1, 10, 2);
|
|
1775
|
+
if (raw.cooldownMaxSec !== undefined) out.cooldownMaxSec = clampInt(raw.cooldownMaxSec, 1, 600, 60);
|
|
1776
|
+
if (raw.stuckAfterMin !== undefined) out.stuckAfterMin = clampInt(raw.stuckAfterMin, 5, 720, 30);
|
|
1777
|
+
if (raw.failedAfterMin !== undefined) out.failedAfterMin = clampInt(raw.failedAfterMin, 1, 60, 3);
|
|
1778
|
+
if (typeof raw.failedAutoFix === 'boolean') out.failedAutoFix = raw.failedAutoFix;
|
|
1779
|
+
for (const key of ['permanentPatterns', 'transientPatterns']) {
|
|
1780
|
+
if (Array.isArray(raw[key])) out[key] = raw[key].filter((x) => typeof x === 'string').slice(0, 200);
|
|
1781
|
+
}
|
|
1782
|
+
return out;
|
|
1783
|
+
}
|
|
1784
|
+
// 悬空任务扫描:识别三类卡死——
|
|
1785
|
+
// 终端:background_task.tracking.started 后一直等不到 terminal(只认 exec_*;
|
|
1786
|
+
// agent_* 从不发 terminal,按 spawned/completed 单独配对)。
|
|
1787
|
+
// 子代理:subagent.spawned 后等不到 subagent.completed;失败的子代理只落
|
|
1788
|
+
// turn.failed,所以子会话的 turn.completed/turn.failed 也算这个子代理终结。
|
|
1789
|
+
// 主轮:turn.started 后等不到 turn.completed/turn.failed;同一会话已经有
|
|
1790
|
+
// 终端/子代理条目时不再报主轮(一个原因只出一张卡)。等用户回答或等审批
|
|
1791
|
+
// 的回合没在跑,不算卡死。用户点停(v4.stop)会清掉该会话未完结的主轮。
|
|
1792
|
+
// 每条带 ageSec(从开始算)与 silenceSec(对应会话最后一条日志距今),阈值
|
|
1793
|
+
// 由前端按配置判断。按本地日期命名的当天与前一天两份日志都扫(跨天起步的
|
|
1794
|
+
// 任务在昨天那份里)。
|
|
1795
|
+
function findStuckTasks() {
|
|
1796
|
+
const dir = join(homedir(), '.zcode', 'cli', 'log');
|
|
1797
|
+
const openTasks = new Map(); // exec taskId -> { taskId, sessionId, startedAt }
|
|
1798
|
+
const openTurns = new Map(); // `${sessionId}|${turnId}` -> { turnId, sessionId, startedAt }
|
|
1799
|
+
const openSubs = new Map(); // agentId -> { agentId, sessionId, startedAt }
|
|
1800
|
+
const lastEvent = new Map(); // sessionId -> { ts, name, toolName }
|
|
1801
|
+
const turnFailed = new Map(); // sessionId -> 最近一次 turn.failed(附失败消息)
|
|
1802
|
+
const lastFailMsg = new Map(); // sessionId -> 最近一次请求失败的 statusMessage
|
|
1803
|
+
const lastStopMark = new Map(); // sessionId -> 最近一次 v4.stop.* 事件时间(用户点停的痕迹)
|
|
1804
|
+
const now = Date.now();
|
|
1805
|
+
const closeTurns = (sessionId, turnId) => {
|
|
1806
|
+
if (turnId) openTurns.delete(`${sessionId}|${turnId}`);
|
|
1807
|
+
else for (const [k, v] of openTurns) if (v.sessionId === sessionId) openTurns.delete(k);
|
|
1808
|
+
};
|
|
1809
|
+
for (const offset of [864e5, 0]) {
|
|
1810
|
+
// 日志按本地日期命名(不是 UTC):用本地日期拼文件名
|
|
1811
|
+
const d = new Date(now - offset);
|
|
1812
|
+
const name = `zcode-${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}.jsonl`;
|
|
1813
|
+
const file = join(dir, name);
|
|
1814
|
+
if (!existsSync(file)) continue;
|
|
1815
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
1816
|
+
if (!line) continue;
|
|
1817
|
+
const ts = line.match(/"timestamp":"([^"]+)"/)?.[1];
|
|
1818
|
+
const sid = line.match(/"sessionId":"([^"]+)"/)?.[1];
|
|
1819
|
+
const evName = line.match(/"event":"([^"]+)"/)?.[1];
|
|
1820
|
+
const toolName = line.match(/"toolName":"([^"]+)"/)?.[1];
|
|
1821
|
+
if (ts && sid) {
|
|
1822
|
+
const cur = lastEvent.get(sid);
|
|
1823
|
+
if (!cur || ts > cur.ts) lastEvent.set(sid, { ts, name: evName, toolName });
|
|
1824
|
+
}
|
|
1825
|
+
let e = null;
|
|
1826
|
+
const parse = () => {
|
|
1827
|
+
if (e === null) {
|
|
1828
|
+
try { e = JSON.parse(line); } catch { e = {}; }
|
|
1829
|
+
}
|
|
1830
|
+
return e;
|
|
1831
|
+
};
|
|
1832
|
+
if (line.includes('background_task.tracking.')) {
|
|
1833
|
+
const taskId = parse()?.context?.taskId;
|
|
1834
|
+
if (taskId && taskId.startsWith('exec_')) {
|
|
1835
|
+
if (evName === 'background_task.tracking.started') {
|
|
1836
|
+
openTasks.set(taskId, { taskId, sessionId: sid, startedAt: ts });
|
|
1837
|
+
} else if (evName === 'background_task.tracking.terminal') {
|
|
1838
|
+
openTasks.delete(taskId);
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
if (line.includes('"event":"subagent.spawned"') || line.includes('"event":"subagent.completed"')) {
|
|
1843
|
+
const agentId = parse()?.context?.agentId;
|
|
1844
|
+
if (agentId) {
|
|
1845
|
+
if (evName === 'subagent.spawned') openSubs.set(agentId, { agentId, sessionId: sid, startedAt: ts });
|
|
1846
|
+
else if (evName === 'subagent.completed') openSubs.delete(agentId);
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
if (line.includes('"event":"turn.started"') || line.includes('"event":"turn.completed"') || line.includes('"event":"turn.failed"') || line.includes('"event":"model.request.failed"')) {
|
|
1850
|
+
const p = parse();
|
|
1851
|
+
const turnId = p?.turnId || p?.context?.turnId;
|
|
1852
|
+
if (evName === 'turn.started' && sid && turnId) {
|
|
1853
|
+
openTurns.set(`${sid}|${turnId}`, { turnId, sessionId: sid, startedAt: ts });
|
|
1854
|
+
} else if (evName === 'turn.completed' || evName === 'turn.failed') {
|
|
1855
|
+
if (sid) closeTurns(sid, turnId);
|
|
1856
|
+
// 子代理会话的回合结束(成功或失败)也代表这个子代理结束了
|
|
1857
|
+
if (sid) {
|
|
1858
|
+
const agentId = sid.startsWith('sess_subagent_') ? sid.slice('sess_subagent_'.length) : p?.context?.agentId;
|
|
1859
|
+
if (agentId) openSubs.delete(agentId);
|
|
1860
|
+
}
|
|
1861
|
+
if (evName === 'turn.failed' && sid) {
|
|
1862
|
+
// 失败前 10 秒内点过停止 = 用户主动终止,不列入待救
|
|
1863
|
+
const stopped = lastStopMark.has(sid)
|
|
1864
|
+
&& Date.parse(ts) - lastStopMark.get(sid) <= 10_000;
|
|
1865
|
+
turnFailed.set(sid, { sessionId: sid, failedAt: ts, message: lastFailMsg.get(sid) || '', stopped });
|
|
1866
|
+
}
|
|
1867
|
+
} else if (evName === 'model.request.failed' && sid && p?.context?.statusMessage) {
|
|
1868
|
+
lastFailMsg.set(sid, String(p.context.statusMessage));
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
if (line.includes('"event":"v4.stop')) {
|
|
1872
|
+
const p = parse();
|
|
1873
|
+
if (p?.sessionId) {
|
|
1874
|
+
if (ts) lastStopMark.set(p.sessionId, Date.parse(ts));
|
|
1875
|
+
closeTurns(p.sessionId); // 用户主动停止的回合不再算卡死
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
const out = [];
|
|
1881
|
+
const lastTs = (sessionId, fallback) => Date.parse(lastEvent.get(sessionId)?.ts || fallback);
|
|
1882
|
+
const addStuck = (kind, item, silenceSessionId = item.sessionId) => {
|
|
1883
|
+
const ageSec = Math.round((now - Date.parse(item.startedAt)) / 1000);
|
|
1884
|
+
const silenceSec = Math.round((now - lastTs(silenceSessionId, item.startedAt)) / 1000);
|
|
1885
|
+
if (ageSec > 0 && ageSec < 24 * 3600) out.push({ ...item, kind, ageSec, silenceSec });
|
|
1886
|
+
};
|
|
1887
|
+
for (const t of openTasks.values()) addStuck('terminal', t);
|
|
1888
|
+
for (const s of openSubs.values()) {
|
|
1889
|
+
// 子代理自己的会话日志更能代表它是否还在动
|
|
1890
|
+
addStuck('subagent', { ...s, taskId: `subagent:${s.agentId}` }, `sess_subagent_${s.agentId}`);
|
|
1891
|
+
}
|
|
1892
|
+
const busySessions = new Set(out.map((t) => t.sessionId));
|
|
1893
|
+
for (const t of openTurns.values()) {
|
|
1894
|
+
const le = lastEvent.get(t.sessionId);
|
|
1895
|
+
// 等用户回答/等审批的回合没在跑,不算卡死
|
|
1896
|
+
if (le && (le.name === 'tool.permission.evaluated'
|
|
1897
|
+
|| ((le.name === 'tool.call.started' || le.name === 'tool.call.completed')
|
|
1898
|
+
&& (le.toolName === 'AskUserQuestion' || le.toolName === 'ExitPlanMode')))) continue;
|
|
1899
|
+
if (busySessions.has(t.sessionId)) continue;
|
|
1900
|
+
addStuck('turn', { ...t, taskId: `turn:${t.turnId}` });
|
|
1901
|
+
}
|
|
1902
|
+
// 失败会话:turn.failed 之后该会话再无实质动静(横幅规则、人工都没把它续上)。
|
|
1903
|
+
// 覆盖桌面当前视图之外的会话(手机端/后台的 v4 会话在界面里看不到横幅)。
|
|
1904
|
+
// 静默判定留 60 秒宽限:失败瞬间会跟一大串清理事件(mcp 连接释放、生命周期
|
|
1905
|
+
// 变更,实测能到 50+ 条、持续约 1 秒),把它们当“会话在动”会让这类失败永远
|
|
1906
|
+
// 不进待救清单;用户点停的(stopped)不救。
|
|
1907
|
+
const failed = [];
|
|
1908
|
+
for (const f of turnFailed.values()) {
|
|
1909
|
+
if (f.stopped) continue;
|
|
1910
|
+
const ageSec = Math.round((now - Date.parse(f.failedAt)) / 1000);
|
|
1911
|
+
const last = lastEvent.get(f.sessionId)?.ts || f.failedAt;
|
|
1912
|
+
const quietMs = Date.parse(last) - Date.parse(f.failedAt);
|
|
1913
|
+
if (ageSec > 0 && ageSec < 12 * 3600 && quietMs <= 60_000) failed.push({ ...f, ageSec });
|
|
1914
|
+
}
|
|
1915
|
+
return {
|
|
1916
|
+
tasks: out.sort((a, b) => b.ageSec - a.ageSec),
|
|
1917
|
+
failed: failed.sort((a, b) => b.ageSec - a.ageSec),
|
|
1918
|
+
};
|
|
1919
|
+
}
|
|
1920
|
+
// 会话当前的权限模式存在会话库的 runtime/execution_state 条目里(切模式时原地
|
|
1921
|
+
// 更新,一个会话一条)。无头 -p 不显式传 --mode 时默认 yolo(CLI 的
|
|
1922
|
+
// DEFAULT_HEADLESS_PROMPT_MODE),会把 build/plan 会话的权限提上去;读出来
|
|
1923
|
+
// 原样传给 --mode 才不改变用户设定的权限。读不到(旧会话、旧运行时没有
|
|
1924
|
+
// node:sqlite)返回 null,调用方退回原来的默认行为。
|
|
1925
|
+
async function readSessionMode(sessionId) {
|
|
1926
|
+
try {
|
|
1927
|
+
const dbFile = join(resolveDataRootDir(), 'cli', 'db', 'db.sqlite');
|
|
1928
|
+
if (!existsSync(dbFile)) return null;
|
|
1929
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
1930
|
+
const db = new DatabaseSync(dbFile, { readOnly: true, timeout: 2000 });
|
|
1931
|
+
try {
|
|
1932
|
+
const row = db
|
|
1933
|
+
.prepare(
|
|
1934
|
+
"select json_extract(data, '$.mode') as mode from session_entry where session_id = ? and type = 'runtime/execution_state' order by time_created desc limit 1",
|
|
1935
|
+
)
|
|
1936
|
+
.get(sessionId);
|
|
1937
|
+
return typeof row?.mode === 'string' ? row.mode : null;
|
|
1938
|
+
} finally {
|
|
1939
|
+
db.close();
|
|
1940
|
+
}
|
|
1941
|
+
} catch {
|
|
1942
|
+
return null;
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
// —— 自动继续:设置弹窗“自动继续”标签页读写 ~/.zcode/auto-continue.json
|
|
1946
|
+
// (回合失败/截断自动续接的开关与文案)——
|
|
1947
|
+
if (req.method === 'GET' && url.pathname === '/auto-continue') {
|
|
1948
|
+
const file = defaultAutoContinueFile();
|
|
1949
|
+
const parsed = readJsonFile(file);
|
|
1950
|
+
if (parsed === null && existsSync(file)) {
|
|
1951
|
+
json(res, 500, { ok: false, code: 'ac-read', error: 'auto-continue.json 不是合法 JSON' });
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
json(res, 200, { ok: true, config: parsed, file });
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
if (req.method === 'POST' && url.pathname === '/auto-continue') {
|
|
1958
|
+
const body = await readBody(req);
|
|
1959
|
+
const cfg = body?.config;
|
|
1960
|
+
if (!cfg || typeof cfg !== 'object') {
|
|
1961
|
+
json(res, 400, { ok: false, code: 'ac-invalid', error: '缺少 config 对象' });
|
|
1962
|
+
return;
|
|
1963
|
+
}
|
|
1964
|
+
try {
|
|
1965
|
+
const file = defaultAutoContinueFile();
|
|
1966
|
+
// 已知键按类型收窄后与磁盘旧配置合并(面板不认识的键不动)
|
|
1967
|
+
const merged = { ...(readJsonFile(file) || {}), ...sanitizeAutoContinueConfig(cfg) };
|
|
1968
|
+
const tmp = file + '.tmp';
|
|
1969
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
|
|
1970
|
+
renameSync(tmp, file);
|
|
1971
|
+
} catch (err2) {
|
|
1972
|
+
json(res, 500, { ok: false, code: 'ac-write', error: '写入 auto-continue.json 失败: ' + (err2?.message || err2) });
|
|
1973
|
+
return;
|
|
1974
|
+
}
|
|
1975
|
+
json(res, 200, { ok: true, config: cfg });
|
|
1976
|
+
return;
|
|
1977
|
+
}
|
|
1978
|
+
// —— auto-continue 看门狗:回合卡死(工具执行器悬死、无失败横幅)时的探测数据,
|
|
1979
|
+
// 返回悬空后台任务清单(started 后从未 terminal),注入层据此提示用户 ——
|
|
1980
|
+
if (req.method === 'GET' && url.pathname === '/ac-stuck') {
|
|
1981
|
+
const r = findStuckTasks();
|
|
1982
|
+
json(res, 200, { ok: true, tasks: r.tasks, failed: r.failed });
|
|
1983
|
+
return;
|
|
1984
|
+
}
|
|
1985
|
+
// —— auto-continue 无头续接:用 ZCode 核心运行时的 headless 模式(--resume + -p)
|
|
1986
|
+
// 把指定会话续上一轮,不碰桌面界面——子代理/自动化同款驱动方式,手机端/后台
|
|
1987
|
+
// 等界面外会话也能续。续接回合可能跑几分钟:启动即返回,成败由下一轮
|
|
1988
|
+
// /ac-stuck 的会话活跃度验证(续上 = 有新事件,失败 = 保持静默)——
|
|
1989
|
+
if (req.method === 'POST' && url.pathname === '/ac-continue') {
|
|
1990
|
+
const body = await readBody(req);
|
|
1991
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : '';
|
|
1992
|
+
const text = typeof body?.text === 'string' ? body.text.slice(0, 500) : '';
|
|
1993
|
+
if (!/^(sess_|session_)[A-Za-z0-9_-]+$/.test(sessionId) || !text.trim()) {
|
|
1994
|
+
json(res, 400, { ok: false, code: 'ac-continue-invalid', error: '缺少合法的 sessionId 或 text' });
|
|
1995
|
+
return;
|
|
1996
|
+
}
|
|
1997
|
+
const bundle = zcodeCliBundleCandidates().find((c) => existsSync(c));
|
|
1998
|
+
if (!bundle) {
|
|
1999
|
+
json(res, 500, { ok: false, code: 'cli-not-found', error: '未找到 ZCode CLI(resources/glm/zcode.cjs)' });
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
// 权限模式原样带过去:能读到的五种模式显式传 --mode,避免无头默认 yolo
|
|
2003
|
+
// 把用户在 build/plan 下的限制提上去。auto 是保留未实现的模式(所有工具
|
|
2004
|
+
// 一律拒绝),无头续接没有意义,直接告知调用方。
|
|
2005
|
+
const sessionMode = await readSessionMode(sessionId);
|
|
2006
|
+
if (sessionMode === 'auto') {
|
|
2007
|
+
json(res, 400, { ok: false, code: 'ac-mode-unsupported', error: '会话处于 auto 权限模式(尚未实现),不自动续接' });
|
|
2008
|
+
return;
|
|
2009
|
+
}
|
|
2010
|
+
const spawnArgs = [bundle, '--resume', sessionId, '-p', text, '--surface', 'terminal'];
|
|
2011
|
+
if (['build', 'edit', 'plan', 'yolo', 'guarded'].includes(sessionMode)) spawnArgs.push('--mode', sessionMode);
|
|
2012
|
+
try {
|
|
2013
|
+
// zcode-pro 本就跑在 ZCode 二进制上:ELECTRON_RUN_AS_NODE=1 直接拿它当 node 用
|
|
2014
|
+
spawn(process.execPath, spawnArgs, {
|
|
2015
|
+
detached: true,
|
|
2016
|
+
stdio: 'ignore',
|
|
2017
|
+
env: { ...process.env, ...proxyEnv({}, 'none'), ELECTRON_RUN_AS_NODE: '1', ...zcodeBuiltinConfigEnv(bundle) },
|
|
2018
|
+
windowsHide: true,
|
|
2019
|
+
}).on('error', () => { /* 启动失败由活跃度验证兜底 */ }).unref();
|
|
2020
|
+
} catch (err2) {
|
|
2021
|
+
json(res, 500, { ok: false, code: 'ac-continue-spawn', error: '启动无头续接失败: ' + (err2?.message || err2) });
|
|
2022
|
+
return;
|
|
2023
|
+
}
|
|
2024
|
+
json(res, 200, { ok: true, started: true });
|
|
2025
|
+
return;
|
|
2026
|
+
}
|
|
1732
2027
|
// 供应商下拉取数(视觉代理“供应商”组合框用):合并两张供应商表,只回 id/名称/别名,不含密钥
|
|
1733
2028
|
if (req.method === 'GET' && url.pathname === '/vision/providers') {
|
|
1734
2029
|
json(res, 200, { ok: true, providers: listVisionProviders() });
|
|
@@ -2347,7 +2642,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2347
2642
|
} catch (err) {
|
|
2348
2643
|
// 完整错误只进日志;响应里的消息抹掉主目录前缀,别把本机路径结构带出去
|
|
2349
2644
|
console.error('[zcodepro] 路由处理出错:', err);
|
|
2350
|
-
json(res, 500, { ok: false, error: String(err?.message || err).split(homedir()).join('~') });
|
|
2645
|
+
json(res, 500, { ok: false, code: err?.code, error: String(err?.message || err).split(homedir()).join('~') });
|
|
2351
2646
|
}
|
|
2352
2647
|
});
|
|
2353
2648
|
|
|
@@ -2675,7 +2970,9 @@ export function collectUsageStats(sessionId, wantTurns = true, treeTrace = '') {
|
|
|
2675
2970
|
|
|
2676
2971
|
function readJsonFile(p) {
|
|
2677
2972
|
try {
|
|
2678
|
-
|
|
2973
|
+
// Windows 记事本/PowerShell 保存的 JSON 带 UTF-8 BOM,JSON.parse 不认:先剥掉
|
|
2974
|
+
const text = readFileSync(p, 'utf-8');
|
|
2975
|
+
return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
|
|
2679
2976
|
} catch {
|
|
2680
2977
|
return null;
|
|
2681
2978
|
}
|
|
@@ -3367,9 +3664,9 @@ function applyFeaturesPartial(base, partial) {
|
|
|
3367
3664
|
return out;
|
|
3368
3665
|
}
|
|
3369
3666
|
|
|
3370
|
-
// 空闲回收的后台命令判定:项目会话进程(zcode-cli)的子进程里,插件/MCP
|
|
3371
|
-
//
|
|
3372
|
-
//
|
|
3667
|
+
// 空闲回收的后台命令判定:项目会话进程(zcode-cli)的子进程里,插件/MCP、应用
|
|
3668
|
+
// 自身组件与会话自己拉起的空闲 worker 不算活动;其余(应用的 shell 包装 exec/、
|
|
3669
|
+
// 用户直接启动的进程)一律视为仍在运行的后台命令。
|
|
3373
3670
|
// 匹配前把命令行的反斜杠统一为正斜杠,一份模式通吃三平台。
|
|
3374
3671
|
const IDLE_INFRA_CMDLINE = [
|
|
3375
3672
|
'/.zcode/cli/plugins/', // 插件市场安装的 MCP/hooks(vision、headroom、rtk 等)
|
|
@@ -3384,6 +3681,12 @@ const IDLE_INFRA_CMDLINE = [
|
|
|
3384
3681
|
|
|
3385
3682
|
const SCAN_OFF = { ok: true, scan: false, busy: [] };
|
|
3386
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
|
+
|
|
3387
3690
|
function normCmdline(s) {
|
|
3388
3691
|
return String(s || '').replace(/\\/g, '/');
|
|
3389
3692
|
}
|
|
@@ -3430,7 +3733,6 @@ export async function scanIdleBusy(paths, dataRoot) {
|
|
|
3430
3733
|
return SCAN_OFF;
|
|
3431
3734
|
}
|
|
3432
3735
|
|
|
3433
|
-
// Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
|
|
3434
3736
|
// 后台 bash 任务扫描:运行中的任务进程把 /tmp/zcode-bash-*/<会话id>/call_*-stdout.log
|
|
3435
3737
|
// 握在 stdout/stderr 上(实测 fd/1、fd/2),日志路径就带会话 id——按"有进程握着
|
|
3436
3738
|
// 该文件"判定在跑,纯文件系统读取,不惊动会话进程。不能走会话快照:快照会把
|
|
@@ -3480,7 +3782,93 @@ export function scanBackgroundBash(tmpDir = '/tmp', procDir = '/proc') {
|
|
|
3480
3782
|
return { ok: true, jobs: [...hit.values()] };
|
|
3481
3783
|
}
|
|
3482
3784
|
|
|
3483
|
-
|
|
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
|
+
|
|
3870
|
+
// Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
|
|
3871
|
+
async function scanIdleBusyLinux(paths) {
|
|
3484
3872
|
let pids;
|
|
3485
3873
|
try { pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d)); }
|
|
3486
3874
|
catch { return SCAN_OFF; }
|
|
@@ -3497,44 +3885,117 @@ function scanIdleBusyLinux(paths) {
|
|
|
3497
3885
|
} catch { /* 进程退出/权限:跳过 */ }
|
|
3498
3886
|
}
|
|
3499
3887
|
const busy = new Set();
|
|
3888
|
+
const workers = []; // 暂无活动的 agent worker:稍后采样 CPU 再定
|
|
3500
3889
|
for (const [cwd, cliPids] of cliPidByCwd) {
|
|
3501
3890
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
3502
3891
|
if (!wantedPaths) continue;
|
|
3503
3892
|
for (const pid of cliPids) {
|
|
3504
|
-
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
|
|
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;
|
|
3510
3902
|
let cmdline = '';
|
|
3511
|
-
let
|
|
3903
|
+
let comm = '';
|
|
3512
3904
|
try {
|
|
3513
3905
|
cmdline = normCmdline(readFileSync(`/proc/${childPid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim());
|
|
3514
|
-
|
|
3515
|
-
zombie = /\) Z /.test(stat);
|
|
3906
|
+
comm = readFileSync(`/proc/${childPid}/comm`, 'utf8').trim();
|
|
3516
3907
|
} catch { continue; }
|
|
3517
|
-
if (
|
|
3518
|
-
|
|
3519
|
-
|
|
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); // 认不出的进程宁可误判为忙
|
|
3520
3921
|
break;
|
|
3521
3922
|
}
|
|
3923
|
+
for (const wp of wantedPaths) busy.add(wp); // 认不出的进程宁可误判为忙,也不回收可能在跑命令的项目
|
|
3924
|
+
break;
|
|
3522
3925
|
}
|
|
3523
3926
|
}
|
|
3524
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
|
+
}
|
|
3525
3939
|
return { ok: true, scan: true, busy: [...busy] };
|
|
3526
3940
|
}
|
|
3527
3941
|
|
|
3528
|
-
|
|
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 进程的工作目录。
|
|
3529
3990
|
// 都是系统自带工具、本用户进程无需提权。任何一个 CLI 的工作目录取不到就本轮放弃
|
|
3530
3991
|
// (scan=false),宁可不动也不猜
|
|
3531
3992
|
async function scanIdleBusyDarwin(paths) {
|
|
3532
|
-
const psInfo = await runCmd('ps', ['-axo', 'pid=,ppid=,stat=,comm=']);
|
|
3993
|
+
const psInfo = await runCmd('ps', ['-axo', 'pid=,ppid=,stat=,time=,comm=']);
|
|
3533
3994
|
if (psInfo.err) return SCAN_OFF;
|
|
3534
3995
|
const procs = [];
|
|
3535
3996
|
for (const line of psInfo.stdout.split('\n')) {
|
|
3536
|
-
const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/);
|
|
3537
|
-
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() });
|
|
3538
3999
|
}
|
|
3539
4000
|
const clis = procs.filter((p) => /(^|\/)zcode-cli$/.test(p.comm));
|
|
3540
4001
|
if (!clis.length) return SCAN_OFF; // 定位不到会话进程:可能名称对不上,不猜
|
|
@@ -3546,7 +4007,12 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
3546
4007
|
if (m) cmdByPid.set(Number(m[1]), m[2]);
|
|
3547
4008
|
}
|
|
3548
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]));
|
|
3549
4014
|
const busy = new Set();
|
|
4015
|
+
const workers = [];
|
|
3550
4016
|
for (const cli of clis) {
|
|
3551
4017
|
const lsof = await runCmd('lsof', ['-a', '-p', String(cli.pid), '-d', 'cwd', '-Fn', '-w']);
|
|
3552
4018
|
// 与注释的约定一致:任一 CLI 的工作目录取不到就整轮放弃(scan=false)——
|
|
@@ -3559,9 +4025,38 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
3559
4025
|
for (const child of procs) {
|
|
3560
4026
|
if (child.ppid !== cli.pid || child.stat.includes('Z')) continue;
|
|
3561
4027
|
const cmdline = normCmdline(cmdByPid.get(child.pid) || '');
|
|
3562
|
-
if (
|
|
3563
|
-
|
|
3564
|
-
|
|
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);
|
|
3565
4060
|
}
|
|
3566
4061
|
}
|
|
3567
4062
|
}
|
|
@@ -3591,36 +4086,116 @@ async function scanIdleBusyWindows(paths, dataRoot) {
|
|
|
3591
4086
|
name: String(p.Name || ''),
|
|
3592
4087
|
cmdline: normCmdline(p.CommandLine || ''),
|
|
3593
4088
|
}));
|
|
3594
|
-
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
|
+
};
|
|
3595
4121
|
const lookupTaskWs = async (taskId) => {
|
|
3596
|
-
if (
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
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]);
|
|
3600
4127
|
}
|
|
3601
|
-
return
|
|
4128
|
+
return undefined;
|
|
3602
4129
|
};
|
|
3603
4130
|
return classifyIdleBusyWindows(procs, paths, lookupTaskWs);
|
|
3604
4131
|
}
|
|
3605
4132
|
|
|
3606
|
-
// 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
|
+
// 没有子进程时与空闲无法区分,这一层依靠调用方的官方活跃会话判定兜底。
|
|
3607
4145
|
export async function classifyIdleBusyWindows(procs, paths, lookupTaskWs) {
|
|
3608
4146
|
const clis = procs.filter((p) => /^zcode-cli(\.exe)?$/i.test(p.name));
|
|
3609
4147
|
if (!clis.length) return SCAN_OFF; // 定位不到会话进程:可能名称对不上,不猜
|
|
3610
4148
|
const reqByNorm = new Map();
|
|
3611
|
-
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
|
+
}
|
|
3612
4156
|
let unattributed = false;
|
|
3613
4157
|
const busy = new Set();
|
|
3614
4158
|
const markByTask = async (taskId) => {
|
|
3615
4159
|
const normWs = await lookupTaskWs(taskId);
|
|
3616
|
-
|
|
4160
|
+
// 归属明确但不在本轮请求的项目里(Windows 会扫全机所有会话进程):与本轮
|
|
4161
|
+
// 判定无关,不能据此把其他项目全部判忙
|
|
4162
|
+
if (!normWs) { unattributed = true; return; }
|
|
4163
|
+
const req = reqByNorm.get(normWs);
|
|
3617
4164
|
if (req) busy.add(req);
|
|
3618
|
-
|
|
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
|
+
}
|
|
3619
4181
|
};
|
|
3620
4182
|
for (const cli of clis) {
|
|
3621
4183
|
for (const child of procs) {
|
|
3622
4184
|
if (child.ppid !== cli.pid) continue;
|
|
3623
|
-
|
|
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;
|
|
3624
4199
|
if (!child.cmdline) { unattributed = true; continue; }
|
|
3625
4200
|
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_);字符集与
|
|
3626
4201
|
// 路由校验的 id 白名单一致(含 . 和 _)——字符类偏窄会在这些字符处截断成
|
|
@@ -3694,8 +4269,8 @@ export function listVisionProviders() {
|
|
|
3694
4269
|
|
|
3695
4270
|
// —— 智能起名:供应商取数、模型调用与标题清洗 ——
|
|
3696
4271
|
|
|
3697
|
-
//
|
|
3698
|
-
//
|
|
4272
|
+
// 内置默认提示词(用户可在设置弹窗覆盖),按界面语言取对应语言版本。
|
|
4273
|
+
// 英文/韩文/俄文按词数限制,中文和日文按字数/词数习惯收紧,保证会话列表里放得下
|
|
3699
4274
|
const TITLE_GEN_DEFAULT_PROMPTS = {
|
|
3700
4275
|
zh: [
|
|
3701
4276
|
'为下面的会话生成一个简短的标题。',
|
|
@@ -3719,21 +4294,80 @@ const TITLE_GEN_DEFAULT_PROMPTS = {
|
|
|
3719
4294
|
'- Do not copy or truncate the user\'s message as the title',
|
|
3720
4295
|
'- Output only the title itself: no explanation, no quotes, no trailing punctuation, no markdown',
|
|
3721
4296
|
].join('\n'),
|
|
4297
|
+
ja: [
|
|
4298
|
+
'以下のセッションに短いタイトルを付けてください。',
|
|
4299
|
+
'要件:',
|
|
4300
|
+
'- ユーザーのメッセージで使われている主な言語に合わせる(日本語のメッセージなら日本語のタイトル)',
|
|
4301
|
+
'- ユーザーが行おうとしている主な作業やテーマを要約する(回答や結果は書かない)',
|
|
4302
|
+
'- 通常10〜20文字程度で、セッション一覧でひと目で分かる長さにする',
|
|
4303
|
+
'- 重要な固有名詞(ファイル名、製品名、技術用語などがあれば)は残す',
|
|
4304
|
+
'- `ユーザーの依頼`、`新しいタスク`、`質問`のような曖昧なタイトルは使わない',
|
|
4305
|
+
'- ユーザーのメッセージをそのまま繰り返したり、一部を切り取ったりしない',
|
|
4306
|
+
'- タイトルだけを出力する:説明、引用符、末尾の句読点、Markdown は付けない',
|
|
4307
|
+
].join('\n'),
|
|
4308
|
+
ko: [
|
|
4309
|
+
'아래 세션에 짧은 제목을 붙여 주세요.',
|
|
4310
|
+
'요구 사항:',
|
|
4311
|
+
'- 사용자 메시지의 주된 언어를 사용하세요(한국어 메시지면 한국어 제목).',
|
|
4312
|
+
'- 사용자가 하려는 주요 작업이나 주제를 요약하고, 답이나 결과는 쓰지 마세요.',
|
|
4313
|
+
'- 보통 3~8단어로, 세션 목록에서 한눈에 알아볼 수 있는 길이로 하세요.',
|
|
4314
|
+
'- 중요한 고유명사(파일명, 제품명, 기술 용어 등)는 유지하세요.',
|
|
4315
|
+
'- `사용자 요청`, `새 작업`, `질문` 같은 두루뭉술한 제목은 쓰지 마세요.',
|
|
4316
|
+
'- 사용자 메시지를 그대로 반복하거나 잘라서 제목으로 쓰지 마세요.',
|
|
4317
|
+
'- 제목만 출력하세요. 설명, 따옴표, 끝 문장부호, 마크다운은 붙이지 마세요.',
|
|
4318
|
+
].join('\n'),
|
|
4319
|
+
ru: [
|
|
4320
|
+
'Придумайте короткое название для сессии ниже.',
|
|
4321
|
+
'Требования:',
|
|
4322
|
+
'- Используйте основной язык сообщения пользователя (для сообщения на русском — название на русском).',
|
|
4323
|
+
'- Кратко передайте основную задачу или тему пользователя; не приводите ответ или результат.',
|
|
4324
|
+
'- Обычно 3–8 слов, чтобы название легко узнавалось в списке сессий.',
|
|
4325
|
+
'- Сохраняйте важные имена собственные (имена файлов, названия продуктов, технические термины), если они есть.',
|
|
4326
|
+
'- Избегайте общих названий вроде «Запрос пользователя», «Новая задача» или «Вопрос».',
|
|
4327
|
+
'- Не копируйте и не обрезайте сообщение пользователя как название.',
|
|
4328
|
+
'- Выводите только само название: без пояснений, кавычек, завершающей пунктуации и Markdown.',
|
|
4329
|
+
].join('\n'),
|
|
3722
4330
|
};
|
|
3723
4331
|
|
|
3724
|
-
// 界面语言:桌面设置(v2/setting.json 的 localePreference
|
|
3725
|
-
//
|
|
4332
|
+
// 界面语言:桌面设置(v2/setting.json 的 localePreference)为官方五种语言时直接采用;
|
|
4333
|
+
// system 或未设置时优先用官方已解析的 locale,再按系统环境语言判断,未识别的回退英文
|
|
4334
|
+
const titleGenLocaleKey = (v) => {
|
|
4335
|
+
const s = String(v || '').trim().toLowerCase();
|
|
4336
|
+
return s.startsWith('zh') ? 'zh'
|
|
4337
|
+
: s.startsWith('ja') ? 'ja'
|
|
4338
|
+
: s.startsWith('ko') ? 'ko'
|
|
4339
|
+
: s.startsWith('ru') ? 'ru'
|
|
4340
|
+
: s.startsWith('en') ? 'en' : '';
|
|
4341
|
+
};
|
|
4342
|
+
// 3.18.2 起真正的五种语言写在 uiLocale*;旧字段 locale/localePreference 只保留
|
|
4343
|
+
// zh-CN / en-US 兼容值(ja/ko/ru 会写成 en-US),必须优先读新字段
|
|
4344
|
+
export function titleGenLocaleFromSettings(s) {
|
|
4345
|
+
const byUiPref = titleGenLocaleKey(s && s.uiLocalePreference);
|
|
4346
|
+
if (byUiPref) return byUiPref;
|
|
4347
|
+
const byUi = titleGenLocaleKey(s && s.uiLocale);
|
|
4348
|
+
if (byUi) return byUi;
|
|
4349
|
+
const byPref = titleGenLocaleKey(s && s.localePreference);
|
|
4350
|
+
if (byPref) return byPref;
|
|
4351
|
+
const byResolved = titleGenLocaleKey(s && s.locale);
|
|
4352
|
+
if (byResolved) return byResolved;
|
|
4353
|
+
return '';
|
|
4354
|
+
}
|
|
3726
4355
|
function titleGenLocale() {
|
|
3727
4356
|
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移(同 startHelper 的 settingsFile)
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
4357
|
+
return titleGenLocaleFromSettings(s)
|
|
4358
|
+
|| titleGenLocaleKey(process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG)
|
|
4359
|
+
|| 'en';
|
|
4360
|
+
}
|
|
4361
|
+
|
|
4362
|
+
function titleGenDefaultPrompt(locale) {
|
|
4363
|
+
return TITLE_GEN_DEFAULT_PROMPTS[locale || titleGenLocale()] || TITLE_GEN_DEFAULT_PROMPTS.en;
|
|
3733
4364
|
}
|
|
3734
4365
|
|
|
3735
|
-
|
|
3736
|
-
|
|
4366
|
+
// 没有保存过提示词时才用当前语言的默认值;已保存的值(包括旧语言的内置默认)保持不变。
|
|
4367
|
+
// 用户想换成当前语言的默认值,在设置页点“使用默认提示词”重新取。
|
|
4368
|
+
function titleGenPromptFor(value, locale) {
|
|
4369
|
+
const text = String(value || '');
|
|
4370
|
+
return text.trim() ? text : titleGenDefaultPrompt(locale);
|
|
3737
4371
|
}
|
|
3738
4372
|
|
|
3739
4373
|
const TITLE_GEN_MAX_TEXT = 1200; // 用户消息送入模型的长度上限(与官方起名一致)
|
|
@@ -3872,11 +4506,19 @@ async function callAnthropicText(baseUrl, apiKey, model, content) {
|
|
|
3872
4506
|
const doc = JSON.parse(body);
|
|
3873
4507
|
const text = Array.isArray(doc.content)
|
|
3874
4508
|
? doc.content.filter((b) => b && b.type === 'text').map((b) => b.text || '').join('') : '';
|
|
3875
|
-
if (!text)
|
|
3876
|
-
|
|
4509
|
+
if (!text) {
|
|
4510
|
+
const e = new Error(doc.stop_reason === 'max_tokens'
|
|
4511
|
+
? '模型的思考用完了输出上限,仍未给出标题' : '响应中没有文本内容');
|
|
4512
|
+
e.code = doc.stop_reason === 'max_tokens' ? 'title-gen-thinking' : 'title-gen-empty';
|
|
4513
|
+
throw e;
|
|
4514
|
+
}
|
|
3877
4515
|
return text;
|
|
3878
4516
|
} catch (err) {
|
|
3879
|
-
if (err && err.name === 'AbortError')
|
|
4517
|
+
if (err && err.name === 'AbortError') {
|
|
4518
|
+
const e = new Error(`请求超时(${Math.round(TITLE_GEN_TIMEOUT_MS / 1000)} 秒)`);
|
|
4519
|
+
e.code = 'title-gen-timeout';
|
|
4520
|
+
throw e;
|
|
4521
|
+
}
|
|
3880
4522
|
throw err;
|
|
3881
4523
|
} finally { clearTimeout(timer); }
|
|
3882
4524
|
}
|
|
@@ -3897,10 +4539,18 @@ async function callOpenAiText(baseUrl, apiKey, model, content) {
|
|
|
3897
4539
|
if (!resp.ok) throw new Error(`HTTP ${resp.status} [model=${model}]: ${body.slice(0, 300)}`);
|
|
3898
4540
|
const doc = JSON.parse(body);
|
|
3899
4541
|
const text = doc.choices?.[0]?.message?.content || '';
|
|
3900
|
-
if (typeof text !== 'string' || !text.trim())
|
|
4542
|
+
if (typeof text !== 'string' || !text.trim()) {
|
|
4543
|
+
const e = new Error('响应中没有文本内容');
|
|
4544
|
+
e.code = 'title-gen-empty';
|
|
4545
|
+
throw e;
|
|
4546
|
+
}
|
|
3901
4547
|
return text;
|
|
3902
4548
|
} catch (err) {
|
|
3903
|
-
if (err && err.name === 'AbortError')
|
|
4549
|
+
if (err && err.name === 'AbortError') {
|
|
4550
|
+
const e = new Error(`请求超时(${Math.round(TITLE_GEN_TIMEOUT_MS / 1000)} 秒)`);
|
|
4551
|
+
e.code = 'title-gen-timeout';
|
|
4552
|
+
throw e;
|
|
4553
|
+
}
|
|
3904
4554
|
throw err;
|
|
3905
4555
|
} finally { clearTimeout(timer); }
|
|
3906
4556
|
}
|
|
@@ -3963,21 +4613,35 @@ export async function writeGeneratedTitle(dataRoot, configFile, sessId, title, {
|
|
|
3963
4613
|
return { written, store };
|
|
3964
4614
|
}
|
|
3965
4615
|
|
|
4616
|
+
// 起名提示词里的固定上下文(日期行、用户消息标签)也跟随界面语言,
|
|
4617
|
+
// 避免非中文用户看到中文包装文本
|
|
4618
|
+
const TITLE_GEN_PROMPT_LABELS = {
|
|
4619
|
+
zh: { date: (d, m) => `当前日期(Asia/Shanghai):${d}(MMDD 即 ${m})`, user: '会话的用户消息:' },
|
|
4620
|
+
en: { date: (d, m) => `Current date (Asia/Shanghai): ${d} (MMDD = ${m})`, user: "The session's user messages:" },
|
|
4621
|
+
ja: { date: (d, m) => `現在の日付(Asia/Shanghai):${d}(MMDD は ${m})`, user: 'セッションのユーザーメッセージ:' },
|
|
4622
|
+
ko: { date: (d, m) => `현재 날짜(Asia/Shanghai): ${d} (MMDD = ${m})`, user: '세션의 사용자 메시지:' },
|
|
4623
|
+
ru: { date: (d, m) => `Текущая дата (Asia/Shanghai): ${d} (MMDD = ${m})`, user: 'Сообщения пользователя в сессии:' },
|
|
4624
|
+
};
|
|
4625
|
+
|
|
3966
4626
|
// 生成标题。provider 三种取值:
|
|
3967
4627
|
// - 'session':跟随当前会话——从任务索引解析该会话正在用的供应商与模型
|
|
3968
4628
|
// (model 已填时用填写的),供应商需在可直连列表内;
|
|
3969
4629
|
// - '':不跟随,用配置里的 baseUrl/apiKey/format 直连;
|
|
3970
4630
|
// - 供应商 id:按列表解析直连;id 已被删时退回保存时留下的地址/密钥副本。
|
|
3971
4631
|
// 输出统一清洗为单行短标题。导出以便测试
|
|
3972
|
-
export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = '') {
|
|
4632
|
+
export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = '', locale = '') {
|
|
3973
4633
|
const text = String(rawText || '').trim().replace(/\s+/g, ' ').slice(0, TITLE_GEN_MAX_TEXT);
|
|
3974
|
-
const
|
|
4634
|
+
const loc = titleGenLocaleKey(locale) || titleGenLocale();
|
|
4635
|
+
const prompt = titleGenPromptFor(cfg.prompt, loc);
|
|
3975
4636
|
// 注入当前日期(上海时区):起名模型是无状态的,自定义提示词里要求
|
|
3976
4637
|
// “MMDD 取对话创建日期”时它无从得知,只能留字面量 MMDD
|
|
3977
4638
|
const now = new Date(Date.now() + 8 * 3600 * 1000);
|
|
3978
4639
|
const pad = (n) => String(n).padStart(2, '0');
|
|
3979
|
-
const
|
|
3980
|
-
const
|
|
4640
|
+
const labels = TITLE_GEN_PROMPT_LABELS[loc] || TITLE_GEN_PROMPT_LABELS.en;
|
|
4641
|
+
const ymd = `${now.getUTCFullYear()}-${pad(now.getUTCMonth() + 1)}-${pad(now.getUTCDate())}`;
|
|
4642
|
+
const md = `${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}`;
|
|
4643
|
+
const dateLine = labels.date(ymd, md);
|
|
4644
|
+
const userContent = `${prompt}\n\n${dateLine}\n\n${labels.user}\n${text}`;
|
|
3981
4645
|
const providerId = (cfg.provider || '').trim();
|
|
3982
4646
|
const model = (cfg.model || '').trim();
|
|
3983
4647
|
const conn = await resolveTitleGenConnection(cfg, providerId, model, dataRoot, sessId);
|
|
@@ -3985,7 +4649,11 @@ export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = ''
|
|
|
3985
4649
|
? await callAnthropicText(conn.baseUrl, conn.apiKey, conn.model, userContent)
|
|
3986
4650
|
: await callOpenAiText(conn.baseUrl, conn.apiKey, conn.model, userContent);
|
|
3987
4651
|
const title = cleanGeneratedTitle(raw);
|
|
3988
|
-
if (!title)
|
|
4652
|
+
if (!title) {
|
|
4653
|
+
const e = new Error('模型未返回可用标题');
|
|
4654
|
+
e.code = 'title-gen-no-title';
|
|
4655
|
+
throw e;
|
|
4656
|
+
}
|
|
3989
4657
|
return title;
|
|
3990
4658
|
}
|
|
3991
4659
|
|
|
@@ -5195,6 +5863,35 @@ function zcodeCliBundleCandidates() {
|
|
|
5195
5863
|
].filter(Boolean);
|
|
5196
5864
|
}
|
|
5197
5865
|
|
|
5866
|
+
// ZCode 3.17+ 的安装不再自带 provider/zcode-builtin.json,无头 CLI 起步就报
|
|
5867
|
+
// “无法定位 CLI ZCode Built-in Provider Config”退出;官方环境变量
|
|
5868
|
+
// ZCODE_BUILTIN_PROVIDER_CONFIG_FILE 可以指到运行时生成的版本化副本
|
|
5869
|
+
// (~/.zcode/v2/runtime/provider/<平台>/<版本>/<endpoint>/zcode-builtin.json)。
|
|
5870
|
+
// 旧布局(bundle 旁有 provider/zcode-builtin.json)不需要这个变量。
|
|
5871
|
+
function zcodeBuiltinConfigEnv(bundle) {
|
|
5872
|
+
try {
|
|
5873
|
+
if (existsSync(join(dirname(bundle), 'provider', 'zcode-builtin.json'))) return {};
|
|
5874
|
+
const root = join(homedir(), '.zcode', 'v2', 'runtime', 'provider');
|
|
5875
|
+
if (!existsSync(root)) return {};
|
|
5876
|
+
let newest = null;
|
|
5877
|
+
const stack = [root];
|
|
5878
|
+
while (stack.length) {
|
|
5879
|
+
const d = stack.pop();
|
|
5880
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
5881
|
+
if (e.isDirectory()) stack.push(join(d, e.name));
|
|
5882
|
+
else if (e.name === 'zcode-builtin.json') {
|
|
5883
|
+
const f = join(d, e.name);
|
|
5884
|
+
const m = statSync(f).mtimeMs;
|
|
5885
|
+
if (!newest || m > newest.m) newest = { f, m };
|
|
5886
|
+
}
|
|
5887
|
+
}
|
|
5888
|
+
}
|
|
5889
|
+
return newest ? { ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: newest.f } : {};
|
|
5890
|
+
} catch {
|
|
5891
|
+
return {};
|
|
5892
|
+
}
|
|
5893
|
+
}
|
|
5894
|
+
|
|
5198
5895
|
// 运行 zcode CLI 子命令(plugins … 默认走 plugins 代理范围;智能起名的
|
|
5199
5896
|
// 无界面提问传 none——模型 API 直连,不走下载代理)
|
|
5200
5897
|
function runZcodeCli(subArgs, timeoutMs = 120000, scope = 'plugins') {
|