dsh-gallery 0.11.2 → 0.12.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.
package/host/media.js ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * 媒体支撑:路径解析、HTTP Range、流式下发、MIME。
3
+ *
4
+ * S1 拆分自 index.js(行为零变化)。
5
+ */
6
+
7
+ import { promises as fsp, readFileSync, statSync, createReadStream } from 'node:fs'
8
+ import path from 'node:path'
9
+ import { isInside } from './fsutil.js'
10
+
11
+ export async function resolveReadable(roots, relPath, opts, byteCap) {
12
+ const list = Array.isArray(roots) ? roots : [roots]
13
+ if (typeof relPath !== 'string' || relPath === '') return null
14
+ const cap = typeof byteCap === 'number' && byteCap > 0 ? byteCap : opts.maxImageBytes
15
+ const normalized = relPath.replace(/\\/g, '/')
16
+ if (normalized.split('/').some((segment) => segment === '..' || segment === '')) return null
17
+ for (const root of list) {
18
+ const absolute = path.resolve(root, ...normalized.split('/'))
19
+ if (!isInside(root, absolute)) continue
20
+ try {
21
+ const stat = await fsp.stat(absolute)
22
+ if (!stat.isFile() || stat.size <= 0 || stat.size > cap) continue
23
+ return { absolute, stat, root }
24
+ } catch {
25
+ // 换下一个 root
26
+ }
27
+ }
28
+ return null
29
+ }
30
+
31
+ /**
32
+ * 解析 `Range: bytes=...` 头。
33
+ * 支持:常规 (0-99)、开放 (100-)、后缀 (-50)、不可满足 (416)。
34
+ * 多区间取第一个(HTTP 规范允许)。
35
+ */
36
+
37
+ export function parseMediaRange(raw, size) {
38
+ if (raw === undefined) return null
39
+ const m = /^bytes=(.+)$/i.exec(String(raw).trim())
40
+ if (!m) return null
41
+ const spec = m[1].split(',')[0].trim()
42
+ if (spec === '') return null
43
+ if (spec.startsWith('-')) {
44
+ const suffix = Number(spec.slice(1))
45
+ if (!Number.isFinite(suffix) || suffix <= 0) return null
46
+ if (suffix >= size) return { start: 0, end: size - 1 }
47
+ return { start: size - suffix, end: size - 1 }
48
+ }
49
+ const dash = spec.indexOf('-')
50
+ if (dash === -1) return null
51
+ const startText = spec.slice(0, dash)
52
+ const endText = spec.slice(dash + 1)
53
+ const start = startText === '' ? 0 : Number(startText)
54
+ const end = endText === '' ? size - 1 : Number(endText)
55
+ if (!Number.isInteger(start) || start < 0 || !Number.isInteger(end)) return null
56
+ if (start >= size) return { unsatisfiable: true }
57
+ return { start, end: Math.min(end, size - 1) }
58
+ }
59
+
60
+ /**
61
+ * 用 Node 原生 res 输出一个媒体文件,支持 HTTP Range。
62
+ * 这是 206 能工作的关键:req/res 直写,不经过 DSH 的 fetch 网关。
63
+ */
64
+
65
+ export function serveMedia(req, res, filePath, size, type) {
66
+ const headers = {
67
+ 'content-type': type,
68
+ 'accept-ranges': 'bytes',
69
+ 'cache-control': 'no-cache',
70
+ 'x-content-type-options': 'nosniff',
71
+ }
72
+ const range = parseMediaRange(req.headers.range, size)
73
+
74
+ if (range !== null && range.unsatisfiable === true) {
75
+ res.writeHead(416, { ...headers, 'content-range': `bytes */${size}` })
76
+ res.end()
77
+ return
78
+ }
79
+
80
+ if (range !== null) {
81
+ const { start, end } = range
82
+ res.writeHead(206, {
83
+ ...headers,
84
+ 'content-range': `bytes ${start}-${end}/${size}`,
85
+ 'content-length': String(end - start + 1),
86
+ })
87
+ if (req.method === 'HEAD') { res.end(); return }
88
+ const stream = createReadStream(filePath, { start, end })
89
+ stream.on('error', () => res.destroy())
90
+ stream.pipe(res)
91
+ return
92
+ }
93
+
94
+ res.writeHead(200, { ...headers, 'content-length': String(size) })
95
+ if (req.method === 'HEAD') { res.end(); return }
96
+ const stream = createReadStream(filePath)
97
+ stream.on('error', () => res.destroy())
98
+ stream.pipe(res)
99
+ }
100
+
101
+ export function contentTypeFor(ext) {
102
+ if (ext === '.png') return 'image/png'
103
+ if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg'
104
+ if (ext === '.webp') return 'image/webp'
105
+ if (ext === '.gif') return 'image/gif'
106
+ if (ext === '.bmp') return 'image/bmp'
107
+ // 音视频(v0.10.1):让浏览器 <video>/<audio> 能直接解码
108
+ if (ext === '.mp4' || ext === '.m4v') return 'video/mp4'
109
+ if (ext === '.webm') return 'video/webm'
110
+ if (ext === '.ogv') return 'video/ogg'
111
+ if (ext === '.mov') return 'video/quicktime'
112
+ if (ext === '.mkv') return 'video/x-matroska'
113
+ if (ext === '.mp3') return 'audio/mpeg'
114
+ if (ext === '.wav') return 'audio/wav'
115
+ if (ext === '.m4a' || ext === '.aac') return 'audio/mp4'
116
+ if (ext === '.flac') return 'audio/flac'
117
+ if (ext === '.ogg' || ext === '.oga') return 'audio/ogg'
118
+ if (ext === '.opus') return 'audio/opus'
119
+ return 'application/octet-stream'
120
+ }
121
+
122
+ /** 统一 JSON 响应。 */
@@ -0,0 +1,25 @@
1
+ // GENERATED from src/shared/protocol.js — 请勿手改
2
+ /**
3
+ * 协议常量 —— Host 与 Client 的唯一真源。
4
+ *
5
+ * 拆分前 ROUTE / MEDIA_ROUTE / 扩展名表在 client.js 和 index.js 里各存一份,
6
+ * 改路由要改两处、漏一处就打不通。现在由 scripts/build.mjs 同时生成
7
+ * host/protocol.js 并注入 client bundle,两边不可能再漂移。
8
+ *
9
+ * 注意:本文件是 ESM,注入 client 时构建器会剥掉 export 关键字。
10
+ */
11
+
12
+ /** 与 Host 半部一致的路由(exact Fetch 路由的 path)。 */
13
+ export const ROUTE = '/api/dsh-gallery'
14
+
15
+ /** 音视频直链(GET,支持 Range)——给 <video>/<audio> 用。 */
16
+ export const MEDIA_ROUTE = '/api/dsh-gallery/media'
17
+
18
+ /** 图片扩展名(缩略图/查看器/原图模式共用)。 */
19
+ export const IMAGE_EXTS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp']
20
+
21
+ /** 视频扩展名(与 Host 的 VIDEO_EXTS 保持一致)。 */
22
+ export const VIDEO_EXTS = ['.mp4', '.webm', '.mov', '.m4v', '.mkv', '.avi', '.ogv']
23
+
24
+ /** 音频扩展名。 */
25
+ export const AUDIO_EXTS = ['.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.oga', '.opus', '.wma']
package/host/scan.js ADDED
@@ -0,0 +1,531 @@
1
+ /**
2
+ * 产出扫描:提取资产、扫描目录、分页。
3
+ *
4
+ * S1 拆分自 index.js(行为零变化)。
5
+ */
6
+
7
+ import { promises as fsp, readFileSync, statSync, createReadStream } from 'node:fs'
8
+ import path from 'node:path'
9
+ import { ASSET_CATEGORY, classifyAsset } from './classify.js'
10
+ import { BASH_TOOLS, DEFAULT_SESSIONS_DIR, OUTPUT_TOOLS, VIDEO_EXTS, VIEW_IMAGE_EXTS, VIEW_TOOLS } from './constants.js'
11
+ import { isInside, measureImage, readHead } from './fsutil.js'
12
+ import { buildGroups } from './groups.js'
13
+ import { collectAbsolutePaths, findSubSessionLogs, locateSessionDir, readSessionLogText } from './session.js'
14
+ import { readHiddenList, resolveOptions } from './settings.js'
15
+ import { buildSessionIndex } from './session-index.js'
16
+
17
+ export function extractAssetInfo(logText, sessionStartMs = 0) {
18
+ const assets = new Map()
19
+ if (typeof logText !== 'string' || logText === '') return assets
20
+
21
+ const ensure = (abs) => {
22
+ if (!assets.has(abs)) {
23
+ assets.set(abs, { presented: false, written: false, viewed: false, bashMentioned: false })
24
+ }
25
+ return assets.get(abs)
26
+ }
27
+
28
+ for (const line of logText.split('\n')) {
29
+ if (line === '') continue
30
+ // 快速预筛:只处理含 tool/call 的行,避免全量 JSON.parse
31
+ if (!line.includes('tool/call')) continue
32
+ let record
33
+ try {
34
+ record = JSON.parse(line)
35
+ } catch {
36
+ continue
37
+ }
38
+ if (record?.type !== 'tool/call') continue
39
+ const name = record?.data?.name
40
+ if (typeof name !== 'string') continue
41
+
42
+ const rawArgs = record?.data?.arguments
43
+ if (typeof rawArgs !== 'string') continue
44
+ let args
45
+ try {
46
+ args = JSON.parse(rawArgs)
47
+ } catch {
48
+ continue
49
+ }
50
+
51
+ // ---- bash / pwsh:命令文本里提到的路径,只作为「非输入」的弱证据 ----
52
+ if (BASH_TOOLS.has(name)) {
53
+ const cmdText = `${args?.command ?? ''} ${args?.script_path ?? ''}`
54
+ const re = /[A-Za-z]:[\\/][^\s"'|&;<>()*?]+/g
55
+ for (const m of cmdText.matchAll(re)) {
56
+ const candidate = m[0].replace(/[\\/]+$/, '')
57
+ const ext = path.extname(candidate).toLowerCase()
58
+ // 只接受看起来像文件的路径(有扩展名)
59
+ if (ext === '') continue
60
+ try {
61
+ const info = ensure(path.resolve(candidate))
62
+ info.bashMentioned = true
63
+ } catch {
64
+ // 解析失败就跳过
65
+ }
66
+ }
67
+ continue
68
+ }
69
+
70
+ const isWriter = OUTPUT_TOOLS.has(name)
71
+ const isViewer = VIEW_TOOLS.has(name)
72
+ const isPresenter = name === 'present'
73
+ if (!isWriter && !isViewer && !isPresenter) continue
74
+
75
+ // present 的参数结构是 { files: [{ path, description }]}
76
+ let found = []
77
+ if (isPresenter && Array.isArray(args?.files)) {
78
+ found = args.files.map((f) => f?.path).filter((p) => typeof p === 'string')
79
+ } else {
80
+ collectAbsolutePaths(args, found)
81
+ }
82
+
83
+ for (const entry of found) {
84
+ if (isViewer) {
85
+ // 查看类工具只认图片:避免把 read_image 参数里偶尔出现的
86
+ // 目录、配置等非图片路径当成产出
87
+ const ext = path.extname(entry).toLowerCase()
88
+ if (!VIEW_IMAGE_EXTS.has(ext)) continue
89
+ }
90
+ const info = ensure(path.resolve(entry))
91
+ if (isPresenter) info.presented = true
92
+ else if (isViewer) info.viewed = true
93
+ else info.written = true
94
+ }
95
+ }
96
+
97
+ // ---- 归类 ----
98
+ for (const [abs, info] of assets) {
99
+ classifyAsset(abs, info, sessionStartMs)
100
+ }
101
+
102
+ return assets
103
+ }
104
+
105
+ /**
106
+ * 从会话日志首行解析会话开始时间(createdAt)。
107
+ * @param logText - 解压后的日志文本。
108
+ * @returns 毫秒时间戳;解析失败返回 0。
109
+ */
110
+
111
+ export function parseSessionStartMs(logText) {
112
+ if (typeof logText !== 'string' || logText === '') return 0
113
+ const firstLine = logText.split('\n')[0]
114
+ try {
115
+ const first = JSON.parse(firstLine)
116
+ return typeof first?.createdAt === 'number' ? first.createdAt : 0
117
+ } catch {
118
+ return 0
119
+ }
120
+ }
121
+
122
+ /**
123
+ * 给单个资产定分类。**唯一**的分类入口,别在别处复制这套判据。
124
+ *
125
+ * 规则(按优先级):
126
+ * 1. present 过 → 最终
127
+ * 2. 「只被 read_image 看过」是候选输入,但必须能证明它早于会话开始就存在:
128
+ * - mtime < 会话开始 → 输入(用户预先提供的素材)
129
+ * - mtime >= 会话开始 → 中间(会话期间生成的,脚本产出常见这种)
130
+ * 3. 其余 → 中间
131
+ *
132
+ * 为什么必须看时间:「被 read_image 看过」既可能是用户素材,也可能是脚本产出的图,
133
+ * Agent 两者都会打开看。实测反例:
134
+ * - architecture.png:write 写的是脚本,file_path 不是它,只在 read_image 出现
135
+ * - 缩略图尺寸对比.png:文件名写在 bash 的 python 代码里,不是绝对路径
136
+ * 这两类旧判据都会误判成「输入」。
137
+ *
138
+ * @param abs - 文件绝对路径。
139
+ * @param info - extractAssetInfo 收集到的动作标记(会被写入 category)。
140
+ * @param sessionStartMs - 会话开始时间;0 表示未知(此时不做输入判定)。
141
+ */
142
+
143
+ export function extractOutputPaths(logText) {
144
+ return new Set(extractAssetInfo(logText).keys())
145
+ }
146
+
147
+ /**
148
+ * 算出「本对话」产出过的路径与任务目录。
149
+ *
150
+ * 支持多扫描目录(roots):逐个判断路径落在哪个 root 下。
151
+ * 修法 B:文件**直接躺在 root 根目录下**(没有子目录)时也要能匹配,
152
+ * 原实现只取「第一层目录」并要求至少两段,导致根目录文件全部判为 0。
153
+ *
154
+ * @param config - 用户配置。
155
+ * @param sessionId - 当前会话 id。
156
+ * @param allRoots - 已解析的扫描目录列表(不传则内部再解析一次)。
157
+ * @returns { ok, reason, taskDirs, paths, relPaths }
158
+ */
159
+
160
+ export async function resolveSessionScope(config, sessionId, allRoots) {
161
+ const opts = resolveOptions(config)
162
+ const roots = Array.isArray(allRoots) && allRoots.length > 0 ? allRoots : opts.roots
163
+ const sessionsDir = typeof config?.sessionsDir === 'string' && config.sessionsDir !== ''
164
+ ? path.resolve(config.sessionsDir)
165
+ : DEFAULT_SESSIONS_DIR
166
+ const sessionDir = await locateSessionDir(sessionsDir, sessionId)
167
+ if (sessionDir === null) {
168
+ return { ok: false, reason: 'session-not-found', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
169
+ }
170
+ const logPath = path.join(sessionDir, 'session.v4.jsonl.zstd')
171
+ const logText = await readSessionLogText(logPath)
172
+ if (logText === '') {
173
+ return { ok: false, reason: 'log-empty', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
174
+ }
175
+ // 会话开始时间:用于区分「用户素材」与「会话期间产出」
176
+ const sessionStartMs = parseSessionStartMs(logText)
177
+ const allAssets = extractAssetInfo(logText, sessionStartMs)
178
+
179
+ // 修法 C:合并所有子会话(子智能体)的产出路径
180
+ const subLogs = await findSubSessionLogs(sessionsDir, sessionId)
181
+ for (const subLog of subLogs) {
182
+ const subText = await readSessionLogText(subLog)
183
+ if (subText === '') continue
184
+ for (const [abs, info] of extractAssetInfo(subText, sessionStartMs)) {
185
+ const existing = allAssets.get(abs)
186
+ if (existing) {
187
+ // 合并标记:任一处 present 就算最终
188
+ existing.presented = existing.presented || info.presented
189
+ existing.written = existing.written || info.written
190
+ existing.viewed = existing.viewed || info.viewed
191
+ existing.bashMentioned = existing.bashMentioned || info.bashMentioned
192
+ } else {
193
+ allAssets.set(abs, info)
194
+ }
195
+ }
196
+ }
197
+
198
+ // 合并后重新归类(因为 presented/written 可能变了)。
199
+ // 统一走 classifyAsset,避免两处判据分叉 —— v0.8.1 就是这里漏改导致分类不准。
200
+ for (const [abs, info] of allAssets) {
201
+ classifyAsset(abs, info, sessionStartMs)
202
+ }
203
+
204
+ const normalized = []
205
+ const relPaths = []
206
+ const taskDirs = new Set()
207
+ // relPath(小写) → 分类,供扫描时标注
208
+ const categoryByRel = new Map()
209
+
210
+ for (const [abs, info] of allAssets) {
211
+ const absolute = path.resolve(abs)
212
+ // 找出该路径属于哪个 root
213
+ let ownerRoot = null
214
+ for (const r of roots) {
215
+ if (isInside(r, absolute)) { ownerRoot = r; break }
216
+ }
217
+ if (ownerRoot === null) continue
218
+ normalized.push(absolute)
219
+
220
+ const rel = path.relative(ownerRoot, absolute)
221
+ const segs = rel.split(path.sep).filter((s) => s !== '')
222
+ const relPath = rel.split(path.sep).join('/')
223
+ relPaths.push(relPath)
224
+ categoryByRel.set(relPath.toLowerCase(), info.category)
225
+ // 修法 B:有子目录时取第一层;没有子目录(文件直接在 root 下)时,
226
+ // 用空字符串占位,表示「只在根目录层匹配」,不再直接丢弃
227
+ if (segs.length >= 2) taskDirs.add(segs[0])
228
+ }
229
+
230
+ return {
231
+ ok: true,
232
+ reason: 'ok',
233
+ taskDirs: [...taskDirs],
234
+ paths: normalized,
235
+ relPaths,
236
+ categoryByRel,
237
+ subSessions: subLogs.length,
238
+ }
239
+ }
240
+
241
+ /**
242
+ * 扫描画廊候选:广度优先、深度受限、跳过批量目录、有目录/条目预算。
243
+ * 结果按修改时间倒序,只回传 maxItems 条,另外给出 total 供「还有 N 张」。
244
+ */
245
+
246
+ export async function scanGallery(config, kind = 'image', scope = 'global', sessionId = '', page = 1) {
247
+ const opts = resolveOptions(config)
248
+ const now = Date.now()
249
+ const cutoff = now - opts.windowHours * 3600_000
250
+ const isFile = kind === 'file'
251
+ const isMedia = kind === 'media'
252
+ const isSession = scope === 'session'
253
+ // 页码从 1 开始;非法值一律回到第 1 页
254
+ const currentPage = Math.max(1, Math.trunc(Number(page) || 1))
255
+ // 图片格式永远排除在文件画廊之外;防止用户配置误把图片塞进来
256
+ const extraImageEx = new Set(['.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tif', '.tiff', '.heic', '.avif', '.ico'])
257
+ // 音视频同样不能混进文件画廊(v0.10.1):音视频有自己的画廊
258
+ const mediaEx = new Set(opts.mediaExtensions)
259
+ let rawExts
260
+ if (isFile) rawExts = opts.fileExtensions
261
+ else if (isMedia) rawExts = opts.mediaExtensions
262
+ else rawExts = opts.extensions
263
+ const extSet = new Set(rawExts.filter((e) => !(
264
+ (isFile && extraImageEx.has(e))
265
+ || (isFile && mediaEx.has(e))
266
+ || (isMedia && extraImageEx.has(e))
267
+ )))
268
+ const skipSet = new Set(opts.skipDirs)
269
+
270
+ // 当前对话范围:先解析会话日志(含子智能体会话),得到「本对话产出过的路径」
271
+ let scopeInfo = { ok: true, reason: 'global', taskDirs: [], paths: [], relPaths: [], subSessions: 0 }
272
+ let sessionRelSet = null
273
+ if (isSession) {
274
+ scopeInfo = await resolveSessionScope(config, sessionId, opts.roots)
275
+ // 修法 B:用「精确相对路径」集合判定,而不是只靠第一层目录名。
276
+ // 这样既能处理有子目录的情况,也能处理「文件直接躺在 root 根目录下」。
277
+ sessionRelSet = new Set((scopeInfo.relPaths ?? []).map((p) => p.toLowerCase()))
278
+ }
279
+
280
+ // 会话索引:建立「文件 → 所属对话 + 分类」的映射,供全局按对话分组用
281
+ const sessionsDir = typeof config?.sessionsDir === 'string' && config.sessionsDir !== ''
282
+ ? path.resolve(config.sessionsDir)
283
+ : DEFAULT_SESSIONS_DIR
284
+ let sessionIndex = null
285
+ // 全局模式才需要索引(当前对话模式已有自己的 scopeInfo)
286
+ if (!isSession) {
287
+ sessionIndex = await buildSessionIndex(sessionsDir, opts, {
288
+ readSessionLogText,
289
+ extractAssetInfo,
290
+ })
291
+ }
292
+
293
+ // 文件绝对路径 → { sessionId, title, category }
294
+ const ownerByAbs = new Map()
295
+ if (sessionIndex !== null) {
296
+ for (const [sid, entry] of sessionIndex) {
297
+ for (const [abs, cat] of entry.files) {
298
+ // 同一个文件被多个对话产出时,取最近的那个对话
299
+ const prev = ownerByAbs.get(abs)
300
+ if (prev === undefined || entry.createdAt > prev.createdAt) {
301
+ ownerByAbs.set(abs, {
302
+ sessionId: sid,
303
+ title: entry.title || '',
304
+ createdAt: entry.createdAt,
305
+ category: cat,
306
+ })
307
+ }
308
+ }
309
+ }
310
+ }
311
+
312
+ // 已隐藏的路径:扫描时直接跳过(不移动文件,只从列表里拿掉)
313
+ const hiddenSet = new Set(await readHiddenList(opts.settingsFile))
314
+
315
+ const matches = []
316
+ let directories = 0
317
+ let entries = 0
318
+ let capped = false
319
+ let anyRootExists = false
320
+ const missingRoots = []
321
+
322
+ // 遍历所有扫描目录(多目录支持)
323
+ for (const rootDir of opts.roots) {
324
+ if (directories >= opts.maxDirectories || entries >= opts.maxEntries) {
325
+ capped = true
326
+ break
327
+ }
328
+ let rootOk = false
329
+ try {
330
+ const st = await fsp.stat(rootDir)
331
+ rootOk = st.isDirectory()
332
+ } catch {
333
+ rootOk = false
334
+ }
335
+ if (!rootOk) {
336
+ missingRoots.push(rootDir)
337
+ continue
338
+ }
339
+ anyRootExists = true
340
+
341
+ const dirQueue = [{ dir: rootDir, depth: 0 }]
342
+ while (dirQueue.length > 0) {
343
+ if (directories >= opts.maxDirectories || entries >= opts.maxEntries) {
344
+ capped = true
345
+ break
346
+ }
347
+ const { dir, depth } = dirQueue.shift()
348
+ directories += 1
349
+ let dirents
350
+ try {
351
+ dirents = await fsp.readdir(dir, { withFileTypes: true })
352
+ } catch {
353
+ continue
354
+ }
355
+ for (const dirent of dirents) {
356
+ entries += 1
357
+ if (entries >= opts.maxEntries) {
358
+ capped = true
359
+ break
360
+ }
361
+ const entryName = String(dirent.name)
362
+ const fullPath = path.join(dir, entryName)
363
+ if (dirent.isDirectory()) {
364
+ if (depth + 1 > opts.maxDepth) continue
365
+ if (skipSet.has(entryName.toLowerCase())) continue
366
+ dirQueue.push({ dir: fullPath, depth: depth + 1 })
367
+ continue
368
+ }
369
+ if (!dirent.isFile()) continue
370
+ const ext = path.extname(entryName).toLowerCase()
371
+ if (!extSet.has(ext)) continue
372
+ // 当前对话范围:按精确相对路径判定(支持根目录文件与多层子目录)
373
+ const relPath = path.relative(rootDir, fullPath).split(path.sep).join('/')
374
+ if (sessionRelSet !== null && !sessionRelSet.has(relPath.toLowerCase())) continue
375
+ let stat
376
+ try {
377
+ stat = await fsp.stat(fullPath)
378
+ } catch {
379
+ continue
380
+ }
381
+ if (stat.size <= 0 || stat.mtimeMs < cutoff) continue
382
+ // 音视频:超过体积上限的直接跳过(视频可能几百 MB,列出来点开就卡)
383
+ if (isMedia && stat.size > opts.maxMediaBytes) continue
384
+ // 被隐藏的直接跳过(隐藏只影响列表展示,文件仍在磁盘上)
385
+ if (hiddenSet.has(relPath)) continue
386
+ matches.push({
387
+ relPath,
388
+ relKey: `${opts.roots.indexOf(rootDir)}:${relPath}`,
389
+ rootDir,
390
+ rootIndex: opts.roots.indexOf(rootDir),
391
+ name: entryName,
392
+ size: stat.size,
393
+ mtime: stat.mtimeMs,
394
+ extension: ext,
395
+ // 音视频区分「视频 / 音频」,客户端据此选 <video> 还是 <audio>
396
+ ...(isMedia ? { mediaType: VIDEO_EXTS.includes(ext) ? 'video' : 'audio' } : {}),
397
+ })
398
+ }
399
+ }
400
+ }
401
+
402
+ const rootMissing = !anyRootExists
403
+
404
+ // 给每个条目附加「分类」和「所属对话」
405
+ for (const item of matches) {
406
+ const abs = path.join(item.rootDir, ...item.relPath.split('/'))
407
+ const owner = ownerByAbs.get(abs)
408
+ item.absPath = abs
409
+ if (isSession) {
410
+ item.category = (scopeInfo.categoryByRel?.get(item.relPath.toLowerCase())) ?? null
411
+ item.sessionId = sessionId
412
+ } else if (owner !== undefined) {
413
+ item.category = owner.category
414
+ item.sessionId = owner.sessionId
415
+ item.sessionTitle = owner.title
416
+ item.sessionCreatedAt = owner.createdAt
417
+ } else {
418
+ // 不属于任何已知对话的文件:归到「历史资产」,分类记为**未归类**
419
+ // 不能兜底成 input —— 那会把 4995 个历史文件全标成「输入」
420
+ item.category = ASSET_CATEGORY.UNKNOWN
421
+ item.sessionId = null
422
+ }
423
+ }
424
+
425
+ matches.sort((a, b) => b.mtime - a.mtime)
426
+ const total = matches.length
427
+ // 分页:每页 maxItems 条,保留 total 供页码条使用
428
+ // 全局分组模式下不分页(客户端自己分组折叠),所有条目都返回摘要
429
+ const pageCount = isSession
430
+ ? Math.max(1, Math.ceil(total / opts.maxItems))
431
+ : Math.max(1, Math.ceil(total / opts.maxItems))
432
+ const safePage = Math.min(currentPage, pageCount)
433
+ const offset = (safePage - 1) * opts.maxItems
434
+ const visible = matches.slice(offset, offset + opts.maxItems)
435
+
436
+ await Promise.all(visible.map(async (item) => {
437
+ if (isFile || isMedia) {
438
+ // 文件/音视频画廊不解析图片尺寸
439
+ item.width = null
440
+ item.height = null
441
+ return
442
+ }
443
+ // 多目录:用该条目自己所属的 rootDir 拼绝对路径
444
+ const measured = measureImage(
445
+ await readHead(path.join(item.rootDir, ...item.relPath.split('/')), 65536),
446
+ item.extension,
447
+ )
448
+ item.width = measured?.width ?? null
449
+ item.height = measured?.height ?? null
450
+ }))
451
+
452
+ // 全量统计:供「全局按对话分组」使用(不受分页限制)
453
+ const allItemsSummary = []
454
+ if (!isSession) {
455
+ for (const item of matches) {
456
+ allItemsSummary.push({
457
+ absPath: item.absPath,
458
+ relPath: item.relPath,
459
+ sessionId: item.sessionId,
460
+ sessionTitle: item.sessionTitle ?? '',
461
+ sessionCreatedAt: item.sessionCreatedAt ?? 0,
462
+ category: item.category,
463
+ mtime: item.mtime,
464
+ width: item.width ?? null,
465
+ height: item.height ?? null,
466
+ size: item.size,
467
+ name: item.name,
468
+ extension: item.extension,
469
+ // 音视频类型(video / audio),客户端据此选 <video> 还是 <audio>
470
+ ...(item.mediaType !== undefined ? { mediaType: item.mediaType } : {}),
471
+ })
472
+ }
473
+ }
474
+
475
+ return {
476
+ kind,
477
+ scope: isSession ? 'session' : 'global',
478
+ scopeInfo: {
479
+ ok: scopeInfo.ok,
480
+ reason: scopeInfo.reason,
481
+ taskDirs: scopeInfo.taskDirs.length,
482
+ paths: scopeInfo.paths.length,
483
+ relPaths: (scopeInfo.relPaths ?? []).length,
484
+ // 子智能体会话数:> 0 表示已纳入它们的产出
485
+ subSessions: scopeInfo.subSessions ?? 0,
486
+ },
487
+ root: opts.root,
488
+ roots: opts.roots,
489
+ rootSource: opts.rootSource,
490
+ missingRoots,
491
+ windowHours: opts.windowHours,
492
+ maxItems: opts.maxItems,
493
+ maxDepth: opts.maxDepth,
494
+ generatedAt: now,
495
+ items: visible,
496
+ total,
497
+ // 分页信息,客户端据此渲染页码条
498
+ page: safePage,
499
+ pageCount,
500
+ pageSize: opts.maxItems,
501
+ // 「还有 N 张」= 当前页之外的总数(不再只是「被截掉的」)
502
+ hidden: Math.max(0, total - visible.length),
503
+ rootMissing,
504
+ scan: { directories, entries, capped },
505
+ // 全局模式额外返回:按对话分组的数据(客户端做折叠展示用)
506
+ groups: isSession ? null : buildGroups(allItemsSummary, 120, sessionId),
507
+ }
508
+ }
509
+
510
+ /**
511
+ * 把扁平的资产列表按「所属对话」分组。
512
+ *
513
+ * 分组规则:
514
+ * - 属于某个已知对话的文件 → 归到该对话(标题用会话标题)
515
+ * - 其余(日志里查不到归属的历史文件)→ 统一归到「历史资产」组
516
+ *
517
+ * 排序(v0.8.2 调整):
518
+ * 1. **当前对话永远置顶** —— 用户打开「全局资产」最想先看自己这次做了什么,
519
+ * 按时间倒序会把它压到中间(当前对话可能很早创建、但一直在用)。
520
+ * 2. 其余对话按创建时间倒序。
521
+ * 3. 「历史资产」永远最后。
522
+ *
523
+ * ⚠️ 体积控制:每组只返回前 maxPerGroup 条明细 + 完整总数。
524
+ * 为什么必须截断:历史组有 4995 个文件,全量返回会让单次响应达到 1.3 MB,
525
+ * 前端解析/渲染都会卡,面板看起来「只显示两组」。
526
+ *
527
+ * @param summary - 扁平资产摘要数组。
528
+ * @param maxPerGroup - 每组最多返回多少条明细(默认 120)。
529
+ * @param currentSessionId - 当前打开的会话 id;匹配到的组会标记 isCurrent 并置顶。
530
+ * @returns 分组数组。
531
+ */