zcode-pro 1.8.1 → 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.
@@ -21,7 +21,14 @@ import { listImportSessions, runImport } from './session-import/index.mjs';
21
21
 
22
22
  // 会话导入(/import/list、/import/run):把外部 CLI 的历史会话写成 ZCode 任务。
23
23
 
24
- const VERSION = '1.7.0';
24
+ // 版本号以 package.json 为准:升版只改版本文件,这里不再单独维护一份
25
+ //(此前固定写 1.7.0,之后一直没跟着升,设置弹窗显示的就是旧版)
26
+ const VERSION = (() => {
27
+ try {
28
+ const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json'), 'utf8'));
29
+ return String(pkg.version || '0.0.0');
30
+ } catch { return '0.0.0'; }
31
+ })();
25
32
 
26
33
  // 全局提示词固定在用户主目录:官方加载器按 HOME/USERPROFILE 拼 .zcode/AGENTS.md,
27
34
  // 不读 ZCODE_DATA_BASE_DIR(数据根迁走时全局指令仍在原位)。
@@ -34,6 +41,11 @@ function defaultVisionFile() {
34
41
  return join(homedir(), '.zcode', 'zcode-vision.json');
35
42
  }
36
43
 
44
+ // 自动继续(回合失败/截断自动续接)的配置:设置页“自动继续”标签读写此文件
45
+ function defaultAutoContinueFile() {
46
+ return join(homedir(), '.zcode', 'auto-continue.json');
47
+ }
48
+
37
49
  // rtk 插件的状态目录(钩子按 ${RTK_DIR:-~/.zcode-rtk} 解析,这里保持一致)
