zcode-pro 1.5.1 → 1.6.2
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 +33 -21
- package/README.md +23 -13
- package/dist/inject.js +9803 -7820
- package/package.json +3 -2
- package/src/host/cdp.mjs +13 -3
- package/src/host/helper.mjs +1591 -495
- package/src/host/main.mjs +412 -26
- 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 +57 -18
- package/src/host/skill-stats.mjs +163 -0
- package/src/host/taskIndex.mjs +198 -66
- package/src/host/taskOrder.mjs +128 -57
- package/src/host/version.mjs +15 -7
- package/src/host/wallpaper.mjs +328 -0
- package/src/host/webdav.mjs +66 -10
- package/src/inject/core.js +300 -105
- package/src/inject/features/alias-migration.js +8 -4
- package/src/inject/features/alias.js +2 -2
- package/src/inject/features/auto-rename.js +166 -0
- package/src/inject/features/composer-provider.js +82 -63
- package/src/inject/features/copy-path.js +1 -1
- package/src/inject/features/file-menu.js +9 -3
- package/src/inject/features/idle-reclaim.js +31 -8
- package/src/inject/features/image-menu.js +2 -2
- package/src/inject/features/newtab-panels.js +13 -3
- package/src/inject/features/pinned-collapse.js +11 -3
- package/src/inject/features/plugin-card-retry.js +18 -8
- package/src/inject/features/project-menu.js +1 -1
- package/src/inject/features/relocate-dialog.js +2 -1
- package/src/inject/features/sandbox-reclaim.js +17 -1
- package/src/inject/features/session-link.js +200 -0
- package/src/inject/features/session-switch.js +61 -27
- package/src/inject/features/settings-dialog.js +544 -158
- package/src/inject/features/status-bar.js +126 -24
- package/src/inject/features/table-copy.js +18 -2
- package/src/inject/features/task-order.js +48 -14
- package/src/inject/features/theme.js +644 -99
- 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 +69 -29
- package/src/inject/features/ws-running.js +32 -11
- package/src/inject/index.js +18 -1
- package/src/inject/provider-fields.js +2 -2
- package/src/inject/ui.js +91 -17
package/src/host/helper.mjs
CHANGED
|
@@ -4,18 +4,19 @@
|
|
|
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';
|
|
8
|
-
import { appendFileSync, chmodSync, closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
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, 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
|
+
import { skillStats, DEFAULT_METADATA_BUDGET } from './skill-stats.mjs';
|
|
19
20
|
|
|
20
21
|
const VERSION = '1.5.1';
|
|
21
22
|
|
|
@@ -35,46 +36,162 @@ function defaultRtkDir() {
|
|
|
35
36
|
return process.env.RTK_DIR || join(homedir(), '.zcode-rtk');
|
|
36
37
|
}
|
|
37
38
|
|
|
38
|
-
//
|
|
39
|
-
//
|
|
39
|
+
// 主题功能的壁纸图库:用户上传的图片/视频都存这里,helper 以 /bg/file/<name> 提供,
|
|
40
|
+
// 注入层直接引用该 URL(媒体元素/CSS url() 带不了鉴权请求头,URL 带 ?t= token,见下)
|
|
40
41
|
const BG_DIR_NAME = 'backgrounds';
|
|
41
|
-
function backgroundsDir(dataRoot) {
|
|
42
|
+
export function backgroundsDir(dataRoot) {
|
|
42
43
|
return join(dataRoot, BG_DIR_NAME);
|
|
43
44
|
}
|
|
44
|
-
//
|
|
45
|
-
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
-
const
|
|
45
|
+
// 壁纸上传约束:图片只收常见位图格式(单张 ≤10MB),视频收 mp4/webm/mov(单个
|
|
46
|
+
// ≤200MB);图库合计 ≤50 个(防塞爆磁盘与同步)
|
|
47
|
+
export const BG_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.avif']);
|
|
48
|
+
export const VIDEO_EXT = new Set(['.mp4', '.webm', '.mov']);
|
|
49
|
+
export const MEDIA_EXT = new Set([...BG_EXT, ...VIDEO_EXT]);
|
|
50
|
+
export const BG_MAX_BYTES = 10 * 1024 * 1024;
|
|
51
|
+
export const VIDEO_MAX_BYTES = 200 * 1024 * 1024;
|
|
52
|
+
export const BG_MAX_COUNT = 50;
|
|
53
|
+
const BG_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.bmp': 'image/bmp', '.avif': 'image/avif', '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime' };
|
|
49
54
|
// 文件名安全化:去路径分隔符与控制字符,空白折叠,保留扩展名;非法返回 null
|
|
50
|
-
function sanitizeBgName(raw) {
|
|
55
|
+
export function sanitizeBgName(raw) {
|
|
51
56
|
if (typeof raw !== 'string') return null;
|
|
52
|
-
const name = raw.replace(/[\r\n\t
|
|
57
|
+
const name = raw.replace(/[\r\n\t\/\\:*?"<>|]/g, '').replace(/\s+/g, ' ').trim().replace(/[. ]+$/, '');
|
|
53
58
|
if (!name || name.startsWith('.') || name.length > 120) return null;
|
|
54
59
|
const ext = name.slice(name.lastIndexOf('.')).toLowerCase();
|
|
55
|
-
if (!
|
|
60
|
+
if (!MEDIA_EXT.has(ext)) return null;
|
|
61
|
+
// Windows 设备名(CON/NUL/COM1…)作文件名会落到设备而非磁盘
|
|
62
|
+
if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(name)) return null;
|
|
56
63
|
return name;
|
|
57
64
|
}
|
|
58
|
-
|
|
65
|
+
// 文件头魔数校验(防把可执行文件改扩展名上传):图片按扩展名匹配常见位图头,
|
|
66
|
+
// 视频 mp4/mov 是 ftyp 盒、webm 是 EBML。/bg 上传与 wallpaper CLI 共用这一份
|
|
67
|
+
export function bgMagicOk(name, head) {
|
|
68
|
+
const ext = name.slice(name.lastIndexOf('.')).toLowerCase();
|
|
69
|
+
if (VIDEO_EXT.has(ext)) {
|
|
70
|
+
return ext === '.webm'
|
|
71
|
+
? head.slice(0, 4).toString('hex') === '1a45dfa3'
|
|
72
|
+
: head.slice(4, 8).toString('ascii') === 'ftyp';
|
|
73
|
+
}
|
|
74
|
+
return ({
|
|
75
|
+
'.png': head.slice(0, 8).toString('hex') === '89504e470d0a1a0a',
|
|
76
|
+
'.jpg': head[0] === 0xff && head[1] === 0xd8,
|
|
77
|
+
'.jpeg': head[0] === 0xff && head[1] === 0xd8,
|
|
78
|
+
'.gif': head.slice(0, 3).toString('ascii') === 'GIF',
|
|
79
|
+
'.webp': head.slice(0, 4).toString('ascii') === 'RIFF' && head.slice(8, 12).toString('ascii') === 'WEBP',
|
|
80
|
+
'.bmp': head[0] === 0x42 && head[1] === 0x4d,
|
|
81
|
+
'.avif': head.slice(4, 8).toString('ascii') === 'ftyp',
|
|
82
|
+
})[ext] === true;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 删原片时同步清掉该视频的转码缓存(key 公式与 /bg/transcode 相同):不清的话
|
|
86
|
+
// 删了原片,抽帧版会永久残留在 cache/transcode。/bg/delete 与 wallpaper CLI 共用
|
|
87
|
+
export function cleanupBgTranscode(dataRoot, file) {
|
|
88
|
+
try {
|
|
89
|
+
const st = statSync(file);
|
|
90
|
+
for (const fps of TRANSCODE_FPS) {
|
|
91
|
+
const k = createHash('sha1').update(`${file}#${fps}#${st.mtimeMs}#${st.size}`).digest('hex').slice(0, 16);
|
|
92
|
+
const out = join(transcodeDir(dataRoot), k + '.mp4');
|
|
93
|
+
if (existsSync(out)) unlinkOrDefer(out);
|
|
94
|
+
}
|
|
95
|
+
} catch { /* 缓存清理失败不影响删原片 */ }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// Windows 下 ffmpeg 转码/杀软会短暂占用文件,直接 unlink/rename 抛 EPERM/EBUSY:
|
|
99
|
+
// 抢不到就改名挂起(.deleted-<ts>),后续清理,不让一次失败卡住用户操作
|
|
100
|
+
export function unlinkOrDefer(file) {
|
|
101
|
+
try {
|
|
102
|
+
unlinkSync(file);
|
|
103
|
+
} catch (e) {
|
|
104
|
+
if (e && (e.code === 'EPERM' || e.code === 'EBUSY' || e.code === 'EACCES')) {
|
|
105
|
+
try { renameSync(file, `${file}.deleted-${Date.now().toString(36)}`); } catch { /* 仍被占:下轮再试 */ }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
export function renameOrReplace(tmp, dst) {
|
|
110
|
+
try {
|
|
111
|
+
renameSync(tmp, dst);
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e && (e.code === 'EPERM' || e.code === 'EBUSY' || e.code === 'EACCES')) {
|
|
114
|
+
// 目标被占用:把旧文件改名挂起后再改名落位
|
|
115
|
+
try { renameSync(dst, `${dst}.deleted-${Date.now().toString(36)}`); renameSync(tmp, dst); } catch { throw e; }
|
|
116
|
+
} else {
|
|
117
|
+
throw e;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// 惰性清掉上轮挂起的 .deleted-*(超过 1 天才清,避开仍被占用的)
|
|
122
|
+
export function sweepDeferredBg(dir) {
|
|
123
|
+
try {
|
|
124
|
+
for (const n of readdirSync(dir)) {
|
|
125
|
+
// .deleted-* 是延迟删除的残留;结尾 .tmp 是上传中断留下的半截文件(正常
|
|
126
|
+
// 流程会即时改名或删掉)。都只清超过 24 小时的,避免误伤进行中的操作;
|
|
127
|
+
// 媒体文件扩展名有白名单,正常文件不会以 .tmp 结尾
|
|
128
|
+
if (!n.includes('.deleted-') && !n.endsWith('.tmp')) continue;
|
|
129
|
+
const f = join(dir, n);
|
|
130
|
+
try {
|
|
131
|
+
if (Date.now() - statSync(f).mtimeMs > 24 * 3600 * 1000) unlinkSync(f);
|
|
132
|
+
} catch { /* 仍被占用 */ }
|
|
133
|
+
}
|
|
134
|
+
} catch { /* 目录不存在 */ }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export function listBgFiles(dataRoot) {
|
|
59
138
|
const dir = backgroundsDir(dataRoot);
|
|
60
139
|
try {
|
|
61
140
|
return readdirSync(dir)
|
|
62
|
-
.map((name) => { const st = statSync(join(dir, name)); return { name, size: st.size, mtime: st.mtimeMs }; })
|
|
63
|
-
.filter((f) =>
|
|
141
|
+
.map((name) => { try { const st = statSync(join(dir, name)); return { name, size: st.size, mtime: st.mtimeMs }; } catch { return null; } })
|
|
142
|
+
.filter((f) => f && MEDIA_EXT.has(f.name.slice(f.name.lastIndexOf('.')).toLowerCase()))
|
|
143
|
+
.filter((f) => sanitizeBgName(f.name) === f.name) // 与取文件的二次清洗对齐:名字对不上的不列(列了会误命中清洗后同名文件)
|
|
64
144
|
.sort((a, b) => b.mtime - a.mtime);
|
|
65
145
|
} catch { return []; } // 目录不存在 = 空图库
|
|
66
146
|
}
|
|
67
147
|
|
|
68
|
-
//
|
|
69
|
-
//
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
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
|
+
|
|
157
|
+
// 视频壁纸帧率上限:ffmpeg 一次性转码出抽帧版存缓存目录,注入层先播原片、
|
|
158
|
+
// 转码完成再换。没有 ffmpeg 时接口直接报缺依赖,注入层保持原片播放
|
|
159
|
+
export const TRANSCODE_FPS = new Set([15, 30, 60, 90, 120]);
|
|
160
|
+
let ffmpegOk = null; // 三态:null 未探测 / true / false
|
|
161
|
+
function hasFfmpeg() {
|
|
162
|
+
if (ffmpegOk === null) {
|
|
163
|
+
try { ffmpegOk = spawnSync('ffmpeg', ['-version'], { stdio: 'ignore' }).status === 0; }
|
|
164
|
+
catch { ffmpegOk = false; }
|
|
165
|
+
}
|
|
166
|
+
return ffmpegOk;
|
|
167
|
+
}
|
|
168
|
+
export function transcodeDir(dataRoot) {
|
|
169
|
+
return join(dataRoot, 'cache', 'transcode');
|
|
170
|
+
}
|
|
171
|
+
const transcodeJobs = new Set(); // 正在转码的 key,防同一文件重复起 ffmpeg
|
|
172
|
+
const transcodeChildren = new Set(); // 在跑的 ffmpeg 子进程:退出/交接时统一收掉,防孤儿进程
|
|
173
|
+
const TRANSCODE_MAX_CONCURRENCY = 2; // 同时最多 2 个 ffmpeg,防批量请求打满 CPU/磁盘
|
|
174
|
+
// URL 路径段解码:非法 % 序列回 null(调用方回 400),不让 URIError 落成 500
|
|
175
|
+
let folderCfgCache = { at: 0, dir: '' };
|
|
176
|
+
function decodeName(raw) {
|
|
177
|
+
try { return decodeURIComponent(raw); } catch { return null; }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// 主题配置(设置 → 外观 → 主题/壁纸):skin 为皮肤 id(default = 不覆盖,
|
|
181
|
+
// custom = 用 custom 锚点色现算色阶);bg.mode 选壁纸来源——none 无壁纸 /
|
|
182
|
+
// library 本地图库(file 为当前文件,单选一张,轮换归文件夹)/ folder 文件夹
|
|
183
|
+
// (定时轮换,folderRandom 随机或顺序)/ url 图片网址(intervalMin 定时刷新)/
|
|
184
|
+
// web 网页(url 为页面地址,iframe 铺在界面后方);
|
|
185
|
+
// maskOpacity 遮罩不透明度 0-0.99(越高画面越向主题背景色淡化,文字对比越
|
|
186
|
+
// 清晰,默认 0.82)、blurPx 画面模糊 0-24px(默认 0)、panelOpacity 面板
|
|
187
|
+
// 不透明度 0-1(侧栏/面板/标签栏,越低透出画面越多,默认 0.3);
|
|
188
|
+
// transition 换壁纸转场(cut 直接切换 / fade 淡入淡出)、fpsCap 视频帧率上限
|
|
189
|
+
// (0 原始,其余 15/30/60/90/120,需 ffmpeg 抽帧转码)、videoVolume 音量 0-1(默认 0
|
|
190
|
+
// 静音)、playbackRate 倍速 0.5-2(默认 1);pauseOnHidden/pauseOnBlur/
|
|
191
|
+
// pauseOnBattery 三个暂停条件(默认开/关/关)
|
|
75
192
|
const THEME_SKINS = new Set(['default', 'dracula', 'nord', 'tokyonight', 'catppuccin', 'gruvbox', 'onedark', 'solarized', 'rosepine', 'everforest', 'nightowl', 'kanagawa', 'custom']);
|
|
76
|
-
const BG_MODES = new Set(['none', 'library', 'folder', 'url']);
|
|
77
|
-
const BG_FITS = new Set(['cover', 'contain', 'fill', 'tile']);
|
|
193
|
+
export const BG_MODES = new Set(['none', 'library', 'folder', 'url', 'web']);
|
|
194
|
+
export const BG_FITS = new Set(['cover', 'contain', 'fill', 'tile']);
|
|
78
195
|
const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
|
|
79
196
|
const CUSTOM_KEYS = ['bg', 'card', 'fg', 'muted', 'accent'];
|
|
80
197
|
function mergeCustomSkin(saved) {
|
|
@@ -100,11 +217,16 @@ function mergeBgRegion(src) {
|
|
|
100
217
|
file: mode === 'library' ? (str(src.file, 200) || '') : '',
|
|
101
218
|
folder: mode === 'folder' ? (str(src.folder, 4096) || '') : '',
|
|
102
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,
|
|
103
224
|
};
|
|
104
225
|
}
|
|
105
226
|
export function mergeThemeConfig(saved) {
|
|
106
227
|
const t = saved && typeof saved === 'object' ? saved : {};
|
|
107
228
|
const bg = t.bg && typeof t.bg === 'object' ? t.bg : {};
|
|
229
|
+
const bgUrl = (str(bg.url, 2000) || '').trim();
|
|
108
230
|
const cfg = {
|
|
109
231
|
skin: THEME_SKINS.has(t.skin) ? t.skin : 'default',
|
|
110
232
|
custom: mergeCustomSkin(t.custom),
|
|
@@ -113,14 +235,25 @@ export function mergeThemeConfig(saved) {
|
|
|
113
235
|
file: str(bg.file, 200) || '',
|
|
114
236
|
folder: str(bg.folder, 4096) || '',
|
|
115
237
|
folderRandom: bg.folderRandom !== false,
|
|
116
|
-
url: (
|
|
117
|
-
|
|
238
|
+
url: /^https?:\/\//i.test(bgUrl) ? bgUrl : '', // 网页壁纸只收 http(s)(与 wallpaper CLI 校验一致)
|
|
239
|
+
// Number() 容错与相邻数值字段一致:外部写入方(手改配置/壁纸控制插件)写数字字符串也能生效
|
|
240
|
+
intervalMin: bg.intervalMin != null && Number.isFinite(Number(bg.intervalMin)) ? Math.min(1440, Math.max(0, Math.round(Number(bg.intervalMin)))) : 0,
|
|
118
241
|
fit: BG_FITS.has(bg.fit) ? bg.fit : 'cover',
|
|
119
242
|
// null/undefined/非数值都落默认(Number(null)=0 是有限数,须先排除 null)
|
|
120
|
-
maskOpacity: bg.maskOpacity != null && Number.isFinite(Number(bg.maskOpacity))
|
|
243
|
+
maskOpacity: bg.maskOpacity != null && bg.maskOpacity !== '' && Number.isFinite(Number(bg.maskOpacity))
|
|
121
244
|
? Math.min(0.99, Math.max(0, Number(bg.maskOpacity))) : 0.82,
|
|
122
|
-
blurPx: bg.blurPx != null && Number.isFinite(Number(bg.blurPx)) ? Math.min(24, Math.max(0, Math.round(
|
|
123
|
-
panelOpacity: bg.panelOpacity != null && Number.isFinite(Number(bg.panelOpacity)) ? Math.min(1, Math.max(0, Number(bg.panelOpacity))) : 0.3,
|
|
245
|
+
blurPx: bg.blurPx != null && Number.isFinite(Number(bg.blurPx)) ? Math.min(24, Math.max(0, Math.round(bg.blurPx))) : 0,
|
|
246
|
+
panelOpacity: bg.panelOpacity != null && bg.panelOpacity !== '' && Number.isFinite(Number(bg.panelOpacity)) ? Math.min(1, Math.max(0, Number(bg.panelOpacity))) : 0.3,
|
|
247
|
+
transition: bg.transition === 'fade' ? 'fade' : 'cut',
|
|
248
|
+
fpsCap: TRANSCODE_FPS.has(Number(bg.fpsCap)) ? Number(bg.fpsCap) : 0,
|
|
249
|
+
dialogFrost: bg.dialogFrost !== false,
|
|
250
|
+
videoVolume: bg.videoVolume != null && Number.isFinite(Number(bg.videoVolume))
|
|
251
|
+
? Math.min(1, Math.max(0, Number(bg.videoVolume))) : 0,
|
|
252
|
+
playbackRate: bg.playbackRate != null && Number.isFinite(Number(bg.playbackRate))
|
|
253
|
+
? Math.min(2, Math.max(0.5, Number(bg.playbackRate))) : 1,
|
|
254
|
+
pauseOnHidden: bg.pauseOnHidden !== false,
|
|
255
|
+
pauseOnBlur: bg.pauseOnBlur === true,
|
|
256
|
+
pauseOnBattery: bg.pauseOnBattery === true,
|
|
124
257
|
regions: {
|
|
125
258
|
left: mergeBgRegion(bg.regions && bg.regions.left),
|
|
126
259
|
center: mergeBgRegion(bg.regions && bg.regions.center),
|
|
@@ -131,6 +264,17 @@ export function mergeThemeConfig(saved) {
|
|
|
131
264
|
return cfg;
|
|
132
265
|
}
|
|
133
266
|
|
|
267
|
+
// wallpaper CLI 的参数键分类:与上面 mergeThemeConfig 里可调的 bg 参数一一对应
|
|
268
|
+
//(mode/file/folder/url/regions 是来源字段归 set 命令、intervalMin/folderRandom 归
|
|
269
|
+
// rotate 命令,都不在此表),mergeThemeConfig 加可调字段时这张表同步加。
|
|
270
|
+
// 值 'number'/'boolean' = 类型检查,Set = 枚举成员集;取值范围仍归
|
|
271
|
+
// mergeThemeConfig(clamp + 默认值)
|
|
272
|
+
export const BG_PARAM_KEYS = {
|
|
273
|
+
maskOpacity: 'number', blurPx: 'number', panelOpacity: 'number', videoVolume: 'number', playbackRate: 'number',
|
|
274
|
+
pauseOnHidden: 'boolean', pauseOnBlur: 'boolean', pauseOnBattery: 'boolean', dialogFrost: 'boolean',
|
|
275
|
+
fit: BG_FITS, transition: new Set(['cut', 'fade']), fpsCap: new Set([0, ...TRANSCODE_FPS]),
|
|
276
|
+
};
|
|
277
|
+
|
|
134
278
|
// headroom 插件的配置文件(与 /hr-* 命令、钩子共用,headroom-lib.sh 按 HOME 定位)
|
|
135
279
|
function defaultHeadroomFile() {
|
|
136
280
|
return join(homedir(), '.zcode', 'headroom.json');
|
|
@@ -142,7 +286,8 @@ const ZCODE_PLUGINS_MARKETPLACE = 'duanluan-zcode-plugins';
|
|
|
142
286
|
const ZCODE_PLUGINS_MARKETPLACE_SOURCE = 'duanluan/zcode-plugins';
|
|
143
287
|
|
|
144
288
|
function cliPluginsDir() {
|
|
145
|
-
|
|
289
|
+
// 官方 CLI 数据目录跟 ZCODE_DATA_BASE_DIR 迁移(rollout/v2 同款),别固定 HOME
|
|
290
|
+
return join(resolveDataRootDir(), 'cli', 'plugins');
|
|
146
291
|
}
|
|
147
292
|
|
|
148
293
|
export function defaultConfig() {
|
|
@@ -160,6 +305,7 @@ export function defaultConfig() {
|
|
|
160
305
|
toolbarIcons: true, // 侧栏菜单并入顶栏:新建任务/搜索/自动化/插件市场收成顶栏图标按钮(原菜单隐藏,点击转发)
|
|
161
306
|
pinnedCollapse: true, // 已置顶分区可折叠:标题可点折叠/展开任务列表(状态记 localStorage)
|
|
162
307
|
tableCopy: true, // 表格工具条"复制表格"按钮:富文本剪贴板,粘贴即表格(table-copy.js)
|
|
308
|
+
sessionLink: true, // 会话 ID 显示为任务名链接:聊天里的 sess_/session_ 显示为任务名,点击切换(session-link.js)
|
|
163
309
|
composerProvider: true, // 输入框模型名前显示供应商名(composer-provider.js)
|
|
164
310
|
},
|
|
165
311
|
// 空闲项目内存回收的判定时长(分钟,1–1440):项目无运行中会话、无后台命令
|
|
@@ -193,13 +339,16 @@ export function defaultConfig() {
|
|
|
193
339
|
// headroom 启用开关的记忆(供应商 id → { proxy, direct }):关闭时把走 headroom 的
|
|
194
340
|
// 供应商地址切回直连并记录下来,再次开启时按记录把地址切回代理
|
|
195
341
|
headroomRoutes: {},
|
|
196
|
-
//
|
|
197
|
-
//
|
|
342
|
+
// 自动重命名(原“任务名提示词”):新会话开始作答后按可配置的供应商与
|
|
343
|
+
// 提示词生成标题,并按“手动重命名”写入任务索引。默认关闭。provider:
|
|
198
344
|
// 'session' = 跟随当前会话(调用时从任务索引解析该会话的供应商,默认)、
|
|
199
345
|
// '' = 不跟随(自填 baseUrl/apiKey/format)、其余 = 供应商 id(保存时同步
|
|
200
346
|
// 解析一份 baseUrl/apiKey/format 副本,供应商日后被删仍可直连);
|
|
201
347
|
// model 默认 glm-5.3-flash(起名用快模型即可),跟随会话时可留空
|
|
202
|
-
//(用会话当前模型);prompt 留空 =
|
|
348
|
+
//(用会话当前模型);prompt 留空 = 内置默认提示词。
|
|
349
|
+
// 手动“自动重命名”(任务行悬浮按钮 / 右键菜单入口,取会话最近 recentQa
|
|
350
|
+
// 轮问答起名、已重命名也覆盖)不受 enabled 限制,入口各有开关:
|
|
351
|
+
// hoverBtn 任务行按钮、menuEntry 右键菜单项
|
|
203
352
|
titleGen: {
|
|
204
353
|
enabled: false,
|
|
205
354
|
customWritten: {},
|
|
@@ -209,6 +358,9 @@ export function defaultConfig() {
|
|
|
209
358
|
baseUrl: '',
|
|
210
359
|
apiKey: '',
|
|
211
360
|
format: '',
|
|
361
|
+
recentQa: 3,
|
|
362
|
+
hoverBtn: true,
|
|
363
|
+
menuEntry: true,
|
|
212
364
|
},
|
|
213
365
|
// HTTP 代理(http(s)://host:port):helper 发起的网络访问走它——插件市场更新/安装
|
|
214
366
|
// (zcode CLI → git)、headroom/rtk 的安装与升级(pip/GitHub)。空 = 不用代理。
|
|
@@ -246,10 +398,20 @@ export function defaultConfig() {
|
|
|
246
398
|
};
|
|
247
399
|
}
|
|
248
400
|
|
|
401
|
+
// 配置文件“存在但读不出/解析不了”标记:写路径见标记拒绝写回,防止把默认值
|
|
402
|
+
// 覆盖上去把用户配置(WebDAV 账号、别名、样式…)整份清掉
|
|
403
|
+
let configUnreadable = false;
|
|
404
|
+
// 写配置前的可写检查(wallpaper CLI 等外部写入方用):loadConfig 读不出时置位、
|
|
405
|
+
// saveConfig 据此拒写;外部写入方读到损坏要转成明确报错,别等 saveConfig 静默拒写
|
|
406
|
+
export function configFileUnreadable() {
|
|
407
|
+
return configUnreadable;
|
|
408
|
+
}
|
|
249
409
|
export function loadConfig(configFile) {
|
|
250
410
|
try {
|
|
251
|
-
if (!existsSync(configFile)) return defaultConfig();
|
|
252
|
-
const saved = JSON.parse(readFileSyncText(configFile));
|
|
411
|
+
if (!existsSync(configFile)) { configUnreadable = false; return defaultConfig(); }
|
|
412
|
+
const saved = JSON.parse(readFileSyncText(configFile).replace(/^\uFEFF/, '')); // 记事本存的带 BOM 文件也能解析
|
|
413
|
+
if (Array.isArray(saved)) throw new Error('顶层是数组'); // 按损坏处理
|
|
414
|
+
configUnreadable = false; // 解析成功就复位:修好文件后自动恢复可写
|
|
253
415
|
const minutes = Number(saved.idleReclaimMinutes);
|
|
254
416
|
const startupMinutes = Number(saved.idleReclaimStartupMinutes);
|
|
255
417
|
return {
|
|
@@ -271,6 +433,7 @@ export function loadConfig(configFile) {
|
|
|
271
433
|
sync: mergeSyncConfig(saved.sync),
|
|
272
434
|
};
|
|
273
435
|
} catch {
|
|
436
|
+
configUnreadable = existsSync(configFile);
|
|
274
437
|
return defaultConfig();
|
|
275
438
|
}
|
|
276
439
|
}
|
|
@@ -279,11 +442,121 @@ function readFileSyncText(p) {
|
|
|
279
442
|
return readFileSync(p, 'utf8');
|
|
280
443
|
}
|
|
281
444
|
|
|
445
|
+
// 原子写任意 JSON 文件:先写临时文件再改名,避免崩溃留下半截 JSON
|
|
446
|
+
function writeJsonAtomic(file, obj) {
|
|
447
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
448
|
+
try { mkdirSync(dirname(file), { recursive: true }); } catch { /* 目录已存在 */ } // 数据目录缺失时先建,别让写入直接抛
|
|
449
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2), { encoding: 'utf8', mode: 0o600 }); // 配置含凭据,限制本人读写
|
|
450
|
+
renameSync(tmp, file);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// 读改写必须同步完成(loadConfig→改→saveConfig 中间不能加 await):
|
|
454
|
+
// HTTP 处理器靠单线程的同步原子性保证并发保存不互相覆盖字段
|
|
282
455
|
export function saveConfig(configFile, config) {
|
|
283
|
-
//
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
456
|
+
// 配置"存在但损坏"时拒绝写回:否则 title-gen/同步/别名等写路径会把默认值
|
|
457
|
+
// 整份覆盖上去(WebDAV 账号、样式、主题全丢且不可恢复)。POST /config 另有
|
|
458
|
+
// 显式报错,这里兜住其余调用方;修好文件后 loadConfig 会复位标记恢复可写。
|
|
459
|
+
// 保护只针对 zcodepro.json:写别的文件(/zcode-config 写 cli/config.json)
|
|
460
|
+
// 直接用 writeJsonAtomic,别被这个标记误伤成静默不写。
|
|
461
|
+
// 返回是否写入:调用方据此报错(同步导入不能在拒写时还报成功)
|
|
462
|
+
if (configUnreadable) {
|
|
463
|
+
console.error('[zcodepro] zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置');
|
|
464
|
+
return false;
|
|
465
|
+
}
|
|
466
|
+
writeJsonAtomic(configFile, config);
|
|
467
|
+
return true;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// —— zcodepro.json 跨进程写锁 ——————————————————————————————————
|
|
471
|
+
// 多个进程(helper、wallpaper CLI、同步导入…)会同时读改写 zcodepro.json,
|
|
472
|
+
// 不互斥时各拿旧快照写回,会把对方改的整段配置(WebDAV 凭据、别名、样式)盖掉。
|
|
473
|
+
// 锁 = 配置文件同目录下的锁目录(mkdir 原子创建),目录里写持有者信息(pid + 随机 token)。
|
|
474
|
+
const CONFIG_LOCK_STALE_MS = 10_000; // 锁龄超过这个数按悬挂锁接管
|
|
475
|
+
const CONFIG_LOCK_WAIT_MS = 5_000; // 等锁上限;等不到带提示继续尽力而为
|
|
476
|
+
|
|
477
|
+
// 进程还在不在(pid 被系统复用的极端情形由锁龄上限兜底)
|
|
478
|
+
function pidAlive(pid) {
|
|
479
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
480
|
+
try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// 抢一次锁:mkdir 成功即持有;已有锁时仅在持有者死亡或锁龄超时才拆掉接管。
|
|
484
|
+
// 返回是否拿到(没拿到由调用方等待重试)
|
|
485
|
+
function tryAcquireConfigLock(configFile, token) {
|
|
486
|
+
const lockDir = configFile + '.lock';
|
|
487
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
488
|
+
try {
|
|
489
|
+
mkdirSync(lockDir); // 原子创建:同时只有一个进程成功
|
|
490
|
+
try {
|
|
491
|
+
writeFileSync(join(lockDir, 'holder.json'), JSON.stringify({ pid: process.pid, token }), 'utf8');
|
|
492
|
+
} catch { /* 持有者信息写失败不影响锁本身,释放时按超时接管兜底 */ }
|
|
493
|
+
return true;
|
|
494
|
+
} catch (err) {
|
|
495
|
+
if (err.code !== 'EEXIST') throw err;
|
|
496
|
+
let stale = false;
|
|
497
|
+
try {
|
|
498
|
+
let alive = true;
|
|
499
|
+
try {
|
|
500
|
+
const holder = JSON.parse(readFileSync(join(lockDir, 'holder.json'), 'utf8'));
|
|
501
|
+
alive = pidAlive(Number(holder.pid));
|
|
502
|
+
} catch { alive = true; } // 持有者信息缺失/写坏:只按锁龄判悬挂
|
|
503
|
+
stale = Date.now() - statSync(lockDir).mtimeMs > CONFIG_LOCK_STALE_MS || !alive;
|
|
504
|
+
} catch { stale = true; } // 锁目录正被删/读不了:按悬挂接管
|
|
505
|
+
if (!stale) return false;
|
|
506
|
+
try { rmSync(lockDir, { recursive: true, force: true }); } catch { return false; }
|
|
507
|
+
// 接管后回到循环重试 mkdir(可能被另一个进程抢先)
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return false;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// 释放锁:只认自己那份持有者信息,被别人接管后不能把别人的锁删掉
|
|
514
|
+
function releaseConfigLock(configFile, token) {
|
|
515
|
+
const lockDir = configFile + '.lock';
|
|
516
|
+
try {
|
|
517
|
+
const holder = JSON.parse(readFileSync(join(lockDir, 'holder.json'), 'utf8'));
|
|
518
|
+
if (holder.token !== token) return;
|
|
519
|
+
} catch { return; } // 读不到持有者信息(已被接管后删除等):不动目录,留超时接管
|
|
520
|
+
try { rmSync(lockDir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// 在跨进程锁内同步执行 fn 并返回其结果:fn 里保持同步读改写(loadConfig→改→
|
|
524
|
+
// saveConfig 中间不要 await)。等锁上限约 5 秒,等不到带提示继续尽力而为
|
|
525
|
+
//(不加锁至少还能写成,别直接失败)。调用点是 async 就 await 这个函数。
|
|
526
|
+
export async function withConfigLock(configFile, fn) {
|
|
527
|
+
const token = randomBytes(12).toString('hex');
|
|
528
|
+
const deadline = Date.now() + CONFIG_LOCK_WAIT_MS;
|
|
529
|
+
while (!tryAcquireConfigLock(configFile, token)) {
|
|
530
|
+
if (Date.now() >= deadline) {
|
|
531
|
+
console.error('[zcodepro] 等 zcodepro.json 写锁超时,继续无锁写入(可能与别的进程互相覆盖)');
|
|
532
|
+
return fn();
|
|
533
|
+
}
|
|
534
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
535
|
+
}
|
|
536
|
+
try {
|
|
537
|
+
return fn();
|
|
538
|
+
} finally {
|
|
539
|
+
releaseConfigLock(configFile, token);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
// 同步等锁变体(同步调用点用,如 setHeadroomUsage):Atomics.wait 睡眠重试,
|
|
544
|
+
// 语义与 withConfigLock 相同
|
|
545
|
+
export function withConfigLockSync(configFile, fn) {
|
|
546
|
+
const token = randomBytes(12).toString('hex');
|
|
547
|
+
const deadline = Date.now() + CONFIG_LOCK_WAIT_MS;
|
|
548
|
+
while (!tryAcquireConfigLock(configFile, token)) {
|
|
549
|
+
if (Date.now() >= deadline) {
|
|
550
|
+
console.error('[zcodepro] 等 zcodepro.json 写锁超时,继续无锁写入(可能与别的进程互相覆盖)');
|
|
551
|
+
return fn();
|
|
552
|
+
}
|
|
553
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
|
|
554
|
+
}
|
|
555
|
+
try {
|
|
556
|
+
return fn();
|
|
557
|
+
} finally {
|
|
558
|
+
releaseConfigLock(configFile, token);
|
|
559
|
+
}
|
|
287
560
|
}
|
|
288
561
|
|
|
289
562
|
// 一次性配置迁移已移除(原 wsRunningSpinOff):旧实验版“折叠项目运行提示”
|
|
@@ -291,6 +564,7 @@ export function saveConfig(configFile, config) {
|
|
|
291
564
|
// 已重写,迁移对新装机(首启无配置文件、首存后才建)误伤为默认关闭,故删。
|
|
292
565
|
|
|
293
566
|
function json(res, status, obj) {
|
|
567
|
+
if (res.writableEnded || res.headersSent) return; // 已发过响应就不再写(防双发崩进程)
|
|
294
568
|
const body = JSON.stringify(obj);
|
|
295
569
|
res.writeHead(status, {
|
|
296
570
|
'Content-Type': 'application/json; charset=utf-8',
|
|
@@ -305,12 +579,14 @@ function readBody(req, limitBytes = 1 << 20) {
|
|
|
305
579
|
return new Promise((resolveBody, rejectBody) => {
|
|
306
580
|
const chunks = [];
|
|
307
581
|
let size = 0;
|
|
582
|
+
let overflowed = false;
|
|
308
583
|
req.on('data', (c) => {
|
|
309
584
|
size += c.length;
|
|
310
|
-
if (size > limitBytes) {
|
|
585
|
+
if (size > limitBytes) { overflowed = true; chunks.length = 0; return; } // 排干剩余字节,防 keep-alive 残字节错位
|
|
311
586
|
chunks.push(c);
|
|
312
587
|
});
|
|
313
588
|
req.on('end', () => {
|
|
589
|
+
if (overflowed) { rejectBody(Object.assign(new Error('请求体过大'), { statusCode: 413 })); return; }
|
|
314
590
|
try { resolveBody(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); }
|
|
315
591
|
catch (e) { rejectBody(new Error('无效的 JSON 请求体')); }
|
|
316
592
|
});
|
|
@@ -355,7 +631,66 @@ function titleGenLog(dataRoot, line) {
|
|
|
355
631
|
} catch { /* 日志失败不影响功能 */ }
|
|
356
632
|
}
|
|
357
633
|
|
|
358
|
-
|
|
634
|
+
// ZCode 自身的行为配置(~/.zcode/cli/config.json,ZCode 官方用户级配置文件):
|
|
635
|
+
// 设置弹窗“行为 → ZCode CLI”由此读写,只更新提交的键,其余内容原样保留。
|
|
636
|
+
// 与全局提示词一样固定按主目录定位,不跟 ZCODE_DATA_BASE_DIR 迁移
|
|
637
|
+
function zcodeDataRoot() {
|
|
638
|
+
return join(homedir(), '.zcode');
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function readZcodeConfig(file) {
|
|
642
|
+
try {
|
|
643
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
644
|
+
} catch {
|
|
645
|
+
return {};
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
// 记忆不在此列:工作区记忆由桌面设置里的 memoryEnabled(~/.zcode/v2/setting.json)
|
|
650
|
+
// 控制,官方 设置 → Agent 能力 → 记忆 页负责开关
|
|
651
|
+
const ZCODE_FEATURE_KEYS = ['compact', 'rewind', 'subagent', 'skill', 'mcp'];
|
|
652
|
+
|
|
653
|
+
function zcodeConfigSnapshot(dataRoot) {
|
|
654
|
+
const cfg = readZcodeConfig(join(dataRoot, 'cli', 'config.json'));
|
|
655
|
+
const skills = cfg.skills && typeof cfg.skills === 'object' ? cfg.skills : {};
|
|
656
|
+
const features = cfg.features && typeof cfg.features === 'object' ? cfg.features : {};
|
|
657
|
+
const roots = Array.isArray(skills.roots)
|
|
658
|
+
? skills.roots.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim())
|
|
659
|
+
: [];
|
|
660
|
+
const has = (v) => v !== undefined;
|
|
661
|
+
const values = {
|
|
662
|
+
skills: {
|
|
663
|
+
enabled: skills.enabled !== false,
|
|
664
|
+
includeInstructions: skills.includeInstructions !== false,
|
|
665
|
+
metadataBudget: Number.isFinite(skills.metadataBudget) ? skills.metadataBudget : DEFAULT_METADATA_BUDGET,
|
|
666
|
+
roots,
|
|
667
|
+
},
|
|
668
|
+
features: Object.fromEntries(ZCODE_FEATURE_KEYS.map((k) => [k, features[k] !== false])),
|
|
669
|
+
};
|
|
670
|
+
// configured(是否显式写在配置里):界面据此标注“默认值”,也保证只写用户动过的键
|
|
671
|
+
const configured = {
|
|
672
|
+
skills: {
|
|
673
|
+
enabled: has(skills.enabled),
|
|
674
|
+
includeInstructions: has(skills.includeInstructions),
|
|
675
|
+
metadataBudget: has(skills.metadataBudget),
|
|
676
|
+
roots: has(skills.roots),
|
|
677
|
+
},
|
|
678
|
+
features: Object.fromEntries(ZCODE_FEATURE_KEYS.map((k) => [k, has(features[k])])),
|
|
679
|
+
};
|
|
680
|
+
const stats = skillStats({
|
|
681
|
+
dataRoot,
|
|
682
|
+
roots: values.skills.roots,
|
|
683
|
+
budget: values.skills.metadataBudget,
|
|
684
|
+
pluginsEnabled: cfg.plugins && typeof cfg.plugins === 'object' ? cfg.plugins.enabled !== false : true,
|
|
685
|
+
enabledPlugins: cfg.plugins && typeof cfg.plugins.enabledPlugins === 'object' ? cfg.plugins.enabledPlugins : {},
|
|
686
|
+
suppressedBuiltins: cfg.plugins && Array.isArray(cfg.plugins.suppressedBuiltins) ? cfg.plugins.suppressedBuiltins : [],
|
|
687
|
+
});
|
|
688
|
+
return { ok: true, values, configured, stats };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
export function startHelper({ port, token, dataRoot, state, agentsFile = defaultAgentsFile(), listenTries = 40, rolloutDir = '', visionFile = '' }) {
|
|
692
|
+
if (rolloutDir) rolloutDirOverride = rolloutDir;
|
|
693
|
+
if (!visionFile) visionFile = defaultVisionFile(); // 测试可覆盖,别把启动补写落到真实 ~/.zcode
|
|
359
694
|
const configFile = join(dataRoot, 'zcodepro.json');
|
|
360
695
|
const settingsFile = join(dataRoot, 'v2', 'setting.json');
|
|
361
696
|
const bootConfig = loadConfig(configFile);
|
|
@@ -376,9 +711,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
376
711
|
json(res, 204, {});
|
|
377
712
|
return;
|
|
378
713
|
}
|
|
379
|
-
//
|
|
380
|
-
//
|
|
381
|
-
//
|
|
714
|
+
// 背景图/壁纸取文件:媒体元素与 CSS url() 发不了自定义头,该路由在 token 校验
|
|
715
|
+
// 之前放行。仅 Host 校验(127.0.0.1,防 DNS rebinding)+ 文件名白名单目录内
|
|
716
|
+
// 取文件,不接受路径参数之外的任何输入。文件夹模式从配置的目录里取(同样免
|
|
717
|
+
// token)。流式输出并支持 Range:视频元素播放中会按字节段请求
|
|
382
718
|
const serveBgFile = (name, dir, res2) => {
|
|
383
719
|
const safe = sanitizeBgName(name);
|
|
384
720
|
const file = safe && join(dir, safe);
|
|
@@ -388,33 +724,114 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
388
724
|
return;
|
|
389
725
|
}
|
|
390
726
|
try {
|
|
391
|
-
const
|
|
392
|
-
|
|
727
|
+
const st = statSync(file);
|
|
728
|
+
if (!st.isFile()) {
|
|
729
|
+
res2.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
730
|
+
res2.end('not found');
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
const headers = {
|
|
393
734
|
'Content-Type': BG_MIME[safe.slice(safe.lastIndexOf('.')).toLowerCase()] || 'application/octet-stream',
|
|
394
735
|
'Cache-Control': 'no-cache',
|
|
736
|
+
'Accept-Ranges': 'bytes',
|
|
737
|
+
'Last-Modified': st.mtime.toUTCString(),
|
|
395
738
|
'Access-Control-Allow-Origin': '*',
|
|
396
|
-
}
|
|
397
|
-
|
|
739
|
+
};
|
|
740
|
+
// 条件请求命中直接 304:视频被反复重载时不再整段重下
|
|
741
|
+
const ims = String(req.headers['if-modified-since'] || '');
|
|
742
|
+
if (ims && Date.parse(ims) >= Math.floor(st.mtimeMs / 1000) * 1000) {
|
|
743
|
+
res2.writeHead(304, headers);
|
|
744
|
+
res2.end();
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
// 读流出错(文件恰好被删/盘错误)不能裸抛:未发头回 500,已发则掐断连接
|
|
748
|
+
const streamFile = (opts) => {
|
|
749
|
+
const rs = createReadStream(file, opts);
|
|
750
|
+
rs.on('error', () => {
|
|
751
|
+
if (!res2.headersSent) {
|
|
752
|
+
res2.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
753
|
+
res2.end('read error');
|
|
754
|
+
} else {
|
|
755
|
+
res2.destroy();
|
|
756
|
+
}
|
|
757
|
+
});
|
|
758
|
+
res2.on('close', () => rs.destroy());
|
|
759
|
+
rs.pipe(res2);
|
|
760
|
+
};
|
|
761
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range || ''));
|
|
762
|
+
if (m && (m[1] || m[2])) {
|
|
763
|
+
// 后缀区间 bytes=-N 取末尾 N 字节(N 是个数不是终点);起点越界按 RFC 回 416
|
|
764
|
+
const suffix = !m[1];
|
|
765
|
+
const start = suffix ? Math.max(0, st.size - (+m[2] || 0)) : +m[1];
|
|
766
|
+
const end = suffix ? st.size - 1 : (m[2] ? Math.min(+m[2], st.size - 1) : st.size - 1);
|
|
767
|
+
if (st.size === 0 || start >= st.size || start > end) {
|
|
768
|
+
res2.writeHead(416, { 'Content-Range': `bytes */${st.size}` });
|
|
769
|
+
res2.end();
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
res2.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 });
|
|
773
|
+
streamFile({ start, end });
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
res2.writeHead(200, { ...headers, 'Content-Length': st.size });
|
|
777
|
+
streamFile();
|
|
398
778
|
} catch {
|
|
399
779
|
res2.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
400
780
|
res2.end('read error');
|
|
401
781
|
}
|
|
402
782
|
};
|
|
783
|
+
// 媒体路由(CSS url()/<video> 引用,带不了鉴权请求头):认 URL 上的
|
|
784
|
+
// ?t= token,外部页面猜不到 token 就读不走图库媒体、也做不了存在性探测
|
|
785
|
+
if (req.method === 'GET' && (url.pathname.startsWith('/bg/file/')
|
|
786
|
+
|| url.pathname.startsWith('/bg/folder/file/') || url.pathname.startsWith('/bg/transcode/file/'))) {
|
|
787
|
+
const q = url.searchParams.get('t');
|
|
788
|
+
if (!token || (req.headers['x-zcodepro-token'] !== token && q !== token)) {
|
|
789
|
+
json(res, 401, { ok: false, error: 'unauthorized' });
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
403
793
|
if (req.method === 'GET' && url.pathname.startsWith('/bg/file/')) {
|
|
404
|
-
|
|
794
|
+
const dec = decodeName(url.pathname.slice('/bg/file/'.length));
|
|
795
|
+
if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
|
|
796
|
+
serveBgFile(dec, backgroundsDir(dataRoot), res);
|
|
405
797
|
return;
|
|
406
798
|
}
|
|
407
799
|
if (req.method === 'GET' && url.pathname.startsWith('/bg/folder/file/')) {
|
|
408
|
-
|
|
800
|
+
// 分区背景可带自己的目录(?dir=);缺省用全局设置的文件夹。目录值缓存 5 秒:
|
|
801
|
+
// 媒体请求(含每个 Range 分段)都完整读盘解析配置太浪费
|
|
802
|
+
const qDir = url.searchParams.get('dir');
|
|
803
|
+
let dir;
|
|
804
|
+
if (qDir) {
|
|
805
|
+
// dir 只认用户配置过的目录(全局文件夹 + 各分区目录),
|
|
806
|
+
// 判定与 /bg/folder/list 共用 bgFolderDirAllowed
|
|
807
|
+
if (!bgFolderDirAllowed(loadConfig(configFile).theme.bg, qDir)) {
|
|
808
|
+
json(res, 400, { ok: false, error: 'dir 参数无效或未配置' });
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
dir = qDir;
|
|
812
|
+
} else {
|
|
813
|
+
if (Math.abs(Date.now() - folderCfgCache.at) > 5000) folderCfgCache = { at: Date.now(), dir: loadConfig(configFile).theme.bg.folder };
|
|
814
|
+
dir = folderCfgCache.dir;
|
|
815
|
+
}
|
|
409
816
|
if (!dir) {
|
|
410
817
|
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
411
818
|
res.end('no folder');
|
|
412
819
|
return;
|
|
413
820
|
}
|
|
414
|
-
|
|
821
|
+
const dec = decodeName(url.pathname.slice('/bg/folder/file/'.length));
|
|
822
|
+
if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
|
|
823
|
+
serveBgFile(dec, dir, res);
|
|
415
824
|
return;
|
|
416
825
|
}
|
|
417
|
-
if (
|
|
826
|
+
if (req.method === 'GET' && url.pathname.startsWith('/bg/transcode/file/')) {
|
|
827
|
+
const dec = decodeName(url.pathname.slice('/bg/transcode/file/'.length));
|
|
828
|
+
if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
|
|
829
|
+
if (!/^[0-9a-f]{16}\.mp4$/.test(dec)) { json(res, 400, { ok: false, error: '非法转码文件名' }); return; } // 只服务 key.mp4:写一半的 .tmp.mp4 别被取走
|
|
830
|
+
serveBgFile(dec, transcodeDir(dataRoot), res);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
// 空 token 视为配置错误直接拒绝(fail-closed),别放成免鉴权
|
|
834
|
+
if (!token || req.headers['x-zcodepro-token'] !== token) {
|
|
418
835
|
json(res, 401, { ok: false, error: 'unauthorized' });
|
|
419
836
|
return;
|
|
420
837
|
}
|
|
@@ -429,123 +846,186 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
429
846
|
}
|
|
430
847
|
if (req.method === 'POST' && url.pathname === '/config') {
|
|
431
848
|
const body = await readBody(req);
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
json(res, 400, { ok: false, code: 'proxy-invalid', error: '代理地址需形如 http://127.0.0.1:7890,或留空清除' });
|
|
849
|
+
// 整段读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
850
|
+
// 防止两个写入方各拿旧快照写回、互相覆盖整份配置
|
|
851
|
+
await withConfigLock(configFile, () => {
|
|
852
|
+
const current = loadConfig(configFile);
|
|
853
|
+
if (configUnreadable) {
|
|
854
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置;请先修复该文件' });
|
|
439
855
|
return;
|
|
440
856
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
857
|
+
if (body && typeof body === 'object' && typeof body.proxy === 'string') {
|
|
858
|
+
const v = body.proxy.trim();
|
|
859
|
+
if (v === '') current.proxy = '';
|
|
860
|
+
else if (/^https?:\/\/\S+:\d+$/.test(v) && v.length <= 300) current.proxy = v;
|
|
861
|
+
else {
|
|
862
|
+
json(res, 400, { ok: false, code: 'proxy-invalid', error: '代理地址需形如 http://127.0.0.1:7890,或留空清除' });
|
|
863
|
+
return;
|
|
864
|
+
}
|
|
865
|
+
activeProxyUrl = current.proxy;
|
|
447
866
|
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
// 会话名锁定开关的每次变化都落日志:它被意外关闭两次(页面里是关、
|
|
455
|
-
// 配置文件是开,来源不明),有记录才能查到是谁改的
|
|
456
|
-
if (typeof body.features.titleLock === 'boolean' && body.features.titleLock !== (loadConfig(configFile).features.titleLock !== false)) {
|
|
457
|
-
titleGenLog(dataRoot, `titleLock ${body.features.titleLock ? 'on' : 'off'}(此前为 ${!body.features.titleLock ? 'on' : 'off'})`);
|
|
867
|
+
if (body && typeof body === 'object' && body.proxyScopes && typeof body.proxyScopes === 'object') {
|
|
868
|
+
// 代理生效范围按单项提交(每个开关只改自己那项),即时生效
|
|
869
|
+
for (const k of ['plugins', 'deps', 'sync']) {
|
|
870
|
+
if (typeof body.proxyScopes[k] === 'boolean') current.proxyScopes[k] = body.proxyScopes[k];
|
|
871
|
+
}
|
|
872
|
+
activeProxyScopes = { ...current.proxyScopes };
|
|
458
873
|
}
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
if (body && typeof body === 'object' && typeof body.idleReclaimMinutes === 'number' && Number.isFinite(body.idleReclaimMinutes)) {
|
|
462
|
-
current.idleReclaimMinutes = Math.min(1440, Math.max(1, Math.round(body.idleReclaimMinutes)));
|
|
463
|
-
}
|
|
464
|
-
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
465
|
-
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
466
|
-
}
|
|
467
|
-
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
468
|
-
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
469
|
-
}
|
|
470
|
-
// 会话快捷切换的键位(设置 → 快捷键里修改):键名固定,值限单个字母或数字
|
|
471
|
-
if (body && typeof body === 'object' && body.shortcuts && typeof body.shortcuts === 'object') {
|
|
472
|
-
const patch = {};
|
|
473
|
-
for (const k of ['switchLast', 'switchPrev', 'switchNext', 'switchRecent', 'switchAttention']) {
|
|
474
|
-
const v = body.shortcuts[k];
|
|
475
|
-
if (typeof v === 'string' && /^[a-z0-9]$/.test(v)) patch[k] = v;
|
|
874
|
+
if (body && typeof body === 'object' && typeof body.devMode === 'boolean') {
|
|
875
|
+
current.devMode = body.devMode;
|
|
476
876
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
877
|
+
if (body && typeof body === 'object' && body.features && typeof body.features === 'object') {
|
|
878
|
+
// 会话名锁定开关的每次变化都落日志:它被意外关闭两次(页面里是关、
|
|
879
|
+
// 配置文件是开,来源不明),有记录才能查到是谁改的
|
|
880
|
+
if (typeof body.features.titleLock === 'boolean' && body.features.titleLock !== (loadConfig(configFile).features.titleLock !== false)) {
|
|
881
|
+
titleGenLog(dataRoot, `titleLock ${body.features.titleLock ? 'on' : 'off'}(此前为 ${!body.features.titleLock ? 'on' : 'off'})`);
|
|
882
|
+
}
|
|
883
|
+
applyFeaturesPartial(current.features, body.features);
|
|
884
|
+
}
|
|
885
|
+
if (body && typeof body === 'object' && typeof body.idleReclaimMinutes === 'number' && Number.isFinite(body.idleReclaimMinutes)) {
|
|
886
|
+
current.idleReclaimMinutes = Math.min(1440, Math.max(1, Math.round(body.idleReclaimMinutes)));
|
|
887
|
+
}
|
|
888
|
+
if (body && typeof body === 'object' && typeof body.idleReclaimStartupMinutes === 'number' && Number.isFinite(body.idleReclaimStartupMinutes)) {
|
|
889
|
+
current.idleReclaimStartupMinutes = Math.min(1440, Math.max(0, Math.round(body.idleReclaimStartupMinutes)));
|
|
890
|
+
}
|
|
891
|
+
if (body && typeof body === 'object' && body.styles && typeof body.styles === 'object') {
|
|
892
|
+
current.styles = applyStylesPartial(current.styles, body.styles);
|
|
893
|
+
}
|
|
894
|
+
// 会话快捷切换的键位(设置 → 快捷键里修改):键名固定,值限单个字母或数字
|
|
895
|
+
if (body && typeof body === 'object' && body.shortcuts && typeof body.shortcuts === 'object') {
|
|
896
|
+
const patch = {};
|
|
897
|
+
for (const k of ['switchLast', 'switchPrev', 'switchNext', 'switchRecent', 'switchAttention']) {
|
|
898
|
+
const v = body.shortcuts[k];
|
|
899
|
+
if (typeof v === 'string' && /^[a-z0-9]$/.test(v)) patch[k] = v;
|
|
492
900
|
}
|
|
493
|
-
|
|
901
|
+
current.shortcuts = { ...(current.shortcuts || {}), ...patch };
|
|
494
902
|
}
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
903
|
+
// 状态栏统计(设置 → 样式 → 状态栏):items(任务统计项)与
|
|
904
|
+
// turnItems(每轮统计项)两个清单各自整表覆盖,谁在请求里就更新谁;
|
|
905
|
+
// id 白名单 + 去重保序,未知项丢弃
|
|
906
|
+
if (body && typeof body === 'object' && body.statusBar && typeof body.statusBar === 'object') {
|
|
907
|
+
const next = { ...(current.statusBar || {}) };
|
|
908
|
+
if (Array.isArray(body.statusBar.items)) {
|
|
909
|
+
const valid = new Set(['ctx', 'tokRate', 'questions', 'todayTokens', 'totalTokens', 'tasks']);
|
|
910
|
+
const seen = new Set();
|
|
911
|
+
const items = [];
|
|
912
|
+
for (const it of body.statusBar.items) {
|
|
913
|
+
if (!it || !valid.has(it.id) || seen.has(it.id)) continue;
|
|
914
|
+
seen.add(it.id);
|
|
915
|
+
items.push({ id: it.id, on: it.on !== false });
|
|
916
|
+
}
|
|
917
|
+
next.items = items;
|
|
918
|
+
}
|
|
919
|
+
if (Array.isArray(body.statusBar.turnItems)) {
|
|
920
|
+
const turnValid = new Set(['turnIn', 'turnOut', 'turnCache']);
|
|
921
|
+
const tseen = new Set();
|
|
922
|
+
const turnItems = [];
|
|
923
|
+
for (const it of body.statusBar.turnItems) {
|
|
924
|
+
if (!it || !turnValid.has(it.id) || tseen.has(it.id)) continue;
|
|
925
|
+
tseen.add(it.id);
|
|
926
|
+
turnItems.push({ id: it.id, on: it.on !== false });
|
|
927
|
+
}
|
|
928
|
+
next.turnItems = turnItems;
|
|
503
929
|
}
|
|
504
|
-
|
|
930
|
+
current.statusBar = next;
|
|
931
|
+
}
|
|
932
|
+
// 主题(设置 → 样式 → 颜色/背景图):按字段合并,白名单校验在
|
|
933
|
+
// mergeThemeConfig;library 的 file 与 folder 的目录可能指向已不存在的
|
|
934
|
+
// 目标(图已删/目录移走/同步后缺失),注入层按“取不到 = 无背景”降级
|
|
935
|
+
if (body && typeof body === 'object' && body.theme && typeof body.theme === 'object') {
|
|
936
|
+
const bt = body.theme;
|
|
937
|
+
const cur = current.theme;
|
|
938
|
+
const next = {
|
|
939
|
+
skin: bt.skin !== undefined ? bt.skin : cur.skin,
|
|
940
|
+
custom: bt.custom !== undefined ? bt.custom : cur.custom,
|
|
941
|
+
bg: {
|
|
942
|
+
mode: bt.bg && bt.bg.mode !== undefined ? bt.bg.mode : cur.bg.mode,
|
|
943
|
+
file: bt.bg && bt.bg.file !== undefined ? bt.bg.file : cur.bg.file,
|
|
944
|
+
folder: bt.bg && bt.bg.folder !== undefined ? bt.bg.folder : cur.bg.folder,
|
|
945
|
+
folderRandom: bt.bg && bt.bg.folderRandom !== undefined ? bt.bg.folderRandom : cur.bg.folderRandom,
|
|
946
|
+
url: bt.bg && bt.bg.url !== undefined ? bt.bg.url : cur.bg.url,
|
|
947
|
+
intervalMin: bt.bg && bt.bg.intervalMin !== undefined ? bt.bg.intervalMin : cur.bg.intervalMin,
|
|
948
|
+
fit: bt.bg && bt.bg.fit !== undefined ? bt.bg.fit : cur.bg.fit,
|
|
949
|
+
maskOpacity: bt.bg && bt.bg.maskOpacity !== undefined ? bt.bg.maskOpacity : cur.bg.maskOpacity,
|
|
950
|
+
blurPx: bt.bg && bt.bg.blurPx !== undefined ? bt.bg.blurPx : cur.bg.blurPx,
|
|
951
|
+
panelOpacity: bt.bg && bt.bg.panelOpacity !== undefined ? bt.bg.panelOpacity : cur.bg.panelOpacity,
|
|
952
|
+
transition: bt.bg && bt.bg.transition !== undefined ? bt.bg.transition : cur.bg.transition,
|
|
953
|
+
fpsCap: bt.bg && bt.bg.fpsCap !== undefined ? bt.bg.fpsCap : cur.bg.fpsCap,
|
|
954
|
+
videoVolume: bt.bg && bt.bg.videoVolume !== undefined ? bt.bg.videoVolume : cur.bg.videoVolume,
|
|
955
|
+
playbackRate: bt.bg && bt.bg.playbackRate !== undefined ? bt.bg.playbackRate : cur.bg.playbackRate,
|
|
956
|
+
pauseOnHidden: bt.bg && bt.bg.pauseOnHidden !== undefined ? bt.bg.pauseOnHidden : cur.bg.pauseOnHidden,
|
|
957
|
+
pauseOnBlur: bt.bg && bt.bg.pauseOnBlur !== undefined ? bt.bg.pauseOnBlur : cur.bg.pauseOnBlur,
|
|
958
|
+
pauseOnBattery: bt.bg && bt.bg.pauseOnBattery !== undefined ? bt.bg.pauseOnBattery : cur.bg.pauseOnBattery,
|
|
959
|
+
dialogFrost: bt.bg && bt.bg.dialogFrost !== undefined ? bt.bg.dialogFrost : cur.bg.dialogFrost,
|
|
960
|
+
regions: bt.bg && bt.bg.regions !== undefined ? bt.bg.regions : cur.bg.regions,
|
|
961
|
+
},
|
|
962
|
+
};
|
|
963
|
+
current.theme = mergeThemeConfig(next);
|
|
964
|
+
}
|
|
965
|
+
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
966
|
+
current.titleGen = mergeTitleGenConfig({ ...current.titleGen, ...body.titleGen });
|
|
967
|
+
}
|
|
968
|
+
// 一次性迁移标记(如别名迁移弹窗的“暂不迁移”):按项合并,只接受布尔值
|
|
969
|
+
if (body && typeof body === 'object' && body.migrations && typeof body.migrations === 'object') {
|
|
970
|
+
const patch = {};
|
|
971
|
+
for (const [k, v] of Object.entries(body.migrations)) {
|
|
972
|
+
if (typeof v === 'boolean') patch[k] = v;
|
|
973
|
+
}
|
|
974
|
+
current.migrations = { ...(current.migrations || {}), ...patch };
|
|
975
|
+
}
|
|
976
|
+
if (!saveConfig(configFile, current)) {
|
|
977
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
json(res, 200, { ok: true, config: current });
|
|
981
|
+
});
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
// —— ZCode CLI 行为配置(设置 → 行为 → ZCode CLI):读写 ~/.zcode/cli/config.json
|
|
985
|
+
// 里的 skills / features 两组键,另附技能清单检查统计 ——
|
|
986
|
+
if (req.method === 'GET' && url.pathname === '/zcode-config') {
|
|
987
|
+
json(res, 200, zcodeConfigSnapshot(zcodeDataRoot()));
|
|
988
|
+
return;
|
|
989
|
+
}
|
|
990
|
+
if (req.method === 'POST' && url.pathname === '/zcode-config') {
|
|
991
|
+
const body = await readBody(req);
|
|
992
|
+
const file = join(zcodeDataRoot(), 'cli', 'config.json');
|
|
993
|
+
// 文件存在但解析失败时拒绝写入:按空对象重写会把 provider 等配置清掉
|
|
994
|
+
let cfg;
|
|
995
|
+
try {
|
|
996
|
+
cfg = JSON.parse(readFileSync(file, 'utf8'));
|
|
997
|
+
} catch {
|
|
998
|
+
if (existsSync(file)) {
|
|
999
|
+
json(res, 500, { ok: false, code: 'zcode-config-unreadable', error: 'ZCode 配置文件无法解析,已中止写入' });
|
|
1000
|
+
return;
|
|
505
1001
|
}
|
|
506
|
-
|
|
1002
|
+
cfg = {};
|
|
507
1003
|
}
|
|
508
|
-
//
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
if (
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
skin: bt.skin !== undefined ? bt.skin : cur.skin,
|
|
516
|
-
custom: bt.custom !== undefined ? bt.custom : cur.custom,
|
|
517
|
-
bg: {
|
|
518
|
-
mode: bt.bg && bt.bg.mode !== undefined ? bt.bg.mode : cur.bg.mode,
|
|
519
|
-
file: bt.bg && bt.bg.file !== undefined ? bt.bg.file : cur.bg.file,
|
|
520
|
-
folder: bt.bg && bt.bg.folder !== undefined ? bt.bg.folder : cur.bg.folder,
|
|
521
|
-
folderRandom: bt.bg && bt.bg.folderRandom !== undefined ? bt.bg.folderRandom : cur.bg.folderRandom,
|
|
522
|
-
url: bt.bg && bt.bg.url !== undefined ? bt.bg.url : cur.bg.url,
|
|
523
|
-
intervalMin: bt.bg && bt.bg.intervalMin !== undefined ? bt.bg.intervalMin : cur.bg.intervalMin,
|
|
524
|
-
fit: bt.bg && bt.bg.fit !== undefined ? bt.bg.fit : cur.bg.fit,
|
|
525
|
-
maskOpacity: bt.bg && bt.bg.maskOpacity !== undefined ? bt.bg.maskOpacity : cur.bg.maskOpacity,
|
|
526
|
-
blurPx: bt.bg && bt.bg.blurPx !== undefined ? bt.bg.blurPx : cur.bg.blurPx,
|
|
527
|
-
panelOpacity: bt.bg && bt.bg.panelOpacity !== undefined ? bt.bg.panelOpacity : cur.bg.panelOpacity,
|
|
528
|
-
regions: bt.bg && bt.bg.regions !== undefined ? bt.bg.regions : cur.bg.regions,
|
|
529
|
-
},
|
|
530
|
-
};
|
|
531
|
-
current.theme = mergeThemeConfig(next);
|
|
1004
|
+
// 只收白名单里类型正确的键;数组类的 roots 整组覆盖(空数组 = 清空)
|
|
1005
|
+
const s = body && typeof body === 'object' && body.skills && typeof body.skills === 'object' ? body.skills : {};
|
|
1006
|
+
const skillsPatch = {};
|
|
1007
|
+
if (typeof s.enabled === 'boolean') skillsPatch.enabled = s.enabled;
|
|
1008
|
+
if (typeof s.includeInstructions === 'boolean') skillsPatch.includeInstructions = s.includeInstructions;
|
|
1009
|
+
if (typeof s.metadataBudget === 'number' && Number.isFinite(s.metadataBudget) && s.metadataBudget >= 0 && s.metadataBudget <= 1000000) {
|
|
1010
|
+
skillsPatch.metadataBudget = Math.round(s.metadataBudget);
|
|
532
1011
|
}
|
|
533
|
-
if (
|
|
534
|
-
|
|
1012
|
+
if (Array.isArray(s.roots)) {
|
|
1013
|
+
skillsPatch.roots = s.roots.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim());
|
|
535
1014
|
}
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
const patch = {};
|
|
539
|
-
for (const [k, v] of Object.entries(body.migrations)) {
|
|
540
|
-
if (typeof v === 'boolean') patch[k] = v;
|
|
541
|
-
}
|
|
542
|
-
current.migrations = { ...(current.migrations || {}), ...patch };
|
|
1015
|
+
if (Object.keys(skillsPatch).length) {
|
|
1016
|
+
cfg.skills = { ...(cfg.skills && typeof cfg.skills === 'object' ? cfg.skills : {}), ...skillsPatch };
|
|
543
1017
|
}
|
|
544
|
-
|
|
545
|
-
|
|
1018
|
+
const f = body && typeof body === 'object' && body.features && typeof body.features === 'object' ? body.features : {};
|
|
1019
|
+
const featuresPatch = {};
|
|
1020
|
+
for (const k of ZCODE_FEATURE_KEYS) if (typeof f[k] === 'boolean') featuresPatch[k] = f[k];
|
|
1021
|
+
if (Object.keys(featuresPatch).length) {
|
|
1022
|
+
cfg.features = { ...(cfg.features && typeof cfg.features === 'object' ? cfg.features : {}), ...featuresPatch };
|
|
1023
|
+
}
|
|
1024
|
+
writeJsonAtomic(file, cfg); // 写的是 cli/config.json:不走 saveConfig 的 zcodepro.json 拒写保护
|
|
1025
|
+
json(res, 200, zcodeConfigSnapshot(zcodeDataRoot()));
|
|
546
1026
|
return;
|
|
547
1027
|
}
|
|
548
|
-
// —— 主题背景图库:列表 / base64 上传 /
|
|
1028
|
+
// —— 主题背景图库:列表 / base64 上传 / 删除(取文件见上方的 /bg/file,URL 带 ?t= token)——
|
|
549
1029
|
if (req.method === 'GET' && url.pathname === '/bg') {
|
|
550
1030
|
json(res, 200, { ok: true, files: listBgFiles(dataRoot), maxCount: BG_MAX_COUNT });
|
|
551
1031
|
return;
|
|
@@ -556,50 +1036,43 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
556
1036
|
const body = await readBody(req, 16 << 20);
|
|
557
1037
|
const name = sanitizeBgName(body?.name);
|
|
558
1038
|
const data = typeof body?.data === 'string' ? body.data : '';
|
|
559
|
-
if (!name) {
|
|
560
|
-
json(res, 400, { ok: false, code: 'bg-name', error: '
|
|
1039
|
+
if (!name || !BG_EXT.has(name.slice(name.lastIndexOf('.')).toLowerCase())) {
|
|
1040
|
+
json(res, 400, { ok: false, code: 'bg-name', error: '图片文件名需以 png/jpg/jpeg/webp/gif/bmp/avif 结尾,且不含路径' });
|
|
561
1041
|
return;
|
|
562
1042
|
}
|
|
563
1043
|
if (!/^data:image\/[a-z+]+;base64,/.test(data)) {
|
|
564
|
-
json(res, 400, { ok: false, code: 'bg-data', error: '
|
|
1044
|
+
json(res, 400, { ok: false, code: 'bg-data', error: '图片数据需为 data:image/*;base64 格式(视频走 /bg/upload)' });
|
|
565
1045
|
return;
|
|
566
1046
|
}
|
|
567
1047
|
const b64 = data.slice(data.indexOf(',') + 1);
|
|
568
1048
|
const buf = Buffer.from(b64, 'base64');
|
|
569
1049
|
if (!buf.length || buf.length > BG_MAX_BYTES) {
|
|
570
|
-
json(res, 400, { ok: false, code: 'bg-size', error:
|
|
1050
|
+
json(res, 400, { ok: false, code: 'bg-size', error: `图片需在 10MB 以内(收到 ${(buf.length / 1048576).toFixed(1)}MB)` });
|
|
571
1051
|
return;
|
|
572
1052
|
}
|
|
573
1053
|
const dir = backgroundsDir(dataRoot);
|
|
574
1054
|
const existing = listBgFiles(dataRoot);
|
|
575
1055
|
if (!existsSync(join(dir, name)) && existing.length >= BG_MAX_COUNT) {
|
|
576
|
-
json(res, 400, { ok: false, code: 'bg-count', error: `图库最多 ${BG_MAX_COUNT}
|
|
1056
|
+
json(res, 400, { ok: false, code: 'bg-count', error: `图库最多 ${BG_MAX_COUNT} 个文件,请先删除一些再上传` });
|
|
577
1057
|
return;
|
|
578
1058
|
}
|
|
579
1059
|
// 图片解码校验:文件头魔数匹配扩展名(防止把可执行文件改名成 png 上传)
|
|
580
|
-
const magicOk =
|
|
581
|
-
'.png': buf.slice(0, 8).toString('hex') === '89504e470d0a1a0a',
|
|
582
|
-
'.jpg': buf[0] === 0xff && buf[1] === 0xd8,
|
|
583
|
-
'.jpeg': buf[0] === 0xff && buf[1] === 0xd8,
|
|
584
|
-
'.gif': buf.slice(0, 3).toString('ascii') === 'GIF',
|
|
585
|
-
'.webp': buf.slice(0, 4).toString('ascii') === 'RIFF' && buf.slice(8, 12).toString('ascii') === 'WEBP',
|
|
586
|
-
'.bmp': buf[0] === 0x42 && buf[1] === 0x4d,
|
|
587
|
-
'.avif': buf.slice(4, 8).toString('ascii') === 'ftyp',
|
|
588
|
-
}[name.slice(name.lastIndexOf('.')).toLowerCase()];
|
|
1060
|
+
const magicOk = bgMagicOk(name, buf);
|
|
589
1061
|
if (!magicOk) {
|
|
590
1062
|
json(res, 400, { ok: false, code: 'bg-magic', error: '图片内容与扩展名不符' });
|
|
591
1063
|
return;
|
|
592
1064
|
}
|
|
593
1065
|
try {
|
|
594
1066
|
mkdirSync(dir, { recursive: true });
|
|
595
|
-
|
|
1067
|
+
// 临时名带 pid+随机:两个写者(上传/同步下载)撞同一文件名时不共用一个 .tmp
|
|
1068
|
+
const tmp = join(dir, `${name}.${process.pid}.${Date.now().toString(36)}.tmp`);
|
|
596
1069
|
writeFileSync(tmp, buf);
|
|
597
|
-
|
|
1070
|
+
renameOrReplace(tmp, join(dir, name));
|
|
598
1071
|
} catch (errBg) {
|
|
599
|
-
json(res, 500, { ok: false, code: 'bg-write', error: '
|
|
1072
|
+
json(res, 500, { ok: false, code: 'bg-write', error: '写入壁纸文件失败: ' + (errBg?.message || errBg) });
|
|
600
1073
|
return;
|
|
601
1074
|
}
|
|
602
|
-
json(res, 200, { ok: true, files: listBgFiles(dataRoot) });
|
|
1075
|
+
json(res, 200, { ok: true, name, files: listBgFiles(dataRoot) }); // 回传清洗后的落盘名:客户端选中态要按它存
|
|
603
1076
|
return;
|
|
604
1077
|
}
|
|
605
1078
|
if (req.method === 'POST' && url.pathname === '/bg/delete') {
|
|
@@ -608,21 +1081,156 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
608
1081
|
if (!name) { json(res, 400, { ok: false, code: 'bg-name', error: '非法文件名' }); return; }
|
|
609
1082
|
try {
|
|
610
1083
|
const file = join(backgroundsDir(dataRoot), name);
|
|
611
|
-
if (existsSync(file))
|
|
1084
|
+
if (existsSync(file)) {
|
|
1085
|
+
cleanupBgTranscode(dataRoot, file);
|
|
1086
|
+
unlinkOrDefer(file);
|
|
1087
|
+
}
|
|
1088
|
+
sweepDeferredBg(backgroundsDir(dataRoot));
|
|
1089
|
+
sweepDeferredBg(transcodeDir(dataRoot)); // 转码缓存里被删片时改名的 .deleted-* 也扫
|
|
612
1090
|
} catch (errBg) {
|
|
613
|
-
json(res, 500, { ok: false, code: 'bg-delete', error: '
|
|
1091
|
+
json(res, 500, { ok: false, code: 'bg-delete', error: '删除壁纸文件失败: ' + (errBg?.message || errBg) });
|
|
614
1092
|
return;
|
|
615
1093
|
}
|
|
616
1094
|
json(res, 200, { ok: true, files: listBgFiles(dataRoot) });
|
|
617
1095
|
return;
|
|
618
1096
|
}
|
|
1097
|
+
// —— 视频壁纸上传:raw 字节流直写文件(base64 会把内存翻倍,视频走这里)——
|
|
1098
|
+
if (req.method === 'POST' && url.pathname === '/bg/upload') {
|
|
1099
|
+
const name = sanitizeBgName(url.searchParams.get('name') || '');
|
|
1100
|
+
const ext = name ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
|
|
1101
|
+
if (!name || !VIDEO_EXT.has(ext)) {
|
|
1102
|
+
json(res, 400, { ok: false, code: 'bg-name', error: '视频文件名需以 mp4/webm/mov 结尾,且不含路径' });
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
const dir = backgroundsDir(dataRoot);
|
|
1106
|
+
const existing = listBgFiles(dataRoot);
|
|
1107
|
+
if (!existsSync(join(dir, name)) && existing.length >= BG_MAX_COUNT) {
|
|
1108
|
+
json(res, 400, { ok: false, code: 'bg-count', error: `图库最多 ${BG_MAX_COUNT} 个文件,请先删除一些再上传` });
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
let cleanupTmp = () => {};
|
|
1112
|
+
try {
|
|
1113
|
+
mkdirSync(dir, { recursive: true });
|
|
1114
|
+
// tmp 名带随机后缀:同名并发上传不共用一个临时文件互相写坏
|
|
1115
|
+
const tmp = join(dir, `${name}.${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}.tmp`);
|
|
1116
|
+
cleanupTmp = () => { try { unlinkSync(tmp); } catch { /* 未写入过就没有 */ } };
|
|
1117
|
+
const ws = createWriteStream(tmp);
|
|
1118
|
+
ws.on('error', () => {
|
|
1119
|
+
cleanupTmp();
|
|
1120
|
+
if (!res.writableEnded) json(res, 500, { ok: false, code: 'bg-write', error: '写入视频失败(磁盘或权限)' });
|
|
1121
|
+
});
|
|
1122
|
+
let size = 0;
|
|
1123
|
+
let head = Buffer.alloc(0);
|
|
1124
|
+
let overflow = false;
|
|
1125
|
+
for await (const chunk of req) {
|
|
1126
|
+
size += chunk.length;
|
|
1127
|
+
if (size > VIDEO_MAX_BYTES) {
|
|
1128
|
+
overflow = true; // 超限后排干剩余字节,直接 break 会销毁连接、400 到不了客户端
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
if (head.length < 16) head = Buffer.concat([head, chunk]).slice(0, 16);
|
|
1132
|
+
ws.write(chunk);
|
|
1133
|
+
}
|
|
1134
|
+
if (overflow) {
|
|
1135
|
+
try { ws.destroy(); } catch { /* ignore */ }
|
|
1136
|
+
cleanupTmp();
|
|
1137
|
+
json(res, 400, { ok: false, code: 'bg-size', error: `视频需在 ${VIDEO_MAX_BYTES / 1048576}MB 以内` });
|
|
1138
|
+
return;
|
|
1139
|
+
}
|
|
1140
|
+
// 等数据全部落盘再校验/改名:半截文件冒充成功是数据损坏
|
|
1141
|
+
await new Promise((resolveWait) => {
|
|
1142
|
+
if (ws.writableFinished) { resolveWait(); return; }
|
|
1143
|
+
ws.on('finish', resolveWait);
|
|
1144
|
+
ws.on('error', resolveWait); // 出错同样解除等待,不然请求处理函数永久挂起
|
|
1145
|
+
ws.end();
|
|
1146
|
+
});
|
|
1147
|
+
// 文件头魔数校验(防把可执行文件改名成 mp4 上传):mp4/mov 是 ftyp 盒,webm 是 EBML
|
|
1148
|
+
const magicOk = bgMagicOk(name, head);
|
|
1149
|
+
if (!size || !magicOk) {
|
|
1150
|
+
try { unlinkSync(tmp); } catch { /* ignore */ }
|
|
1151
|
+
json(res, 400, { ok: false, code: 'bg-magic', error: '视频内容与扩展名不符' });
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
renameOrReplace(tmp, join(dir, name));
|
|
1155
|
+
} catch (errBg) {
|
|
1156
|
+
cleanupTmp();
|
|
1157
|
+
if (!res.writableEnded) json(res, 500, { ok: false, code: 'bg-write', error: '写入视频失败: ' + (errBg?.message || errBg) });
|
|
1158
|
+
return;
|
|
1159
|
+
}
|
|
1160
|
+
json(res, 200, { ok: true, name, files: listBgFiles(dataRoot) });
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
// —— 视频帧率上限转码:起 ffmpeg 出抽帧版存缓存(key = 源路径+帧率的散列),
|
|
1164
|
+
// 注入层先播原片、转码完成再换;同一文件重复请求只起一个 ffmpeg
|
|
1165
|
+
if (req.method === 'POST' && url.pathname === '/bg/transcode') {
|
|
1166
|
+
const body = await readBody(req);
|
|
1167
|
+
const name = sanitizeBgName(body?.name || '');
|
|
1168
|
+
const ext = name ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
|
|
1169
|
+
const fps = Number(body?.fps);
|
|
1170
|
+
const dir = body?.from === 'folder' ? loadConfig(configFile).theme.bg.folder : backgroundsDir(dataRoot);
|
|
1171
|
+
const src = name && dir ? join(dir, name) : '';
|
|
1172
|
+
if (!src || !VIDEO_EXT.has(ext) || !existsSync(src)) {
|
|
1173
|
+
json(res, 400, { ok: false, code: 'transcode-src', error: '转码源视频无效' });
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
if (!TRANSCODE_FPS.has(fps)) {
|
|
1177
|
+
json(res, 400, { ok: false, code: 'transcode-fps', error: `帧率上限仅支持 ${[...TRANSCODE_FPS].join('/')}` });
|
|
1178
|
+
return;
|
|
1179
|
+
}
|
|
1180
|
+
const srcStat = statSync(src);
|
|
1181
|
+
// key 并入源文件大小与修改时间:同名覆盖后缓存自动失效重转
|
|
1182
|
+
const key = createHash('sha1').update(`${src}#${fps}#${srcStat.mtimeMs}#${srcStat.size}`).digest('hex').slice(0, 16);
|
|
1183
|
+
const out = join(transcodeDir(dataRoot), key + '.mp4');
|
|
1184
|
+
if (existsSync(out)) { json(res, 200, { ok: true, key, ready: true }); return; }
|
|
1185
|
+
if (!hasFfmpeg()) { json(res, 200, { ok: false, code: 'no-ffmpeg', error: '未检测到 ffmpeg,帧率上限不可用' }); return; }
|
|
1186
|
+
if (transcodeJobs.has(key)) { json(res, 200, { ok: true, key, ready: false }); return; }
|
|
1187
|
+
if (transcodeJobs.size >= TRANSCODE_MAX_CONCURRENCY) {
|
|
1188
|
+
// 并发满显式拒绝:让注入层本轮放弃,别空等 30 分钟轮询一个不会出现的文件
|
|
1189
|
+
json(res, 200, { ok: false, code: 'transcode-busy', error: '转码排队已满,稍后重试' });
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
if (true) {
|
|
1193
|
+
mkdirSync(transcodeDir(dataRoot), { recursive: true }); // 先建目录:同步抛错(磁盘满/无权限)不能把并发名额占住
|
|
1194
|
+
transcodeJobs.add(key);
|
|
1195
|
+
// 临时名必须保留 .mp4 后缀:ffmpeg 靠后缀识别容器,.tmp 会直接报
|
|
1196
|
+
// Unable to find a suitable output format(fpsCap 全程哑火的根因)
|
|
1197
|
+
const tmp = out + '.tmp.mp4';
|
|
1198
|
+
// 抽帧同时把长边压到 1920 以内:4K 素材按原始分辨率解码是视频壁纸
|
|
1199
|
+
// 发热/卡顿的大头,缩小后解码与合成开销成倍下降;小视频不放大
|
|
1200
|
+
const vf = `fps=${fps},scale=min(1920\\,iw):min(1920\\,ih):force_original_aspect_ratio=decrease`;
|
|
1201
|
+
let child;
|
|
1202
|
+
try {
|
|
1203
|
+
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 });
|
|
1204
|
+
transcodeChildren.add(child);
|
|
1205
|
+
} catch (errSpawn) {
|
|
1206
|
+
transcodeJobs.delete(key); // 同步抛错也把名额放掉
|
|
1207
|
+
throw errSpawn;
|
|
1208
|
+
}
|
|
1209
|
+
child.on('exit', (code) => {
|
|
1210
|
+
transcodeJobs.delete(key);
|
|
1211
|
+
transcodeChildren.delete(child);
|
|
1212
|
+
try {
|
|
1213
|
+
if (code === 0) renameOrReplace(tmp, out); // renameOrReplace 扛得住 Windows 文件占用
|
|
1214
|
+
else rmSync(tmp, { force: true });
|
|
1215
|
+
} catch { /* 缓存目录写失败:下次再试 */ }
|
|
1216
|
+
});
|
|
1217
|
+
child.on('error', () => { transcodeJobs.delete(key); transcodeChildren.delete(child); });
|
|
1218
|
+
// 看门狗直接 SIGKILL(与 jobRun 一致):ffmpeg 不退则 exit 不触发、转码名额泄漏
|
|
1219
|
+
const killTimer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* 已退出 */ } }, 30 * 60 * 1000);
|
|
1220
|
+
child.on('exit', () => clearTimeout(killTimer));
|
|
1221
|
+
}
|
|
1222
|
+
json(res, 200, { ok: true, key, ready: false });
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
619
1225
|
// —— 文件夹背景:设置/刷新列表(目录本身存 theme.bg.folder,文件原地读
|
|
620
1226
|
// 取不复制);切换由注入层定时驱动(随机或顺序)
|
|
621
1227
|
const listFolderBg = (dir) => {
|
|
622
1228
|
const st = statSync(dir);
|
|
623
1229
|
if (!st.isDirectory()) return { error: '不是文件夹:' + dir };
|
|
624
1230
|
const files = readdirSync(dir)
|
|
625
|
-
.filter((name) =>
|
|
1231
|
+
.filter((name) => MEDIA_EXT.has(name.slice(name.lastIndexOf('.')).toLowerCase()))
|
|
1232
|
+
// 名字过不了取文件时二次清洗的不列(列了也取不到,还会误命中清洗后同名的文件)
|
|
1233
|
+
.filter((name) => sanitizeBgName(name) === name)
|
|
626
1234
|
.map((name) => { const s = statSync(join(dir, name)); return { name, size: s.size, mtime: s.mtimeMs }; })
|
|
627
1235
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
628
1236
|
return { files };
|
|
@@ -644,9 +1252,14 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
644
1252
|
return;
|
|
645
1253
|
}
|
|
646
1254
|
if (req.method === 'GET' && url.pathname === '/bg/folder/list') {
|
|
647
|
-
// dir
|
|
1255
|
+
// dir 查询参数:分区背景列自己目录时传入;缺省列全局设置的目录。
|
|
1256
|
+
// dir 只认用户配置过的目录(与取文件路由同一判定),不合法与文件路由同款报错
|
|
648
1257
|
const qDir = url.searchParams.get('dir');
|
|
649
|
-
|
|
1258
|
+
if (qDir && !bgFolderDirAllowed(loadConfig(configFile).theme.bg, qDir)) {
|
|
1259
|
+
json(res, 400, { ok: false, error: 'dir 参数无效或未配置' });
|
|
1260
|
+
return;
|
|
1261
|
+
}
|
|
1262
|
+
const dir = qDir || loadConfig(configFile).theme.bg.folder;
|
|
650
1263
|
if (!dir || !existsSync(dir)) { json(res, 200, { ok: true, files: [], missing: true, dir: dir || '' }); return; }
|
|
651
1264
|
try {
|
|
652
1265
|
const r = listFolderBg(dir);
|
|
@@ -730,7 +1343,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
730
1343
|
}
|
|
731
1344
|
if (req.method === 'POST' && url.pathname === '/project/alias') {
|
|
732
1345
|
const body = await readBody(req);
|
|
733
|
-
json(res, ...setAlias(body, configFile));
|
|
1346
|
+
json(res, ...(await setAlias(body, configFile)));
|
|
734
1347
|
return;
|
|
735
1348
|
}
|
|
736
1349
|
if (req.method === 'POST' && url.pathname === '/project/relocate') {
|
|
@@ -745,8 +1358,9 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
745
1358
|
json(res, 200, { ok: true, ...(await pickFolderSystem(start, title)) });
|
|
746
1359
|
return;
|
|
747
1360
|
}
|
|
748
|
-
// 会话拖动排序持久化:
|
|
749
|
-
//
|
|
1361
|
+
// 会话拖动排序持久化:hint = 拖动落点所在的列表(project/pinned/section,
|
|
1362
|
+
// 缺省按数据判定),旧注入包的 scope(workspace/group-members)回退认作 hint;
|
|
1363
|
+
// 工作区列表重盖 updated_at,分组会话重写 members.sort_order
|
|
750
1364
|
if (req.method === 'POST' && url.pathname === '/task-order') {
|
|
751
1365
|
const body = await readBody(req);
|
|
752
1366
|
const ordered = Array.isArray(body?.ordered) ? body.ordered.filter((k) => typeof k === 'string') : [];
|
|
@@ -754,13 +1368,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
754
1368
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'ordered 不能为空' });
|
|
755
1369
|
return;
|
|
756
1370
|
}
|
|
757
|
-
|
|
758
|
-
if (body.scope === 'workspace') result = await reorderWorkspaceTasks(dataRoot, ordered);
|
|
759
|
-
else if (body.scope === 'group-members') result = await reorderGroupMembers(dataRoot, ordered);
|
|
760
|
-
else {
|
|
761
|
-
json(res, 400, { ok: false, code: 'invalid-request', error: '无效的 scope' });
|
|
762
|
-
return;
|
|
763
|
-
}
|
|
1371
|
+
const result = await reorderTasks(dataRoot, ordered, body.hint ?? body.scope);
|
|
764
1372
|
if (result.error) {
|
|
765
1373
|
json(res, 400, { ok: false, code: result.code, error: result.error });
|
|
766
1374
|
return;
|
|
@@ -796,29 +1404,36 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
796
1404
|
if (req.method === 'POST' && url.pathname === '/title-gen') {
|
|
797
1405
|
const body = await readBody(req);
|
|
798
1406
|
if (body && typeof body === 'object' && body.titleGen && typeof body.titleGen === 'object') {
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
const found = listTitleGenProviders().find((p) => p.id === providerId);
|
|
807
|
-
if (found) {
|
|
808
|
-
next.baseUrl = found.baseUrl;
|
|
809
|
-
next.apiKey = found.apiKey;
|
|
810
|
-
next.format = found.format;
|
|
811
|
-
}
|
|
812
|
-
// 找不到(手输 id 或已删):保留原有副本字段不动
|
|
813
|
-
} else if (providerId === 'session') {
|
|
1407
|
+
// 读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
1408
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
1409
|
+
await withConfigLock(configFile, () => {
|
|
1410
|
+
const current = loadConfig(configFile);
|
|
1411
|
+
const next = { ...current.titleGen, ...body.titleGen };
|
|
1412
|
+
// 选了列表内供应商:同步解析并保存其地址/密钥/协议副本——供应商日后
|
|
1413
|
+
// 被删,这份副本仍可直连(界面标注“已删除”并展开字段);
|
|
814
1414
|
// 跟随会话不存副本(每次调用时按该会话实时解析)
|
|
815
|
-
next.
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
1415
|
+
const providerId = (next.provider || '').trim();
|
|
1416
|
+
if (providerId && providerId !== 'session') {
|
|
1417
|
+
const found = listTitleGenProviders().find((p) => p.id === providerId);
|
|
1418
|
+
if (found) {
|
|
1419
|
+
next.baseUrl = found.baseUrl;
|
|
1420
|
+
next.apiKey = found.apiKey;
|
|
1421
|
+
next.format = found.format;
|
|
1422
|
+
}
|
|
1423
|
+
// 找不到(手输 id 或已删):保留原有副本字段不动
|
|
1424
|
+
} else if (providerId === 'session') {
|
|
1425
|
+
// 跟随会话不存副本(每次调用时按该会话实时解析)
|
|
1426
|
+
next.baseUrl = '';
|
|
1427
|
+
next.apiKey = '';
|
|
1428
|
+
next.format = '';
|
|
1429
|
+
}
|
|
1430
|
+
current.titleGen = mergeTitleGenConfig(next);
|
|
1431
|
+
if (!saveConfig(configFile, current)) {
|
|
1432
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1433
|
+
return;
|
|
1434
|
+
}
|
|
1435
|
+
json(res, 200, { ok: true, titleGen: current.titleGen });
|
|
1436
|
+
});
|
|
822
1437
|
return;
|
|
823
1438
|
}
|
|
824
1439
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'body 需包含 titleGen 对象' });
|
|
@@ -867,66 +1482,74 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
867
1482
|
json(res, 200, { ok: true, title, written: false, store: 'skipped: overridden' });
|
|
868
1483
|
return;
|
|
869
1484
|
}
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
// CLI 库不可写(旧版无 title_source 列 / 无该会话行)不阻断:退回
|
|
875
|
-
// 单写任务索引的旧行为;任务索引随后失败也不回滚 CLI——同步器会补
|
|
876
|
-
for (let attempt = 0; ; attempt++) {
|
|
877
|
-
try {
|
|
878
|
-
const r = await setCustomSessionTitle(dataRoot, sessId, title);
|
|
879
|
-
store = r.written ? '' : (r.skipped || 'skipped');
|
|
880
|
-
break;
|
|
881
|
-
} catch (err) {
|
|
882
|
-
if (err.code === 'index-busy' && attempt < 2) {
|
|
883
|
-
await new Promise((r) => setTimeout(r, 1200));
|
|
884
|
-
continue;
|
|
885
|
-
}
|
|
886
|
-
store = 'error: ' + (err?.message || err);
|
|
887
|
-
titleGenLog(dataRoot, `cli-store-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
888
|
-
break;
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
// 写库撞上宿主写入时稍候重试(起名不急这几秒)
|
|
892
|
-
for (let attempt = 0; ; attempt++) {
|
|
893
|
-
try {
|
|
894
|
-
const r = await setTaskTitleIfNotOverridden(dataRoot, sessId, title);
|
|
895
|
-
written = r.written;
|
|
896
|
-
break;
|
|
897
|
-
} catch (err) {
|
|
898
|
-
if (err.code === 'index-busy' && attempt < 2) {
|
|
899
|
-
await new Promise((r) => setTimeout(r, 1200));
|
|
900
|
-
continue;
|
|
901
|
-
}
|
|
902
|
-
titleGenLog(dataRoot, `index-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
903
|
-
json(res, 500, { ok: false, code: err.code || 'index-error', error: err.message });
|
|
904
|
-
return;
|
|
905
|
-
}
|
|
1485
|
+
const r = await writeGeneratedTitle(dataRoot, configFile, sessId, title);
|
|
1486
|
+
if (r.error) {
|
|
1487
|
+
json(res, 500, { ok: false, code: r.error.code || 'index-error', error: r.error.message });
|
|
1488
|
+
return;
|
|
906
1489
|
}
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
if (sessId && store === '') {
|
|
910
|
-
const c = loadConfig(configFile);
|
|
911
|
-
c.titleGen.customWritten = { ...(c.titleGen.customWritten || {}), [sessId]: { title, at: Date.now() } };
|
|
912
|
-
saveConfig(configFile, c);
|
|
1490
|
+
written = r.written;
|
|
1491
|
+
store = r.store;
|
|
913
1492
|
}
|
|
914
1493
|
json(res, 200, { ok: true, title, written, store });
|
|
915
1494
|
return;
|
|
916
1495
|
}
|
|
1496
|
+
// 手动自动重命名(任务行悬浮按钮 / 右键菜单入口):取会话最近 N 轮问答按
|
|
1497
|
+
// 提示词生成标题并按“手动重命名”写库。用户显式动作:已重命名过也照写
|
|
1498
|
+
//(force),不受启用开关限制(入口各有开关);生成失败交外层统一 500
|
|
1499
|
+
if (req.method === 'POST' && url.pathname === '/title-gen/rename') {
|
|
1500
|
+
const body = await readBody(req);
|
|
1501
|
+
const sessId = typeof body?.sessId === 'string' && /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(body.sessId) ? body.sessId : '';
|
|
1502
|
+
if (!sessId) {
|
|
1503
|
+
json(res, 400, { ok: false, code: 'invalid-request', error: 'sessId 不能为空' });
|
|
1504
|
+
return;
|
|
1505
|
+
}
|
|
1506
|
+
const cfg = loadConfig(configFile).titleGen;
|
|
1507
|
+
let material;
|
|
1508
|
+
try {
|
|
1509
|
+
material = await readRecentQa(dataRoot, sessId, cfg.recentQa);
|
|
1510
|
+
} catch (err) {
|
|
1511
|
+
titleGenLog(dataRoot, `rename-read-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1512
|
+
json(res, 500, { ok: false, code: 'read-error', error: err?.message || '读取会话内容失败' });
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
if (!material) {
|
|
1516
|
+
json(res, 200, { ok: false, code: 'no-content', error: '会话还没有问答内容' });
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
let title;
|
|
1520
|
+
try {
|
|
1521
|
+
title = await generateTitleWith(cfg, material, dataRoot, sessId);
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
titleGenLog(dataRoot, `rename-generate-failed sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
1524
|
+
throw err; // 交给外层统一 500
|
|
1525
|
+
}
|
|
1526
|
+
const r = await writeGeneratedTitle(dataRoot, configFile, sessId, title, { force: true });
|
|
1527
|
+
if (r.error) {
|
|
1528
|
+
json(res, 500, { ok: false, code: r.error.code || 'index-error', error: r.error.message });
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
json(res, 200, { ok: true, title, written: r.written, store: r.store });
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
917
1534
|
// —— zcode-vision 插件(图片视觉代理):设置弹窗“视觉代理”标签页读写 ————
|
|
918
1535
|
if (req.method === 'GET' && url.pathname === '/vision') {
|
|
919
|
-
const file =
|
|
1536
|
+
const file = visionFile;
|
|
920
1537
|
let parsed = readJsonFile(file);
|
|
921
1538
|
// 装了 zcode-pro 默认启用识图卡片(插件纯安装默认关,纯文本展示):
|
|
922
1539
|
// 只补从未写过的配置,用户显式设过 cardUi(含 false)不覆盖
|
|
923
1540
|
if (parsed && typeof parsed === 'object' && !('cardUi' in parsed)) {
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
1541
|
+
// 写前重读一次拿最新值合并:与插件侧的模板升级等写方并发时,
|
|
1542
|
+
// 拿读取时的旧快照整份写回会把对方刚写的键盖掉
|
|
1543
|
+
const fresh = readJsonFile(file);
|
|
1544
|
+
const base = (fresh && typeof fresh === 'object') ? fresh : parsed;
|
|
1545
|
+
if (!('cardUi' in base)) {
|
|
1546
|
+
const merged = { ...base, cardUi: true };
|
|
1547
|
+
try {
|
|
1548
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者撕裂
|
|
1549
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
1550
|
+
renameSync(tmp, file);
|
|
1551
|
+
} catch { /* 补写失败下次再试,不阻塞读取 */ }
|
|
1552
|
+
}
|
|
930
1553
|
}
|
|
931
1554
|
if (parsed === null && existsSync(file)) {
|
|
932
1555
|
json(res, 500, { ok: false, code: 'vision-read', error: 'zcode-vision.json 不是合法 JSON' });
|
|
@@ -943,13 +1566,15 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
943
1566
|
return;
|
|
944
1567
|
}
|
|
945
1568
|
try {
|
|
946
|
-
const file =
|
|
1569
|
+
const file = visionFile;
|
|
947
1570
|
// 与磁盘旧配置合并(本块曾两次被并发改动覆盖回全量覆盖):前端按自己
|
|
948
1571
|
// 的字段重建整份配置,直接覆盖会丢插件新增、面板还不认识的键
|
|
949
1572
|
//(cardSandboxBudget/cardUi/interceptMode 等)
|
|
950
1573
|
const merged = { ...(readJsonFile(file) || {}), ...cfg };
|
|
951
|
-
|
|
952
|
-
|
|
1574
|
+
// forceIntercept 为 null = 面板选了「自动」:从磁盘配置删掉该键,恢复插件缺省联动
|
|
1575
|
+
if (cfg.forceIntercept === null) delete merged.forceIntercept;
|
|
1576
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者撕裂
|
|
1577
|
+
writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
|
|
953
1578
|
renameSync(tmp, file);
|
|
954
1579
|
} catch (err2) {
|
|
955
1580
|
json(res, 500, { ok: false, code: 'vision-write', error: '写入 zcode-vision.json 失败: ' + (err2?.message || err2) });
|
|
@@ -1169,9 +1794,15 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1169
1794
|
return;
|
|
1170
1795
|
} else if (body && 'interval' in body) {
|
|
1171
1796
|
try {
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1797
|
+
// 只改 powerWatchInterval 一个键:readHeadroomConfig 会把非规范值归一
|
|
1798
|
+
// 成默认值(插件侧是宽松读法),整份写回会把 backend 之类的本机值打回默认。
|
|
1799
|
+
// 套配置锁:与同步导入、setHeadroomUsage 等自家写方互斥(插件侧写方走
|
|
1800
|
+
// 它自己的生命周期锁,两边共存仍留极小窗口,写回本身是原子改名兜底)
|
|
1801
|
+
await withConfigLock(file, () => {
|
|
1802
|
+
const cfg = readJsonFile(file) || {};
|
|
1803
|
+
cfg.powerWatchInterval = clampInt(body.interval, 10, 3600, Number(cfg.powerWatchInterval) || 60);
|
|
1804
|
+
writeHeadroomConfig(file, cfg);
|
|
1805
|
+
});
|
|
1175
1806
|
} catch (err) {
|
|
1176
1807
|
json(res, 500, { ok: false, code: 'headroom-write', error: '写入 headroom.json 失败: ' + (err?.message || err) });
|
|
1177
1808
|
return;
|
|
@@ -1194,8 +1825,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1194
1825
|
// 源码目录(有 package.json 与 esbuild)先构建,安装副本没有构建环境则跳过
|
|
1195
1826
|
let built = false;
|
|
1196
1827
|
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
1197
|
-
|
|
1198
|
-
|
|
1828
|
+
// Windows 上优先 esbuild.exe:无扩展名的 bin/esbuild 是 JS 垫片,spawnSync 跑不起来
|
|
1829
|
+
const esbuildNames = process.platform === 'win32' ? ['esbuild.exe', 'esbuild'] : ['esbuild', 'esbuild.exe'];
|
|
1830
|
+
const esbuildBin = esbuildNames
|
|
1831
|
+
.map((n) => join(repoRoot, 'node_modules', 'esbuild', 'bin', n))
|
|
1199
1832
|
.find((p) => existsSync(p)) || '';
|
|
1200
1833
|
if (esbuildBin) {
|
|
1201
1834
|
try {
|
|
@@ -1216,7 +1849,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1216
1849
|
});
|
|
1217
1850
|
child.unref();
|
|
1218
1851
|
} catch { /* 拉不起来就只能等下次手动重启 */ }
|
|
1219
|
-
setTimeout(() =>
|
|
1852
|
+
setTimeout(() => {
|
|
1853
|
+
try { dispose(); } catch { /* ignore */ } // 收掉残留 ffmpeg 子进程,防孤儿与新实例抢写缓存
|
|
1854
|
+
process.exit(0);
|
|
1855
|
+
}, 250);
|
|
1220
1856
|
}, 150);
|
|
1221
1857
|
return;
|
|
1222
1858
|
}
|
|
@@ -1297,22 +1933,29 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1297
1933
|
}
|
|
1298
1934
|
if (req.method === 'POST' && url.pathname === '/sync') {
|
|
1299
1935
|
const body = await readBody(req);
|
|
1300
|
-
|
|
1301
|
-
//
|
|
1302
|
-
|
|
1303
|
-
const
|
|
1304
|
-
|
|
1305
|
-
|
|
1936
|
+
// 读改写(loadConfig→改→saveConfig)放进跨进程锁内同步执行,
|
|
1937
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
1938
|
+
await withConfigLock(configFile, () => {
|
|
1939
|
+
const current = loadConfig(configFile);
|
|
1940
|
+
// 表单(类型/URL/登录/密码)与同步内容开关分开提交:表单全量替换,开关只改单项
|
|
1941
|
+
if (body && typeof body === 'object' && body.sync && typeof body.sync === 'object') {
|
|
1942
|
+
const v = validateSyncForm(body.sync);
|
|
1943
|
+
if (v.error) {
|
|
1944
|
+
json(res, 400, { ok: false, code: 'sync-invalid', error: v.error });
|
|
1945
|
+
return;
|
|
1946
|
+
}
|
|
1947
|
+
Object.assign(current.sync, v.sync);
|
|
1948
|
+
}
|
|
1949
|
+
if (body && typeof body === 'object' && body.include && typeof body.include === 'object') {
|
|
1950
|
+
if (typeof body.include.zcodepro === 'boolean') current.sync.include.zcodepro = body.include.zcodepro;
|
|
1951
|
+
if (typeof body.include.model === 'boolean') current.sync.include.model = body.include.model;
|
|
1952
|
+
}
|
|
1953
|
+
if (!saveConfig(configFile, current)) {
|
|
1954
|
+
json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' });
|
|
1306
1955
|
return;
|
|
1307
1956
|
}
|
|
1308
|
-
|
|
1309
|
-
}
|
|
1310
|
-
if (body && typeof body === 'object' && body.include && typeof body.include === 'object') {
|
|
1311
|
-
if (typeof body.include.zcodepro === 'boolean') current.sync.include.zcodepro = body.include.zcodepro;
|
|
1312
|
-
if (typeof body.include.model === 'boolean') current.sync.include.model = body.include.model;
|
|
1313
|
-
}
|
|
1314
|
-
saveConfig(configFile, current);
|
|
1315
|
-
json(res, 200, { ok: true, sync: current.sync });
|
|
1957
|
+
json(res, 200, { ok: true, sync: current.sync });
|
|
1958
|
+
});
|
|
1316
1959
|
return;
|
|
1317
1960
|
}
|
|
1318
1961
|
if (req.method === 'POST' && url.pathname === '/sync/run') {
|
|
@@ -1322,8 +1965,12 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1322
1965
|
json(res, 400, { ok: false, code: 'invalid-request', error: 'direction 只能是 push 或 pull' });
|
|
1323
1966
|
return;
|
|
1324
1967
|
}
|
|
1325
|
-
|
|
1326
|
-
|
|
1968
|
+
// 同 direction 的并发触发共用同一次执行结果(见 enqueueSyncRun),
|
|
1969
|
+
// 不同 direction 串行排队
|
|
1970
|
+
const r = await enqueueSyncRun(direction, async () => {
|
|
1971
|
+
const cfg = loadConfig(configFile);
|
|
1972
|
+
return runSettingsSync({ direction, dataRoot, configFile, config: cfg, proxyUrl: proxyUrlFor('sync') });
|
|
1973
|
+
});
|
|
1327
1974
|
if (r.error) {
|
|
1328
1975
|
json(res, r.status || 500, { ok: false, code: r.code || 'sync-run', error: r.error });
|
|
1329
1976
|
return;
|
|
@@ -1357,6 +2004,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1357
2004
|
json(res, 400, { ok: false, code: 'sync-not-configured', error: '请先填写 WebDAV URL 并保存' });
|
|
1358
2005
|
return;
|
|
1359
2006
|
}
|
|
2007
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2008
|
+
json(res, 400, { ok: false, code: 'sync-not-configured', error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' });
|
|
2009
|
+
return;
|
|
2010
|
+
}
|
|
1360
2011
|
const r = await listSyncVersions(sync, proxyUrlFor('sync'));
|
|
1361
2012
|
if (r.error) {
|
|
1362
2013
|
json(res, r.status || 500, { ok: false, code: r.code || 'sync-request', error: r.error });
|
|
@@ -1384,6 +2035,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1384
2035
|
json(res, 400, { ok: false, code: 'sync-not-configured', error: '请先填写 WebDAV URL 并保存' });
|
|
1385
2036
|
return;
|
|
1386
2037
|
}
|
|
2038
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2039
|
+
json(res, 400, { ok: false, code: 'sync-not-configured', error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' });
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
1387
2042
|
const remoteMissing = () => json(res, 404, { ok: false, code: 'sync-remote-missing', error: `云端文件 ${file} 不存在(可能已被删除)` });
|
|
1388
2043
|
if (action === 'apply') {
|
|
1389
2044
|
const remote = await fetchSyncNamedDoc(sync, proxyUrlFor('sync'), file);
|
|
@@ -1398,6 +2053,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1398
2053
|
const kind = file.startsWith('model') ? 'model' : 'zcodepro';
|
|
1399
2054
|
sync.lastPullAt = Date.now();
|
|
1400
2055
|
const r = applySyncDocs({ docs: { [kind]: remote.doc.data }, dataRoot, configFile, config, sync });
|
|
2056
|
+
if (r && r.error) {
|
|
2057
|
+
json(res, r.status || 500, { ok: false, code: r.code, error: r.error });
|
|
2058
|
+
return;
|
|
2059
|
+
}
|
|
1401
2060
|
json(res, 200, { ok: true, applied: r.applied, sync: loadConfig(configFile).sync });
|
|
1402
2061
|
return;
|
|
1403
2062
|
}
|
|
@@ -1446,7 +2105,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1446
2105
|
return;
|
|
1447
2106
|
}
|
|
1448
2107
|
try {
|
|
1449
|
-
writeFileSync(target, r.body, 'utf8');
|
|
2108
|
+
writeFileSync(target, r.body, { encoding: 'utf8', mode: 0o600 }); // 导出内容含明文 apiKey,限制本人读写
|
|
2109
|
+
try { chmodSync(target, 0o600); } catch { /* 覆盖同名旧文件时 mode 不生效,补一次 */ }
|
|
1450
2110
|
} catch (err) {
|
|
1451
2111
|
json(res, 500, { ok: false, code: 'sync-export', error: `写入 ${target} 失败: ${err?.message || err}` });
|
|
1452
2112
|
return;
|
|
@@ -1459,8 +2119,13 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1459
2119
|
// model-io-*.jsonl 每行一次模型调用,response.usage 有分项 token;成本字段
|
|
1460
2120
|
// 官方未落本地,成本类统计项由注入侧按“无数据自动隐藏”处理
|
|
1461
2121
|
if (req.method === 'GET' && url.pathname === '/stats/usage') {
|
|
1462
|
-
|
|
1463
|
-
|
|
2122
|
+
// 会话 id 校验同 sessId 白名单:不像会话 id 的一律按全局口径处理
|
|
2123
|
+
//(降级后注入侧仍按“本会话”展示全局速率,官方改 key 格式时才会踩到)
|
|
2124
|
+
const rawSid = url.searchParams.get('session') || '';
|
|
2125
|
+
const sessionId = /^(?:sess|session)_[A-Za-z0-9._-]+$/.test(rawSid) ? rawSid : '';
|
|
2126
|
+
// turns=0 跳过分钟桶聚合(状态栏只读 global,不白建每轮桶)
|
|
2127
|
+
const wantTurns = url.searchParams.get('turns') !== '0';
|
|
2128
|
+
const { global, recentTurns } = collectUsageStats(sessionId, wantTurns);
|
|
1464
2129
|
// 任务总数 60 秒缓存:状态栏每 2 秒请求一次,不必每次开关 SQLite
|
|
1465
2130
|
if (Date.now() - tasksCountAt > 60_000) {
|
|
1466
2131
|
tasksCountAt = Date.now();
|
|
@@ -1471,12 +2136,19 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1471
2136
|
return;
|
|
1472
2137
|
}
|
|
1473
2138
|
if (req.method === 'GET' && url.pathname === '/plugins/status') {
|
|
1474
|
-
|
|
1475
|
-
//
|
|
1476
|
-
//
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
2139
|
+
// 市场同步与更新任务共用同一条串行队列,不能绕过它:两处同时 clone/pull
|
|
2140
|
+
// 同一个市场目录会互相删对方的中间目录(ENOENT/坏目录)。
|
|
2141
|
+
// 有更新任务在跑/排队时整个跳过(任务自身会做市场同步并刷新时间戳),
|
|
2142
|
+
// 状态页轮询不排队等待、不能被长任务挂住;检查与入队在同一同步段内完成
|
|
2143
|
+
if (!pluginsUpdateJobs.size) {
|
|
2144
|
+
await runPluginsQueued(async () => {
|
|
2145
|
+
await ensureZcodePluginsMarketplace();
|
|
2146
|
+
if (Date.now() - lastMarketplaceSync > 30 * 60 * 1000) {
|
|
2147
|
+
await ensureZcodePluginsCloneFresh();
|
|
2148
|
+
await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
|
|
2149
|
+
lastMarketplaceSync = Date.now();
|
|
2150
|
+
}
|
|
2151
|
+
});
|
|
1480
2152
|
}
|
|
1481
2153
|
const status = pluginUpdateStatus();
|
|
1482
2154
|
if (!status) {
|
|
@@ -1494,19 +2166,22 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1494
2166
|
}
|
|
1495
2167
|
json(res, 404, { ok: false, error: 'not found' });
|
|
1496
2168
|
} catch (err) {
|
|
1497
|
-
|
|
2169
|
+
// 完整错误只进日志;响应里的消息抹掉主目录前缀,别把本机路径结构带出去
|
|
2170
|
+
console.error('[zcodepro] 路由处理出错:', err);
|
|
2171
|
+
json(res, 500, { ok: false, error: String(err?.message || err).split(homedir()).join('~') });
|
|
1498
2172
|
}
|
|
1499
2173
|
});
|
|
1500
2174
|
|
|
1501
2175
|
// 端口被占时重试:开发重载的交接窗口内,旧进程退出略晚于新进程启动,
|
|
1502
|
-
//
|
|
2176
|
+
// 新进程在这里等它让出端口(默认最多 20 秒),而不是启动失败;
|
|
2177
|
+
// 热替换路径传小的 listenTries,别把启动器主循环卡在这里
|
|
1503
2178
|
return new Promise((resolveStarted, rejectStarted) => {
|
|
1504
2179
|
let attempts = 0;
|
|
1505
2180
|
const tryListen = () => {
|
|
1506
2181
|
attempts += 1;
|
|
1507
2182
|
server.removeAllListeners('error');
|
|
1508
2183
|
server.once('error', (err) => {
|
|
1509
|
-
if (err && err.code === 'EADDRINUSE' && attempts <
|
|
2184
|
+
if (err && err.code === 'EADDRINUSE' && attempts < listenTries) {
|
|
1510
2185
|
try { server.close(); } catch { /* ignore */ }
|
|
1511
2186
|
setTimeout(tryListen, 500);
|
|
1512
2187
|
return;
|
|
@@ -1516,17 +2191,17 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
|
|
|
1516
2191
|
// 启动即补视觉配置缺省键:装了 zcode-pro ⇒ cardUi=true(识图卡片开,缺省
|
|
1517
2192
|
// 才补、显式设过不动,规则同 GET /vision),不必等用户打开视觉设置页
|
|
1518
2193
|
try {
|
|
1519
|
-
const vFile =
|
|
2194
|
+
const vFile = visionFile;
|
|
1520
2195
|
const vParsed = readJsonFile(vFile);
|
|
1521
2196
|
if (vParsed && typeof vParsed === 'object' && !('cardUi' in vParsed)) {
|
|
1522
2197
|
vParsed.cardUi = true;
|
|
1523
|
-
const vTmp = vFile
|
|
1524
|
-
writeFileSync(vTmp, JSON.stringify(vParsed, null, 2) + '\n', 'utf-8');
|
|
2198
|
+
const vTmp = `${vFile}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
2199
|
+
writeFileSync(vTmp, JSON.stringify(vParsed, null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 }); // 文件里有明文 apiKey,限制本人读写
|
|
1525
2200
|
renameSync(vTmp, vFile);
|
|
1526
2201
|
}
|
|
1527
2202
|
} catch { /* 无配置或不可写不影响启动 */ }
|
|
1528
2203
|
// 服务就绪即安排 headroom 代理兜底(内部延迟 5 秒执行,避开启动高峰)
|
|
1529
|
-
server.listen(port, '127.0.0.1', () => { ensureHeadroomAtStartup(); resolveStarted(server); });
|
|
2204
|
+
server.listen(port, '127.0.0.1', () => { ensureHeadroomAtStartup(state); resolveStarted(server); });
|
|
1530
2205
|
};
|
|
1531
2206
|
tryListen();
|
|
1532
2207
|
});
|
|
@@ -1541,7 +2216,28 @@ let tasksCountCache = 0; // 任务总数缓存(/stats/usage 高频轮询,60
|
|
|
1541
2216
|
// ~/.zcode/cli/rollout/model-io-*.jsonl 每行一次模型调用;usage 字段有两种键风格
|
|
1542
2217
|
// (协议 camelCase 与原始 snake_case),两种都解析。文件小(个位数、每会话一个),
|
|
1543
2218
|
// 按 mtime+size 缓存只重读变过的文件;聚合结果含按日分桶(本地时区)供“今日”用
|
|
1544
|
-
const usageFileCache = new Map(); // 文件名 → { mtime, size, recs: [{at, in, out,
|
|
2219
|
+
const usageFileCache = new Map(); // 文件名 → { mtime, size, recs: [{at, ts, ms, in, out, cacheRead, session}] }
|
|
2220
|
+
// 测试缝:覆盖 rollout 记录目录(scripts/test-usage-stats.mjs 用假数据跑真实聚合)
|
|
2221
|
+
let rolloutDirOverride = '';
|
|
2222
|
+
// 记录合并结果缓存:文件签名(名称+mtime+size)没变就直接复用上次合并好的记录
|
|
2223
|
+
let rolloutSig = '';
|
|
2224
|
+
let rolloutRecsCache = null;
|
|
2225
|
+
// 聚合结果缓存:同文件签名 + 同查询参数(含本地日期)直接复用,
|
|
2226
|
+
// /stats/usage 2 秒轮询不用每次全量重聚合十万级记录
|
|
2227
|
+
let statsResultCache = { sig: '', key: '', result: null };
|
|
2228
|
+
// 供启动器热替换前调用:旧模块实例被 ESM 模块表永久持有,清掉大块缓存省内存
|
|
2229
|
+
export function dispose() {
|
|
2230
|
+
usageFileCache.clear();
|
|
2231
|
+
rolloutRecsCache = null; // 合并后的全量记录数组(可达十万级),不留
|
|
2232
|
+
rolloutSig = '';
|
|
2233
|
+
statsResultCache = { sig: '', key: '', result: null };
|
|
2234
|
+
// 残留的 ffmpeg 转码子进程一并收掉(退出/交接时调用):孤儿进程会与新实例
|
|
2235
|
+
// 并发写同一个 .tmp.mp4 写坏缓存且不再重建;杀掉只会丢半截临时文件,重启后重建
|
|
2236
|
+
for (const child of transcodeChildren) {
|
|
2237
|
+
try { child.kill(); } catch { /* 已退出 */ }
|
|
2238
|
+
}
|
|
2239
|
+
transcodeChildren.clear();
|
|
2240
|
+
}
|
|
1545
2241
|
// 解析一段 rollout 文本为记录;completeBytes = 已完整解析的整行字节数
|
|
1546
2242
|
//(末行若是不完整 JSON(写入中途)不计入,调用方据此决定偏移推进量)
|
|
1547
2243
|
function parseRolloutLines(text) {
|
|
@@ -1585,8 +2281,11 @@ function parseRolloutLines(text) {
|
|
|
1585
2281
|
input = num(u.input_tokens) + cacheRead + cacheWrite;
|
|
1586
2282
|
}
|
|
1587
2283
|
const output = num(u.outputTokens ?? u.output_tokens);
|
|
2284
|
+
const at = d.completedAt || d.startedAt || '';
|
|
1588
2285
|
recs.push({
|
|
1589
|
-
at
|
|
2286
|
+
at,
|
|
2287
|
+
ts: Date.parse(at),
|
|
2288
|
+
ms: Number(d.durationMs) || 0,
|
|
1590
2289
|
in: input, out: output,
|
|
1591
2290
|
cacheRead,
|
|
1592
2291
|
session: String(d.sessionId || ''),
|
|
@@ -1599,21 +2298,34 @@ function parseRolloutLines(text) {
|
|
|
1599
2298
|
}
|
|
1600
2299
|
|
|
1601
2300
|
function rolloutRecords() {
|
|
1602
|
-
const dir = join(
|
|
2301
|
+
const dir = rolloutDirOverride || join(resolveDataRootDir(), 'cli', 'rollout'); // 官方 rollout 目录跟数据根迁移
|
|
1603
2302
|
let names = [];
|
|
1604
|
-
try { names = readdirSync(dir).filter((n) => n.startsWith('model-io-') && n.endsWith('.jsonl')); } catch {
|
|
2303
|
+
try { names = readdirSync(dir).filter((n) => n.startsWith('model-io-') && n.endsWith('.jsonl')); } catch {
|
|
2304
|
+
// 读目录失败(杀软/权限抖动)时旧签名作废:否则空记录算出的 0 值结果会
|
|
2305
|
+
// 连着旧签名进缓存,目录恢复后文件没变就一直命中 0
|
|
2306
|
+
rolloutSig = '';
|
|
2307
|
+
rolloutRecsCache = null;
|
|
2308
|
+
return [];
|
|
2309
|
+
}
|
|
1605
2310
|
// 缓存条目随文件淘汰:会话记录滚动删除后残留条目不再增长(虽小但是纯泄漏)
|
|
2311
|
+
const nameSet = new Set(names); // Set 判定:文件数上千时 names.includes 是 O(F²)
|
|
1606
2312
|
for (const k of usageFileCache.keys()) {
|
|
1607
|
-
if (!
|
|
2313
|
+
if (!nameSet.has(k)) usageFileCache.delete(k);
|
|
1608
2314
|
}
|
|
1609
2315
|
const recs = [];
|
|
2316
|
+
// 先取各文件 stat 并算签名:签名没变直接复用上次合并好的记录。shortcut:
|
|
2317
|
+
// 同一毫秒内改写成相同字节数检测不到,实际不会发生,如遇到可把签名换成内容哈希
|
|
2318
|
+
const stats = [];
|
|
1610
2319
|
for (const name of names) {
|
|
2320
|
+
try { stats.push([name, statSync(join(dir, name))]); } catch { /* 读不到的文件跳过 */ }
|
|
2321
|
+
}
|
|
2322
|
+
const sig = stats.map(([name, st]) => `${name}:${st.mtimeMs}:${st.size}`).join('|');
|
|
2323
|
+
if (sig === rolloutSig && rolloutRecsCache) return rolloutRecsCache;
|
|
2324
|
+
for (const [name, st] of stats) {
|
|
1611
2325
|
const full = join(dir, name);
|
|
1612
|
-
let st;
|
|
1613
|
-
try { st = statSync(full); } catch { continue; }
|
|
1614
2326
|
const cached = usageFileCache.get(name);
|
|
1615
2327
|
if (cached && cached.mtime === st.mtimeMs && cached.size === st.size) {
|
|
1616
|
-
|
|
2328
|
+
for (const r of cached.recs) recs.push(r); // 不用展开语法:单文件 13 万条会 RangeError
|
|
1617
2329
|
continue;
|
|
1618
2330
|
}
|
|
1619
2331
|
// 追加式增量解析:jsonl 只追加(流式输出期间当前会话文件持续增长,整文件
|
|
@@ -1633,7 +2345,8 @@ function rolloutRecords() {
|
|
|
1633
2345
|
size: cached.size + completeBytes,
|
|
1634
2346
|
recs: cached.recs.concat(added),
|
|
1635
2347
|
});
|
|
1636
|
-
|
|
2348
|
+
for (const r of cached.recs) recs.push(r);
|
|
2349
|
+
for (const r of added) recs.push(r);
|
|
1637
2350
|
continue;
|
|
1638
2351
|
}
|
|
1639
2352
|
let parsed = [];
|
|
@@ -1647,39 +2360,78 @@ function rolloutRecords() {
|
|
|
1647
2360
|
parsedBytes = Math.min(r.completeBytes, Buffer.byteLength(text, 'utf8'));
|
|
1648
2361
|
} catch { /* 文件读失败跳过 */ }
|
|
1649
2362
|
usageFileCache.set(name, { mtime: st.mtimeMs, size: parsedBytes, recs: parsed });
|
|
1650
|
-
recs.push(
|
|
2363
|
+
for (const r of parsed) recs.push(r);
|
|
1651
2364
|
}
|
|
2365
|
+
rolloutSig = sig;
|
|
2366
|
+
rolloutRecsCache = recs;
|
|
1652
2367
|
return recs;
|
|
1653
2368
|
}
|
|
1654
2369
|
|
|
1655
|
-
function collectUsageStats(sessionId) {
|
|
2370
|
+
function collectUsageStats(sessionId, wantTurns = true) {
|
|
1656
2371
|
const recs = rolloutRecords();
|
|
1657
|
-
//
|
|
1658
|
-
//
|
|
1659
|
-
|
|
2372
|
+
// 分钟桶只服务每轮统计(turn-usage 带 session 拉取),状态栏请求带 turns=0
|
|
2373
|
+
// 跳过:省掉全记录分桶与 60 桶序列化(大记录集下每请求几十毫秒)
|
|
2374
|
+
wantTurns = wantTurns && !!sessionId;
|
|
1660
2375
|
const today = new Date();
|
|
1661
2376
|
const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;
|
|
2377
|
+
// 记录没变(文件签名相同)+ 查询口径没变时直接复用上次聚合结果:锚定速率是
|
|
2378
|
+
// 记录的纯函数(锚 = 最新完成时刻,不随请求时刻移动),跨午夜才要重算"今日"
|
|
2379
|
+
const cacheKey = `${sessionId || ''}|${wantTurns ? 1 : 0}|${todayKey}`;
|
|
2380
|
+
if (statsResultCache.sig === rolloutSig && statsResultCache.key === cacheKey && statsResultCache.result) {
|
|
2381
|
+
return statsResultCache.result;
|
|
2382
|
+
}
|
|
1662
2383
|
const global = { todayTokens: 0, todayOut: 0, totalTokens: 0, totalOut: 0, tasks: 0, records: recs.length };
|
|
1663
2384
|
// 每轮用量按本地 HH:mm 分桶(回答末尾的显示时间与之匹配);
|
|
1664
2385
|
// 本地记录只留最近几轮,注入侧只给能对上时间的回答显示
|
|
1665
2386
|
const byMinute = new Map();
|
|
2387
|
+
// 最近 60 秒速率(状态栏 tokRate 项):token 按调用耗时摊到时间轴(完成
|
|
2388
|
+
// 时刻往前 durationMs 一段),按窗口重叠比例折算,长调用完成瞬间不会出现
|
|
2389
|
+
// 假尖峰。窗口以该口径最新一条记录的完成时刻为锚、往前 60 秒——回答结束
|
|
2390
|
+
// 后锚不再移动,速率自然停在最后的值:不衰减归零,也不依赖进程内状态
|
|
2391
|
+
//(重启/热替换后显示一致);有新调用完成锚前移、数值刷新。
|
|
2392
|
+
// 统计范围:带 ?session= 只算该会话,不带则全局;与每轮桶不同,辅助小调用
|
|
2393
|
+
// 也计入(它们是真实消耗)
|
|
2394
|
+
const winMs = 60_000;
|
|
2395
|
+
let anchor = 0;
|
|
2396
|
+
for (const r of recs) {
|
|
2397
|
+
if (Number.isFinite(r.ts) && (!sessionId || r.session === sessionId)) anchor = Math.max(anchor, r.ts);
|
|
2398
|
+
}
|
|
2399
|
+
const anchorFuture = anchor > Date.now(); // 未来时间戳:钳制值依赖请求时刻,结果不能缓存
|
|
2400
|
+
anchor = Math.min(anchor, Date.now()); // 未来时间戳(时钟回拨等)别把锚拉到未来
|
|
2401
|
+
let rateTotal = 0;
|
|
2402
|
+
let rateOut = 0;
|
|
1666
2403
|
for (const r of recs) {
|
|
1667
2404
|
const total = r.in + r.out;
|
|
1668
2405
|
global.totalTokens += total;
|
|
1669
2406
|
global.totalOut += r.out;
|
|
1670
|
-
|
|
1671
|
-
|
|
2407
|
+
// 按本地日期归"今日":r.at 是 ISO/UTC 串,直接取前 10 位是 UTC 日期,
|
|
2408
|
+
// 本地凌晨(UTC+8 的 0-8 点)完成的调用会被算进昨天
|
|
2409
|
+
if (Number.isFinite(r.ts)) {
|
|
2410
|
+
const rd = new Date(r.ts);
|
|
2411
|
+
const day = `${rd.getFullYear()}-${String(rd.getMonth() + 1).padStart(2, '0')}-${String(rd.getDate()).padStart(2, '0')}`;
|
|
2412
|
+
if (day === todayKey) { global.todayTokens += total; global.todayOut += r.out; }
|
|
2413
|
+
}
|
|
2414
|
+
const end = r.ts;
|
|
2415
|
+
if (Number.isFinite(end) && (!sessionId || r.session === sessionId)) {
|
|
2416
|
+
const dur = Math.max(r.ms || 0, 1); // 无耗时字段的旧记录按 1ms 点事件计
|
|
2417
|
+
const overlap = Math.min(end, anchor) - Math.max(end - dur, anchor - winMs);
|
|
2418
|
+
if (overlap > 0) {
|
|
2419
|
+
const w = overlap / dur;
|
|
2420
|
+
rateTotal += total * w;
|
|
2421
|
+
rateOut += r.out * w;
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
1672
2424
|
// 每轮回答只统计主对话流的调用:起名等辅助请求是独立小上下文、
|
|
1673
2425
|
// 缓存从零开始,混进分钟桶会把命中率拉到个位数(全局统计仍全量计入)
|
|
1674
2426
|
if (!wantTurns || total < 5000) continue;
|
|
1675
2427
|
// 指定会话时每轮桶只算该会话的调用——否则切到别的会话聊天后,
|
|
1676
2428
|
// 那些调用会被区间归属算进当前会话最后一行的头上
|
|
1677
2429
|
if (r.session !== sessionId) continue;
|
|
1678
|
-
const t =
|
|
2430
|
+
const t = r.ts;
|
|
1679
2431
|
if (!Number.isFinite(t)) continue;
|
|
1680
2432
|
const d = new Date(t);
|
|
1681
|
-
//
|
|
1682
|
-
//
|
|
2433
|
+
// 桶键 = 本地"月-日 时:分";注入侧不读这个键(按 ts 区间归属到回答行),
|
|
2434
|
+
// 键只用于同分钟的调用并桶
|
|
1683
2435
|
const hm = (d.getMonth() + 1) + '-' + d.getDate() + ' ' + String(d.getHours()).padStart(2, '0') + ':' + String(d.getMinutes()).padStart(2, '0');
|
|
1684
2436
|
const bucket = byMinute.get(hm) || { hm, in: 0, out: 0, cacheRead: 0, ts: t };
|
|
1685
2437
|
bucket.in += r.in;
|
|
@@ -1688,8 +2440,13 @@ function collectUsageStats(sessionId) {
|
|
|
1688
2440
|
bucket.ts = Math.max(bucket.ts, t);
|
|
1689
2441
|
byMinute.set(hm, bucket);
|
|
1690
2442
|
}
|
|
2443
|
+
// 保留 1 位小数:工具循环期的输出只有零点几每秒,取整会显示成 0/s
|
|
2444
|
+
const perSec = (x) => Math.round((x / (winMs / 1000)) * 10) / 10;
|
|
2445
|
+
global.rate60 = { total: perSec(rateTotal), out: perSec(rateOut) };
|
|
1691
2446
|
const recentTurns = [...byMinute.values()].sort((a, b) => b.ts - a.ts).slice(0, 60);
|
|
1692
|
-
|
|
2447
|
+
const out = { global, recentTurns };
|
|
2448
|
+
if (!anchorFuture) statsResultCache = { sig: rolloutSig, key: cacheKey, result: out };
|
|
2449
|
+
return out;
|
|
1693
2450
|
}
|
|
1694
2451
|
|
|
1695
2452
|
function readJsonFile(p) {
|
|
@@ -1737,6 +2494,9 @@ function mergeTitleGenConfig(saved) {
|
|
|
1737
2494
|
baseUrl: typeof s.baseUrl === 'string' ? s.baseUrl.trim().slice(0, 500) : d.baseUrl,
|
|
1738
2495
|
apiKey: typeof s.apiKey === 'string' ? s.apiKey.trim().slice(0, 500) : d.apiKey,
|
|
1739
2496
|
format: s.format === 'openai' ? 'openai' : s.format === 'anthropic' ? 'anthropic' : '',
|
|
2497
|
+
recentQa: Number.isFinite(Number(s.recentQa)) ? Math.min(20, Math.max(1, Math.round(Number(s.recentQa)))) : d.recentQa,
|
|
2498
|
+
hoverBtn: s.hoverBtn !== false,
|
|
2499
|
+
menuEntry: s.menuEntry !== false,
|
|
1740
2500
|
customWritten: written,
|
|
1741
2501
|
};
|
|
1742
2502
|
}
|
|
@@ -1773,6 +2533,30 @@ function mergeSyncConfig(saved) {
|
|
|
1773
2533
|
};
|
|
1774
2534
|
}
|
|
1775
2535
|
|
|
2536
|
+
// WebDAV 地址的协议判定:http 明文会把 Basic 登录名和密码原样传出去,
|
|
2537
|
+
// http 只放行回环与内网地址(内网 NAS 常用 http),公网主机必须 https
|
|
2538
|
+
function webdavHttpSchemeOk(raw) {
|
|
2539
|
+
const url = typeof raw === 'string' ? raw.trim() : '';
|
|
2540
|
+
if (!/^https?:\/\//i.test(url)) return false;
|
|
2541
|
+
if (/^https:/i.test(url)) return true;
|
|
2542
|
+
let host = '';
|
|
2543
|
+
try { host = new URL(url).hostname.toLowerCase(); } catch { return false; }
|
|
2544
|
+
host = host.replace(/^\[|\]$/g, ''); // URL.hostname 对 IPv6 地址带方括号
|
|
2545
|
+
if (host === 'localhost' || host === '::1') return true;
|
|
2546
|
+
// IPv6 字面量不走下面的域名规则(不含点,会被误判成内网主机名):
|
|
2547
|
+
// 只放行链路本地(fe80::/10)与 ULA(fc00::/7)内网段,公网 v6 仍要 https
|
|
2548
|
+
// (按 RFC 5952 规范写法匹配首段,缩写首段的极端写法不认)
|
|
2549
|
+
if (host.includes(':')) return /^(fe[89ab][0-9a-f]|f[cd][0-9a-f]{2}):/i.test(host);
|
|
2550
|
+
// 单标签主机名(无点,如 mynas)与 .local/.lan/.internal 后缀的域名按内网 NAS
|
|
2551
|
+
// 处理放行 http;其余域名型主机要求 https
|
|
2552
|
+
if (!host.includes('.') || /\.(local|lan|internal)$/.test(host)) return true;
|
|
2553
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
2554
|
+
if (!m) return false;
|
|
2555
|
+
const a = Number(m[1]);
|
|
2556
|
+
const b = Number(m[2]);
|
|
2557
|
+
return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
|
2558
|
+
}
|
|
2559
|
+
|
|
1776
2560
|
// POST /sync 表单校验:url/login/password/dir 全量替换(dir 缺省时不动已有值)。
|
|
1777
2561
|
// URL 必填,指向 WebDAV 服务器(可含路径前缀);dir 为其下的上传目录,可多级;
|
|
1778
2562
|
// historyLimit 可选(缺省时不动已有值),0–100 的整数
|
|
@@ -1783,6 +2567,7 @@ function validateSyncForm(raw) {
|
|
|
1783
2567
|
if (!url) return { error: '请先填写 URL(如 https://dav.jianguoyun.com/dav/)' };
|
|
1784
2568
|
if (!/^https?:\/\/\S+$/.test(url)) return { error: 'URL 需为 WebDAV 服务器地址,如 https://dav.example.com/dav/' };
|
|
1785
2569
|
if (url.length > 500) return { error: 'URL 过长(最多 500 字符)' };
|
|
2570
|
+
if (!webdavHttpSchemeOk(url)) return { error: '公网地址需用 https(http 明文传输登录名和密码);内网或回环地址(如 http://192.168.1.5:5005)可继续用 http' };
|
|
1786
2571
|
if (login.length > 300 || password.length > 300) return { error: '登录名或密码过长(最多 300 字符)' };
|
|
1787
2572
|
const out = { type: 'webdav', url, login, password };
|
|
1788
2573
|
if (typeof raw.dir === 'string') {
|
|
@@ -1855,7 +2640,7 @@ async function syncBgListRemote(sync, proxyUrl) {
|
|
|
1855
2640
|
if (!list.ok) return { error: list.error, code: 'sync-request', status: 502 };
|
|
1856
2641
|
if (list.httpCode === 404) return { files: [] };
|
|
1857
2642
|
if (list.httpCode < 200 || list.httpCode >= 300) return { error: webdavHttpText(list.httpCode), code: 'sync-request', status: 502 };
|
|
1858
|
-
return { files: parseWebdavListing(list.body).filter((f) =>
|
|
2643
|
+
return { files: parseWebdavListing(list.body).filter((f) => MEDIA_EXT.has(f.name.slice(f.name.lastIndexOf('.')).toLowerCase())) };
|
|
1859
2644
|
}
|
|
1860
2645
|
async function syncBgPush({ sync, proxyUrl, dataRoot }) {
|
|
1861
2646
|
const localFiles = listBgFiles(dataRoot);
|
|
@@ -1902,7 +2687,8 @@ async function syncBgPull({ sync, proxyUrl, dataRoot }) {
|
|
|
1902
2687
|
if (!name) continue; // 云端的异常文件名条目不镜像
|
|
1903
2688
|
const l = localByName.get(name);
|
|
1904
2689
|
if (l && l.size === f.size) continue;
|
|
1905
|
-
|
|
2690
|
+
// 临时名带 pid+随机:与上传路径撞同一文件名时不共用一个 .tmp
|
|
2691
|
+
const tmp = join(dir, `${name}.${process.pid}.${Date.now().toString(36)}.tmp`);
|
|
1906
2692
|
const get = await webdavRequest({ method: 'GET', url: syncBgFileUrl(sync, name), login: sync.login, password: sync.password, proxyUrl, timeoutMs: 120000, downloadFile: tmp });
|
|
1907
2693
|
const bad = !get.ok || get.httpCode < 200 || get.httpCode >= 300;
|
|
1908
2694
|
if (bad) {
|
|
@@ -1922,8 +2708,8 @@ async function syncBgPull({ sync, proxyUrl, dataRoot }) {
|
|
|
1922
2708
|
}
|
|
1923
2709
|
|
|
1924
2710
|
// 信封校验:云端文件必须是 { app: 'zcode-pro', kind, format, data } 且组别与文件名
|
|
1925
|
-
// 前缀一致;4MB
|
|
1926
|
-
function parseSyncEnvelope(body, kind, label) {
|
|
2711
|
+
// 前缀一致;4MB 上限挡住异常大文件。导出供回归测试直接喂坏信封
|
|
2712
|
+
export function parseSyncEnvelope(body, kind, label) {
|
|
1927
2713
|
if (body.length > 4 * 1024 * 1024) {
|
|
1928
2714
|
return { error: `云端 ${label} 超过 4MB,已拒绝应用`, code: 'sync-remote-invalid', status: 400 };
|
|
1929
2715
|
}
|
|
@@ -1932,6 +2718,10 @@ function parseSyncEnvelope(body, kind, label) {
|
|
|
1932
2718
|
if (!doc || typeof doc !== 'object' || doc.app !== 'zcode-pro' || doc.kind !== kind || !doc.data || typeof doc.data !== 'object') {
|
|
1933
2719
|
return { error: `云端 ${label} 不是 zcode-pro 的同步数据(可能被其他内容占用),请删除该文件或换一个目录`, code: 'sync-remote-invalid', status: 409 };
|
|
1934
2720
|
}
|
|
2721
|
+
// format 超出认识范围(更新版本的 zcode-pro 写入的新格式):不导入,提示升级客户端
|
|
2722
|
+
if (doc.format !== 1) {
|
|
2723
|
+
return { error: `云端 ${label} 是更新版本的 zcode-pro 写入的数据,当前客户端版本过旧,请升级 zcode-pro 后再同步`, code: 'sync-remote-invalid', status: 400 };
|
|
2724
|
+
}
|
|
1935
2725
|
return { doc };
|
|
1936
2726
|
}
|
|
1937
2727
|
|
|
@@ -1960,11 +2750,38 @@ async function fetchSyncNamedDoc(sync, proxyUrl, fileName) {
|
|
|
1960
2750
|
return parseSyncEnvelope(r.body, kind, fileName);
|
|
1961
2751
|
}
|
|
1962
2752
|
|
|
2753
|
+
// —— /sync/run 单飞 ————————————————————————————————————
|
|
2754
|
+
// 同 direction 的并发触发共用同一个 promise(去重),不同 direction 串行排队:
|
|
2755
|
+
// 两轮同步并发跑会互相清掉对方刚上传的历史版本。在途(排队 + 执行)期间计入
|
|
2756
|
+
// 忙碌标志,启动器热替换据此延后——同步中途换进程同样会互删历史版本
|
|
2757
|
+
let syncRunJobs = new Map(); // direction → 在跑或排队的 promise
|
|
2758
|
+
let syncRunQueue = Promise.resolve();
|
|
2759
|
+
|
|
2760
|
+
function enqueueSyncRun(direction, fn) {
|
|
2761
|
+
const inflight = syncRunJobs.get(direction);
|
|
2762
|
+
if (inflight) return inflight;
|
|
2763
|
+
const prev = syncRunQueue;
|
|
2764
|
+
const promise = (async () => {
|
|
2765
|
+
await prev;
|
|
2766
|
+
try {
|
|
2767
|
+
return await fn();
|
|
2768
|
+
} finally {
|
|
2769
|
+
syncRunJobs.delete(direction);
|
|
2770
|
+
}
|
|
2771
|
+
})();
|
|
2772
|
+
syncRunQueue = promise.then(() => undefined, () => undefined);
|
|
2773
|
+
syncRunJobs.set(direction, promise);
|
|
2774
|
+
return trackBusy(promise);
|
|
2775
|
+
}
|
|
2776
|
+
|
|
1963
2777
|
async function runSettingsSync({ direction, dataRoot, configFile, config, proxyUrl }) {
|
|
1964
2778
|
const sync = config.sync;
|
|
1965
2779
|
if (!sync.url || !/^https?:\/\/\S+$/.test(sync.url)) {
|
|
1966
2780
|
return { code: 'sync-not-configured', status: 400, error: '请先填写 WebDAV URL 并保存' };
|
|
1967
2781
|
}
|
|
2782
|
+
if (!webdavHttpSchemeOk(sync.url)) {
|
|
2783
|
+
return { code: 'sync-not-configured', status: 400, error: '公网 WebDAV 地址需改用 https(http 明文传输登录名和密码);内网或回环地址可继续用 http' };
|
|
2784
|
+
}
|
|
1968
2785
|
if (!sync.include.zcodepro && !sync.include.model) {
|
|
1969
2786
|
return { code: 'sync-not-configured', status: 400, error: '请至少选择一项同步内容' };
|
|
1970
2787
|
}
|
|
@@ -1973,6 +2790,19 @@ async function runSettingsSync({ direction, dataRoot, configFile, config, proxyU
|
|
|
1973
2790
|
: runSyncPull({ dataRoot, configFile, config, sync, proxyUrl });
|
|
1974
2791
|
}
|
|
1975
2792
|
|
|
2793
|
+
// headroom.json 里值得同步/应用的判定:providers 每条注册都得带路由必需的
|
|
2794
|
+
// id/upstream/format/keyHash 才算有效——空对象、空注册或残缺条目(如只写个 id
|
|
2795
|
+
// 的测试夹具)不上传也不覆盖,免得把别台机器拉回无映射状态(请求 502)
|
|
2796
|
+
function validHeadroomDoc(hr) {
|
|
2797
|
+
return !!hr && typeof hr === 'object' && !Array.isArray(hr)
|
|
2798
|
+
&& Array.isArray(hr.providers) && hr.providers.length > 0
|
|
2799
|
+
&& hr.providers.every((p) => !!p && typeof p === 'object'
|
|
2800
|
+
&& typeof p.id === 'string' && p.id !== ''
|
|
2801
|
+
&& typeof p.upstream === 'string' && p.upstream !== ''
|
|
2802
|
+
&& (p.format === 'anthropic' || p.format === 'openai')
|
|
2803
|
+
&& typeof p.keyHash === 'string' && p.keyHash !== '');
|
|
2804
|
+
}
|
|
2805
|
+
|
|
1976
2806
|
// 上传:每组独立一个云端文件(zcodepro.json / model.json,始终最新一版),勾选几组
|
|
1977
2807
|
// 写几个。aliases 不再上传——3.16.1 起别名功能已停用(官方“编辑项目”改名),
|
|
1978
2808
|
// 且各机器项目路径不同,同步别名只会互相带来无效路径。同一份内容再写一个带
|
|
@@ -1985,6 +2815,11 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
1985
2815
|
if (sync.include.zcodepro) {
|
|
1986
2816
|
// sync(本机的同步配置与凭据)、version(本机 helper 版本)与 aliases 不外发
|
|
1987
2817
|
const { sync: _s, version: _v, aliases: _a, ...rest } = config;
|
|
2818
|
+
// titleGen.apiKey 是模型凭据,与 sync 一样只留本机(设置页文案:凭据不参与同步)
|
|
2819
|
+
if (rest.titleGen && typeof rest.titleGen === 'object') {
|
|
2820
|
+
const { apiKey: _k, ...tg } = rest.titleGen;
|
|
2821
|
+
rest.titleGen = tg;
|
|
2822
|
+
}
|
|
1988
2823
|
docs.zcodepro = rest;
|
|
1989
2824
|
}
|
|
1990
2825
|
if (sync.include.model) {
|
|
@@ -1993,6 +2828,15 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
1993
2828
|
docs.model = { provider: v2conf.provider };
|
|
1994
2829
|
const pc = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'));
|
|
1995
2830
|
if (pc && typeof pc === 'object') docs.model.providerConfig = pc;
|
|
2831
|
+
// headroom.json 随模型组一起同步:它登记供应商的“keyHash → 上游”映射,
|
|
2832
|
+
// 缺了它新机器上指向 127.0.0.1:8787 的供应商会被 headroom 拒绝(401);
|
|
2833
|
+
// 文件里 key 只以 keyHash 形式存储,没有明文。providers 为空不算有效注册,
|
|
2834
|
+
// 不上传;instances(实例端口表)与 router(监听端口)是本机运行状态,不外发
|
|
2835
|
+
const hr = readJsonFile(defaultHeadroomFile());
|
|
2836
|
+
if (validHeadroomDoc(hr)) {
|
|
2837
|
+
const { instances: _inst, router: _router, ...hrSync } = hr;
|
|
2838
|
+
docs.model.headroom = hrSync;
|
|
2839
|
+
}
|
|
1996
2840
|
// 注意:v2/credentials.json 不参与同步——里面是账号登录态(BigModel OAuth、
|
|
1997
2841
|
// JWT、Coding Plan 账号 key)与应用自身数据,各机器用各自账号登录;
|
|
1998
2842
|
// 自定义模型的 API Key 存在 config.json 的 provider.options.apiKey,随 provider 同步
|
|
@@ -2008,6 +2852,11 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
2008
2852
|
for (const kind of Object.keys(docs)) {
|
|
2009
2853
|
const remote = await fetchSyncDoc(sync, proxyUrl, kind);
|
|
2010
2854
|
if (remote.error) return remote;
|
|
2855
|
+
// 本机没有有效 headroom 注册时保留云端旧键:没接入 headroom 的机器上传,
|
|
2856
|
+
// 不该把已传播给新机器的映射抹掉(本地空 ≠ 用户想清空云端)
|
|
2857
|
+
if (kind === 'model' && !docs[kind].headroom && validHeadroomDoc(remote.doc?.data?.headroom)) {
|
|
2858
|
+
docs[kind].headroom = remote.doc.data.headroom;
|
|
2859
|
+
}
|
|
2011
2860
|
const doc = { app: 'zcode-pro', kind, format: 1, savedAt: stamp.toISOString(), data: docs[kind] };
|
|
2012
2861
|
const docPath = join(dir, SYNC_FILES[kind]);
|
|
2013
2862
|
writeFileSync(docPath, JSON.stringify(doc, null, 2), 'utf8');
|
|
@@ -2034,7 +2883,13 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
2034
2883
|
try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
|
|
2035
2884
|
}
|
|
2036
2885
|
sync.lastPushAt = Date.now();
|
|
2037
|
-
|
|
2886
|
+
// 同步是分钟级网络流程:写回前重读配置、只合并本次时间戳,
|
|
2887
|
+
// 别把期间用户在设置弹窗的修改用这份旧快照盖掉;读改写放进跨进程锁内同步执行
|
|
2888
|
+
await withConfigLock(configFile, () => {
|
|
2889
|
+
const freshPush = loadConfig(configFile);
|
|
2890
|
+
freshPush.sync = { ...freshPush.sync, lastPushAt: sync.lastPushAt };
|
|
2891
|
+
if (!saveConfig(configFile, freshPush)) console.error('[zcodepro] lastPushAt 写回被拒(zcodepro.json 损坏),上传本身已成功');
|
|
2892
|
+
});
|
|
2038
2893
|
// 上传成功后清理超出保留个数的旧历史版本(best-effort,失败不影响上传结果)
|
|
2039
2894
|
const pruned = await pruneSyncHistory(sync, proxyUrl, keep);
|
|
2040
2895
|
// 背景图库镜像上传(勾了 zcodepro 组才传;设置文档已传走,图库失败单独报错,重试幂等)
|
|
@@ -2079,32 +2934,40 @@ async function runSyncPull({ dataRoot, configFile, config, sync, proxyUrl }) {
|
|
|
2079
2934
|
// 把云端读到的各组数据落到本机(runSyncPull 与按文件的历史版本导入共用):
|
|
2080
2935
|
// zcodepro 组覆盖功能/样式/代理(sync 配置与凭据保留本机的),别名不导入
|
|
2081
2936
|
//(云端备份可能出自别的机器,路径在本机无效),model 组覆盖 v2/config.json 的
|
|
2082
|
-
// provider 与
|
|
2083
|
-
function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
2937
|
+
// provider、provider_config.json 与 headroom.json;覆盖前都留备份。导出以便测试。
|
|
2938
|
+
export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
2084
2939
|
const applied = [];
|
|
2085
2940
|
const backupFile = (p) => {
|
|
2086
2941
|
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
2087
2942
|
};
|
|
2088
2943
|
const atomicWrite = (p, obj) => {
|
|
2089
|
-
const tmp = p
|
|
2090
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', 'utf8');
|
|
2944
|
+
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
2945
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
2091
2946
|
renameSync(tmp, p);
|
|
2092
2947
|
};
|
|
2093
2948
|
|
|
2094
2949
|
if (docs.zcodepro) {
|
|
2095
2950
|
const rz = docs.zcodepro;
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2951
|
+
// 整段 zcodepro.json 读改写放进跨进程锁内同步执行(applySyncDocs 是同步
|
|
2952
|
+
// 调用点,用同步等锁变体),防止与别的写入方互相覆盖整份配置
|
|
2953
|
+
const rzErr = withConfigLockSync(configFile, () => {
|
|
2954
|
+
const next = loadConfig(configFile);
|
|
2955
|
+
applyFeaturesPartial(next.features, rz.features);
|
|
2956
|
+
next.styles = applyStylesPartial(next.styles, rz.styles);
|
|
2957
|
+
// 别名保持本机的原样:云端备份里的别名可能出自其他机器(路径在本机无效),
|
|
2958
|
+
// 且 3.16.1 起别名功能已停用,不再导入
|
|
2959
|
+
if (typeof rz.proxy === 'string') {
|
|
2960
|
+
const v = rz.proxy.trim();
|
|
2961
|
+
if (v === '' || /^https?:\/\/\S+:\d+$/.test(v)) next.proxy = v;
|
|
2962
|
+
}
|
|
2963
|
+
next.sync = { ...next.sync, lastPullAt: sync.lastPullAt }; // 保留本机 sync 配置与凭据,只记本次拉取时间
|
|
2964
|
+
backupFile(configFile);
|
|
2965
|
+
if (!saveConfig(configFile, next)) {
|
|
2966
|
+
return { error: 'zcodepro.json 读取失败或已损坏,导入中止(请先修好配置文件)', code: 'config-unreadable', status: 500 };
|
|
2967
|
+
}
|
|
2968
|
+
return null;
|
|
2969
|
+
});
|
|
2970
|
+
if (rzErr) return rzErr;
|
|
2108
2971
|
applied.push('zcodepro');
|
|
2109
2972
|
}
|
|
2110
2973
|
if (docs.model) {
|
|
@@ -2121,10 +2984,45 @@ function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
|
|
|
2121
2984
|
backupFile(pcFile);
|
|
2122
2985
|
atomicWrite(pcFile, pc);
|
|
2123
2986
|
}
|
|
2987
|
+
// headroom.json 只在云端文档带有效注册时才覆盖(旧版云端文档没有该字段、
|
|
2988
|
+
// 或 providers 为空/残缺,都不动本机,免得清掉已有映射);instances(实例端口表)
|
|
2989
|
+
// 与 router(监听端口)是本机运行状态,云端的一律不用,保留本机的。
|
|
2990
|
+
// 路径跟随 dataRoot(与同组其他文件一致):defaultHeadroomFile() 按 HOME 定位,
|
|
2991
|
+
// 测试跑进真配置会把用户的路由表整个写坏
|
|
2992
|
+
const hr = docs.model.headroom;
|
|
2993
|
+
if (validHeadroomDoc(hr)) {
|
|
2994
|
+
const hrFile = join(dataRoot, 'headroom.json');
|
|
2995
|
+
// 云端文档里带的三个设置键也剥掉:kompressBackend/powerSaveCpu/powerWatchInterval
|
|
2996
|
+
// 是本机设置,云端的赢会把 B 机器的压缩设备决策改成 A 机器的
|
|
2997
|
+
const { instances: _remoteInst, router: _remoteRouter, kompressBackend: _rKb, powerSaveCpu: _rPs, powerWatchInterval: _rWi, ...hrRest } = hr;
|
|
2998
|
+
// 读改写整段持 headroom.json 文件锁(与面板 interval 写入、setHeadroomUsage 互斥),
|
|
2999
|
+
// 锁内重读最新基线合并:以本机现有键为底、云端注册覆盖 providers,
|
|
3000
|
+
// instances/router 与三个本机设置键保留本机值
|
|
3001
|
+
withConfigLockSync(hrFile, () => {
|
|
3002
|
+
const fresh = readJsonFile(hrFile);
|
|
3003
|
+
const base = (fresh && typeof fresh === 'object') ? fresh : {};
|
|
3004
|
+
const merged = { ...base, ...hrRest };
|
|
3005
|
+
if (base.instances) merged.instances = base.instances;
|
|
3006
|
+
if (base.router) merged.router = base.router;
|
|
3007
|
+
backupFile(hrFile);
|
|
3008
|
+
atomicWrite(hrFile, merged);
|
|
3009
|
+
});
|
|
3010
|
+
// 让路由立刻吃到新映射、缺的实例补起来(路由器本身每请求重读配置,
|
|
3011
|
+
// 只有新上游的实例需要这一步),失败不影响同步结果
|
|
3012
|
+
runHeadroomHook(['ensure'], 20000).catch(() => { /* 尽力而为 */ });
|
|
3013
|
+
}
|
|
2124
3014
|
applied.push('model');
|
|
2125
3015
|
}
|
|
2126
|
-
// 没动 zcodepro.json 时,lastPullAt 也要写入配置文件(动了则已随 next
|
|
2127
|
-
|
|
3016
|
+
// 没动 zcodepro.json 时,lastPullAt 也要写入配置文件(动了则已随 next 一起保存)。
|
|
3017
|
+
// 写回前重读配置、只合并时间戳:别用旧快照盖掉同步期间用户的修改
|
|
3018
|
+
if (!applied.includes('zcodepro')) {
|
|
3019
|
+
// lastPullAt 读改写同样在跨进程锁内同步完成
|
|
3020
|
+
withConfigLockSync(configFile, () => {
|
|
3021
|
+
const freshPull = loadConfig(configFile);
|
|
3022
|
+
freshPull.sync = { ...freshPull.sync, lastPullAt: sync.lastPullAt };
|
|
3023
|
+
if (!saveConfig(configFile, freshPull)) console.error('[zcodepro] lastPullAt 写回被拒(zcodepro.json 损坏)');
|
|
3024
|
+
});
|
|
3025
|
+
}
|
|
2128
3026
|
return { applied };
|
|
2129
3027
|
}
|
|
2130
3028
|
|
|
@@ -2149,7 +3047,9 @@ async function runSyncTest({ sync, proxyUrl }) {
|
|
|
2149
3047
|
});
|
|
2150
3048
|
return { ok, resp };
|
|
2151
3049
|
};
|
|
2152
|
-
|
|
3050
|
+
// PROPFIND 的集合地址统一带尾斜杠(图库列表 syncBgListRemote 同款):
|
|
3051
|
+
// 会给目录地址回 301 的网盘不认无斜杠写法,会报“HTTP 301”
|
|
3052
|
+
const baseDir = syncBaseDir(sync) + '/';
|
|
2153
3053
|
// ① 只要拿到响应且不是凭据问题就算连通(404/409 = 目录还没建,交给第②步处理)
|
|
2154
3054
|
const connect = await probe('connect', () => webdavRequest({ method: 'PROPFIND', url: baseDir, ...auth, timeoutMs: 20000, headers: ['Depth: 0'] }));
|
|
2155
3055
|
if (!connect.ok && connect.resp.ok && (connect.resp.httpCode === 404 || connect.resp.httpCode === 409)) {
|
|
@@ -2185,7 +3085,7 @@ async function runSyncTest({ sync, proxyUrl }) {
|
|
|
2185
3085
|
// PROPFIND 云端同步目录,列出全部备份版本(固定名 + 带时间戳的历史):
|
|
2186
3086
|
// 按修改时间从新到旧(时间缺失的按文件名排后);目录还不存在视为空列表
|
|
2187
3087
|
async function listSyncVersions(sync, proxyUrl) {
|
|
2188
|
-
const r = await webdavRequest({ method: 'PROPFIND', url: syncBaseDir(sync), login: sync.login, password: sync.password, proxyUrl, timeoutMs: 30000, headers: ['Depth: 1'] });
|
|
3088
|
+
const r = await webdavRequest({ method: 'PROPFIND', url: syncBaseDir(sync) + '/', login: sync.login, password: sync.password, proxyUrl, timeoutMs: 30000, headers: ['Depth: 1'] });
|
|
2189
3089
|
if (!r.ok) return { error: r.error, code: 'sync-request', status: 502 };
|
|
2190
3090
|
if (r.httpCode === 404 || r.httpCode === 409) return { files: [] };
|
|
2191
3091
|
if (r.httpCode < 200 || r.httpCode >= 300) return { error: webdavHttpText(r.httpCode), code: 'sync-request', status: 502 };
|
|
@@ -2229,40 +3129,6 @@ async function pruneSyncHistory(sync, proxyUrl, keep) {
|
|
|
2229
3129
|
return removed;
|
|
2230
3130
|
}
|
|
2231
3131
|
|
|
2232
|
-
// 别名表清洗(同步下载用):只收 路径字符串 → 短字符串 的条目,数量限幅
|
|
2233
|
-
function sanitizeAliases(raw) {
|
|
2234
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
2235
|
-
const out = {};
|
|
2236
|
-
let n = 0;
|
|
2237
|
-
for (const [k, v] of Object.entries(raw)) {
|
|
2238
|
-
if (typeof k !== 'string' || k.length > 500 || k.includes('\0')) continue;
|
|
2239
|
-
if (typeof v !== 'string' || v.length > 200 || /[\r\n\0]/.test(v)) continue;
|
|
2240
|
-
out[k] = v;
|
|
2241
|
-
if (++n >= 2000) break;
|
|
2242
|
-
}
|
|
2243
|
-
return out;
|
|
2244
|
-
}
|
|
2245
|
-
|
|
2246
|
-
// 别名表合并(同步上传/下载共用):取两边的并集,配过别名的条目优先——同一路径
|
|
2247
|
-
// 两边都配了别名时用本机的;只有一边配过时保留配过的那个。所以在一台机器上清除
|
|
2248
|
-
// 别名后,只要别的机器还配着,下次同步还会把这条带回来,两边都清掉才会真正消失。
|
|
2249
|
-
// 导出以便测试脚本直接驱动。
|
|
2250
|
-
export function mergeAliases(localRaw, remoteRaw) {
|
|
2251
|
-
const out = {};
|
|
2252
|
-
const put = (k, v) => {
|
|
2253
|
-
if (typeof k !== 'string' || k.length > 500 || k.includes('\0')) return;
|
|
2254
|
-
if (typeof v !== 'string' || !v || v.length > 200 || /[\r\n\0]/.test(v)) return;
|
|
2255
|
-
out[k] = v;
|
|
2256
|
-
};
|
|
2257
|
-
const entries = (raw) => (raw && typeof raw === 'object' && !Array.isArray(raw)) ? Object.entries(raw) : [];
|
|
2258
|
-
for (const [k, v] of entries(remoteRaw)) put(k, v);
|
|
2259
|
-
for (const [k, v] of entries(localRaw)) {
|
|
2260
|
-
// 本机配过的覆盖云端同路径条目;本机是空值(视为没配过)时不覆盖,云端配过的留下
|
|
2261
|
-
if (v) put(k, v);
|
|
2262
|
-
}
|
|
2263
|
-
return out;
|
|
2264
|
-
}
|
|
2265
|
-
|
|
2266
3132
|
// features 部分更新(POST /config 与同步下载共用):只收已知开关的布尔值
|
|
2267
3133
|
function applyFeaturesPartial(base, partial) {
|
|
2268
3134
|
const out = (base && typeof base === 'object') ? base : {};
|
|
@@ -2270,9 +3136,9 @@ function applyFeaturesPartial(base, partial) {
|
|
|
2270
3136
|
const known = new Set(Object.keys(defaultConfig().features));
|
|
2271
3137
|
for (const key of Object.keys(partial)) {
|
|
2272
3138
|
// 布尔特性一律可存(新特性未列入 defaultConfig 时不能被丢弃),
|
|
2273
|
-
//
|
|
3139
|
+
// 非布尔值只在已知键内、且与默认值同类型时接受——防垃圾类型进配置
|
|
2274
3140
|
if (typeof partial[key] === 'boolean') out[key] = partial[key];
|
|
2275
|
-
else if (known.has(key)) out[key] = partial[key];
|
|
3141
|
+
else if (known.has(key) && typeof partial[key] === typeof defaultConfig().features[key]) out[key] = partial[key];
|
|
2276
3142
|
}
|
|
2277
3143
|
return out;
|
|
2278
3144
|
}
|
|
@@ -2350,30 +3216,36 @@ function scanIdleBusyLinux(paths) {
|
|
|
2350
3216
|
for (const pid of pids) {
|
|
2351
3217
|
try {
|
|
2352
3218
|
if (readFileSync(`/proc/${pid}/comm`, 'utf8').trim() !== 'zcode-cli') continue;
|
|
2353
|
-
|
|
3219
|
+
const cwd = readlinkSync(`/proc/${pid}/cwd`);
|
|
3220
|
+
// 同一工作区可以开多个会话进程:记列表别后写覆盖先写——漏扫一个会话的
|
|
3221
|
+
// 子进程会把跑着命令的项目判成空闲
|
|
3222
|
+
const arr = cliPidByCwd.get(cwd);
|
|
3223
|
+
if (arr) arr.push(pid); else cliPidByCwd.set(cwd, [pid]);
|
|
2354
3224
|
} catch { /* 进程退出/权限:跳过 */ }
|
|
2355
3225
|
}
|
|
2356
3226
|
const busy = new Set();
|
|
2357
|
-
for (const [cwd,
|
|
3227
|
+
for (const [cwd, cliPids] of cliPidByCwd) {
|
|
2358
3228
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
2359
3229
|
if (!wantedPaths) continue;
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
const
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
3230
|
+
for (const pid of cliPids) {
|
|
3231
|
+
let children = '';
|
|
3232
|
+
try { children = readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8'); }
|
|
3233
|
+
catch { continue; }
|
|
3234
|
+
for (const childPidStr of children.split(/\s+/)) {
|
|
3235
|
+
const childPid = Number(childPidStr);
|
|
3236
|
+
if (!Number.isFinite(childPid)) continue;
|
|
3237
|
+
let cmdline = '';
|
|
3238
|
+
let zombie = false;
|
|
3239
|
+
try {
|
|
3240
|
+
cmdline = normCmdline(readFileSync(`/proc/${childPid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim());
|
|
3241
|
+
const stat = readFileSync(`/proc/${childPid}/stat`, 'utf8');
|
|
3242
|
+
zombie = /\) Z /.test(stat);
|
|
3243
|
+
} catch { continue; }
|
|
3244
|
+
if (zombie) continue;
|
|
3245
|
+
if (!cmdline || !isInfraCmdline(cmdline)) {
|
|
3246
|
+
for (const wp of wantedPaths) busy.add(wp); // 认不出的进程宁可误判为忙,也不回收可能在跑命令的项目
|
|
3247
|
+
break;
|
|
3248
|
+
}
|
|
2377
3249
|
}
|
|
2378
3250
|
}
|
|
2379
3251
|
}
|
|
@@ -2404,8 +3276,11 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
2404
3276
|
const busy = new Set();
|
|
2405
3277
|
for (const cli of clis) {
|
|
2406
3278
|
const lsof = await runCmd('lsof', ['-a', '-p', String(cli.pid), '-d', 'cwd', '-Fn', '-w']);
|
|
3279
|
+
// 与注释的约定一致:任一 CLI 的工作目录取不到就整轮放弃(scan=false)——
|
|
3280
|
+
// lsof 缺失/被限权/进程行取不到 cwd 时都不能把项目判成空闲
|
|
3281
|
+
if (lsof.err) return SCAN_OFF;
|
|
2407
3282
|
const cwd = (lsof.stdout.match(/^n(.+)$/m) || [])[1];
|
|
2408
|
-
if (!cwd)
|
|
3283
|
+
if (!cwd) return SCAN_OFF;
|
|
2409
3284
|
const wantedPaths = wantedByCwd.get(cwd);
|
|
2410
3285
|
if (!wantedPaths) continue;
|
|
2411
3286
|
for (const child of procs) {
|
|
@@ -2425,8 +3300,10 @@ async function scanIdleBusyDarwin(paths) {
|
|
|
2425
3300
|
// 查任务索引反查工作区;认不出且无会话 ID 的活动子进程无法归属 → 全部请求判忙(保守)。
|
|
2426
3301
|
// 路径比较忽略大小写与分隔符差异
|
|
2427
3302
|
async function scanIdleBusyWindows(paths, dataRoot) {
|
|
3303
|
+
// 输出编码固定 UTF-8(同 pickFolder.mjs):默认走 OEM 代码页(中文系统 936),
|
|
3304
|
+
// 按 UTF-8 解码不只乱码,GBK 尾字节 0x5C 还会被当转义符让 JSON.parse 抛错
|
|
2428
3305
|
const ps = await runCmd('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
|
2429
|
-
'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress'], 30000);
|
|
3306
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress'], 30000);
|
|
2430
3307
|
if (ps.err || !ps.stdout.trim()) return SCAN_OFF;
|
|
2431
3308
|
let list;
|
|
2432
3309
|
try {
|
|
@@ -2472,9 +3349,11 @@ export async function classifyIdleBusyWindows(procs, paths, lookupTaskWs) {
|
|
|
2472
3349
|
if (child.ppid !== cli.pid) continue;
|
|
2473
3350
|
if (isInfraCmdline(child.cmdline)) continue;
|
|
2474
3351
|
if (!child.cmdline) { unattributed = true; continue; }
|
|
2475
|
-
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_
|
|
2476
|
-
//
|
|
2477
|
-
|
|
3352
|
+
// 会话 id 有 sess_ 与 session_ 两种前缀(新版应用为 session_);字符集与
|
|
3353
|
+
// 路由校验的 id 白名单一致(含 . 和 _)——字符类偏窄会在这些字符处截断成
|
|
3354
|
+
// 前缀,撞上别的真实 task_id 会把错误项目判忙。匹配不到会走 unattributed
|
|
3355
|
+
// 全量判忙——新形式命令挂着时空闲回收会整体停摆
|
|
3356
|
+
const sess = child.cmdline.match(/(?:sess|session)_[A-Za-z0-9._-]+/);
|
|
2478
3357
|
if (sess) await markByTask(sess[0]);
|
|
2479
3358
|
else unattributed = true; // 用户进程但无会话线索:归属不到具体项目
|
|
2480
3359
|
}
|
|
@@ -2568,7 +3447,7 @@ const TITLE_GEN_DEFAULT_PROMPTS = {
|
|
|
2568
3447
|
// 界面语言:桌面设置(v2/setting.json 的 localePreference)为 en-US / zh-CN 时
|
|
2569
3448
|
// 直接采用;system 或未设置时按系统环境语言判断(中文环境 → 中文,其余 → 英文)
|
|
2570
3449
|
function titleGenLocale() {
|
|
2571
|
-
const s = readJsonFile(join(
|
|
3450
|
+
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移(同 startHelper 的 settingsFile)
|
|
2572
3451
|
const pref = String((s && s.localePreference) || '').toLowerCase();
|
|
2573
3452
|
if (pref.startsWith('en')) return 'en';
|
|
2574
3453
|
if (pref.startsWith('zh')) return 'zh';
|
|
@@ -2590,7 +3469,7 @@ const TITLE_GEN_TIMEOUT_MS = 60000; // 单次模型调用超时(与官方起
|
|
|
2590
3469
|
// providerFamilyConnectionSelections)读当前登录的连接方式(kind 含
|
|
2591
3470
|
// individual → 个人、team → 团队),读不到时退回“个人/团队”
|
|
2592
3471
|
function codingPlanKindByFamily() {
|
|
2593
|
-
const s = readJsonFile(join(
|
|
3472
|
+
const s = readJsonFile(join(resolveDataRootDir(), 'v2', 'setting.json')); // 官方 v2 配置跟数据根迁移
|
|
2594
3473
|
const sel = (s && s.providerFamilyConnectionSelections && typeof s.providerFamilyConnectionSelections === 'object')
|
|
2595
3474
|
? s.providerFamilyConnectionSelections : {};
|
|
2596
3475
|
const out = {};
|
|
@@ -2640,7 +3519,7 @@ export function listTitleGenProviders() {
|
|
|
2640
3519
|
const byId = new Map();
|
|
2641
3520
|
const planKinds = codingPlanKindByFamily();
|
|
2642
3521
|
// 注册表读一次,供下方各条目的协议判定兜底复用(文件不存在时为空数组)
|
|
2643
|
-
const headroomProviders = (readJsonFile(
|
|
3522
|
+
const headroomProviders = (readJsonFile(defaultHeadroomFile()) || {}).providers || [];
|
|
2644
3523
|
const add = (id, { name, aliases = [], kind, baseUrl, apiKey, models = [] }) => {
|
|
2645
3524
|
baseUrl = typeof baseUrl === 'string' ? baseUrl.trim() : '';
|
|
2646
3525
|
apiKey = typeof apiKey === 'string' ? apiKey.trim() : '';
|
|
@@ -2666,9 +3545,9 @@ export function listTitleGenProviders() {
|
|
|
2666
3545
|
out.push(entry);
|
|
2667
3546
|
};
|
|
2668
3547
|
|
|
2669
|
-
const v2 = readJsonFile(join(
|
|
3548
|
+
const v2 = readJsonFile(join(resolveDataRootDir(), 'v2', 'config.json')); // 官方 v2 配置跟数据根迁移
|
|
2670
3549
|
const providers = (v2 && typeof v2.provider === 'object' && v2.provider) || {};
|
|
2671
|
-
const rulesDoc = readJsonFile(join(
|
|
3550
|
+
const rulesDoc = readJsonFile(join(resolveDataRootDir(), 'v2', 'provider_config.json'));
|
|
2672
3551
|
const rules = (rulesDoc && rulesDoc.config?.providerConfigRules?.providerRules) || [];
|
|
2673
3552
|
const ruleById = new Map(rules.filter((r) => r && typeof r.providerId === 'string').map((r) => [r.providerId, r]));
|
|
2674
3553
|
// 同一 id 在两张表的字段并起来(provider 表优先:地址/密钥以桌面实际在用的为准)
|
|
@@ -2749,6 +3628,64 @@ async function callOpenAiText(baseUrl, apiKey, model, content) {
|
|
|
2749
3628
|
} finally { clearTimeout(timer); }
|
|
2750
3629
|
}
|
|
2751
3630
|
|
|
3631
|
+
// 生成标题的双写收尾,顺序不能反:先写 CLI 会话库(title_source=custom,权威层
|
|
3632
|
+
// ——官方自动起名看到 custom 会放弃,桌面同步器会把 custom 标题带着 overridden=1
|
|
3633
|
+
// 送回任务索引),再写任务索引(展示层,立即上屏)。只写任务索引时,官方运行时
|
|
3634
|
+
// 排队的自动标题会在几秒后把它覆盖(实测)。CLI 库不可写(旧版无 title_source
|
|
3635
|
+
// 列 / 无该会话行)不阻断:退回单写任务索引的旧行为;任务索引随后失败也不回滚
|
|
3636
|
+
// CLI——同步器会补。写库撞上宿主写入时稍候重试(起名不急这几秒)。
|
|
3637
|
+
// force = 手动“自动重命名”:已重命名的会话也照写(用户显式改名)。
|
|
3638
|
+
// 返回 { written, store, error }:store '' 成功 | skipped 原因 | 'error…';
|
|
3639
|
+
// error 非空 = 任务索引最终没写成(err 带 code,由调用方转 500)。
|
|
3640
|
+
// CLI 库写成功才登记回查记录(reconcileCustomTitles 只认这些记录校正),
|
|
3641
|
+
// 登记只是回查簿记,失败不影响改名结果。导出以便测试
|
|
3642
|
+
export async function writeGeneratedTitle(dataRoot, configFile, sessId, title, { force = false } = {}) {
|
|
3643
|
+
let written = false;
|
|
3644
|
+
let store = ''; // CLI 会话库写入结果:'' 成功 | skipped 原因 | 'error…'
|
|
3645
|
+
for (let attempt = 0; ; attempt++) {
|
|
3646
|
+
try {
|
|
3647
|
+
const r = await setCustomSessionTitle(dataRoot, sessId, title);
|
|
3648
|
+
store = r.written ? '' : (r.skipped || 'skipped');
|
|
3649
|
+
break;
|
|
3650
|
+
} catch (err) {
|
|
3651
|
+
if (err.code === 'index-busy' && attempt < 2) {
|
|
3652
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
3653
|
+
continue;
|
|
3654
|
+
}
|
|
3655
|
+
store = 'error: ' + (err?.message || err);
|
|
3656
|
+
titleGenLog(dataRoot, `cli-store-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3657
|
+
break;
|
|
3658
|
+
}
|
|
3659
|
+
}
|
|
3660
|
+
for (let attempt = 0; ; attempt++) {
|
|
3661
|
+
try {
|
|
3662
|
+
const r = await setTaskTitleIfNotOverridden(dataRoot, sessId, title, { force });
|
|
3663
|
+
written = r.written;
|
|
3664
|
+
break;
|
|
3665
|
+
} catch (err) {
|
|
3666
|
+
if (err.code === 'index-busy' && attempt < 2) {
|
|
3667
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
3668
|
+
continue;
|
|
3669
|
+
}
|
|
3670
|
+
titleGenLog(dataRoot, `index-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3671
|
+
return { written, store, error: err };
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
if (store === '') {
|
|
3675
|
+
// 跨进程锁内同步读改写,防止与别的写入方互相覆盖整份配置
|
|
3676
|
+
await withConfigLock(configFile, () => {
|
|
3677
|
+
try {
|
|
3678
|
+
const c = loadConfig(configFile);
|
|
3679
|
+
c.titleGen.customWritten = { ...(c.titleGen.customWritten || {}), [sessId]: { title, at: Date.now() } };
|
|
3680
|
+
if (!saveConfig(configFile, c)) throw new Error('zcodepro.json 损坏,写入被拒');
|
|
3681
|
+
} catch (err) {
|
|
3682
|
+
titleGenLog(dataRoot, `customWritten-save-error sess=${sessId.slice(0, 13)} err=${err?.message || err}`);
|
|
3683
|
+
}
|
|
3684
|
+
});
|
|
3685
|
+
}
|
|
3686
|
+
return { written, store };
|
|
3687
|
+
}
|
|
3688
|
+
|
|
2752
3689
|
// 生成标题。provider 三种取值:
|
|
2753
3690
|
// - 'session':跟随当前会话——从任务索引解析该会话正在用的供应商与模型
|
|
2754
3691
|
// (model 已填时用填写的),供应商需在可直连列表内;
|
|
@@ -2876,6 +3813,7 @@ export async function exchangeAccountProjectToken(family, dataRoot) {
|
|
|
2876
3813
|
const issueCtrl = new AbortController();
|
|
2877
3814
|
const issueTimer = setTimeout(() => issueCtrl.abort(), 20000);
|
|
2878
3815
|
let issueResp;
|
|
3816
|
+
let issue;
|
|
2879
3817
|
try {
|
|
2880
3818
|
issueResp = await fetch(`${origin}${keysUrl}/${encodeURIComponent(apiKeyId)}/access_tokens`, {
|
|
2881
3819
|
method: 'POST',
|
|
@@ -2883,8 +3821,9 @@ export async function exchangeAccountProjectToken(family, dataRoot) {
|
|
|
2883
3821
|
headers: { 'content-type': 'application/json', authorization: `Bearer ${loginToken}` },
|
|
2884
3822
|
body: JSON.stringify({ clientType: 'zcode', clientVersion: VERSION }),
|
|
2885
3823
|
});
|
|
3824
|
+
// 响应体读取也放超时保护内(与 api() 同款):管理接口回完头拖着不发体会永久挂起
|
|
3825
|
+
issue = await issueResp.json().catch(() => null);
|
|
2886
3826
|
} finally { clearTimeout(issueTimer); }
|
|
2887
|
-
const issue = await issueResp.json().catch(() => null);
|
|
2888
3827
|
const issueData = (issue && [200, 0, '200', '0'].includes(issue.code)) ? issue.data : null;
|
|
2889
3828
|
if (!issueData) throw new Error(`签发项目 token 失败(${issueResp.status})`);
|
|
2890
3829
|
// enable 语义与官方一致:旧版接口不回该字段(实测回的是同义的 enabled),
|
|
@@ -2999,7 +3938,9 @@ export function validateVisionConfig(raw) {
|
|
|
2999
3938
|
if (!Array.isArray(raw.chain) || raw.chain.some((n) => typeof n !== 'string')) return [null, 'chain 必须是代理名数组'];
|
|
3000
3939
|
if (!Array.isArray(raw.proxies)) return [null, 'proxies 必须是数组'];
|
|
3001
3940
|
const cfg = {
|
|
3002
|
-
|
|
3941
|
+
// enabled 同 cardUi:显式给值才写键,缺省保持磁盘原值(否则磁盘上显式
|
|
3942
|
+
// false 会被一次省略 enabled 的保存覆盖回 true)
|
|
3943
|
+
...(raw.enabled !== undefined ? { enabled: raw.enabled !== false } : {}),
|
|
3003
3944
|
chainMode: raw.chainMode,
|
|
3004
3945
|
chain: raw.chain.map((s) => s.trim()).filter(Boolean),
|
|
3005
3946
|
proxies: [],
|
|
@@ -3009,8 +3950,12 @@ export function validateVisionConfig(raw) {
|
|
|
3009
3950
|
// 连续失败跳过(0 = 不跳过);跳过时长(分钟)
|
|
3010
3951
|
skipAfterFailures: clampInt(raw.skipAfterFailures, 0, 100, 2),
|
|
3011
3952
|
skipMinutes: clampInt(raw.skipMinutes, 1, 10080, 30),
|
|
3012
|
-
//
|
|
3013
|
-
|
|
3953
|
+
// 主模型能看图时的策略:true = 始终走识别代理(双重识别换卡片);false = 能看图就不拦截;
|
|
3954
|
+
// null = 自动(跟随宿主「模型设置」图片开关,zcode-vision ≥1.7.9 语义)。缺省不写键(POST
|
|
3955
|
+
// 磁盘合并保留原值);显式 null 由 POST 合并处删键(面板「自动」选项)
|
|
3956
|
+
...(raw.forceIntercept !== undefined
|
|
3957
|
+
? { forceIntercept: raw.forceIntercept === true ? true : raw.forceIntercept === false ? false : null }
|
|
3958
|
+
: {}),
|
|
3014
3959
|
// 识图卡片展示:只在调用方显式给值时透传(面板开关用);缺省不写键,
|
|
3015
3960
|
// 让 POST 的磁盘合并保留原值(zcode-pro 装机缺省 true 的补键逻辑见 GET /vision)
|
|
3016
3961
|
...(raw.cardUi !== undefined ? { cardUi: raw.cardUi === true } : {}),
|
|
@@ -3098,8 +4043,10 @@ export function validateRtkWhitelist(raw) {
|
|
|
3098
4043
|
// (钩子视为未自定义);文件头带注释说明格式,方便用户直接编辑。
|
|
3099
4044
|
function writeRtkState(dir, { mode, whitelist }) {
|
|
3100
4045
|
mkdirSync(dir, { recursive: true });
|
|
4046
|
+
// 临时名带 pid+随机:钩子进程与面板并发写这两个文件时不共用一个 .tmp
|
|
4047
|
+
const pidTmp = (f) => `${f}.${process.pid}.${Date.now().toString(36)}.tmp`;
|
|
3101
4048
|
const modeFile = join(dir, 'mode');
|
|
3102
|
-
const tmp = modeFile
|
|
4049
|
+
const tmp = pidTmp(modeFile);
|
|
3103
4050
|
writeFileSync(tmp, mode, 'utf8');
|
|
3104
4051
|
renameSync(tmp, modeFile);
|
|
3105
4052
|
const wlFile = join(dir, 'whitelist');
|
|
@@ -3107,7 +4054,7 @@ function writeRtkState(dir, { mode, whitelist }) {
|
|
|
3107
4054
|
try { unlinkSync(wlFile); } catch { /* 不存在即目标状态 */ }
|
|
3108
4055
|
return;
|
|
3109
4056
|
}
|
|
3110
|
-
const wlTmp = wlFile
|
|
4057
|
+
const wlTmp = pidTmp(wlFile);
|
|
3111
4058
|
writeFileSync(wlTmp, '# rtk 白名单(不压缩直接放行):每行 name 或 git:name(git 子命令)。删除本文件即恢复默认。\n'
|
|
3112
4059
|
+ whitelist.join('\n') + '\n', 'utf8');
|
|
3113
4060
|
renameSync(wlTmp, wlFile);
|
|
@@ -3230,16 +4177,20 @@ function startRtkUpgrade() {
|
|
|
3230
4177
|
j.output += `下载 ${info.assetName}…\n`;
|
|
3231
4178
|
const archPath = join(dir, info.assetName);
|
|
3232
4179
|
await downloadToFile(j, info.assetUrl, archPath, 600000);
|
|
3233
|
-
// sha256 校验(checksums.txt
|
|
3234
|
-
|
|
4180
|
+
// sha256 校验(checksums.txt 与本机摘要工具;失败即中止,不替换)。
|
|
4181
|
+
// Release 没有 checksums.txt:无从校验,直接中止升级,绝不替换未经校验的二进制
|
|
4182
|
+
if (!info.sumsUrl) throw new Error('Release 缺少 checksums.txt,无法校验下载文件,已中止升级');
|
|
4183
|
+
{
|
|
3235
4184
|
const sumPath = join(dir, 'checksums.txt');
|
|
3236
4185
|
await downloadToFile(j, info.sumsUrl, sumPath, 30000);
|
|
3237
4186
|
const want = readFileSync(sumPath, 'utf8').split('\n')
|
|
3238
4187
|
.find((l) => l.trim().endsWith(info.assetName))?.trim().split(/\s+/)[0];
|
|
3239
4188
|
let got = '';
|
|
3240
4189
|
if (WIN) {
|
|
4190
|
+
// 路径包进单引号(内部 ' 写成 ''):双引号里 $、反引号会被当变量/子表达式求值
|
|
4191
|
+
const safeArch = String(archPath).replace(/'/g, "''");
|
|
3241
4192
|
const local = await execCapture('powershell.exe',
|
|
3242
|
-
['-NoProfile', '-Command', `(Get-FileHash -Algorithm SHA256 -LiteralPath
|
|
4193
|
+
['-NoProfile', '-Command', `(Get-FileHash -Algorithm SHA256 -LiteralPath '${safeArch}').Hash`], 60000);
|
|
3243
4194
|
got = (/[0-9a-fA-F]{64}/.exec(local.output || '') || [''])[0];
|
|
3244
4195
|
} else {
|
|
3245
4196
|
const sumCmd = process.platform === 'darwin' ? 'shasum' : 'sha256sum';
|
|
@@ -3267,6 +4218,9 @@ function startRtkUpgrade() {
|
|
|
3267
4218
|
if (!WIN) chmodSync(newBin, 0o755);
|
|
3268
4219
|
const v = await binVersionOf(newBin);
|
|
3269
4220
|
if (!v) throw new Error('新版本无法运行(--version 无输出)');
|
|
4221
|
+
// 试运行有约 10 秒窗口:期间被取消就别再替换二进制(否则状态显示
|
|
4222
|
+
// 已取消又显示升级成功,自相矛盾)
|
|
4223
|
+
if (j.canceled) throw new Error('canceled');
|
|
3270
4224
|
// 放置:全新安装建目录直接放;已有旧文件则原子替换(先挪走,失败可回滚)
|
|
3271
4225
|
if (freshInstall) mkdirSync(dirname(bin), { recursive: true });
|
|
3272
4226
|
const backup = bin + '.rtk-old';
|
|
@@ -3309,20 +4263,39 @@ function startRtkUpgrade() {
|
|
|
3309
4263
|
// 把目录追加进用户级 PATH(HKCU\Environment,Windows):保持原值类型不展开(REG_EXPAND_SZ
|
|
3310
4264
|
// 里的 %VAR% 引用原样保留),已含该目录则不动。不广播环境变更——运行中的进程读不到,
|
|
3311
4265
|
// 重启 ZCode 后新会话生效(rtk 钩子按固定清单找 rtk,不受 PATH 影响)。
|
|
4266
|
+
// 注册表读写走 PowerShell 而不是 reg.exe:reg 的输出按系统代码页编码(中文 Windows
|
|
4267
|
+
// 是 GBK),Node 按 UTF-8 解码会把中文条目弄乱,原样写回就把用户 PATH 写坏了;
|
|
4268
|
+
// PowerShell 经 .NET 读写值本身不做编码转换,只有控制台输出要固定 UTF-8(同 pickFolder.mjs)。
|
|
3312
4269
|
async function ensureUserPathEntry(dir) {
|
|
3313
|
-
const
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
4270
|
+
const psRead = [
|
|
4271
|
+
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
|
|
4272
|
+
"$k = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)",
|
|
4273
|
+
"if ($null -eq $k -or -not ($k.GetValueNames() -contains 'PATH')) { exit 2 }",
|
|
4274
|
+
"$v = $k.GetValue('PATH', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)",
|
|
4275
|
+
"[Console]::Out.Write([string]($k.GetValueKind('PATH')) + [char]10 + [string]$v)",
|
|
4276
|
+
].join('; ');
|
|
4277
|
+
const q = await execCapture('powershell.exe', ['-NoProfile', '-Command', psRead], 15000);
|
|
4278
|
+
// 值缺失才新建;读取本身出错一律不动用户 PATH(不能把整份值覆盖没了)
|
|
4279
|
+
let kind = 'String';
|
|
4280
|
+
let next = dir; // 缺失分支写调用方给的目录,别写死别的路径
|
|
4281
|
+
if (q.code !== 2) {
|
|
4282
|
+
if (!q.ok) return false;
|
|
4283
|
+
const nl = q.output.indexOf('\n');
|
|
4284
|
+
const curKind = (nl < 0 ? q.output : q.output.slice(0, nl)).trim();
|
|
4285
|
+
if (curKind !== 'String' && curKind !== 'ExpandString') return false; // REG_SZ/REG_EXPAND_SZ 之外的类型不认识,不动它
|
|
4286
|
+
const cur = (nl < 0 ? '' : q.output.slice(nl + 1)).trim();
|
|
4287
|
+
const norm = (s) => s.replace(/[/\\]+/g, '\\').replace(/\\+$/, '').toLowerCase();
|
|
4288
|
+
const expanded = cur.replaceAll('%USERPROFILE%', homedir());
|
|
4289
|
+
if (expanded.split(';').some((p) => p && norm(p) === norm(dir))) return true;
|
|
4290
|
+
kind = curKind;
|
|
4291
|
+
next = cur ? `${cur};${dir}` : dir;
|
|
3317
4292
|
}
|
|
3318
|
-
|
|
3319
|
-
|
|
3320
|
-
|
|
3321
|
-
|
|
3322
|
-
|
|
3323
|
-
|
|
3324
|
-
const next = cur ? `${cur};${dir}` : dir;
|
|
3325
|
-
const r = await execCapture('reg', ['add', 'HKCU\\Environment', '/v', 'PATH', '/t', m[1], '/d', next, '/f'], 15000);
|
|
4293
|
+
// 值包进单引号(内部 ' 写成 ''):$、反引号、$( ) 都不会被当变量/子表达式求值
|
|
4294
|
+
const psWrite = [
|
|
4295
|
+
"$k = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')",
|
|
4296
|
+
`$k.SetValue('PATH', '${next.replace(/'/g, "''")}', [Microsoft.Win32.RegistryValueKind]::${kind})`,
|
|
4297
|
+
].join('; ');
|
|
4298
|
+
const r = await execCapture('powershell.exe', ['-NoProfile', '-Command', psWrite], 15000);
|
|
3326
4299
|
return r.ok;
|
|
3327
4300
|
}
|
|
3328
4301
|
|
|
@@ -3367,14 +4340,18 @@ export function readHeadroomConfig(file) {
|
|
|
3367
4340
|
};
|
|
3368
4341
|
}
|
|
3369
4342
|
|
|
3370
|
-
// 写配置:与插件 hr_config_set
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
4343
|
+
// 写配置:与插件 hr_config_set 同语义——只改这三个键,其余键(hr-join 注册的
|
|
4344
|
+
// providers/router/instances 等)原样保留,缺键不动对应旧值;三键重盖整文件
|
|
4345
|
+
// 会把供应商映射丢光,面板一调设置全员 401(插件侧 ADR-0008 修过同款坑)。
|
|
4346
|
+
// 导出以便测试。
|
|
4347
|
+
export function writeHeadroomConfig(file, cfg) {
|
|
4348
|
+
const cur = readJsonFile(file);
|
|
4349
|
+
const out = (cur && typeof cur === 'object' && !Array.isArray(cur)) ? { ...cur } : {};
|
|
4350
|
+
for (const k of ['kompressBackend', 'powerSaveCpu', 'powerWatchInterval']) {
|
|
4351
|
+
if (cfg[k] !== undefined) out[k] = cfg[k];
|
|
4352
|
+
}
|
|
4353
|
+
const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4354
|
+
writeFileSync(tmp, JSON.stringify(out, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 }); // 配置含供应商凭据,限制本人读写
|
|
3378
4355
|
renameSync(tmp, file);
|
|
3379
4356
|
}
|
|
3380
4357
|
|
|
@@ -3478,18 +4455,31 @@ async function downloadToFile(j, url, dest, timeoutMs = 600000) {
|
|
|
3478
4455
|
if (!res.ok || !res.body) throw new Error(`下载失败 HTTP ${res.status}`);
|
|
3479
4456
|
const total = Number(res.headers.get('content-length')) || 0;
|
|
3480
4457
|
const out = createWriteStream(dest);
|
|
4458
|
+
// 写盘错误必须有人接(磁盘满/杀软锁文件):无人订阅的 error 事件直接崩进程,
|
|
4459
|
+
// 挂在 drain 等待上时还会永久不返回、升级任务卡死
|
|
4460
|
+
let outErr = null;
|
|
4461
|
+
out.on('error', (e) => { outErr = e; });
|
|
3481
4462
|
let got = 0;
|
|
3482
4463
|
let lastPct = -1;
|
|
3483
4464
|
try {
|
|
3484
4465
|
for await (const chunk of res.body) {
|
|
3485
4466
|
if (j.canceled) throw new Error('canceled');
|
|
3486
|
-
if (
|
|
4467
|
+
if (outErr) throw outErr;
|
|
4468
|
+
if (!out.write(chunk)) {
|
|
4469
|
+
await new Promise((r) => {
|
|
4470
|
+
const done = () => { out.off('drain', done); out.off('error', done); r(); };
|
|
4471
|
+
out.once('drain', done);
|
|
4472
|
+
out.once('error', done); // 出错也解除等待,别永久挂起
|
|
4473
|
+
});
|
|
4474
|
+
if (outErr) throw outErr;
|
|
4475
|
+
}
|
|
3487
4476
|
got += chunk.length;
|
|
3488
4477
|
if (total > 0) {
|
|
3489
4478
|
const pct = Math.floor((got / total) * 100);
|
|
3490
4479
|
if (pct >= lastPct + 5) { lastPct = pct; j.output += `下载中 ${pct}%\n`; }
|
|
3491
4480
|
}
|
|
3492
4481
|
}
|
|
4482
|
+
if (outErr) throw outErr;
|
|
3493
4483
|
await new Promise((resolve, reject) => { out.end(resolve); out.once('error', reject); });
|
|
3494
4484
|
} catch (err) {
|
|
3495
4485
|
try { out.destroy(); } catch { /* ignore */ }
|
|
@@ -3528,7 +4518,8 @@ async function headroomBinaryInfo() {
|
|
|
3528
4518
|
}
|
|
3529
4519
|
|
|
3530
4520
|
// 通用命令执行(headroom 本体的 pip 检查/升级等),输出合并 stdout+stderr,
|
|
3531
|
-
// 环境按用途注入代理(默认 deps:headroom/rtk
|
|
4521
|
+
// 环境按用途注入代理(默认 deps:headroom/rtk;CLI 的市场命令走 runNodeScript,
|
|
4522
|
+
// 市场回退克隆的 git 操作走这里,scope 传 plugins)
|
|
3532
4523
|
function execCapture(cmd, args, timeoutMs = 30000, scope = 'deps') {
|
|
3533
4524
|
return new Promise((resolveRun) => {
|
|
3534
4525
|
execFile(cmd, args, { timeout: timeoutMs, env: { ...process.env, ...proxyEnv({}, scope) }, windowsHide: true }, (err, stdout, stderr) => {
|
|
@@ -3685,10 +4676,10 @@ async function runHeadroomHook(args, timeoutMs = 30000) {
|
|
|
3685
4676
|
// 旧版 headroom 插件的钩子只匹配 startup,代理不会自动启动(要等用户新建会话或
|
|
3686
4677
|
// 手动重启)。helper 就绪后延迟几秒补一次 ensure:动作幂等(已在跑秒回),新版
|
|
3687
4678
|
// 插件侧还带跨进程锁;失败一律静默——没装 headroom 插件/本体的环境不能打扰启动。
|
|
3688
|
-
|
|
3689
|
-
|
|
3690
|
-
if (
|
|
3691
|
-
|
|
4679
|
+
function ensureHeadroomAtStartup(state = {}) {
|
|
4680
|
+
// 标志挂 state(跨热替换实例共享):放模块级时每次热替换都重置,兜底 ensure 会重复排队
|
|
4681
|
+
if (state.headroomEnsureFired) return;
|
|
4682
|
+
state.headroomEnsureFired = true;
|
|
3692
4683
|
const timer = setTimeout(() => {
|
|
3693
4684
|
runHeadroomHook(['ensure'], 20000).catch(() => { /* 兜底失败不影响启动 */ });
|
|
3694
4685
|
}, 5000);
|
|
@@ -3758,12 +4749,17 @@ export function headroomUsageScan(dataRoot) {
|
|
|
3758
4749
|
// 切换启用状态:enable=false 时 127.0.0.1 条目 → 直连(并记录);enable=true 时按
|
|
3759
4750
|
// 记录把直连条目切回代理。改写前各留 .zcodepro-backup 备份,与同步导入同款。
|
|
3760
4751
|
export function setHeadroomUsage(dataRoot, configFile, enable) {
|
|
4752
|
+
// 同步调用点用同步等锁变体:整段读改写在跨进程锁内完成,防止与别的写入方互相覆盖
|
|
4753
|
+
return withConfigLockSync(configFile, () => setHeadroomUsageLocked(dataRoot, configFile, enable));
|
|
4754
|
+
}
|
|
4755
|
+
|
|
4756
|
+
function setHeadroomUsageLocked(dataRoot, configFile, enable) {
|
|
3761
4757
|
const backupFile = (p) => {
|
|
3762
4758
|
try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
|
|
3763
4759
|
};
|
|
3764
4760
|
const atomicWrite = (p, obj) => {
|
|
3765
|
-
const tmp = p
|
|
3766
|
-
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', 'utf8');
|
|
4761
|
+
const tmp = `${p}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4762
|
+
writeFileSync(tmp, JSON.stringify(obj, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
|
|
3767
4763
|
renameSync(tmp, p);
|
|
3768
4764
|
};
|
|
3769
4765
|
const v2File = join(dataRoot, 'v2', 'config.json');
|
|
@@ -3815,7 +4811,9 @@ export function setHeadroomUsage(dataRoot, configFile, enable) {
|
|
|
3815
4811
|
if (touched) { backupFile(pcFile); atomicWrite(pcFile, pc); }
|
|
3816
4812
|
}
|
|
3817
4813
|
config.headroomRoutes = routes;
|
|
3818
|
-
saveConfig(configFile, config)
|
|
4814
|
+
if (!saveConfig(configFile, config)) {
|
|
4815
|
+
return { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' };
|
|
4816
|
+
}
|
|
3819
4817
|
return { ok: true, changed };
|
|
3820
4818
|
}
|
|
3821
4819
|
|
|
@@ -3921,36 +4919,115 @@ export function pluginUpdateStatus() {
|
|
|
3921
4919
|
}
|
|
3922
4920
|
|
|
3923
4921
|
// 市场未添加时自动补装(新机器上设置面板的“安装/更新”按钮一键可用):
|
|
3924
|
-
// 读 known_marketplaces.json 判断,缺失则跑 plugins marketplace add
|
|
3925
|
-
//
|
|
4922
|
+
// 读 known_marketplaces.json 判断,缺失则跑 plugins marketplace add;add 退出后
|
|
4923
|
+
// 验证登记结果,未登记则回退 git clone 到本地走目录源——node 26 下 CLI 的 GitHub
|
|
4924
|
+
// 归档解包会挂死并以退出码 0 静默退出,add 看似成功、登记表却没写,不能只信退出码。
|
|
4925
|
+
// 失败 30 分钟内不重试(add 要访问 GitHub,网络不通时每次面板请求都会白等
|
|
3926
4926
|
// 最长 120 秒);返回 null = 已存在无需处理,{ ok, cached } = 执行或跳过了 add。
|
|
3927
4927
|
let lastMarketplaceAddFail = 0;
|
|
3928
|
-
|
|
4928
|
+
|
|
4929
|
+
// 目录源回退的 git 克隆位置(sources/ 对 CLI 是无关目录,不干扰它自己的缓存布局)
|
|
4930
|
+
function zcodePluginsSourceDir() {
|
|
4931
|
+
return join(cliPluginsDir(), 'sources', ZCODE_PLUGINS_MARKETPLACE);
|
|
4932
|
+
}
|
|
4933
|
+
|
|
4934
|
+
function zcodePluginsMarketplaceRegistered() {
|
|
3929
4935
|
const known = readJsonFile(join(cliPluginsDir(), 'known_marketplaces.json'));
|
|
3930
|
-
|
|
3931
|
-
|
|
4936
|
+
return (known?.marketplaces || []).some((m) => m?.id === ZCODE_PLUGINS_MARKETPLACE);
|
|
4937
|
+
}
|
|
4938
|
+
|
|
4939
|
+
// 目录源市场的内容刷新:marketplace update 对目录源只重读本地目录,
|
|
4940
|
+
// 新版本靠这里先 git pull(没有回退克隆时什么都不做)。导出以便测试。
|
|
4941
|
+
export async function pullZcodePluginsSourceClone() {
|
|
4942
|
+
const dir = zcodePluginsSourceDir();
|
|
4943
|
+
if (!existsSync(dir)) return null;
|
|
4944
|
+
return execCapture('git', ['-C', dir, 'pull', '--ff-only'], 60000, 'plugins');
|
|
4945
|
+
}
|
|
4946
|
+
|
|
4947
|
+
// 目录源刷新:目录不存在返回 null(正常 GitHub 源机器无克隆,不动作);存在则
|
|
4948
|
+
// git pull,pull 失败(残目录/上游强推无法快进)删掉重克隆自动恢复——坏目录不能让
|
|
4949
|
+
// 市场更新永远停摆。wantClone = true 时目录缺失也克隆(add 回退路径用)
|
|
4950
|
+
async function ensureZcodePluginsCloneFresh(wantClone = false) {
|
|
4951
|
+
const dir = zcodePluginsSourceDir();
|
|
4952
|
+
if (!existsSync(dir) && !wantClone) return null;
|
|
4953
|
+
const r = existsSync(dir) ? await pullZcodePluginsSourceClone() : null;
|
|
4954
|
+
if (r?.ok) return r;
|
|
4955
|
+
// pull 失败(残目录/上游强推):先克隆到临时目录、成功后才替换旧目录——
|
|
4956
|
+
// 网络瞬断时保留“过时但可用”的旧目录,别一删了之
|
|
4957
|
+
const tmp = dir + '.reclone';
|
|
4958
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
4959
|
+
const c = await execCapture('git', ['clone', '--depth', '1', `https://github.com/${ZCODE_PLUGINS_MARKETPLACE_SOURCE}.git`, tmp], 120000, 'plugins');
|
|
4960
|
+
if (!c.ok) return c;
|
|
4961
|
+
rmSync(dir, { recursive: true, force: true });
|
|
4962
|
+
renameSync(tmp, dir);
|
|
4963
|
+
return c;
|
|
4964
|
+
}
|
|
4965
|
+
|
|
4966
|
+
// 目录源回退:克隆到本地后以目录源登记(marketplace add <目录>)。目录源的登记/
|
|
4967
|
+
// 更新/安装只做文件读写,不走 CLI 的 GitHub 归档解包
|
|
4968
|
+
async function addZcodePluginsMarketplaceFromClone() {
|
|
4969
|
+
const r = await ensureZcodePluginsCloneFresh(true);
|
|
4970
|
+
if (!r.ok) return r;
|
|
4971
|
+
return runZcodeCli(['plugins', 'marketplace', 'add', zcodePluginsSourceDir()], 120000);
|
|
4972
|
+
}
|
|
4973
|
+
|
|
4974
|
+
export async function ensureZcodePluginsMarketplace() {
|
|
4975
|
+
if (zcodePluginsMarketplaceRegistered()) return null;
|
|
3932
4976
|
if (Date.now() - lastMarketplaceAddFail < 30 * 60 * 1000) return { ok: false, cached: true, error: '上次添加市场失败,30 分钟内不再自动重试' };
|
|
3933
|
-
|
|
3934
|
-
if (!
|
|
3935
|
-
|
|
4977
|
+
let r = await runZcodeCli(['plugins', 'marketplace', 'add', ZCODE_PLUGINS_MARKETPLACE_SOURCE], 120000);
|
|
4978
|
+
if (!zcodePluginsMarketplaceRegistered()) r = await addZcodePluginsMarketplaceFromClone();
|
|
4979
|
+
const ok = r.ok && zcodePluginsMarketplaceRegistered();
|
|
4980
|
+
if (!ok) lastMarketplaceAddFail = Date.now();
|
|
4981
|
+
return { ok, output: r.output, error: ok ? r.error : (r.error || 'marketplace add 未生效:登记表里没有该市场') };
|
|
3936
4982
|
}
|
|
3937
4983
|
|
|
3938
4984
|
// /plugins/update 并发控制:启动自动更新、打开设置弹窗时的自动触发、手动按钮、
|
|
3939
4985
|
// 各插件面板的单插件操作都打到这个端点,而 CLI 同时改同一个插件目录会互相破坏。
|
|
3940
|
-
//
|
|
3941
|
-
//
|
|
3942
|
-
let
|
|
4986
|
+
// 按目标键(全量 = 空键,或同一插件名)去重:同目标的并发请求共用同一次执行结果,
|
|
4987
|
+
// 不同目标各占一个槽位互不顶掉、排队串行,后到的等前一个结束再跑
|
|
4988
|
+
let pluginsUpdateJobs = new Map(); // only 键 → 在跑或排队的任务 promise
|
|
4989
|
+
// 一般后台任务在途标志(市场克隆/刷新、WebDAV 同步):排队 + 执行期间 +1,跑完 -1
|
|
4990
|
+
let busyBackground = 0;
|
|
4991
|
+
// 后台任务占用标志:启动器热替换前查询,有任务在跑就延后换——新模块实例
|
|
4992
|
+
// 不继承任务锁,立刻换会跟旧实例拉起的子进程(插件更新/同步/转码等)并发互删中间文件。
|
|
4993
|
+
// 升级任务对象完成后变量不置回 null(只把 running 置 false),必须看 running
|
|
4994
|
+
export function busyJobs() {
|
|
4995
|
+
return !!(pluginsUpdateJobs.size || busyBackground || (headroomUpgradeJob && headroomUpgradeJob.running) || (rtkUpgradeJob && rtkUpgradeJob.running) || transcodeJobs.size);
|
|
4996
|
+
}
|
|
3943
4997
|
let pluginsUpdateQueue = Promise.resolve();
|
|
3944
4998
|
|
|
4999
|
+
// 任务在途(排队 + 执行)期间计入忙碌标志,跑完清掉,热替换据此延后
|
|
5000
|
+
function trackBusy(promise) {
|
|
5001
|
+
busyBackground += 1;
|
|
5002
|
+
promise.then(() => { busyBackground -= 1; }, () => { busyBackground -= 1; });
|
|
5003
|
+
return promise;
|
|
5004
|
+
}
|
|
5005
|
+
|
|
5006
|
+
// 把一步市场操作排进串行队列(状态页的节流同步用):与更新任务互斥执行
|
|
5007
|
+
function runPluginsQueued(fn) {
|
|
5008
|
+
const promise = pluginsUpdateQueue.then(() => fn());
|
|
5009
|
+
pluginsUpdateQueue = promise.then(() => undefined, () => undefined);
|
|
5010
|
+
return trackBusy(promise);
|
|
5011
|
+
}
|
|
5012
|
+
|
|
3945
5013
|
async function runPluginsUpdateJob(body) {
|
|
3946
5014
|
// name 指定时只处理该插件:已装且有更新则更新,未装则安装(各插件面板的单插件操作)
|
|
3947
5015
|
const only = typeof body?.name === 'string' && body.name.trim() ? body.name.trim() : null;
|
|
3948
5016
|
const steps = [];
|
|
3949
5017
|
const added = await ensureZcodePluginsMarketplace();
|
|
3950
5018
|
if (added) steps.push({ step: 'marketplace add', ok: added.ok, output: added.output || added.error });
|
|
5019
|
+
if (added && !added.ok) {
|
|
5020
|
+
// 市场没登记上时 update 必然报 Marketplace not found,别让它冒头顶掉真实错误
|
|
5021
|
+
return { status: 500, payload: { ok: false, code: 'plugins-update', error: added.error || added.output || 'marketplace add 失败', steps } };
|
|
5022
|
+
}
|
|
5023
|
+
const pull = await ensureZcodePluginsCloneFresh();
|
|
3951
5024
|
const sync = await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
|
|
3952
5025
|
lastMarketplaceSync = Date.now();
|
|
3953
|
-
steps.push({
|
|
5026
|
+
steps.push({
|
|
5027
|
+
step: 'marketplace update',
|
|
5028
|
+
ok: sync.ok,
|
|
5029
|
+
output: [pull && !pull.ok ? `目录源刷新失败(git pull / 重克隆),本地目录源可能不是最新:${pull.output || pull.error}` : '', sync.output].filter(Boolean).join('\n'),
|
|
5030
|
+
});
|
|
3954
5031
|
if (!sync.ok && sync.code !== 'cli-not-found') {
|
|
3955
5032
|
return { status: 500, payload: { ok: false, code: 'plugins-update', error: sync.error || sync.output || 'marketplace update 失败', steps } };
|
|
3956
5033
|
}
|
|
@@ -3977,18 +5054,21 @@ async function runPluginsUpdateJob(body) {
|
|
|
3977
5054
|
|
|
3978
5055
|
function enqueuePluginsUpdate(body) {
|
|
3979
5056
|
const only = typeof body?.name === 'string' && body.name.trim() ? body.name.trim() : null;
|
|
3980
|
-
|
|
5057
|
+
// 按 only 键去重:单个槽位会被后到的不同目标顶掉,被顶掉的任务随后会重复跑
|
|
5058
|
+
const key = only || '';
|
|
5059
|
+
const inflight = pluginsUpdateJobs.get(key);
|
|
5060
|
+
if (inflight) return inflight;
|
|
3981
5061
|
const prev = pluginsUpdateQueue;
|
|
3982
5062
|
const promise = (async () => {
|
|
3983
5063
|
await prev;
|
|
3984
5064
|
try {
|
|
3985
5065
|
return await runPluginsUpdateJob(body);
|
|
3986
5066
|
} finally {
|
|
3987
|
-
|
|
5067
|
+
pluginsUpdateJobs.delete(key); // 同键去重保证此刻槽里就是自己,不用再比对
|
|
3988
5068
|
}
|
|
3989
5069
|
})();
|
|
3990
5070
|
pluginsUpdateQueue = promise.then(() => undefined, () => undefined);
|
|
3991
|
-
|
|
5071
|
+
pluginsUpdateJobs.set(key, promise);
|
|
3992
5072
|
return promise;
|
|
3993
5073
|
}
|
|
3994
5074
|
|
|
@@ -4018,9 +5098,13 @@ export function writeAgents(body, agentsFile) {
|
|
|
4018
5098
|
} else if (empty) {
|
|
4019
5099
|
return [200, { ok: true, content: '' }];
|
|
4020
5100
|
}
|
|
4021
|
-
|
|
5101
|
+
// 改名目标取真实路径:直接 rename 到 agentsFile 会把符号链接本身替换成
|
|
5102
|
+
// 普通文件(dotfiles 管理的链接会丢)
|
|
5103
|
+
let real = agentsFile;
|
|
5104
|
+
try { real = realpathSync(agentsFile); } catch { /* 文件还不存在:直接写原路径 */ }
|
|
5105
|
+
const tmp = `${real}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
|
|
4022
5106
|
writeFileSync(tmp, body.content, 'utf8');
|
|
4023
|
-
renameSync(tmp,
|
|
5107
|
+
renameSync(tmp, real);
|
|
4024
5108
|
} catch (err) {
|
|
4025
5109
|
return [500, { ok: false, code: 'agents-write', error: '写入 AGENTS.md 失败: ' + (err?.message || err) }];
|
|
4026
5110
|
}
|
|
@@ -4141,7 +5225,12 @@ export function openWithDefaultApp(rawPath) {
|
|
|
4141
5225
|
const child = spawn('rundll32.exe', ['url.dll,FileProtocolHandler', p], { detached: true, stdio: 'ignore', windowsHide: true });
|
|
4142
5226
|
child.on('spawn', () => finish(null));
|
|
4143
5227
|
child.on('error', () => {
|
|
4144
|
-
|
|
5228
|
+
// cmd 兜底里路径不能直接拼进命令行(%VAR% 会被展开改写命令结构):
|
|
5229
|
+
// 走环境变量传入,% 的展开是单遍、变量值不会被二次扫描
|
|
5230
|
+
const viaCmd = spawn('cmd.exe', ['/d /s /c start "" "%ZP_OPEN%"'], {
|
|
5231
|
+
env: { ...process.env, ZP_OPEN: p },
|
|
5232
|
+
windowsVerbatimArguments: true, detached: true, stdio: 'ignore', windowsHide: true,
|
|
5233
|
+
});
|
|
4145
5234
|
viaCmd.on('spawn', () => finish(null));
|
|
4146
5235
|
viaCmd.on('error', finish);
|
|
4147
5236
|
});
|
|
@@ -4151,7 +5240,7 @@ export function openWithDefaultApp(rawPath) {
|
|
|
4151
5240
|
|
|
4152
5241
|
// 设置/清除项目自定义别名(纯渲染层,不动磁盘与任何 ZCode 数据)。
|
|
4153
5242
|
// alias 传空字符串/null 即清除该项目条目。
|
|
4154
|
-
export function setAlias(body, configFile) {
|
|
5243
|
+
export async function setAlias(body, configFile) {
|
|
4155
5244
|
const raw = typeof body?.path === 'string' ? body.path.trim() : '';
|
|
4156
5245
|
// 先校验再 resolve:resolve 会把相对路径悄悄变绝对,绕过校验
|
|
4157
5246
|
if (!raw || !isAbsolute(raw)) return [400, { ok: false, error: '无效的项目路径' }];
|
|
@@ -4161,16 +5250,21 @@ export function setAlias(body, configFile) {
|
|
|
4161
5250
|
if (name.length > 100) return [400, { ok: false, error: '别名过长(最多 100 字符)', code: 'name-too-long' }];
|
|
4162
5251
|
if (/[\r\n\0]/.test(name)) return [400, { ok: false, error: '别名不能包含换行等控制字符', code: 'name-invalid-chars' }];
|
|
4163
5252
|
}
|
|
4164
|
-
|
|
4165
|
-
|
|
4166
|
-
|
|
4167
|
-
|
|
4168
|
-
|
|
4169
|
-
|
|
4170
|
-
|
|
4171
|
-
|
|
4172
|
-
|
|
4173
|
-
|
|
5253
|
+
// 读改写放进跨进程锁内同步执行,防止与别的写入方互相覆盖整份配置
|
|
5254
|
+
return withConfigLock(configFile, () => {
|
|
5255
|
+
const config = loadConfig(configFile);
|
|
5256
|
+
if (!config.aliases || typeof config.aliases !== 'object') config.aliases = {};
|
|
5257
|
+
if (name) config.aliases[path] = name;
|
|
5258
|
+
else delete config.aliases[path];
|
|
5259
|
+
try {
|
|
5260
|
+
if (!saveConfig(configFile, config)) {
|
|
5261
|
+
return [500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,保存中止(请先修好配置文件)' }];
|
|
5262
|
+
}
|
|
5263
|
+
} catch (err) {
|
|
5264
|
+
return [500, { ok: false, code: 'config-save', error: '保存配置失败: ' + (err?.message || err) }];
|
|
5265
|
+
}
|
|
5266
|
+
return [200, { ok: true, path, alias: name, aliases: config.aliases }];
|
|
5267
|
+
});
|
|
4174
5268
|
}
|
|
4175
5269
|
|
|
4176
5270
|
function invalidProjectName(name) {
|
|
@@ -4218,11 +5312,11 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4218
5312
|
}
|
|
4219
5313
|
}
|
|
4220
5314
|
|
|
4221
|
-
// setting.json 路径引用同步(recentProjects / lastWorkspaceSession / webRemoteControl
|
|
5315
|
+
// setting.json 路径引用同步(recentProjects / lastWorkspaceSession / webRemoteControl…);
|
|
5316
|
+
// 写回前比对 mtime 的重算逻辑在 remapSettingsPathsAtomic 里
|
|
4222
5317
|
const settingsFile = join(dataRoot, 'v2', 'setting.json');
|
|
4223
5318
|
try {
|
|
4224
|
-
|
|
4225
|
-
writeSettingsAtomic(settingsFile, remapSettingsPaths(settings, oldPath, newPath));
|
|
5319
|
+
remapSettingsPathsAtomic(settingsFile, oldPath, newPath);
|
|
4226
5320
|
} catch (err) {
|
|
4227
5321
|
return [500, { ok: false, error: '更新 setting.json 失败: ' + (err?.message || err) }];
|
|
4228
5322
|
}
|
|
@@ -4233,8 +5327,7 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4233
5327
|
await remapTaskIndexPaths(dataRoot, oldPath, newPath);
|
|
4234
5328
|
} catch (err) {
|
|
4235
5329
|
try {
|
|
4236
|
-
|
|
4237
|
-
writeSettingsAtomic(settingsFile, remapSettingsPaths(cur, newPath, oldPath));
|
|
5330
|
+
remapSettingsPathsAtomic(settingsFile, newPath, oldPath);
|
|
4238
5331
|
} catch { /* 回滚失败:setting.json.zcodepro-backup 仍有兜底 */ }
|
|
4239
5332
|
return [500, {
|
|
4240
5333
|
ok: false,
|
|
@@ -4244,16 +5337,19 @@ export async function relocateProject(body, dataRoot) {
|
|
|
4244
5337
|
}
|
|
4245
5338
|
}
|
|
4246
5339
|
|
|
4247
|
-
//
|
|
5340
|
+
// 别名随迁(仅渲染层数据,失败不影响结果);读改写放进跨进程锁内同步执行,
|
|
5341
|
+
// 防止与别的写入方互相覆盖整份配置
|
|
4248
5342
|
try {
|
|
4249
|
-
|
|
4250
|
-
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
|
|
5343
|
+
await withConfigLock(join(dataRoot, 'zcodepro.json'), () => {
|
|
5344
|
+
const config = loadConfig(join(dataRoot, 'zcodepro.json'));
|
|
5345
|
+
const aliases = config.aliases || {};
|
|
5346
|
+
if (Object.prototype.hasOwnProperty.call(aliases, oldPath)) {
|
|
5347
|
+
const v = aliases[oldPath];
|
|
5348
|
+
delete aliases[oldPath];
|
|
5349
|
+
aliases[newPath] = v;
|
|
5350
|
+
saveConfig(join(dataRoot, 'zcodepro.json'), config);
|
|
5351
|
+
}
|
|
5352
|
+
});
|
|
4257
5353
|
} catch { /* ignore */ }
|
|
4258
5354
|
|
|
4259
5355
|
return [200, {
|