dsh-gallery 1.4.2 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,379 @@
1
+ /**
2
+ * 交付清单组装内核(v1.5.0)
3
+ *
4
+ * 一个内核、两个出口:
5
+ * · 出口 1 —— op `exportManifest`:落盘成 CSV / JSON,给人看、进 Excel 做物料表
6
+ * · 出口 2 —— 工具 `gallery_manifest`:直接回给 Agent,驱动下一轮
7
+ * 两边都调这里,保证「您看到的清单」和「我读到的清单」永远是同一份数字。
8
+ *
9
+ * 三条硬约束:
10
+ * 1. **只读**:本模块绝不写盘。落盘由 http.js 的 op 负责(走 atomic.js)。
11
+ * 2. **不猜**:拿不到尺寸就留空,不写 0,免得客户以为图是 0×0。
12
+ * 3. **截断必须说出来**:超上限如实置 truncated,不静默少给。
13
+ *
14
+ * 为什么尺寸要自己读文件头:扫描结果里没有宽高(`context.json` 实测字段无 width/height),
15
+ * 而整图解码来拿尺寸代价太大。`regions.js` 的 `imageSizeOf()` 只解析文件头(零依赖,
16
+ * 不用任何图像库),读一次 open 同时取 stat,IO 只走一趟。
17
+ */
18
+
19
+ import { promises as fsp } from 'node:fs'
20
+
21
+ import { imageSizeOf } from './regions.js'
22
+ import { mapPool, SCAN_CONCURRENCY } from './scan.js'
23
+ // 时间码格式复用截帧那一套(`00-02-17-892`,用「-」而非「:」因为文件名不许冒号),
24
+ // 不在这里另写一份,免得清单上的时间码和文件名里的对不上。
25
+ import { frameTimecode } from './frames.js'
26
+
27
+ /** 清单格式版本:将来加列/改语义就升这个数,读的人能判断兼容性。 */
28
+ export const MANIFEST_SCHEMA = 1
29
+
30
+ /** 分类的中文名,CSV 里给人看的就是这几个字 */
31
+ export const CATEGORY_TEXT = {
32
+ final: '定稿',
33
+ input: '素材',
34
+ intermediate: '过程稿',
35
+ unknown: '未归类',
36
+ }
37
+
38
+ export const MANIFEST_CATEGORIES = ['final', 'input', 'intermediate', 'unknown']
39
+
40
+ /**
41
+ * 读文件头用的字节数。JPEG 的 SOF 段前面可能挂着 EXIF 缩略图,
42
+ * 64 字节常常看不到宽高,所以一次读 8 KB(只读头部,不读整图)。
43
+ */
44
+ const HEAD_BYTES = 8192
45
+
46
+ /**
47
+ * 需要读盘的条目上限。**只统计「扫描条目里缺 width/height/size」的那些** ——
48
+ * 扫描结果实测自带 width / height / size(见 scan.js 产出),绝大多数条目根本不用读盘。
49
+ * 真正要读盘的是老缓存、文件类资产这些,数量有限;超了就让它们留空,不硬扛。
50
+ */
51
+ const SIZE_PROBE_MAX = 4000
52
+
53
+ /** 单份清单的条目上限:全库实测 6930 条,留足余量又不至于把响应撑爆。 */
54
+ const MANIFEST_MAX_ITEMS = 20000
55
+
56
+ /** 路径统一成斜杠形态(与 labels / frames 的键口径一致,否则永远查不中)。 */
57
+ export function normalizeRelPath(value) {
58
+ return String(value ?? '').replace(/\\/g, '/').replace(/^\.\//, '').trim()
59
+ }
60
+
61
+ const pad2 = (n) => String(n).padStart(2, '0')
62
+
63
+ /**
64
+ * 取一个「大于 0 的有限数」,拿不到一律回 0。
65
+ *
66
+ * 🔴 必须用这个而不是 `Number(x) || y`:扫描条目里 width/height 可能是 null,
67
+ * `Number(null)` 是 0 但兜底到 frames 的 undefined 就成了 NaN,
68
+ * 而 **NaN 参与任何比较都是 false**(`NaN <= 0` 为 false),
69
+ * 会让「缺宽高就去读盘」的判断静默失效 —— 实测 2024 条一条都没补上。
70
+ */
71
+ function positiveNum(value) {
72
+ const n = Number(value)
73
+ return Number.isFinite(n) && n > 0 ? n : 0
74
+ }
75
+
76
+ /** 本地时间 `2026-11-25 10:43`;拿不到就留空,别写 1970。 */
77
+ export function formatLocalTime(ms) {
78
+ const n = Number(ms)
79
+ if (!Number.isFinite(n) || n <= 0) return ''
80
+ const d = new Date(n)
81
+ if (Number.isNaN(d.getTime())) return ''
82
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} `
83
+ + `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
84
+ }
85
+
86
+ /** 人类可读体积:给客户看的是「1.2 MB」而不是 1258291。 */
87
+ export function formatBytes(bytes) {
88
+ const n = Number(bytes)
89
+ if (!Number.isFinite(n) || n <= 0) return ''
90
+ if (n < 1024) return `${Math.round(n)} B`
91
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
92
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`
93
+ }
94
+
95
+ /**
96
+ * CSV 单元格转义(RFC 4180)。
97
+ * 逗号、引号、换行都必须整格包引号,内部引号写成两个 ——
98
+ * 少做一步,Excel 就会把一格拆成两列,客户拿到的清单是错位的。
99
+ */
100
+ export function csvCell(value) {
101
+ const s = value === null || value === undefined ? '' : String(value)
102
+ if (s === '') return ''
103
+ if (/[",\r\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`
104
+ return s
105
+ }
106
+
107
+ /**
108
+ * 读一个文件的体积 + 宽高(一次 open 同时拿 stat 和文件头)。
109
+ * hint 是 frames 里已经记过的 imageWidth/imageHeight,有就不必再读头。
110
+ */
111
+ async function probeFile(absPath, hint) {
112
+ if (!absPath) return null
113
+ let handle = null
114
+ try {
115
+ handle = await fsp.open(absPath, 'r')
116
+ const st = await handle.stat()
117
+ if (!st.isFile()) return null
118
+ let size = null
119
+ if (hint && Number(hint.width) > 0 && Number(hint.height) > 0) {
120
+ size = { width: Number(hint.width), height: Number(hint.height), format: '' }
121
+ } else {
122
+ const buf = Buffer.alloc(HEAD_BYTES)
123
+ const { bytesRead } = await handle.read(buf, 0, HEAD_BYTES, 0)
124
+ if (bytesRead >= 24) size = imageSizeOf(buf.subarray(0, bytesRead))
125
+ }
126
+ return { bytes: st.size, width: size?.width ?? 0, height: size?.height ?? 0, format: size?.format ?? '' }
127
+ } catch {
128
+ // 文件被移走 / 没权限都走这里:清单里这一格留空,不编数
129
+ return null
130
+ } finally {
131
+ if (handle !== null) {
132
+ try { await handle.close() } catch { /* 关不掉不影响结果 */ }
133
+ }
134
+ }
135
+ }
136
+
137
+ /** 从 frames 登记里取「这条资产是从哪个视频的哪一刻截出来的」。 */
138
+ function sourceOfFrame(frame) {
139
+ if (frame === null || typeof frame !== 'object') return null
140
+ const videoName = String(frame.videoName ?? frame.sourceName ?? '')
141
+ const videoRelPath = String(frame.videoRelPath ?? frame.sourceRelPath ?? '')
142
+ const frameMs = Number(frame.frameMs)
143
+ const hasMs = Number.isFinite(frameMs) && frameMs > 0
144
+ // 老登记没有 timecode 字段只有 frameMs,这时按同一套规则补出来
145
+ const timecode = String(frame.timecode ?? '') || (hasMs ? frameTimecode(frameMs) : '')
146
+ if (videoName === '' && videoRelPath === '' && timecode === '') return null
147
+ return {
148
+ videoName,
149
+ videoRelPath,
150
+ timecode,
151
+ frameMs: hasMs ? frameMs : 0,
152
+ }
153
+ }
154
+
155
+ /** 反馈篮里对这条资产的备注(结构开放,认不出就当没有)。 */
156
+ function noteOf(record) {
157
+ if (record === null || typeof record !== 'object') return { note: '', annotationCount: 0 }
158
+ const note = typeof record.text === 'string' ? record.text
159
+ : typeof record.note === 'string' ? record.note
160
+ : typeof record.comment === 'string' ? record.comment : ''
161
+ const regions = Array.isArray(record.regions) ? record.regions
162
+ : Array.isArray(record.annotations) ? record.annotations
163
+ : Array.isArray(record.region) ? record.region : []
164
+ return { note: String(note).slice(0, 300), annotationCount: regions.length }
165
+ }
166
+
167
+ /**
168
+ * 组装交付清单。**只读,不落盘。**
169
+ *
170
+ * @param options.entries 扫描出来的条目(一定要带 relPath)
171
+ * @param options.relPaths 只要这些(批量选中时传);空 = 不限
172
+ * @param options.categories 只要这几类;空 = 不限
173
+ * @param options.frames frames.json 的 frames 映射(补来源视频与时间码)
174
+ * @param options.labels labels.json 的 labels 映射(判断是否人工改过)
175
+ * @param options.feedback feedback.json 的 feedback 映射(补备注)
176
+ * @param options.masks relPath → 配套遮罩的相对路径(buildLinkedMaskIndex 产出)
177
+ * @param options.includeSize 是否补宽高与体积(默认 true;条目自带就不读盘,只在缺字段时读文件头)
178
+ * @param options.includeNotes 是否带反馈备注(默认 false,导出交付件时才开)
179
+ * @param options.maxItems 硬上限,超出置 truncated
180
+ */
181
+ export async function buildManifest(options = {}) {
182
+ const entries = Array.isArray(options.entries) ? options.entries : []
183
+ const frames = options.frames !== null && typeof options.frames === 'object' ? options.frames : {}
184
+ const labels = options.labels !== null && typeof options.labels === 'object' ? options.labels : {}
185
+ const feedback = options.feedback !== null && typeof options.feedback === 'object' ? options.feedback : {}
186
+ // masks:relPath -> 遮罩相对路径(由 frames.js 的 buildLinkedMaskIndex 建,http.js 传进来)
187
+ const masks = options.masks !== null && typeof options.masks === 'object' ? options.masks : {}
188
+ const includeSize = options.includeSize !== false
189
+ const includeNotes = options.includeNotes === true
190
+ const maxItems = Math.max(1, Math.min(MANIFEST_MAX_ITEMS, Math.trunc(Number(options.maxItems)) || 2000))
191
+ const wantPaths = Array.isArray(options.relPaths) && options.relPaths.length > 0
192
+ ? new Set(options.relPaths.map(normalizeRelPath).filter((p) => p !== ''))
193
+ : null
194
+ const wantCats = Array.isArray(options.categories) && options.categories.length > 0
195
+ ? new Set(options.categories.map((c) => String(c ?? '')).filter((c) => MANIFEST_CATEGORIES.includes(c)))
196
+ : null
197
+
198
+ // 去重 + 过滤。同一张图可能同时出现在 items 与 groups[].files 里。
199
+ const picked = []
200
+ const seen = new Set()
201
+ for (const entry of entries) {
202
+ if (entry === null || typeof entry !== 'object') continue
203
+ const relPath = normalizeRelPath(entry.relPath)
204
+ if (relPath === '' || seen.has(relPath)) continue
205
+ // 分叉隔离:分叉会话继承来的资产默认不进交付清单(它们不属于本次产出)
206
+ if (entry.inherited === true || entry.shared === true) {
207
+ if (options.includeInherited !== true) continue
208
+ }
209
+ if (wantPaths !== null && !wantPaths.has(relPath)) continue
210
+ const manual = labels[relPath]
211
+ const category = String(entry.category ?? (manual?.category ?? 'unknown')) || 'unknown'
212
+ if (wantCats !== null && !wantCats.has(category)) continue
213
+ seen.add(relPath)
214
+ picked.push({ entry, relPath, category, manual: manual !== null && typeof manual === 'object' })
215
+ }
216
+
217
+ // 稳定顺序:按相对路径升序,同一份数据导两次的序号能对上账
218
+ picked.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0))
219
+
220
+ const truncated = picked.length > maxItems
221
+ const sliced = truncated ? picked.slice(0, maxItems) : picked
222
+
223
+ // 扫描条目本身自带 width / height / size(实测字段),能用就直接用,一次盘都不读。
224
+ // 只有缺这些字段的(老缓存、文件类资产、视频)才去读文件头。
225
+ const needProbe = []
226
+ if (includeSize) {
227
+ for (let i = 0; i < sliced.length; i += 1) {
228
+ const { entry, relPath } = sliced[i]
229
+ const fr = frames[relPath]
230
+ const w = positiveNum(entry.width) || positiveNum(fr?.imageWidth)
231
+ const h = positiveNum(entry.height) || positiveNum(fr?.imageHeight)
232
+ const size = positiveNum(entry.size)
233
+ // 写成 !(w > 0) 而不是 w <= 0:NaN 会让后者恒为 false,缺尺寸的条目会被整体漏掉
234
+ if ((!(w > 0) || !(h > 0) || !(size > 0)) && String(entry.absPath ?? '') !== '') needProbe.push(i)
235
+ }
236
+ }
237
+ const probes = new Map()
238
+ if (needProbe.length > 0 && needProbe.length <= SIZE_PROBE_MAX) {
239
+ const results = await mapPool(needProbe, SCAN_CONCURRENCY, (i) => {
240
+ const { entry, relPath } = sliced[i]
241
+ const fr = frames[relPath]
242
+ return probeFile(String(entry.absPath ?? ''), {
243
+ width: positiveNum(entry.width) || positiveNum(fr?.imageWidth),
244
+ height: positiveNum(entry.height) || positiveNum(fr?.imageHeight),
245
+ })
246
+ })
247
+ for (let k = 0; k < needProbe.length; k += 1) probes.set(needProbe[k], results[k])
248
+ }
249
+
250
+ // summary 必须基于**截断前**的 picked:total 是「筛选后一共多少条」,
251
+ // 不是「这次返回了多少条」。否则模型看到「共 8 条」会以为清单只有 8 条。
252
+ const byCategory = { final: 0, input: 0, intermediate: 0, unknown: 0 }
253
+ let withMask = 0
254
+ let fromVideo = 0
255
+ let totalBytes = 0
256
+ for (const { entry, relPath, category } of picked) {
257
+ if (Object.prototype.hasOwnProperty.call(byCategory, category)) byCategory[category] += 1
258
+ else byCategory.unknown += 1
259
+ if (normalizeRelPath(entry.maskPath ?? masks[relPath] ?? '') !== '') withMask += 1
260
+ if (sourceOfFrame(frames[relPath]) !== null) fromVideo += 1
261
+ totalBytes += positiveNum(entry.size)
262
+ }
263
+
264
+ const items = []
265
+ for (let i = 0; i < sliced.length; i += 1) {
266
+ const { entry, relPath, category, manual } = sliced[i]
267
+ const probe = probes.get(i) ?? null
268
+ const fr = frames[relPath]
269
+ const frame = sourceOfFrame(fr)
270
+ const fb = includeNotes ? noteOf(feedback[relPath]) : { note: '', annotationCount: 0 }
271
+ // 扫描条目里**没有** maskPath 字段(实测过),遮罩只能靠 frames 的关联索引反查:
272
+ // 索引的键是原图/预览图的相对路径,值是配套遮罩图。不传索引就是空的。
273
+ const maskPath = normalizeRelPath(entry.maskPath ?? masks[relPath] ?? '')
274
+ const name = String(entry.name ?? relPath.split('/').pop() ?? '')
275
+ const width = positiveNum(probe?.width) || positiveNum(entry.width) || positiveNum(fr?.imageWidth)
276
+ const height = positiveNum(probe?.height) || positiveNum(entry.height) || positiveNum(fr?.imageHeight)
277
+ const bytes = positiveNum(probe?.bytes) || positiveNum(entry.size)
278
+
279
+ items.push({
280
+ index: i + 1,
281
+ name,
282
+ relPath,
283
+ absPath: String(entry.absPath ?? ''),
284
+ category,
285
+ categoryText: CATEGORY_TEXT[category] ?? CATEGORY_TEXT.unknown,
286
+ categoryManual: manual,
287
+ width,
288
+ height,
289
+ format: probe?.format ?? '',
290
+ bytes,
291
+ bytesText: formatBytes(bytes),
292
+ mtime: Number(entry.mtime) || 0,
293
+ mtimeText: formatLocalTime(entry.mtime),
294
+ sessionId: String(entry.sessionId ?? ''),
295
+ sessionTitle: String(entry.sessionTitle ?? ''),
296
+ maskPath,
297
+ videoName: frame?.videoName ?? '',
298
+ videoRelPath: frame?.videoRelPath ?? '',
299
+ timecode: frame?.timecode ?? '',
300
+ frameMs: frame?.frameMs ?? 0,
301
+ note: fb.note,
302
+ annotationCount: fb.annotationCount,
303
+ })
304
+ }
305
+
306
+ return {
307
+ schema: MANIFEST_SCHEMA,
308
+ generatedAt: Date.now(),
309
+ generatedAtText: formatLocalTime(Date.now()),
310
+ scope: String(options.scope ?? ''),
311
+ kind: String(options.kind ?? ''),
312
+ summary: {
313
+ total: picked.length,
314
+ returned: items.length,
315
+ byCategory,
316
+ withMask,
317
+ fromVideo,
318
+ totalBytes,
319
+ totalBytesText: formatBytes(totalBytes),
320
+ probedCount: needProbe.length,
321
+ },
322
+ truncated,
323
+ items,
324
+ }
325
+ }
326
+
327
+ /** CSV 的列名(中文,给客户看的)。 */
328
+ const CSV_COLUMNS = [
329
+ '序号', '文件名', '相对路径', '分类', '尺寸', '体积',
330
+ '修改时间', '来源对话', '来源视频', '时间码', '遮罩', '备注',
331
+ ]
332
+
333
+ /**
334
+ * 序列化成 CSV。
335
+ *
336
+ * **BOM 不能省**:Excel 双击打开 CSV 时不会探测 UTF-8,没有 `EF BB BF`
337
+ * 就按系统 ANSI(中文环境是 GBK)解析,中文全变乱码。
338
+ */
339
+ export function manifestToCsv(manifest, options = {}) {
340
+ const items = Array.isArray(manifest?.items) ? manifest.items : []
341
+ const withNotes = options.withNotes === true
342
+ const columns = withNotes ? CSV_COLUMNS : CSV_COLUMNS.slice(0, -1)
343
+ const lines = [columns.join(',')]
344
+ for (const it of items) {
345
+ const size = it.width > 0 && it.height > 0 ? `${it.width}×${it.height}` : ''
346
+ const cells = [
347
+ it.index, it.name, it.relPath, it.categoryText, size, it.bytesText,
348
+ it.mtimeText, it.sessionTitle, it.videoName, it.timecode,
349
+ it.maskPath === '' ? '' : '有',
350
+ ]
351
+ if (withNotes) cells.push(it.note)
352
+ lines.push(cells.map(csvCell).join(','))
353
+ }
354
+ // 行尾用 CRLF:RFC 4180 的要求,也是 Excel 最保险的形态
355
+ return `\ufeff${lines.join('\r\n')}\r\n`
356
+ }
357
+
358
+ /** 序列化成 JSON。**不加 BOM** —— 加了 JSON.parse 会直接拒收。 */
359
+ export function manifestToJson(manifest) {
360
+ return `${JSON.stringify(manifest, null, 2)}\n`
361
+ }
362
+
363
+ /**
364
+ * 生成落盘文件名(不含扩展名):`交付清单_20261125-1043_定稿_8张`。
365
+ * 只保留 Windows 允许的字符;分类用中文名,客户一眼能看懂。
366
+ */
367
+ export function manifestFileBase(manifest, options = {}) {
368
+ const at = Number(manifest?.generatedAt) || Date.now()
369
+ const d = new Date(at)
370
+ const stamp = `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}`
371
+ + `-${pad2(d.getHours())}${pad2(d.getMinutes())}`
372
+ const cats = Array.isArray(options.categories) ? options.categories : []
373
+ let catText = '全部'
374
+ if (cats.length === 1) catText = CATEGORY_TEXT[cats[0]] ?? '全部'
375
+ else if (cats.length > 1 && cats.length < 4) catText = cats.map((c) => CATEGORY_TEXT[c] ?? c).join('+')
376
+ const count = Array.isArray(manifest?.items) ? manifest.items.length : 0
377
+ const raw = `交付清单_${stamp}_${catText}_${count}张`
378
+ return raw.replace(/[\\/:*?"<>|\r\n]/g, '_')
379
+ }
package/host/tools.js CHANGED
@@ -37,12 +37,20 @@ import { buildLinkedMaskIndex } from './frames.js'
37
37
  // 起因是实测:用户框选后说「把框里的字母改掉」,模型拿不到框的位置,
38
38
  // 只能翻 frames.json / 临时目录满地找,光找就花了 97 秒。
39
39
  import { readFeedback, setFeedback } from './feedback.js'
40
+ // v1.5.0:交付清单。与 op exportManifest 共用同一个内核,两边数字永远一致。
41
+ import { readLabels } from './labels.js'
42
+ import { readFrames } from './frames.js'
43
+ import { buildManifest } from './manifest.js'
40
44
  import { annotationsFor, latestAnnotationAt, materializeRegions, materializeMaskRegion } from './regions.js'
41
45
 
42
46
  const TOOL_NAME = 'gallery_find'
43
47
  const CONTEXT_TOOL_NAME = 'gallery_context'
44
48
  const REGIONS_TOOL_NAME = 'gallery_regions'
45
49
  const REPLY_TOOL_NAME = 'gallery_reply'
50
+ const MANIFEST_TOOL_NAME = 'gallery_manifest'
51
+ // 清单一次最多回多少条:默认 200 够写交付说明,上限 500 防止把上下文撑爆
52
+ const MANIFEST_LIMIT_DEFAULT = 200
53
+ const MANIFEST_LIMIT_MAX = 500
46
54
  const MAX_LIMIT = 100
47
55
  const DEFAULT_LIMIT = 20
48
56
  // 第二档:gallery_context 一次列多少张「最近看过的」。
@@ -67,7 +75,8 @@ function scanCacheKey(config, kind, scope, sid, opts) {
67
75
  try { stamp += `${statSync(path.join(home, name)).mtimeMs}|` } catch { stamp += "0|" }
68
76
  }
69
77
  } catch { stamp = "" }
70
- return [kind, scope, sid, JSON.stringify(config ?? {}), stamp].join("~")
78
+ // 键里必须带 maxItems:列表要 60 条、清单要 5000 条,共用一份缓存会互相投毒
79
+ return [kind, scope, sid, String(opts?.maxItems ?? ''), JSON.stringify(config ?? {}), stamp].join("~")
71
80
  }
