zcode-pro 1.6.1 → 1.7.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 +31 -21
- package/README.md +20 -12
- package/dist/inject.js +10431 -8836
- package/package.json +2 -1
- package/src/host/cdp.mjs +13 -3
- package/src/host/helper.mjs +1287 -488
- package/src/host/main.mjs +368 -30
- package/src/host/paths.mjs +17 -9
- package/src/host/pickFolder.mjs +11 -4
- package/src/host/settings.mjs +15 -2
- package/src/host/setup.mjs +54 -15
- package/src/host/skill-stats.mjs +6 -1
- package/src/host/taskIndex.mjs +464 -66
- package/src/host/taskOrder.mjs +128 -57
- package/src/host/version.mjs +15 -7
- package/src/host/wallpaper.mjs +76 -59
- package/src/host/webdav.mjs +66 -10
- package/src/inject/core.js +228 -103
- package/src/inject/features/alias-migration.js +5 -1
- package/src/inject/features/auto-rename.js +166 -0
- package/src/inject/features/file-menu.js +6 -2
- package/src/inject/features/idle-reclaim.js +31 -8
- package/src/inject/features/newtab-panels.js +11 -1
- package/src/inject/features/pinned-collapse.js +11 -3
- package/src/inject/features/plugin-card-retry.js +18 -8
- package/src/inject/features/plugin-updates.js +58 -0
- package/src/inject/features/sandbox-reclaim.js +17 -1
- package/src/inject/features/session-link.js +202 -0
- package/src/inject/features/session-switch.js +67 -30
- package/src/inject/features/settings-dialog.js +323 -124
- package/src/inject/features/status-bar.js +150 -28
- package/src/inject/features/subagent-icon.js +473 -0
- package/src/inject/features/table-copy.js +18 -2
- package/src/inject/features/task-order.js +47 -13
- package/src/inject/features/theme.js +88 -31
- package/src/inject/features/title-gen.js +5 -4
- package/src/inject/features/title-lock.js +13 -8
- package/src/inject/features/turn-usage.js +99 -47
- package/src/inject/features/ws-running.js +28 -13
- package/src/inject/index.js +7 -0
- package/src/inject/provider-fields.js +2 -2
- package/src/inject/ui.js +14 -0
package/src/host/helper.mjs
CHANGED
|
@@ -4,21 +4,21 @@
|
|
|
4
4
|
|
|
5
5
|
import { createServer } from 'node:http';
|
|
6
6
|
import { execFile, spawn, spawnSync } from 'node:child_process';
|
|
7
|
-
import { createDecipheriv, createHash } from 'node:crypto';
|
|
7
|
+
import { createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
8
8
|
import { appendFileSync, chmodSync, closeSync, copyFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
9
9
|
import { mkdtemp } from 'node:fs/promises'; // 注意:fs 的 mkdtemp 是回调版,await 它会把 undefined 当回调
|
|
10
10
|
import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
11
11
|
import { homedir, tmpdir, userInfo } from 'node:os';
|
|
12
12
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
13
|
-
import { readSettings,
|
|
14
|
-
import { taskIndexPath, probeTaskIndexWritable, remapTaskIndexPaths, taskIndexDriverAvailable, listOverriddenTitles, listTaskWorkspaceMap, listTaskStatuses, setTaskTitleIfNotOverridden, setCustomSessionTitle, isTaskTitleOverridden, reconcileCustomTitles, getTaskProviderModel, listVirtualProjects, countTasks } from './taskIndex.mjs';
|
|
13
|
+
import { readSettings, remapSettingsPathsAtomic, isProjectOpenInTabs } from './settings.mjs';
|
|
14
|
+
import { taskIndexPath, probeTaskIndexWritable, remapTaskIndexPaths, taskIndexDriverAvailable, listOverriddenTitles, listTaskWorkspaceMap, listTaskStatuses, listSessionsActivity, listSessionsTrace, listSessionModelUsage, listSubagentChildrenActivity, listProjectsUnread, listWorkspaceTaskIds, setTaskTitleIfNotOverridden, setCustomSessionTitle, isTaskTitleOverridden, reconcileCustomTitles, getTaskProviderModel, listVirtualProjects, countTasks, readRecentQa } from './taskIndex.mjs';
|
|
15
15
|
import { pickFolderSystem } from './pickFolder.mjs';
|
|
16
|
-
import {
|
|
16
|
+
import { reorderTasks } from './taskOrder.mjs';
|
|
17
17
|
import { webdavRequest, webdavPutWithMkcol, webdavHttpText, parseWebdavListing, findCurl } from './webdav.mjs';
|
|
18
|
-
import { resolveZcodeExecutable } from './paths.mjs';
|
|
18
|
+
import { resolveZcodeExecutable, resolveDataRootDir } from './paths.mjs';
|
|
19
19
|
import { skillStats, DEFAULT_METADATA_BUDGET } from './skill-stats.mjs';
|
|
20
20
|
|
|
21
|
-
const VERSION = '1.
|
|
21
|
+
const VERSION = '1.7.0';
|
|
22
22
|
|
|
23
23
|
// 全局提示词固定在用户主目录:官方加载器按 HOME/USERPROFILE 拼 .zcode/AGENTS.md,
|
|
24
24
|
// 不读 ZCODE_DATA_BASE_DIR(数据根迁走时全局指令仍在原位)。
|
|
@@ -37,7 +37,7 @@ function defaultRtkDir() {
|
|
|
37
37
|
}
|
|
38
38
|
|
|
39
39
|
// 主题功能的壁纸图库:用户上传的图片/视频都存这里,helper 以 /bg/file/<name> 提供,
|
|
40
|
-
// 注入层直接引用该 URL(媒体元素/CSS url()
|
|
40
|
+
// 注入层直接引用该 URL(媒体元素/CSS url() 带不了鉴权请求头,URL 带 ?t= token,见下)
|
|
41
41
|
const BG_DIR_NAME = 'backgrounds';
|
|
42
42
|
export function backgroundsDir(dataRoot) {
|
|
43
43
|
return join(dataRoot, BG_DIR_NAME);
|
|
@@ -122,7 +122,10 @@ export function renameOrReplace(tmp, dst) {
|
|
|
122
122
|
export function sweepDeferredBg(dir) {
|
|
123
123
|
try {
|
|
124
124
|
for (const n of readdirSync(dir)) {
|
|
125
|
-
|
|
125
|
+
// .deleted-* 是延迟删除的残留;结尾 .tmp 是上传中断留下的半截文件(正常
|
|
126
|
+
// 流程会即时改名或删掉)。都只清超过 24 小时的,避免误伤进行中的操作;
|
|
127
|
+
// 媒体文件扩展名有白名单,正常文件不会以 .tmp 结尾
|
|
128
|
+
if (!n.includes('.deleted-') && !n.endsWith('.tmp')) continue;
|
|
126
129
|
const f = join(dir, n);
|
|
127
130
|
try {
|
|
128
131
|
if (Date.now() - statSync(f).mtimeMs > 24 * 3600 * 1000) unlinkSync(f);
|
|
@@ -142,9 +145,18 @@ export function listBgFiles(dataRoot) {
|
|
|
142
145
|
} catch { return []; } // 目录不存在 = 空图库
|
|
143
146
|
}
|
|
144
147
|
|
|
148
|
+
// ?dir= 只认用户配置过的目录(全局文件夹 + 各分区目录)——仅凭 URL 上的 token
|
|
149
|
+
// 还不够,别让持 token 的调用列出/读取任意目录的文件。取文件与列目录两条路由共用这一个判定
|
|
150
|
+
function bgFolderDirAllowed(bgCfg, qDir) {
|
|
151
|
+
if (!qDir || qDir.length > 4096 || !isAbsolute(qDir)) return false;
|
|
152
|
+
const allowed = [bgCfg.folder,
|
|
153
|
+
bgCfg.regions?.left?.folder, bgCfg.regions?.center?.folder, bgCfg.regions?.right?.folder].filter(Boolean);
|
|
154
|
+
return allowed.includes(qDir);
|
|
155
|
+
}
|
|
156
|
+
|
|
145
157
|
// 视频壁纸帧率上限:ffmpeg 一次性转码出抽帧版存缓存目录,注入层先播原片、
|
|
146
158
|
// 转码完成再换。没有 ffmpeg 时接口直接报缺依赖,注入层保持原片播放
|
|
147
|
-
export const TRANSCODE_FPS = new Set([15, 30, 60]);
|
|
159
|
+
export const TRANSCODE_FPS = new Set([15, 30, 60, 90, 120]);
|
|
148
160
|
let ffmpegOk = null; // 三态:null 未探测 / true / false
|
|
149
161
|
function hasFfmpeg() {
|
|
150
162
|
if (ffmpegOk === null) {
|
|
@@ -157,6 +169,7 @@ export function transcodeDir(dataRoot) {
|
|
|
157
169
|
return join(dataRoot, 'cache', 'transcode');
|
|
158
170
|
}
|
|
159
171
|
const transcodeJobs = new Set(); // 正在转码的 key,防同一文件重复起 ffmpeg
|
|
172
|
+
const transcodeChildren = new Set(); // 在跑的 ffmpeg 子进程:退出/交接时统一收掉,防孤儿进程
|
|
160
173
|
const TRANSCODE_MAX_CONCURRENCY = 2; // 同时最多 2 个 ffmpeg,防批量请求打满 CPU/磁盘
|
|
161
174
|
// URL 路径段解码:非法 % 序列回 null(调用方回 400),不让 URIError 落成 500
|
|
162
175
|
let folderCfgCache = { at: 0, dir: '' };
|
|
@@ -166,14 +179,14 @@ function decodeName(raw) {
|
|
|
166
179
|
|
|
167
180
|
// 主题配置(设置 → 外观 → 主题/壁纸):skin 为皮肤 id(default = 不覆盖,
|
|
168
181
|
// custom = 用 custom 锚点色现算色阶);bg.mode 选壁纸来源——none 无壁纸 /
|
|
169
|
-
// library 本地图库(file
|
|
182
|
+
// library 本地图库(file 为当前文件,单选一张,轮换归文件夹)/ folder 文件夹
|
|
170
183
|
// (定时轮换,folderRandom 随机或顺序)/ url 图片网址(intervalMin 定时刷新)/
|
|
171
184
|
// web 网页(url 为页面地址,iframe 铺在界面后方);
|
|
172
185
|
// maskOpacity 遮罩不透明度 0-0.99(越高画面越向主题背景色淡化,文字对比越
|
|
173
186
|
// 清晰,默认 0.82)、blurPx 画面模糊 0-24px(默认 0)、panelOpacity 面板
|
|
174
187
|
// 不透明度 0-1(侧栏/面板/标签栏,越低透出画面越多,默认 0.3);
|
|
175
|
-
// transition 换壁纸转场(cut
|
|
176
|
-
// (0 原始,其余 15/30/60,需 ffmpeg 抽帧转码)、videoVolume 音量 0-1(默认 0
|
|
188
|
+
// transition 换壁纸转场(cut 直接切换 / fade 淡入淡出)、fpsCap 视频帧率上限
|
|
189
|
+
// (0 原始,其余 15/30/60/90/120,需 ffmpeg 抽帧转码)、videoVolume 音量 0-1(默认 0
|
|
177
190
|
// 静音)、playbackRate 倍速 0.5-2(默认 1);pauseOnHidden/pauseOnBlur/
|
|
178
191
|
// pauseOnBattery 三个暂停条件(默认开/关/关)
|
|
179
192
|
const THEME_SKINS = new Set(['default', 'dracula', 'nord', 'tokyonight', 'catppuccin', 'gruvbox', 'onedark', 'solarized', 'rosepine', 'everforest', 'nightowl', 'kanagawa', 'custom']);
|
|
@@ -204,11 +217,16 @@ function mergeBgRegion(src) {
|
|
|
204
217
|
file: mode === 'library' ? (str(src.file, 200) || '') : '',
|
|
205
218
|
folder: mode === 'folder' ? (str(src.folder, 4096) || '') : '',
|
|
206
219
|
url: mode === 'url' ? (str(src.url, 2000) || '').trim() : '',
|
|
220
|
+
// 分区独立缩放/遮罩:null = 跟随全局(只有分区行的控件会写这两项)
|
|
221
|
+
fit: BG_FITS.has(src.fit) ? src.fit : null,
|
|
222
|
+
maskOpacity: src.maskOpacity != null && src.maskOpacity !== '' && Number.isFinite(Number(src.maskOpacity))
|
|
223
|
+
? Math.min(0.99, Math.max(0, Number(src.maskOpacity))) : null,
|
|
207
224
|
};
|
|
208
225
|
}
|
|
209
226
|
export function mergeThemeConfig(saved) {
|
|
210
227
|
const t = saved && typeof saved === 'object' ? saved : {};
|
|
211
228
|
const bg = t.bg && typeof t.bg === 'object' ? t.bg : {};
|
|
229
|
+
const bgUrl = (str(bg.url, 2000) || '').trim();
|
|
212
230
|
const cfg = {
|
|
213
231
|
skin: THEME_SKINS.has(t.skin) ? t.skin : 'default',
|
|
214
232
|
custom: mergeCustomSkin(t.custom),
|
|
@@ -217,17 +235,18 @@ export function mergeThemeConfig(saved) {
|
|
|
217
235
|
file: str(bg.file, 200) || '',
|
|
218
236
|
folder: str(bg.folder, 4096) || '',
|
|
219
237
|
folderRandom: bg.folderRandom !== false,
|
|
220
|
-
url: (
|
|
238
|
+
url: /^https?:\/\//i.test(bgUrl) ? bgUrl : '', // 网页壁纸只收 http(s)(与 wallpaper CLI 校验一致)
|
|
221
239
|
// Number() 容错与相邻数值字段一致:外部写入方(手改配置/壁纸控制插件)写数字字符串也能生效
|
|
222
240
|
intervalMin: bg.intervalMin != null && Number.isFinite(Number(bg.intervalMin)) ? Math.min(1440, Math.max(0, Math.round(Number(bg.intervalMin)))) : 0,
|
|
223
241
|
fit: BG_FITS.has(bg.fit) ? bg.fit : 'cover',
|
|
224
242
|
// null/undefined/非数值都落默认(Number(null)=0 是有限数,须先排除 null)
|
|
225
|
-
maskOpacity: bg.maskOpacity != null && Number.isFinite(Number(bg.maskOpacity))
|
|
243
|
+
maskOpacity: bg.maskOpacity != null && bg.maskOpacity !== '' && Number.isFinite(Number(bg.maskOpacity))
|
|
226
244
|
? Math.min(0.99, Math.max(0, Number(bg.maskOpacity))) : 0.82,
|
|
227
245
|
blurPx: bg.blurPx != null && Number.isFinite(Number(bg.blurPx)) ? Math.min(24, Math.max(0, Math.round(bg.blurPx))) : 0,
|
|
228
|
-
panelOpacity: bg.panelOpacity != null && Number.isFinite(Number(bg.panelOpacity)) ? Math.min(1, Math.max(0, Number(bg.panelOpacity))) : 0.3,
|
|
246
|
+
panelOpacity: bg.panelOpacity != null && bg.panelOpacity !== '' && Number.isFinite(Number(bg.panelOpacity)) ? Math.min(1, Math.max(0, Number(bg.panelOpacity))) : 0.3,
|
|
229
247
|
transition: bg.transition === 'fade' ? 'fade' : 'cut',
|
|
230
248
|
fpsCap: TRANSCODE_FPS.has(Number(bg.fpsCap)) ? Number(bg.fpsCap) : 0,
|
|
249
|
+
dialogFrost: bg.dialogFrost !== false,
|
|
231
250
|
videoVolume: bg.videoVolume != null && Number.isFinite(Number(bg.videoVolume))
|
|
232
251
|
? Math.min(1, Math.max(0, Number(bg.videoVolume))) : 0,
|
|
233
252
|
playbackRate: bg.playbackRate != null && Number.isFinite(Number(bg.playbackRate))
|
|
@@ -252,7 +271,7 @@ export function mergeThemeConfig(saved) {
|
|
|
252
271
|
// mergeThemeConfig(clamp + 默认值)
|
|
253
272
|
export const BG_PARAM_KEYS = {
|
|
254
273
|
maskOpacity: 'number', blurPx: 'number', panelOpacity: 'number', videoVolume: 'number', playbackRate: 'number',
|
|
255
|
-
pauseOnHidden: 'boolean', pauseOnBlur: 'boolean', pauseOnBattery: 'boolean',
|
|
274
|
+
pauseOnHidden: 'boolean', pauseOnBlur: 'boolean', pauseOnBattery: 'boolean', dialogFrost: 'boolean',
|
|
256
275
|
fit: BG_FITS, transition: new Set(['cut', 'fade']), fpsCap: new Set([0, ...TRANSCODE_FPS]),
|
|
257
276
|
};
|
|
258
277
|
|
|
@@ -267,7 +286,8 @@ const ZCODE_PLUGINS_MARKETPLACE = 'duanluan-zcode-plugins';
|
|
|
267
286
|
const ZCODE_PLUGINS_MARKETPLACE_SOURCE = 'duanluan/zcode-plugins';
|
|
268
287
|
|
|
269
288
|
function cliPluginsDir() {
|
|
270
|
-
|
|
289
|
+
// 官方 CLI 数据目录跟 ZCODE_DATA_BASE_DIR 迁移(rollout/v2 同款),别固定 HOME
|
|
290
|
+
return join(resolveDataRootDir(), 'cli', 'plugins');
|
|
271
291
|
}
|
|
272
292
|
|
|
273
293
|
export function defaultConfig() {
|
|
@@ -281,10 +301,12 @@ export function defaultConfig() {
|
|
|
281
301
|
sessionSwitch: true, // 会话快捷切换(alt+z 上次会话;按住 alt x/c 弹窗导航,类 alt+tab)
|
|
282
302
|
titleLock: true, // 会话名锁定:手动重命名过的会话不被运行时推送的自动标题覆盖(侧栏钉回索引库中的名字)
|
|
283
303
|
wsRunningSpin: true, // 折叠项目运行提示:折叠后其中仍有会话运行时项目图标旋转
|
|
304
|
+
subagentIcon: true, // 子代理运行提示:任务行空闲图标位与折叠项目图标显示机器人(subagent-icon.js)
|
|
284
305
|
idleReclaim: true, // 空闲项目内存回收:长时间无活动的项目释放其会话进程(时长 idleReclaimMinutes)
|
|
285
306
|
toolbarIcons: true, // 侧栏菜单并入顶栏:新建任务/搜索/自动化/插件市场收成顶栏图标按钮(原菜单隐藏,点击转发)
|
|
286
307
|
pinnedCollapse: true, // 已置顶分区可折叠:标题可点折叠/展开任务列表(状态记 localStorage)
|
|
287
308
|
tableCopy: true, // 表格工具条"复制表格"按钮:富文本剪贴板,粘贴即表格(table-copy.js)
|
|
309
|
+
sessionLink: true, // 会话 ID 显示为任务名链接:聊天里的 sess_/session_ 显示为任务名,点击切换(session-link.js)
|
|
288
310
|
composerProvider: true, // 输入框模型名前显示供应商名(composer-provider.js)
|
|
289
311
|
},
|
|
290
312
|
// 空闲项目内存回收的判定时长(分钟,1–1440):项目无运行中会话、无后台命令
|
|
@@ -318,13 +340,16 @@ export function defaultConfig() {
|
|
|
318
340
|
// headroom 启用开关的记忆(供应商 id → { proxy, direct }):关闭时把走 headroom 的
|
|
319
341
|
// 供应商地址切回直连并记录下来,再次开启时按记录把地址切回代理
|
|
320
342
|
headroomRoutes: {},
|
|
321
|
-
//
|
|
322
|
-
//
|
|
343
|
+
// 自动重命名(原“任务名提示词”):新会话开始作答后按可配置的供应商与
|
|
344
|
+
// 提示词生成标题,并按“手动重命名”写入任务索引。默认关闭。provider:
|
|
323
345
|
// 'session' = 跟随当前会话(调用时从任务索引解析该会话的供应商,默认)、
|
|
324
346
|
// '' = 不跟随(自填 baseUrl/apiKey/format)、其余 = 供应商 id(保存时同步
|
|
325
347
|
// 解析一份 baseUrl/apiKey/format 副本,供应商日后被删仍可直连);
|
|
326
348
|
// model 默认 glm-5.3-flash(起名用快模型即可),跟随会话时可留空
|
|
327
|
-
//(用会话当前模型);prompt 留空 =
|
|
349
|
+
//(用会话当前模型);prompt 留空 = 内置默认提示词。
|
|
350
|
+
// 手动“自动重命名”(任务行悬浮按钮 / 右键菜单入口,取会话最近 recentQa
|
|
351
|
+
// 轮问答起名、已重命名也覆盖)不受 enabled 限制,入口各有开关:
|
|
352
|
+
// hoverBtn 任务行按钮、menuEntry 右键菜单项
|
|
328
353
|
titleGen: {
|
|
329
354
|
enabled: false,
|
|
330
355
|
customWritten: {},
|
|
@@ -334,6 +359,9 @@ export function defaultConfig() {
|
|
|
334
359
|
baseUrl: '',
|
|
335
360
|
apiKey: '',
|
|
336
361
|
format: '',
|
|
362
|
+
recentQa: 3,
|
|
363
|
+
hoverBtn: true,
|
|
364
|
+
menuEntry: true,
|
|
337
365
|
},
|
|
338
366
|
// HTTP 代理(http(s)://host:port):helper 发起的网络访问走它——插件市场更新/安装
|
|
339
367
|
// (zcode CLI → git)、headroom/rtk 的安装与升级(pip/GitHub)。空 = 不用代理。
|
|
@@ -418,21 +446,118 @@ function readFileSyncText(p) {
|
|
|
418
446
|
// 原子写任意 JSON 文件:先写临时文件再改名,避免崩溃留下半截 JSON
|
|
419
447
|
function writeJsonAtomic(file, obj) {
|
|
420
448
|
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
421
|
-
|
|
449
|
+
try { mkdirSync(dirname(file), { recursive: true }); } catch { /* 目录已存在 */ } // 数据目录缺失时先建,别让写入直接抛
|
|
450
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2), { encoding: 'utf8', mode: 0o600 }); // 配置含凭据,限制本人读写
|
|
422
451
|
renameSync(tmp, file);
|
|
423
452
|
}
|
|
424
453
|
|
|
454
|
+
// 读改写必须同步完成(loadConfig→改→saveConfig 中间不能加 await):
|
|
455
|
+
// HTTP 处理器靠单线程的同步原子性保证并发保存不互相覆盖字段
|
|
425
456
|
export function saveConfig(configFile, config) {
|
|
426
457
|
// 配置"存在但损坏"时拒绝写回:否则 title-gen/同步/别名等写路径会把默认值
|
|
427
458
|
// 整份覆盖上去(WebDAV 账号、样式、主题全丢且不可恢复)。POST /config 另有
|
|
428
459
|
// 显式报错,这里兜住其余调用方;修好文件后 loadConfig 会复位标记恢复可写。
|
|
429
460
|
// 保护只针对 zcodepro.json:写别的文件(/zcode-config 写 cli/config.json)
|
|
430
|
-
// 直接用 writeJsonAtomic
|
|
461
|
+
// 直接用 writeJsonAtomic,别被这个标记误伤成静默不写。
|
|
462
|
+
// 返回是否写入:调用方据此报错(同步导入不能在拒写时还报成功)
|
|
431
463
|
if (configUnreadable) {
|
|
432
464
|
console.error('[zcodepro] zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置');
|
|
433
|
-
return;
|
|
465
|
+
return false;
|
|
434
466
|
}
|
|
435
467
|
writeJsonAtomic(configFile, config);
|
|
468
|
+
return true;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// —— zcodepro.json 跨进程写锁 ——————————————————————————————————
|
|
472
|
+
// 多个进程(helper、wallpaper CLI、同步导入…)会同时读改写 zcodepro.json,
|
|
473
|
+
// 不互斥时各拿旧快照写回,会把对方改的整段配置(WebDAV 凭据、别名、样式)盖掉。
|
|
474
|
+
// 锁 = 配置文件同目录下的锁目录(mkdir 原子创建),目录里写持有者信息(pid + 随机 token)。
|
|
475
|
+
const CONFIG_LOCK_STALE_MS = 10_000; // 锁龄超过这个数按悬挂锁接管
|
|
476
|
+
const CONFIG_LOCK_WAIT_MS = 5_000; // 等锁上限;等不到带提示继续尽力而为
|
|
477
|
+
|
|
478
|
+
// 进程还在不在(pid 被系统复用的极端情形由锁龄上限兜底)
|
|
479
|
+
function pidAlive(pid) {
|
|
480
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
481
|
+
try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// 抢一次锁:mkdir 成功即持有;已有锁时仅在持有者死亡或锁龄超时才拆掉接管。
|
|
485
|
+
// 返回是否拿到(没拿到由调用方等待重试)
|
|
486
|
+
function tryAcquireConfigLock(configFile, token) {
|
|
487
|
+
const lockDir = configFile + '.lock';
|
|
488
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
489
|
+
try {
|
|
490
|
+
mkdirSync(lockDir); // 原子创建:同时只有一个进程成功
|
|
491
|
+
try {
|
|
492
|
+
writeFileSync(join(lockDir, 'holder.json'), JSON.stringify({ pid: process.pid, token }), 'utf8');
|
|
493
|
+
} catch { /* 持有者信息写失败不影响锁本身,释放时按超时接管兜底 */ }
|
|
494
|
+
return true;
|
|
495
|
+
} catch (err) {
|
|
496
|
+
if (err.code !== 'EEXIST') throw err;
|
|
497
|
+
let stale = false;
|
|
498
|
+
try {
|
|
499
|
+
let alive = true;
|
|
500
|
+
try {
|
|
501
|
+
const holder = JSON.parse(readFileSync(join(lockDir, 'holder.json'), 'utf8'));
|
|
502
|
+
alive = pidAlive(Number(holder.pid));
|
|
503
|
+
} catch { alive = true; } // 持有者信息缺失/写坏:只按锁龄判悬挂
|
|
504
|
+
stale = Date.now() - statSync(lockDir).mtimeMs > CONFIG_LOCK_STALE_MS || !alive;
|
|
505
|
+
} catch { stale = true; } // 锁目录正被删/读不了:按悬挂接管
|
|
506
|
+
if (!stale) return false;
|
|
507
|
+
try { rmSync(lockDir, { recursive: true, force: true }); } catch { return false; }
|
|
508
|
+
// 接管后回到循环重试 mkdir(可能被另一个进程抢先)
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return false;
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// 释放锁:只认自己那份持有者信息,被别人接管后不能把别人的锁删掉
|
|
515
|
+
function releaseConfigLock(configFile, token) {
|
|
516
|
+
const lockDir = configFile + '.lock';
|
|
517
|
+
try {
|
|
518
|
+
const holder = JSON.parse(readFileSync(join(lockDir, 'holder.json'), 'utf8'));
|
|
519
|
+
if (holder.token !== token) return;
|
|
520
|
+
} catch { return; } // 读不到持有者信息(已被接管后删除等):不动目录,留超时接管
|
|
521
|
+
try { rmSync(lockDir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// 在跨进程锁内同步执行 fn 并返回其结果:fn 里保持同步读改写(loadConfig→改→
|
|
525
|
+
// saveConfig 中间不要 await)。等锁上限约 5 秒,等不到带提示继续尽力而为
|
|
526
|
+
//(不加锁至少还能写成,别直接失败)。调用点是 async 就 await 这个函数。
|
|
527
|
+
export async function withConfigLock(configFile, fn) {
|
|
528
|
+
const token = randomBytes(12).toString('hex');
|
|
529
|
+
const deadline = Date.now() + CONFIG_LOCK_WAIT_MS;
|
|
530
|
+
while (!tryAcquireConfigLock(configFile, token)) {
|
|
531
|
+
if (Date.now() >= deadline) {
|
|
532
|
+
console.error('[zcodepro] 等 zcodepro.json 写锁超时,继续无锁写入(可能与别的进程互相覆盖)');
|
|
533
|
+
return fn();
|
|
534
|
+
}
|
|
535
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
536
|
+
}
|
|
537
|
+
try {
|
|
538
|
+
return fn();
|
|
539
|
+
} finally {
|
|
540
|
+
releaseConfigLock(configFile, token);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// 同步等锁变体(同步调用点用,如 setHeadroomUsage):Atomics.wait 睡眠重试,
|
|
545
|
+
// 语义与 withConfigLock 相同
|
|
546
|
+
export function withConfigLockSync(configFile, fn) {
|
|
547
|
+
const token = randomBytes(12).toString('hex');
|
|
548
|
+
const deadline = Date.now() + CONFIG_LOCK_WAIT_MS;
|
|
549
|
+
while (!tryAcquireConfigLock(configFile, token)) {
|
|
550
|
+
if (Date.now() >= deadline) {
|
|
551
|
+
console.error('[zcodepro] 等 zcodepro.json 写锁超时,继续无锁写入(可能与别的进程互相覆盖)');
|
|
552
|
+
return fn();
|
|
553
|
+
}
|
|
554
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
555
|
+
}
|
|
556
|
+
try {
|
|
557
|
+
return fn();
|
|
558
|
+
} finally {
|
|
559
|
+
releaseConfigLock(configFile, token);
|
|
560
|
+
}
|
|
436
561
|
}
|
|
437
562
|
|
|
438
563
|
// 一次性配置迁移已移除(原 wsRunningSpinOff):旧实验版“折叠项目运行提示”
|
|
@@ -471,18 +596,65 @@ function readBody(req, limitBytes = 1 << 20) {
|
|
|
471
596
|
}
|
|
472
597
|
|
|
473
598
|
// 软件代理(设置弹窗“代理”标签页):helper 发起的网络访问(zcode CLI→git、pip、
|
|
474
|
-
// WebDAV 同步)按用途(proxyScopes
|
|
475
|
-
//
|
|
599
|
+
// WebDAV 同步)按用途(proxyScopes)走这里。activeProxyUrl 只存手填代理;没填时
|
|
600
|
+
// 按需读 Windows 系统代理(带短缓存,Clash 开关后能自动跟上)。
|
|
476
601
|
let activeProxyUrl = '';
|
|
477
602
|
let activeProxyScopes = { plugins: true, deps: true, sync: false };
|
|
603
|
+
let systemProxyCache = { url: '', at: 0 };
|
|
604
|
+
|
|
605
|
+
// ProxyServer 的值有两种写法:host:port,或 http=host:port;https=host:port。
|
|
606
|
+
// 取 https(没有就取 http),补上协议。导出以便测试。
|
|
607
|
+
export function parseWindowsProxyServer(raw) {
|
|
608
|
+
if (!raw) return '';
|
|
609
|
+
const clean = (s) => String(s).trim().replace(/^"|"$/g, '').trim();
|
|
610
|
+
let v = clean(raw);
|
|
611
|
+
if (v.includes('=')) {
|
|
612
|
+
const parts = {};
|
|
613
|
+
for (const seg of v.split(';')) {
|
|
614
|
+
const i = seg.indexOf('=');
|
|
615
|
+
if (i > 0) parts[seg.slice(0, i).trim().toLowerCase()] = clean(seg.slice(i + 1));
|
|
616
|
+
}
|
|
617
|
+
v = parts.https || parts.http || '';
|
|
618
|
+
}
|
|
619
|
+
if (!v) return '';
|
|
620
|
+
const url = /^[a-z]+:\/\//i.test(v) ? v : `http://${v}`;
|
|
621
|
+
// 注册表值不做校验会被坏值原样塞进 HTTP_PROXY;和手填代理一样要求 host:port
|
|
622
|
+
return /^https?:\/\/[^\s/]+:\d+$/.test(url) ? url : '';
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Windows 系统代理(Internet 选项)。没单独配代理时沿用它:新电脑上 Clash 等
|
|
626
|
+
// 工具通常只开系统代理,用户不会再为单个应用填一遍地址。
|
|
627
|
+
function windowsSystemProxy() {
|
|
628
|
+
if (process.platform !== 'win32') return '';
|
|
629
|
+
const query = (name) => {
|
|
630
|
+
const r = spawnSync('reg', ['query', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', '/v', name],
|
|
631
|
+
{ encoding: 'utf8', windowsHide: true, timeout: 5000 });
|
|
632
|
+
const m = new RegExp(`${name}\\s+REG_(?:DWORD|SZ)\\s+(.+)`, 'i').exec(r.stdout || '');
|
|
633
|
+
return m ? m[1].trim() : '';
|
|
634
|
+
};
|
|
635
|
+
if (!/^0x0*1$/i.test(query('ProxyEnable'))) return '';
|
|
636
|
+
return parseWindowsProxyServer(query('ProxyServer'));
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// 生效代理:手填优先;没填时读 Windows 系统代理并缓存 30 秒。Clash 在 ZCode
|
|
640
|
+
// 之后启动或退出时能自动跟上,又不会每次请求都跑 reg。
|
|
641
|
+
function effectiveProxyUrl() {
|
|
642
|
+
if (activeProxyUrl) return activeProxyUrl;
|
|
643
|
+
if (Date.now() - systemProxyCache.at > 30_000) {
|
|
644
|
+
systemProxyCache = { url: windowsSystemProxy(), at: Date.now() };
|
|
645
|
+
}
|
|
646
|
+
return systemProxyCache.url;
|
|
647
|
+
}
|
|
478
648
|
|
|
479
649
|
// scope:'plugins'(插件市场)/ 'deps'(headroom、rtk)/ 'sync'(WebDAV 同步);
|
|
480
650
|
// 'none' 表示这次调用与下载无关(headroom 生命周期钩子等),永不注入下载代理
|
|
481
651
|
function proxyEnv(extra = {}, scope = 'deps') {
|
|
482
|
-
if (scope === 'none' || !
|
|
652
|
+
if (scope === 'none' || !activeProxyScopes[scope]) return extra;
|
|
653
|
+
const proxy = effectiveProxyUrl();
|
|
654
|
+
if (!proxy) return extra;
|
|
483
655
|
return {
|
|
484
|
-
HTTP_PROXY:
|
|
485
|
-
http_proxy:
|
|
656
|
+
HTTP_PROXY: proxy, HTTPS_PROXY: proxy,
|
|
657
|
+
http_proxy: proxy, https_proxy: proxy,
|
|
486
658
|
...extra,
|
|
487
659
|
};
|
|
488
660
|
}
|
|
@@ -490,7 +662,7 @@ function proxyEnv(extra = {}, scope = 'deps') {
|
|
|
490
662
|
// 该用途当前是否走代理:同步按 proxyUrl 参数传给 webdav(curl 路径用,
|
|
491
663
|
// fetch 兜底路径不认代理环境变量)
|
|
492
664
|
function proxyUrlFor(scope) {
|
|
493
|
-
return activeProxyScopes[scope] ?
|
|
665
|
+
return activeProxyScopes[scope] ? effectiveProxyUrl() : '';
|
|
494
666
|
}
|
|
495
667
|
|
|
496
668
|
// 智能起名诊断日志:追加到 <dataRoot>/zcodepro.log(与启动诊断同文件),超 512KB
|
|
@@ -564,7 +736,9 @@ function zcodeConfigSnapshot(dataRoot) {
|
|
|
564
736
|
return { ok: true, values, configured, stats };
|
|
565
737
|
}
|
|
566
738
|
|
|
567
|
-
export function startHelper({ port, token, dataRoot, state, agentsFile = defaultAgentsFile() }) {
|
|
739
|
+
export function startHelper({ port, token, dataRoot, state, agentsFile = defaultAgentsFile(), listenTries = 40, rolloutDir = '', visionFile = '' }) {
|
|
740
|
+
if (rolloutDir) rolloutDirOverride = rolloutDir;
|
|
741
|
+
if (!visionFile) visionFile = defaultVisionFile(); // 测试可覆盖,别把启动补写落到真实 ~/.zcode
|
|
568
742
|
const configFile = join(dataRoot, 'zcodepro.json');
|
|
569
743
|
const settingsFile = join(dataRoot, 'v2', 'setting.json');
|
|
570
744
|
const bootConfig = loadConfig(configFile);
|
|
@@ -654,6 +828,16 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
654
828
|
res2.end('read error');
|
|
655
829
|
}
|
|
656
830
|
};
|
|
831
|
+
// 媒体路由(CSS url()/<video> 引用,带不了鉴权请求头):认 URL 上的
|
|
832
|
+
// ?t= token,外部页面猜不到 token 就读不走图库媒体、也做不了存在性探测
|
|
833
|
+
if (req.method === 'GET' && (url.pathname.startsWith('/bg/file/')
|
|
834
|
+
|| url.pathname.startsWith('/bg/folder/file/') || url.pathname.startsWith('/bg/transcode/file/'))) {
|
|
835
|
+
const q = url.searchParams.get('t');
|
|
836
|
+
if (!token || (req.headers['x-zcodepro-token'] !== token && q !== token)) {
|
|
837
|
+
json(res, 401, { ok: false, error: 'unauthorized' });
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
657
841
|
if (req.method === 'GET' && url.pathname.startsWith('/bg/file/')) {
|
|
658
842
|
const dec = decodeName(url.pathname.slice('/bg/file/'.length));
|
|
659
843
|
if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
|
|
@@ -666,12 +850,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
666
850
|
const qDir = url.searchParams.get('dir');
|
|
667
851
|
let dir;
|
|
668
852
|
if (qDir) {
|
|
669
|
-
//
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
const allowed = [cfgB.folder,
|
|
673
|
-
cfgB.regions?.left?.folder, cfgB.regions?.center?.folder, cfgB.regions?.right?.folder].filter(Boolean);
|
|
674
|
-
if (qDir.length > 4096 || !isAbsolute(qDir) || !allowed.includes(qDir)) {
|
|
853
|
+
// dir 只认用户配置过的目录(全局文件夹 + 各分区目录),
|
|
854
|
+
// 判定与 /bg/folder/list 共用 bgFolderDirAllowed
|
|
855
|
+
if (!bgFolderDirAllowed(loadConfig(configFile).theme.bg, qDir)) {
|
|
675
856
|
json(res, 400, { ok: false, error: 'dir 参数无效或未配置' });
|
|
676
857
|
return;
|
|
677
858
|
}
|
|
@@ -697,7 +878,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
697
878
|
serveBgFile(dec, transcodeDir(dataRoot), res);
|
|
698
879
|
return;
|
|
699
880
|
}
|
|
700
|
-
|
|
881
|
+
// 空 token 视为配置错误直接拒绝(fail-closed),别放成免鉴权
|
|
882
|
+
if (!token || req.headers['x-zcodepro-token'] !== token) {
|
|
701
883
|
json(res, 401, { ok: false, error: 'unauthorized' });
|
|
702
884
|
return;
|
|
703
885
|
}
|
|
@@ -712,131 +894,140 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
712
894
|
}
|
|
713
895
|
if (req.method === 'POST' && url.pathname === '/config') {
|
|
714
896
|
const body = await readBody(req);
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
const v = body.proxy.trim();
|
|
722
|
-
if (v === '') current.proxy = '';
|
|
723
|
-
else if (/^https?:\/\/\S+:\d+$/.test(v) && v.length <= 300) current.proxy = v;
|
|
724
|
-
else {
|
|
725
|
-
json(res, 400, { ok: false, code: 'proxy-invalid', error: '代理地址需形如 http://127.0.0.1:7890,或留空清除' });
|
|
897
|
+
// 整段读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
898
|
+
// 防止两个写入方各拿旧快照写回、互相覆盖整份配置
|
|
899
|
+
await withConfigLock(configFile, () => {
|
|
900
|
+
const current = loadConfig(configFile);
|
|
901
|
+
if (configUnreadable) {
|
|
902
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置;请先修复该文件' });
|
|
726
903
|
return;
|
|
727
904
|
}
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
905
|
+
if (body && typeof body === 'object' && typeof body.proxy === 'string') {
|
|
906
|
+
const v = body.proxy.trim();
|
|
907
|
+
if (v === '') current.proxy = '';
|
|
908
|
+
else if (/^https?:\/\/\S+:\d+$/.test(v) && v.length <= 300) current.proxy = v;
|
|
909
|
+
else {
|
|
910
|
+
json(res, 400, { ok: false, code: 'proxy-invalid', error: '代理地址需形如 http://127.0.0.1:7890,或留空清除' });
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
activeProxyUrl = current.proxy;
|
|
914
|
+
if (!current.proxy) systemProxyCache = { url: '', at: 0 }; // 清空手填后立即重读系统代理
|
|
734
915
|
}
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
// 会话名锁定开关的每次变化都落日志:它被意外关闭两次(页面里是关、
|
|
742
|
-
// 配置文件是开,来源不明),有记录才能查到是谁改的
|
|
743
|
-
if (typeof body.features.titleLock === 'boolean' && body.features.titleLock !== (loadConfig(configFile).features.titleLock !== false)) {
|
|
744
|
-
titleGenLog(dataRoot, `titleLock ${body.features.titleLock ? 'on' : 'off'}(此前为 ${!body.features.titleLock ? 'on' : 'off'})`);
|
|
916
|
+
if (body && typeof body === 'object' && body.proxyScopes && typeof body.proxyScopes === 'object') {
|
|
917
|
+
// 代理生效范围按单项提交(每个开关只改自己那项),即时生效
|
|
918
|
+
for (const k of ['plugins', 'deps', 'sync']) {
|
|
919
|
+
if (typeof body.proxyScopes[k] === 'boolean') current.proxyScopes[k] = body.proxyScopes[k];
|
|
920
|
+
}
|
|
921
|
+
activeProxyScopes = { ...current.proxyScopes };
|
|
745
922
|
}
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
if (body && typeof body === 'object' && typeof body.idleReclaimMinutes === 'number' && Number.isFinite(body.idleReclaimMinutes)) {
|
|
749
|
-
current.idleReclaimMinutes = Math.min(1440, Math.max(1, Math.round(body.idleReclaimMinutes)));
|
|
750
|
-
}
|
|
751
|
-
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
752
|
-
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
753
|
-
}
|
|
754
|
-
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
755
|
-
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
756
|
-
}
|
|
757
|
-
// 会话快捷切换的键位(设置 → 快捷键里修改):键名固定,值限单个字母或数字
|
|
758
|
-
if (body && typeof body === 'object' && body.shortcuts && typeof body.shortcuts === 'object') {
|
|
759
|
-
const patch = {};
|
|
760
|
-
for (const k of ['switchLast', 'switchPrev', 'switchNext', 'switchRecent', 'switchAttention']) {
|
|
761
|
-
const v = body.shortcuts[k];
|
|
762
|
-
if (typeof v === 'string' && /^[a-z0-9]$/.test(v)) patch[k] = v;
|
|
923
|
+
if (body && typeof body === 'object' && typeof body.devMode === 'boolean') {
|
|
924
|
+
current.devMode = body.devMode;
|
|
763
925
|
}
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
if (body && typeof body === 'object' && body.statusBar && typeof body.statusBar === 'object') {
|
|
770
|
-
const next = { ...(current.statusBar || {}) };
|
|
771
|
-
if (Array.isArray(body.statusBar.items)) {
|
|
772
|
-
const valid = new Set(['ctx', 'questions', 'todayTokens', 'totalTokens', 'tasks']);
|
|
773
|
-
const seen = new Set();
|
|
774
|
-
const items = [];
|
|
775
|
-
for (const it of body.statusBar.items) {
|
|
776
|
-
if (!it || !valid.has(it.id) || seen.has(it.id)) continue;
|
|
777
|
-
seen.add(it.id);
|
|
778
|
-
items.push({ id: it.id, on: it.on !== false });
|
|
926
|
+
if (body && typeof body === 'object' && body.features && typeof body.features === 'object') {
|
|
927
|
+
// 会话名锁定开关的每次变化都落日志:它被意外关闭两次(页面里是关、
|
|
928
|
+
// 配置文件是开,来源不明),有记录才能查到是谁改的
|
|
929
|
+
if (typeof body.features.titleLock === 'boolean' && body.features.titleLock !== (loadConfig(configFile).features.titleLock !== false)) {
|
|
930
|
+
titleGenLog(dataRoot, `titleLock ${body.features.titleLock ? 'on' : 'off'}(此前为 ${!body.features.titleLock ? 'on' : 'off'})`);
|
|
779
931
|
}
|
|
780
|
-
|
|
932
|
+
applyFeaturesPartial(current.features, body.features);
|
|
933
|
+
}
|
|
934
|
+
if (body && typeof body === 'object' && typeof body.idleReclaimMinutes === 'number' && Number.isFinite(body.idleReclaimMinutes)) {
|
|
935
|
+
current.idleReclaimMinutes = Math.min(1440, Math.max(1, Math.round(body.idleReclaimMinutes)));
|
|
936
|
+
}
|
|
937
|
+
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
938
|
+
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
939
|
+
}
|
|
940
|
+
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
941
|
+
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
781
942
|
}
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
const
|
|
785
|
-
const
|
|
786
|
-
|
|
787
|
-
if (
|
|
788
|
-
tseen.add(it.id);
|
|
789
|
-
turnItems.push({ id: it.id, on: it.on !== false });
|
|
943
|
+
// 会话快捷切换的键位(设置 → 快捷键里修改):键名固定,值限单个字母或数字
|
|
944
|
+
if (body && typeof body === 'object' && body.shortcuts && typeof body.shortcuts === 'object') {
|
|
945
|
+
const patch = {};
|
|
946
|
+
for (const k of ['switchLast', 'switchPrev', 'switchNext', 'switchRecent', 'switchAttention']) {
|
|
947
|
+
const v = body.shortcuts[k];
|
|
948
|
+
if (typeof v === 'string' && /^[a-z0-9]$/.test(v)) patch[k] = v;
|
|
790
949
|
}
|
|
791
|
-
|
|
950
|
+
current.shortcuts = { ...(current.shortcuts || {}), ...patch };
|
|
792
951
|
}
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
pauseOnBattery: bt.bg && bt.bg.pauseOnBattery !== undefined ? bt.bg.pauseOnBattery : cur.bg.pauseOnBattery,
|
|
822
|
-
regions: bt.bg && bt.bg.regions !== undefined ? bt.bg.regions : cur.bg.regions,
|
|
823
|
-
},
|
|
824
|
-
};
|
|
825
|
-
current.theme = mergeThemeConfig(next);
|
|
826
|
-
}
|
|
827
|
-
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
828
|
-
current.titleGen = mergeTitleGenConfig({ ...current.titleGen, ...body.titleGen });
|
|
829
|
-
}
|
|
830
|
-
// 一次性迁移标记(如别名迁移弹窗的“暂不迁移”):按项合并,只接受布尔值
|
|
831
|
-
if (body && typeof body === 'object' && body.migrations && typeof body.migrations === 'object') {
|
|
832
|
-
const patch = {};
|
|
833
|
-
for (const [k, v] of Object.entries(body.migrations)) {
|
|
834
|
-
if (typeof v === 'boolean') patch[k] = v;
|
|
952
|
+
// 状态栏统计(设置 → 样式 → 状态栏):items(任务统计项)与
|
|
953
|
+
// turnItems(每轮统计项)两个清单各自整表覆盖,谁在请求里就更新谁;
|
|
954
|
+
// id 白名单 + 去重保序,未知项丢弃
|
|
955
|
+
if (body && typeof body === 'object' && body.statusBar && typeof body.statusBar === 'object') {
|
|
956
|
+
const next = { ...(current.statusBar || {}) };
|
|
957
|
+
if (Array.isArray(body.statusBar.items)) {
|
|
958
|
+
const valid = new Set(['ctx', 'tokRate', 'questions', 'todayTokens', 'totalTokens', 'tasks']);
|
|
959
|
+
const seen = new Set();
|
|
960
|
+
const items = [];
|
|
961
|
+
for (const it of body.statusBar.items) {
|
|
962
|
+
if (!it || !valid.has(it.id) || seen.has(it.id)) continue;
|
|
963
|
+
seen.add(it.id);
|
|
964
|
+
items.push({ id: it.id, on: it.on !== false });
|
|
965
|
+
}
|
|
966
|
+
next.items = items;
|
|
967
|
+
}
|
|
968
|
+
if (Array.isArray(body.statusBar.turnItems)) {
|
|
969
|
+
const turnValid = new Set(['turnIn', 'turnOut', 'turnCache']);
|
|
970
|
+
const tseen = new Set();
|
|
971
|
+
const turnItems = [];
|
|
972
|
+
for (const it of body.statusBar.turnItems) {
|
|
973
|
+
if (!it || !turnValid.has(it.id) || tseen.has(it.id)) continue;
|
|
974
|
+
tseen.add(it.id);
|
|
975
|
+
turnItems.push({ id: it.id, on: it.on !== false });
|
|
976
|
+
}
|
|
977
|
+
next.turnItems = turnItems;
|
|
978
|
+
}
|
|
979
|
+
current.statusBar = next;
|
|
835
980
|
}
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
981
|
+
// 主题(设置 → 样式 → 颜色/背景图):按字段合并,白名单校验在
|
|
982
|
+
// mergeThemeConfig;library 的 file 与 folder 的目录可能指向已不存在的
|
|
983
|
+
// 目标(图已删/目录移走/同步后缺失),注入层按“取不到 = 无背景”降级
|
|
984
|
+
if (body && typeof body === 'object' && body.theme && typeof body.theme === 'object') {
|
|
985
|
+
const bt = body.theme;
|
|
986
|
+
const cur = current.theme;
|
|
987
|
+
const next = {
|
|
988
|
+
skin: bt.skin !== undefined ? bt.skin : cur.skin,
|
|
989
|
+
custom: bt.custom !== undefined ? bt.custom : cur.custom,
|
|
990
|
+
bg: {
|
|
991
|
+
mode: bt.bg && bt.bg.mode !== undefined ? bt.bg.mode : cur.bg.mode,
|
|
992
|
+
file: bt.bg && bt.bg.file !== undefined ? bt.bg.file : cur.bg.file,
|
|
993
|
+
folder: bt.bg && bt.bg.folder !== undefined ? bt.bg.folder : cur.bg.folder,
|
|
994
|
+
folderRandom: bt.bg && bt.bg.folderRandom !== undefined ? bt.bg.folderRandom : cur.bg.folderRandom,
|
|
995
|
+
url: bt.bg && bt.bg.url !== undefined ? bt.bg.url : cur.bg.url,
|
|
996
|
+
intervalMin: bt.bg && bt.bg.intervalMin !== undefined ? bt.bg.intervalMin : cur.bg.intervalMin,
|
|
997
|
+
fit: bt.bg && bt.bg.fit !== undefined ? bt.bg.fit : cur.bg.fit,
|
|
998
|
+
maskOpacity: bt.bg && bt.bg.maskOpacity !== undefined ? bt.bg.maskOpacity : cur.bg.maskOpacity,
|
|
999
|
+
blurPx: bt.bg && bt.bg.blurPx !== undefined ? bt.bg.blurPx : cur.bg.blurPx,
|
|
1000
|
+
panelOpacity: bt.bg && bt.bg.panelOpacity !== undefined ? bt.bg.panelOpacity : cur.bg.panelOpacity,
|
|
1001
|
+
transition: bt.bg && bt.bg.transition !== undefined ? bt.bg.transition : cur.bg.transition,
|
|
1002
|
+
fpsCap: bt.bg && bt.bg.fpsCap !== undefined ? bt.bg.fpsCap : cur.bg.fpsCap,
|
|
1003
|
+
videoVolume: bt.bg && bt.bg.videoVolume !== undefined ? bt.bg.videoVolume : cur.bg.videoVolume,
|
|
1004
|
+
playbackRate: bt.bg && bt.bg.playbackRate !== undefined ? bt.bg.playbackRate : cur.bg.playbackRate,
|
|
1005
|
+
pauseOnHidden: bt.bg && bt.bg.pauseOnHidden !== undefined ? bt.bg.pauseOnHidden : cur.bg.pauseOnHidden,
|
|
1006
|
+
pauseOnBlur: bt.bg && bt.bg.pauseOnBlur !== undefined ? bt.bg.pauseOnBlur : cur.bg.pauseOnBlur,
|
|
1007
|
+
pauseOnBattery: bt.bg && bt.bg.pauseOnBattery !== undefined ? bt.bg.pauseOnBattery : cur.bg.pauseOnBattery,
|
|
1008
|
+
dialogFrost: bt.bg && bt.bg.dialogFrost !== undefined ? bt.bg.dialogFrost : cur.bg.dialogFrost,
|
|
1009
|
+
regions: bt.bg && bt.bg.regions !== undefined ? bt.bg.regions : cur.bg.regions,
|
|
1010
|
+
},
|
|
1011
|
+
};
|
|
1012
|
+
current.theme = mergeThemeConfig(next);
|
|
1013
|
+
}
|
|
1014
|
+
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
1015
|
+
current.titleGen = mergeTitleGenConfig({ ...current.titleGen, ...body.titleGen });
|
|
1016
|
+
}
|
|
1017
|
+
// 一次性迁移标记(如别名迁移弹窗的“暂不迁移”):按项合并,只接受布尔值
|
|
1018
|
+
if (body && typeof body === 'object' && body.migrations && typeof body.migrations === 'object') {
|
|
1019
|
+
const patch = {};
|
|
1020
|
+
for (const [k, v] of Object.entries(body.migrations)) {
|
|
1021
|
+
if (typeof v === 'boolean') patch[k] = v;
|
|
1022
|
+
}
|
|
1023
|
+
current.migrations = { ...(current.migrations || {}), ...patch };
|
|
1024
|
+
}
|
|
1025
|
+
if (!saveConfig(configFile, current)) {
|
|
1026
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
json(res, 200, { ok: true, config: current });
|
|
1030
|
+
});
|
|
840
1031
|
return;
|
|
841
1032
|
}
|
|
842
1033
|
// —— ZCode CLI 行为配置(设置 → 行为 → ZCode CLI):读写 ~/.zcode/cli/config.json
|
|
@@ -883,7 +1074,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
883
1074
|
json(res, 200, zcodeConfigSnapshot(zcodeDataRoot()));
|
|
884
1075
|
return;
|
|
885
1076
|
}
|
|
886
|
-
// —— 主题背景图库:列表 / base64 上传 /
|
|
1077
|
+
// —— 主题背景图库:列表 / base64 上传 / 删除(取文件见上方的 /bg/file,URL 带 ?t= token)——
|
|
887
1078
|
if (req.method === 'GET' && url.pathname === '/bg') {
|
|
888
1079
|
json(res, 200, { ok: true, files: listBgFiles(dataRoot), maxCount: BG_MAX_COUNT });
|
|
889
1080
|
return;
|
|
@@ -922,7 +1113,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
922
1113
|
}
|
|
923
1114
|
try {
|
|
924
1115
|
mkdirSync(dir, { recursive: true });
|
|
925
|
-
|
|
1116
|
+
// 临时名带 pid+随机:两个写者(上传/同步下载)撞同一文件名时不共用一个 .tmp
|
|
1117
|
+
const tmp = join(dir, `${name}.${process.pid}.${Date.now().toString(36)}.tmp`);
|
|
926
1118
|
writeFileSync(tmp, buf);
|
|
927
1119
|
renameOrReplace(tmp, join(dir, name));
|
|
928
1120
|
} catch (errBg) {
|
|
@@ -1031,7 +1223,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1031
1223
|
return;
|
|
1032
1224
|
}
|
|
1033
1225
|
if (!TRANSCODE_FPS.has(fps)) {
|
|
1034
|
-
json(res, 400, { ok: false, code: 'transcode-fps', error: '
|
|
1226
|
+
json(res, 400, { ok: false, code: 'transcode-fps', error: `帧率上限仅支持 ${[...TRANSCODE_FPS].join('/')}` });
|
|
1035
1227
|
return;
|
|
1036
1228
|
}
|
|
1037
1229
|
const srcStat = statSync(src);
|
|
@@ -1057,20 +1249,23 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1057
1249
|
const vf = `fps=${fps},scale=min(1920\\,iw):min(1920\\,ih):force_original_aspect_ratio=decrease`;
|
|
1058
1250
|
let child;
|
|
1059
1251
|
try {
|
|
1060
|
-
child = spawn('ffmpeg', ['-y', '-i', src, '-vf', vf, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', tmp], { stdio: 'ignore' });
|
|
1252
|
+
child = spawn('ffmpeg', ['-y', '-i', src, '-vf', vf, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', tmp], { stdio: 'ignore', windowsHide: true });
|
|
1253
|
+
transcodeChildren.add(child);
|
|
1061
1254
|
} catch (errSpawn) {
|
|
1062
1255
|
transcodeJobs.delete(key); // 同步抛错也把名额放掉
|
|
1063
1256
|
throw errSpawn;
|
|
1064
1257
|
}
|
|
1065
1258
|
child.on('exit', (code) => {
|
|
1066
1259
|
transcodeJobs.delete(key);
|
|
1260
|
+
transcodeChildren.delete(child);
|
|
1067
1261
|
try {
|
|
1068
1262
|
if (code === 0) renameOrReplace(tmp, out); // renameOrReplace 扛得住 Windows 文件占用
|
|
1069
1263
|
else rmSync(tmp, { force: true });
|
|
1070
1264
|
} catch { /* 缓存目录写失败:下次再试 */ }
|
|
1071
1265
|
});
|
|
1072
|
-
child.on('error', () => { transcodeJobs.delete(key); });
|
|
1073
|
-
|
|
1266
|
+
child.on('error', () => { transcodeJobs.delete(key); transcodeChildren.delete(child); });
|
|
1267
|
+
// 看门狗直接 SIGKILL(与 jobRun 一致):ffmpeg 不退则 exit 不触发、转码名额泄漏
|
|
1268
|
+
const killTimer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* 已退出 */ } }, 30 * 60 * 1000);
|
|
1074
1269
|
child.on('exit', () => clearTimeout(killTimer));
|
|
1075
1270
|
}
|
|
1076
1271
|
json(res, 200, { ok: true, key, ready: false });
|
|
@@ -1106,9 +1301,14 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1106
1301
|
return;
|
|
1107
1302
|
}
|
|
1108
1303
|
if (req.method === 'GET' && url.pathname === '/bg/folder/list') {
|
|
1109
|
-
// dir
|
|
1304
|
+
// dir 查询参数:分区背景列自己目录时传入;缺省列全局设置的目录。
|
|
1305
|
+
// dir 只认用户配置过的目录(与取文件路由同一判定),不合法与文件路由同款报错
|
|
1110
1306
|
const qDir = url.searchParams.get('dir');
|
|
1111
|
-
|
|
1307
|
+
if (qDir && !bgFolderDirAllowed(loadConfig(configFile).theme.bg, qDir)) {
|
|
1308
|
+
json(res, 400, { ok: false, error: 'dir 参数无效或未配置' });
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
const dir = qDir || loadConfig(configFile).theme.bg.folder;
|
|
1112
1312
|
if (!dir || !existsSync(dir)) { json(res, 200, { ok: true, files: [], missing: true, dir: dir || '' }); return; }
|
|
1113
1313
|
try {
|
|
1114
1314
|
const r = listFolderBg(dir);
|
|
@@ -1180,6 +1380,45 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1180
1380
|
: { ok: true, available: false, statuses: {} });
|
|
1181
1381
|
return;
|
|
1182
1382
|
}
|
|
1383
|
+
if (req.method === 'GET' && url.pathname === '/sessions-activity') {
|
|
1384
|
+
// 子会话最近活动时间(毫秒):子代理 running 记录的新鲜度校验,
|
|
1385
|
+
// 长时间没动静的僵死记录不亮机器人(subagent-icon.js)
|
|
1386
|
+
const ids = (url.searchParams.get('ids') || '')
|
|
1387
|
+
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
|
|
1388
|
+
const activity = ids.length ? await listSessionsActivity(dataRoot, ids) : {};
|
|
1389
|
+
json(res, 200, { ok: true, activity });
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
if (req.method === 'GET' && url.pathname === '/workspace-sessions') {
|
|
1393
|
+
// 某工作区的任务会话 id(任务索引反查):折叠项目行扫子代理运行状态的候选清单
|
|
1394
|
+
const path = url.searchParams.get('path') || '';
|
|
1395
|
+
const ids = path ? await listWorkspaceTaskIds(dataRoot, path) : [];
|
|
1396
|
+
json(res, 200, { ok: true, ids });
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
if (req.method === 'GET' && url.pathname === '/subagent-children') {
|
|
1400
|
+
// 会话的子代理子会话及最近活动时间(含嵌套):子代理判活的主信号——
|
|
1401
|
+
// 应用的运行记录会把还在跑的长跑子代理误记为结束(subagent-icon.js)
|
|
1402
|
+
const ids = (url.searchParams.get('ids') || '')
|
|
1403
|
+
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 300);
|
|
1404
|
+
const children = ids.length ? await listSubagentChildrenActivity(dataRoot, ids) : [];
|
|
1405
|
+
json(res, 200, { ok: true, children });
|
|
1406
|
+
return;
|
|
1407
|
+
}
|
|
1408
|
+
if (req.method === 'GET' && url.pathname === '/background-bash') {
|
|
1409
|
+
// 后台 bash 任务在跑清单(进程握着的日志文件反查会话):终端图标的信号,
|
|
1410
|
+
// 纯文件系统扫描,不拉会话快照(快照会 resume 会话,见 scanBackgroundBash)
|
|
1411
|
+
json(res, 200, scanBackgroundBash());
|
|
1412
|
+
return;
|
|
1413
|
+
}
|
|
1414
|
+
if (req.method === 'GET' && url.pathname === '/project-unread') {
|
|
1415
|
+
// 项目"真未读"任务数(排除错误态):项目行蓝色未读徽标忽略红色错误行
|
|
1416
|
+
const ids = (url.searchParams.get('ids') || '')
|
|
1417
|
+
.split(',').map((s) => s.trim()).filter(Boolean).slice(0, 100);
|
|
1418
|
+
const unread = ids.length ? await listProjectsUnread(dataRoot, ids) : {};
|
|
1419
|
+
json(res, 200, unread === null ? { ok: false } : { ok: true, unread });
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1183
1422
|
if (req.method === 'GET' && url.pathname === '/projects') {
|
|
1184
1423
|
const settings = readSettings(settingsFile);
|
|
1185
1424
|
const projects = (settings.recentProjects || []).map((p) => {
|
|
@@ -1192,7 +1431,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1192
1431
|
}
|
|
1193
1432
|
if (req.method === 'POST' && url.pathname === '/project/alias') {
|
|
1194
1433
|
const body = await readBody(req);
|
|
1195
|
-
json(res, ...setAlias(body, configFile));
|
|
1434
|
+
json(res, ...(await setAlias(body, configFile)));
|
|
1196
1435
|
return;
|
|
1197
1436
|
}
|
|
1198
1437
|
if (req.method === 'POST' && url.pathname === '/project/relocate') {
|
|
@@ -1207,8 +1446,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1207
1446
|
json(res, 200, { ok: true, ...(await pickFolderSystem(start, title)) });
|
|
1208
1447
|
return;
|
|
1209
1448
|
}
|
|
1210
|
-
// 会话拖动排序持久化:
|
|
1211
|
-
//
|
|
1449
|
+
// 会话拖动排序持久化:hint = 拖动落点所在的列表(project/pinned/section,
|
|
1450
|
+
// 缺省按数据判定),旧注入包的 scope(workspace/group-members)回退认作 hint;
|
|
1451
|
+
// 工作区列表重盖 updated_at,分组会话重写 members.sort_order
|
|
1212
1452
|
if (req.method === 'POST' && url.pathname === '/task-order') {
|
|
1213
1453
|
const body = await readBody(req);
|
|
1214
1454
|
const ordered = Array.isArray(body?.ordered) ? body.ordered.filter((k) => typeof k === 'string') : [];
|
|
@@ -1216,13 +1456,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1216
1456
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'ordered 不能为空' });
|
|
1217
1457
|
return;
|
|
1218
1458
|
}
|
|
1219
|
-
|
|
1220
|
-
if (body.scope === 'workspace') result = await reorderWorkspaceTasks(dataRoot, ordered);
|
|
1221
|
-
else if (body.scope === 'group-members') result = await reorderGroupMembers(dataRoot, ordered);
|
|
1222
|
-
else {
|
|
1223
|
-
json(res, 400, { ok: false, code: 'invalid-request', error: '无效的 scope' });
|
|
1224
|
-
return;
|
|
1225
|
-
}
|
|
1459
|
+
const result = await reorderTasks(dataRoot, ordered, body.hint ?? body.scope);
|
|
1226
1460
|
if (result.error) {
|
|
1227
1461
|
json(res, 400, { ok: false, code: result.code, error: result.error });
|
|
1228
1462
|
return;
|
|
@@ -1258,29 +1492,36 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1258
1492
|
if (req.method === 'POST' && url.pathname === '/title-gen') {
|
|
1259
1493
|
const body = await readBody(req);
|
|
1260
1494
|
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
const found = listTitleGenProviders().find((p) => p.id === providerId);
|
|
1269
|
-
if (found) {
|
|
1270
|
-
next.baseUrl = found.baseUrl;
|
|
1271
|
-
next.apiKey = found.apiKey;
|
|
1272
|
-
next.format = found.format;
|
|
1273
|
-
}
|
|
1274
|
-
// 找不到(手输 id 或已删):保留原有副本字段不动
|
|
1275
|
-
} else if (providerId === 'session') {
|
|
1495
|
+
// 读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
1496
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
1497
|
+
await withConfigLock(configFile, () => {
|
|
1498
|
+
const current = loadConfig(configFile);
|
|
1499
|
+
const next = { ...current.titleGen, ...body.titleGen };
|
|
1500
|
+
// 选了列表内供应商:同步解析并保存其地址/密钥/协议副本——供应商日后
|
|
1501
|
+
// 被删,这份副本仍可直连(界面标注“已删除”并展开字段);
|
|
1276
1502
|
// 跟随会话不存副本(每次调用时按该会话实时解析)
|
|
1277
|
-
next.
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1503
|
+
const providerId = (next.provider || '').trim();
|
|
1504
|
+
if (providerId && providerId !== 'session') {
|
|
1505
|
+
const found = listTitleGenProviders().find((p) => p.id === providerId);
|
|
1506
|
+
if (found) {
|
|
1507
|
+
next.baseUrl = found.baseUrl;
|
|
1508
|
+
next.apiKey = found.apiKey;
|
|
1509
|
+
next.format = found.format;
|
|
1510
|
+
}
|
|
1511
|
+
// 找不到(手输 id 或已删):保留原有副本字段不动
|
|
1512
|
+
} else if (providerId === 'session') {
|
|
1513
|
+
// 跟随会话不存副本(每次调用时按该会话实时解析)
|
|
1514
|
+
next.baseUrl = '';
|
|
1515
|
+
next.apiKey = '';
|
|
1516
|
+
next.format = '';
|
|
1517
|
+
}
|
|
1518
|
+
current.titleGen = mergeTitleGenConfig(next);
|
|
1519
|
+
if (!saveConfig(configFile, current)) {
|
|
1520
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
json(res, 200, { ok: true, titleGen: current.titleGen });
|
|
1524
|
+
});
|
|
1284
1525
|
return;
|
|
1285
1526
|
}
|
|
1286
1527
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'body 需包含 titleGen 对象' });
|
|
@@ -1329,66 +1570,74 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1329
1570
|
json(res, 200, { ok: true, title, written: false, store: 'skipped: overridden' });
|
|
1330
1571
|
return;
|
|
1331
1572
|
}
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
// CLI 库不可写(旧版无 title_source 列 / 无该会话行)不阻断:退回
|
|
1337
|
-
// 单写任务索引的旧行为;任务索引随后失败也不回滚 CLI——同步器会补
|
|
1338
|
-
for (let attempt = 0; ; attempt++) {
|
|
1339
|
-
try {
|
|
1340
|
-
const r = await setCustomSessionTitle(dataRoot, sessId, title);
|
|
1341
|
-
store = r.written ? '' : (r.skipped || 'skipped');
|
|
1342
|
-
break;
|
|
1343
|
-
} catch (err) {
|
|
1344
|
-
if (err.code === 'index-busy' && attempt < 2) {
|
|
1345
|
-
await new Promise((r) => setTimeout(r, 1200));
|
|
1346
|
-
continue;
|
|
1347
|
-
}
|
|
1348
|
-
store = 'error: ' + (err?.message || err);
|
|
1349
|
-
titleGenLog(dataRoot, `cli-store-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1350
|
-
break;
|
|
1351
|
-
}
|
|
1352
|
-
}
|
|
1353
|
-
// 写库撞上宿主写入时稍候重试(起名不急这几秒)
|
|
1354
|
-
for (let attempt = 0; ; attempt++) {
|
|
1355
|
-
try {
|
|
1356
|
-
const r = await setTaskTitleIfNotOverridden(dataRoot, sessId, title);
|
|
1357
|
-
written = r.written;
|
|
1358
|
-
break;
|
|
1359
|
-
} catch (err) {
|
|
1360
|
-
if (err.code === 'index-busy' && attempt < 2) {
|
|
1361
|
-
await new Promise((r) => setTimeout(r, 1200));
|
|
1362
|
-
continue;
|
|
1363
|
-
}
|
|
1364
|
-
titleGenLog(dataRoot, `index-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1365
|
-
json(res, 500, { ok: false, code: err.code || 'index-error', error: err.message });
|
|
1366
|
-
return;
|
|
1367
|
-
}
|
|
1573
|
+
const r = await writeGeneratedTitle(dataRoot, configFile, sessId, title);
|
|
1574
|
+
if (r.error) {
|
|
1575
|
+
json(res, 500, { ok: false, code: r.error.code || 'index-error', error: r.error.message });
|
|
1576
|
+
return;
|
|
1368
1577
|
}
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
if (sessId && store === '') {
|
|
1372
|
-
const c = loadConfig(configFile);
|
|
1373
|
-
c.titleGen.customWritten = { ...(c.titleGen.customWritten || {}), [sessId]: { title, at: Date.now() } };
|
|
1374
|
-
saveConfig(configFile, c);
|
|
1578
|
+
written = r.written;
|
|
1579
|
+
store = r.store;
|
|
1375
1580
|
}
|
|
1376
1581
|
json(res, 200, { ok: true, title, written, store });
|
|
1377
1582
|
return;
|
|
1378
1583
|
}
|
|
1584
|
+
// 手动自动重命名(任务行悬浮按钮 / 右键菜单入口):取会话最近 N 轮问答按
|
|
1585
|
+
// 提示词生成标题并按“手动重命名”写库。用户显式动作:已重命名过也照写
|
|
1586
|
+
//(force),不受启用开关限制(入口各有开关);生成失败交外层统一 500
|
|
1587
|
+
if (req.method === 'POST' && url.pathname === '/title-gen/rename') {
|
|
1588
|
+
const body = await readBody(req);
|
|
1589
|
+
const sessId = typeof body?.sessId === 'string' && /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(body.sessId) ? body.sessId : '';
|
|
1590
|
+
if (!sessId) {
|
|
1591
|
+
json(res, 400, { ok: false, code: 'invalid-request', error: 'sessId 不能为空' });
|
|
1592
|
+
return;
|
|
1593
|
+
}
|
|
1594
|
+
const cfg = loadConfig(configFile).titleGen;
|
|
1595
|
+
let material;
|
|
1596
|
+
try {
|
|
1597
|
+
material = await readRecentQa(dataRoot, sessId, cfg.recentQa);
|
|
1598
|
+
} catch (err) {
|
|
1599
|
+
titleGenLog(dataRoot, `rename-read-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1600
|
+
json(res, 500, { ok: false, code: 'read-error', error: err?.message || '读取会话内容失败' });
|
|
1601
|
+
return;
|
|
1602
|
+
}
|
|
1603
|
+
if (!material) {
|
|
1604
|
+
json(res, 200, { ok: false, code: 'no-content', error: '会话还没有问答内容' });
|
|
1605
|
+
return;
|
|
1606
|
+
}
|
|
1607
|
+
let title;
|
|
1608
|
+
try {
|
|
1609
|
+
title = await generateTitleWith(cfg, material, dataRoot, sessId);
|
|
1610
|
+
} catch (err) {
|
|
1611
|
+
titleGenLog(dataRoot, `rename-generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1612
|
+
throw err; // 交给外层统一 500
|
|
1613
|
+
}
|
|
1614
|
+
const r = await writeGeneratedTitle(dataRoot, configFile, sessId, title, { force: true });
|
|
1615
|
+
if (r.error) {
|
|
1616
|
+
json(res, 500, { ok: false, code: r.error.code || 'index-error', error: r.error.message });
|
|
1617
|
+
return;
|
|
1618
|
+
}
|
|
1619
|
+
json(res, 200, { ok: true, title, written: r.written, store: r.store });
|
|
1620
|
+
return;
|
|
1621
|
+
}
|
|
1379
1622
|
// —— zcode-vision 插件(图片视觉代理):设置弹窗“视觉代理”标签页读写 ————
|
|
1380
1623
|
if (req.method === 'GET' && url.pathname === '/vision') {
|
|
1381
|
-
const file =
|
|
1624
|
+
const file = visionFile;
|
|
1382
1625
|
let parsed = readJsonFile(file);
|
|
1383
1626
|
// 装了 zcode-pro 默认启用识图卡片(插件纯安装默认关,纯文本展示):
|
|
1384
1627
|
// 只补从未写过的配置,用户显式设过 cardUi(含 false)不覆盖
|
|
1385
1628
|
if (parsed && typeof parsed === 'object' && !('cardUi' in parsed)) {
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1629
|
+
// 写前重读一次拿最新值合并:与插件侧的模板升级等写方并发时,
|
|
1630
|
+
// 拿读取时的旧快照整份写回会把对方刚写的键盖掉
|
|
1631
|
+
const fresh = readJsonFile(file);
|
|
1632
|
+
const base = (fresh && typeof fresh === 'object') ? fresh : parsed;
|
|
1633
|
+
if (!('cardUi' in base)) {
|
|
1634
|
+
const merged = { ...base, cardUi: true };
|
|
1635
|
+
try {
|
|
1636
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者撕裂
|
|
1637
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
1638
|
+
renameSync(tmp, file);
|
|
1639
|
+
} catch { /* 补写失败下次再试,不阻塞读取 */ }
|
|
1640
|
+
}
|
|
1392
1641
|
}
|
|
1393
1642
|
if (parsed === null && existsSync(file)) {
|
|
1394
1643
|
json(res, 500, { ok: false, code: 'vision-read', error: 'zcode-vision.json 不是合法 JSON' });
|
|
@@ -1405,15 +1654,15 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1405
1654
|
return;
|
|
1406
1655
|
}
|
|
1407
1656
|
try {
|
|
1408
|
-
const file =
|
|
1657
|
+
const file = visionFile;
|
|
1409
1658
|
// 与磁盘旧配置合并(本块曾两次被并发改动覆盖回全量覆盖):前端按自己
|
|
1410
1659
|
// 的字段重建整份配置,直接覆盖会丢插件新增、面板还不认识的键
|
|
1411
1660
|
//(cardSandboxBudget/cardUi/interceptMode 等)
|
|
1412
1661
|
const merged = { ...(readJsonFile(file) || {}), ...cfg };
|
|
1413
1662
|
// forceIntercept 为 null = 面板选了「自动」:从磁盘配置删掉该键,恢复插件缺省联动
|
|
1414
1663
|
if (cfg.forceIntercept === null) delete merged.forceIntercept;
|
|
1415
|
-
const tmp = file
|
|
1416
|
-
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
|
|
1664
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者撕裂
|
|
1665
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
1417
1666
|
renameSync(tmp, file);
|
|
1418
1667
|
} catch (err2) {
|
|
1419
1668
|
json(res, 500, { ok: false, code: 'vision-write', error: '写入 zcode-vision.json 失败: ' + (err2?.message || err2) });
|
|
@@ -1538,6 +1787,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1538
1787
|
ok: true, config, file, hook,
|
|
1539
1788
|
pluginVersion: vm ? vm[1] : null,
|
|
1540
1789
|
usage: headroomUsageScan(dataRoot),
|
|
1790
|
+
serena: serenaScan(),
|
|
1541
1791
|
...(await headroomBinaryInfo()),
|
|
1542
1792
|
});
|
|
1543
1793
|
return;
|
|
@@ -1606,6 +1856,16 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1606
1856
|
}
|
|
1607
1857
|
json(res, 200, { ok: true, usage: headroomUsageScan(dataRoot), changed: r.changed });
|
|
1608
1858
|
return;
|
|
1859
|
+
} else if (body && typeof body.serena === 'boolean') {
|
|
1860
|
+
// Serena 开关:写/删 ~/.zcode/cli/config.json 的 mcp.servers.serena,
|
|
1861
|
+
// ZCode 新会话启动时加载该 MCP 服务器(当前会话不重连,重启会话后生效)
|
|
1862
|
+
const r = setSerenaEnabled(body.serena);
|
|
1863
|
+
if (!r.ok) {
|
|
1864
|
+
json(res, 500, { ok: false, code: r.code, error: r.error });
|
|
1865
|
+
return;
|
|
1866
|
+
}
|
|
1867
|
+
json(res, 200, { ok: true, serena: r.serena });
|
|
1868
|
+
return;
|
|
1609
1869
|
} else if (body && body.cancelUpgrade === true) {
|
|
1610
1870
|
json(res, 200, { ok: true, upgrade: cancelHeadroomUpgrade() });
|
|
1611
1871
|
return;
|
|
@@ -1633,15 +1893,21 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1633
1893
|
return;
|
|
1634
1894
|
} else if (body && 'interval' in body) {
|
|
1635
1895
|
try {
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1896
|
+
// 只改 powerWatchInterval 一个键:readHeadroomConfig 会把非规范值归一
|
|
1897
|
+
// 成默认值(插件侧是宽松读法),整份写回会把 backend 之类的本机值打回默认。
|
|
1898
|
+
// 套配置锁:与同步导入、setHeadroomUsage 等自家写方互斥(插件侧写方走
|
|
1899
|
+
// 它自己的生命周期锁,两边共存仍留极小窗口,写回本身是原子改名兜底)
|
|
1900
|
+
await withConfigLock(file, () => {
|
|
1901
|
+
const cfg = readJsonFile(file) || {};
|
|
1902
|
+
cfg.powerWatchInterval = clampInt(body.interval, 10, 3600, Number(cfg.powerWatchInterval) || 60);
|
|
1903
|
+
writeHeadroomConfig(file, cfg);
|
|
1904
|
+
});
|
|
1639
1905
|
} catch (err) {
|
|
1640
1906
|
json(res, 500, { ok: false, code: 'headroom-write', error: '写入 headroom.json 失败: ' + (err?.message || err) });
|
|
1641
1907
|
return;
|
|
1642
1908
|
}
|
|
1643
1909
|
} else {
|
|
1644
|
-
json(res, 400, { ok: false, code: 'invalid-request', error: 'body 需包含 action/backend/power/usage/interval 之一' });
|
|
1910
|
+
json(res, 400, { ok: false, code: 'invalid-request', error: 'body 需包含 action/backend/power/usage/serena/interval 之一' });
|
|
1645
1911
|
return;
|
|
1646
1912
|
}
|
|
1647
1913
|
let config = null;
|
|
@@ -1658,8 +1924,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1658
1924
|
// 源码目录(有 package.json 与 esbuild)先构建,安装副本没有构建环境则跳过
|
|
1659
1925
|
let built = false;
|
|
1660
1926
|
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
1661
|
-
|
|
1662
|
-
|
|
1927
|
+
// Windows 上优先 esbuild.exe:无扩展名的 bin/esbuild 是 JS 垫片,spawnSync 跑不起来
|
|
1928
|
+
const esbuildNames = process.platform === 'win32' ? ['esbuild.exe', 'esbuild'] : ['esbuild', 'esbuild.exe'];
|
|
1929
|
+
const esbuildBin = esbuildNames
|
|
1930
|
+
.map((n) => join(repoRoot, 'node_modules', 'esbuild', 'bin', n))
|
|
1663
1931
|
.find((p) => existsSync(p)) || '';
|
|
1664
1932
|
if (esbuildBin) {
|
|
1665
1933
|
try {
|
|
@@ -1680,14 +1948,17 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1680
1948
|
});
|
|
1681
1949
|
child.unref();
|
|
1682
1950
|
} catch { /* 拉不起来就只能等下次手动重启 */ }
|
|
1683
|
-
setTimeout(() =>
|
|
1951
|
+
setTimeout(() => {
|
|
1952
|
+
try { dispose(); } catch { /* ignore */ } // 收掉残留 ffmpeg 子进程,防孤儿与新实例抢写缓存
|
|
1953
|
+
process.exit(0);
|
|
1954
|
+
}, 250);
|
|
1684
1955
|
}, 150);
|
|
1685
1956
|
return;
|
|
1686
1957
|
}
|
|
1687
1958
|
// —— 软件代理连通性检测:经 curl -x 走代理访问插件市场/本体升级实际要用的站点 ——
|
|
1688
1959
|
if (req.method === 'POST' && url.pathname === '/proxy/test') {
|
|
1689
1960
|
const body = await readBody(req);
|
|
1690
|
-
const proxy = typeof body?.proxy === 'string' && body.proxy.trim() ? body.proxy.trim() :
|
|
1961
|
+
const proxy = typeof body?.proxy === 'string' && body.proxy.trim() ? body.proxy.trim() : effectiveProxyUrl();
|
|
1691
1962
|
if (!proxy) {
|
|
1692
1963
|
json(res, 400, { ok: false, code: 'proxy-not-set', error: '请先填写代理地址' });
|
|
1693
1964
|
return;
|
|
@@ -1761,22 +2032,29 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1761
2032
|
}
|
|
1762
2033
|
if (req.method === 'POST' && url.pathname === '/sync') {
|
|
1763
2034
|
const body = await readBody(req);
|
|
1764
|
-
|
|
1765
|
-
//
|
|
1766
|
-
|
|
1767
|
-
const
|
|
1768
|
-
|
|
1769
|
-
|
|
2035
|
+
// 读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
2036
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
2037
|
+
await withConfigLock(configFile, () => {
|
|
2038
|
+
const current = loadConfig(configFile);
|
|
2039
|
+
// 表单(类型/URL/登录/密码)与同步内容开关分开提交:表单全量替换,开关只改单项
|
|
2040
|
+
if (body && typeof body === 'object' && body.sync && typeof body.sync === 'object') {
|
|
2041
|
+
const v = validateSyncForm(body.sync);
|
|
2042
|
+
if (v.error) {
|
|
2043
|
+
json(res, 400, { ok: false, code: 'sync-invalid', error: v.error });
|
|
2044
|
+
return;
|
|
2045
|
+
}
|
|
2046
|
+
Object.assign(current.sync, v.sync);
|
|
2047
|
+
}
|
|
2048
|
+
if (body && typeof body === 'object' && body.include && typeof body.include === 'object') {
|
|
2049
|
+
if (typeof body.include.zcodepro === 'boolean') current.sync.include.zcodepro = body.include.zcodepro;
|
|
2050
|
+
if (typeof body.include.model === 'boolean') current.sync.include.model = body.include.model;
|
|
2051
|
+
}
|
|
2052
|
+
if (!saveConfig(configFile, current)) {
|
|
2053
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1770
2054
|
return;
|
|
1771
2055
|
}
|
|
1772
|
-
|
|
1773
|
-
}
|
|
1774
|
-
if (body && typeof body === 'object' && body.include && typeof body.include === 'object') {
|
|
1775
|
-
if (typeof body.include.zcodepro === 'boolean') current.sync.include.zcodepro = body.include.zcodepro;
|
|
1776
|
-
if (typeof body.include.model === 'boolean') current.sync.include.model = body.include.model;
|
|
1777
|
-
}
|
|
1778
|
-
saveConfig(configFile, current);
|
|
1779
|
-
json(res, 200, { ok: true, sync: current.sync });
|
|
2056
|
+
json(res, 200, { ok: true, sync: current.sync });
|
|
2057
|
+
});
|
|
1780
2058
|
return;
|
|
1781
2059
|
}
|
|
1782
2060
|
if (req.method === 'POST' && url.pathname === '/sync/run') {
|
|
@@ -1786,8 +2064,12 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1786
2064
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'direction 只能是 push 或 pull' });
|
|
1787
2065
|
return;
|
|
1788
2066
|
}
|
|
1789
|
-
|
|
1790
|
-
|
|
2067
|
+
// 同 direction 的并发触发共用同一次执行结果(见 enqueueSyncRun),
|
|
2068
|
+
// 不同 direction 串行排队
|
|
2069
|
+
const r = await enqueueSyncRun(direction, async () => {
|
|
2070
|
+
const cfg = loadConfig(configFile);
|
|
2071
|
+
return runSettingsSync({ direction, dataRoot, configFile, config: cfg, proxyUrl: proxyUrlFor('sync') });
|
|
2072
|
+
});
|
|
1791
2073
|
if (r.error) {
|
|
1792
2074
|
json(res, r.status || 500, { ok: false, code: r.code || 'sync-run', error: r.error });
|
|
1793
2075
|
return;
|
|
@@ -1821,6 +2103,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1821
2103
|
json(res, 400, { ok: false, code: 'sync-not-configured', error: '请先填写 WebDAV URL 并保存' });
|
|
1822
2104
|
return;
|
|
1823
2105
|
}
|
|
2106
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2107
|
+
json(res, 400, { ok: false, code: 'sync-not-configured', error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' });
|
|
2108
|
+
return;
|
|
2109
|
+
}
|
|
1824
2110
|
const r = await listSyncVersions(sync, proxyUrlFor('sync'));
|
|
1825
2111
|
if (r.error) {
|
|
1826
2112
|
json(res, r.status || 500, { ok: false, code: r.code || 'sync-request', error: r.error });
|
|
@@ -1848,6 +2134,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1848
2134
|
json(res, 400, { ok: false, code: 'sync-not-configured', error: '请先填写 WebDAV URL 并保存' });
|
|
1849
2135
|
return;
|
|
1850
2136
|
}
|
|
2137
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2138
|
+
json(res, 400, { ok: false, code: 'sync-not-configured', error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' });
|
|
2139
|
+
return;
|
|
2140
|
+
}
|
|
1851
2141
|
const remoteMissing = () => json(res, 404, { ok: false, code: 'sync-remote-missing', error: `云端文件 ${file} 不存在(可能已被删除)` });
|
|
1852
2142
|
if (action === 'apply') {
|
|
1853
2143
|
const remote = await fetchSyncNamedDoc(sync, proxyUrlFor('sync'), file);
|
|
@@ -1862,6 +2152,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1862
2152
|
const kind = file.startsWith('model') ? 'model' : 'zcodepro';
|
|
1863
2153
|
sync.lastPullAt = Date.now();
|
|
1864
2154
|
const r = applySyncDocs({ docs: { [kind]: remote.doc.data }, dataRoot, configFile, config, sync });
|
|
2155
|
+
if (r && r.error) {
|
|
2156
|
+
json(res, r.status || 500, { ok: false, code: r.code, error: r.error });
|
|
2157
|
+
return;
|
|
2158
|
+
}
|
|
1865
2159
|
json(res, 200, { ok: true, applied: r.applied, sync: loadConfig(configFile).sync });
|
|
1866
2160
|
return;
|
|
1867
2161
|
}
|
|
@@ -1910,7 +2204,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1910
2204
|
return;
|
|
1911
2205
|
}
|
|
1912
2206
|
try {
|
|
1913
|
-
writeFileSync(target, r.body, 'utf8');
|
|
2207
|
+
writeFileSync(target, r.body, { encoding: 'utf8', mode: 0o600 }); // 导出内容含明文 apiKey,限制本人读写
|
|
2208
|
+
try { chmodSync(target, 0o600); } catch { /* 覆盖同名旧文件时 mode 不生效,补一次 */ }
|
|
1914
2209
|
} catch (err) {
|
|
1915
2210
|
json(res, 500, { ok: false, code: 'sync-export', error: `写入 ${target} 失败: ${err?.message || err}` });
|
|
1916
2211
|
return;
|
|
@@ -1923,29 +2218,60 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1923
2218
|
// model-io-*.jsonl 每行一次模型调用,response.usage 有分项 token;成本字段
|
|
1924
2219
|
// 官方未落本地,成本类统计项由注入侧按“无数据自动隐藏”处理
|
|
1925
2220
|
if (req.method === 'GET' && url.pathname === '/stats/usage') {
|
|
1926
|
-
|
|
1927
|
-
|
|
2221
|
+
// 会话 id 校验同 sessId 白名单:不像会话 id 的一律按全局口径处理
|
|
2222
|
+
//(降级后注入侧仍按“本会话”展示全局速率,官方改 key 格式时才会踩到)
|
|
2223
|
+
const rawSid = url.searchParams.get('session') || '';
|
|
2224
|
+
const sessionId = /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(rawSid) ? rawSid : '';
|
|
2225
|
+
// turns=0 跳过分钟桶聚合(状态栏只读 global,不白建每轮桶)
|
|
2226
|
+
const wantTurns = url.searchParams.get('turns') !== '0';
|
|
2227
|
+
// 会话树 trace:速率把同树子代理的调用算进来
|
|
2228
|
+
const treeTrace = sessionId ? await sessionTrace(dataRoot, sessionId) : '';
|
|
2229
|
+
const { global, recentTurns } = collectUsageStats(sessionId, wantTurns, treeTrace);
|
|
2230
|
+
// 官方口径的会话汇总(主轮请求/累计输入输出/平均命中/树口径净生成速率):状态栏会话组用
|
|
2231
|
+
const mu = sessionId ? await listSessionModelUsage(dataRoot, sessionId, treeTrace) : null;
|
|
1928
2232
|
// 任务总数 60 秒缓存:状态栏每 2 秒请求一次,不必每次开关 SQLite
|
|
1929
2233
|
if (Date.now() - tasksCountAt > 60_000) {
|
|
1930
2234
|
tasksCountAt = Date.now();
|
|
1931
2235
|
tasksCountCache = await countTasks(dataRoot);
|
|
1932
2236
|
}
|
|
1933
2237
|
global.tasks = tasksCountCache;
|
|
1934
|
-
json(res, 200, { ok: true, global, recentTurns });
|
|
2238
|
+
json(res, 200, { ok: true, global, recentTurns, ...(mu ? { sessionSummary: mu.summary } : {}) });
|
|
2239
|
+
return;
|
|
2240
|
+
}
|
|
2241
|
+
// —— 每轮用量(turn-usage.js):官方 model_usage 同源的主轮请求明细 ——
|
|
2242
|
+
if (req.method === 'GET' && url.pathname === '/stats/turns') {
|
|
2243
|
+
const rawSid = url.searchParams.get('session') || '';
|
|
2244
|
+
const sessionId = /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(rawSid) ? rawSid : '';
|
|
2245
|
+
const mu = await listSessionModelUsage(dataRoot, sessionId);
|
|
2246
|
+
json(res, 200, { ok: true, rounds: mu.rounds, summary: mu.summary });
|
|
1935
2247
|
return;
|
|
1936
2248
|
}
|
|
1937
2249
|
if (req.method === 'GET' && url.pathname === '/plugins/status') {
|
|
1938
|
-
|
|
1939
|
-
//
|
|
1940
|
-
//
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
2250
|
+
// 市场同步与更新任务共用同一条串行队列,不能绕过它:两处同时 clone/pull
|
|
2251
|
+
// 同一个市场目录会互相删对方的中间目录(ENOENT/坏目录)。
|
|
2252
|
+
// 有更新任务在跑/排队时整个跳过(任务自身会做市场同步并刷新时间戳),
|
|
2253
|
+
// 状态页轮询不排队等待、不能被长任务挂住;检查与入队在同一同步段内完成
|
|
2254
|
+
let marketAdd = null;
|
|
2255
|
+
if (!pluginsUpdateJobs.size) {
|
|
2256
|
+
await runPluginsQueued(async () => {
|
|
2257
|
+
marketAdd = await ensureZcodePluginsMarketplace();
|
|
2258
|
+
if (Date.now() - lastMarketplaceSync > 30 * 60 * 1000) {
|
|
2259
|
+
await ensureZcodePluginsCloneFresh();
|
|
2260
|
+
await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
|
|
2261
|
+
lastMarketplaceSync = Date.now();
|
|
2262
|
+
}
|
|
2263
|
+
});
|
|
1945
2264
|
}
|
|
1946
2265
|
const status = pluginUpdateStatus();
|
|
1947
2266
|
if (!status) {
|
|
1948
|
-
|
|
2267
|
+
// 带上市场添加失败的真实原因:新机器最常见的是连不上 GitHub / 没装 Git,
|
|
2268
|
+
// 设置面板和启动检查都靠这条信息提示用户,别再只给一句“读取失败”
|
|
2269
|
+
const failed = marketAdd && !marketAdd.ok ? marketAdd : null;
|
|
2270
|
+
json(res, 500, {
|
|
2271
|
+
ok: false,
|
|
2272
|
+
code: failed?.code || 'plugins-status',
|
|
2273
|
+
error: failed?.error || '读取插件清单失败(未安装过 zcode-plugins 市场?)',
|
|
2274
|
+
});
|
|
1949
2275
|
return;
|
|
1950
2276
|
}
|
|
1951
2277
|
json(res, 200, { ok: true, ...status });
|
|
@@ -1959,19 +2285,22 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1959
2285
|
}
|
|
1960
2286
|
json(res, 404, { ok: false, error: 'not found' });
|
|
1961
2287
|
} catch (err) {
|
|
1962
|
-
|
|
2288
|
+
// 完整错误只进日志;响应里的消息抹掉主目录前缀,别把本机路径结构带出去
|
|
2289
|
+
console.error('[zcodepro] 路由处理出错:', err);
|
|
2290
|
+
json(res, 500, { ok: false, error: String(err?.message || err).split(homedir()).join('~') });
|
|
1963
2291
|
}
|
|
1964
2292
|
});
|
|
1965
2293
|
|
|
1966
2294
|
// 端口被占时重试:开发重载的交接窗口内,旧进程退出略晚于新进程启动,
|
|
1967
|
-
//
|
|
2295
|
+
// 新进程在这里等它让出端口(默认最多 20 秒),而不是启动失败;
|
|
2296
|
+
// 热替换路径传小的 listenTries,别把启动器主循环卡在这里
|
|
1968
2297
|
return new Promise((resolveStarted, rejectStarted) => {
|
|
1969
2298
|
let attempts = 0;
|
|
1970
2299
|
const tryListen = () => {
|
|
1971
2300
|
attempts += 1;
|
|
1972
2301
|
server.removeAllListeners('error');
|
|
1973
2302
|
server.once('error', (err) => {
|
|
1974
|
-
if (err && err.code === 'EADDRINUSE' && attempts <
|
|
2303
|
+
if (err && err.code === 'EADDRINUSE' && attempts < listenTries) {
|
|
1975
2304
|
try { server.close(); } catch { /* ignore */ }
|
|
1976
2305
|
setTimeout(tryListen, 500);
|
|
1977
2306
|
return;
|
|
@@ -1981,17 +2310,17 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1981
2310
|
// 启动即补视觉配置缺省键:装了 zcode-pro ⇒ cardUi=true(识图卡片开,缺省
|
|
1982
2311
|
// 才补、显式设过不动,规则同 GET /vision),不必等用户打开视觉设置页
|
|
1983
2312
|
try {
|
|
1984
|
-
const vFile =
|
|
2313
|
+
const vFile = visionFile;
|
|
1985
2314
|
const vParsed = readJsonFile(vFile);
|
|
1986
2315
|
if (vParsed && typeof vParsed === 'object' && !('cardUi' in vParsed)) {
|
|
1987
2316
|
vParsed.cardUi = true;
|
|
1988
|
-
const vTmp = vFile
|
|
1989
|
-
writeFileSync(vTmp, JSON.stringify(vParsed, null, 2) + '\n', 'utf-8');
|
|
2317
|
+
const vTmp = `${vFile}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
2318
|
+
writeFileSync(vTmp, JSON.stringify(vParsed, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 }); // 文件里有明文 apiKey,限制本人读写
|
|
1990
2319
|
renameSync(vTmp, vFile);
|
|
1991
2320
|
}
|
|
1992
2321
|
} catch { /* 无配置或不可写不影响启动 */ }
|
|
1993
2322
|
// 服务就绪即安排 headroom 代理兜底(内部延迟 5 秒执行,避开启动高峰)
|
|
1994
|
-
server.listen(port, '127.0.0.1', () => { ensureHeadroomAtStartup(); resolveStarted(server); });
|
|
2323
|
+
server.listen(port, '127.0.0.1', () => { ensureHeadroomAtStartup(state); resolveStarted(server); });
|
|
1995
2324
|
};
|
|
1996
2325
|
tryListen();
|
|
1997
2326
|
});
|
|
@@ -2006,7 +2335,38 @@ let tasksCountCache = 0; // 任务总数缓存(/stats/usage 高频轮询,60
|
|
|
2006
2335
|
// ~/.zcode/cli/rollout/model-io-*.jsonl 每行一次模型调用;usage 字段有两种键风格
|
|
2007
2336
|
// (协议 camelCase 与原始 snake_case),两种都解析。文件小(个位数、每会话一个),
|
|
2008
2337
|
// 按 mtime+size 缓存只重读变过的文件;聚合结果含按日分桶(本地时区)供“今日”用
|
|
2009
|
-
const usageFileCache = new Map(); // 文件名 → { mtime, size, recs: [{at, in, out, session,
|
|
2338
|
+
const usageFileCache = new Map(); // 文件名 → { mtime, size, ino, goneAt, recs: [{at, ts, ms, in, out, cacheRead, session, trace}] }
|
|
2339
|
+
// 测试缝:覆盖 rollout 记录目录(scripts/test-usage-stats.mjs 用假数据跑真实聚合)
|
|
2340
|
+
let rolloutDirOverride = '';
|
|
2341
|
+
// 被滚动删除的会话文件,其解析记录在缓存里的保留时长
|
|
2342
|
+
const ROLLOUT_KEEP_MS = 2 * 3600_000;
|
|
2343
|
+
// 测试用:换目录即作废全部缓存,假数据与真实记录不混算
|
|
2344
|
+
export function setRolloutDirForTest(dir) {
|
|
2345
|
+
rolloutDirOverride = dir || '';
|
|
2346
|
+
usageFileCache.clear();
|
|
2347
|
+
rolloutRecsCache = null;
|
|
2348
|
+
rolloutSig = '';
|
|
2349
|
+
statsResultCache = { sig: '', key: '', result: null };
|
|
2350
|
+
}
|
|
2351
|
+
// 记录合并结果缓存:文件签名(名称+mtime+size)没变就直接复用上次合并好的记录
|
|
2352
|
+
let rolloutSig = '';
|
|
2353
|
+
let rolloutRecsCache = null;
|
|
2354
|
+
// 聚合结果缓存:同文件签名 + 同查询参数(含本地日期)直接复用,
|
|
2355
|
+
// /stats/usage 2 秒轮询不用每次全量重聚合十万级记录
|
|
2356
|
+
let statsResultCache = { sig: '', key: '', result: null };
|
|
2357
|
+
// 供启动器热替换前调用:旧模块实例被 ESM 模块表永久持有,清掉大块缓存省内存
|
|
2358
|
+
export function dispose() {
|
|
2359
|
+
usageFileCache.clear();
|
|
2360
|
+
rolloutRecsCache = null; // 合并后的全量记录数组(可达十万级),不留
|
|
2361
|
+
rolloutSig = '';
|
|
2362
|
+
statsResultCache = { sig: '', key: '', result: null };
|
|
2363
|
+
// 残留的 ffmpeg 转码子进程一并收掉(退出/交接时调用):孤儿进程会与新实例
|
|
2364
|
+
// 并发写同一个 .tmp.mp4 写坏缓存且不再重建;杀掉只会丢半截临时文件,重启后重建
|
|
2365
|
+
for (const child of transcodeChildren) {
|
|
2366
|
+
try { child.kill(); } catch { /* 已退出 */ }
|
|
2367
|
+
}
|
|
2368
|
+
transcodeChildren.clear();
|
|
2369
|
+
}
|
|
2010
2370
|
// 解析一段 rollout 文本为记录;completeBytes = 已完整解析的整行字节数
|
|
2011
2371
|
//(末行若是不完整 JSON(写入中途)不计入,调用方据此决定偏移推进量)
|
|
2012
2372
|
function parseRolloutLines(text) {
|
|
@@ -2050,11 +2410,15 @@ function parseRolloutLines(text) {
|
|
|
2050
2410
|
input = num(u.input_tokens) + cacheRead + cacheWrite;
|
|
2051
2411
|
}
|
|
2052
2412
|
const output = num(u.outputTokens ?? u.output_tokens);
|
|
2413
|
+
const at = d.completedAt || d.startedAt || '';
|
|
2053
2414
|
recs.push({
|
|
2054
|
-
at
|
|
2415
|
+
at,
|
|
2416
|
+
ts: Date.parse(at),
|
|
2417
|
+
ms: Number(d.durationMs) || 0,
|
|
2055
2418
|
in: input, out: output,
|
|
2056
2419
|
cacheRead,
|
|
2057
2420
|
session: String(d.sessionId || ''),
|
|
2421
|
+
trace: String(d.traceId || ''), // 会话树(父会话+子代理)共享同一 trace
|
|
2058
2422
|
});
|
|
2059
2423
|
}
|
|
2060
2424
|
consumed += isTail ? Buffer.byteLength(line, 'utf8') : lineBytes;
|
|
@@ -2064,27 +2428,49 @@ function parseRolloutLines(text) {
|
|
|
2064
2428
|
}
|
|
2065
2429
|
|
|
2066
2430
|
function rolloutRecords() {
|
|
2067
|
-
const dir = join(
|
|
2431
|
+
const dir = rolloutDirOverride || join(resolveDataRootDir(), 'cli', 'rollout'); // 官方 rollout 目录跟数据根迁移
|
|
2068
2432
|
let names = [];
|
|
2069
|
-
try { names = readdirSync(dir).filter((n) => n.startsWith('model-io-') && n.endsWith('.jsonl')); } catch {
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2433
|
+
try { names = readdirSync(dir).filter((n) => n.startsWith('model-io-') && n.endsWith('.jsonl')); } catch {
|
|
2434
|
+
// 读目录失败(杀软/权限抖动)时旧签名作废:否则空记录算出的 0 值结果会
|
|
2435
|
+
// 连着旧签名进缓存,目录恢复后文件没变就一直命中 0
|
|
2436
|
+
rolloutSig = '';
|
|
2437
|
+
rolloutRecsCache = null;
|
|
2438
|
+
return [];
|
|
2439
|
+
}
|
|
2440
|
+
// 官方会滚动删除会话文件(运行中的会话也会被删了重建,窗口期数据不断档),
|
|
2441
|
+
// 被删文件的解析记录在缓存里再留 ROLLOUT_KEEP_MS:速率停在最后的值而不是归零,
|
|
2442
|
+
// 累计数也不缩水;超时才淘汰,别让长跑进程无限积压(受控泄漏)
|
|
2443
|
+
const nameSet = new Set(names); // Set 判定:文件数上千时 names.includes 是 O(F²)
|
|
2444
|
+
for (const [k, v] of usageFileCache) {
|
|
2445
|
+
if (nameSet.has(k)) { v.goneAt = 0; continue; }
|
|
2446
|
+
if (!v.goneAt) { v.goneAt = Date.now(); continue; }
|
|
2447
|
+
if (Date.now() - v.goneAt > ROLLOUT_KEEP_MS) {
|
|
2448
|
+
usageFileCache.delete(k);
|
|
2449
|
+
rolloutSig = ''; // 记录变少了:作废合并缓存,强制重建
|
|
2450
|
+
}
|
|
2073
2451
|
}
|
|
2074
2452
|
const recs = [];
|
|
2453
|
+
// 先取各文件 stat 并算签名:签名没变直接复用上次合并好的记录。shortcut:
|
|
2454
|
+
// 同一毫秒内改写成相同字节数检测不到,实际不会发生,如遇到可把签名换成内容哈希
|
|
2455
|
+
const stats = [];
|
|
2075
2456
|
for (const name of names) {
|
|
2457
|
+
try { stats.push([name, statSync(join(dir, name))]); } catch { /* 读不到的文件跳过 */ }
|
|
2458
|
+
}
|
|
2459
|
+
const sig = stats.map(([name, st]) => `${name}:${st.mtimeMs}:${st.size}`).join('|');
|
|
2460
|
+
if (sig === rolloutSig && rolloutRecsCache) return rolloutRecsCache;
|
|
2461
|
+
for (const [name, st] of stats) {
|
|
2076
2462
|
const full = join(dir, name);
|
|
2077
|
-
let st;
|
|
2078
|
-
try { st = statSync(full); } catch { continue; }
|
|
2079
2463
|
const cached = usageFileCache.get(name);
|
|
2080
|
-
if (cached && cached.mtime === st.mtimeMs && cached.size === st.size) {
|
|
2081
|
-
|
|
2464
|
+
if (cached && cached.mtime === st.mtimeMs && cached.size === st.size && cached.ino === st.ino) {
|
|
2465
|
+
for (const r of cached.recs) recs.push(r); // 不用展开语法:单文件 13 万条会 RangeError
|
|
2082
2466
|
continue;
|
|
2083
2467
|
}
|
|
2084
2468
|
// 追加式增量解析:jsonl 只追加(流式输出期间当前会话文件持续增长,整文件
|
|
2085
2469
|
// 重读重解析一次可达数十毫秒)。从上次已完整解析的偏移续读新增部分;末行
|
|
2086
|
-
//
|
|
2087
|
-
|
|
2470
|
+
// 若是写入中途的半行会被丢弃且偏移不推进,下次变化时重读该行。
|
|
2471
|
+
// inode 也要求一致:文件被滚动删除后同名重建,旧偏移对不上新内容,
|
|
2472
|
+
// 续读会把半截 JSON 当坏行丢掉(实测运行中的会话也会被删了重建)
|
|
2473
|
+
if (cached && st.size > cached.size && st.mtimeMs >= cached.mtimeMs && cached.ino === st.ino) {
|
|
2088
2474
|
const fd = openSync(full, 'r');
|
|
2089
2475
|
let tail = '';
|
|
2090
2476
|
try {
|
|
@@ -2096,9 +2482,11 @@ function rolloutRecords() {
|
|
|
2096
2482
|
usageFileCache.set(name, {
|
|
2097
2483
|
mtime: st.mtimeMs,
|
|
2098
2484
|
size: cached.size + completeBytes,
|
|
2485
|
+
ino: st.ino,
|
|
2099
2486
|
recs: cached.recs.concat(added),
|
|
2100
2487
|
});
|
|
2101
|
-
|
|
2488
|
+
for (const r of cached.recs) recs.push(r);
|
|
2489
|
+
for (const r of added) recs.push(r);
|
|
2102
2490
|
continue;
|
|
2103
2491
|
}
|
|
2104
2492
|
let parsed = [];
|
|
@@ -2111,40 +2499,103 @@ function rolloutRecords() {
|
|
|
2111
2499
|
// 同样只把已完整解析的字节数记为偏移
|
|
2112
2500
|
parsedBytes = Math.min(r.completeBytes, Buffer.byteLength(text, 'utf8'));
|
|
2113
2501
|
} catch { /* 文件读失败跳过 */ }
|
|
2114
|
-
|
|
2115
|
-
|
|
2502
|
+
// 同名重建(inode 变了):旧记录并进来——那是该会话真实发生过的调用;
|
|
2503
|
+
// 同 inode 的全量重读(截断等)仍整体替换
|
|
2504
|
+
const prior = cached && cached.ino !== st.ino ? cached.recs : [];
|
|
2505
|
+
usageFileCache.set(name, { mtime: st.mtimeMs, size: parsedBytes, ino: st.ino, recs: prior.concat(parsed) });
|
|
2506
|
+
for (const r of prior) recs.push(r);
|
|
2507
|
+
for (const r of parsed) recs.push(r);
|
|
2508
|
+
}
|
|
2509
|
+
// 已被滚动删除的文件:保留窗内的解析记录继续参与聚合
|
|
2510
|
+
for (const [k, v] of usageFileCache) {
|
|
2511
|
+
if (nameSet.has(k)) continue;
|
|
2512
|
+
for (const r of v.recs) recs.push(r);
|
|
2116
2513
|
}
|
|
2514
|
+
rolloutSig = sig;
|
|
2515
|
+
rolloutRecsCache = recs;
|
|
2117
2516
|
return recs;
|
|
2118
2517
|
}
|
|
2119
2518
|
|
|
2120
|
-
|
|
2519
|
+
// 会话 → trace_id(官方 db.sqlite 的 session 表,父子会话树共享同一 trace):
|
|
2520
|
+
// 命中即缓存(会话的 trace 写入后不变);查不到不缓存,下轮再试
|
|
2521
|
+
const traceBySession = new Map();
|
|
2522
|
+
async function sessionTrace(dataRoot, sessionId) {
|
|
2523
|
+
if (traceBySession.has(sessionId)) return traceBySession.get(sessionId);
|
|
2524
|
+
const m = await listSessionsTrace(dataRoot, [sessionId]);
|
|
2525
|
+
const trace = m[sessionId] || '';
|
|
2526
|
+
if (trace) traceBySession.set(sessionId, trace);
|
|
2527
|
+
return trace;
|
|
2528
|
+
}
|
|
2529
|
+
|
|
2530
|
+
export function collectUsageStats(sessionId, wantTurns = true, treeTrace = '') {
|
|
2121
2531
|
const recs = rolloutRecords();
|
|
2122
|
-
//
|
|
2123
|
-
//
|
|
2124
|
-
|
|
2532
|
+
// 分钟桶只服务每轮统计(turn-usage 带 session 拉取),状态栏请求带 turns=0
|
|
2533
|
+
// 跳过:省掉全记录分桶与 60 桶序列化(大记录集下每请求几十毫秒)
|
|
2534
|
+
wantTurns = wantTurns && !!sessionId;
|
|
2125
2535
|
const today = new Date();
|
|
2126
2536
|
const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
|
|
2537
|
+
// 记录没变(文件签名相同)+ 查询口径没变时直接复用上次聚合结果:锚定速率是
|
|
2538
|
+
// 记录的纯函数(锚 = 最新完成时刻,不随请求时刻移动),跨午夜才要重算"今日"
|
|
2539
|
+
const cacheKey = `${sessionId || ''}|${wantTurns ? 1 : 0}|${treeTrace}|${todayKey}`;
|
|
2540
|
+
if (statsResultCache.sig === rolloutSig && statsResultCache.key === cacheKey && statsResultCache.result) {
|
|
2541
|
+
return statsResultCache.result;
|
|
2542
|
+
}
|
|
2127
2543
|
const global = { todayTokens: 0, todayOut: 0, totalTokens: 0, totalOut: 0, tasks: 0, records: recs.length };
|
|
2128
2544
|
// 每轮用量按本地 HH:mm 分桶(回答末尾的显示时间与之匹配);
|
|
2129
2545
|
// 本地记录只留最近几轮,注入侧只给能对上时间的回答显示
|
|
2130
2546
|
const byMinute = new Map();
|
|
2547
|
+
// 最近 60 秒速率(状态栏 tokRate 项):token 按调用耗时摊到时间轴(完成
|
|
2548
|
+
// 时刻往前 durationMs 一段),按窗口重叠比例折算,长调用完成瞬间不会出现
|
|
2549
|
+
// 假尖峰。窗口以该口径最新一条记录的完成时刻为锚、往前 60 秒——回答结束
|
|
2550
|
+
// 后锚不再移动,速率自然停在最后的值:不衰减归零;有新调用完成锚前移、
|
|
2551
|
+
// 数值刷新。文件被官方滚动删除后靠保留窗内的缓存记录维持显示
|
|
2552
|
+
//(shortcut: 重启/热替换后只剩存活文件的记录,全删完速率归零,等官方出持久数据源再换)。
|
|
2553
|
+
// 统计范围:带 ?session= 按会话树算——本会话 + 同 trace 的子代理会话
|
|
2554
|
+
//(子代理的模型调用是这个会话真实发生的输出,只算本会话 id 会让派了
|
|
2555
|
+
// 子代理的会话速率归零),treeTrace 查不到时退化为只算本会话;
|
|
2556
|
+
// 不带 ?session= 则全局。与每轮桶不同,辅助小调用也计入(它们是真实消耗)
|
|
2557
|
+
const inTree = (r) => !sessionId || r.session === sessionId || (!!treeTrace && r.trace === treeTrace);
|
|
2558
|
+
const winMs = 60_000;
|
|
2559
|
+
let anchor = 0;
|
|
2560
|
+
for (const r of recs) {
|
|
2561
|
+
if (Number.isFinite(r.ts) && inTree(r)) anchor = Math.max(anchor, r.ts);
|
|
2562
|
+
}
|
|
2563
|
+
const anchorFuture = anchor > Date.now(); // 未来时间戳:钳制值依赖请求时刻,结果不能缓存
|
|
2564
|
+
anchor = Math.min(anchor, Date.now()); // 未来时间戳(时钟回拨等)别把锚拉到未来
|
|
2565
|
+
let rateTotal = 0;
|
|
2566
|
+
let rateOut = 0;
|
|
2131
2567
|
for (const r of recs) {
|
|
2132
2568
|
const total = r.in + r.out;
|
|
2133
2569
|
global.totalTokens += total;
|
|
2134
2570
|
global.totalOut += r.out;
|
|
2135
|
-
|
|
2136
|
-
|
|
2571
|
+
// 按本地日期归"今日":r.at 是 ISO/UTC 串,直接取前 10 位是 UTC 日期,
|
|
2572
|
+
// 本地凌晨(UTC+8 的 0-8 点)完成的调用会被算进昨天
|
|
2573
|
+
if (Number.isFinite(r.ts)) {
|
|
2574
|
+
const rd = new Date(r.ts);
|
|
2575
|
+
const day = `${rd.getFullYear()}-${String(rd.getMonth() + 1).padStart(2, '0')}-${String(rd.getDate()).padStart(2, '0')}`;
|
|
2576
|
+
if (day === todayKey) { global.todayTokens += total; global.todayOut += r.out; }
|
|
2577
|
+
}
|
|
2578
|
+
const end = r.ts;
|
|
2579
|
+
if (Number.isFinite(end) && inTree(r)) {
|
|
2580
|
+
const dur = Math.max(r.ms || 0, 1); // 无耗时字段的旧记录按 1ms 点事件计
|
|
2581
|
+
const overlap = Math.min(end, anchor) - Math.max(end - dur, anchor - winMs);
|
|
2582
|
+
if (overlap > 0) {
|
|
2583
|
+
const w = overlap / dur;
|
|
2584
|
+
rateTotal += total * w;
|
|
2585
|
+
rateOut += r.out * w;
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2137
2588
|
// 每轮回答只统计主对话流的调用:起名等辅助请求是独立小上下文、
|
|
2138
2589
|
// 缓存从零开始,混进分钟桶会把命中率拉到个位数(全局统计仍全量计入)
|
|
2139
2590
|
if (!wantTurns || total < 5000) continue;
|
|
2140
2591
|
// 指定会话时每轮桶只算该会话的调用——否则切到别的会话聊天后,
|
|
2141
2592
|
// 那些调用会被区间归属算进当前会话最后一行的头上
|
|
2142
2593
|
if (r.session !== sessionId) continue;
|
|
2143
|
-
const t =
|
|
2594
|
+
const t = r.ts;
|
|
2144
2595
|
if (!Number.isFinite(t)) continue;
|
|
2145
2596
|
const d = new Date(t);
|
|
2146
|
-
//
|
|
2147
|
-
//
|
|
2597
|
+
// 桶键 = 本地"月-日 时:分";注入侧不读这个键(按 ts 区间归属到回答行),
|
|
2598
|
+
// 键只用于同分钟的调用并桶
|
|
2148
2599
|
const hm = (d.getMonth() + 1) + '-' + d.getDate() + ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
|
|
2149
2600
|
const bucket = byMinute.get(hm) || { hm, in: 0, out: 0, cacheRead: 0, ts: t };
|
|
2150
2601
|
bucket.in += r.in;
|
|
@@ -2153,8 +2604,13 @@ function collectUsageStats(sessionId) {
|
|
|
2153
2604
|
bucket.ts = Math.max(bucket.ts, t);
|
|
2154
2605
|
byMinute.set(hm, bucket);
|
|
2155
2606
|
}
|
|
2607
|
+
// 保留 1 位小数:工具循环期的输出只有零点几每秒,取整会显示成 0/s
|
|
2608
|
+
const perSec = (x) => Math.round((x / (winMs / 1000)) * 10) / 10;
|
|
2609
|
+
global.rate60 = { total: perSec(rateTotal), out: perSec(rateOut) };
|
|
2156
2610
|
const recentTurns = [...byMinute.values()].sort((a, b) => b.ts - a.ts).slice(0, 60);
|
|
2157
|
-
|
|
2611
|
+
const out = { global, recentTurns };
|
|
2612
|
+
if (!anchorFuture) statsResultCache = { sig: rolloutSig, key: cacheKey, result: out };
|
|
2613
|
+
return out;
|
|
2158
2614
|
}
|
|
2159
2615
|
|
|
2160
2616
|
function readJsonFile(p) {
|
|
@@ -2202,6 +2658,9 @@ function mergeTitleGenConfig(saved) {
|
|
|
2202
2658
|
baseUrl: typeof s.baseUrl === 'string' ? s.baseUrl.trim().slice(0, 500) : d.baseUrl,
|
|
2203
2659
|
apiKey: typeof s.apiKey === 'string' ? s.apiKey.trim().slice(0, 500) : d.apiKey,
|
|
2204
2660
|
format: s.format === 'openai' ? 'openai' : s.format === 'anthropic' ? 'anthropic' : '',
|
|
2661
|
+
recentQa: Number.isFinite(Number(s.recentQa)) ? Math.min(20, Math.max(1, Math.round(Number(s.recentQa)))) : d.recentQa,
|
|
2662
|
+
hoverBtn: s.hoverBtn !== false,
|
|
2663
|
+
menuEntry: s.menuEntry !== false,
|
|
2205
2664
|
customWritten: written,
|
|
2206
2665
|
};
|
|
2207
2666
|
}
|
|
@@ -2238,6 +2697,30 @@ function mergeSyncConfig(saved) {
|
|
|
2238
2697
|
};
|
|
2239
2698
|
}
|
|
2240
2699
|
|
|
2700
|
+
// WebDAV 地址的协议判定:http 明文会把 Basic 登录名和密码原样传出去,
|
|
2701
|
+
// http 只放行回环与内网地址(内网 NAS 常用 http),公网主机必须 https
|
|
2702
|
+
function webdavHttpSchemeOk(raw) {
|
|
2703
|
+
const url = typeof raw === 'string' ? raw.trim() : '';
|
|
2704
|
+
if (!/^https?:\/\//i.test(url)) return false;
|
|
2705
|
+
if (/^https:/i.test(url)) return true;
|
|
2706
|
+
let host = '';
|
|
2707
|
+
try { host = new URL(url).hostname.toLowerCase(); } catch { return false; }
|
|
2708
|
+
host = host.replace(/^\[|\]$/g, ''); // URL.hostname 对 IPv6 地址带方括号
|
|
2709
|
+
if (host === 'localhost' || host === '::1') return true;
|
|
2710
|
+
// IPv6 字面量不走下面的域名规则(不含点,会被误判成内网主机名):
|
|
2711
|
+
// 只放行链路本地(fe80::/10)与 ULA(fc00::/7)内网段,公网 v6 仍要 https
|
|
2712
|
+
// (按 RFC 5952 规范写法匹配首段,缩写首段的极端写法不认)
|
|
2713
|
+
if (host.includes(':')) return /^(fe[89ab][0-9a-f]|f[cd][0-9a-f]{2}):/i.test(host);
|
|
2714
|
+
// 单标签主机名(无点,如 mynas)与 .local/.lan/.internal 后缀的域名按内网 NAS
|
|
2715
|
+
// 处理放行 http;其余域名型主机要求 https
|
|
2716
|
+
if (!host.includes('.') || /\.(local|lan|internal)$/.test(host)) return true;
|
|
2717
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
2718
|
+
if (!m) return false;
|
|
2719
|
+
const a = Number(m[1]);
|
|
2720
|
+
const b = Number(m[2]);
|
|
2721
|
+
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
|
2722
|
+
}
|
|
2723
|
+
|
|
2241
2724
|
// POST /sync 表单校验:url/login/password/dir 全量替换(dir 缺省时不动已有值)。
|
|
2242
2725
|
// URL 必填,指向 WebDAV 服务器(可含路径前缀);dir 为其下的上传目录,可多级;
|
|
2243
2726
|
// historyLimit 可选(缺省时不动已有值),0–100 的整数
|
|
@@ -2248,6 +2731,7 @@ function validateSyncForm(raw) {
|
|
|
2248
2731
|
if (!url) return { error: '请先填写 URL(如 https://dav.jianguoyun.com/dav/)' };
|
|
2249
2732
|
if (!/^https?:\/\/\S+$/.test(url)) return { error: 'URL 需为 WebDAV 服务器地址,如 https://dav.example.com/dav/' };
|
|
2250
2733
|
if (url.length > 500) return { error: 'URL 过长(最多 500 字符)' };
|
|
2734
|
+
if (!webdavHttpSchemeOk(url)) return { error: '公网地址需用 https(http 明文传输登录名和密码);内网或回环地址(如 http://192.168.1.5:5005)可继续用 http' };
|
|
2251
2735
|
if (login.length > 300 || password.length > 300) return { error: '登录名或密码过长(最多 300 字符)' };
|
|
2252
2736
|
const out = { type: 'webdav', url, login, password };
|
|
2253
2737
|
if (typeof raw.dir === 'string') {
|
|
@@ -2367,7 +2851,8 @@ async function syncBgPull({ sync, proxyUrl, dataRoot }) {
|
|
|
2367
2851
|
if (!name) continue; // 云端的异常文件名条目不镜像
|
|
2368
2852
|
const l = localByName.get(name);
|
|
2369
2853
|
if (l && l.size === f.size) continue;
|
|
2370
|
-
|
|
2854
|
+
// 临时名带 pid+随机:与上传路径撞同一文件名时不共用一个 .tmp
|
|
2855
|
+
const tmp = join(dir, `${name}.${process.pid}.${Date.now().toString(36)}.tmp`);
|
|
2371
2856
|
const get = await webdavRequest({ method: 'GET', url: syncBgFileUrl(sync, name), login: sync.login, password: sync.password, proxyUrl, timeoutMs: 120000, downloadFile: tmp });
|
|
2372
2857
|
const bad = !get.ok || get.httpCode < 200 || get.httpCode >= 300;
|
|
2373
2858
|
if (bad) {
|
|
@@ -2387,8 +2872,8 @@ async function syncBgPull({ sync, proxyUrl, dataRoot }) {
|
|
|
2387
2872
|
}
|
|
2388
2873
|
|
|
2389
2874
|
// 信封校验:云端文件必须是 { app: 'zcode-pro', kind, format, data } 且组别与文件名
|
|
2390
|
-
// 前缀一致;4MB
|
|
2391
|
-
function parseSyncEnvelope(body, kind, label) {
|
|
2875
|
+
// 前缀一致;4MB 上限挡住异常大文件。导出供回归测试直接喂坏信封
|
|
2876
|
+
export function parseSyncEnvelope(body, kind, label) {
|
|
2392
2877
|
if (body.length > 4 * 1024 * 1024) {
|
|
2393
2878
|
return { error: `云端 ${label} 超过 4MB,已拒绝应用`, code: 'sync-remote-invalid', status: 400 };
|
|
2394
2879
|
}
|
|
@@ -2397,6 +2882,10 @@ function parseSyncEnvelope(body, kind, label) {
|
|
|
2397
2882
|
if (!doc || typeof doc !== 'object' || doc.app !== 'zcode-pro' || doc.kind !== kind || !doc.data || typeof doc.data !== 'object') {
|
|
2398
2883
|
return { error: `云端 ${label} 不是 zcode-pro 的同步数据(可能被其他内容占用),请删除该文件或换一个目录`, code: 'sync-remote-invalid', status: 409 };
|
|
2399
2884
|
}
|
|
2885
|
+
// format 超出认识范围(更新版本的 zcode-pro 写入的新格式):不导入,提示升级客户端
|
|
2886
|
+
if (doc.format !== 1) {
|
|
2887
|
+
return { error: `云端 ${label} 是更新版本的 zcode-pro 写入的数据,当前客户端版本过旧,请升级 zcode-pro 后再同步`, code: 'sync-remote-invalid', status: 400 };
|
|
2888
|
+
}
|
|
2400
2889
|
return { doc };
|
|
2401
2890
|
}
|
|
2402
2891
|
|
|
@@ -2425,11 +2914,38 @@ async function fetchSyncNamedDoc(sync, proxyUrl, fileName) {
|
|
|
2425
2914
|
return parseSyncEnvelope(r.body, kind, fileName);
|
|
2426
2915
|
}
|
|
2427
2916
|
|
|
2917
|
+
// —— /sync/run 单飞 ————————————————————————————————————
|
|
2918
|
+
// 同 direction 的并发触发共用同一个 promise(去重),不同 direction 串行排队:
|
|
2919
|
+
// 两轮同步并发跑会互相清掉对方刚上传的历史版本。在途(排队 + 执行)期间计入
|
|
2920
|
+
// 忙碌标志,启动器热替换据此延后——同步中途换进程同样会互删历史版本
|
|
2921
|
+
let syncRunJobs = new Map(); // direction → 在跑或排队的 promise
|
|
2922
|
+
let syncRunQueue = Promise.resolve();
|
|
2923
|
+
|
|
2924
|
+
function enqueueSyncRun(direction, fn) {
|
|
2925
|
+
const inflight = syncRunJobs.get(direction);
|
|
2926
|
+
if (inflight) return inflight;
|
|
2927
|
+
const prev = syncRunQueue;
|
|
2928
|
+
const promise = (async () => {
|
|
2929
|
+
await prev;
|
|
2930
|
+
try {
|
|
2931
|
+
return await fn();
|
|
2932
|
+
} finally {
|
|
2933
|
+
syncRunJobs.delete(direction);
|
|
2934
|
+
}
|
|
2935
|
+
})();
|
|
2936
|
+
syncRunQueue = promise.then(() => undefined, () => undefined);
|
|
2937
|
+
syncRunJobs.set(direction, promise);
|
|
2938
|
+
return trackBusy(promise);
|
|
2939
|
+
}
|
|
2940
|
+
|
|
2428
2941
|
async function runSettingsSync({ direction, dataRoot, configFile, config, proxyUrl }) {
|
|
2429
2942
|
const sync = config.sync;
|
|
2430
2943
|
if (!sync.url || !/^https?:\/\/\S+$/.test(sync.url)) {
|
|
2431
2944
|
return { code: 'sync-not-configured', status: 400, error: '请先填写 WebDAV URL 并保存' };
|
|
2432
2945
|
}
|
|
2946
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2947
|
+
return { code: 'sync-not-configured', status: 400, error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' };
|
|
2948
|
+
}
|
|
2433
2949
|
if (!sync.include.zcodepro && !sync.include.model) {
|
|
2434
2950
|
return { code: 'sync-not-configured', status: 400, error: '请至少选择一项同步内容' };
|
|
2435
2951
|
}
|
|
@@ -2438,10 +2954,17 @@ async function runSettingsSync({ direction, dataRoot, configFile, config, proxyU
|
|
|
2438
2954
|
: runSyncPull({ dataRoot, configFile, config, sync, proxyUrl });
|
|
2439
2955
|
}
|
|
2440
2956
|
|
|
2441
|
-
// headroom.json 里值得同步/应用的判定:providers
|
|
2442
|
-
//
|
|
2957
|
+
// headroom.json 里值得同步/应用的判定:providers 每条注册都得带路由必需的
|
|
2958
|
+
// id/upstream/format/keyHash 才算有效——空对象、空注册或残缺条目(如只写个 id
|
|
2959
|
+
// 的测试夹具)不上传也不覆盖,免得把别台机器拉回无映射状态(请求 502)
|
|
2443
2960
|
function validHeadroomDoc(hr) {
|
|
2444
|
-
return !!hr && typeof hr === 'object' && !Array.isArray(hr)
|
|
2961
|
+
return !!hr && typeof hr === 'object' && !Array.isArray(hr)
|
|
2962
|
+
&& Array.isArray(hr.providers) && hr.providers.length > 0
|
|
2963
|
+
&& hr.providers.every((p) => !!p && typeof p === 'object'
|
|
2964
|
+
&& typeof p.id === 'string' && p.id !== ''
|
|
2965
|
+
&& typeof p.upstream === 'string' && p.upstream !== ''
|
|
2966
|
+
&& (p.format === 'anthropic' || p.format === 'openai')
|
|
2967
|
+
&& typeof p.keyHash === 'string' && p.keyHash !== '');
|
|
2445
2968
|
}
|
|
2446
2969
|
|
|
2447
2970
|
// 上传:每组独立一个云端文件(zcodepro.json / model.json,始终最新一版),勾选几组
|
|
@@ -2456,6 +2979,11 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
2456
2979
|
if (sync.include.zcodepro) {
|
|
2457
2980
|
// sync(本机的同步配置与凭据)、version(本机 helper 版本)与 aliases 不外发
|
|
2458
2981
|
const { sync: _s, version: _v, aliases: _a, ...rest } = config;
|
|
2982
|
+
// titleGen.apiKey 是模型凭据,与 sync 一样只留本机(设置页文案:凭据不参与同步)
|
|
2983
|
+
if (rest.titleGen && typeof rest.titleGen === 'object') {
|
|
2984
|
+
const { apiKey: _k, ...tg } = rest.titleGen;
|
|
2985
|
+
rest.titleGen = tg;
|
|
2986
|
+
}
|
|
2459
2987
|
docs.zcodepro = rest;
|
|
2460
2988
|
}
|
|
2461
2989
|
if (sync.include.model) {
|
|
@@ -2520,10 +3048,12 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
2520
3048
|
}
|
|
2521
3049
|
sync.lastPushAt = Date.now();
|
|
2522
3050
|
// 同步是分钟级网络流程:写回前重读配置、只合并本次时间戳,
|
|
2523
|
-
//
|
|
2524
|
-
|
|
2525
|
-
|
|
2526
|
-
|
|
3051
|
+
// 别把期间用户在设置弹窗的修改用这份旧快照盖掉;读改写放进跨进程锁内同步执行
|
|
3052
|
+
await withConfigLock(configFile, () => {
|
|
3053
|
+
const freshPush = loadConfig(configFile);
|
|
3054
|
+
freshPush.sync = { ...freshPush.sync, lastPushAt: sync.lastPushAt };
|
|
3055
|
+
if (!saveConfig(configFile, freshPush)) console.error('[zcodepro] lastPushAt 写回被拒(zcodepro.json 损坏),上传本身已成功');
|
|
3056
|
+
});
|
|
2527
3057
|
// 上传成功后清理超出保留个数的旧历史版本(best-effort,失败不影响上传结果)
|
|
2528
3058
|
const pruned = await pruneSyncHistory(sync, proxyUrl, keep);
|
|
2529
3059
|
// 背景图库镜像上传(勾了 zcodepro 组才传;设置文档已传走,图库失败单独报错,重试幂等)
|
|
@@ -2575,25 +3105,33 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
2575
3105
|
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
2576
3106
|
};
|
|
2577
3107
|
const atomicWrite = (p, obj) => {
|
|
2578
|
-
const tmp = p
|
|
2579
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', 'utf8');
|
|
3108
|
+
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
3109
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
2580
3110
|
renameSync(tmp, p);
|
|
2581
3111
|
};
|
|
2582
3112
|
|
|
2583
3113
|
if (docs.zcodepro) {
|
|
2584
3114
|
const rz = docs.zcodepro;
|
|
2585
|
-
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
2596
|
-
|
|
3115
|
+
// 整段 zcodepro.json 读改写放进跨进程锁内同步执行(applySyncDocs 是同步
|
|
3116
|
+
// 调用点,用同步等锁变体),防止与别的写入方互相覆盖整份配置
|
|
3117
|
+
const rzErr = withConfigLockSync(configFile, () => {
|
|
3118
|
+
const next = loadConfig(configFile);
|
|
3119
|
+
applyFeaturesPartial(next.features, rz.features);
|
|
3120
|
+
next.styles = applyStylesPartial(next.styles, rz.styles);
|
|
3121
|
+
// 别名保持本机的原样:云端备份里的别名可能出自其他机器(路径在本机无效),
|
|
3122
|
+
// 且 3.16.1 起别名功能已停用,不再导入
|
|
3123
|
+
if (typeof rz.proxy === 'string') {
|
|
3124
|
+
const v = rz.proxy.trim();
|
|
3125
|
+
if (v === '' || /^https?:\/\/\S+:\d+$/.test(v)) next.proxy = v;
|
|
3126
|
+
}
|
|
3127
|
+
next.sync = { ...next.sync, lastPullAt: sync.lastPullAt }; // 保留本机 sync 配置与凭据,只记本次拉取时间
|
|
3128
|
+
backupFile(configFile);
|
|
3129
|
+
if (!saveConfig(configFile, next)) {
|
|
3130
|
+
return { error: 'zcodepro.json 读取失败或已损坏,导入中止(请先修好配置文件)', code: 'config-unreadable', status: 500 };
|
|
3131
|
+
}
|
|
3132
|
+
return null;
|
|
3133
|
+
});
|
|
3134
|
+
if (rzErr) return rzErr;
|
|
2597
3135
|
applied.push('zcodepro');
|
|
2598
3136
|
}
|
|
2599
3137
|
if (docs.model) {
|
|
@@ -2611,19 +3149,28 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
2611
3149
|
atomicWrite(pcFile, pc);
|
|
2612
3150
|
}
|
|
2613
3151
|
// headroom.json 只在云端文档带有效注册时才覆盖(旧版云端文档没有该字段、
|
|
2614
|
-
// 或 providers
|
|
2615
|
-
// 与 router
|
|
3152
|
+
// 或 providers 为空/残缺,都不动本机,免得清掉已有映射);instances(实例端口表)
|
|
3153
|
+
// 与 router(监听端口)是本机运行状态,云端的一律不用,保留本机的。
|
|
3154
|
+
// 路径跟随 dataRoot(与同组其他文件一致):defaultHeadroomFile() 按 HOME 定位,
|
|
3155
|
+
// 测试跑进真配置会把用户的路由表整个写坏
|
|
2616
3156
|
const hr = docs.model.headroom;
|
|
2617
3157
|
if (validHeadroomDoc(hr)) {
|
|
2618
|
-
const hrFile =
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
const
|
|
2622
|
-
|
|
2623
|
-
|
|
2624
|
-
|
|
2625
|
-
|
|
2626
|
-
|
|
3158
|
+
const hrFile = join(dataRoot, 'headroom.json');
|
|
3159
|
+
// 云端文档里带的三个设置键也剥掉:kompressBackend/powerSaveCpu/powerWatchInterval
|
|
3160
|
+
// 是本机设置,云端的赢会把 B 机器的压缩设备决策改成 A 机器的
|
|
3161
|
+
const { instances: _remoteInst, router: _remoteRouter, kompressBackend: _rKb, powerSaveCpu: _rPs, powerWatchInterval: _rWi, ...hrRest } = hr;
|
|
3162
|
+
// 读改写整段持 headroom.json 文件锁(与面板 interval 写入、setHeadroomUsage 互斥),
|
|
3163
|
+
// 锁内重读最新基线合并:以本机现有键为底、云端注册覆盖 providers,
|
|
3164
|
+
// instances/router 与三个本机设置键保留本机值
|
|
3165
|
+
withConfigLockSync(hrFile, () => {
|
|
3166
|
+
const fresh = readJsonFile(hrFile);
|
|
3167
|
+
const base = (fresh && typeof fresh === 'object') ? fresh : {};
|
|
3168
|
+
const merged = { ...base, ...hrRest };
|
|
3169
|
+
if (base.instances) merged.instances = base.instances;
|
|
3170
|
+
if (base.router) merged.router = base.router;
|
|
3171
|
+
backupFile(hrFile);
|
|
3172
|
+
atomicWrite(hrFile, merged);
|
|
3173
|
+
});
|
|
2627
3174
|
// 让路由立刻吃到新映射、缺的实例补起来(路由器本身每请求重读配置,
|
|
2628
3175
|
// 只有新上游的实例需要这一步),失败不影响同步结果
|
|
2629
3176
|
runHeadroomHook(['ensure'], 20000).catch(() => { /* 尽力而为 */ });
|
|
@@ -2633,9 +3180,12 @@ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
2633
3180
|
// 没动 zcodepro.json 时,lastPullAt 也要写入配置文件(动了则已随 next 一起保存)。
|
|
2634
3181
|
// 写回前重读配置、只合并时间戳:别用旧快照盖掉同步期间用户的修改
|
|
2635
3182
|
if (!applied.includes('zcodepro')) {
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
3183
|
+
// lastPullAt 读改写同样在跨进程锁内同步完成
|
|
3184
|
+
withConfigLockSync(configFile, () => {
|
|
3185
|
+
const freshPull = loadConfig(configFile);
|
|
3186
|
+
freshPull.sync = { ...freshPull.sync, lastPullAt: sync.lastPullAt };
|
|
3187
|
+
if (!saveConfig(configFile, freshPull)) console.error('[zcodepro] lastPullAt 写回被拒(zcodepro.json 损坏)');
|
|
3188
|
+
});
|
|
2639
3189
|
}
|
|
2640
3190
|
return { applied };
|
|
2641
3191
|
}
|
|
@@ -2661,7 +3211,9 @@ async function runSyncTest({ sync, proxyUrl }) {
|
|
|
2661
3211
|
});
|
|
2662
3212
|
return { ok, resp };
|
|
2663
3213
|
};
|
|
2664
|
-
|
|
3214
|
+
// PROPFIND 的集合地址统一带尾斜杠(图库列表 syncBgListRemote 同款):
|
|
3215
|
+
// 会给目录地址回 301 的网盘不认无斜杠写法,会报“HTTP 301”
|
|
3216
|
+
const baseDir = syncBaseDir(sync) + '/';
|
|
2665
3217
|
// ① 只要拿到响应且不是凭据问题就算连通(404/409 = 目录还没建,交给第②步处理)
|
|
2666
3218
|
const connect = await probe('connect', () => webdavRequest({ method: 'PROPFIND', url: baseDir, ...auth, timeoutMs: 20000, headers: ['Depth: 0'] }));
|
|
2667
3219
|
if (!connect.ok && connect.resp.ok && (connect.resp.httpCode === 404 || connect.resp.httpCode === 409)) {
|
|
@@ -2697,7 +3249,7 @@ async function runSyncTest({ sync, proxyUrl }) {
|
|
|
2697
3249
|
// PROPFIND 云端同步目录,列出全部备份版本(固定名 + 带时间戳的历史):
|
|
2698
3250
|
// 按修改时间从新到旧(时间缺失的按文件名排后);目录还不存在视为空列表
|
|
2699
3251
|
async function listSyncVersions(sync, proxyUrl) {
|
|
2700
|
-
const r = await webdavRequest({ method: 'PROPFIND', url: syncBaseDir(sync), login: sync.login, password: sync.password, proxyUrl, timeoutMs: 30000, headers: ['Depth: 1'] });
|
|
3252
|
+
const r = await webdavRequest({ method: 'PROPFIND', url: syncBaseDir(sync) + '/', login: sync.login, password: sync.password, proxyUrl, timeoutMs: 30000, headers: ['Depth: 1'] });
|
|
2701
3253
|
if (!r.ok) return { error: r.error, code: 'sync-request', status: 502 };
|
|
2702
3254
|
if (r.httpCode === 404 || r.httpCode === 409) return { files: [] };
|
|
2703
3255
|
if (r.httpCode < 200 || r.httpCode >= 300) return { error: webdavHttpText(r.httpCode), code: 'sync-request', status: 502 };
|
|
@@ -2741,40 +3293,6 @@ async function pruneSyncHistory(sync, proxyUrl, keep) {
|
|
|
2741
3293
|
return removed;
|
|
2742
3294
|
}
|
|
2743
3295
|
|
|
2744
|
-
// 别名表清洗(同步下载用):只收 路径字符串 → 短字符串 的条目,数量限幅
|
|
2745
|
-
function sanitizeAliases(raw) {
|
|
2746
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
2747
|
-
const out = {};
|
|
2748
|
-
let n = 0;
|
|
2749
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
2750
|
-
if (typeof k !== 'string' || k.length > 500 || k.includes('\0')) continue;
|
|
2751
|
-
if (typeof v !== 'string' || v.length > 200 || /[\r\n\0]/.test(v)) continue;
|
|
2752
|
-
out[k] = v;
|
|
2753
|
-
if (++n >= 2000) break;
|
|
2754
|
-
}
|
|
2755
|
-
return out;
|
|
2756
|
-
}
|
|
2757
|
-
|
|
2758
|
-
// 别名表合并(同步上传/下载共用):取两边的并集,配过别名的条目优先——同一路径
|
|
2759
|
-
// 两边都配了别名时用本机的;只有一边配过时保留配过的那个。所以在一台机器上清除
|
|
2760
|
-
// 别名后,只要别的机器还配着,下次同步还会把这条带回来,两边都清掉才会真正消失。
|
|
2761
|
-
// 导出以便测试脚本直接驱动。
|
|
2762
|
-
export function mergeAliases(localRaw, remoteRaw) {
|
|
2763
|
-
const out = {};
|
|
2764
|
-
const put = (k, v) => {
|
|
2765
|
-
if (typeof k !== 'string' || k.length > 500 || k.includes('\0')) return;
|
|
2766
|
-
if (typeof v !== 'string' || !v || v.length > 200 || /[\r\n\0]/.test(v)) return;
|
|
2767
|
-
out[k] = v;
|
|
2768
|
-
};
|
|
2769
|
-
const entries = (raw) => (raw && typeof raw === 'object' && !Array.isArray(raw)) ? Object.entries(raw) : [];
|
|
2770
|
-
for (const [k, v] of entries(remoteRaw)) put(k, v);
|
|
2771
|
-
for (const [k, v] of entries(localRaw)) {
|
|
2772
|
-
// 本机配过的覆盖云端同路径条目;本机是空值(视为没配过)时不覆盖,云端配过的留下
|
|
2773
|
-
if (v) put(k, v);
|
|
2774
|
-
}
|
|
2775
|
-
return out;
|
|
2776
|
-
}
|
|
2777
|
-
|
|
2778
3296
|
// features 部分更新(POST /config 与同步下载共用):只收已知开关的布尔值
|
|
2779
3297
|
function applyFeaturesPartial(base, partial) {
|
|
2780
3298
|
const out = (base && typeof base === 'object') ? base : {};
|
|
@@ -2782,9 +3300,9 @@ function applyFeaturesPartial(base, partial) {
|
|
|
2782
3300
|
const known = new Set(Object.keys(defaultConfig().features));
|
|
2783
3301
|
for (const key of Object.keys(partial)) {
|
|
2784
3302
|
// 布尔特性一律可存(新特性未列入 defaultConfig 时不能被丢弃),
|
|
2785
|
-
//
|
|
3303
|
+
// 非布尔值只在已知键内、且与默认值同类型时接受——防垃圾类型进配置
|
|
2786
3304
|
if (typeof partial[key] === 'boolean') out[key] = partial[key];
|
|
2787
|
-
else if (known.has(key)) out[key] = partial[key];
|
|
3305
|
+
else if (known.has(key) && typeof partial[key] === typeof defaultConfig().features[key]) out[key] = partial[key];
|
|
2788
3306
|
}
|
|
2789
3307
|
return out;
|
|
2790
3308
|
}
|
|
@@ -2853,6 +3371,55 @@ export async function scanIdleBusy(paths, dataRoot) {
|
|
|
2853
3371
|
}
|
|
2854
3372
|
|
|
2855
3373
|
// Linux:直接读取 /proc(comm 定位 CLI、cwd 定位项目、task/<pid>/children 拿子进程)
|
|
3374
|
+
// 后台 bash 任务扫描:运行中的任务进程把 /tmp/zcode-bash-*/<会话id>/call_*-stdout.log
|
|
3375
|
+
// 握在 stdout/stderr 上(实测 fd/1、fd/2),日志路径就带会话 id——按"有进程握着
|
|
3376
|
+
// 该文件"判定在跑,纯文件系统读取,不惊动会话进程。不能走会话快照:快照会把
|
|
3377
|
+
// 会话 resume 起来,逐会话轮询快照曾造成整夜 6600 次/小时 resume、内存暴涨。
|
|
3378
|
+
// 返回 { ok, jobs: [{ sessionId, jobId }] };平台不支持(无 /proc 且无 lsof)时 ok=false
|
|
3379
|
+
export function scanBackgroundBash(tmpDir = '/tmp', procDir = '/proc') {
|
|
3380
|
+
let files;
|
|
3381
|
+
try {
|
|
3382
|
+
files = new Map(); // 日志绝对路径 → { sessionId, jobId }
|
|
3383
|
+
for (const d of readdirSync(tmpDir)) {
|
|
3384
|
+
if (!d.startsWith('zcode-bash-')) continue;
|
|
3385
|
+
let sessDirs;
|
|
3386
|
+
try { sessDirs = readdirSync(join(tmpDir, d)); } catch { continue; }
|
|
3387
|
+
for (const sess of sessDirs) {
|
|
3388
|
+
if (!/^sess/.test(sess)) continue;
|
|
3389
|
+
let names;
|
|
3390
|
+
try { names = readdirSync(join(tmpDir, d, sess)); } catch { continue; }
|
|
3391
|
+
for (const n of names) {
|
|
3392
|
+
const m = n.match(/^call_(.+)-stdout\.log$/);
|
|
3393
|
+
if (m) files.set(join(tmpDir, d, sess, n), { sessionId: sess, jobId: m[1] });
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
}
|
|
3397
|
+
} catch { return { ok: false, jobs: [] }; }
|
|
3398
|
+
if (!files.size) return { ok: true, jobs: [] };
|
|
3399
|
+
const hit = new Map(); // 文件 → 记录(同一任务的 stdout/stderr 两个 fd 去重)
|
|
3400
|
+
try {
|
|
3401
|
+
// Linux:/proc/*/fd/{1,2} 的符号链接命中即在跑
|
|
3402
|
+
for (const p of readdirSync(procDir)) {
|
|
3403
|
+
if (!/^\d+$/.test(p)) continue;
|
|
3404
|
+
for (const fd of ['1', '2']) {
|
|
3405
|
+
let target;
|
|
3406
|
+
try { target = readlinkSync(join(procDir, p, 'fd', fd)); } catch { continue; }
|
|
3407
|
+
const rec = files.get(target);
|
|
3408
|
+
if (rec) hit.set(target, rec);
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
} catch {
|
|
3412
|
+
// 无 /proc(macOS):lsof -t 判文件是否被占用
|
|
3413
|
+
for (const f of files.keys()) {
|
|
3414
|
+
let r;
|
|
3415
|
+
try { r = spawnSync('lsof', ['-t', '--', f], { encoding: 'utf8', timeout: 3000 }); } catch { return { ok: false, jobs: [] }; }
|
|
3416
|
+
if (r.error) return { ok: false, jobs: [] };
|
|
3417
|
+
if ((r.stdout || '').trim()) hit.set(f, files.get(f));
|
|
3418
|
+
}
|
|
3419
|
+
}
|
|
3420
|
+
return { ok: true, jobs: [...hit.values()] };
|
|
3421
|
+
}
|
|
3422
|
+
|
|
2856
3423
|
function scanIdleBusyLinux(paths) {
|
|
2857
3424
|
let pids;
|
|
2858
3425
|
try { pids = readdirSync('/proc').filter((d) => /^\d+$/.test(d)); }
|
|
@@ -2862,30 +3429,36 @@ function scanIdleBusyLinux(paths) {
|
|
|
2862
3429
|
for (const pid of pids) {
|
|
2863
3430
|
try {
|
|
2864
3431
|
if (readFileSync(`/proc/${pid}/comm`, 'utf8').trim() !== 'zcode-cli') continue;
|
|
2865
|
-
|
|
3432
|
+
const cwd = readlinkSync(`/proc/${pid}/cwd`);
|
|
3433
|
+
// 同一工作区可以开多个会话进程:记列表别后写覆盖先写——漏扫一个会话的
|
|
3434
|
+
// 子进程会把跑着命令的项目判成空闲
|
|
3435
|
+
const arr = cliPidByCwd.get(cwd);
|
|
3436
|
+
if (arr) arr.push(pid); else cliPidByCwd.set(cwd, [pid]);
|
|
2866
3437
|
} catch { /* 进程退出/权限:跳过 */ }
|
|
2867
3438
|
}
|
|
2868
3439
|
const busy = new Set();
|
|
2869
|
-
for (const [cwd,
|
|
3440
|
+
for (const [cwd, cliPids] of cliPidByCwd) {
|
|
2870
3441
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
2871
3442
|
if (!wantedPaths) continue;
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2875
|
-
|
|
2876
|
-
const
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
2888
|
-
|
|
3443
|
+
for (const pid of cliPids) {
|
|
3444
|
+
let children = '';
|
|
3445
|
+
try { children = readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8'); }
|
|
3446
|
+
catch { continue; }
|
|
3447
|
+
for (const childPidStr of children.split(/\s+/)) {
|
|
3448
|
+
const childPid = Number(childPidStr);
|
|
3449
|
+
if (!Number.isFinite(childPid)) continue;
|
|
3450
|
+
let cmdline = '';
|
|
3451
|
+
let zombie = false;
|
|
3452
|
+
try {
|
|
3453
|
+
cmdline = normCmdline(readFileSync(`/proc/${childPid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim());
|
|
3454
|
+
const stat = readFileSync(`/proc/${childPid}/stat`, 'utf8');
|
|
3455
|
+
zombie = /\) Z /.test(stat);
|
|
3456
|
+
} catch { continue; }
|
|
3457
|
+
if (zombie) continue;
|
|
3458
|
+
if (!cmdline || !isInfraCmdline(cmdline)) {
|
|
3459
|
+
for (const wp of wantedPaths) busy.add(wp); // 认不出的进程宁可误判为忙,也不回收可能在跑命令的项目
|
|
3460
|
+
break;
|
|
3461
|
+
}
|
|
2889
3462
|
}
|
|
2890
3463
|
}
|
|
2891
3464
|
}
|
|
@@ -2916,8 +3489,11 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
2916
3489
|
const busy = new Set();
|
|
2917
3490
|
for (const cli of clis) {
|
|
2918
3491
|
const lsof = await runCmd('lsof', ['-a', '-p', String(cli.pid), '-d', 'cwd', '-Fn', '-w']);
|
|
3492
|
+
// 与注释的约定一致:任一 CLI 的工作目录取不到就整轮放弃(scan=false)——
|
|
3493
|
+
// lsof 缺失/被限权/进程行取不到 cwd 时都不能把项目判成空闲
|
|
3494
|
+
if (lsof.err) return SCAN_OFF;
|
|
2919
3495
|
const cwd = (lsof.stdout.match(/^n(.+)$/m) || [])[1];
|
|
2920
|
-
if (!cwd)
|
|
3496
|
+
if (!cwd) return SCAN_OFF;
|
|
2921
3497
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
2922
3498
|
if (!wantedPaths) continue;
|
|
2923
3499
|
for (const child of procs) {
|
|
@@ -2937,8 +3513,10 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
2937
3513
|
// 查任务索引反查工作区;认不出且无会话 ID 的活动子进程无法归属 → 全部请求判忙(保守)。
|
|
2938
3514
|
// 路径比较忽略大小写与分隔符差异
|
|
2939
3515
|
async function scanIdleBusyWindows(paths, dataRoot) {
|
|
3516
|
+
// 输出编码固定 UTF-8(同 pickFolder.mjs):默认走 OEM 代码页(中文系统 936),
|
|
3517
|
+
// 按 UTF-8 解码不只乱码,GBK 尾字节 0x5C 还会被当转义符让 JSON.parse 抛错
|
|
2940
3518
|
const ps = await runCmd('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
|
2941
|
-
'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress'], 30000);
|
|
3519
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress'], 30000);
|
|
2942
3520
|
if (ps.err || !ps.stdout.trim()) return SCAN_OFF;
|
|
2943
3521
|
let list;
|
|
2944
3522
|
try {
|
|
@@ -2984,9 +3562,11 @@ export async function classifyIdleBusyWindows(procs, paths, lookupTaskWs) {
|
|
|
2984
3562
|
if (child.ppid !== cli.pid) continue;
|
|
2985
3563
|
if (isInfraCmdline(child.cmdline)) continue;
|
|
2986
3564
|
if (!child.cmdline) { unattributed = true; continue; }
|
|
2987
|
-
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_
|
|
2988
|
-
//
|
|
2989
|
-
|
|
3565
|
+
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_);字符集与
|
|
3566
|
+
// 路由校验的 id 白名单一致(含 . 和 _)——字符类偏窄会在这些字符处截断成
|
|
3567
|
+
// 前缀,撞上别的真实 task_id 会把错误项目判忙。匹配不到会走 unattributed
|
|
3568
|
+
// 全量判忙——新形式命令挂着时空闲回收会整体停摆
|
|
3569
|
+
const sess = child.cmdline.match(/(?:sess|session)_[A-Za-z0-9._-]+/);
|
|
2990
3570
|
if (sess) await markByTask(sess[0]);
|
|
2991
3571
|
else unattributed = true; // 用户进程但无会话线索:归属不到具体项目
|
|
2992
3572
|
}
|
|
@@ -3080,7 +3660,7 @@ const TITLE_GEN_DEFAULT_PROMPTS = {
|
|
|
3080
3660
|
// 界面语言:桌面设置(v2/setting.json 的 localePreference)为 en-US / zh-CN 时
|
|
3081
3661
|
// 直接采用;system 或未设置时按系统环境语言判断(中文环境 → 中文,其余 → 英文)
|
|
3082
3662
|
function titleGenLocale() {
|
|
3083
|
-
const s = readJsonFile(join(
|
|
3663
|
+
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移(同 startHelper 的 settingsFile)
|
|
3084
3664
|
const pref = String((s && s.localePreference) || '').toLowerCase();
|
|
3085
3665
|
if (pref.startsWith('en')) return 'en';
|
|
3086
3666
|
if (pref.startsWith('zh')) return 'zh';
|
|
@@ -3102,7 +3682,7 @@ const TITLE_GEN_TIMEOUT_MS = 60000; // 单次模型调用超时(与官方起
|
|
|
3102
3682
|
// providerFamilyConnectionSelections)读当前登录的连接方式(kind 含
|
|
3103
3683
|
// individual → 个人、team → 团队),读不到时退回“个人/团队”
|
|
3104
3684
|
function codingPlanKindByFamily() {
|
|
3105
|
-
const s = readJsonFile(join(
|
|
3685
|
+
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移
|
|
3106
3686
|
const sel = (s && s.providerFamilyConnectionSelections && typeof s.providerFamilyConnectionSelections === 'object')
|
|
3107
3687
|
? s.providerFamilyConnectionSelections : {};
|
|
3108
3688
|
const out = {};
|
|
@@ -3152,7 +3732,7 @@ export function listTitleGenProviders() {
|
|
|
3152
3732
|
const byId = new Map();
|
|
3153
3733
|
const planKinds = codingPlanKindByFamily();
|
|
3154
3734
|
// 注册表读一次,供下方各条目的协议判定兜底复用(文件不存在时为空数组)
|
|
3155
|
-
const headroomProviders = (readJsonFile(
|
|
3735
|
+
const headroomProviders = (readJsonFile(defaultHeadroomFile()) || {}).providers || [];
|
|
3156
3736
|
const add = (id, { name, aliases = [], kind, baseUrl, apiKey, models = [] }) => {
|
|
3157
3737
|
baseUrl = typeof baseUrl === 'string' ? baseUrl.trim() : '';
|
|
3158
3738
|
apiKey = typeof apiKey === 'string' ? apiKey.trim() : '';
|
|
@@ -3178,9 +3758,9 @@ export function listTitleGenProviders() {
|
|
|
3178
3758
|
out.push(entry);
|
|
3179
3759
|
};
|
|
3180
3760
|
|
|
3181
|
-
const v2 = readJsonFile(join(
|
|
3761
|
+
const v2 = readJsonFile(join(resolveDataRootDir(), 'v2', 'config.json')); // 官方 v2 配置跟数据根迁移
|
|
3182
3762
|
const providers = (v2 && typeof v2.provider === 'object' && v2.provider) || {};
|
|
3183
|
-
const rulesDoc = readJsonFile(join(
|
|
3763
|
+
const rulesDoc = readJsonFile(join(resolveDataRootDir(), 'v2', 'provider_config.json'));
|
|
3184
3764
|
const rules = (rulesDoc && rulesDoc.config?.providerConfigRules?.providerRules) || [];
|
|
3185
3765
|
const ruleById = new Map(rules.filter((r) => r && typeof r.providerId === 'string').map((r) => [r.providerId, r]));
|
|
3186
3766
|
// 同一 id 在两张表的字段并起来(provider 表优先:地址/密钥以桌面实际在用的为准)
|
|
@@ -3261,6 +3841,64 @@ async function callOpenAiText(baseUrl, apiKey, model, content) {
|
|
|
3261
3841
|
} finally { clearTimeout(timer); }
|
|
3262
3842
|
}
|
|
3263
3843
|
|
|
3844
|
+
// 生成标题的双写收尾,顺序不能反:先写 CLI 会话库(title_source=custom,权威层
|
|
3845
|
+
// ——官方自动起名看到 custom 会放弃,桌面同步器会把 custom 标题带着 overridden=1
|
|
3846
|
+
// 送回任务索引),再写任务索引(展示层,立即上屏)。只写任务索引时,官方运行时
|
|
3847
|
+
// 排队的自动标题会在几秒后把它覆盖(实测)。CLI 库不可写(旧版无 title_source
|
|
3848
|
+
// 列 / 无该会话行)不阻断:退回单写任务索引的旧行为;任务索引随后失败也不回滚
|
|
3849
|
+
// CLI——同步器会补。写库撞上宿主写入时稍候重试(起名不急这几秒)。
|
|
3850
|
+
// force = 手动“自动重命名”:已重命名的会话也照写(用户显式改名)。
|
|
3851
|
+
// 返回 { written, store, error }:store '' 成功 | skipped 原因 | 'error…';
|
|
3852
|
+
// error 非空 = 任务索引最终没写成(err 带 code,由调用方转 500)。
|
|
3853
|
+
// CLI 库写成功才登记回查记录(reconcileCustomTitles 只认这些记录校正),
|
|
3854
|
+
// 登记只是回查簿记,失败不影响改名结果。导出以便测试
|
|
3855
|
+
export async function writeGeneratedTitle(dataRoot, configFile, sessId, title, { force = false } = {}) {
|
|
3856
|
+
let written = false;
|
|
3857
|
+
let store = ''; // CLI 会话库写入结果:'' 成功 | skipped 原因 | 'error…'
|
|
3858
|
+
for (let attempt = 0; ; attempt++) {
|
|
3859
|
+
try {
|
|
3860
|
+
const r = await setCustomSessionTitle(dataRoot, sessId, title);
|
|
3861
|
+
store = r.written ? '' : (r.skipped || 'skipped');
|
|
3862
|
+
break;
|
|
3863
|
+
} catch (err) {
|
|
3864
|
+
if (err.code === 'index-busy' && attempt < 2) {
|
|
3865
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
3866
|
+
continue;
|
|
3867
|
+
}
|
|
3868
|
+
store = 'error: ' + (err?.message || err);
|
|
3869
|
+
titleGenLog(dataRoot, `cli-store-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3870
|
+
break;
|
|
3871
|
+
}
|
|
3872
|
+
}
|
|
3873
|
+
for (let attempt = 0; ; attempt++) {
|
|
3874
|
+
try {
|
|
3875
|
+
const r = await setTaskTitleIfNotOverridden(dataRoot, sessId, title, { force });
|
|
3876
|
+
written = r.written;
|
|
3877
|
+
break;
|
|
3878
|
+
} catch (err) {
|
|
3879
|
+
if (err.code === 'index-busy' && attempt < 2) {
|
|
3880
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
3881
|
+
continue;
|
|
3882
|
+
}
|
|
3883
|
+
titleGenLog(dataRoot, `index-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3884
|
+
return { written, store, error: err };
|
|
3885
|
+
}
|
|
3886
|
+
}
|
|
3887
|
+
if (store === '') {
|
|
3888
|
+
// 跨进程锁内同步读改写,防止与别的写入方互相覆盖整份配置
|
|
3889
|
+
await withConfigLock(configFile, () => {
|
|
3890
|
+
try {
|
|
3891
|
+
const c = loadConfig(configFile);
|
|
3892
|
+
c.titleGen.customWritten = { ...(c.titleGen.customWritten || {}), [sessId]: { title, at: Date.now() } };
|
|
3893
|
+
if (!saveConfig(configFile, c)) throw new Error('zcodepro.json 损坏,写入被拒');
|
|
3894
|
+
} catch (err) {
|
|
3895
|
+
titleGenLog(dataRoot, `customWritten-save-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3896
|
+
}
|
|
3897
|
+
});
|
|
3898
|
+
}
|
|
3899
|
+
return { written, store };
|
|
3900
|
+
}
|
|
3901
|
+
|
|
3264
3902
|
// 生成标题。provider 三种取值:
|
|
3265
3903
|
// - 'session':跟随当前会话——从任务索引解析该会话正在用的供应商与模型
|
|
3266
3904
|
// (model 已填时用填写的),供应商需在可直连列表内;
|
|
@@ -3388,6 +4026,7 @@ export async function exchangeAccountProjectToken(family, dataRoot) {
|
|
|
3388
4026
|
const issueCtrl = new AbortController();
|
|
3389
4027
|
const issueTimer = setTimeout(() => issueCtrl.abort(), 20000);
|
|
3390
4028
|
let issueResp;
|
|
4029
|
+
let issue;
|
|
3391
4030
|
try {
|
|
3392
4031
|
issueResp = await fetch(`${origin}${keysUrl}/${encodeURIComponent(apiKeyId)}/access_tokens`, {
|
|
3393
4032
|
method: 'POST',
|
|
@@ -3395,8 +4034,9 @@ export async function exchangeAccountProjectToken(family, dataRoot) {
|
|
|
3395
4034
|
headers: { 'content-type': 'application/json', authorization: `Bearer ${loginToken}` },
|
|
3396
4035
|
body: JSON.stringify({ clientType: 'zcode', clientVersion: VERSION }),
|
|
3397
4036
|
});
|
|
4037
|
+
// 响应体读取也放超时保护内(与 api() 同款):管理接口回完头拖着不发体会永久挂起
|
|
4038
|
+
issue = await issueResp.json().catch(() => null);
|
|
3398
4039
|
} finally { clearTimeout(issueTimer); }
|
|
3399
|
-
const issue = await issueResp.json().catch(() => null);
|
|
3400
4040
|
const issueData = (issue && [200, 0, '200', '0'].includes(issue.code)) ? issue.data : null;
|
|
3401
4041
|
if (!issueData) throw new Error(`签发项目 token 失败(${issueResp.status})`);
|
|
3402
4042
|
// enable 语义与官方一致:旧版接口不回该字段(实测回的是同义的 enabled),
|
|
@@ -3511,7 +4151,9 @@ export function validateVisionConfig(raw) {
|
|
|
3511
4151
|
if (!Array.isArray(raw.chain) || raw.chain.some((n) => typeof n !== 'string')) return [null, 'chain 必须是代理名数组'];
|
|
3512
4152
|
if (!Array.isArray(raw.proxies)) return [null, 'proxies 必须是数组'];
|
|
3513
4153
|
const cfg = {
|
|
3514
|
-
|
|
4154
|
+
// enabled 同 cardUi:显式给值才写键,缺省保持磁盘原值(否则磁盘上显式
|
|
4155
|
+
// false 会被一次省略 enabled 的保存覆盖回 true)
|
|
4156
|
+
...(raw.enabled !== undefined ? { enabled: raw.enabled !== false } : {}),
|
|
3515
4157
|
chainMode: raw.chainMode,
|
|
3516
4158
|
chain: raw.chain.map((s) => s.trim()).filter(Boolean),
|
|
3517
4159
|
proxies: [],
|
|
@@ -3614,8 +4256,10 @@ export function validateRtkWhitelist(raw) {
|
|
|
3614
4256
|
// (钩子视为未自定义);文件头带注释说明格式,方便用户直接编辑。
|
|
3615
4257
|
function writeRtkState(dir, { mode, whitelist }) {
|
|
3616
4258
|
mkdirSync(dir, { recursive: true });
|
|
4259
|
+
// 临时名带 pid+随机:钩子进程与面板并发写这两个文件时不共用一个 .tmp
|
|
4260
|
+
const pidTmp = (f) => `${f}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
3617
4261
|
const modeFile = join(dir, 'mode');
|
|
3618
|
-
const tmp = modeFile
|
|
4262
|
+
const tmp = pidTmp(modeFile);
|
|
3619
4263
|
writeFileSync(tmp, mode, 'utf8');
|
|
3620
4264
|
renameSync(tmp, modeFile);
|
|
3621
4265
|
const wlFile = join(dir, 'whitelist');
|
|
@@ -3623,7 +4267,7 @@ function writeRtkState(dir, { mode, whitelist }) {
|
|
|
3623
4267
|
try { unlinkSync(wlFile); } catch { /* 不存在即目标状态 */ }
|
|
3624
4268
|
return;
|
|
3625
4269
|
}
|
|
3626
|
-
const wlTmp = wlFile
|
|
4270
|
+
const wlTmp = pidTmp(wlFile);
|
|
3627
4271
|
writeFileSync(wlTmp, '# rtk 白名单(不压缩直接放行):每行 name 或 git:name(git 子命令)。删除本文件即恢复默认。\n'
|
|
3628
4272
|
+ whitelist.join('\n') + '\n', 'utf8');
|
|
3629
4273
|
renameSync(wlTmp, wlFile);
|
|
@@ -3746,16 +4390,20 @@ function startRtkUpgrade() {
|
|
|
3746
4390
|
j.output += `下载 ${info.assetName}…\n`;
|
|
3747
4391
|
const archPath = join(dir, info.assetName);
|
|
3748
4392
|
await downloadToFile(j, info.assetUrl, archPath, 600000);
|
|
3749
|
-
// sha256 校验(checksums.txt
|
|
3750
|
-
|
|
4393
|
+
// sha256 校验(checksums.txt 与本机摘要工具;失败即中止,不替换)。
|
|
4394
|
+
// Release 没有 checksums.txt:无从校验,直接中止升级,绝不替换未经校验的二进制
|
|
4395
|
+
if (!info.sumsUrl) throw new Error('Release 缺少 checksums.txt,无法校验下载文件,已中止升级');
|
|
4396
|
+
{
|
|
3751
4397
|
const sumPath = join(dir, 'checksums.txt');
|
|
3752
4398
|
await downloadToFile(j, info.sumsUrl, sumPath, 30000);
|
|
3753
4399
|
const want = readFileSync(sumPath, 'utf8').split('\n')
|
|
3754
4400
|
.find((l) => l.trim().endsWith(info.assetName))?.trim().split(/\s+/)[0];
|
|
3755
4401
|
let got = '';
|
|
3756
4402
|
if (WIN) {
|
|
4403
|
+
// 路径包进单引号(内部 ' 写成 ''):双引号里 $、反引号会被当变量/子表达式求值
|
|
4404
|
+
const safeArch = String(archPath).replace(/'/g, "''");
|
|
3757
4405
|
const local = await execCapture('powershell.exe',
|
|
3758
|
-
['-NoProfile', '-Command', `(Get-FileHash -Algorithm SHA256 -LiteralPath
|
|
4406
|
+
['-NoProfile', '-Command', `(Get-FileHash -Algorithm SHA256 -LiteralPath '${safeArch}').Hash`], 60000);
|
|
3759
4407
|
got = (/[0-9a-fA-F]{64}/.exec(local.output || '') || [''])[0];
|
|
3760
4408
|
} else {
|
|
3761
4409
|
const sumCmd = process.platform === 'darwin' ? 'shasum' : 'sha256sum';
|
|
@@ -3783,6 +4431,9 @@ function startRtkUpgrade() {
|
|
|
3783
4431
|
if (!WIN) chmodSync(newBin, 0o755);
|
|
3784
4432
|
const v = await binVersionOf(newBin);
|
|
3785
4433
|
if (!v) throw new Error('新版本无法运行(--version 无输出)');
|
|
4434
|
+
// 试运行有约 10 秒窗口:期间被取消就别再替换二进制(否则状态显示
|
|
4435
|
+
// 已取消又显示升级成功,自相矛盾)
|
|
4436
|
+
if (j.canceled) throw new Error('canceled');
|
|
3786
4437
|
// 放置:全新安装建目录直接放;已有旧文件则原子替换(先挪走,失败可回滚)
|
|
3787
4438
|
if (freshInstall) mkdirSync(dirname(bin), { recursive: true });
|
|
3788
4439
|
const backup = bin + '.rtk-old';
|
|
@@ -3825,20 +4476,39 @@ function startRtkUpgrade() {
|
|
|
3825
4476
|
// 把目录追加进用户级 PATH(HKCU\Environment,Windows):保持原值类型不展开(REG_EXPAND_SZ
|
|
3826
4477
|
// 里的 %VAR% 引用原样保留),已含该目录则不动。不广播环境变更——运行中的进程读不到,
|
|
3827
4478
|
// 重启 ZCode 后新会话生效(rtk 钩子按固定清单找 rtk,不受 PATH 影响)。
|
|
4479
|
+
// 注册表读写走 PowerShell 而不是 reg.exe:reg 的输出按系统代码页编码(中文 Windows
|
|
4480
|
+
// 是 GBK),Node 按 UTF-8 解码会把中文条目弄乱,原样写回就把用户 PATH 写坏了;
|
|
4481
|
+
// PowerShell 经 .NET 读写值本身不做编码转换,只有控制台输出要固定 UTF-8(同 pickFolder.mjs)。
|
|
3828
4482
|
async function ensureUserPathEntry(dir) {
|
|
3829
|
-
const
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
4483
|
+
const psRead = [
|
|
4484
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
|
|
4485
|
+
"$k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)",
|
|
4486
|
+
"if ($null -eq $k -or -not ($k.GetValueNames() -contains 'PATH')) { exit 2 }",
|
|
4487
|
+
"$v = $k.GetValue('PATH', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)",
|
|
4488
|
+
"[Console]::Out.Write([string]($k.GetValueKind('PATH')) + [char]10 + [string]$v)",
|
|
4489
|
+
].join('; ');
|
|
4490
|
+
const q = await execCapture('powershell.exe', ['-NoProfile', '-Command', psRead], 15000);
|
|
4491
|
+
// 值缺失才新建;读取本身出错一律不动用户 PATH(不能把整份值覆盖没了)
|
|
4492
|
+
let kind = 'String';
|
|
4493
|
+
let next = dir; // 缺失分支写调用方给的目录,别写死别的路径
|
|
4494
|
+
if (q.code !== 2) {
|
|
4495
|
+
if (!q.ok) return false;
|
|
4496
|
+
const nl = q.output.indexOf('\n');
|
|
4497
|
+
const curKind = (nl < 0 ? q.output : q.output.slice(0, nl)).trim();
|
|
4498
|
+
if (curKind !== 'String' && curKind !== 'ExpandString') return false; // REG_SZ/REG_EXPAND_SZ 之外的类型不认识,不动它
|
|
4499
|
+
const cur = (nl < 0 ? '' : q.output.slice(nl + 1)).trim();
|
|
4500
|
+
const norm = (s) => s.replace(/[/\\]+/g, '\\').replace(/\\+$/, '').toLowerCase();
|
|
4501
|
+
const expanded = cur.replaceAll('%USERPROFILE%', homedir());
|
|
4502
|
+
if (expanded.split(';').some((p) => p && norm(p) === norm(dir))) return true;
|
|
4503
|
+
kind = curKind;
|
|
4504
|
+
next = cur ? `${cur};${dir}` : dir;
|
|
3833
4505
|
}
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
const next = cur ? `${cur};${dir}` : dir;
|
|
3841
|
-
const r = await execCapture('reg', ['add', 'HKCU\\Environment', '/v', 'PATH', '/t', m[1], '/d', next, '/f'], 15000);
|
|
4506
|
+
// 值包进单引号(内部 ' 写成 ''):$、反引号、$( ) 都不会被当变量/子表达式求值
|
|
4507
|
+
const psWrite = [
|
|
4508
|
+
"$k = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')",
|
|
4509
|
+
`$k.SetValue('PATH', '${next.replace(/'/g, "''")}', [Microsoft.Win32.RegistryValueKind]::${kind})`,
|
|
4510
|
+
].join('; ');
|
|
4511
|
+
const r = await execCapture('powershell.exe', ['-NoProfile', '-Command', psWrite], 15000);
|
|
3842
4512
|
return r.ok;
|
|
3843
4513
|
}
|
|
3844
4514
|
|
|
@@ -3893,8 +4563,8 @@ export function writeHeadroomConfig(file, cfg) {
|
|
|
3893
4563
|
for (const k of ['kompressBackend', 'powerSaveCpu', 'powerWatchInterval']) {
|
|
3894
4564
|
if (cfg[k] !== undefined) out[k] = cfg[k];
|
|
3895
4565
|
}
|
|
3896
|
-
const tmp = file
|
|
3897
|
-
writeFileSync(tmp, JSON.stringify(out, null, 2) + '\n', 'utf8');
|
|
4566
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4567
|
+
writeFileSync(tmp, JSON.stringify(out, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 }); // 配置含供应商凭据,限制本人读写
|
|
3898
4568
|
renameSync(tmp, file);
|
|
3899
4569
|
}
|
|
3900
4570
|
|
|
@@ -3998,18 +4668,31 @@ async function downloadToFile(j, url, dest, timeoutMs = 600000) {
|
|
|
3998
4668
|
if (!res.ok || !res.body) throw new Error(`下载失败 HTTP ${res.status}`);
|
|
3999
4669
|
const total = Number(res.headers.get('content-length')) || 0;
|
|
4000
4670
|
const out = createWriteStream(dest);
|
|
4671
|
+
// 写盘错误必须有人接(磁盘满/杀软锁文件):无人订阅的 error 事件直接崩进程,
|
|
4672
|
+
// 挂在 drain 等待上时还会永久不返回、升级任务卡死
|
|
4673
|
+
let outErr = null;
|
|
4674
|
+
out.on('error', (e) => { outErr = e; });
|
|
4001
4675
|
let got = 0;
|
|
4002
4676
|
let lastPct = -1;
|
|
4003
4677
|
try {
|
|
4004
4678
|
for await (const chunk of res.body) {
|
|
4005
4679
|
if (j.canceled) throw new Error('canceled');
|
|
4006
|
-
if (
|
|
4680
|
+
if (outErr) throw outErr;
|
|
4681
|
+
if (!out.write(chunk)) {
|
|
4682
|
+
await new Promise((r) => {
|
|
4683
|
+
const done = () => { out.off('drain', done); out.off('error', done); r(); };
|
|
4684
|
+
out.once('drain', done);
|
|
4685
|
+
out.once('error', done); // 出错也解除等待,别永久挂起
|
|
4686
|
+
});
|
|
4687
|
+
if (outErr) throw outErr;
|
|
4688
|
+
}
|
|
4007
4689
|
got += chunk.length;
|
|
4008
4690
|
if (total > 0) {
|
|
4009
4691
|
const pct = Math.floor((got / total) * 100);
|
|
4010
4692
|
if (pct >= lastPct + 5) { lastPct = pct; j.output += `下载中 ${pct}%\n`; }
|
|
4011
4693
|
}
|
|
4012
4694
|
}
|
|
4695
|
+
if (outErr) throw outErr;
|
|
4013
4696
|
await new Promise((resolve, reject) => { out.end(resolve); out.once('error', reject); });
|
|
4014
4697
|
} catch (err) {
|
|
4015
4698
|
try { out.destroy(); } catch { /* ignore */ }
|
|
@@ -4206,10 +4889,10 @@ async function runHeadroomHook(args, timeoutMs = 30000) {
|
|
|
4206
4889
|
// 旧版 headroom 插件的钩子只匹配 startup,代理不会自动启动(要等用户新建会话或
|
|
4207
4890
|
// 手动重启)。helper 就绪后延迟几秒补一次 ensure:动作幂等(已在跑秒回),新版
|
|
4208
4891
|
// 插件侧还带跨进程锁;失败一律静默——没装 headroom 插件/本体的环境不能打扰启动。
|
|
4209
|
-
|
|
4210
|
-
|
|
4211
|
-
if (
|
|
4212
|
-
|
|
4892
|
+
function ensureHeadroomAtStartup(state = {}) {
|
|
4893
|
+
// 标志挂 state(跨热替换实例共享):放模块级时每次热替换都重置,兜底 ensure 会重复排队
|
|
4894
|
+
if (state.headroomEnsureFired) return;
|
|
4895
|
+
state.headroomEnsureFired = true;
|
|
4213
4896
|
const timer = setTimeout(() => {
|
|
4214
4897
|
runHeadroomHook(['ensure'], 20000).catch(() => { /* 兜底失败不影响启动 */ });
|
|
4215
4898
|
}, 5000);
|
|
@@ -4259,6 +4942,54 @@ export function parseHeadroomStatus(text) {
|
|
|
4259
4942
|
const HEADROOM_DIRECT_URL = 'https://open.bigmodel.cn/api/anthropic';
|
|
4260
4943
|
const HEADROOM_LOCAL_URL_RE = /^http:\/\/127\.0\.0\.1:\d+\/?$/;
|
|
4261
4944
|
|
|
4945
|
+
// —— Serena(语义代码分析 MCP):headroom 标签页的启用开关 ——
|
|
4946
|
+
// 开关写 ~/.zcode/cli/config.json 的 mcp.servers.serena,ZCode 新会话启动时加载,
|
|
4947
|
+
// 会话内即可用 find_symbol / find_referencing_symbols 等语义检索代替整文件读取。
|
|
4948
|
+
// 默认关闭:配置里没有 serena 条目就是关闭,不再另设布尔键。
|
|
4949
|
+
// 启动参数取 headroom 的 serena 集成:PyPI serena-agent 预编译 wheel(git 源码构建
|
|
4950
|
+
// 在部分文件系统下失败),--open-web-dashboard False 免得每次启动弹浏览器面板。
|
|
4951
|
+
// --project . 把项目根钉在工作区(MCP 启动时的 cwd),不往上找 .git/.serena:谁的
|
|
4952
|
+
// home 有没有假项目都不影响(--project-from-cwd 往上撞到 home 的 .git 就把整个 home
|
|
4953
|
+
// 当项目,各人 home 不同、没法逐台清);多仓库/多工作区父目录则由 agent 调
|
|
4954
|
+
// activate_project 挑具体那个。
|
|
4955
|
+
const SERENA_ARGS = ['--from', 'serena-agent', 'serena', 'start-mcp-server',
|
|
4956
|
+
'--project', '.', '--context', 'ide-assistant', '--open-web-dashboard', 'False'];
|
|
4957
|
+
|
|
4958
|
+
function serenaServerSpec() {
|
|
4959
|
+
// ZCode 拉起 MCP 时的 PATH 不一定含 ~/.local/bin,uvx 写绝对路径兜底(同 mastergo 的 npx)
|
|
4960
|
+
const uvx = findBinFile(['uvx'], [join(homedir(), '.local', 'bin', 'uvx'), '/usr/local/bin/uvx', '/usr/bin/uvx'])
|
|
4961
|
+
|| 'uvx';
|
|
4962
|
+
return { type: 'stdio', command: uvx, args: SERENA_ARGS, timeoutMs: 60000 };
|
|
4963
|
+
}
|
|
4964
|
+
|
|
4965
|
+
export function serenaScan() {
|
|
4966
|
+
// cli/config.json 固定按主目录定位(同 /zcode-config),不跟 ZCODE_DATA_BASE_DIR 迁移
|
|
4967
|
+
const cfg = readZcodeConfig(join(zcodeDataRoot(), 'cli', 'config.json'));
|
|
4968
|
+
return { enabled: !!(cfg.mcp && cfg.mcp.servers && cfg.mcp.servers.serena) };
|
|
4969
|
+
}
|
|
4970
|
+
|
|
4971
|
+
// 切换 Serena:enable=true 写入 mcp.servers.serena,false 删掉该键。
|
|
4972
|
+
// 只动 serena 一个键,其它 MCP(如 mastergo)原样保留。
|
|
4973
|
+
export function setSerenaEnabled(enable) {
|
|
4974
|
+
const file = join(zcodeDataRoot(), 'cli', 'config.json');
|
|
4975
|
+
let cfg;
|
|
4976
|
+
try {
|
|
4977
|
+
cfg = JSON.parse(readFileSync(file, 'utf8'));
|
|
4978
|
+
} catch {
|
|
4979
|
+
// 文件存在但解析失败时拒绝写入:按空对象重写会把 provider 等配置清掉
|
|
4980
|
+
if (existsSync(file)) return { ok: false, code: 'serena-config-unreadable', error: 'ZCode 配置文件无法解析,已中止写入' };
|
|
4981
|
+
cfg = {};
|
|
4982
|
+
}
|
|
4983
|
+
const mcp = (cfg.mcp && typeof cfg.mcp === 'object' && !Array.isArray(cfg.mcp)) ? { ...cfg.mcp } : {};
|
|
4984
|
+
const servers = (mcp.servers && typeof mcp.servers === 'object' && !Array.isArray(mcp.servers)) ? { ...mcp.servers } : {};
|
|
4985
|
+
if (enable) servers.serena = serenaServerSpec();
|
|
4986
|
+
else delete servers.serena;
|
|
4987
|
+
mcp.servers = servers;
|
|
4988
|
+
cfg.mcp = mcp;
|
|
4989
|
+
writeJsonAtomic(file, cfg);
|
|
4990
|
+
return { ok: true, serena: serenaScan() };
|
|
4991
|
+
}
|
|
4992
|
+
|
|
4262
4993
|
// 扫描 v2/config.json(provider.<id>.options.baseURL)与 v2/provider_config.json
|
|
4263
4994
|
// (providerRules[].config.api.baseUrl),统计当前走本地代理的条目数
|
|
4264
4995
|
export function headroomUsageScan(dataRoot) {
|
|
@@ -4279,12 +5010,17 @@ export function headroomUsageScan(dataRoot) {
|
|
|
4279
5010
|
// 切换启用状态:enable=false 时 127.0.0.1 条目 → 直连(并记录);enable=true 时按
|
|
4280
5011
|
// 记录把直连条目切回代理。改写前各留 .zcodepro-backup 备份,与同步导入同款。
|
|
4281
5012
|
export function setHeadroomUsage(dataRoot, configFile, enable) {
|
|
5013
|
+
// 同步调用点用同步等锁变体:整段读改写在跨进程锁内完成,防止与别的写入方互相覆盖
|
|
5014
|
+
return withConfigLockSync(configFile, () => setHeadroomUsageLocked(dataRoot, configFile, enable));
|
|
5015
|
+
}
|
|
5016
|
+
|
|
5017
|
+
function setHeadroomUsageLocked(dataRoot, configFile, enable) {
|
|
4282
5018
|
const backupFile = (p) => {
|
|
4283
5019
|
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
4284
5020
|
};
|
|
4285
5021
|
const atomicWrite = (p, obj) => {
|
|
4286
|
-
const tmp = p
|
|
4287
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', 'utf8');
|
|
5022
|
+
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
5023
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
4288
5024
|
renameSync(tmp, p);
|
|
4289
5025
|
};
|
|
4290
5026
|
const v2File = join(dataRoot, 'v2', 'config.json');
|
|
@@ -4336,7 +5072,9 @@ export function setHeadroomUsage(dataRoot, configFile, enable) {
|
|
|
4336
5072
|
if (touched) { backupFile(pcFile); atomicWrite(pcFile, pc); }
|
|
4337
5073
|
}
|
|
4338
5074
|
config.headroomRoutes = routes;
|
|
4339
|
-
saveConfig(configFile, config)
|
|
5075
|
+
if (!saveConfig(configFile, config)) {
|
|
5076
|
+
return { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' };
|
|
5077
|
+
}
|
|
4340
5078
|
return { ok: true, changed };
|
|
4341
5079
|
}
|
|
4342
5080
|
|
|
@@ -4445,9 +5183,8 @@ export function pluginUpdateStatus() {
|
|
|
4445
5183
|
// 读 known_marketplaces.json 判断,缺失则跑 plugins marketplace add;add 退出后
|
|
4446
5184
|
// 验证登记结果,未登记则回退 git clone 到本地走目录源——node 26 下 CLI 的 GitHub
|
|
4447
5185
|
// 归档解包会挂死并以退出码 0 静默退出,add 看似成功、登记表却没写,不能只信退出码。
|
|
4448
|
-
//
|
|
4449
|
-
//
|
|
4450
|
-
let lastMarketplaceAddFail = 0;
|
|
5186
|
+
// 不做失败冷却:用户可能刚配好代理就要重试,限制次数只会让人以为一直装不上。
|
|
5187
|
+
// 返回 null = 已存在无需处理,{ ok } = 本次执行结果。
|
|
4451
5188
|
|
|
4452
5189
|
// 目录源回退的 git 克隆位置(sources/ 对 CLI 是无关目录,不干扰它自己的缓存布局)
|
|
4453
5190
|
function zcodePluginsSourceDir() {
|
|
@@ -4494,23 +5231,66 @@ async function addZcodePluginsMarketplaceFromClone() {
|
|
|
4494
5231
|
return runZcodeCli(['plugins', 'marketplace', 'add', zcodePluginsSourceDir()], 120000);
|
|
4495
5232
|
}
|
|
4496
5233
|
|
|
5234
|
+
// 市场添加失败的分类与提示:新机器常见两类原因——没装 Git、连不上 GitHub。
|
|
5235
|
+
// 提示放最前:toast 是单行截断,放末尾会被长长的命令错误挤掉;独立的 code 让
|
|
5236
|
+
// 英文界面也能显示对应说明(errText 对已登录的错误码用 errEn 文案)。
|
|
5237
|
+
export function marketplaceAddFailure(raw) {
|
|
5238
|
+
const text = String(raw || '');
|
|
5239
|
+
if (/spawn git ENOENT/i.test(text)) {
|
|
5240
|
+
return { code: 'plugins-market-git', hint: '本机没有 Git,且直连 GitHub 失败;请安装 Git,或在 ZCode Pro 设置 → 代理 填写代理地址后重试。' };
|
|
5241
|
+
}
|
|
5242
|
+
if (/fetch failed|ENOTFOUND|ECONN|ETIMEDOUT|Failed to materialize|Failed to connect|Could not (?:connect|resolve)|unable to access/i.test(text)) {
|
|
5243
|
+
return { code: 'plugins-market-network', hint: '当前网络访问不了 GitHub;如需要代理,请在 ZCode Pro 设置 → 代理 填写代理地址后重试。' };
|
|
5244
|
+
}
|
|
5245
|
+
return { code: '', hint: '' };
|
|
5246
|
+
}
|
|
5247
|
+
|
|
4497
5248
|
export async function ensureZcodePluginsMarketplace() {
|
|
4498
5249
|
if (zcodePluginsMarketplaceRegistered()) return null;
|
|
4499
|
-
if (Date.now() - lastMarketplaceAddFail < 30 * 60 * 1000) return { ok: false, cached: true, error: '上次添加市场失败,30 分钟内不再自动重试' };
|
|
4500
5250
|
let r = await runZcodeCli(['plugins', 'marketplace', 'add', ZCODE_PLUGINS_MARKETPLACE_SOURCE], 120000);
|
|
4501
5251
|
if (!zcodePluginsMarketplaceRegistered()) r = await addZcodePluginsMarketplaceFromClone();
|
|
4502
5252
|
const ok = r.ok && zcodePluginsMarketplaceRegistered();
|
|
4503
|
-
|
|
4504
|
-
return { ok, output: r.output, error:
|
|
5253
|
+
const raw = r.error || 'marketplace add 未生效:登记表里没有该市场';
|
|
5254
|
+
if (ok) return { ok, output: r.output, error: raw };
|
|
5255
|
+
const failure = marketplaceAddFailure(raw);
|
|
5256
|
+
const detail = raw.length > 300 ? `${raw.slice(0, 300)}…` : raw;
|
|
5257
|
+
return {
|
|
5258
|
+
ok,
|
|
5259
|
+
output: r.output,
|
|
5260
|
+
code: failure.code || undefined,
|
|
5261
|
+
error: failure.hint ? `${failure.hint} ${detail}` : detail,
|
|
5262
|
+
};
|
|
4505
5263
|
}
|
|
4506
5264
|
|
|
4507
5265
|
// /plugins/update 并发控制:启动自动更新、打开设置弹窗时的自动触发、手动按钮、
|
|
4508
5266
|
// 各插件面板的单插件操作都打到这个端点,而 CLI 同时改同一个插件目录会互相破坏。
|
|
4509
|
-
//
|
|
4510
|
-
//
|
|
4511
|
-
let
|
|
5267
|
+
// 按目标键(全量 = 空键,或同一插件名)去重:同目标的并发请求共用同一次执行结果,
|
|
5268
|
+
// 不同目标各占一个槽位互不顶掉、排队串行,后到的等前一个结束再跑
|
|
5269
|
+
let pluginsUpdateJobs = new Map(); // only 键 → 在跑或排队的任务 promise
|
|
5270
|
+
// 一般后台任务在途标志(市场克隆/刷新、WebDAV 同步):排队 + 执行期间 +1,跑完 -1
|
|
5271
|
+
let busyBackground = 0;
|
|
5272
|
+
// 后台任务占用标志:启动器热替换前查询,有任务在跑就延后换——新模块实例
|
|
5273
|
+
// 不继承任务锁,立刻换会跟旧实例拉起的子进程(插件更新/同步/转码等)并发互删中间文件。
|
|
5274
|
+
// 升级任务对象完成后变量不置回 null(只把 running 置 false),必须看 running
|
|
5275
|
+
export function busyJobs() {
|
|
5276
|
+
return !!(pluginsUpdateJobs.size || busyBackground || (headroomUpgradeJob && headroomUpgradeJob.running) || (rtkUpgradeJob && rtkUpgradeJob.running) || transcodeJobs.size);
|
|
5277
|
+
}
|
|
4512
5278
|
let pluginsUpdateQueue = Promise.resolve();
|
|
4513
5279
|
|
|
5280
|
+
// 任务在途(排队 + 执行)期间计入忙碌标志,跑完清掉,热替换据此延后
|
|
5281
|
+
function trackBusy(promise) {
|
|
5282
|
+
busyBackground += 1;
|
|
5283
|
+
promise.then(() => { busyBackground -= 1; }, () => { busyBackground -= 1; });
|
|
5284
|
+
return promise;
|
|
5285
|
+
}
|
|
5286
|
+
|
|
5287
|
+
// 把一步市场操作排进串行队列(状态页的节流同步用):与更新任务互斥执行
|
|
5288
|
+
function runPluginsQueued(fn) {
|
|
5289
|
+
const promise = pluginsUpdateQueue.then(() => fn());
|
|
5290
|
+
pluginsUpdateQueue = promise.then(() => undefined, () => undefined);
|
|
5291
|
+
return trackBusy(promise);
|
|
5292
|
+
}
|
|
5293
|
+
|
|
4514
5294
|
async function runPluginsUpdateJob(body) {
|
|
4515
5295
|
// name 指定时只处理该插件:已装且有更新则更新,未装则安装(各插件面板的单插件操作)
|
|
4516
5296
|
const only = typeof body?.name === 'string' && body.name.trim() ? body.name.trim() : null;
|
|
@@ -4519,7 +5299,7 @@ async function runPluginsUpdateJob(body) {
|
|
|
4519
5299
|
if (added) steps.push({ step: 'marketplace add', ok: added.ok, output: added.output || added.error });
|
|
4520
5300
|
if (added && !added.ok) {
|
|
4521
5301
|
// 市场没登记上时 update 必然报 Marketplace not found,别让它冒头顶掉真实错误
|
|
4522
|
-
return { status: 500, payload: { ok: false, code: 'plugins-update', error: added.error || added.output || 'marketplace add 失败', steps } };
|
|
5302
|
+
return { status: 500, payload: { ok: false, code: added.code || 'plugins-update', error: added.error || added.output || 'marketplace add 失败', steps } };
|
|
4523
5303
|
}
|
|
4524
5304
|
const pull = await ensureZcodePluginsCloneFresh();
|
|
4525
5305
|
const sync = await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
|
|
@@ -4555,18 +5335,21 @@ async function runPluginsUpdateJob(body) {
|
|
|
4555
5335
|
|
|
4556
5336
|
function enqueuePluginsUpdate(body) {
|
|
4557
5337
|
const only = typeof body?.name === 'string' && body.name.trim() ? body.name.trim() : null;
|
|
4558
|
-
|
|
5338
|
+
// 按 only 键去重:单个槽位会被后到的不同目标顶掉,被顶掉的任务随后会重复跑
|
|
5339
|
+
const key = only || '';
|
|
5340
|
+
const inflight = pluginsUpdateJobs.get(key);
|
|
5341
|
+
if (inflight) return inflight;
|
|
4559
5342
|
const prev = pluginsUpdateQueue;
|
|
4560
5343
|
const promise = (async () => {
|
|
4561
5344
|
await prev;
|
|
4562
5345
|
try {
|
|
4563
5346
|
return await runPluginsUpdateJob(body);
|
|
4564
5347
|
} finally {
|
|
4565
|
-
|
|
5348
|
+
pluginsUpdateJobs.delete(key); // 同键去重保证此刻槽里就是自己,不用再比对
|
|
4566
5349
|
}
|
|
4567
5350
|
})();
|
|
4568
5351
|
pluginsUpdateQueue = promise.then(() => undefined, () => undefined);
|
|
4569
|
-
|
|
5352
|
+
pluginsUpdateJobs.set(key, promise);
|
|
4570
5353
|
return promise;
|
|
4571
5354
|
}
|
|
4572
5355
|
|
|
@@ -4596,9 +5379,13 @@ export function writeAgents(body, agentsFile) {
|
|
|
4596
5379
|
} else if (empty) {
|
|
4597
5380
|
return [200, { ok: true, content: '' }];
|
|
4598
5381
|
}
|
|
4599
|
-
|
|
5382
|
+
// 改名目标取真实路径:直接 rename 到 agentsFile 会把符号链接本身替换成
|
|
5383
|
+
// 普通文件(dotfiles 管理的链接会丢)
|
|
5384
|
+
let real = agentsFile;
|
|
5385
|
+
try { real = realpathSync(agentsFile); } catch { /* 文件还不存在:直接写原路径 */ }
|
|
5386
|
+
const tmp = `${real}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4600
5387
|
writeFileSync(tmp, body.content, 'utf8');
|
|
4601
|
-
renameSync(tmp,
|
|
5388
|
+
renameSync(tmp, real);
|
|
4602
5389
|
} catch (err) {
|
|
4603
5390
|
return [500, { ok: false, code: 'agents-write', error: '写入 AGENTS.md 失败: ' + (err?.message || err) }];
|
|
4604
5391
|
}
|
|
@@ -4719,7 +5506,12 @@ export function openWithDefaultApp(rawPath) {
|
|
|
4719
5506
|
const child = spawn('rundll32.exe', ['url.dll,FileProtocolHandler', p], { detached: true, stdio: 'ignore', windowsHide: true });
|
|
4720
5507
|
child.on('spawn', () => finish(null));
|
|
4721
5508
|
child.on('error', () => {
|
|
4722
|
-
|
|
5509
|
+
// cmd 兜底里路径不能直接拼进命令行(%VAR% 会被展开改写命令结构):
|
|
5510
|
+
// 走环境变量传入,% 的展开是单遍、变量值不会被二次扫描
|
|
5511
|
+
const viaCmd = spawn('cmd.exe', ['/d /s /c start "" "%ZP_OPEN%"'], {
|
|
5512
|
+
env: { ...process.env, ZP_OPEN: p },
|
|
5513
|
+
windowsVerbatimArguments: true, detached: true, stdio: 'ignore', windowsHide: true,
|
|
5514
|
+
});
|
|
4723
5515
|
viaCmd.on('spawn', () => finish(null));
|
|
4724
5516
|
viaCmd.on('error', finish);
|
|
4725
5517
|
});
|
|
@@ -4729,7 +5521,7 @@ export function openWithDefaultApp(rawPath) {
|
|
|
4729
5521
|
|
|
4730
5522
|
// 设置/清除项目自定义别名(纯渲染层,不动磁盘与任何 ZCode 数据)。
|
|
4731
5523
|
// alias 传空字符串/null 即清除该项目条目。
|
|
4732
|
-
export function setAlias(body, configFile) {
|
|
5524
|
+
export async function setAlias(body, configFile) {
|
|
4733
5525
|
const raw = typeof body?.path === 'string' ? body.path.trim() : '';
|
|
4734
5526
|
// 先校验再 resolve:resolve 会把相对路径悄悄变绝对,绕过校验
|
|
4735
5527
|
if (!raw || !isAbsolute(raw)) return [400, { ok: false, error: '无效的项目路径' }];
|
|
@@ -4739,16 +5531,21 @@ export function setAlias(body, configFile) {
|
|
|
4739
5531
|
if (name.length > 100) return [400, { ok: false, error: '别名过长(最多 100 字符)', code: 'name-too-long' }];
|
|
4740
5532
|
if (/[\r\n\0]/.test(name)) return [400, { ok: false, error: '别名不能包含换行等控制字符', code: 'name-invalid-chars' }];
|
|
4741
5533
|
}
|
|
4742
|
-
|
|
4743
|
-
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
5534
|
+
// 读改写放进跨进程锁内同步执行,防止与别的写入方互相覆盖整份配置
|
|
5535
|
+
return withConfigLock(configFile, () => {
|
|
5536
|
+
const config = loadConfig(configFile);
|
|
5537
|
+
if (!config.aliases || typeof config.aliases !== 'object') config.aliases = {};
|
|
5538
|
+
if (name) config.aliases[path] = name;
|
|
5539
|
+
else delete config.aliases[path];
|
|
5540
|
+
try {
|
|
5541
|
+
if (!saveConfig(configFile, config)) {
|
|
5542
|
+
return [500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' }];
|
|
5543
|
+
}
|
|
5544
|
+
} catch (err) {
|
|
5545
|
+
return [500, { ok: false, code: 'config-save', error: '保存配置失败: ' + (err?.message || err) }];
|
|
5546
|
+
}
|
|
5547
|
+
return [200, { ok: true, path, alias: name, aliases: config.aliases }];
|
|
5548
|
+
});
|
|
4752
5549
|
}
|
|
4753
5550
|
|
|
4754
5551
|
function invalidProjectName(name) {
|
|
@@ -4796,11 +5593,11 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4796
5593
|
}
|
|
4797
5594
|
}
|
|
4798
5595
|
|
|
4799
|
-
// setting.json 路径引用同步(recentProjects / lastWorkspaceSession / webRemoteControl
|
|
5596
|
+
// setting.json 路径引用同步(recentProjects / lastWorkspaceSession / webRemoteControl…);
|
|
5597
|
+
// 写回前比对 mtime 的重算逻辑在 remapSettingsPathsAtomic 里
|
|
4800
5598
|
const settingsFile = join(dataRoot, 'v2', 'setting.json');
|
|
4801
5599
|
try {
|
|
4802
|
-
|
|
4803
|
-
writeSettingsAtomic(settingsFile, remapSettingsPaths(settings, oldPath, newPath));
|
|
5600
|
+
remapSettingsPathsAtomic(settingsFile, oldPath, newPath);
|
|
4804
5601
|
} catch (err) {
|
|
4805
5602
|
return [500, { ok: false, error: '更新 setting.json 失败: ' + (err?.message || err) }];
|
|
4806
5603
|
}
|
|
@@ -4811,8 +5608,7 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4811
5608
|
await remapTaskIndexPaths(dataRoot, oldPath, newPath);
|
|
4812
5609
|
} catch (err) {
|
|
4813
5610
|
try {
|
|
4814
|
-
|
|
4815
|
-
writeSettingsAtomic(settingsFile, remapSettingsPaths(cur, newPath, oldPath));
|
|
5611
|
+
remapSettingsPathsAtomic(settingsFile, newPath, oldPath);
|
|
4816
5612
|
} catch { /* 回滚失败:setting.json.zcodepro-backup 仍有兜底 */ }
|
|
4817
5613
|
return [500, {
|
|
4818
5614
|
ok: false,
|
|
@@ -4822,16 +5618,19 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4822
5618
|
}
|
|
4823
5619
|
}
|
|
4824
5620
|
|
|
4825
|
-
//
|
|
5621
|
+
// 别名随迁(仅渲染层数据,失败不影响结果);读改写放进跨进程锁内同步执行,
|
|
5622
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
4826
5623
|
try {
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
5624
|
+
await withConfigLock(join(dataRoot, 'zcodepro.json'), () => {
|
|
5625
|
+
const config = loadConfig(join(dataRoot, 'zcodepro.json'));
|
|
5626
|
+
const aliases = config.aliases || {};
|
|
5627
|
+
if (Object.prototype.hasOwnProperty.call(aliases, oldPath)) {
|
|
5628
|
+
const v = aliases[oldPath];
|
|
5629
|
+
delete aliases[oldPath];
|
|
5630
|
+
aliases[newPath] = v;
|
|
5631
|
+
saveConfig(join(dataRoot, 'zcodepro.json'), config);
|
|
5632
|
+
}
|
|
5633
|
+
});
|
|
4835
5634
|
} catch { /* ignore */ }
|
|
4836
5635
|
|
|
4837
5636
|
return [200, {
|