38
50
  function defaultRtkDir() {
39
51
  return process.env.RTK_DIR || join(homedir(), '.zcode-rtk');
@@ -316,6 +328,7 @@ export function defaultConfig() {
316
328
  tableCopy: true, // 表格工具条"复制表格"按钮:富文本剪贴板,粘贴即表格(table-copy.js)
317
329
  sessionLink: true, // 会话 ID 显示为任务名链接:聊天里的 sess_/session_ 显示为任务名,点击切换(session-link.js)
318
330
  composerProvider: true, // 输入框模型名前显示供应商名(composer-provider.js)
331
+ composerEditModel: true, // 编辑上一条消息时保持输入框当前模型(composer-edit-model.js)
319
332
  sessionImport: true, // 导入会话:把 Codex/Claude Code/dsh/pi 的历史会话复制成 ZCode 任务
320
333
  },
321
334
  // 空闲项目内存回收的判定时长(分钟,1–1440):项目无运行中会话、无后台命令
@@ -326,7 +339,8 @@ export function defaultConfig() {
326
339
  idleReclaimStartupMinutes: 5,
327
340
  // 样式调整(设置弹窗“样式调整”标签页)。null = 不覆盖,跟随应用默认。
328
341
  styles: {
329
- rowGap: null, // 段落间距:会话内各块之间的垂直间距(应用默认 20px)
342
+ thinkingRowGap: null, // 思考段落间距:“已工作/工作中”过程视图内各行的垂直间距(应用默认 20px)
343
+ answerRowGap: null, // 回答段落间距:回答正文与回合之间的垂直间距(应用默认 20px)
330
344
  listSpacing: null, // 列表上下留白(应用默认 12px)
331
345
  listItemSpacing: null, // 列表项之间的间距(应用默认 6px)
332
346
  quoteCodeSpacing: null, // 引用/代码块上下留白(应用默认 16px,my-4)
@@ -416,6 +430,22 @@ let configUnreadable = false;
416
430
  export function configFileUnreadable() {
417
431
  return configUnreadable;
418
432
  }
433
+ // 旧版单一的“段落间距”(rowGap)已拆成思考/回答两项:读旧配置或旧同步文档时
434
+ // 把旧值同时给到两项。新键显式出现过(哪怕是 null)就不再迁移,避免“恢复默认”
435
+ // 之后又被旧值顶回去
436
+ function migrateStyles(saved) {
437
+ const src = saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {};
438
+ const out = { ...defaultConfig().styles, ...src };
439
+ const legacy = src.rowGap;
440
+ if (typeof legacy === 'number' && Number.isFinite(legacy) && legacy >= 0
441
+ && !('thinkingRowGap' in src) && !('answerRowGap' in src)) {
442
+ out.thinkingRowGap = Math.round(legacy);
443
+ out.answerRowGap = Math.round(legacy);
444
+ delete out.rowGap;
445
+ }
446
+ return out;
447
+ }
448
+
419
449
  export function loadConfig(configFile) {
420
450
  try {
421
451
  if (!existsSync(configFile)) { configUnreadable = false; return defaultConfig(); }
@@ -430,7 +460,7 @@ export function loadConfig(configFile) {
430
460
  idleReclaimMinutes: Number.isFinite(minutes) && minutes >= 1 ? Math.min(1440, Math.round(minutes)) : 30,
431
461
  idleReclaimStartupMinutes: Number.isFinite(startupMinutes) && startupMinutes >= 0 ? Math.min(1440, Math.round(startupMinutes)) : 5,
432
462
  features: { ...defaultConfig().features, ...(saved.features || {}) },
433
- styles: { ...defaultConfig().styles, ...(saved.styles && typeof saved.styles === 'object' ? saved.styles : {}) },
463
+ styles: migrateStyles(saved.styles),
434
464
  aliases: { ...((saved.aliases && typeof saved.aliases === 'object') ? saved.aliases : {}) },
435
465
  headroomRoutes: { ...((saved.headroomRoutes && typeof saved.headroomRoutes === 'object' && !Array.isArray(saved.headroomRoutes)) ? saved.headroomRoutes : {}) },
436
466
  titleGen: mergeTitleGenConfig(saved.titleGen),
@@ -1431,7 +1461,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
1431
1461
  }
1432
1462
  if (req.method === 'GET' && url.pathname === '/subagent-children') {
1433
1463
  // 会话的子代理子会话及最近活动时间(含嵌套):子代理判活的主信号——
1434
- // 应用的运行记录会把还在跑的长跑子代理误记为结束(subagent-icon.js)
1464
+ // 应用的运行记录会把还在跑的长跑子代理误记为结束;已失败/中断的子代理
1465
+ // 不返回(last_outcome),否则中断后图标会一直亮着(subagent-icon.js)
1435
1466
  const ids = (url.searchParams.get('ids') || '')
1436
1467
  .split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
1437
1468
  const children = ids.length ? await listSubagentChildrenActivity(dataRoot, ids) : [];
@@ -1519,7 +1550,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
1519
1550
  }
1520
1551
  // —— 智能起名:配置读写 + 供应商列表 + 生成并写库 ——
1521
1552
  if (req.method === 'GET' && url.pathname === '/title-gen') {
1522
- json(res, 200, { ok: true, titleGen: loadConfig(configFile).titleGen, defaultPrompt: titleGenDefaultPrompt() });
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) });
1523
1557
  return;
1524
1558
  }
1525
1559
  if (req.method === 'POST' && url.pathname === '/title-gen') {
@@ -1587,9 +1621,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
1587
1621
  // 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_),两种都认,
1588
1622
  // 否则新形式会话的标题永远不会写入数据库
1589
1623
  const sessId = typeof body?.sessId === 'string' && /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(body.sessId) ? body.sessId : '';
1624
+ const loc = titleGenLocaleKey(body?.locale) || '';
1590
1625
  let title;
1591
1626
  try {
1592
- title = await generateTitleWith(cfg, text, dataRoot, sessId);
1627
+ title = await generateTitleWith(cfg, text, dataRoot, sessId, loc);
1593
1628
  } catch (err) {
1594
1629
  titleGenLog(dataRoot, `generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
1595
1630
  throw err; // 交给外层统一 500
@@ -1638,8 +1673,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
1638
1673
  return;
1639
1674
  }
1640
1675
  let title;
1676
+ const loc = titleGenLocaleKey(body?.locale) || '';
1641
1677
  try {
1642
- title = await generateTitleWith(cfg, material, dataRoot, sessId);
1678
+ title = await generateTitleWith(cfg, material, dataRoot, sessId, loc);
1643
1679
  } catch (err) {
1644
1680
  titleGenLog(dataRoot, `rename-generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
1645
1681
  throw err; // 交给外层统一 500
@@ -1704,6 +1740,266 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
1704
1740
  json(res, 200, { ok: true, config: cfg });
1705
1741
  return;
1706
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
+ }
1707
2003
  // 供应商下拉取数(视觉代理“供应商”组合框用):合并两张供应商表,只回 id/名称/别名,不含密钥
1708
2004
  if (req.method === 'GET' && url.pathname === '/vision/providers') {
1709
2005
  json(res, 200, { ok: true, providers: listVisionProviders() });
@@ -2322,7 +2618,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
2322
2618
  } catch (err) {
2323
2619
  // 完整错误只进日志;响应里的消息抹掉主目录前缀,别把本机路径结构带出去
2324
2620
  console.error('[zcodepro] 路由处理出错:', err);
2325
- 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('~') });
2326
2622
  }
2327
2623
  });