72
81
  async function scanWithShortCache(config, kind, scope, sid, opts) {
73
82
  const key = scanCacheKey(config, kind, scope, sid, opts)
@@ -907,6 +916,200 @@ export function buildReplyToolDefinition(config) {
907
916
  }
908
917
  }
909
918
 
919
+
920
+ /**
921
+ * 取一批资产的结构化清单(v1.5.0)。
922
+ *
923
+ * 与 op `exportManifest` 走**同一个** buildManifest:模型读到的条数、分类计数、
924
+ * 来源视频,跟用户导出的 CSV 必须完全对得上 —— 这是「一个内核两个出口」的意义。
925
+ *
926
+ * 扫描口径也与导出相同:一次取全,不按页翻。当前对话视图每翻一页都要重解一次
927
+ * 会话日志,翻十几页能把工具调用拖到几十秒。
928
+ */
929
+ async function manifestOf(args, exec, config) {
930
+ const a = args ?? {}
931
+ try {
932
+ const opts = resolveOptions(config)
933
+ const kind = a.kind === 'file' || a.kind === 'media' ? a.kind : 'image'
934
+ const execSessionId = typeof exec?.agent?.session?.id === 'string' ? exec.agent.session.id : ''
935
+ const scope = a.scope === 'session' && execSessionId !== '' ? 'session' : 'global'
936
+ const limit = Math.max(1, Math.min(MANIFEST_LIMIT_MAX, Math.trunc(Number(a.limit)) || MANIFEST_LIMIT_DEFAULT))
937
+ const cats = Array.isArray(a.categories) && a.categories.length > 0
938
+ ? a.categories.map((c) => String(c ?? ''))
939
+ : (typeof a.category === 'string' && a.category !== '' ? [a.category] : [])
940
+ const selected = Array.isArray(a.selected) ? a.selected.map((v) => String(v ?? '')).filter((v) => v !== '') : []
941
+
942
+ // 走短缓存:全库扫描实测 8 秒,同一轮里连着问两次不该扫两遍
943
+ const full = await scanWithShortCache(config, kind, scope, execSessionId, { ...opts, maxItems: 5000 })
944
+ const entries = Array.isArray(full?.items) ? [...full.items] : []
945
+ for (const g of (Array.isArray(full?.groups) ? full.groups : [])) {
946
+ for (const f of (Array.isArray(g?.files) ? g.files : [])) entries.push(f)
947
+ }
948
+
949
+ const [labelsDoc, framesDoc, feedbackDoc, maskIndex] = await Promise.all([
950
+ readLabels(opts.settingsFile),
951
+ readFrames(opts.settingsFile),
952
+ readFeedback(opts.settingsFile, opts),
953
+ buildLinkedMaskIndex(opts.settingsFile),
954
+ ])
955
+
956
+ const manifest = await buildManifest({
957
+ entries,
958
+ relPaths: selected,
959
+ categories: cats,
960
+ frames: framesDoc?.frames ?? {},
961
+ labels: labelsDoc?.labels ?? {},
962
+ feedback: feedbackDoc?.feedback ?? {},
963
+ masks: Object.fromEntries(maskIndex ?? []),
964
+ scope,
965
+ kind,
966
+ includeNotes: a.includeNotes === true,
967
+ includeSize: a.includeSize !== false,
968
+ // 与 op exportManifest 同口径:显式选中就必须全给(含继承 / 共享),
969
+ // 仅按分类扫整批时排除,两个出口才不会各说各的。
970
+ includeInherited: selected.length > 0,
971
+ maxItems: limit,
972
+ })
973
+
974
+ return {
975
+ found: manifest.items.length > 0,
976
+ total: manifest.summary.total,
977
+ truncated: manifest.truncated,
978
+ summary: manifest.summary,
979
+ items: manifest.items,
980
+ error: '',
981
+ }
982
+ } catch (error) {
983
+ return {
984
+ found: false, total: 0, truncated: false, summary: null, items: [],
985
+ error: String(error?.message ?? error),
986
+ }
987
+ }
988
+ }
989
+
990
+ /** 把清单写成模型能直接照着干活的样子:先给总量分布,再每条一行。 */
991
+ function renderManifest(args, value) {
992
+ if (value?.error) return [{ type: 'text', text: `取交付清单失败:${value.error}` }]
993
+ const items = Array.isArray(value?.items) ? value.items : []
994
+ if (items.length === 0) {
995
+ return [{ type: 'text', text: '这一批里没有符合条件的资产(可能还没打分类)。' }]
996
+ }
997
+ const s = value.summary ?? {}
998
+ const by = s.byCategory ?? {}
999
+ const lines = []
1000
+ lines.push(`共 ${value.total} 条${value.truncated ? `(本次只列前 ${items.length} 条,完整清单让用户点面板「导出清单」)` : ''}:`
1001
+ + `定稿 ${by.final ?? 0} / 素材 ${by.input ?? 0} / 过程稿 ${by.intermediate ?? 0} / 未归类 ${by.unknown ?? 0};`
1002
+ + `有遮罩 ${s.withMask ?? 0} 条,截帧 ${s.fromVideo ?? 0} 条,合计 ${s.totalBytesText || '—'}。`)
1003
+ for (const it of items) {
1004
+ const bits = [it.categoryText || it.category]
1005
+ if (it.width > 0 && it.height > 0) bits.push(`${it.width}×${it.height}`)
1006
+ if (it.bytesText) bits.push(it.bytesText)
1007
+ if (it.sessionTitle) bits.push(`会话「${it.sessionTitle}」`)
1008
+ if (it.videoName) bits.push(`取自 ${it.videoName}${it.timecode ? ` @ ${it.timecode}` : ''}`)
1009
+ if (it.maskPath) bits.push('有遮罩')
1010
+ lines.push(`· ${it.relPath} | ${bits.join(' | ')}`)
1011
+ if (it.absPath) lines.push(` 图:${it.absPath}`)
1012
+ if (it.note) lines.push(` 备注:${it.note}`)
1013
+ }
1014
+ lines.push('以上是这一批的完整清单,可直接据此作答或接着做下一轮改动;'
1015
+ + '不要再用命令行 / 脚本重复扫描核对,也不要再调一次本工具确认。'
1016
+ + '要给客户的 CSV / JSON 文件请让用户在面板上点「导出清单」—— 本工具只读,不生成文件。')
1017
+ return [{ type: 'text', text: lines.join('\n') }]
1018
+ }
1019
+
1020
+ /** v1.5.0:交付清单(只读)。给 Agent 读,导出文件那半在 op exportManifest。 */
1021
+ export function buildManifestToolDefinition(config) {
1022
+ return {
1023
+ name: MANIFEST_TOOL_NAME,
1024
+ description: '按分类或选中范围取一份结构化清单:文件名、相对/绝对路径、分类、尺寸、体积、修改时间、'
1025
+ + '来源对话、来源视频与时间码(截帧才有)、有无遮罩、反馈备注。'
1026
+ + '当用户说「把这批的清单给我」「定稿都有哪些」「整理一份交付清单」「按这个清单接着改」'
1027
+ + '「哪些是定稿哪些是过程稿」时用本工具 —— 不要让用户手抄文件名,也不要自己扫盘。'
1028
+ + '只读:不落盘、不发送任何消息。要生成给客户的 CSV / JSON 文件,请用户在面板上点「导出清单」。',
1029
+ parameters: {
1030
+ type: 'object',
1031
+ properties: {
1032
+ category: {
1033
+ type: 'string',
1034
+ description: '只取一类:final=定稿 / input=素材 / intermediate=过程稿 / unknown=未归类;留空=全部',
1035
+ },
1036
+ categories: {
1037
+ type: 'array',
1038
+ description: '取多类(与 category 二选一,本项优先)',
1039
+ items: { type: 'string' },
1040
+ },
1041
+ scope: { type: 'string', description: 'session=当前对话 / global=全部对话;默认 global' },
1042
+ kind: { type: 'string', description: 'image / file / media;默认 image' },
1043
+ selected: {
1044
+ type: 'array',
1045
+ description: '只要这些相对路径(用户在面板上批量选中的那批,直接从 gallery_context 或用户描述里取)',
1046
+ items: { type: 'string' },
1047
+ },
1048
+ includeNotes: { type: 'boolean', description: '是否带反馈篮里的备注;默认 false' },
1049
+ includeSize: { type: 'boolean', description: '是否补宽高与体积;默认 true(条目自带字段时不读盘)' },
1050
+ limit: { type: 'number', description: `最多返回条数,默认 ${MANIFEST_LIMIT_DEFAULT},最大 ${MANIFEST_LIMIT_MAX}` },
1051
+ },
1052
+ },
1053
+ output: {
1054
+ schema: {
1055
+ type: 'object',
1056
+ properties: {
1057
+ found: { type: 'boolean', description: '有没有取到资产' },
1058
+ total: { type: 'number', description: '清单条数' },
1059
+ truncated: { type: 'boolean', description: '是否因为上限被截断' },
1060
+ summary: {
1061
+ type: 'object',
1062
+ description: '总量与分布',
1063
+ properties: {
1064
+ total: { type: 'number' },
1065
+ byCategory: {
1066
+ type: 'object',
1067
+ properties: {
1068
+ final: { type: 'number' }, input: { type: 'number' },
1069
+ intermediate: { type: 'number' }, unknown: { type: 'number' },
1070
+ },
1071
+ },
1072
+ withMask: { type: 'number', description: '有配套遮罩的条数' },
1073
+ fromVideo: { type: 'number', description: '从视频截出来的帧图条数' },
1074
+ totalBytesText: { type: 'string', description: '总体积,如「4985.5 MB」' },
1075
+ },
1076
+ },
1077
+ items: {
1078
+ type: 'array',
1079
+ description: '清单明细,按相对路径升序',
1080
+ items: {
1081
+ type: 'object',
1082
+ properties: {
1083
+ index: { type: 'number' },
1084
+ name: { type: 'string' },
1085
+ relPath: { type: 'string' },
1086
+ absPath: { type: 'string' },
1087
+ category: { type: 'string', description: 'final / input / intermediate / unknown' },
1088
+ categoryText: { type: 'string', description: '中文分类名' },
1089
+ categoryManual: { type: 'boolean', description: '分类是用户手动改过的' },
1090
+ width: { type: 'number' }, height: { type: 'number' },
1091
+ bytesText: { type: 'string' },
1092
+ mtimeText: { type: 'string' },
1093
+ sessionTitle: { type: 'string' },
1094
+ videoName: { type: 'string', description: '截帧的来源视频文件名;非截帧为空' },
1095
+ timecode: { type: 'string', description: '截帧时间码,如 00-02-17-892' },
1096
+ maskPath: { type: 'string', description: '配套遮罩的相对路径;没有则为空' },
1097
+ note: { type: 'string', description: '反馈篮里的备注;includeNotes 开启时才有' },
1098
+ },
1099
+ required: ['relPath'],
1100
+ },
1101
+ },
1102
+ error: { type: 'string' },
1103
+ },
1104
+ },
1105
+ render: renderManifest,
1106
+ },
1107
+ async execute(args, exec) {
1108
+ return manifestOf(args, exec, config)
1109
+ },
1110
+ }
1111
+ }
1112
+
910
1113
  /**
911
1114
  * 在插件 apply() 里调用。
912
1115
  * 返回 disposer;任何失败都吞掉并记日志 —— 绝不能因为 tool 注册失败
@@ -918,6 +1121,7 @@ export function registerTools(ctx, config) {
918
1121
  buildContextToolDefinition(config),
919
1122
  buildRegionsToolDefinition(config),
920
1123
  buildReplyToolDefinition(config),
1124
+ buildManifestToolDefinition(config),
921
1125
  ]
922
1126
  if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
923
1127
  ctx?.logger?.warn?.('dsh-gallery: ctx.tools 不可用,Agent 工具未注册')
@@ -937,5 +1141,5 @@ export function registerTools(ctx, config) {
937
1141
  return () => { for (const d of disposers) { try { d() } catch { /* 忽略 */ } } }
