zcode-pro 1.8.2 → 1.9.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 +3377 -130
- package/package.json +2 -2
- package/src/host/helper.mjs +423 -28
- package/src/host/taskIndex.mjs +25 -2
- package/src/inject/core.js +149 -21
- package/src/inject/features/auto-continue.js +574 -0
- package/src/inject/features/auto-rename.js +3 -3
- 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 +117 -33
- package/src/inject/features/status-bar.js +25 -20
- package/src/inject/features/subagent-icon.js +3 -1
- 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 +770 -0
- package/src/inject/locales/ko.js +770 -0
- package/src/inject/locales/ru.js +770 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "zcode-pro",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"description": "ZCode Pro — ZCode 桌面版增强工具:壁纸引擎(图片/视频/网页)、皮肤主题、会话快捷切换、状态栏统计等二十余项界面与体验增强;不修改客户端文件,用 ZCode Pro 快捷方式启动即可生效。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"scripts": {
|
|
10
10
|
"build": "esbuild src/inject/index.js --bundle --format=iife --target=chrome120 --outfile=dist/inject.js",
|
|
11
|
-
"test": "node scripts/test-usage-stats.mjs && node scripts/test-session-link.mjs && node scripts/test-err-codes.mjs && node scripts/test-sync-docs.mjs && node scripts/test-config.mjs && node scripts/test-task-order.mjs && node scripts/test-inject-logic.mjs && node scripts/test-task-index.mjs && node scripts/test-webdav.mjs && node scripts/test-wallpaper-setup.mjs && node scripts/test-headroom.mjs && node scripts/test-concurrency.mjs && node scripts/test-plugin-install.mjs && node scripts/test-plugin-autoupdate.mjs && node scripts/test-session-import.mjs && node scripts/test-setup-run.mjs",
|
|
11
|
+
"test": "node scripts/test-usage-stats.mjs && node scripts/test-session-link.mjs && node scripts/test-err-codes.mjs && node scripts/test-sync-docs.mjs && node scripts/test-config.mjs && node scripts/test-task-order.mjs && node scripts/test-inject-logic.mjs && node scripts/test-locales.mjs && node scripts/test-task-index.mjs && node scripts/test-webdav.mjs && node scripts/test-wallpaper-setup.mjs && node scripts/test-headroom.mjs && node scripts/test-concurrency.mjs && node scripts/test-plugin-install.mjs && node scripts/test-plugin-autoupdate.mjs && node scripts/test-session-import.mjs && node scripts/test-setup-run.mjs",
|
|
12
12
|
"prepack": "npm run build",
|
|
13
13
|
"start": "./bin/zcode-pro"
|
|
14
14
|
},
|
package/src/host/helper.mjs
CHANGED
|
@@ -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');
|
|
@@ -1456,7 +1461,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1456
1461
|
}
|
|
1457
1462
|
if (req.method === 'GET' && url.pathname === '/subagent-children') {
|
|
1458
1463
|
// 会话的子代理子会话及最近活动时间(含嵌套):子代理判活的主信号——
|
|
1459
|
-
//
|
|
1464
|
+
// 应用的运行记录会把还在跑的长跑子代理误记为结束;已失败/中断的子代理
|
|
1465
|
+
// 不返回(last_outcome),否则中断后图标会一直亮着(subagent-icon.js)
|
|
1460
1466
|
const ids = (url.searchParams.get('ids') || '')
|
|
1461
1467
|
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
|
|
1462
1468
|
const children = ids.length ? await listSubagentChildrenActivity(dataRoot, ids) : [];
|
|
@@ -1544,7 +1550,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1544
1550
|
}
|
|
1545
1551
|
// —— 智能起名:配置读写 + 供应商列表 + 生成并写库 ——
|
|
1546
1552
|
if (req.method === 'GET' && url.pathname === '/title-gen') {
|
|
1547
|
-
|
|
1553
|
+
// 注入层带上它当前实际使用的界面语言:官方 setting.json 的语言切换有时
|
|
1554
|
+
// 不会立刻落盘,只靠文件判断会把日语界面当成英文
|
|
1555
|
+
const loc = titleGenLocaleKey(url.searchParams.get('locale')) || titleGenLocale();
|
|
1556
|
+
json(res, 200, { ok: true, titleGen: loadConfig(configFile).titleGen, defaultPrompt: titleGenDefaultPrompt(loc) });
|
|
1548
1557
|
return;
|
|
1549
1558
|
}
|
|
1550
1559
|
if (req.method === 'POST' && url.pathname === '/title-gen') {
|
|
@@ -1612,9 +1621,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1612
1621
|
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_),两种都认,
|
|
1613
1622
|
// 否则新形式会话的标题永远不会写入数据库
|
|
1614
1623
|
const sessId = typeof body?.sessId === 'string' && /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(body.sessId) ? body.sessId : '';
|
|
1624
|
+
const loc = titleGenLocaleKey(body?.locale) || '';
|
|
1615
1625
|
let title;
|
|
1616
1626
|
try {
|
|
1617
|
-
title = await generateTitleWith(cfg, text, dataRoot, sessId);
|
|
1627
|
+
title = await generateTitleWith(cfg, text, dataRoot, sessId, loc);
|
|
1618
1628
|
} catch (err) {
|
|
1619
1629
|
titleGenLog(dataRoot, `generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1620
1630
|
throw err; // 交给外层统一 500
|
|
@@ -1663,8 +1673,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1663
1673
|
return;
|
|
1664
1674
|
}
|
|
1665
1675
|
let title;
|
|
1676
|
+
const loc = titleGenLocaleKey(body?.locale) || '';
|
|
1666
1677
|
try {
|
|
1667
|
-
title = await generateTitleWith(cfg, material, dataRoot, sessId);
|
|
1678
|
+
title = await generateTitleWith(cfg, material, dataRoot, sessId, loc);
|
|
1668
1679
|
} catch (err) {
|
|
1669
1680
|
titleGenLog(dataRoot, `rename-generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1670
1681
|
throw err; // 交给外层统一 500
|
|
@@ -1729,6 +1740,266 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1729
1740
|
json(res, 200, { ok: true, config: cfg });
|
|
1730
1741
|
return;
|
|
1731
1742
|
}
|
|
1743
|
+
// auto-continue 配置已知键按类型收窄(文件缺失/键非法 → 跳过该项,由消费方回默认)
|
|
1744
|
+
function sanitizeAutoContinueConfig(raw) {
|
|
1745
|
+
const out = {};
|
|
1746
|
+
if (typeof raw.enabled === 'boolean') out.enabled = raw.enabled;
|
|
1747
|
+
if (typeof raw.continueText === 'string') out.continueText = raw.continueText.slice(0, 2000);
|
|
1748
|
+
if (raw.maxRetries !== undefined) out.maxRetries = clampInt(raw.maxRetries, 1, 50, 8);
|
|
1749
|
+
if (raw.cooldownBaseSec !== undefined) out.cooldownBaseSec = clampInt(raw.cooldownBaseSec, 0, 600, 10);
|
|
1750
|
+
if (raw.cooldownFactor !== undefined) out.cooldownFactor = clampInt(raw.cooldownFactor, 1, 10, 2);
|
|
1751
|
+
if (raw.cooldownMaxSec !== undefined) out.cooldownMaxSec = clampInt(raw.cooldownMaxSec, 1, 600, 60);
|
|
1752
|
+
if (raw.stuckAfterMin !== undefined) out.stuckAfterMin = clampInt(raw.stuckAfterMin, 5, 720, 30);
|
|
1753
|
+
if (raw.failedAfterMin !== undefined) out.failedAfterMin = clampInt(raw.failedAfterMin, 1, 60, 3);
|
|
1754
|
+
if (typeof raw.failedAutoFix === 'boolean') out.failedAutoFix = raw.failedAutoFix;
|
|
1755
|
+
for (const key of ['permanentPatterns', 'transientPatterns']) {
|
|
1756
|
+
if (Array.isArray(raw[key])) out[key] = raw[key].filter((x) => typeof x === 'string').slice(0, 200);
|
|
1757
|
+
}
|
|
1758
|
+
return out;
|
|
1759
|
+
}
|
|
1760
|
+
// 悬空任务扫描:识别三类卡死——
|
|
1761
|
+
// 终端:background_task.tracking.started 后一直等不到 terminal(只认 exec_*;
|
|
1762
|
+
// agent_* 从不发 terminal,按 spawned/completed 单独配对)。
|
|
1763
|
+
// 子代理:subagent.spawned 后等不到 subagent.completed;失败的子代理只落
|
|
1764
|
+
// turn.failed,所以子会话的 turn.completed/turn.failed 也算这个子代理终结。
|
|
1765
|
+
// 主轮:turn.started 后等不到 turn.completed/turn.failed;同一会话已经有
|
|
1766
|
+
// 终端/子代理条目时不再报主轮(一个原因只出一张卡)。等用户回答或等审批
|
|
1767
|
+
// 的回合没在跑,不算卡死。用户点停(v4.stop)会清掉该会话未完结的主轮。
|
|
1768
|
+
// 每条带 ageSec(从开始算)与 silenceSec(对应会话最后一条日志距今),阈值
|
|
1769
|
+
// 由前端按配置判断。按本地日期命名的当天与前一天两份日志都扫(跨天起步的
|
|
1770
|
+
// 任务在昨天那份里)。
|
|
1771
|
+
function findStuckTasks() {
|
|
1772
|
+
const dir = join(homedir(), '.zcode', 'cli', 'log');
|
|
1773
|
+
const openTasks = new Map(); // exec taskId -> { taskId, sessionId, startedAt }
|
|
1774
|
+
const openTurns = new Map(); // `${sessionId}|${turnId}` -> { turnId, sessionId, startedAt }
|
|
1775
|
+
const openSubs = new Map(); // agentId -> { agentId, sessionId, startedAt }
|
|
1776
|
+
const lastEvent = new Map(); // sessionId -> { ts, name, toolName }
|
|
1777
|
+
const turnFailed = new Map(); // sessionId -> 最近一次 turn.failed(附失败消息)
|
|
1778
|
+
const lastFailMsg = new Map(); // sessionId -> 最近一次请求失败的 statusMessage
|
|
1779
|
+
const lastStopMark = new Map(); // sessionId -> 最近一次 v4.stop.* 事件时间(用户点停的痕迹)
|
|
1780
|
+
const now = Date.now();
|
|
1781
|
+
const closeTurns = (sessionId, turnId) => {
|
|
1782
|
+
if (turnId) openTurns.delete(`${sessionId}|${turnId}`);
|
|
1783
|
+
else for (const [k, v] of openTurns) if (v.sessionId === sessionId) openTurns.delete(k);
|
|
1784
|
+
};
|
|
1785
|
+
for (const offset of [864e5, 0]) {
|
|
1786
|
+
// 日志按本地日期命名(不是 UTC):用本地日期拼文件名
|
|
1787
|
+
const d = new Date(now - offset);
|
|
1788
|
+
const name = `zcode-${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}.jsonl`;
|
|
1789
|
+
const file = join(dir, name);
|
|
1790
|
+
if (!existsSync(file)) continue;
|
|
1791
|
+
for (const line of readFileSync(file, 'utf8').split('\n')) {
|
|
1792
|
+
if (!line) continue;
|
|
1793
|
+
const ts = line.match(/"timestamp":"([^"]+)"/)?.[1];
|
|
1794
|
+
const sid = line.match(/"sessionId":"([^"]+)"/)?.[1];
|
|
1795
|
+
const evName = line.match(/"event":"([^"]+)"/)?.[1];
|
|
1796
|
+
const toolName = line.match(/"toolName":"([^"]+)"/)?.[1];
|
|
1797
|
+
if (ts && sid) {
|
|
1798
|
+
const cur = lastEvent.get(sid);
|
|
1799
|
+
if (!cur || ts > cur.ts) lastEvent.set(sid, { ts, name: evName, toolName });
|
|
1800
|
+
}
|
|
1801
|
+
let e = null;
|
|
1802
|
+
const parse = () => {
|
|
1803
|
+
if (e === null) {
|
|
1804
|
+
try { e = JSON.parse(line); } catch { e = {}; }
|
|
1805
|
+
}
|
|
1806
|
+
return e;
|
|
1807
|
+
};
|
|
1808
|
+
if (line.includes('background_task.tracking.')) {
|
|
1809
|
+
const taskId = parse()?.context?.taskId;
|
|
1810
|
+
if (taskId && taskId.startsWith('exec_')) {
|
|
1811
|
+
if (evName === 'background_task.tracking.started') {
|
|
1812
|
+
openTasks.set(taskId, { taskId, sessionId: sid, startedAt: ts });
|
|
1813
|
+
} else if (evName === 'background_task.tracking.terminal') {
|
|
1814
|
+
openTasks.delete(taskId);
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
if (line.includes('"event":"subagent.spawned"') || line.includes('"event":"subagent.completed"')) {
|
|
1819
|
+
const agentId = parse()?.context?.agentId;
|
|
1820
|
+
if (agentId) {
|
|
1821
|
+
if (evName === 'subagent.spawned') openSubs.set(agentId, { agentId, sessionId: sid, startedAt: ts });
|
|
1822
|
+
else if (evName === 'subagent.completed') openSubs.delete(agentId);
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
if (line.includes('"event":"turn.started"') || line.includes('"event":"turn.completed"') || line.includes('"event":"turn.failed"') || line.includes('"event":"model.request.failed"')) {
|
|
1826
|
+
const p = parse();
|
|
1827
|
+
const turnId = p?.turnId || p?.context?.turnId;
|
|
1828
|
+
if (evName === 'turn.started' && sid && turnId) {
|
|
1829
|
+
openTurns.set(`${sid}|${turnId}`, { turnId, sessionId: sid, startedAt: ts });
|
|
1830
|
+
} else if (evName === 'turn.completed' || evName === 'turn.failed') {
|
|
1831
|
+
if (sid) closeTurns(sid, turnId);
|
|
1832
|
+
// 子代理会话的回合结束(成功或失败)也代表这个子代理结束了
|
|
1833
|
+
if (sid) {
|
|
1834
|
+
const agentId = sid.startsWith('sess_subagent_') ? sid.slice('sess_subagent_'.length) : p?.context?.agentId;
|
|
1835
|
+
if (agentId) openSubs.delete(agentId);
|
|
1836
|
+
}
|
|
1837
|
+
if (evName === 'turn.failed' && sid) {
|
|
1838
|
+
// 失败前 10 秒内点过停止 = 用户主动终止,不列入待救
|
|
1839
|
+
const stopped = lastStopMark.has(sid)
|
|
1840
|
+
&& Date.parse(ts) - lastStopMark.get(sid) <= 10_000;
|
|
1841
|
+
turnFailed.set(sid, { sessionId: sid, failedAt: ts, message: lastFailMsg.get(sid) || '', stopped });
|
|
1842
|
+
}
|
|
1843
|
+
} else if (evName === 'model.request.failed' && sid && p?.context?.statusMessage) {
|
|
1844
|
+
lastFailMsg.set(sid, String(p.context.statusMessage));
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
if (line.includes('"event":"v4.stop')) {
|
|
1848
|
+
const p = parse();
|
|
1849
|
+
if (p?.sessionId) {
|
|
1850
|
+
if (ts) lastStopMark.set(p.sessionId, Date.parse(ts));
|
|
1851
|
+
closeTurns(p.sessionId); // 用户主动停止的回合不再算卡死
|
|
1852
|
+
}
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
const out = [];
|
|
1857
|
+
const lastTs = (sessionId, fallback) => Date.parse(lastEvent.get(sessionId)?.ts || fallback);
|
|
1858
|
+
const addStuck = (kind, item, silenceSessionId = item.sessionId) => {
|
|
1859
|
+
const ageSec = Math.round((now - Date.parse(item.startedAt)) / 1000);
|
|
1860
|
+
const silenceSec = Math.round((now - lastTs(silenceSessionId, item.startedAt)) / 1000);
|
|
1861
|
+
if (ageSec > 0 && ageSec < 24 * 3600) out.push({ ...item, kind, ageSec, silenceSec });
|
|
1862
|
+
};
|
|
1863
|
+
for (const t of openTasks.values()) addStuck('terminal', t);
|
|
1864
|
+
for (const s of openSubs.values()) {
|
|
1865
|
+
// 子代理自己的会话日志更能代表它是否还在动
|
|
1866
|
+
addStuck('subagent', { ...s, taskId: `subagent:${s.agentId}` }, `sess_subagent_${s.agentId}`);
|
|
1867
|
+
}
|
|
1868
|
+
const busySessions = new Set(out.map((t) => t.sessionId));
|
|
1869
|
+
for (const t of openTurns.values()) {
|
|
1870
|
+
const le = lastEvent.get(t.sessionId);
|
|
1871
|
+
// 等用户回答/等审批的回合没在跑,不算卡死
|
|
1872
|
+
if (le && (le.name === 'tool.permission.evaluated'
|
|
1873
|
+
|| ((le.name === 'tool.call.started' || le.name === 'tool.call.completed')
|
|
1874
|
+
&& (le.toolName === 'AskUserQuestion' || le.toolName === 'ExitPlanMode')))) continue;
|
|
1875
|
+
if (busySessions.has(t.sessionId)) continue;
|
|
1876
|
+
addStuck('turn', { ...t, taskId: `turn:${t.turnId}` });
|
|
1877
|
+
}
|
|
1878
|
+
// 失败会话:turn.failed 之后该会话再无实质动静(横幅规则、人工都没把它续上)。
|
|
1879
|
+
// 覆盖桌面当前视图之外的会话(手机端/后台的 v4 会话在界面里看不到横幅)。
|
|
1880
|
+
// 静默判定留 60 秒宽限:失败瞬间会跟一大串清理事件(mcp 连接释放、生命周期
|
|
1881
|
+
// 变更,实测能到 50+ 条、持续约 1 秒),把它们当“会话在动”会让这类失败永远
|
|
1882
|
+
// 不进待救清单;用户点停的(stopped)不救。
|
|
1883
|
+
const failed = [];
|
|
1884
|
+
for (const f of turnFailed.values()) {
|
|
1885
|
+
if (f.stopped) continue;
|
|
1886
|
+
const ageSec = Math.round((now - Date.parse(f.failedAt)) / 1000);
|
|
1887
|
+
const last = lastEvent.get(f.sessionId)?.ts || f.failedAt;
|
|
1888
|
+
const quietMs = Date.parse(last) - Date.parse(f.failedAt);
|
|
1889
|
+
if (ageSec > 0 && ageSec < 12 * 3600 && quietMs <= 60_000) failed.push({ ...f, ageSec });
|
|
1890
|
+
}
|
|
1891
|
+
return {
|
|
1892
|
+
tasks: out.sort((a, b) => b.ageSec - a.ageSec),
|
|
1893
|
+
failed: failed.sort((a, b) => b.ageSec - a.ageSec),
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
// 会话当前的权限模式存在会话库的 runtime/execution_state 条目里(切模式时原地
|
|
1897
|
+
// 更新,一个会话一条)。无头 -p 不显式传 --mode 时默认 yolo(CLI 的
|
|
1898
|
+
// DEFAULT_HEADLESS_PROMPT_MODE),会把 build/plan 会话的权限提上去;读出来
|
|
1899
|
+
// 原样传给 --mode 才不改变用户设定的权限。读不到(旧会话、旧运行时没有
|
|
1900
|
+
// node:sqlite)返回 null,调用方退回原来的默认行为。
|
|
1901
|
+
async function readSessionMode(sessionId) {
|
|
1902
|
+
try {
|
|
1903
|
+
const dbFile = join(resolveDataRootDir(), 'cli', 'db', 'db.sqlite');
|
|
1904
|
+
if (!existsSync(dbFile)) return null;
|
|
1905
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
1906
|
+
const db = new DatabaseSync(dbFile, { readOnly: true, timeout: 2000 });
|
|
1907
|
+
try {
|
|
1908
|
+
const row = db
|
|
1909
|
+
.prepare(
|
|
1910
|
+
"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",
|
|
1911
|
+
)
|
|
1912
|
+
.get(sessionId);
|
|
1913
|
+
return typeof row?.mode === 'string' ? row.mode : null;
|
|
1914
|
+
} finally {
|
|
1915
|
+
db.close();
|
|
1916
|
+
}
|
|
1917
|
+
} catch {
|
|
1918
|
+
return null;
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1921
|
+
// —— 自动继续:设置弹窗“自动继续”标签页读写 ~/.zcode/auto-continue.json
|
|
1922
|
+
// (回合失败/截断自动续接的开关与文案)——
|
|
1923
|
+
if (req.method === 'GET' && url.pathname === '/auto-continue') {
|
|
1924
|
+
const file = defaultAutoContinueFile();
|
|
1925
|
+
const parsed = readJsonFile(file);
|
|
1926
|
+
if (parsed === null && existsSync(file)) {
|
|
1927
|
+
json(res, 500, { ok: false, code: 'ac-read', error: 'auto-continue.json 不是合法 JSON' });
|
|
1928
|
+
return;
|
|
1929
|
+
}
|
|
1930
|
+
json(res, 200, { ok: true, config: parsed, file });
|
|
1931
|
+
return;
|
|
1932
|
+
}
|
|
1933
|
+
if (req.method === 'POST' && url.pathname === '/auto-continue') {
|
|
1934
|
+
const body = await readBody(req);
|
|
1935
|
+
const cfg = body?.config;
|
|
1936
|
+
if (!cfg || typeof cfg !== 'object') {
|
|
1937
|
+
json(res, 400, { ok: false, code: 'ac-invalid', error: '缺少 config 对象' });
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
try {
|
|
1941
|
+
const file = defaultAutoContinueFile();
|
|
1942
|
+
// 已知键按类型收窄后与磁盘旧配置合并(面板不认识的键不动)
|
|
1943
|
+
const merged = { ...(readJsonFile(file) || {}), ...sanitizeAutoContinueConfig(cfg) };
|
|
1944
|
+
const tmp = file + '.tmp';
|
|
1945
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
|
|
1946
|
+
renameSync(tmp, file);
|
|
1947
|
+
} catch (err2) {
|
|
1948
|
+
json(res, 500, { ok: false, code: 'ac-write', error: '写入 auto-continue.json 失败: ' + (err2?.message || err2) });
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
json(res, 200, { ok: true, config: cfg });
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
// —— auto-continue 看门狗:回合卡死(工具执行器悬死、无失败横幅)时的探测数据,
|
|
1955
|
+
// 返回悬空后台任务清单(started 后从未 terminal),注入层据此提示用户 ——
|
|
1956
|
+
if (req.method === 'GET' && url.pathname === '/ac-stuck') {
|
|
1957
|
+
const r = findStuckTasks();
|
|
1958
|
+
json(res, 200, { ok: true, tasks: r.tasks, failed: r.failed });
|
|
1959
|
+
return;
|
|
1960
|
+
}
|
|
1961
|
+
// —— auto-continue 无头续接:用 ZCode 核心运行时的 headless 模式(--resume + -p)
|
|
1962
|
+
// 把指定会话续上一轮,不碰桌面界面——子代理/自动化同款驱动方式,手机端/后台
|
|
1963
|
+
// 等界面外会话也能续。续接回合可能跑几分钟:启动即返回,成败由下一轮
|
|
1964
|
+
// /ac-stuck 的会话活跃度验证(续上 = 有新事件,失败 = 保持静默)——
|
|
1965
|
+
if (req.method === 'POST' && url.pathname === '/ac-continue') {
|
|
1966
|
+
const body = await readBody(req);
|
|
1967
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : '';
|
|
1968
|
+
const text = typeof body?.text === 'string' ? body.text.slice(0, 500) : '';
|
|
1969
|
+
if (!/^(sess_|session_)[A-Za-z0-9_-]+$/.test(sessionId) || !text.trim()) {
|
|
1970
|
+
json(res, 400, { ok: false, code: 'ac-continue-invalid', error: '缺少合法的 sessionId 或 text' });
|
|
1971
|
+
return;
|
|
1972
|
+
}
|
|
1973
|
+
const bundle = zcodeCliBundleCandidates().find((c) => existsSync(c));
|
|
1974
|
+
if (!bundle) {
|
|
1975
|
+
json(res, 500, { ok: false, code: 'cli-not-found', error: '未找到 ZCode CLI(resources/glm/zcode.cjs)' });
|
|
1976
|
+
return;
|
|
1977
|
+
}
|
|
1978
|
+
// 权限模式原样带过去:能读到的五种模式显式传 --mode,避免无头默认 yolo
|
|
1979
|
+
// 把用户在 build/plan 下的限制提上去。auto 是保留未实现的模式(所有工具
|
|
1980
|
+
// 一律拒绝),无头续接没有意义,直接告知调用方。
|
|
1981
|
+
const sessionMode = await readSessionMode(sessionId);
|
|
1982
|
+
if (sessionMode === 'auto') {
|
|
1983
|
+
json(res, 400, { ok: false, code: 'ac-mode-unsupported', error: '会话处于 auto 权限模式(尚未实现),不自动续接' });
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
const spawnArgs = [bundle, '--resume', sessionId, '-p', text, '--surface', 'terminal'];
|
|
1987
|
+
if (['build', 'edit', 'plan', 'yolo', 'guarded'].includes(sessionMode)) spawnArgs.push('--mode', sessionMode);
|
|
1988
|
+
try {
|
|
1989
|
+
// zcode-pro 本就跑在 ZCode 二进制上:ELECTRON_RUN_AS_NODE=1 直接拿它当 node 用
|
|
1990
|
+
spawn(process.execPath, spawnArgs, {
|
|
1991
|
+
detached: true,
|
|
1992
|
+
stdio: 'ignore',
|
|
1993
|
+
env: { ...process.env, ...proxyEnv({}, 'none'), ELECTRON_RUN_AS_NODE: '1', ...zcodeBuiltinConfigEnv(bundle) },
|
|
1994
|
+
windowsHide: true,
|
|
1995
|
+
}).on('error', () => { /* 启动失败由活跃度验证兜底 */ }).unref();
|
|
1996
|
+
} catch (err2) {
|
|
1997
|
+
json(res, 500, { ok: false, code: 'ac-continue-spawn', error: '启动无头续接失败: ' + (err2?.message || err2) });
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
json(res, 200, { ok: true, started: true });
|
|
2001
|
+
return;
|
|
2002
|
+
}
|
|
1732
2003
|
// 供应商下拉取数(视觉代理“供应商”组合框用):合并两张供应商表,只回 id/名称/别名,不含密钥
|
|
1733
2004
|
if (req.method === 'GET' && url.pathname === '/vision/providers') {
|
|
1734
2005
|
json(res, 200, { ok: true, providers: listVisionProviders() });
|
|
@@ -2347,7 +2618,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
2347
2618
|
} catch (err) {
|
|
2348
2619
|
// 完整错误只进日志;响应里的消息抹掉主目录前缀,别把本机路径结构带出去
|
|
2349
2620
|
console.error('[zcodepro] 路由处理出错:', err);
|
|
2350
|
-
json(res, 500, { ok: false, error: String(err?.message || err).split(homedir()).join('~') });
|
|
2621
|
+
json(res, 500, { ok: false, code: err?.code, error: String(err?.message || err).split(homedir()).join('~') });
|
|
2351
2622
|
}
|
|
2352
2623
|
});
|
|
2353
2624
|
|
|
@@ -2675,7 +2946,9 @@ export function collectUsageStats(sessionId, wantTurns = true, treeTrace = '') {
|
|
|
2675
2946
|
|
|
2676
2947
|
function readJsonFile(p) {
|
|
2677
2948
|
try {
|
|
2678
|
-
|
|
2949
|
+
// Windows 记事本/PowerShell 保存的 JSON 带 UTF-8 BOM,JSON.parse 不认:先剥掉
|
|
2950
|
+
const text = readFileSync(p, 'utf-8');
|
|
2951
|
+
return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
|
|
2679
2952
|
} catch {
|
|
2680
2953
|
return null;
|
|
2681
2954
|
}
|
|
@@ -3430,7 +3703,6 @@ export async function scanIdleBusy(paths, dataRoot) {
|
|
|
3430
3703
|
return SCAN_OFF;
|
|
3431
3704
|
}
|
|
3432
3705
|
|
|
3433
|
-
// Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
|
|
3434
3706
|
// 后台 bash 任务扫描:运行中的任务进程把 /tmp/zcode-bash-*/<会话id>/call_*-stdout.log
|
|
3435
3707
|
// 握在 stdout/stderr 上(实测 fd/1、fd/2),日志路径就带会话 id——按"有进程握着
|
|
3436
3708
|
// 该文件"判定在跑,纯文件系统读取,不惊动会话进程。不能走会话快照:快照会把
|
|
@@ -3480,6 +3752,7 @@ export function scanBackgroundBash(tmpDir = '/tmp', procDir = '/proc') {
|
|
|
3480
3752
|
return { ok: true, jobs: [...hit.values()] };
|
|
3481
3753
|
}
|
|
3482
3754
|
|
|
3755
|
+
// Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
|
|
3483
3756
|
function scanIdleBusyLinux(paths) {
|
|
3484
3757
|
let pids;
|
|
3485
3758
|
try { pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d)); }
|
|
@@ -3694,8 +3967,8 @@ export function listVisionProviders() {
|
|
|
3694
3967
|
|
|
3695
3968
|
// —— 智能起名:供应商取数、模型调用与标题清洗 ——
|
|
3696
3969
|
|
|
3697
|
-
//
|
|
3698
|
-
//
|
|
3970
|
+
// 内置默认提示词(用户可在设置弹窗覆盖),按界面语言取对应语言版本。
|
|
3971
|
+
// 英文/韩文/俄文按词数限制,中文和日文按字数/词数习惯收紧,保证会话列表里放得下
|
|
3699
3972
|
const TITLE_GEN_DEFAULT_PROMPTS = {
|
|
3700
3973
|
zh: [
|
|
3701
3974
|
'为下面的会话生成一个简短的标题。',
|
|
@@ -3719,21 +3992,80 @@ const TITLE_GEN_DEFAULT_PROMPTS = {
|
|
|
3719
3992
|
'- Do not copy or truncate the user\'s message as the title',
|
|
3720
3993
|
'- Output only the title itself: no explanation, no quotes, no trailing punctuation, no markdown',
|
|
3721
3994
|
].join('\n'),
|
|
3995
|
+
ja: [
|
|
3996
|
+
'以下のセッションに短いタイトルを付けてください。',
|
|
3997
|
+
'要件:',
|
|
3998
|
+
'- ユーザーのメッセージで使われている主な言語に合わせる(日本語のメッセージなら日本語のタイトル)',
|
|
3999
|
+
'- ユーザーが行おうとしている主な作業やテーマを要約する(回答や結果は書かない)',
|
|
4000
|
+
'- 通常10〜20文字程度で、セッション一覧でひと目で分かる長さにする',
|
|
4001
|
+
'- 重要な固有名詞(ファイル名、製品名、技術用語などがあれば)は残す',
|
|
4002
|
+
'- `ユーザーの依頼`、`新しいタスク`、`質問`のような曖昧なタイトルは使わない',
|
|
4003
|
+
'- ユーザーのメッセージをそのまま繰り返したり、一部を切り取ったりしない',
|
|
4004
|
+
'- タイトルだけを出力する:説明、引用符、末尾の句読点、Markdown は付けない',
|
|
4005
|
+
].join('\n'),
|
|
4006
|
+
ko: [
|
|
4007
|
+
'아래 세션에 짧은 제목을 붙여 주세요.',
|
|
4008
|
+
'요구 사항:',
|
|
4009
|
+
'- 사용자 메시지의 주된 언어를 사용하세요(한국어 메시지면 한국어 제목).',
|
|
4010
|
+
'- 사용자가 하려는 주요 작업이나 주제를 요약하고, 답이나 결과는 쓰지 마세요.',
|
|
4011
|
+
'- 보통 3~8단어로, 세션 목록에서 한눈에 알아볼 수 있는 길이로 하세요.',
|
|
4012
|
+
'- 중요한 고유명사(파일명, 제품명, 기술 용어 등)는 유지하세요.',
|
|
4013
|
+
'- `사용자 요청`, `새 작업`, `질문` 같은 두루뭉술한 제목은 쓰지 마세요.',
|
|
4014
|
+
'- 사용자 메시지를 그대로 반복하거나 잘라서 제목으로 쓰지 마세요.',
|
|
4015
|
+
'- 제목만 출력하세요. 설명, 따옴표, 끝 문장부호, 마크다운은 붙이지 마세요.',
|
|
4016
|
+
].join('\n'),
|
|
4017
|
+
ru: [
|
|
4018
|
+
'Придумайте короткое название для сессии ниже.',
|
|
4019
|
+
'Требования:',
|
|
4020
|
+
'- Используйте основной язык сообщения пользователя (для сообщения на русском — название на русском).',
|
|
4021
|
+
'- Кратко передайте основную задачу или тему пользователя; не приводите ответ или результат.',
|
|
4022
|
+
'- Обычно 3–8 слов, чтобы название легко узнавалось в списке сессий.',
|
|
4023
|
+
'- Сохраняйте важные имена собственные (имена файлов, названия продуктов, технические термины), если они есть.',
|
|
4024
|
+
'- Избегайте общих названий вроде «Запрос пользователя», «Новая задача» или «Вопрос».',
|
|
4025
|
+
'- Не копируйте и не обрезайте сообщение пользователя как название.',
|
|
4026
|
+
'- Выводите только само название: без пояснений, кавычек, завершающей пунктуации и Markdown.',
|
|
4027
|
+
].join('\n'),
|
|
3722
4028
|
};
|
|
3723
4029
|
|
|
3724
|
-
// 界面语言:桌面设置(v2/setting.json 的 localePreference
|
|
3725
|
-
//
|
|
4030
|
+
// 界面语言:桌面设置(v2/setting.json 的 localePreference)为官方五种语言时直接采用;
|
|
4031
|
+
// system 或未设置时优先用官方已解析的 locale,再按系统环境语言判断,未识别的回退英文
|
|
4032
|
+
const titleGenLocaleKey = (v) => {
|
|
4033
|
+
const s = String(v || '').trim().toLowerCase();
|
|
4034
|
+
return s.startsWith('zh') ? 'zh'
|
|
4035
|
+
: s.startsWith('ja') ? 'ja'
|
|
4036
|
+
: s.startsWith('ko') ? 'ko'
|
|
4037
|
+
: s.startsWith('ru') ? 'ru'
|
|
4038
|
+
: s.startsWith('en') ? 'en' : '';
|
|
4039
|
+
};
|
|
4040
|
+
// 3.18.2 起真正的五种语言写在 uiLocale*;旧字段 locale/localePreference 只保留
|
|
4041
|
+
// zh-CN / en-US 兼容值(ja/ko/ru 会写成 en-US),必须优先读新字段
|
|
4042
|
+
export function titleGenLocaleFromSettings(s) {
|
|
4043
|
+
const byUiPref = titleGenLocaleKey(s && s.uiLocalePreference);
|
|
4044
|
+
if (byUiPref) return byUiPref;
|
|
4045
|
+
const byUi = titleGenLocaleKey(s && s.uiLocale);
|
|
4046
|
+
if (byUi) return byUi;
|
|
4047
|
+
const byPref = titleGenLocaleKey(s && s.localePreference);
|
|
4048
|
+
if (byPref) return byPref;
|
|
4049
|
+
const byResolved = titleGenLocaleKey(s && s.locale);
|
|
4050
|
+
if (byResolved) return byResolved;
|
|
4051
|
+
return '';
|
|
4052
|
+
}
|
|
3726
4053
|
function titleGenLocale() {
|
|
3727
4054
|
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移(同 startHelper 的 settingsFile)
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
4055
|
+
return titleGenLocaleFromSettings(s)
|
|
4056
|
+
|| titleGenLocaleKey(process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG)
|
|
4057
|
+
|| 'en';
|
|
4058
|
+
}
|
|
4059
|
+
|
|
4060
|
+
function titleGenDefaultPrompt(locale) {
|
|
4061
|
+
return TITLE_GEN_DEFAULT_PROMPTS[locale || titleGenLocale()] || TITLE_GEN_DEFAULT_PROMPTS.en;
|
|
3733
4062
|
}
|
|
3734
4063
|
|
|
3735
|
-
|
|
3736
|
-
|
|
4064
|
+
// 没有保存过提示词时才用当前语言的默认值;已保存的值(包括旧语言的内置默认)保持不变。
|
|
4065
|
+
// 用户想换成当前语言的默认值,在设置页点“使用默认提示词”重新取。
|
|
4066
|
+
function titleGenPromptFor(value, locale) {
|
|
4067
|
+
const text = String(value || '');
|
|
4068
|
+
return text.trim() ? text : titleGenDefaultPrompt(locale);
|
|
3737
4069
|
}
|
|
3738
4070
|
|
|
3739
4071
|
const TITLE_GEN_MAX_TEXT = 1200; // 用户消息送入模型的长度上限(与官方起名一致)
|
|
@@ -3872,11 +4204,19 @@ async function callAnthropicText(baseUrl, apiKey, model, content) {
|
|
|
3872
4204
|
const doc = JSON.parse(body);
|
|
3873
4205
|
const text = Array.isArray(doc.content)
|
|
3874
4206
|
? doc.content.filter((b) => b && b.type === 'text').map((b) => b.text || '').join('') : '';
|
|
3875
|
-
if (!text)
|
|
3876
|
-
|
|
4207
|
+
if (!text) {
|
|
4208
|
+
const e = new Error(doc.stop_reason === 'max_tokens'
|
|
4209
|
+
? '模型的思考用完了输出上限,仍未给出标题' : '响应中没有文本内容');
|
|
4210
|
+
e.code = doc.stop_reason === 'max_tokens' ? 'title-gen-thinking' : 'title-gen-empty';
|
|
4211
|
+
throw e;
|
|
4212
|
+
}
|
|
3877
4213
|
return text;
|
|
3878
4214
|
} catch (err) {
|
|
3879
|
-
if (err && err.name === 'AbortError')
|
|
4215
|
+
if (err && err.name === 'AbortError') {
|
|
4216
|
+
const e = new Error(`请求超时(${Math.round(TITLE_GEN_TIMEOUT_MS / 1000)} 秒)`);
|
|
4217
|
+
e.code = 'title-gen-timeout';
|
|
4218
|
+
throw e;
|
|
4219
|
+
}
|
|
3880
4220
|
throw err;
|
|
3881
4221
|
} finally { clearTimeout(timer); }
|
|
3882
4222
|
}
|
|
@@ -3897,10 +4237,18 @@ async function callOpenAiText(baseUrl, apiKey, model, content) {
|
|
|
3897
4237
|
if (!resp.ok) throw new Error(`HTTP ${resp.status} [model=${model}]: ${body.slice(0, 300)}`);
|
|
3898
4238
|
const doc = JSON.parse(body);
|
|
3899
4239
|
const text = doc.choices?.[0]?.message?.content || '';
|
|
3900
|
-
if (typeof text !== 'string' || !text.trim())
|
|
4240
|
+
if (typeof text !== 'string' || !text.trim()) {
|
|
4241
|
+
const e = new Error('响应中没有文本内容');
|
|
4242
|
+
e.code = 'title-gen-empty';
|
|
4243
|
+
throw e;
|
|
4244
|
+
}
|
|
3901
4245
|
return text;
|
|
3902
4246
|
} catch (err) {
|
|
3903
|
-
if (err && err.name === 'AbortError')
|
|
4247
|
+
if (err && err.name === 'AbortError') {
|
|
4248
|
+
const e = new Error(`请求超时(${Math.round(TITLE_GEN_TIMEOUT_MS / 1000)} 秒)`);
|
|
4249
|
+
e.code = 'title-gen-timeout';
|
|
4250
|
+
throw e;
|
|
4251
|
+
}
|
|
3904
4252
|
throw err;
|
|
3905
4253
|
} finally { clearTimeout(timer); }
|
|
3906
4254
|
}
|
|
@@ -3963,21 +4311,35 @@ export async function writeGeneratedTitle(dataRoot, configFile, sessId, title, {
|
|
|
3963
4311
|
return { written, store };
|
|
3964
4312
|
}
|
|
3965
4313
|
|
|
4314
|
+
// 起名提示词里的固定上下文(日期行、用户消息标签)也跟随界面语言,
|
|
4315
|
+
// 避免非中文用户看到中文包装文本
|
|
4316
|
+
const TITLE_GEN_PROMPT_LABELS = {
|
|
4317
|
+
zh: { date: (d, m) => `当前日期(Asia/Shanghai):${d}(MMDD 即 ${m})`, user: '会话的用户消息:' },
|
|
4318
|
+
en: { date: (d, m) => `Current date (Asia/Shanghai): ${d} (MMDD = ${m})`, user: "The session's user messages:" },
|
|
4319
|
+
ja: { date: (d, m) => `現在の日付(Asia/Shanghai):${d}(MMDD は ${m})`, user: 'セッションのユーザーメッセージ:' },
|
|
4320
|
+
ko: { date: (d, m) => `현재 날짜(Asia/Shanghai): ${d} (MMDD = ${m})`, user: '세션의 사용자 메시지:' },
|
|
4321
|
+
ru: { date: (d, m) => `Текущая дата (Asia/Shanghai): ${d} (MMDD = ${m})`, user: 'Сообщения пользователя в сессии:' },
|
|
4322
|
+
};
|
|
4323
|
+
|
|
3966
4324
|
// 生成标题。provider 三种取值:
|
|
3967
4325
|
// - 'session':跟随当前会话——从任务索引解析该会话正在用的供应商与模型
|
|
3968
4326
|
// (model 已填时用填写的),供应商需在可直连列表内;
|
|
3969
4327
|
// - '':不跟随,用配置里的 baseUrl/apiKey/format 直连;
|
|
3970
4328
|
// - 供应商 id:按列表解析直连;id 已被删时退回保存时留下的地址/密钥副本。
|
|
3971
4329
|
// 输出统一清洗为单行短标题。导出以便测试
|
|
3972
|
-
export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = '') {
|
|
4330
|
+
export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = '', locale = '') {
|
|
3973
4331
|
const text = String(rawText || '').trim().replace(/\s+/g, ' ').slice(0, TITLE_GEN_MAX_TEXT);
|
|
3974
|
-
const
|
|
4332
|
+
const loc = titleGenLocaleKey(locale) || titleGenLocale();
|
|
4333
|
+
const prompt = titleGenPromptFor(cfg.prompt, loc);
|
|
3975
4334
|
// 注入当前日期(上海时区):起名模型是无状态的,自定义提示词里要求
|
|
3976
4335
|
// “MMDD 取对话创建日期”时它无从得知,只能留字面量 MMDD
|
|
3977
4336
|
const now = new Date(Date.now() + 8 * 3600 * 1000);
|
|
3978
4337
|
const pad = (n) => String(n).padStart(2, '0');
|
|
3979
|
-
const
|
|
3980
|
-
const
|
|
4338
|
+
const labels = TITLE_GEN_PROMPT_LABELS[loc] || TITLE_GEN_PROMPT_LABELS.en;
|
|
4339
|
+
const ymd = `${now.getUTCFullYear()}-${pad(now.getUTCMonth() + 1)}-${pad(now.getUTCDate())}`;
|
|
4340
|
+
const md = `${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}`;
|
|
4341
|
+
const dateLine = labels.date(ymd, md);
|
|
4342
|
+
const userContent = `${prompt}\n\n${dateLine}\n\n${labels.user}\n${text}`;
|
|
3981
4343
|
const providerId = (cfg.provider || '').trim();
|
|
3982
4344
|
const model = (cfg.model || '').trim();
|
|
3983
4345
|
const conn = await resolveTitleGenConnection(cfg, providerId, model, dataRoot, sessId);
|
|
@@ -3985,7 +4347,11 @@ export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = ''
|
|
|
3985
4347
|
? await callAnthropicText(conn.baseUrl, conn.apiKey, conn.model, userContent)
|
|
3986
4348
|
: await callOpenAiText(conn.baseUrl, conn.apiKey, conn.model, userContent);
|
|
3987
4349
|
const title = cleanGeneratedTitle(raw);
|
|
3988
|
-
if (!title)
|
|
4350
|
+
if (!title) {
|
|
4351
|
+
const e = new Error('模型未返回可用标题');
|
|
4352
|
+
e.code = 'title-gen-no-title';
|
|
4353
|
+
throw e;
|
|
4354
|
+
}
|
|
3989
4355
|
return title;
|
|
3990
4356
|
}
|
|
3991
4357
|
|
|
@@ -5195,6 +5561,35 @@ function zcodeCliBundleCandidates() {
|
|
|
5195
5561
|
].filter(Boolean);
|
|
5196
5562
|
}
|
|
5197
5563
|
|
|
5564
|
+
// ZCode 3.17+ 的安装不再自带 provider/zcode-builtin.json,无头 CLI 起步就报
|
|
5565
|
+
// “无法定位 CLI ZCode Built-in Provider Config”退出;官方环境变量
|
|
5566
|
+
// ZCODE_BUILTIN_PROVIDER_CONFIG_FILE 可以指到运行时生成的版本化副本
|
|
5567
|
+
// (~/.zcode/v2/runtime/provider/<平台>/<版本>/<endpoint>/zcode-builtin.json)。
|
|
5568
|
+
// 旧布局(bundle 旁有 provider/zcode-builtin.json)不需要这个变量。
|
|
5569
|
+
function zcodeBuiltinConfigEnv(bundle) {
|
|
5570
|
+
try {
|
|
5571
|
+
if (existsSync(join(dirname(bundle), 'provider', 'zcode-builtin.json'))) return {};
|
|
5572
|
+
const root = join(homedir(), '.zcode', 'v2', 'runtime', 'provider');
|
|
5573
|
+
if (!existsSync(root)) return {};
|
|
5574
|
+
let newest = null;
|
|
5575
|
+
const stack = [root];
|
|
5576
|
+
while (stack.length) {
|
|
5577
|
+
const d = stack.pop();
|
|
5578
|
+
for (const e of readdirSync(d, { withFileTypes: true })) {
|
|
5579
|
+
if (e.isDirectory()) stack.push(join(d, e.name));
|
|
5580
|
+
else if (e.name === 'zcode-builtin.json') {
|
|
5581
|
+
const f = join(d, e.name);
|
|
5582
|
+
const m = statSync(f).mtimeMs;
|
|
5583
|
+
if (!newest || m > newest.m) newest = { f, m };
|
|
5584
|
+
}
|
|
5585
|
+
}
|
|
5586
|
+
}
|
|
5587
|
+
return newest ? { ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: newest.f } : {};
|
|
5588
|
+
} catch {
|
|
5589
|
+
return {};
|
|
5590
|
+
}
|
|
5591
|
+
}
|
|
5592
|
+
|
|
5198
5593
|
// 运行 zcode CLI 子命令(plugins … 默认走 plugins 代理范围;智能起名的
|
|
5199
5594
|
// 无界面提问传 none——模型 API 直连,不走下载代理)
|
|
5200
5595
|
function runZcodeCli(subArgs, timeoutMs = 120000, scope = 'plugins') {
|