2328
2624
 
@@ -2650,7 +2946,9 @@ export function collectUsageStats(sessionId, wantTurns = true, treeTrace = '') {
2650
2946
 
2651
2947
  function readJsonFile(p) {
2652
2948
  try {
2653
- return JSON.parse(readFileSync(p, 'utf-8'));
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);
2654
2952
  } catch {
2655
2953
  return null;
2656
2954
  }
@@ -3405,7 +3703,6 @@ export async function scanIdleBusy(paths, dataRoot) {
3405
3703
  return SCAN_OFF;
3406
3704
  }
3407
3705
 
3408
- // Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
3409
3706
  // 后台 bash 任务扫描:运行中的任务进程把 /tmp/zcode-bash-*/<会话id>/call_*-stdout.log
3410
3707
  // 握在 stdout/stderr 上(实测 fd/1、fd/2),日志路径就带会话 id——按"有进程握着
3411
3708
  // 该文件"判定在跑,纯文件系统读取,不惊动会话进程。不能走会话快照:快照会把
@@ -3455,6 +3752,7 @@ export function scanBackgroundBash(tmpDir = '/tmp', procDir = '/proc') {
3455
3752
  return { ok: true, jobs: [...hit.values()] };
3456
3753
  }
3457
3754
 
3755
+ // Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
3458
3756
  function scanIdleBusyLinux(paths) {
3459
3757
  let pids;
3460
3758
  try { pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d)); }