938
1142
  }
939
1143
 
940
- export { TOOL_NAME, CONTEXT_TOOL_NAME, REGIONS_TOOL_NAME, REPLY_TOOL_NAME,
1144
+ export { TOOL_NAME, CONTEXT_TOOL_NAME, REGIONS_TOOL_NAME, REPLY_TOOL_NAME, MANIFEST_TOOL_NAME,
941
1145
  rootOf, toRow, renderRows, renderContext, renderRegions, renderReply }
package/index.js CHANGED
@@ -29,6 +29,7 @@ import { registerTools } from './host/tools.js'
29
29
  import os from 'node:os'
30
30
  import { sweepStaleTmp } from './host/atomic.js'
31
31
  import { sweepExpiredFeedback } from './host/feedback.js'
32
+ import { sweepContext } from './host/context.js'
32
33
 
33
34
  export const inject = ['connection', 'webServer', 'tools']
34
35
 
@@ -47,6 +48,15 @@ export function apply(ctx, config) {
47
48
  if (r.removed > 0) ctx?.logger?.info?.(`dsh-gallery: 清掉 ${r.removed} 个残留 tmp`)
48
49
  }).catch(() => {})
49
50
  } catch { /* 忽略 */ }
51
+ // v1.5.0:浏览记录按 TTL 清扫(默认 0=不自动清,用户开了才跑)
52
+ try {
53
+ const opts = resolveOptions(config)
54
+ if (Number(opts.contextTtlHours) > 0) {
55
+ void sweepContext(opts.settingsFile, opts.contextTtlHours).then((r) => {
56
+ if (r.removed > 0) ctx?.logger?.info?.(`dsh-gallery: 清掉 ${r.removed} 条过期浏览记录`)
57
+ }).catch(() => {})
58
+ }
59
+ } catch { /* 忽略 */ }
50
60
  try {
51
61
  const opts = resolveOptions(config)
52
62
  void sweepExpiredFeedback(opts.settingsFile, opts).then((r) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-gallery",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "description": "产出台:图片 / 文件 / 音视频实时可见、当场校验;原生产出标签(素材 / 过程稿 / 定稿 / 未归类)可手动改且持久生效,改标签动作与图上圈选批注攒进反馈篮,由人审核合并后发送,全程零自动发送;视频「截取当前帧」自动存入当前对话资产;图上左键拖矩形、左键逐点圈不规则区域直接进反馈篮、右键逐点闭合成实心多边形导出 ComfyUI 直接可用的 RGBA 遮罩(选区内 alpha=0、RGB 保留原图),另出红 / 绿 / 蓝纯色半透明填充预览供目视核对;同一张图可连框多处,每处各带说明一并交给助手;内置三个只读工具——按关键词或对话标题查资产、读到「你此刻正在看哪张」与最近看过的十几张、给出你框选区域的整图像素矩形与外扩裁剪图并可直接取用你已画好的遮罩;图片查看器带像素级放大镜裁剪(绿框八向手柄、裁剪尺寸、光标处坐标与色值);分类显隐按图片 / 文件 / 音视频各记各的,支持多个扫描目录;把图拖进对话框会自动带上文件名与绝对路径(含对应主遮罩名),助手不必扫目录找图;图片查看器带前后对比——两张图叠在同一处用滑块左右拖动、放大后仍像素级对齐、也能切平铺并排看,批量选两张即可进对比,候选按遮罩关系/同尺寸智能推荐配对。Output gallery for DeepSeek Harness: live image/file/audio/video preview, persistent manual asset labels, region annotations and label changes queued in a human-approved feedback basket, one-click video frame capture filed into the current session, rectangle / multi-point polygon / irregular region selections, ComfyUI-ready RGBA mask export (alpha=0 inside the selection, original RGB kept) plus a colored translucent fill preview, three read-only agent tools (keyword or conversation search, what you are viewing right now, and pixel rects plus expanded crops of your selections with direct reuse of a mask you already painted), pixel-level magnifier crop in the viewer, multi-root scanning, and drag-to-chat that carries the file name and absolute path so agents need no directory scan; before/after comparison in the viewer — two images stacked with a draggable slider that stays pixel-aligned when zoomed, or side-by-side tiles, batch-select two or pick from smart-ranked candidates by mask relation and matching size.",
6
6
  "repository": {