dsh-gallery 0.0.0-stage → 0.7.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/index.js ADDED
@@ -0,0 +1,1187 @@
1
+ /**
2
+ * 产出画廊 —— Host 半部。
3
+ *
4
+ * 负责三件事:
5
+ * 1. 解析「产出根目录」:运行时配置 > YAML 配置 > 自动探测(三级优先,见 resolveOptions);
6
+ * 2. 扫描根目录下最近 N 小时的图片 / 文件(深度受限、跳过批量目录、有扫描预算);
7
+ * 3. 通过 /api 的 exact Fetch 路由把「列表」「原始字节」「设置」交给浏览器半部。
8
+ *
9
+ * 缩略图压缩在客户端用 canvas 完成(本文件不生成缩略图,只给原始字节)。
10
+ */
11
+ import { promises as fsp, readFileSync, statSync } from 'node:fs'
12
+ import os from 'node:os'
13
+ import path from 'node:path'
14
+ import { zstdDecompressSync } from 'node:zlib'
15
+
16
+ /** 路由:一个 POST 通道,op 区分 list / raw / reveal / settings。exact Fetch 路由必须以 / 开头。 */
17
+ export const ROUTE = '/api/dsh-gallery'
18
+
19
+ /** DSH 主目录:优先环境变量,回退 ~/.dsh。 */
20
+ const DSH_HOME = process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh')
21
+
22
+ /** 会话日志根目录(DSH 主目录下的 sessions)。 */
23
+ const DEFAULT_SESSIONS_DIR = path.join(DSH_HOME, 'sessions')
24
+
25
+ /**
26
+ * 运行时配置文件的默认位置。
27
+ * 用户可在面板内直接改产出根目录,改动写这里;
28
+ * 它的优先级高于 cordis.patch.yml,低于用户显式传入的 root。
29
+ */
30
+ const DEFAULT_SETTINGS_FILE = path.join(DSH_HOME, 'dsh-gallery.json')
31
+
32
+ /**
33
+ * 会话日志里,哪些工具调用的参数算「本对话的产出」。
34
+ *
35
+ * 分三类:
36
+ * 1. **直接写文件**:write / edit / present 等 —— 路径一定是产出。
37
+ * 2. **脚本产出**:Python/命令行脚本跑出来的图,不在 write 调用里,
38
+ * 但 Agent 一定会用 read_image 打开它看效果 —— 所以「看过的图」也算产出。
39
+ * 这是「过程中即时可见」的关键:不然脚本生成的中间图和成品图都看不见。
40
+ * 3. **不看文件**:read / grep / glob 等纯读取,不算产出(避免把别人的文件算进来)。
41
+ */
42
+ const OUTPUT_TOOLS = new Set([
43
+ 'write',
44
+ 'edit',
45
+ 'present',
46
+ 'dsh_im_return_file',
47
+ 'ops_write_file',
48
+ 'ops_edit_file',
49
+ ])
50
+
51
+ /**
52
+ * 「Agent 看过的图片」也算本对话产出。
53
+ * 只对图片生效(read_image 的参数就是图片路径),风险低:
54
+ * Agent 不会无缘无故打开一张与任务无关的图。
55
+ */
56
+ const VIEW_TOOLS = new Set(['read_image'])
57
+
58
+ /** 只从 VIEW_TOOLS 里接受的图片扩展名。 */
59
+ const VIEW_IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.avif', '.tif', '.tiff'])
60
+
61
+ /** zstd 帧起始魔数(小端 0x28B52FFD)。一个 .zstd 文件可能由多帧拼接而成。 */
62
+ const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
63
+
64
+ /**
65
+ * 自动探测产出根目录(当用户既没配 root、也没有运行时配置时使用)。
66
+ *
67
+ * 策略:先找相对用户主目录的常见位置,再遍历可用盘符找 \DSH产出。
68
+ * 关键点:**代码里不出现任何写死的盘符**(是用循环遍历 A-Z 探测),
69
+ * 所以发布到别人机器上不会指向一个必然存在的错误路径,同时又能自动找到
70
+ * 装在其他盘上的产出目录。
71
+ *
72
+ * 探测结果会缓存 —— detectDefaultRoot 在每次请求的 resolveOptions 里都会被调用,
73
+ * 而遍历盘符涉及多次 stat,没必要每次都做。
74
+ */
75
+ let defaultRootCache = null
76
+
77
+ function detectDefaultRoot() {
78
+ if (defaultRootCache !== null) return defaultRootCache
79
+
80
+ const home = os.homedir()
81
+ const candidates = [
82
+ // 1. 用户主目录下
83
+ path.join(home, 'DSH产出'),
84
+ path.join(home, 'DSH-outputs'),
85
+ // 2. 文档下
86
+ path.join(home, 'Documents', 'DSH产出'),
87
+ path.join(home, 'Documents', 'DSH-outputs'),
88
+ // 3. 桌面下
89
+ path.join(home, 'Desktop', 'DSH产出'),
90
+ // 4. 下载目录下
91
+ path.join(home, 'Downloads', 'DSH产出'),
92
+ ]
93
+
94
+ // 5. 遍历可用盘符(Windows):C:\DSH产出、D:\DSH产出 …… 不写死任何字母
95
+ if (process.platform === 'win32') {
96
+ for (let code = 67; code <= 90; code += 1) { // C(67) → Z(90)
97
+ const drive = String.fromCharCode(code) + ':'
98
+ candidates.push(path.join(drive + path.sep, 'DSH产出'))
99
+ }
100
+ }
101
+
102
+ for (const candidate of candidates) {
103
+ try {
104
+ if (statSync(candidate).isDirectory()) {
105
+ defaultRootCache = candidate
106
+ return candidate
107
+ }
108
+ } catch {
109
+ // 不存在就试下一个
110
+ }
111
+ }
112
+
113
+ // 全都不存在:返回第一个候选,让面板显示「目录不存在」并给出修改入口
114
+ defaultRootCache = candidates[0]
115
+ return defaultRootCache
116
+ }
117
+
118
+ const DEFAULTS = {
119
+ // root 不在默认值里写死,由 resolveOptions 三级优先推导
120
+ windowHours: 24,
121
+ maxItems: 60,
122
+ maxDepth: 3,
123
+ extensions: ['.png', '.jpg', '.jpeg', '.webp'],
124
+ /**
125
+ * 文件画廊:只放「产出文件」——文档、代码、数据、压缩包、链接。
126
+ * 不收任何图片格式(图片归图片画廊),也不收音视频(体积大且非文档产出)。
127
+ */
128
+ fileExtensions: [
129
+ '.md', '.markdown', '.txt', '.log',
130
+ '.json', '.jsonl', '.csv', '.tsv', '.yaml', '.yml', '.xml', '.toml',
131
+ '.pdf', '.docx', '.doc', '.xlsx', '.xls', '.pptx', '.ppt', '.rtf', '.odt',
132
+ '.html', '.htm', '.mht',
133
+ '.zip', '.7z', '.rar', '.tar', '.gz',
134
+ '.py', '.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx',
135
+ '.ps1', '.sh', '.bat', '.cmd', '.sql', '.ipynb',
136
+ '.url', '.lnk', '.webloc',
137
+ '.dxf', '.dwg', '.skp', '.3dm',
138
+ ],
139
+ skipDirs: [
140
+ 'library_merged',
141
+ 'node_modules',
142
+ '.git',
143
+ '.svn',
144
+ '$RECYCLE.BIN',
145
+ 'System Volume Information',
146
+ '__pycache__',
147
+ '.venv',
148
+ 'venv',
149
+ '.cache',
150
+ ],
151
+ maxDirectories: 4000,
152
+ maxEntries: 60000,
153
+ maxImageBytes: 64 * 1024 * 1024,
154
+ }
155
+
156
+ /** 读取运行时配置文件(<DSH_HOME>/dsh-gallery.json);不存在或损坏返回空对象。 */
157
+ function readSettingsFile(file) {
158
+ try {
159
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
160
+ return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
161
+ } catch {
162
+ return {}
163
+ }
164
+ }
165
+
166
+ /**
167
+ * 读取「已隐藏」的相对路径集合。
168
+ * 隐藏只记录路径,不移动/删除文件;列表扫描时按此过滤。
169
+ * @param settingsFile - 配置文件路径。
170
+ * @returns 规范化(正斜杠)后的相对路径数组。
171
+ */
172
+ async function readHiddenList(settingsFile) {
173
+ const stored = readSettingsFile(settingsFile)
174
+ if (!Array.isArray(stored.hidden)) return []
175
+ return stored.hidden
176
+ .filter((p) => typeof p === 'string' && p !== '')
177
+ .map((p) => p.replace(/\\/g, '/'))
178
+ }
179
+
180
+ /**
181
+ * 解析最终配置。扫描目录(roots)的优先级(高 → 低):
182
+ * 1. 运行时配置文件的 roots 数组(面板内可加多个目录)
183
+ * 2. 运行时配置文件的 root(旧版单目录写法,兼容保留)
184
+ * 3. cordis.patch.yml 里配的 root / roots
185
+ * 4. 自动探测(detectDefaultRoot)
186
+ *
187
+ * 为什么支持多目录:DSH 一个会话一个 cwd,产出可能写在任意工作区下
188
+ * (例如 G:\DSH任务文件\xxx),不一定落在 G:\DSH产出。只配一个目录必然漏。
189
+ */
190
+ function resolveOptions(config) {
191
+ const merged = { ...DEFAULTS, ...(config ?? {}) }
192
+ const settingsFile = String(merged.settingsFile ?? DEFAULT_SETTINGS_FILE)
193
+ const stored = readSettingsFile(settingsFile)
194
+
195
+ // 收集所有候选目录
196
+ const collected = []
197
+ const pushRoot = (value) => {
198
+ if (typeof value === 'string' && value.trim() !== '') collected.push(value.trim())
199
+ }
200
+ const pushList = (value) => {
201
+ if (Array.isArray(value)) for (const v of value) pushRoot(v)
202
+ }
203
+
204
+ pushList(stored.roots) // 1. 设置里的多目录
205
+ pushRoot(stored.root) // 2. 设置里的单目录(旧格式)
206
+ pushList(merged.roots) // 3. YAML 多目录
207
+ pushRoot(merged.root) // 4. YAML 单目录
208
+
209
+ // 去重(Windows 路径大小写不敏感)
210
+ const deduped = []
211
+ const seenRoots = new Set()
212
+ const candidates = collected.length > 0 ? collected : [detectDefaultRoot()]
213
+ for (const r of candidates) {
214
+ const abs = path.resolve(r)
215
+ const key = abs.toLowerCase()
216
+ if (seenRoots.has(key)) continue
217
+ seenRoots.add(key)
218
+ deduped.push(abs)
219
+ }
220
+
221
+ const resolvedRoots = deduped.length > 0 ? deduped : [path.resolve(detectDefaultRoot())]
222
+ const rootSource = collected.length === 0
223
+ ? 'auto-detect'
224
+ : (typeof stored.root === 'string' || (Array.isArray(stored.roots) && stored.roots.length > 0) ? 'settings' : 'config')
225
+
226
+ return {
227
+ root: resolvedRoots[0],
228
+ roots: resolvedRoots,
229
+ rootSource,
230
+ settingsFile,
231
+ windowHours: numberOr(merged.windowHours, DEFAULTS.windowHours, 1, 24 * 30),
232
+ maxItems: numberOr(merged.maxItems, DEFAULTS.maxItems, 1, 500),
233
+ maxDepth: numberOr(merged.maxDepth, DEFAULTS.maxDepth, 0, 8),
234
+ extensions: arrayOfStrings(merged.extensions, DEFAULTS.extensions).map((e) => e.toLowerCase()),
235
+ fileExtensions: arrayOfStrings(merged.fileExtensions, DEFAULTS.fileExtensions).map((e) => e.toLowerCase()),
236
+ skipDirs: arrayOfStrings(merged.skipDirs, DEFAULTS.skipDirs).map((e) => e.toLowerCase()),
237
+ maxDirectories: numberOr(merged.maxDirectories, DEFAULTS.maxDirectories, 1, 200000),
238
+ maxEntries: numberOr(merged.maxEntries, DEFAULTS.maxEntries, 1, 1000000),
239
+ maxImageBytes: numberOr(merged.maxImageBytes, DEFAULTS.maxImageBytes, 1, 512 * 1024 * 1024),
240
+ }
241
+ }
242
+
243
+ function numberOr(value, fallback, min, max) {
244
+ const n = typeof value === 'number' ? value : Number(value)
245
+ if (!Number.isFinite(n)) return fallback
246
+ return Math.min(Math.max(Math.trunc(n), min), max)
247
+ }
248
+
249
+ function arrayOfStrings(value, fallback) {
250
+ if (!Array.isArray(value)) return [...fallback]
251
+ const cleaned = value.filter((entry) => typeof entry === 'string' && entry.trim() !== '').map((entry) => entry.trim())
252
+ return cleaned.length > 0 ? cleaned : [...fallback]
253
+ }
254
+
255
+ /** Windows 路径比较统一小写;用于「必须在根目录内」的判定。 */
256
+ function isInside(root, target) {
257
+ const a = root.toLowerCase().replace(/[\\/]+$/, '')
258
+ const b = target.toLowerCase().replace(/[\\/]+$/, '')
259
+ return b === a || b.startsWith(a + '\\') || b.startsWith(a + '/')
260
+ }
261
+
262
+ /** 只读图片头部若干字节,用于解析尺寸;失败返回 null。 */
263
+ async function readHead(fullPath, byteLimit) {
264
+ let handle
265
+ try {
266
+ handle = await fsp.open(fullPath, 'r')
267
+ const size = (await handle.stat()).size
268
+ const want = Math.min(byteLimit, size)
269
+ const buffer = Buffer.alloc(want)
270
+ const { bytesRead } = await handle.read(buffer, 0, want, 0)
271
+ return buffer.subarray(0, bytesRead)
272
+ } catch {
273
+ return null
274
+ } finally {
275
+ if (handle !== undefined) await handle.close().catch(() => {})
276
+ }
277
+ }
278
+
279
+ /** PNG:IHDR 在固定偏移。 */
280
+ function pngSize(buf) {
281
+ if (buf.length < 24) return null
282
+ if (buf[0] !== 0x89 || buf[1] !== 0x50 || buf[2] !== 0x4e || buf[3] !== 0x47) return null
283
+ const width = buf.readUInt32BE(16)
284
+ const height = buf.readUInt32BE(20)
285
+ return width > 0 && height > 0 ? { width, height } : null
286
+ }
287
+
288
+ /** JPEG:顺序找 SOF 段。 */
289
+ function jpegSize(buf) {
290
+ if (buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null
291
+ let p = 2
292
+ while (p + 9 < buf.length) {
293
+ if (buf[p] !== 0xff) {
294
+ p += 1
295
+ continue
296
+ }
297
+ let marker = buf[p + 1]
298
+ while (marker === 0xff && p + 1 < buf.length) {
299
+ p += 1
300
+ marker = buf[p + 1]
301
+ }
302
+ if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
303
+ p += 2
304
+ continue
305
+ }
306
+ if (marker === 0xd9 || marker === 0xda) return null
307
+ const length = buf.readUInt16BE(p + 2)
308
+ if (length < 2) return null
309
+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc
310
+ if (isSof) {
311
+ const height = buf.readUInt16BE(p + 5)
312
+ const width = buf.readUInt16BE(p + 7)
313
+ return width > 0 && height > 0 ? { width, height } : null
314
+ }
315
+ p += 2 + length
316
+ }
317
+ return null
318
+ }
319
+
320
+ /** WebP:RIFF 容器,VP8 / VP8L / VP8X 三种尺寸布局。 */
321
+ function webpSize(buf) {
322
+ if (buf.length < 32) return null
323
+ if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WEBP') return null
324
+ const chunk = buf.toString('ascii', 12, 16)
325
+ if (chunk === 'VP8 ') {
326
+ const width = buf.readUInt16LE(26) & 0x3fff
327
+ const height = buf.readUInt16LE(28) & 0x3fff
328
+ return width > 0 && height > 0 ? { width, height } : null
329
+ }
330
+ if (chunk === 'VP8L') {
331
+ const b0 = buf[21]
332
+ const b1 = buf[22]
333
+ const b2 = buf[23]
334
+ const b3 = buf[24]
335
+ const width = 1 + (((b0 & 0xff) | ((b1 & 0x3f) << 8)) & 0x3fff)
336
+ const height = 1 + ((((b1 & 0xc0) >> 6) | (b2 << 2) | ((b3 & 0x0f) << 10)) & 0x3fff)
337
+ return width > 0 && height > 0 ? { width, height } : null
338
+ }
339
+ if (chunk === 'VP8X') {
340
+ const width = 1 + (buf[24] | (buf[25] << 8) | (buf[26] << 16))
341
+ const height = 1 + (buf[27] | (buf[28] << 8) | (buf[29] << 16))
342
+ return width > 0 && height > 0 ? { width, height } : null
343
+ }
344
+ return null
345
+ }
346
+
347
+ /** 按扩展名挑选解析器;返回 {width,height} 或 null。 */
348
+ function measureImage(buf, ext) {
349
+ try {
350
+ if (buf === null) return null
351
+ if (ext === '.png') return pngSize(buf)
352
+ if (ext === '.jpg' || ext === '.jpeg') return jpegSize(buf)
353
+ if (ext === '.webp') return webpSize(buf)
354
+ return pngSize(buf) ?? jpegSize(buf) ?? webpSize(buf)
355
+ } catch {
356
+ return null
357
+ }
358
+ }
359
+
360
+ /**
361
+ * 校验用户想设的产出根目录:必须是绝对路径、必须存在、必须是目录。
362
+ * @param candidate - 用户输入的路径。
363
+ * @returns { ok, root?, reason? } —— 通过时 root 是规范化后的绝对路径。
364
+ */
365
+ export async function validateRootCandidate(candidate) {
366
+ if (typeof candidate !== 'string' || candidate.trim() === '') {
367
+ return { ok: false, reason: 'empty' }
368
+ }
369
+ const raw = candidate.trim()
370
+ // 只接受绝对路径(盘符或 UNC),相对路径无法确定含义
371
+ if (!path.isAbsolute(raw)) return { ok: false, reason: 'not-absolute' }
372
+ const resolved = path.resolve(raw)
373
+ try {
374
+ const st = await fsp.stat(resolved)
375
+ if (!st.isDirectory()) return { ok: false, reason: 'not-directory' }
376
+ } catch {
377
+ return { ok: false, reason: 'not-found' }
378
+ }
379
+ return { ok: true, root: resolved }
380
+ }
381
+
382
+ /**
383
+ * 把设置写进运行时配置文件。
384
+ * 只覆盖传入的字段,其余保留——避免把 windowHours 之类顺手清掉。
385
+ * @param settingsFile - 配置文件路径。
386
+ * @param patch - 要合并进去的部分设置。
387
+ */
388
+ export async function writeSettingsFile(settingsFile, patch) {
389
+ const current = readSettingsFile(settingsFile)
390
+ const next = { ...current, ...patch }
391
+ await fsp.mkdir(path.dirname(settingsFile), { recursive: true })
392
+ await fsp.writeFile(settingsFile, JSON.stringify(next, null, 2), 'utf8')
393
+ return next
394
+ }
395
+
396
+ /**
397
+ * 返回设置面板需要的全部信息。
398
+ * @param config - 插件配置。
399
+ */
400
+ async function readSettingsPayload(config) {
401
+ const opts = resolveOptions(config)
402
+ // 逐个检查每个 root 是否存在
403
+ const rootsInfo = []
404
+ for (const r of opts.roots) {
405
+ let exists = false
406
+ try {
407
+ exists = (await fsp.stat(r)).isDirectory()
408
+ } catch {
409
+ exists = false
410
+ }
411
+ rootsInfo.push({ path: r, exists })
412
+ }
413
+ const exists = rootsInfo.length > 0 ? rootsInfo[0].exists : false
414
+ // 已隐藏条数:供设置面板显示「已隐藏 N 个 · 全部恢复」
415
+ const hidden = await readHiddenList(opts.settingsFile)
416
+ return {
417
+ root: opts.root,
418
+ roots: opts.roots,
419
+ rootsInfo,
420
+ rootSource: opts.rootSource,
421
+ rootExists: exists,
422
+ settingsFile: opts.settingsFile,
423
+ windowHours: opts.windowHours,
424
+ maxItems: opts.maxItems,
425
+ maxDepth: opts.maxDepth,
426
+ hiddenCount: hidden.length,
427
+ // 前若干条隐藏项,供面板预览(不返回全部,避免配置很大时拖慢)
428
+ hiddenSample: hidden.slice(0, 10),
429
+ defaults: {
430
+ // 给前端「恢复默认」用:自动探测的结果
431
+ root: path.resolve(detectDefaultRoot()),
432
+ },
433
+ home: os.homedir(),
434
+ platform: process.platform,
435
+ }
436
+ }
437
+
438
+ /**
439
+ * 会话日志解压结果的缓存。
440
+ * 自动刷新每 5 秒一次,而一个活跃会话的日志解压后有 9MB 以上;
441
+ * 用「路径 + mtime + size」做键,日志没变就复用上次的解析结果。
442
+ */
443
+ const sessionLogCache = new Map()
444
+
445
+ /**
446
+ * 解压一个会话日志。
447
+ * DSH 的 session.v4.jsonl.zstd 是「多帧 zstd 拼接」(每次追加写一帧),
448
+ * 单次 zstdDecompressSync 只能解第一帧,所以必须按魔数切开逐帧解。
449
+ * @param fullPath - 日志文件绝对路径。
450
+ * @returns 解压后的完整文本;失败返回空串。
451
+ */
452
+ async function readSessionLogText(fullPath) {
453
+ let stat
454
+ let buf
455
+ try {
456
+ stat = await fsp.stat(fullPath)
457
+ const cacheKey = `${fullPath}|${stat.mtimeMs}|${stat.size}`
458
+ const cached = sessionLogCache.get(fullPath)
459
+ if (cached !== undefined && cached.key === cacheKey) return cached.text
460
+ buf = await fsp.readFile(fullPath)
461
+ } catch {
462
+ return ''
463
+ }
464
+ const offsets = []
465
+ let cursor = 0
466
+ while (cursor < buf.length) {
467
+ const hit = buf.indexOf(ZSTD_MAGIC, cursor)
468
+ if (hit < 0) break
469
+ offsets.push(hit)
470
+ cursor = hit + ZSTD_MAGIC.length
471
+ }
472
+ if (offsets.length === 0) return ''
473
+ const parts = []
474
+ for (const offset of offsets) {
475
+ try {
476
+ parts.push(zstdDecompressSync(buf.subarray(offset)))
477
+ } catch {
478
+ // 单帧损坏就跳过,不影响其余帧
479
+ }
480
+ }
481
+ const text = Buffer.concat(parts).toString('utf8')
482
+ sessionLogCache.set(fullPath, { key: `${fullPath}|${stat.mtimeMs}|${stat.size}`, text })
483
+ // 缓存只留最近若干条,避免长跑后堆积
484
+ if (sessionLogCache.size > 8) {
485
+ const oldest = sessionLogCache.keys().next().value
486
+ if (oldest !== undefined) sessionLogCache.delete(oldest)
487
+ }
488
+ return text
489
+ }
490
+
491
+ /** 在 ~/.dsh/sessions/<工作区分组>/<sessionId>/ 里定位某个会话目录。 */
492
+ async function locateSessionDir(sessionsDir, sessionId) {
493
+ if (typeof sessionId !== 'string' || sessionId === '') return null
494
+ // 防御:会话 id 只可能是 [A-Za-z0-9._-],不许出现路径分隔符
495
+ if (/[\\/]/.test(sessionId) || sessionId.includes('..')) return null
496
+ let groups
497
+ try {
498
+ groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
499
+ } catch {
500
+ return null
501
+ }
502
+ for (const group of groups) {
503
+ if (!group.isDirectory()) continue
504
+ const candidate = path.join(sessionsDir, String(group.name), sessionId)
505
+ try {
506
+ const stat = await fsp.stat(candidate)
507
+ if (stat.isDirectory()) return candidate
508
+ } catch {
509
+ // 继续找下一个分组
510
+ }
511
+ }
512
+ return null
513
+ }
514
+
515
+ /**
516
+ * 找出某个会话的全部**子会话**目录(子智能体)。
517
+ *
518
+ * 修法 C:DSH 里子智能体是独立会话,有自己的 session 日志目录,
519
+ * 它的 write/present 调用**不出现在主会话日志里**。
520
+ * 所以「当前对话」必须把子会话的产出也算进去。
521
+ *
522
+ * 判定依据:子会话日志首行的 `parentSession` 字段指向主会话 id。
523
+ *
524
+ * @param sessionsDir - 会话根目录。
525
+ * @param parentSessionId - 主会话 id。
526
+ * @returns 子会话日志的绝对路径数组。
527
+ */
528
+ async function findSubSessionLogs(sessionsDir, parentSessionId) {
529
+ const result = []
530
+ if (typeof parentSessionId !== 'string' || parentSessionId === '') return result
531
+ let groups
532
+ try {
533
+ groups = await fsp.readdir(sessionsDir, { withFileTypes: true })
534
+ } catch {
535
+ return result
536
+ }
537
+ for (const group of groups) {
538
+ if (!group.isDirectory()) continue
539
+ let sessions
540
+ try {
541
+ sessions = await fsp.readdir(path.join(sessionsDir, String(group.name)), { withFileTypes: true })
542
+ } catch {
543
+ continue
544
+ }
545
+ for (const s of sessions) {
546
+ if (!s.isDirectory()) continue
547
+ const logPath = path.join(sessionsDir, String(group.name), String(s.name), 'session.v4.jsonl.zstd')
548
+ try {
549
+ const st = await fsp.stat(logPath)
550
+ if (!st.isFile()) continue
551
+ } catch {
552
+ continue
553
+ }
554
+ // 读首行判断 parentSession;日志可能很大,只解第一帧就够(首行一定在第一帧)
555
+ const headText = await readSessionLogHead(logPath)
556
+ if (headText === '') continue
557
+ try {
558
+ const first = JSON.parse(headText.split('\n')[0])
559
+ if (first?.type === 'session' && first?.parentSession === parentSessionId) {
560
+ result.push(logPath)
561
+ }
562
+ } catch {
563
+ // 首行解析失败就跳过
564
+ }
565
+ }
566
+ }
567
+ return result
568
+ }
569
+
570
+ /**
571
+ * 只解压会话日志的第一帧,取首行(判断 parentSession 用,避免读整个 9MB 日志)。
572
+ * @param fullPath - 日志路径。
573
+ * @returns 首帧解出的文本;失败返回空串。
574
+ */
575
+ async function readSessionLogHead(fullPath) {
576
+ let buf
577
+ try {
578
+ buf = await fsp.readFile(fullPath)
579
+ } catch {
580
+ return ''
581
+ }
582
+ const hit = buf.indexOf(ZSTD_MAGIC, 0)
583
+ if (hit < 0) return ''
584
+ try {
585
+ return zstdDecompressSync(buf.subarray(hit)).toString('utf8')
586
+ } catch {
587
+ return ''
588
+ }
589
+ }
590
+
591
+ /** 递归收集 JSON 节点里所有以盘符开头的字符串(工具的 path 参数)。 */
592
+ function collectAbsolutePaths(node, sink) {
593
+ if (typeof node === 'string') {
594
+ if (/^[A-Za-z]:[\\/]/.test(node)) sink.push(node)
595
+ return
596
+ }
597
+ if (Array.isArray(node)) {
598
+ for (const entry of node) collectAbsolutePaths(entry, sink)
599
+ return
600
+ }
601
+ if (node !== null && typeof node === 'object') {
602
+ for (const key of Object.keys(node)) collectAbsolutePaths(node[key], sink)
603
+ }
604
+ }
605
+
606
+ /**
607
+ * 从会话日志里读出「本对话产出过的绝对路径」。
608
+ *
609
+ * 覆盖两类来源:
610
+ * 1. `write` / `edit` / `present` 等直接写文件的调用 —— 路径必是产出。
611
+ * 2. `read_image` 打开过的图片 —— 脚本(Python 等)生成的图不在 write 调用里,
612
+ * 但 Agent 一定会打开看效果。不纳入这一条,「过程中生成的图」在
613
+ * 「当前对话」里就完全看不见(只有全局资产能看到)。
614
+ *
615
+ * @param logText - 解压后的日志文本(每行一个 JSON)。
616
+ * @returns 绝对路径的 Set。
617
+ */
618
+ function extractOutputPaths(logText) {
619
+ const paths = new Set()
620
+ if (typeof logText !== 'string' || logText === '') return paths
621
+ const lines = logText.split('\n')
622
+ for (const line of lines) {
623
+ if (line === '') continue
624
+ // 快速预筛:只处理含 tool/call 的行,避免全量 JSON.parse
625
+ if (!line.includes('tool/call')) continue
626
+ let record
627
+ try {
628
+ record = JSON.parse(line)
629
+ } catch {
630
+ continue
631
+ }
632
+ if (record?.type !== 'tool/call') continue
633
+ const name = record?.data?.name
634
+ if (typeof name !== 'string') continue
635
+
636
+ const isWriter = OUTPUT_TOOLS.has(name)
637
+ const isViewer = VIEW_TOOLS.has(name)
638
+ if (!isWriter && !isViewer) continue
639
+
640
+ const rawArgs = record?.data?.arguments
641
+ if (typeof rawArgs !== 'string') continue
642
+ let args
643
+ try {
644
+ args = JSON.parse(rawArgs)
645
+ } catch {
646
+ continue
647
+ }
648
+ const found = []
649
+ collectAbsolutePaths(args, found)
650
+ for (const entry of found) {
651
+ if (isViewer) {
652
+ // 查看类工具只认图片:避免把 read_image 参数里偶尔出现的
653
+ // 目录、配置等非图片路径当成产出
654
+ const ext = path.extname(entry).toLowerCase()
655
+ if (!VIEW_IMAGE_EXTS.has(ext)) continue
656
+ }
657
+ paths.add(entry)
658
+ }
659
+ }
660
+ return paths
661
+ }
662
+
663
+ /**
664
+ * 算出「本对话」产出过的路径与任务目录。
665
+ *
666
+ * 支持多扫描目录(roots):逐个判断路径落在哪个 root 下。
667
+ * 修法 B:文件**直接躺在 root 根目录下**(没有子目录)时也要能匹配,
668
+ * 原实现只取「第一层目录」并要求至少两段,导致根目录文件全部判为 0。
669
+ *
670
+ * @param config - 用户配置。
671
+ * @param sessionId - 当前会话 id。
672
+ * @param allRoots - 已解析的扫描目录列表(不传则内部再解析一次)。
673
+ * @returns { ok, reason, taskDirs, paths, relPaths }
674
+ */
675
+ async function resolveSessionScope(config, sessionId, allRoots) {
676
+ const opts = resolveOptions(config)
677
+ const roots = Array.isArray(allRoots) && allRoots.length > 0 ? allRoots : opts.roots
678
+ const sessionsDir = typeof config?.sessionsDir === 'string' && config.sessionsDir !== ''
679
+ ? path.resolve(config.sessionsDir)
680
+ : DEFAULT_SESSIONS_DIR
681
+ const sessionDir = await locateSessionDir(sessionsDir, sessionId)
682
+ if (sessionDir === null) {
683
+ return { ok: false, reason: 'session-not-found', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
684
+ }
685
+ const logPath = path.join(sessionDir, 'session.v4.jsonl.zstd')
686
+ const logText = await readSessionLogText(logPath)
687
+ if (logText === '') {
688
+ return { ok: false, reason: 'log-empty', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
689
+ }
690
+ const allPaths = extractOutputPaths(logText)
691
+
692
+ // 修法 C:合并所有子会话(子智能体)的产出路径
693
+ const subLogs = await findSubSessionLogs(sessionsDir, sessionId)
694
+ for (const subLog of subLogs) {
695
+ const subText = await readSessionLogText(subLog)
696
+ if (subText === '') continue
697
+ for (const p of extractOutputPaths(subText)) allPaths.add(p)
698
+ }
699
+
700
+ const normalized = []
701
+ const relPaths = []
702
+ const taskDirs = new Set()
703
+
704
+ for (const entry of allPaths) {
705
+ const absolute = path.resolve(entry)
706
+ // 找出该路径属于哪个 root
707
+ let ownerRoot = null
708
+ for (const r of roots) {
709
+ if (isInside(r, absolute)) { ownerRoot = r; break }
710
+ }
711
+ if (ownerRoot === null) continue
712
+ normalized.push(absolute)
713
+
714
+ const rel = path.relative(ownerRoot, absolute)
715
+ const segs = rel.split(path.sep).filter((s) => s !== '')
716
+ relPaths.push(rel.split(path.sep).join('/'))
717
+ // 修法 B:有子目录时取第一层;没有子目录(文件直接在 root 下)时,
718
+ // 用空字符串占位,表示「只在根目录层匹配」,不再直接丢弃
719
+ if (segs.length >= 2) taskDirs.add(segs[0])
720
+ }
721
+
722
+ return {
723
+ ok: true,
724
+ reason: 'ok',
725
+ taskDirs: [...taskDirs],
726
+ paths: normalized,
727
+ relPaths,
728
+ subSessions: subLogs.length,
729
+ }
730
+ }
731
+
732
+ /**
733
+ * 扫描画廊候选:广度优先、深度受限、跳过批量目录、有目录/条目预算。
734
+ * 结果按修改时间倒序,只回传 maxItems 条,另外给出 total 供「还有 N 张」。
735
+ */
736
+ export async function scanGallery(config, kind = 'image', scope = 'global', sessionId = '', page = 1) {
737
+ const opts = resolveOptions(config)
738
+ const now = Date.now()
739
+ const cutoff = now - opts.windowHours * 3600_000
740
+ const isFile = kind === 'file'
741
+ const isSession = scope === 'session'
742
+ // 页码从 1 开始;非法值一律回到第 1 页
743
+ const currentPage = Math.max(1, Math.trunc(Number(page) || 1))
744
+ // 图片格式永远排除在文件画廊之外;防止用户配置误把图片塞进来
745
+ const extraImageEx = new Set(['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tif', '.tiff', '.heic', '.avif', '.ico'])
746
+ const rawExts = isFile ? opts.fileExtensions : opts.extensions
747
+ const extSet = new Set(rawExts.filter((e) => !(isFile && extraImageEx.has(e))))
748
+ const skipSet = new Set(opts.skipDirs)
749
+
750
+ // 当前对话范围:先解析会话日志(含子智能体会话),得到「本对话产出过的路径」
751
+ let scopeInfo = { ok: true, reason: 'global', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
752
+ let sessionRelSet = null
753
+ if (isSession) {
754
+ scopeInfo = await resolveSessionScope(config, sessionId, opts.roots)
755
+ // 修法 B:用「精确相对路径」集合判定,而不是只靠第一层目录名。
756
+ // 这样既能处理有子目录的情况,也能处理「文件直接躺在 root 根目录下」。
757
+ sessionRelSet = new Set((scopeInfo.relPaths ?? []).map((p) => p.toLowerCase()))
758
+ }
759
+
760
+ // 已隐藏的路径:扫描时直接跳过(不移动文件,只从列表里拿掉)
761
+ const hiddenSet = new Set(await readHiddenList(opts.settingsFile))
762
+
763
+ const matches = []
764
+ let directories = 0
765
+ let entries = 0
766
+ let capped = false
767
+ let anyRootExists = false
768
+ const missingRoots = []
769
+
770
+ // 遍历所有扫描目录(多目录支持)
771
+ for (const rootDir of opts.roots) {
772
+ if (directories >= opts.maxDirectories || entries >= opts.maxEntries) {
773
+ capped = true
774
+ break
775
+ }
776
+ let rootOk = false
777
+ try {
778
+ const st = await fsp.stat(rootDir)
779
+ rootOk = st.isDirectory()
780
+ } catch {
781
+ rootOk = false
782
+ }
783
+ if (!rootOk) {
784
+ missingRoots.push(rootDir)
785
+ continue
786
+ }
787
+ anyRootExists = true
788
+
789
+ const dirQueue = [{ dir: rootDir, depth: 0 }]
790
+ while (dirQueue.length > 0) {
791
+ if (directories >= opts.maxDirectories || entries >= opts.maxEntries) {
792
+ capped = true
793
+ break
794
+ }
795
+ const { dir, depth } = dirQueue.shift()
796
+ directories += 1
797
+ let dirents
798
+ try {
799
+ dirents = await fsp.readdir(dir, { withFileTypes: true })
800
+ } catch {
801
+ continue
802
+ }
803
+ for (const dirent of dirents) {
804
+ entries += 1
805
+ if (entries >= opts.maxEntries) {
806
+ capped = true
807
+ break
808
+ }
809
+ const entryName = String(dirent.name)
810
+ const fullPath = path.join(dir, entryName)
811
+ if (dirent.isDirectory()) {
812
+ if (depth + 1 > opts.maxDepth) continue
813
+ if (skipSet.has(entryName.toLowerCase())) continue
814
+ dirQueue.push({ dir: fullPath, depth: depth + 1 })
815
+ continue
816
+ }
817
+ if (!dirent.isFile()) continue
818
+ const ext = path.extname(entryName).toLowerCase()
819
+ if (!extSet.has(ext)) continue
820
+ // 当前对话范围:按精确相对路径判定(支持根目录文件与多层子目录)
821
+ const relPath = path.relative(rootDir, fullPath).split(path.sep).join('/')
822
+ if (sessionRelSet !== null && !sessionRelSet.has(relPath.toLowerCase())) continue
823
+ let stat
824
+ try {
825
+ stat = await fsp.stat(fullPath)
826
+ } catch {
827
+ continue
828
+ }
829
+ if (stat.size <= 0 || stat.mtimeMs < cutoff) continue
830
+ // 被隐藏的直接跳过(隐藏只影响列表展示,文件仍在磁盘上)
831
+ if (hiddenSet.has(relPath)) continue
832
+ matches.push({
833
+ relPath,
834
+ relKey: `${opts.roots.indexOf(rootDir)}:${relPath}`,
835
+ rootDir,
836
+ rootIndex: opts.roots.indexOf(rootDir),
837
+ name: entryName,
838
+ size: stat.size,
839
+ mtime: stat.mtimeMs,
840
+ extension: ext,
841
+ })
842
+ }
843
+ }
844
+ }
845
+
846
+ const rootMissing = !anyRootExists
847
+
848
+ matches.sort((a, b) => b.mtime - a.mtime)
849
+ const total = matches.length
850
+ // 分页:每页 maxItems 条,保留 total 供页码条使用
851
+ const pageCount = Math.max(1, Math.ceil(total / opts.maxItems))
852
+ const safePage = Math.min(currentPage, pageCount)
853
+ const offset = (safePage - 1) * opts.maxItems
854
+ const visible = matches.slice(offset, offset + opts.maxItems)
855
+
856
+ await Promise.all(visible.map(async (item) => {
857
+ if (isFile) {
858
+ // 文件画廊不解析图片尺寸
859
+ item.width = null
860
+ item.height = null
861
+ return
862
+ }
863
+ // 多目录:用该条目自己所属的 rootDir 拼绝对路径
864
+ const measured = measureImage(
865
+ await readHead(path.join(item.rootDir, ...item.relPath.split('/')), 65536),
866
+ item.extension,
867
+ )
868
+ item.width = measured?.width ?? null
869
+ item.height = measured?.height ?? null
870
+ }))
871
+
872
+ return {
873
+ kind,
874
+ scope: isSession ? 'session' : 'global',
875
+ scopeInfo: {
876
+ ok: scopeInfo.ok,
877
+ reason: scopeInfo.reason,
878
+ taskDirs: scopeInfo.taskDirs.length,
879
+ paths: scopeInfo.paths.length,
880
+ relPaths: (scopeInfo.relPaths ?? []).length,
881
+ // 子智能体会话数:> 0 表示已纳入它们的产出
882
+ subSessions: scopeInfo.subSessions ?? 0,
883
+ },
884
+ root: opts.root,
885
+ roots: opts.roots,
886
+ rootSource: opts.rootSource,
887
+ missingRoots,
888
+ windowHours: opts.windowHours,
889
+ maxItems: opts.maxItems,
890
+ maxDepth: opts.maxDepth,
891
+ generatedAt: now,
892
+ items: visible,
893
+ total,
894
+ // 分页信息,客户端据此渲染页码条
895
+ page: safePage,
896
+ pageCount,
897
+ pageSize: opts.maxItems,
898
+ // 「还有 N 张」= 当前页之外的总数(不再只是「被截掉的」)
899
+ hidden: Math.max(0, total - visible.length),
900
+ rootMissing,
901
+ scan: { directories, entries, capped },
902
+ }
903
+ }
904
+
905
+ /**
906
+ * 把一个相对路径解析成根目录内的绝对路径;越界或不存在返回 null。
907
+ * 多目录支持:第一个 root 找不到就逐个试其余 root。
908
+ * @param roots - 扫描目录列表(或单个 root 字符串,兼容旧调用)。
909
+ */
910
+ async function resolveReadable(roots, relPath, opts) {
911
+ const list = Array.isArray(roots) ? roots : [roots]
912
+ if (typeof relPath !== 'string' || relPath === '') return null
913
+ const normalized = relPath.replace(/\\/g, '/')
914
+ if (normalized.split('/').some((segment) => segment === '..' || segment === '')) return null
915
+ for (const root of list) {
916
+ const absolute = path.resolve(root, ...normalized.split('/'))
917
+ if (!isInside(root, absolute)) continue
918
+ try {
919
+ const stat = await fsp.stat(absolute)
920
+ if (!stat.isFile() || stat.size <= 0 || stat.size > opts.maxImageBytes) continue
921
+ return { absolute, stat, root }
922
+ } catch {
923
+ // 换下一个 root
924
+ }
925
+ }
926
+ return null
927
+ }
928
+
929
+ function contentTypeFor(ext) {
930
+ if (ext === '.png') return 'image/png'
931
+ if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg'
932
+ if (ext === '.webp') return 'image/webp'
933
+ return 'application/octet-stream'
934
+ }
935
+
936
+ /** 统一 JSON 响应。 */
937
+ function json(body, status) {
938
+ return new Response(JSON.stringify(body), {
939
+ status: status ?? 200,
940
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
941
+ })
942
+ }
943
+
944
+ /**
945
+ * Host 插件入口。仅依赖 connection(exact Fetch 路由);缺失时插件不激活而不是抛错。
946
+ */
947
+ export const inject = ['connection']
948
+
949
+ export function apply(ctx, config) {
950
+ ctx.effect(
951
+ () =>
952
+ ctx.connection.fetch.register({
953
+ path: ROUTE,
954
+ methods: ['POST'],
955
+ requestBody: 'buffered',
956
+ fetch: async (request) => {
957
+ let body
958
+ try {
959
+ body = await request.json()
960
+ } catch {
961
+ body = {}
962
+ }
963
+ const op = typeof body?.op === 'string' ? body.op : ''
964
+ // 每次请求都重新解析配置:这样用户在面板里改 root 后无需重启即生效
965
+ const resolved = resolveOptions(config)
966
+
967
+ if (op === 'list') {
968
+ try {
969
+ const kind = body?.kind === 'file' ? 'file' : 'image'
970
+ const scope = body?.scope === 'session' ? 'session' : 'global'
971
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''
972
+ return json(await scanGallery(config, kind, scope, sessionId, body?.page))
973
+ } catch (error) {
974
+ return json({ ok: false, error: { code: 'scan-failed', message: String(error?.message ?? error) } }, 500)
975
+ }
976
+ }
977
+
978
+ // 读取当前设置(含 root 来源、是否存在)
979
+ if (op === 'settings') {
980
+ try {
981
+ return json({ ok: true, settings: await readSettingsPayload(config) })
982
+ } catch (error) {
983
+ return json({ ok: false, error: { code: 'settings-failed', message: String(error?.message ?? error) } }, 500)
984
+ }
985
+ }
986
+
987
+ // 修改产出根目录(单值,保留兼容):会覆盖 roots,只留这一个
988
+ if (op === 'setRoot') {
989
+ const candidate = body?.root
990
+ const check = await validateRootCandidate(candidate)
991
+ if (check.ok !== true) {
992
+ const messages = {
993
+ empty: '目录不能为空',
994
+ 'not-absolute': '必须是绝对路径,例如 /Users/you/outputs 或 D:\\产出',
995
+ 'not-directory': '该路径不是目录',
996
+ 'not-found': '目录不存在',
997
+ }
998
+ return json({
999
+ ok: false,
1000
+ error: { code: check.reason, message: messages[check.reason] ?? '目录无效' },
1001
+ }, 400)
1002
+ }
1003
+ try {
1004
+ const opts = resolveOptions(config)
1005
+ // 写 roots 数组,并把旧的单值 root 清掉,避免重复
1006
+ const current = readSettingsFile(opts.settingsFile)
1007
+ delete current.root
1008
+ await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
1009
+ await fsp.writeFile(
1010
+ opts.settingsFile,
1011
+ JSON.stringify({ ...current, roots: [check.root] }, null, 2),
1012
+ 'utf8',
1013
+ )
1014
+ return json({ ok: true, settings: await readSettingsPayload(config) })
1015
+ } catch (error) {
1016
+ return json({ ok: false, error: { code: 'write-failed', message: String(error?.message ?? error) } }, 500)
1017
+ }
1018
+ }
1019
+
1020
+ // 追加一个扫描目录(多目录支持)
1021
+ if (op === 'addRoot') {
1022
+ const check = await validateRootCandidate(body?.root)
1023
+ if (check.ok !== true) {
1024
+ const messages = {
1025
+ empty: '目录不能为空',
1026
+ 'not-absolute': '必须是绝对路径',
1027
+ 'not-directory': '该路径不是目录',
1028
+ 'not-found': '目录不存在',
1029
+ }
1030
+ return json({ ok: false, error: { code: check.reason, message: messages[check.reason] ?? '目录无效' } }, 400)
1031
+ }
1032
+ try {
1033
+ const opts = resolveOptions(config)
1034
+ const current = readSettingsFile(opts.settingsFile)
1035
+ const list = Array.isArray(current.roots) && current.roots.length > 0
1036
+ ? current.roots.slice()
1037
+ : opts.roots.slice()
1038
+ // 去重(大小写不敏感)
1039
+ if (!list.some((r) => path.resolve(r).toLowerCase() === check.root.toLowerCase())) {
1040
+ list.push(check.root)
1041
+ }
1042
+ delete current.root
1043
+ await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
1044
+ await fsp.writeFile(opts.settingsFile, JSON.stringify({ ...current, roots: list }, null, 2), 'utf8')
1045
+ return json({ ok: true, settings: await readSettingsPayload(config) })
1046
+ } catch (error) {
1047
+ return json({ ok: false, error: { code: 'write-failed', message: String(error?.message ?? error) } }, 500)
1048
+ }
1049
+ }
1050
+
1051
+ // 移除一个扫描目录
1052
+ if (op === 'removeRoot') {
1053
+ const target = typeof body?.root === 'string' ? body.root.trim() : ''
1054
+ if (target === '') {
1055
+ return json({ ok: false, error: { code: 'empty', message: '缺少要移除的目录' } }, 400)
1056
+ }
1057
+ try {
1058
+ const opts = resolveOptions(config)
1059
+ const current = readSettingsFile(opts.settingsFile)
1060
+ const list = (Array.isArray(current.roots) && current.roots.length > 0
1061
+ ? current.roots.slice()
1062
+ : opts.roots.slice()
1063
+ ).filter((r) => path.resolve(r).toLowerCase() !== path.resolve(target).toLowerCase())
1064
+ if (list.length === 0) {
1065
+ return json({ ok: false, error: { code: 'last-root', message: '至少要保留一个扫描目录' } }, 400)
1066
+ }
1067
+ delete current.root
1068
+ await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
1069
+ await fsp.writeFile(opts.settingsFile, JSON.stringify({ ...current, roots: list }, null, 2), 'utf8')
1070
+ return json({ ok: true, settings: await readSettingsPayload(config) })
1071
+ } catch (error) {
1072
+ return json({ ok: false, error: { code: 'write-failed', message: String(error?.message ?? error) } }, 500)
1073
+ }
1074
+ }
1075
+
1076
+ if (op === 'raw') {
1077
+ const found = await resolveReadable(resolved.roots, body?.path, resolved)
1078
+ if (found === null) return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
1079
+ let bytes
1080
+ try {
1081
+ bytes = await fsp.readFile(found.absolute)
1082
+ } catch (error) {
1083
+ return json({ ok: false, error: { code: 'read-failed', message: String(error?.message ?? error) } }, 500)
1084
+ }
1085
+ return new Response(bytes, {
1086
+ status: 200,
1087
+ headers: {
1088
+ 'content-type': contentTypeFor(path.extname(found.absolute).toLowerCase()),
1089
+ 'content-length': String(bytes.byteLength),
1090
+ 'cache-control': 'no-store',
1091
+ },
1092
+ })
1093
+ }
1094
+
1095
+ // 在文件管理器中定位该文件(仅 Windows)
1096
+ if (op === 'reveal') {
1097
+ const found = await resolveReadable(resolved.roots, body?.path, resolved)
1098
+ if (found === null) return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
1099
+ try {
1100
+ const { spawn } = await import('node:child_process')
1101
+ if (process.platform === 'win32') {
1102
+ spawn('explorer.exe', [`/select,${found.absolute}`], { detached: true, stdio: 'ignore' }).unref()
1103
+ } else {
1104
+ spawn('xdg-open', [path.dirname(found.absolute)], { detached: true, stdio: 'ignore' }).unref()
1105
+ }
1106
+ return json({ ok: true })
1107
+ } catch (error) {
1108
+ return json({ ok: false, error: { code: 'reveal-failed', message: String(error?.message ?? error) } }, 500)
1109
+ }
1110
+ }
1111
+
1112
+ // ---------- 隐藏 / 取消隐藏 ----------
1113
+ // 隐藏只记路径,不动文件;列表扫描时过滤掉。
1114
+ if (op === 'hide' || op === 'unhide') {
1115
+ const rel = body?.path
1116
+ if (typeof rel !== 'string' || rel === '') {
1117
+ return json({ ok: false, error: { code: 'invalid-path', message: '缺少文件路径' } }, 400)
1118
+ }
1119
+ const normalized = rel.replace(/\\/g, '/')
1120
+ if (normalized.split('/').some((s) => s === '..' || s === '')) {
1121
+ return json({ ok: false, error: { code: 'invalid-path', message: '路径非法' } }, 400)
1122
+ }
1123
+ try {
1124
+ const opts = resolveOptions(config)
1125
+ const hidden = new Set(await readHiddenList(opts.settingsFile))
1126
+ if (op === 'hide') hidden.add(normalized)
1127
+ else hidden.delete(normalized)
1128
+ await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
1129
+ // 只改 hidden 字段,其余设置保留
1130
+ const current = readSettingsFile(opts.settingsFile)
1131
+ const next = { ...current, hidden: [...hidden] }
1132
+ await fsp.writeFile(opts.settingsFile, JSON.stringify(next, null, 2), 'utf8')
1133
+ return json({ ok: true, hidden: hidden.size })
1134
+ } catch (error) {
1135
+ return json({ ok: false, error: { code: 'hide-failed', message: String(error?.message ?? error) } }, 500)
1136
+ }
1137
+ }
1138
+
1139
+ // ---------- 全部恢复(清空隐藏列表)----------
1140
+ if (op === 'clearHidden') {
1141
+ try {
1142
+ const opts = resolveOptions(config)
1143
+ const current = readSettingsFile(opts.settingsFile)
1144
+ const before = Array.isArray(current.hidden) ? current.hidden.length : 0
1145
+ await fsp.mkdir(path.dirname(opts.settingsFile), { recursive: true })
1146
+ await fsp.writeFile(
1147
+ opts.settingsFile,
1148
+ JSON.stringify({ ...current, hidden: [] }, null, 2),
1149
+ 'utf8',
1150
+ )
1151
+ return json({ ok: true, cleared: before })
1152
+ } catch (error) {
1153
+ return json({ ok: false, error: { code: 'clear-failed', message: String(error?.message ?? error) } }, 500)
1154
+ }
1155
+ }
1156
+
1157
+ // ---------- 删除文件(不可逆,前端必须二次确认)----------
1158
+ if (op === 'delete') {
1159
+ const found = await resolveReadable(resolved.roots, body?.path, resolved)
1160
+ if (found === null) return json({ ok: false, error: { code: 'not-readable', message: '文件不存在或不可读' } }, 404)
1161
+ // 双保险:前端未明确确认则拒绝执行
1162
+ if (body?.confirm !== true) {
1163
+ return json({ ok: false, error: { code: 'need-confirm', message: '需要确认后才能删除' } }, 400)
1164
+ }
1165
+ try {
1166
+ await fsp.rm(found.absolute, { force: true })
1167
+ // 删除后从隐藏列表里清掉,避免残留
1168
+ const opts = resolveOptions(config)
1169
+ const hidden = new Set(await readHiddenList(opts.settingsFile))
1170
+ const rel = body?.path.replace(/\\/g, '/')
1171
+ if (hidden.has(rel)) {
1172
+ hidden.delete(rel)
1173
+ const current = readSettingsFile(opts.settingsFile)
1174
+ await fsp.writeFile(opts.settingsFile, JSON.stringify({ ...current, hidden: [...hidden] }, null, 2), 'utf8')
1175
+ }
1176
+ return json({ ok: true, deleted: found.absolute })
1177
+ } catch (error) {
1178
+ return json({ ok: false, error: { code: 'delete-failed', message: String(error?.message ?? error) } }, 500)
1179
+ }
1180
+ }
1181
+
1182
+ return json({ ok: false, error: { code: 'unknown-op', message: `未知操作:${op}` } }, 400)
1183
+ },
1184
+ }),
1185
+ 'dsh-gallery: api route',
1186
+ )
1187
+ }