@@ -3615,7 +3913,11 @@ export async function classifyIdleBusyWindows(procs, paths, lookupTaskWs) {
3615
3913
  function applyStylesPartial(base, partial) {
3616
3914
  const out = (base && typeof base === 'object') ? base : {};
3617
3915
  if (!partial || typeof partial !== 'object') return out;
3618
- for (const key of ['rowGap', 'listSpacing', 'listItemSpacing', 'quoteCodeSpacing', 'tableSpacing', 'tableCellPaddingV', 'tableCellPaddingH', 'sidebarProjectSpacing', 'sidebarTaskSpacing']) {
3916
+ // 旧客户端/旧同步文档仍发 rowGap:折算到拆开后的两项
3917
+ if ('rowGap' in partial && !('thinkingRowGap' in partial) && !('answerRowGap' in partial)) {
3918
+ partial = { ...partial, thinkingRowGap: partial.rowGap, answerRowGap: partial.rowGap };
3919
+ }
3920
+ for (const key of ['thinkingRowGap', 'answerRowGap', 'listSpacing', 'listItemSpacing', 'quoteCodeSpacing', 'tableSpacing', 'tableCellPaddingV', 'tableCellPaddingH', 'sidebarProjectSpacing', 'sidebarTaskSpacing']) {
3619
3921
  if (key in partial) {
3620
3922
  const v = partial[key];
3621
3923
  if (v === null) out[key] = null;
@@ -3665,8 +3967,8 @@ export function listVisionProviders() {
3665
3967
 
3666
3968
  // —— 智能起名:供应商取数、模型调用与标题清洗 ——
3667
3969
 
3668
- // 内置默认提示词(用户可在设置弹窗覆盖),按界面语言取中文或英文版。
3669
- // 英文版的词数上限比中文版紧:英文单词更长,3~15 个词在会话列表里放不下
3970
+ // 内置默认提示词(用户可在设置弹窗覆盖),按界面语言取对应语言版本。
3971
+ // 英文/韩文/俄文按词数限制,中文和日文按字数/词数习惯收紧,保证会话列表里放得下
3670
3972
  const TITLE_GEN_DEFAULT_PROMPTS = {
3671
3973
  zh: [
3672
3974
  '为下面的会话生成一个简短的标题。',
@@ -3690,21 +3992,80 @@ const TITLE_GEN_DEFAULT_PROMPTS = {
3690
3992
  '- Do not copy or truncate the user\'s message as the title',
3691
3993
  '- Output only the title itself: no explanation, no quotes, no trailing punctuation, no markdown',
3692
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'),
3693
4028
  };
3694
4029
 
3695
- // 界面语言:桌面设置(v2/setting.json 的 localePreference)为 en-US / zh-CN 时
3696
- // 直接采用;system 或未设置时按系统环境语言判断(中文环境 → 中文,其余 → 英文)
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
+ }
3697
4053
  function titleGenLocale() {
3698
4054
  const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移(同 startHelper 的 settingsFile)
3699
- const pref = String((s && s.localePreference) || '').toLowerCase();
3700
- if (pref.startsWith('en')) return 'en';
3701
- if (pref.startsWith('zh')) return 'zh';
3702
- const lang = String(process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '').toLowerCase();
3703
- return lang.startsWith('zh') ? 'zh' : 'en';
4055
+ return titleGenLocaleFromSettings(s)
4056
+ || titleGenLocaleKey(process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG)
4057
+ || 'en';
3704
4058
  }
3705
4059
 
3706
- function titleGenDefaultPrompt() {
3707
- return TITLE_GEN_DEFAULT_PROMPTS[titleGenLocale()] || TITLE_GEN_DEFAULT_PROMPTS.en;
4060
+ function titleGenDefaultPrompt(locale) {
4061
+ return TITLE_GEN_DEFAULT_PROMPTS[locale || titleGenLocale()] || TITLE_GEN_DEFAULT_PROMPTS.en;
4062
+ }
4063
+
4064
+ // 没有保存过提示词时才用当前语言的默认值;已保存的值(包括旧语言的内置默认)保持不变。
4065
+ // 用户想换成当前语言的默认值,在设置页点“使用默认提示词”重新取。
4066
+ function titleGenPromptFor(value, locale) {
4067
+ const text = String(value || '');
4068
+ return text.trim() ? text : titleGenDefaultPrompt(locale);
3708
4069
  }
3709
4070
 
3710
4071
  const TITLE_GEN_MAX_TEXT = 1200; // 用户消息送入模型的长度上限(与官方起名一致)
@@ -3843,11 +4204,19 @@ async function callAnthropicText(baseUrl, apiKey, model, content) {
3843
4204
  const doc = JSON.parse(body);
3844
4205
  const text = Array.isArray(doc.content)
3845
4206
  ? doc.content.filter((b) => b && b.type === 'text').map((b) => b.text || '').join('') : '';
3846
- if (!text) throw new Error(doc.stop_reason === 'max_tokens'
3847
- ? '模型的思考用完了输出上限,仍未给出标题' : '响应中没有文本内容');
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
+ }
3848
4213
  return text;
3849
4214
  } catch (err) {
3850
- if (err && err.name === 'AbortError') throw new Error(`请求超时(${Math.round(TITLE_GEN_TIMEOUT_MS / 1000)} 秒)`);
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
+ }
3851
4220
  throw err;
3852
4221
  } finally { clearTimeout(timer); }
3853
4222
  }
@@ -3868,10 +4237,18 @@ async function callOpenAiText(baseUrl, apiKey, model, content) {
3868
4237
  if (!resp.ok) throw new Error(`HTTP ${resp.status} [model=${model}]: ${body.slice(0, 300)}`);
3869
4238
  const doc = JSON.parse(body);
3870
4239
  const text = doc.choices?.[0]?.message?.content || '';
3871
- if (typeof text !== 'string' || !text.trim()) throw new Error('响应中没有文本内容');
4240
+ if (typeof text !== 'string' || !text.trim()) {
4241
+ const e = new Error('响应中没有文本内容');
4242
+ e.code = 'title-gen-empty';
4243
+ throw e;
4244
+ }
3872
4245
  return text;
3873
4246
  } catch (err) {
3874
- if (err && err.name === 'AbortError') throw new Error(`请求超时(${Math.round(TITLE_GEN_TIMEOUT_MS / 1000)} 秒)`);
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
+ }
3875
4252
  throw err;
3876
4253
  } finally { clearTimeout(timer); }
3877
4254
  }
@@ -3934,21 +4311,35 @@ export async function writeGeneratedTitle(dataRoot, configFile, sessId, title, {
3934
4311
  return { written, store };
3935
4312
  }
3936
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
+
3937
4324
  // 生成标题。provider 三种取值:
3938
4325
  // - 'session':跟随当前会话——从任务索引解析该会话正在用的供应商与模型
3939
4326
  // (model 已填时用填写的),供应商需在可直连列表内;
3940
4327
  // - '':不跟随,用配置里的 baseUrl/apiKey/format 直连;
3941
4328
  // - 供应商 id:按列表解析直连;id 已被删时退回保存时留下的地址/密钥副本。
3942
4329
  // 输出统一清洗为单行短标题。导出以便测试
3943
- export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = '') {
4330
+ export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = '', locale = '') {
3944
4331
  const text = String(rawText || '').trim().replace(/\s+/g, ' ').slice(0, TITLE_GEN_MAX_TEXT);
3945
- const prompt = (cfg.prompt && cfg.prompt.trim()) || titleGenDefaultPrompt();
4332
+ const loc = titleGenLocaleKey(locale) || titleGenLocale();
4333
+ const prompt = titleGenPromptFor(cfg.prompt, loc);
3946
4334
  // 注入当前日期(上海时区):起名模型是无状态的,自定义提示词里要求
3947
4335
  // “MMDD 取对话创建日期”时它无从得知,只能留字面量 MMDD
3948
4336
  const now = new Date(Date.now() + 8 * 3600 * 1000);
3949
4337
  const pad = (n) => String(n).padStart(2, '0');
3950
- const dateLine = `当前日期(Asia/Shanghai):${now.getUTCFullYear()}-${pad(now.getUTCMonth() + 1)}-${pad(now.getUTCDate())}(MMDD 即 ${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())})`;
3951
- const userContent = `${prompt}\n\n${dateLine}\n\n会话的用户消息:\n${text}`;
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}`;
3952
4343
  const providerId = (cfg.provider || '').trim();
3953
4344
  const model = (cfg.model || '').trim();
3954
4345
  const conn = await resolveTitleGenConnection(cfg, providerId, model, dataRoot, sessId);
@@ -3956,7 +4347,11 @@ export async function generateTitleWith(cfg, rawText, dataRoot = '', sessId = ''
3956
4347
  ? await callAnthropicText(conn.baseUrl, conn.apiKey, conn.model, userContent)
3957
4348
  : await callOpenAiText(conn.baseUrl, conn.apiKey, conn.model, userContent);
3958
4349
  const title = cleanGeneratedTitle(raw);
3959
- if (!title) throw new Error('模型未返回可用标题');
4350
+ if (!title) {
4351
+ const e = new Error('模型未返回可用标题');
4352
+ e.code = 'title-gen-no-title';
4353
+ throw e;
4354
+ }
3960
4355
  return title;
3961
4356
  }
3962
4357
 
@@ -5166,6 +5561,35 @@ function zcodeCliBundleCandidates() {
5166
5561
  ].filter(Boolean);
5167
5562
  }
5168
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
+
5169
5593
  // 运行 zcode CLI 子命令(plugins … 默认走 plugins 代理范围;智能起名的
5170
5594
  // 无界面提问传 none——模型 API 直连,不走下载代理)
5171
5595
  function runZcodeCli(subArgs, timeoutMs = 120000, scope = 'plugins') {