zcode-pro 1.5.1 → 1.6.1

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.
@@ -5,7 +5,7 @@
5
5
  import { createServer } from 'node:http';
6
6
  import { execFile, spawn, spawnSync } from 'node:child_process';
7
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';
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';
@@ -16,6 +16,7 @@ import { pickFolderSystem } from './pickFolder.mjs';
16
16
  import { reorderWorkspaceTasks, reorderGroupMembers } from './taskOrder.mjs';
17
17
  import { webdavRequest, webdavPutWithMkcol, webdavHttpText, parseWebdavListing, findCurl } from './webdav.mjs';
18
18
  import { resolveZcodeExecutable } 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,149 @@ function defaultRtkDir() {
35
36
  return process.env.RTK_DIR || join(homedir(), '.zcode-rtk');
36
37
  }
37
38
 
38
- // 主题功能的背景图库:用户上传的图片都存这里,helper 以 /bg/file/<name> 提供,
39
- // 注入 CSS 直接引用该 URL(CSS url() 带不了 token 头,该路由免鉴权,见下)
39
+ // 主题功能的壁纸图库:用户上传的图片/视频都存这里,helper 以 /bg/file/<name> 提供,
40
+ // 注入层直接引用该 URL(媒体元素/CSS url() 带不了 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
- // 背景图上传约束:只收常见位图格式,单张 ≤10MB,图库 ≤50 张(防塞爆磁盘与同步)
45
- const BG_EXT = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.avif']);
46
- const BG_MAX_BYTES = 10 * 1024 * 1024;
47
- const BG_MAX_COUNT = 50;
48
- const BG_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.bmp': 'image/bmp', '.avif': 'image/avif' };
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\/\\]/g, '').replace(/\s+/g, ' ').trim();
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 (!BG_EXT.has(ext)) return null;
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
- function listBgFiles(dataRoot) {
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
+ if (!n.includes('.deleted-')) continue;
126
+ const f = join(dir, n);
127
+ try {
128
+ if (Date.now() - statSync(f).mtimeMs > 24 * 3600 * 1000) unlinkSync(f);
129
+ } catch { /* 仍被占用 */ }
130
+ }
131
+ } catch { /* 目录不存在 */ }
132
+ }
133
+
134
+ export function listBgFiles(dataRoot) {
59
135
  const dir = backgroundsDir(dataRoot);
60
136
  try {
61
137
  return readdirSync(dir)
62
- .map((name) => { const st = statSync(join(dir, name)); return { name, size: st.size, mtime: st.mtimeMs }; })
63
- .filter((f) => BG_EXT.has(f.name.slice(f.name.lastIndexOf('.')).toLowerCase()))
138
+ .map((name) => { try { const st = statSync(join(dir, name)); return { name, size: st.size, mtime: st.mtimeMs }; } catch { return null; } })
139
+ .filter((f) => f && MEDIA_EXT.has(f.name.slice(f.name.lastIndexOf('.')).toLowerCase()))
140
+ .filter((f) => sanitizeBgName(f.name) === f.name) // 与取文件的二次清洗对齐:名字对不上的不列(列了会误命中清洗后同名文件)
64
141
  .sort((a, b) => b.mtime - a.mtime);
65
142
  } catch { return []; } // 目录不存在 = 空图库
66
143
  }
67
144
 
68
- // 主题配置(设置 → 外观 → 主题/背景图):skin 为皮肤 id(default = 不覆盖,
69
- // custom = 用 custom 锚点色现算色阶);bg.mode 选背景来源——none 无背景 /
70
- // library 本地图库(file 为当前文件)/ folder 文件夹(定时切换,folderRandom
71
- // 随机或顺序)/ url 网址(intervalMin 针对随机图 API 定时刷新);
72
- // maskOpacity 遮罩不透明度 0-0.99(越高图片越向主题背景色淡化,文字对比越
73
- // 清晰,默认 0.82)、blurPx 图片模糊 0-24px(默认 0)、panelOpacity 面板
74
- // 不透明度 0-1(侧栏/面板/标签栏,越低透出图片越多,默认 0.3)
145
+ // 视频壁纸帧率上限:ffmpeg 一次性转码出抽帧版存缓存目录,注入层先播原片、
146
+ // 转码完成再换。没有 ffmpeg 时接口直接报缺依赖,注入层保持原片播放
147
+ export const TRANSCODE_FPS = new Set([15, 30, 60]);
148
+ let ffmpegOk = null; // 三态:null 未探测 / true / false
149
+ function hasFfmpeg() {
150
+ if (ffmpegOk === null) {
151
+ try { ffmpegOk = spawnSync('ffmpeg', ['-version'], { stdio: 'ignore' }).status === 0; }
152
+ catch { ffmpegOk = false; }
153
+ }
154
+ return ffmpegOk;
155
+ }
156
+ export function transcodeDir(dataRoot) {
157
+ return join(dataRoot, 'cache', 'transcode');
158
+ }
159
+ const transcodeJobs = new Set(); // 正在转码的 key,防同一文件重复起 ffmpeg
160
+ const TRANSCODE_MAX_CONCURRENCY = 2; // 同时最多 2 个 ffmpeg,防批量请求打满 CPU/磁盘
161
+ // URL 路径段解码:非法 % 序列回 null(调用方回 400),不让 URIError 落成 500
162
+ let folderCfgCache = { at: 0, dir: '' };
163
+ function decodeName(raw) {
164
+ try { return decodeURIComponent(raw); } catch { return null; }
165
+ }
166
+
167
+ // 主题配置(设置 → 外观 → 主题/壁纸):skin 为皮肤 id(default = 不覆盖,
168
+ // custom = 用 custom 锚点色现算色阶);bg.mode 选壁纸来源——none 无壁纸 /
169
+ // library 本地图库(file 为当前文件,intervalMin > 0 时全库轮换)/ folder 文件夹
170
+ // (定时轮换,folderRandom 随机或顺序)/ url 图片网址(intervalMin 定时刷新)/
171
+ // web 网页(url 为页面地址,iframe 铺在界面后方);
172
+ // maskOpacity 遮罩不透明度 0-0.99(越高画面越向主题背景色淡化,文字对比越
173
+ // 清晰,默认 0.82)、blurPx 画面模糊 0-24px(默认 0)、panelOpacity 面板
174
+ // 不透明度 0-1(侧栏/面板/标签栏,越低透出画面越多,默认 0.3);
175
+ // transition 换壁纸转场(cut 硬切 / fade 淡入淡出)、fpsCap 视频帧率上限
176
+ // (0 原始,其余 15/30/60,需 ffmpeg 抽帧转码)、videoVolume 音量 0-1(默认 0
177
+ // 静音)、playbackRate 倍速 0.5-2(默认 1);pauseOnHidden/pauseOnBlur/
178
+ // pauseOnBattery 三个暂停条件(默认开/关/关)
75
179
  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']);
180
+ export const BG_MODES = new Set(['none', 'library', 'folder', 'url', 'web']);
181
+ export const BG_FITS = new Set(['cover', 'contain', 'fill', 'tile']);
78
182
  const HEX_COLOR = /^#[0-9a-fA-F]{6}$/;
79
183
  const CUSTOM_KEYS = ['bg', 'card', 'fg', 'muted', 'accent'];
80
184
  function mergeCustomSkin(saved) {
@@ -114,13 +218,23 @@ export function mergeThemeConfig(saved) {
114
218
  folder: str(bg.folder, 4096) || '',
115
219
  folderRandom: bg.folderRandom !== false,
116
220
  url: (str(bg.url, 2000) || '').trim(),
117
- intervalMin: Number.isFinite(Number(bg.intervalMin)) ? Math.min(1440, Math.max(0, Math.round(Number(bg.intervalMin)))) : 0,
221
+ // Number() 容错与相邻数值字段一致:外部写入方(手改配置/壁纸控制插件)写数字字符串也能生效
222
+ intervalMin: bg.intervalMin != null && Number.isFinite(Number(bg.intervalMin)) ? Math.min(1440, Math.max(0, Math.round(Number(bg.intervalMin)))) : 0,
118
223
  fit: BG_FITS.has(bg.fit) ? bg.fit : 'cover',
119
224
  // null/undefined/非数值都落默认(Number(null)=0 是有限数,须先排除 null)
120
225
  maskOpacity: bg.maskOpacity != null && Number.isFinite(Number(bg.maskOpacity))
121
226
  ? 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(Number(bg.blurPx)))) : 0,
227
+ blurPx: bg.blurPx != null && Number.isFinite(Number(bg.blurPx)) ? Math.min(24, Math.max(0, Math.round(bg.blurPx))) : 0,
123
228
  panelOpacity: bg.panelOpacity != null && Number.isFinite(Number(bg.panelOpacity)) ? Math.min(1, Math.max(0, Number(bg.panelOpacity))) : 0.3,
229
+ transition: bg.transition === 'fade' ? 'fade' : 'cut',
230
+ fpsCap: TRANSCODE_FPS.has(Number(bg.fpsCap)) ? Number(bg.fpsCap) : 0,
231
+ videoVolume: bg.videoVolume != null && Number.isFinite(Number(bg.videoVolume))
232
+ ? Math.min(1, Math.max(0, Number(bg.videoVolume))) : 0,
233
+ playbackRate: bg.playbackRate != null && Number.isFinite(Number(bg.playbackRate))
234
+ ? Math.min(2, Math.max(0.5, Number(bg.playbackRate))) : 1,
235
+ pauseOnHidden: bg.pauseOnHidden !== false,
236
+ pauseOnBlur: bg.pauseOnBlur === true,
237
+ pauseOnBattery: bg.pauseOnBattery === true,
124
238
  regions: {
125
239
  left: mergeBgRegion(bg.regions && bg.regions.left),
126
240
  center: mergeBgRegion(bg.regions && bg.regions.center),
@@ -131,6 +245,17 @@ export function mergeThemeConfig(saved) {
131
245
  return cfg;
132
246
  }
133
247
 
248
+ // wallpaper CLI 的参数键分类:与上面 mergeThemeConfig 里可调的 bg 参数一一对应
249
+ //(mode/file/folder/url/regions 是来源字段归 set 命令、intervalMin/folderRandom 归
250
+ // rotate 命令,都不在此表),mergeThemeConfig 加可调字段时这张表同步加。
251
+ // 值 'number'/'boolean' = 类型检查,Set = 枚举成员集;取值范围仍归
252
+ // mergeThemeConfig(clamp + 默认值)
253
+ export const BG_PARAM_KEYS = {
254
+ maskOpacity: 'number', blurPx: 'number', panelOpacity: 'number', videoVolume: 'number', playbackRate: 'number',
255
+ pauseOnHidden: 'boolean', pauseOnBlur: 'boolean', pauseOnBattery: 'boolean',
256
+ fit: BG_FITS, transition: new Set(['cut', 'fade']), fpsCap: new Set([0, ...TRANSCODE_FPS]),
257
+ };
258
+
134
259
  // headroom 插件的配置文件(与 /hr-* 命令、钩子共用,headroom-lib.sh 按 HOME 定位)
135
260
  function defaultHeadroomFile() {
136
261
  return join(homedir(), '.zcode', 'headroom.json');
@@ -246,10 +371,20 @@ export function defaultConfig() {
246
371
  };
247
372
  }
248
373
 
374
+ // 配置文件“存在但读不出/解析不了”标记:写路径见标记拒绝写回,防止把默认值
375
+ // 覆盖上去把用户配置(WebDAV 账号、别名、样式…)整份清掉
376
+ let configUnreadable = false;
377
+ // 写配置前的可写检查(wallpaper CLI 等外部写入方用):loadConfig 读不出时置位、
378
+ // saveConfig 据此拒写;外部写入方读到损坏要转成明确报错,别等 saveConfig 静默拒写
379
+ export function configFileUnreadable() {
380
+ return configUnreadable;
381
+ }
249
382
  export function loadConfig(configFile) {
250
383
  try {
251
- if (!existsSync(configFile)) return defaultConfig();
252
- const saved = JSON.parse(readFileSyncText(configFile));
384
+ if (!existsSync(configFile)) { configUnreadable = false; return defaultConfig(); }
385
+ const saved = JSON.parse(readFileSyncText(configFile).replace(/^\uFEFF/, '')); // 记事本存的带 BOM 文件也能解析
386
+ if (Array.isArray(saved)) throw new Error('顶层是数组'); // 按损坏处理
387
+ configUnreadable = false; // 解析成功就复位:修好文件后自动恢复可写
253
388
  const minutes = Number(saved.idleReclaimMinutes);
254
389
  const startupMinutes = Number(saved.idleReclaimStartupMinutes);
255
390
  return {
@@ -271,6 +406,7 @@ export function loadConfig(configFile) {
271
406
  sync: mergeSyncConfig(saved.sync),
272
407
  };
273
408
  } catch {
409
+ configUnreadable = existsSync(configFile);
274
410
  return defaultConfig();
275
411
  }
276
412
  }
@@ -279,11 +415,24 @@ function readFileSyncText(p) {
279
415
  return readFileSync(p, 'utf8');
280
416
  }
281
417
 
418
+ // 原子写任意 JSON 文件:先写临时文件再改名,避免崩溃留下半截 JSON
419
+ function writeJsonAtomic(file, obj) {
420
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`; // 防多写者共用同一 .tmp 撕裂
421
+ writeFileSync(tmp, JSON.stringify(obj, null, 2), 'utf8');
422
+ renameSync(tmp, file);
423
+ }
424
+
282
425
  export function saveConfig(configFile, config) {
283
- // 原子写:先写临时文件再改名,避免崩溃留下半截 JSON
284
- const tmp = configFile + '.tmp';
285
- writeFileSync(tmp, JSON.stringify(config, null, 2), 'utf8');
286
- renameSync(tmp, configFile);
426
+ // 配置"存在但损坏"时拒绝写回:否则 title-gen/同步/别名等写路径会把默认值
427
+ // 整份覆盖上去(WebDAV 账号、样式、主题全丢且不可恢复)。POST /config 另有
428
+ // 显式报错,这里兜住其余调用方;修好文件后 loadConfig 会复位标记恢复可写。
429
+ // 保护只针对 zcodepro.json:写别的文件(/zcode-config 写 cli/config.json)
430
+ // 直接用 writeJsonAtomic,别被这个标记误伤成静默不写
431
+ if (configUnreadable) {
432
+ console.error('[zcodepro] zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置');
433
+ return;
434
+ }
435
+ writeJsonAtomic(configFile, config);
287
436
  }
288
437
 
289
438
  // 一次性配置迁移已移除(原 wsRunningSpinOff):旧实验版“折叠项目运行提示”
@@ -291,6 +440,7 @@ export function saveConfig(configFile, config) {
291
440
  // 已重写,迁移对新装机(首启无配置文件、首存后才建)误伤为默认关闭,故删。
292
441
 
293
442
  function json(res, status, obj) {
443
+ if (res.writableEnded || res.headersSent) return; // 已发过响应就不再写(防双发崩进程)
294
444
  const body = JSON.stringify(obj);
295
445
  res.writeHead(status, {
296
446
  'Content-Type': 'application/json; charset=utf-8',
@@ -305,12 +455,14 @@ function readBody(req, limitBytes = 1 << 20) {
305
455
  return new Promise((resolveBody, rejectBody) => {
306
456
  const chunks = [];
307
457
  let size = 0;
458
+ let overflowed = false;
308
459
  req.on('data', (c) => {
309
460
  size += c.length;
310
- if (size > limitBytes) { rejectBody(new Error('请求体过大')); req.destroy(); return; }
461
+ if (size > limitBytes) { overflowed = true; chunks.length = 0; return; } // 排干剩余字节,防 keep-alive 残字节错位
311
462
  chunks.push(c);
312
463
  });
313
464
  req.on('end', () => {
465
+ if (overflowed) { rejectBody(Object.assign(new Error('请求体过大'), { statusCode: 413 })); return; }
314
466
  try { resolveBody(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); }
315
467
  catch (e) { rejectBody(new Error('无效的 JSON 请求体')); }
316
468
  });
@@ -355,6 +507,63 @@ function titleGenLog(dataRoot, line) {
355
507
  } catch { /* 日志失败不影响功能 */ }
356
508
  }
357
509
 
510
+ // ZCode 自身的行为配置(~/.zcode/cli/config.json,ZCode 官方用户级配置文件):
511
+ // 设置弹窗“行为 → ZCode CLI”由此读写,只更新提交的键,其余内容原样保留。
512
+ // 与全局提示词一样固定按主目录定位,不跟 ZCODE_DATA_BASE_DIR 迁移
513
+ function zcodeDataRoot() {
514
+ return join(homedir(), '.zcode');
515
+ }
516
+
517
+ function readZcodeConfig(file) {
518
+ try {
519
+ return JSON.parse(readFileSync(file, 'utf8'));
520
+ } catch {
521
+ return {};
522
+ }
523
+ }
524
+
525
+ // 记忆不在此列:工作区记忆由桌面设置里的 memoryEnabled(~/.zcode/v2/setting.json)
526
+ // 控制,官方 设置 → Agent 能力 → 记忆 页负责开关
527
+ const ZCODE_FEATURE_KEYS = ['compact', 'rewind', 'subagent', 'skill', 'mcp'];
528
+
529
+ function zcodeConfigSnapshot(dataRoot) {
530
+ const cfg = readZcodeConfig(join(dataRoot, 'cli', 'config.json'));
531
+ const skills = cfg.skills && typeof cfg.skills === 'object' ? cfg.skills : {};
532
+ const features = cfg.features && typeof cfg.features === 'object' ? cfg.features : {};
533
+ const roots = Array.isArray(skills.roots)
534
+ ? skills.roots.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim())
535
+ : [];
536
+ const has = (v) => v !== undefined;
537
+ const values = {
538
+ skills: {
539
+ enabled: skills.enabled !== false,
540
+ includeInstructions: skills.includeInstructions !== false,
541
+ metadataBudget: Number.isFinite(skills.metadataBudget) ? skills.metadataBudget : DEFAULT_METADATA_BUDGET,
542
+ roots,
543
+ },
544
+ features: Object.fromEntries(ZCODE_FEATURE_KEYS.map((k) => [k, features[k] !== false])),
545
+ };
546
+ // configured(是否显式写在配置里):界面据此标注“默认值”,也保证只写用户动过的键
547
+ const configured = {
548
+ skills: {
549
+ enabled: has(skills.enabled),
550
+ includeInstructions: has(skills.includeInstructions),
551
+ metadataBudget: has(skills.metadataBudget),
552
+ roots: has(skills.roots),
553
+ },
554
+ features: Object.fromEntries(ZCODE_FEATURE_KEYS.map((k) => [k, has(features[k])])),
555
+ };
556
+ const stats = skillStats({
557
+ dataRoot,
558
+ roots: values.skills.roots,
559
+ budget: values.skills.metadataBudget,
560
+ pluginsEnabled: cfg.plugins && typeof cfg.plugins === 'object' ? cfg.plugins.enabled !== false : true,
561
+ enabledPlugins: cfg.plugins && typeof cfg.plugins.enabledPlugins === 'object' ? cfg.plugins.enabledPlugins : {},
562
+ suppressedBuiltins: cfg.plugins && Array.isArray(cfg.plugins.suppressedBuiltins) ? cfg.plugins.suppressedBuiltins : [],
563
+ });
564
+ return { ok: true, values, configured, stats };
565
+ }
566
+
358
567
  export function startHelper({ port, token, dataRoot, state, agentsFile = defaultAgentsFile() }) {
359
568
  const configFile = join(dataRoot, 'zcodepro.json');
360
569
  const settingsFile = join(dataRoot, 'v2', 'setting.json');
@@ -376,9 +585,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
376
585
  json(res, 204, {});
377
586
  return;
378
587
  }
379
- // 背景图取文件:CSS url() 发不了自定义头,该路由在 token 校验之前放行。
380
- // 仅 Host 校验(127.0.0.1,防 DNS rebinding)+ 文件名白名单目录内取图,
381
- // 不接受路径参数之外的任何输入。文件夹模式从配置的目录里取(同样免 token)
588
+ // 背景图/壁纸取文件:媒体元素与 CSS url() 发不了自定义头,该路由在 token 校验
589
+ // 之前放行。仅 Host 校验(127.0.0.1,防 DNS rebinding)+ 文件名白名单目录内
590
+ // 取文件,不接受路径参数之外的任何输入。文件夹模式从配置的目录里取(同样免
591
+ // token)。流式输出并支持 Range:视频元素播放中会按字节段请求
382
592
  const serveBgFile = (name, dir, res2) => {
383
593
  const safe = sanitizeBgName(name);
384
594
  const file = safe && join(dir, safe);
@@ -388,30 +598,103 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
388
598
  return;
389
599
  }
390
600
  try {
391
- const buf = readFileSync(file);
392
- res2.writeHead(200, {
601
+ const st = statSync(file);
602
+ if (!st.isFile()) {
603
+ res2.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
604
+ res2.end('not found');
605
+ return;
606
+ }
607
+ const headers = {
393
608
  'Content-Type': BG_MIME[safe.slice(safe.lastIndexOf('.')).toLowerCase()] || 'application/octet-stream',
394
609
  'Cache-Control': 'no-cache',
610
+ 'Accept-Ranges': 'bytes',
611
+ 'Last-Modified': st.mtime.toUTCString(),
395
612
  'Access-Control-Allow-Origin': '*',
396
- });
397
- res2.end(buf);
613
+ };
614
+ // 条件请求命中直接 304:视频被反复重载时不再整段重下
615
+ const ims = String(req.headers['if-modified-since'] || '');
616
+ if (ims && Date.parse(ims) >= Math.floor(st.mtimeMs / 1000) * 1000) {
617
+ res2.writeHead(304, headers);
618
+ res2.end();
619
+ return;
620
+ }
621
+ // 读流出错(文件恰好被删/盘错误)不能裸抛:未发头回 500,已发则掐断连接
622
+ const streamFile = (opts) => {
623
+ const rs = createReadStream(file, opts);
624
+ rs.on('error', () => {
625
+ if (!res2.headersSent) {
626
+ res2.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
627
+ res2.end('read error');
628
+ } else {
629
+ res2.destroy();
630
+ }
631
+ });
632
+ res2.on('close', () => rs.destroy());
633
+ rs.pipe(res2);
634
+ };
635
+ const m = /^bytes=(\d*)-(\d*)$/.exec(String(req.headers.range || ''));
636
+ if (m && (m[1] || m[2])) {
637
+ // 后缀区间 bytes=-N 取末尾 N 字节(N 是个数不是终点);起点越界按 RFC 回 416
638
+ const suffix = !m[1];
639
+ const start = suffix ? Math.max(0, st.size - (+m[2] || 0)) : +m[1];
640
+ const end = suffix ? st.size - 1 : (m[2] ? Math.min(+m[2], st.size - 1) : st.size - 1);
641
+ if (st.size === 0 || start >= st.size || start > end) {
642
+ res2.writeHead(416, { 'Content-Range': `bytes */${st.size}` });
643
+ res2.end();
644
+ return;
645
+ }
646
+ res2.writeHead(206, { ...headers, 'Content-Range': `bytes ${start}-${end}/${st.size}`, 'Content-Length': end - start + 1 });
647
+ streamFile({ start, end });
648
+ return;
649
+ }
650
+ res2.writeHead(200, { ...headers, 'Content-Length': st.size });
651
+ streamFile();
398
652
  } catch {
399
653
  res2.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
400
654
  res2.end('read error');
401
655
  }
402
656
  };
403
657
  if (req.method === 'GET' && url.pathname.startsWith('/bg/file/')) {
404
- serveBgFile(decodeURIComponent(url.pathname.slice('/bg/file/'.length)), backgroundsDir(dataRoot), res);
658
+ const dec = decodeName(url.pathname.slice('/bg/file/'.length));
659
+ if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
660
+ serveBgFile(dec, backgroundsDir(dataRoot), res);
405
661
  return;
406
662
  }
407
663
  if (req.method === 'GET' && url.pathname.startsWith('/bg/folder/file/')) {
408
- const dir = loadConfig(configFile).theme.bg.folder;
664
+ // 分区背景可带自己的目录(?dir=);缺省用全局设置的文件夹。目录值缓存 5 秒:
665
+ // 媒体请求(含每个 Range 分段)都完整读盘解析配置太浪费
666
+ const qDir = url.searchParams.get('dir');
667
+ let dir;
668
+ if (qDir) {
669
+ // 本路由免鉴权(CSS url() 带不了头),dir 只认用户配置过的目录
670
+ //(全局文件夹 + 各分区目录)——否则任意外部页面可读本机任意目录的媒体文件
671
+ const cfgB = loadConfig(configFile).theme.bg;
672
+ const allowed = [cfgB.folder,
673
+ cfgB.regions?.left?.folder, cfgB.regions?.center?.folder, cfgB.regions?.right?.folder].filter(Boolean);
674
+ if (qDir.length > 4096 || !isAbsolute(qDir) || !allowed.includes(qDir)) {
675
+ json(res, 400, { ok: false, error: 'dir 参数无效或未配置' });
676
+ return;
677
+ }
678
+ dir = qDir;
679
+ } else {
680
+ if (Math.abs(Date.now() - folderCfgCache.at) > 5000) folderCfgCache = { at: Date.now(), dir: loadConfig(configFile).theme.bg.folder };
681
+ dir = folderCfgCache.dir;
682
+ }
409
683
  if (!dir) {
410
684
  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
411
685
  res.end('no folder');
412
686
  return;
413
687
  }
414
- serveBgFile(decodeURIComponent(url.pathname.slice('/bg/folder/file/'.length)), dir, res);
688
+ const dec = decodeName(url.pathname.slice('/bg/folder/file/'.length));
689
+ if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
690
+ serveBgFile(dec, dir, res);
691
+ return;
692
+ }
693
+ if (req.method === 'GET' && url.pathname.startsWith('/bg/transcode/file/')) {
694
+ const dec = decodeName(url.pathname.slice('/bg/transcode/file/'.length));
695
+ if (dec === null) { json(res, 400, { ok: false, error: '非法文件名编码' }); return; }
696
+ if (!/^[0-9a-f]{16}\.mp4$/.test(dec)) { json(res, 400, { ok: false, error: '非法转码文件名' }); return; } // 只服务 key.mp4:写一半的 .tmp.mp4 别被取走
697
+ serveBgFile(dec, transcodeDir(dataRoot), res);
415
698
  return;
416
699
  }
417
700
  if (token && req.headers['x-zcodepro-token'] !== token) {
@@ -430,6 +713,10 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
430
713
  if (req.method === 'POST' && url.pathname === '/config') {
431
714
  const body = await readBody(req);
432
715
  const current = loadConfig(configFile);
716
+ if (configUnreadable) {
717
+ json(res, 500, { ok: false, code: 'config-unreadable', error: 'zcodepro.json 读取失败或已损坏,拒绝写回以免清空配置;请先修复该文件' });
718
+ return;
719
+ }
433
720
  if (body && typeof body === 'object' && typeof body.proxy === 'string') {
434
721
  const v = body.proxy.trim();
435
722
  if (v === '') current.proxy = '';
@@ -525,6 +812,13 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
525
812
  maskOpacity: bt.bg && bt.bg.maskOpacity !== undefined ? bt.bg.maskOpacity : cur.bg.maskOpacity,
526
813
  blurPx: bt.bg && bt.bg.blurPx !== undefined ? bt.bg.blurPx : cur.bg.blurPx,
527
814
  panelOpacity: bt.bg && bt.bg.panelOpacity !== undefined ? bt.bg.panelOpacity : cur.bg.panelOpacity,
815
+ transition: bt.bg && bt.bg.transition !== undefined ? bt.bg.transition : cur.bg.transition,
816
+ fpsCap: bt.bg && bt.bg.fpsCap !== undefined ? bt.bg.fpsCap : cur.bg.fpsCap,
817
+ videoVolume: bt.bg && bt.bg.videoVolume !== undefined ? bt.bg.videoVolume : cur.bg.videoVolume,
818
+ playbackRate: bt.bg && bt.bg.playbackRate !== undefined ? bt.bg.playbackRate : cur.bg.playbackRate,
819
+ pauseOnHidden: bt.bg && bt.bg.pauseOnHidden !== undefined ? bt.bg.pauseOnHidden : cur.bg.pauseOnHidden,
820
+ pauseOnBlur: bt.bg && bt.bg.pauseOnBlur !== undefined ? bt.bg.pauseOnBlur : cur.bg.pauseOnBlur,
821
+ pauseOnBattery: bt.bg && bt.bg.pauseOnBattery !== undefined ? bt.bg.pauseOnBattery : cur.bg.pauseOnBattery,
528
822
  regions: bt.bg && bt.bg.regions !== undefined ? bt.bg.regions : cur.bg.regions,
529
823
  },
530
824
  };
@@ -545,6 +839,50 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
545
839
  json(res, 200, { ok: true, config: current });
546
840
  return;
547
841
  }
842
+ // —— ZCode CLI 行为配置(设置 → 行为 → ZCode CLI):读写 ~/.zcode/cli/config.json
843
+ // 里的 skills / features 两组键,另附技能清单检查统计 ——
844
+ if (req.method === 'GET' && url.pathname === '/zcode-config') {
845
+ json(res, 200, zcodeConfigSnapshot(zcodeDataRoot()));
846
+ return;
847
+ }
848
+ if (req.method === 'POST' && url.pathname === '/zcode-config') {
849
+ const body = await readBody(req);
850
+ const file = join(zcodeDataRoot(), 'cli', 'config.json');
851
+ // 文件存在但解析失败时拒绝写入:按空对象重写会把 provider 等配置清掉
852
+ let cfg;
853
+ try {
854
+ cfg = JSON.parse(readFileSync(file, 'utf8'));
855
+ } catch {
856
+ if (existsSync(file)) {
857
+ json(res, 500, { ok: false, code: 'zcode-config-unreadable', error: 'ZCode 配置文件无法解析,已中止写入' });
858
+ return;
859
+ }
860
+ cfg = {};
861
+ }
862
+ // 只收白名单里类型正确的键;数组类的 roots 整组覆盖(空数组 = 清空)
863
+ const s = body && typeof body === 'object' && body.skills && typeof body.skills === 'object' ? body.skills : {};
864
+ const skillsPatch = {};
865
+ if (typeof s.enabled === 'boolean') skillsPatch.enabled = s.enabled;
866
+ if (typeof s.includeInstructions === 'boolean') skillsPatch.includeInstructions = s.includeInstructions;
867
+ if (typeof s.metadataBudget === 'number' && Number.isFinite(s.metadataBudget) && s.metadataBudget >= 0 && s.metadataBudget <= 1000000) {
868
+ skillsPatch.metadataBudget = Math.round(s.metadataBudget);
869
+ }
870
+ if (Array.isArray(s.roots)) {
871
+ skillsPatch.roots = s.roots.filter((v) => typeof v === 'string' && v.trim()).map((v) => v.trim());
872
+ }
873
+ if (Object.keys(skillsPatch).length) {
874
+ cfg.skills = { ...(cfg.skills && typeof cfg.skills === 'object' ? cfg.skills : {}), ...skillsPatch };
875
+ }
876
+ const f = body && typeof body === 'object' && body.features && typeof body.features === 'object' ? body.features : {};
877
+ const featuresPatch = {};
878
+ for (const k of ZCODE_FEATURE_KEYS) if (typeof f[k] === 'boolean') featuresPatch[k] = f[k];
879
+ if (Object.keys(featuresPatch).length) {
880
+ cfg.features = { ...(cfg.features && typeof cfg.features === 'object' ? cfg.features : {}), ...featuresPatch };
881
+ }
882
+ writeJsonAtomic(file, cfg); // 写的是 cli/config.json:不走 saveConfig 的 zcodepro.json 拒写保护
883
+ json(res, 200, zcodeConfigSnapshot(zcodeDataRoot()));
884
+ return;
885
+ }
548
886
  // —— 主题背景图库:列表 / base64 上传 / 删除(取文件见上方免 token 的 /bg/file)——
549
887
  if (req.method === 'GET' && url.pathname === '/bg') {
550
888
  json(res, 200, { ok: true, files: listBgFiles(dataRoot), maxCount: BG_MAX_COUNT });
@@ -556,36 +894,28 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
556
894
  const body = await readBody(req, 16 << 20);
557
895
  const name = sanitizeBgName(body?.name);
558
896
  const data = typeof body?.data === 'string' ? body.data : '';
559
- if (!name) {
560
- json(res, 400, { ok: false, code: 'bg-name', error: '背景图文件名需以 png/jpg/jpeg/webp/gif/bmp/avif 结尾,且不含路径' });
897
+ if (!name || !BG_EXT.has(name.slice(name.lastIndexOf('.')).toLowerCase())) {
898
+ json(res, 400, { ok: false, code: 'bg-name', error: '图片文件名需以 png/jpg/jpeg/webp/gif/bmp/avif 结尾,且不含路径' });
561
899
  return;
562
900
  }
563
901
  if (!/^data:image\/[a-z+]+;base64,/.test(data)) {
564
- json(res, 400, { ok: false, code: 'bg-data', error: '背景图数据需为 data:image/*;base64 格式' });
902
+ json(res, 400, { ok: false, code: 'bg-data', error: '图片数据需为 data:image/*;base64 格式(视频走 /bg/upload)' });
565
903
  return;
566
904
  }
567
905
  const b64 = data.slice(data.indexOf(',') + 1);
568
906
  const buf = Buffer.from(b64, 'base64');
569
907
  if (!buf.length || buf.length > BG_MAX_BYTES) {
570
- json(res, 400, { ok: false, code: 'bg-size', error: `背景图需在 10MB 以内(收到 ${(buf.length / 1048576).toFixed(1)}MB)` });
908
+ json(res, 400, { ok: false, code: 'bg-size', error: `图片需在 10MB 以内(收到 ${(buf.length / 1048576).toFixed(1)}MB)` });
571
909
  return;
572
910
  }
573
911
  const dir = backgroundsDir(dataRoot);
574
912
  const existing = listBgFiles(dataRoot);
575
913
  if (!existsSync(join(dir, name)) && existing.length >= BG_MAX_COUNT) {
576
- json(res, 400, { ok: false, code: 'bg-count', error: `图库最多 ${BG_MAX_COUNT} 张,请先删除一些再上传` });
914
+ json(res, 400, { ok: false, code: 'bg-count', error: `图库最多 ${BG_MAX_COUNT} 个文件,请先删除一些再上传` });
577
915
  return;
578
916
  }
579
917
  // 图片解码校验:文件头魔数匹配扩展名(防止把可执行文件改名成 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()];
918
+ const magicOk = bgMagicOk(name, buf);
589
919
  if (!magicOk) {
590
920
  json(res, 400, { ok: false, code: 'bg-magic', error: '图片内容与扩展名不符' });
591
921
  return;
@@ -594,12 +924,12 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
594
924
  mkdirSync(dir, { recursive: true });
595
925
  const tmp = join(dir, name + '.tmp');
596
926
  writeFileSync(tmp, buf);
597
- renameSync(tmp, join(dir, name));
927
+ renameOrReplace(tmp, join(dir, name));
598
928
  } catch (errBg) {
599
- json(res, 500, { ok: false, code: 'bg-write', error: '写入背景图失败: ' + (errBg?.message || errBg) });
929
+ json(res, 500, { ok: false, code: 'bg-write', error: '写入壁纸文件失败: ' + (errBg?.message || errBg) });
600
930
  return;
601
931
  }
602
- json(res, 200, { ok: true, files: listBgFiles(dataRoot) });
932
+ json(res, 200, { ok: true, name, files: listBgFiles(dataRoot) }); // 回传清洗后的落盘名:客户端选中态要按它存
603
933
  return;
604
934
  }
605
935
  if (req.method === 'POST' && url.pathname === '/bg/delete') {
@@ -608,21 +938,153 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
608
938
  if (!name) { json(res, 400, { ok: false, code: 'bg-name', error: '非法文件名' }); return; }
609
939
  try {
610
940
  const file = join(backgroundsDir(dataRoot), name);
611
- if (existsSync(file)) unlinkSync(file);
941
+ if (existsSync(file)) {
942
+ cleanupBgTranscode(dataRoot, file);
943
+ unlinkOrDefer(file);
944
+ }
945
+ sweepDeferredBg(backgroundsDir(dataRoot));
946
+ sweepDeferredBg(transcodeDir(dataRoot)); // 转码缓存里被删片时改名的 .deleted-* 也扫
612
947
  } catch (errBg) {
613
- json(res, 500, { ok: false, code: 'bg-delete', error: '删除背景图失败: ' + (errBg?.message || errBg) });
948
+ json(res, 500, { ok: false, code: 'bg-delete', error: '删除壁纸文件失败: ' + (errBg?.message || errBg) });
614
949
  return;
615
950
  }
616
951
  json(res, 200, { ok: true, files: listBgFiles(dataRoot) });
617
952
  return;
618
953
  }
954
+ // —— 视频壁纸上传:raw 字节流直写文件(base64 会把内存翻倍,视频走这里)——
955
+ if (req.method === 'POST' && url.pathname === '/bg/upload') {
956
+ const name = sanitizeBgName(url.searchParams.get('name') || '');
957
+ const ext = name ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
958
+ if (!name || !VIDEO_EXT.has(ext)) {
959
+ json(res, 400, { ok: false, code: 'bg-name', error: '视频文件名需以 mp4/webm/mov 结尾,且不含路径' });
960
+ return;
961
+ }
962
+ const dir = backgroundsDir(dataRoot);
963
+ const existing = listBgFiles(dataRoot);
964
+ if (!existsSync(join(dir, name)) && existing.length >= BG_MAX_COUNT) {
965
+ json(res, 400, { ok: false, code: 'bg-count', error: `图库最多 ${BG_MAX_COUNT} 个文件,请先删除一些再上传` });
966
+ return;
967
+ }
968
+ let cleanupTmp = () => {};
969
+ try {
970
+ mkdirSync(dir, { recursive: true });
971
+ // tmp 名带随机后缀:同名并发上传不共用一个临时文件互相写坏
972
+ const tmp = join(dir, `${name}.${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}.tmp`);
973
+ cleanupTmp = () => { try { unlinkSync(tmp); } catch { /* 未写入过就没有 */ } };
974
+ const ws = createWriteStream(tmp);
975
+ ws.on('error', () => {
976
+ cleanupTmp();
977
+ if (!res.writableEnded) json(res, 500, { ok: false, code: 'bg-write', error: '写入视频失败(磁盘或权限)' });
978
+ });
979
+ let size = 0;
980
+ let head = Buffer.alloc(0);
981
+ let overflow = false;
982
+ for await (const chunk of req) {
983
+ size += chunk.length;
984
+ if (size > VIDEO_MAX_BYTES) {
985
+ overflow = true; // 超限后排干剩余字节,直接 break 会销毁连接、400 到不了客户端
986
+ continue;
987
+ }
988
+ if (head.length < 16) head = Buffer.concat([head, chunk]).slice(0, 16);
989
+ ws.write(chunk);
990
+ }
991
+ if (overflow) {
992
+ try { ws.destroy(); } catch { /* ignore */ }
993
+ cleanupTmp();
994
+ json(res, 400, { ok: false, code: 'bg-size', error: `视频需在 ${VIDEO_MAX_BYTES / 1048576}MB 以内` });
995
+ return;
996
+ }
997
+ // 等数据全部落盘再校验/改名:半截文件冒充成功是数据损坏
998
+ await new Promise((resolveWait) => {
999
+ if (ws.writableFinished) { resolveWait(); return; }
1000
+ ws.on('finish', resolveWait);
1001
+ ws.on('error', resolveWait); // 出错同样解除等待,不然请求处理函数永久挂起
1002
+ ws.end();
1003
+ });
1004
+ // 文件头魔数校验(防把可执行文件改名成 mp4 上传):mp4/mov 是 ftyp 盒,webm 是 EBML
1005
+ const magicOk = bgMagicOk(name, head);
1006
+ if (!size || !magicOk) {
1007
+ try { unlinkSync(tmp); } catch { /* ignore */ }
1008
+ json(res, 400, { ok: false, code: 'bg-magic', error: '视频内容与扩展名不符' });
1009
+ return;
1010
+ }
1011
+ renameOrReplace(tmp, join(dir, name));
1012
+ } catch (errBg) {
1013
+ cleanupTmp();
1014
+ if (!res.writableEnded) json(res, 500, { ok: false, code: 'bg-write', error: '写入视频失败: ' + (errBg?.message || errBg) });
1015
+ return;
1016
+ }
1017
+ json(res, 200, { ok: true, name, files: listBgFiles(dataRoot) });
1018
+ return;
1019
+ }
1020
+ // —— 视频帧率上限转码:起 ffmpeg 出抽帧版存缓存(key = 源路径+帧率的散列),
1021
+ // 注入层先播原片、转码完成再换;同一文件重复请求只起一个 ffmpeg
1022
+ if (req.method === 'POST' && url.pathname === '/bg/transcode') {
1023
+ const body = await readBody(req);
1024
+ const name = sanitizeBgName(body?.name || '');
1025
+ const ext = name ? name.slice(name.lastIndexOf('.')).toLowerCase() : '';
1026
+ const fps = Number(body?.fps);
1027
+ const dir = body?.from === 'folder' ? loadConfig(configFile).theme.bg.folder : backgroundsDir(dataRoot);
1028
+ const src = name && dir ? join(dir, name) : '';
1029
+ if (!src || !VIDEO_EXT.has(ext) || !existsSync(src)) {
1030
+ json(res, 400, { ok: false, code: 'transcode-src', error: '转码源视频无效' });
1031
+ return;
1032
+ }
1033
+ if (!TRANSCODE_FPS.has(fps)) {
1034
+ json(res, 400, { ok: false, code: 'transcode-fps', error: '帧率上限仅支持 15/30/60' });
1035
+ return;
1036
+ }
1037
+ const srcStat = statSync(src);
1038
+ // key 并入源文件大小与修改时间:同名覆盖后缓存自动失效重转
1039
+ const key = createHash('sha1').update(`${src}#${fps}#${srcStat.mtimeMs}#${srcStat.size}`).digest('hex').slice(0, 16);
1040
+ const out = join(transcodeDir(dataRoot), key + '.mp4');
1041
+ if (existsSync(out)) { json(res, 200, { ok: true, key, ready: true }); return; }
1042
+ if (!hasFfmpeg()) { json(res, 200, { ok: false, code: 'no-ffmpeg', error: '未检测到 ffmpeg,帧率上限不可用' }); return; }
1043
+ if (transcodeJobs.has(key)) { json(res, 200, { ok: true, key, ready: false }); return; }
1044
+ if (transcodeJobs.size >= TRANSCODE_MAX_CONCURRENCY) {
1045
+ // 并发满显式拒绝:让注入层本轮放弃,别空等 30 分钟轮询一个不会出现的文件
1046
+ json(res, 200, { ok: false, code: 'transcode-busy', error: '转码排队已满,稍后重试' });
1047
+ return;
1048
+ }
1049
+ if (true) {
1050
+ mkdirSync(transcodeDir(dataRoot), { recursive: true }); // 先建目录:同步抛错(磁盘满/无权限)不能把并发名额占住
1051
+ transcodeJobs.add(key);
1052
+ // 临时名必须保留 .mp4 后缀:ffmpeg 靠后缀识别容器,.tmp 会直接报
1053
+ // Unable to find a suitable output format(fpsCap 全程哑火的根因)
1054
+ const tmp = out + '.tmp.mp4';
1055
+ // 抽帧同时把长边压到 1920 以内:4K 素材按原始分辨率解码是视频壁纸
1056
+ // 发热/卡顿的大头,缩小后解码与合成开销成倍下降;小视频不放大
1057
+ const vf = `fps=${fps},scale=min(1920\\,iw):min(1920\\,ih):force_original_aspect_ratio=decrease`;
1058
+ let child;
1059
+ try {
1060
+ child = spawn('ffmpeg', ['-y', '-i', src, '-vf', vf, '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-c:a', 'aac', '-b:a', '128k', '-movflags', '+faststart', tmp], { stdio: 'ignore' });
1061
+ } catch (errSpawn) {
1062
+ transcodeJobs.delete(key); // 同步抛错也把名额放掉
1063
+ throw errSpawn;
1064
+ }
1065
+ child.on('exit', (code) => {
1066
+ transcodeJobs.delete(key);
1067
+ try {
1068
+ if (code === 0) renameOrReplace(tmp, out); // renameOrReplace 扛得住 Windows 文件占用
1069
+ else rmSync(tmp, { force: true });
1070
+ } catch { /* 缓存目录写失败:下次再试 */ }
1071
+ });
1072
+ child.on('error', () => { transcodeJobs.delete(key); });
1073
+ const killTimer = setTimeout(() => { try { child.kill(); } catch { /* 已退出 */ } }, 30 * 60 * 1000);
1074
+ child.on('exit', () => clearTimeout(killTimer));
1075
+ }
1076
+ json(res, 200, { ok: true, key, ready: false });
1077
+ return;
1078
+ }
619
1079
  // —— 文件夹背景:设置/刷新列表(目录本身存 theme.bg.folder,文件原地读
620
1080
  // 取不复制);切换由注入层定时驱动(随机或顺序)
621
1081
  const listFolderBg = (dir) => {
622
1082
  const st = statSync(dir);
623
1083
  if (!st.isDirectory()) return { error: '不是文件夹:' + dir };
624
1084
  const files = readdirSync(dir)
625
- .filter((name) => BG_EXT.has(name.slice(name.lastIndexOf('.')).toLowerCase()))
1085
+ .filter((name) => MEDIA_EXT.has(name.slice(name.lastIndexOf('.')).toLowerCase()))
1086
+ // 名字过不了取文件时二次清洗的不列(列了也取不到,还会误命中清洗后同名的文件)
1087
+ .filter((name) => sanitizeBgName(name) === name)
626
1088
  .map((name) => { const s = statSync(join(dir, name)); return { name, size: s.size, mtime: s.mtimeMs }; })
627
1089
  .sort((a, b) => a.name.localeCompare(b.name));
628
1090
  return { files };
@@ -948,6 +1410,8 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
948
1410
  // 的字段重建整份配置,直接覆盖会丢插件新增、面板还不认识的键
949
1411
  //(cardSandboxBudget/cardUi/interceptMode 等)
950
1412
  const merged = { ...(readJsonFile(file) || {}), ...cfg };
1413
+ // forceIntercept 为 null = 面板选了「自动」:从磁盘配置删掉该键,恢复插件缺省联动
1414
+ if (cfg.forceIntercept === null) delete merged.forceIntercept;
951
1415
  const tmp = file + '.tmp';
952
1416
  writeFileSync(tmp, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
953
1417
  renameSync(tmp, file);
@@ -1475,6 +1939,7 @@ export function startHelper({ port, token, dataRoot, state, agentsFile = default
1475
1939
  // 有更新任务在执行或排队时跳过这里的节流同步(任务本身会同步市场并刷新
1476
1940
  // 时间戳),避免两处同时跑 marketplace update
1477
1941
  if (!pluginsUpdateJob && Date.now() - lastMarketplaceSync > 30 * 60 * 1000) {
1942
+ await ensureZcodePluginsCloneFresh();
1478
1943
  await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
1479
1944
  lastMarketplaceSync = Date.now();
1480
1945
  }
@@ -1855,7 +2320,7 @@ async function syncBgListRemote(sync, proxyUrl) {
1855
2320
  if (!list.ok) return { error: list.error, code: 'sync-request', status: 502 };
1856
2321
  if (list.httpCode === 404) return { files: [] };
1857
2322
  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) => BG_EXT.has(f.name.slice(f.name.lastIndexOf('.')).toLowerCase())) };
2323
+ return { files: parseWebdavListing(list.body).filter((f) => MEDIA_EXT.has(f.name.slice(f.name.lastIndexOf('.')).toLowerCase())) };
1859
2324
  }
1860
2325
  async function syncBgPush({ sync, proxyUrl, dataRoot }) {
1861
2326
  const localFiles = listBgFiles(dataRoot);
@@ -1973,6 +2438,12 @@ async function runSettingsSync({ direction, dataRoot, configFile, config, proxyU
1973
2438
  : runSyncPull({ dataRoot, configFile, config, sync, proxyUrl });
1974
2439
  }
1975
2440
 
2441
+ // headroom.json 里值得同步/应用的判定:providers 注册非空才算有效——
2442
+ // 空对象或空注册不上传也不覆盖,免得把别台机器拉回无映射状态(401)
2443
+ function validHeadroomDoc(hr) {
2444
+ return !!hr && typeof hr === 'object' && !Array.isArray(hr) && Array.isArray(hr.providers) && hr.providers.length > 0;
2445
+ }
2446
+
1976
2447
  // 上传:每组独立一个云端文件(zcodepro.json / model.json,始终最新一版),勾选几组
1977
2448
  // 写几个。aliases 不再上传——3.16.1 起别名功能已停用(官方“编辑项目”改名),
1978
2449
  // 且各机器项目路径不同,同步别名只会互相带来无效路径。同一份内容再写一个带
@@ -1993,6 +2464,15 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
1993
2464
  docs.model = { provider: v2conf.provider };
1994
2465
  const pc = readJsonFile(join(dataRoot, 'v2', 'provider_config.json'));
1995
2466
  if (pc && typeof pc === 'object') docs.model.providerConfig = pc;
2467
+ // headroom.json 随模型组一起同步:它登记供应商的“keyHash → 上游”映射,
2468
+ // 缺了它新机器上指向 127.0.0.1:8787 的供应商会被 headroom 拒绝(401);
2469
+ // 文件里 key 只以 keyHash 形式存储,没有明文。providers 为空不算有效注册,
2470
+ // 不上传;instances(实例端口表)与 router(监听端口)是本机运行状态,不外发
2471
+ const hr = readJsonFile(defaultHeadroomFile());
2472
+ if (validHeadroomDoc(hr)) {
2473
+ const { instances: _inst, router: _router, ...hrSync } = hr;
2474
+ docs.model.headroom = hrSync;
2475
+ }
1996
2476
  // 注意:v2/credentials.json 不参与同步——里面是账号登录态(BigModel OAuth、
1997
2477
  // JWT、Coding Plan 账号 key)与应用自身数据,各机器用各自账号登录;
1998
2478
  // 自定义模型的 API Key 存在 config.json 的 provider.options.apiKey,随 provider 同步
@@ -2008,6 +2488,11 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
2008
2488
  for (const kind of Object.keys(docs)) {
2009
2489
  const remote = await fetchSyncDoc(sync, proxyUrl, kind);
2010
2490
  if (remote.error) return remote;
2491
+ // 本机没有有效 headroom 注册时保留云端旧键:没接入 headroom 的机器上传,
2492
+ // 不该把已传播给新机器的映射抹掉(本地空 ≠ 用户想清空云端)
2493
+ if (kind === 'model' && !docs[kind].headroom && validHeadroomDoc(remote.doc?.data?.headroom)) {
2494
+ docs[kind].headroom = remote.doc.data.headroom;
2495
+ }
2011
2496
  const doc = { app: 'zcode-pro', kind, format: 1, savedAt: stamp.toISOString(), data: docs[kind] };
2012
2497
  const docPath = join(dir, SYNC_FILES[kind]);
2013
2498
  writeFileSync(docPath, JSON.stringify(doc, null, 2), 'utf8');
@@ -2034,7 +2519,11 @@ async function runSyncPush({ dataRoot, configFile, config, sync, proxyUrl }) {
2034
2519
  try { rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
2035
2520
  }
2036
2521
  sync.lastPushAt = Date.now();
2037
- saveConfig(configFile, config);
2522
+ // 同步是分钟级网络流程:写回前重读配置、只合并本次时间戳,
2523
+ // 别把期间用户在设置弹窗的修改用这份旧快照盖掉
2524
+ const freshPush = loadConfig(configFile);
2525
+ freshPush.sync = { ...freshPush.sync, lastPushAt: sync.lastPushAt };
2526
+ saveConfig(configFile, freshPush);
2038
2527
  // 上传成功后清理超出保留个数的旧历史版本(best-effort,失败不影响上传结果)
2039
2528
  const pruned = await pruneSyncHistory(sync, proxyUrl, keep);
2040
2529
  // 背景图库镜像上传(勾了 zcodepro 组才传;设置文档已传走,图库失败单独报错,重试幂等)
@@ -2079,8 +2568,8 @@ async function runSyncPull({ dataRoot, configFile, config, sync, proxyUrl }) {
2079
2568
  // 把云端读到的各组数据落到本机(runSyncPull 与按文件的历史版本导入共用):
2080
2569
  // zcodepro 组覆盖功能/样式/代理(sync 配置与凭据保留本机的),别名不导入
2081
2570
  //(云端备份可能出自别的机器,路径在本机无效),model 组覆盖 v2/config.json 的
2082
- // provider 与 provider_config.json;覆盖前都留备份
2083
- function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
2571
+ // provider、provider_config.json 与 headroom.json;覆盖前都留备份。导出以便测试。
2572
+ export function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
2084
2573
  const applied = [];
2085
2574
  const backupFile = (p) => {
2086
2575
  try { if (existsSync(p)) copyFileSync(p, p + '.zcodepro-backup'); } catch { /* 备份失败不阻塞 */ }
@@ -2102,7 +2591,7 @@ function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
2102
2591
  const v = rz.proxy.trim();
2103
2592
  if (v === '' || /^https?:\/\/\S+:\d+$/.test(v)) next.proxy = v;
2104
2593
  }
2105
- next.sync = sync;
2594
+ next.sync = { ...next.sync, lastPullAt: sync.lastPullAt }; // 保留本机 sync 配置与凭据,只记本次拉取时间
2106
2595
  backupFile(configFile);
2107
2596
  saveConfig(configFile, next);
2108
2597
  applied.push('zcodepro');
@@ -2121,10 +2610,33 @@ function applySyncDocs({ docs, dataRoot, configFile, config, sync }) {
2121
2610
  backupFile(pcFile);
2122
2611
  atomicWrite(pcFile, pc);
2123
2612
  }
2613
+ // headroom.json 只在云端文档带有效注册时才覆盖(旧版云端文档没有该字段、
2614
+ // 或 providers 为空,都不动本机,免得清掉已有映射);instances(实例端口表)
2615
+ // 与 router(监听端口)是本机运行状态,云端的一律不用,保留本机的
2616
+ const hr = docs.model.headroom;
2617
+ if (validHeadroomDoc(hr)) {
2618
+ const hrFile = defaultHeadroomFile();
2619
+ const localHr = readJsonFile(hrFile);
2620
+ const { instances: _remoteInst, router: _remoteRouter, ...hrRest } = hr;
2621
+ const keepLocal = (localHr && typeof localHr === 'object') ? localHr : {};
2622
+ const nextHr = { ...hrRest };
2623
+ if (keepLocal.instances) nextHr.instances = keepLocal.instances;
2624
+ if (keepLocal.router) nextHr.router = keepLocal.router;
2625
+ backupFile(hrFile);
2626
+ atomicWrite(hrFile, nextHr);
2627
+ // 让路由立刻吃到新映射、缺的实例补起来(路由器本身每请求重读配置,
2628
+ // 只有新上游的实例需要这一步),失败不影响同步结果
2629
+ runHeadroomHook(['ensure'], 20000).catch(() => { /* 尽力而为 */ });
2630
+ }
2124
2631
  applied.push('model');
2125
2632
  }
2126
- // 没动 zcodepro.json 时,lastPullAt 也要写入配置文件(动了则已随 next 一起保存)
2127
- if (!applied.includes('zcodepro')) saveConfig(configFile, config);
2633
+ // 没动 zcodepro.json 时,lastPullAt 也要写入配置文件(动了则已随 next 一起保存)。
2634
+ // 写回前重读配置、只合并时间戳:别用旧快照盖掉同步期间用户的修改
2635
+ if (!applied.includes('zcodepro')) {
2636
+ const freshPull = loadConfig(configFile);
2637
+ freshPull.sync = { ...freshPull.sync, lastPullAt: sync.lastPullAt };
2638
+ saveConfig(configFile, freshPull);
2639
+ }
2128
2640
  return { applied };
2129
2641
  }
2130
2642
 
@@ -3009,8 +3521,12 @@ export function validateVisionConfig(raw) {
3009
3521
  // 连续失败跳过(0 = 不跳过);跳过时长(分钟)
3010
3522
  skipAfterFailures: clampInt(raw.skipAfterFailures, 0, 100, 2),
3011
3523
  skipMinutes: clampInt(raw.skipMinutes, 1, 10080, 30),
3012
- // 主模型能看图时是否也拦截识别(false = 跳过;flash 主模型始终不触发,见插件)
3013
- forceIntercept: raw.forceIntercept !== false,
3524
+ // 主模型能看图时的策略:true = 始终走识别代理(双重识别换卡片);false = 能看图就不拦截;
3525
+ // null = 自动(跟随宿主「模型设置」图片开关,zcode-vision ≥1.7.9 语义)。缺省不写键(POST
3526
+ // 磁盘合并保留原值);显式 null 由 POST 合并处删键(面板「自动」选项)
3527
+ ...(raw.forceIntercept !== undefined
3528
+ ? { forceIntercept: raw.forceIntercept === true ? true : raw.forceIntercept === false ? false : null }
3529
+ : {}),
3014
3530
  // 识图卡片展示:只在调用方显式给值时透传(面板开关用);缺省不写键,
3015
3531
  // 让 POST 的磁盘合并保留原值(zcode-pro 装机缺省 true 的补键逻辑见 GET /vision)
3016
3532
  ...(raw.cardUi !== undefined ? { cardUi: raw.cardUi === true } : {}),
@@ -3367,14 +3883,18 @@ export function readHeadroomConfig(file) {
3367
3883
  };
3368
3884
  }
3369
3885
 
3370
- // 写配置:与插件 hr_config_set 相同的三键整文件形状(该函数本就只保留这三个键)
3371
- function writeHeadroomConfig(file, cfg) {
3886
+ // 写配置:与插件 hr_config_set 同语义——只改这三个键,其余键(hr-join 注册的
3887
+ // providers/router/instances 等)原样保留,缺键不动对应旧值;三键重盖整文件
3888
+ // 会把供应商映射丢光,面板一调设置全员 401(插件侧 ADR-0008 修过同款坑)。
3889
+ // 导出以便测试。
3890
+ export function writeHeadroomConfig(file, cfg) {
3891
+ const cur = readJsonFile(file);
3892
+ const out = (cur && typeof cur === 'object' && !Array.isArray(cur)) ? { ...cur } : {};
3893
+ for (const k of ['kompressBackend', 'powerSaveCpu', 'powerWatchInterval']) {
3894
+ if (cfg[k] !== undefined) out[k] = cfg[k];
3895
+ }
3372
3896
  const tmp = file + '.tmp';
3373
- writeFileSync(tmp, JSON.stringify({
3374
- kompressBackend: cfg.kompressBackend,
3375
- powerSaveCpu: cfg.powerSaveCpu,
3376
- powerWatchInterval: cfg.powerWatchInterval,
3377
- }, null, 2) + '\n', 'utf8');
3897
+ writeFileSync(tmp, JSON.stringify(out, null, 2) + '\n', 'utf8');
3378
3898
  renameSync(tmp, file);
3379
3899
  }
3380
3900
 
@@ -3528,7 +4048,8 @@ async function headroomBinaryInfo() {
3528
4048
  }
3529
4049
 
3530
4050
  // 通用命令执行(headroom 本体的 pip 检查/升级等),输出合并 stdout+stderr,
3531
- // 环境按用途注入代理(默认 deps:headroom/rtk;市场路径不走这里)
4051
+ // 环境按用途注入代理(默认 deps:headroom/rtk;CLI 的市场命令走 runNodeScript,
4052
+ // 市场回退克隆的 git 操作走这里,scope 传 plugins)
3532
4053
  function execCapture(cmd, args, timeoutMs = 30000, scope = 'deps') {
3533
4054
  return new Promise((resolveRun) => {
3534
4055
  execFile(cmd, args, { timeout: timeoutMs, env: { ...process.env, ...proxyEnv({}, scope) }, windowsHide: true }, (err, stdout, stderr) => {
@@ -3921,18 +4442,66 @@ export function pluginUpdateStatus() {
3921
4442
  }
3922
4443
 
3923
4444
  // 市场未添加时自动补装(新机器上设置面板的“安装/更新”按钮一键可用):
3924
- // 读 known_marketplaces.json 判断,缺失则跑 plugins marketplace add。
3925
- // 失败 30 分钟内不重试(add 是 git clone,GitHub 不通时每次面板请求都会白等
4445
+ // 读 known_marketplaces.json 判断,缺失则跑 plugins marketplace add;add 退出后
4446
+ // 验证登记结果,未登记则回退 git clone 到本地走目录源——node 26 下 CLI 的 GitHub
4447
+ // 归档解包会挂死并以退出码 0 静默退出,add 看似成功、登记表却没写,不能只信退出码。
4448
+ // 失败 30 分钟内不重试(add 要访问 GitHub,网络不通时每次面板请求都会白等
3926
4449
  // 最长 120 秒);返回 null = 已存在无需处理,{ ok, cached } = 执行或跳过了 add。
3927
4450
  let lastMarketplaceAddFail = 0;
3928
- async function ensureZcodePluginsMarketplace() {
4451
+
4452
+ // 目录源回退的 git 克隆位置(sources/ 对 CLI 是无关目录,不干扰它自己的缓存布局)
4453
+ function zcodePluginsSourceDir() {
4454
+ return join(cliPluginsDir(), 'sources', ZCODE_PLUGINS_MARKETPLACE);
4455
+ }
4456
+
4457
+ function zcodePluginsMarketplaceRegistered() {
3929
4458
  const known = readJsonFile(join(cliPluginsDir(), 'known_marketplaces.json'));
3930
- const ids = new Set((known?.marketplaces || []).map((m) => m?.id).filter(Boolean));
3931
- if (ids.has(ZCODE_PLUGINS_MARKETPLACE)) return null;
4459
+ return (known?.marketplaces || []).some((m) => m?.id === ZCODE_PLUGINS_MARKETPLACE);
4460
+ }
4461
+
4462
+ // 目录源市场的内容刷新:marketplace update 对目录源只重读本地目录,
4463
+ // 新版本靠这里先 git pull(没有回退克隆时什么都不做)。导出以便测试。
4464
+ export async function pullZcodePluginsSourceClone() {
4465
+ const dir = zcodePluginsSourceDir();
4466
+ if (!existsSync(dir)) return null;
4467
+ return execCapture('git', ['-C', dir, 'pull', '--ff-only'], 60000, 'plugins');
4468
+ }
4469
+
4470
+ // 目录源刷新:目录不存在返回 null(正常 GitHub 源机器无克隆,不动作);存在则
4471
+ // git pull,pull 失败(残目录/上游强推无法快进)删掉重克隆自动恢复——坏目录不能让
4472
+ // 市场更新永远停摆。wantClone = true 时目录缺失也克隆(add 回退路径用)
4473
+ async function ensureZcodePluginsCloneFresh(wantClone = false) {
4474
+ const dir = zcodePluginsSourceDir();
4475
+ if (!existsSync(dir) && !wantClone) return null;
4476
+ const r = existsSync(dir) ? await pullZcodePluginsSourceClone() : null;
4477
+ if (r?.ok) return r;
4478
+ // pull 失败(残目录/上游强推):先克隆到临时目录、成功后才替换旧目录——
4479
+ // 网络瞬断时保留“过时但可用”的旧目录,别一删了之
4480
+ const tmp = dir + '.reclone';
4481
+ rmSync(tmp, { recursive: true, force: true });
4482
+ const c = await execCapture('git', ['clone', '--depth', '1', `https://github.com/${ZCODE_PLUGINS_MARKETPLACE_SOURCE}.git`, tmp], 120000, 'plugins');
4483
+ if (!c.ok) return c;
4484
+ rmSync(dir, { recursive: true, force: true });
4485
+ renameSync(tmp, dir);
4486
+ return c;
4487
+ }
4488
+
4489
+ // 目录源回退:克隆到本地后以目录源登记(marketplace add <目录>)。目录源的登记/
4490
+ // 更新/安装只做文件读写,不走 CLI 的 GitHub 归档解包
4491
+ async function addZcodePluginsMarketplaceFromClone() {
4492
+ const r = await ensureZcodePluginsCloneFresh(true);
4493
+ if (!r.ok) return r;
4494
+ return runZcodeCli(['plugins', 'marketplace', 'add', zcodePluginsSourceDir()], 120000);
4495
+ }
4496
+
4497
+ export async function ensureZcodePluginsMarketplace() {
4498
+ if (zcodePluginsMarketplaceRegistered()) return null;
3932
4499
  if (Date.now() - lastMarketplaceAddFail < 30 * 60 * 1000) return { ok: false, cached: true, error: '上次添加市场失败,30 分钟内不再自动重试' };
3933
- const r = await runZcodeCli(['plugins', 'marketplace', 'add', ZCODE_PLUGINS_MARKETPLACE_SOURCE], 120000);
3934
- if (!r.ok) lastMarketplaceAddFail = Date.now();
3935
- return { ok: r.ok, output: r.output, error: r.error };
4500
+ let r = await runZcodeCli(['plugins', 'marketplace', 'add', ZCODE_PLUGINS_MARKETPLACE_SOURCE], 120000);
4501
+ if (!zcodePluginsMarketplaceRegistered()) r = await addZcodePluginsMarketplaceFromClone();
4502
+ const ok = r.ok && zcodePluginsMarketplaceRegistered();
4503
+ if (!ok) lastMarketplaceAddFail = Date.now();
4504
+ return { ok, output: r.output, error: ok ? r.error : (r.error || 'marketplace add 未生效:登记表里没有该市场') };
3936
4505
  }
3937
4506
 
3938
4507
  // /plugins/update 并发控制:启动自动更新、打开设置弹窗时的自动触发、手动按钮、
@@ -3948,9 +4517,18 @@ async function runPluginsUpdateJob(body) {
3948
4517
  const steps = [];
3949
4518
  const added = await ensureZcodePluginsMarketplace();
3950
4519
  if (added) steps.push({ step: 'marketplace add', ok: added.ok, output: added.output || added.error });
4520
+ if (added && !added.ok) {
4521
+ // 市场没登记上时 update 必然报 Marketplace not found,别让它冒头顶掉真实错误
4522
+ return { status: 500, payload: { ok: false, code: 'plugins-update', error: added.error || added.output || 'marketplace add 失败', steps } };
4523
+ }
4524
+ const pull = await ensureZcodePluginsCloneFresh();
3951
4525
  const sync = await runZcodeCli(['plugins', 'marketplace', 'update', ZCODE_PLUGINS_MARKETPLACE], 60000);
3952
4526
  lastMarketplaceSync = Date.now();
3953
- steps.push({ step: 'marketplace update', ok: sync.ok, output: sync.output });
4527
+ steps.push({
4528
+ step: 'marketplace update',
4529
+ ok: sync.ok,
4530
+ output: [pull && !pull.ok ? `目录源刷新失败(git pull / 重克隆),本地目录源可能不是最新:${pull.output || pull.error}` : '', sync.output].filter(Boolean).join('\n'),
4531
+ });
3954
4532
  if (!sync.ok && sync.code !== 'cli-not-found') {
3955
4533
  return { status: 500, payload: { ok: false, code: 'plugins-update', error: sync.error || sync.output || 'marketplace update 失败', steps } };
3956
4534
  }