dsh-gallery 1.0.0 → 1.2.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.
package/host/tools.js CHANGED
@@ -24,14 +24,26 @@ import { scanGallery } from './scan.js'
24
24
  import { applyAssetFilter, sortByRelevance } from './http.js'
25
25
  import { resolveOptions } from './settings.js'
26
26
  // 阶段 3 / C1:读「人正在看哪张图」(另一份临时状态,只读)
27
- import { readContext } from './context.js'
27
+ // 第二档:扩成「面板现状 + 最近看过的若干张」
28
+ import { readState } from './context.js'
29
+ import { readMarks } from './marks.js'
30
+ import { rankRecent, activityReasons, describePanel, isPriority } from './activity.js'
28
31
  // 原图 / 预览图反查配套主遮罩(与前端双击、拖图同一口径)
29
32
  import { buildLinkedMaskIndex } from './frames.js'
33
+ // 区域感知(2026-11-16):把「人在这张图上框了哪儿」直接告诉模型。
34
+ // 起因是实测:用户框选后说「把框里的字母改掉」,模型拿不到框的位置,
35
+ // 只能翻 frames.json / 临时目录满地找,光找就花了 97 秒。
36
+ import { readFeedback } from './feedback.js'
37
+ import { annotationsFor, latestAnnotationAt, materializeRegions, materializeMaskRegion } from './regions.js'
30
38
 
31
39
  const TOOL_NAME = 'gallery_find'
32
40
  const CONTEXT_TOOL_NAME = 'gallery_context'
41
+ const REGIONS_TOOL_NAME = 'gallery_regions'
33
42
  const MAX_LIMIT = 100
34
43
  const DEFAULT_LIMIT = 20
44
+ // 第二档:gallery_context 一次列多少张「最近看过的」。
45
+ // 固定值不给参数:这个工具要的是「报现状」,多一个参数只会多占模型上下文。
46
+ const CONTEXT_LIST_LIMIT = 12
35
47
 
36
48
  /**
37
49
  * 短时复用扫描结果(2026-11-15):同一轮里模型反复查同一批资产时,
@@ -150,7 +162,9 @@ async function findAssets(args, exec, config) {
150
162
  filterAction: '',
151
163
  filterExt: '',
152
164
  filterQuery: typeof a.query === 'string' ? a.query.trim().toLowerCase() : '',
153
- filterLimit: 500,
165
+ // 第一档:过滤阶段不再截断。旧值 500 会把宽词命中的真正头名挡在外面;
166
+ // 实际返回条数仍由 limit 控制,这里只影响「按相关性挑前 N 条」的候选池。
167
+ filterLimit: 200000,
154
168
  settingsFile: opts.settingsFile,
155
169
  })
156
170
 
@@ -181,8 +195,11 @@ async function findAssets(args, exec, config) {
181
195
  }
182
196
  // 有关键词时按相关性排(与清单接口同一套打分);没关键词时仍按时间倒序。
183
197
  const q = typeof a.query === 'string' ? a.query.trim().toLowerCase() : ''
198
+ // 排序用过滤阶段实际生效的词(可能是模糊兜底的两字组),否则会打 0 分退化成按时间排
199
+ const orderTerms = Array.isArray(filtered?.queryTerms) && filtered.queryTerms.length > 0
200
+ ? filtered.queryTerms : q
184
201
  const ordered = q !== ''
185
- ? sortByRelevance(rows, q, (r) => String(maskIndex.get(r.relPath)?.sourceName ?? ''))
202
+ ? sortByRelevance(rows, orderTerms, (r) => String(maskIndex.get(r.relPath)?.sourceName ?? ''))
186
203
  : rows.slice().sort((x, y) => y.mtime - x.mtime)
187
204
 
188
205
  return { total: ordered.length, items: ordered.slice(0, limit), error: '' }
@@ -251,20 +268,83 @@ export function buildToolDefinition(config) {
251
268
  }
252
269
  }
253
270
 
254
- /** 阶段 3 / C1:把「人正在看哪张」写成模型直接看得懂的文字。 */
271
+ /** 第二档:把「面板现状 + 最近看过的几张」写成模型直接看得懂的文字。 */
255
272
  function renderContext(args, value) {
256
- const it = value?.item
257
- if (value?.found !== true || it === null || it === undefined || String(it?.relPath ?? '') === '') {
258
- return [{ type: 'text', text: typeof value?.text === 'string' && value.text !== ''
259
- ? value.text : '产出台里还没记下用户打开过哪张图(需要用户先在产出台点开一张大图)。' }]
273
+ // execute 已经把完整文本算好放进 text 时直接透传,不再重拼一遍
274
+ const preset = typeof value?.text === 'string' ? value.text : ''
275
+ if (preset !== '') return [{ type: 'text', text: preset }]
276
+ const lines = []
277
+ const panelText = typeof value?.panelText === 'string' ? value.panelText : ''
278
+ if (panelText !== '') {
279
+ lines.push('产出台此刻的状态:')
280
+ lines.push(panelText)
281
+ lines.push('')
282
+ }
283
+ // 「此刻正开着的那张」单独写一行:排序按活跃度走,正在看不一定排第一,
284
+ // 靠这行文字让模型永远分得清「我这张图」指的是哪一张。
285
+ const current = value?.current
286
+ if (current !== null && current !== undefined && String(current?.relPath ?? '') !== '') {
287
+ lines.push(`用户此刻正开着的是:${current.name || current.relPath}`)
288
+ lines.push(` 路径:${current.absPath || current.relPath}`)
289
+ // 已经手动画好遮罩的图,必须在这里就点明「现成可用」。
290
+ // 不点明的话,模型会怀疑这只是一张预览图,然后自己写脚本去量像素(实测耗掉三分半钟)。
291
+ const curMask = String(current?.maskAbsPath ?? '')
292
+ if (curMask !== '') {
293
+ lines.push(` 这张图已经有用户手动画好的遮罩:${curMask}`)
294
+ lines.push(' (现成可用,直接拿去重绘;要它盖住哪一块、或要一张裁剪小图,调 gallery_regions)')
295
+ }
296
+ lines.push('')
297
+ }
298
+ // 框选批注:这条过去完全没有出口,模型只能自己翻文件找(实测花了 97 秒)。
299
+ // 有就明说,并且直接指向 gallery_regions —— 不要让模型再摸黑试。
300
+ const annots = Array.isArray(value?.annotations) ? value.annotations : []
301
+ if (annots.length > 0) {
302
+ lines.push(`用户在「此刻开着的那张图」上框了 ${annots.length} 处区域:`)
303
+ annots.forEach((a) => {
304
+ const shapeText = a.shape === 'polygon'
305
+ ? `不规则区域 ${a.pointCount} 点`
306
+ : '矩形区域'
307
+ const noteText = a.note !== '' ? ` | 说明:${a.note}` : ''
308
+ lines.push(` ${a.index}. ${shapeText} · 左 ${a.xPct}% 上 ${a.yPct}% 宽 ${a.wPct}% 高 ${a.hPct}%${noteText}`)
309
+ })
310
+ lines.push(' → 要看框里到底是什么、要现成的裁剪小图或遮罩,直接调 gallery_regions。')
311
+ lines.push(' 不要再去翻 feedback.json / frames.json / 临时目录,也不要自己写脚本反解坐标。')
312
+ lines.push('')
313
+ }
314
+ const items = Array.isArray(value?.items) ? value.items : []
315
+ if (items.length === 0) {
316
+ lines.push('产出台里还没记下用户打开过哪张图(需要用户先在产出台点开一张大图)。')
317
+ return [{ type: 'text', text: lines.join('\n') }]
318
+ }
319
+ lines.push(`用户最近在产出台里打开过这 ${items.length} 张,按活跃度排`
320
+ + '(此刻正开着、打过标记的优先展示;其次才是最近标注、最近生成 / 改动的,看过次数排最后):')
321
+ items.forEach((it, i) => {
322
+ const reasons = Array.isArray(it.reasons)
323
+ ? it.reasons.filter((x) => typeof x === 'string' && x !== '') : []
324
+ const tag = reasons.length > 0 ? ` | ${reasons.join(' · ')}` : ''
325
+ lines.push(`${i + 1}. ${it.name || it.relPath}${tag}`)
326
+ lines.push(` 路径:${it.absPath || it.relPath}`)
327
+ const meta = [`分类:${it.category}${it.categoryManual ? '(手动改过)' : ''}`]
328
+ if (it.sessionTitle) meta.push(`会话「${it.sessionTitle}」`)
329
+ lines.push(` ${meta.join(' | ')}`)
330
+ if (it.maskAbsPath) lines.push(` 主遮罩:${it.maskAbsPath}`)
331
+ })
332
+ // 标记过、却不在这份清单里的图:点个名,免得用户以为「我标过的那张怎么没出现」。
333
+ const marksNotListed = Array.isArray(value?.marksNotListed) ? value.marksNotListed : []
334
+ if (marksNotListed.length > 0) {
335
+ const nowMs = Date.now()
336
+ lines.push('')
337
+ lines.push('另外,用户还标记过下面这几张,但它们不在上面这份「最近看过」清单里:')
338
+ for (const m of marksNotListed) {
339
+ const days = Math.max(0, Math.round((nowMs - (Number(m.markedAt) || 0)) / 86400000))
340
+ const when = days <= 0 ? '今天' : `${days} 天前`
341
+ lines.push(` · ${m.relPath}(${when}标记)`)
342
+ }
343
+ lines.push(' 要它们的绝对路径就用 gallery_find 按文件名查,别自己拼目录。')
344
+ lines.push('')
260
345
  }
261
- const lines = ['用户最近在产出台里打开看的资产:']
262
- lines.push(`· 文件名:${it.name || it.relPath}`)
263
- lines.push(`· 完整路径:${it.absPath || it.relPath}`)
264
- lines.push(`· 分类:${it.category}${it.categoryManual ? '(手动改过)' : ''}`)
265
- if (it.sessionTitle) lines.push(`· 所属对话:${it.sessionTitle}`)
266
- if (it.maskAbsPath) lines.push(`· 主遮罩:${it.maskAbsPath}`)
267
346
  lines.push('以上均为绝对路径;做局部重绘时用「图 + 主遮罩」成对取用。')
347
+ lines.push('这只是「用户最近看过的几张」和面板现状,不是全库清单;要找具体资产、或按关键词定位,请用 gallery_find。')
268
348
  return [{ type: 'text', text: lines.join('\n') }]
269
349
  }
270
350
 
@@ -272,9 +352,14 @@ function renderContext(args, value) {
272
352
  export function buildContextToolDefinition(config) {
273
353
  return {
274
354
  name: CONTEXT_TOOL_NAME,
275
- description: '查用户此刻(或最近一次)在产出台里点开看的是哪一件资产。'
276
- + '当用户说「我刚看的那张」「这张图」「当前打开的图」时用本工具,'
277
- + '不要让用户重新报文件名。返回完整绝对路径与关联主遮罩。只读,不发送任何消息。',
355
+ description: '查产出台此刻的状态:面板停在哪个视图、筛掉了哪几类、一共多少资产、分几个对话组,'
356
+ + '以及用户最近打开看过哪几张图(按活跃度排:此刻正开着 / 打过标记的优先展示,'
357
+ + '其次按最近标注、最近生成改动、看过次数)。'
358
+ + '当用户说「这张图」「我刚看的那张」「刚才那几张」「我连着看的那组」'
359
+ + '「产出台里现在有什么 / 还剩多少」时都用本工具,不要让用户重新报文件名。'
360
+ + '返回完整绝对路径与关联主遮罩。只读,不发送任何消息。'
361
+ + '这是「最近看过的几张」而不是全库;要找具体某张、或按关键词定位,用 gallery_find。',
362
+ // 不给参数:这个工具就是「报一下现状 + 最近看过的几张」,多一个参数只会多占上下文
278
363
  parameters: { type: 'object', properties: {} },
279
364
  output: {
280
365
  schema: {
@@ -293,7 +378,73 @@ export function buildContextToolDefinition(config) {
293
378
  },
294
379
  required: ['relPath', 'absPath'],
295
380
  },
381
+ items: {
382
+ type: 'array',
383
+ description: '最近看过的图,按活跃度从高到低',
384
+ items: {
385
+ type: 'object',
386
+ properties: {
387
+ relPath: { type: 'string' }, absPath: { type: 'string' },
388
+ name: { type: 'string' }, category: { type: 'string' },
389
+ categoryManual: { type: 'boolean' },
390
+ sessionTitle: { type: 'string' },
391
+ maskAbsPath: { type: 'string' },
392
+ activityScore: { type: 'number', description: '活跃度分,越高越可能是用户此刻要找的' },
393
+ priority: { type: 'boolean', description: '是否属于优先展示那一档(此刻正开着 / 打过标记)' },
394
+ reasons: {
395
+ type: 'array',
396
+ description: '为什么排在前面:正在看 / 打过标记 / 刚标注过 / 刚生成改过 / 看过几次',
397
+ items: { type: 'string' },
398
+ },
399
+ },
400
+ required: ['relPath', 'absPath'],
401
+ },
402
+ },
403
+ panel: {
404
+ type: 'object',
405
+ description: '面板现状;用户还没打开过面板时数字可能为 0',
406
+ properties: {
407
+ scope: { type: 'string', description: 'global=全部对话 / session=当前对话' },
408
+ kind: { type: 'string', description: 'image / file / media' },
409
+ page: { type: 'number' },
410
+ total: { type: 'number', description: '当前视图里的资产总数' },
411
+ groupCount: { type: 'number', description: '分几个对话组' },
412
+ },
413
+ required: [],
414
+ },
296
415
  text: { type: 'string' },
416
+ annotationCount: { type: 'number', description: '此刻开着的那张图上有几处框选批注' },
417
+ annotations: {
418
+ type: 'array',
419
+ description: '此刻开着的那张图上的框选区域,坐标是相对整图的百分比',
420
+ items: {
421
+ type: 'object',
422
+ properties: {
423
+ index: { type: 'number' },
424
+ shape: { type: 'string', description: 'rect=矩形 / polygon=不规则区域' },
425
+ xPct: { type: 'number', description: '左边距,百分比 0–100' },
426
+ yPct: { type: 'number' },
427
+ wPct: { type: 'number' },
428
+ hPct: { type: 'number' },
429
+ note: { type: 'string', description: '用户给这块写的说明,可能为空' },
430
+ pointCount: { type: 'number', description: '不规则区域的顶点数' },
431
+ },
432
+ required: ['index', 'shape'],
433
+ },
434
+ },
435
+ marksNotListed: {
436
+ type: 'array',
437
+ description: '打过标记、但不在 items 清单里的图;只有相对路径,定位用 gallery_find',
438
+ items: {
439
+ type: 'object',
440
+ properties: {
441
+ relPath: { type: 'string' },
442
+ markedAt: { type: 'number' },
443
+ action: { type: 'string' },
444
+ },
445
+ required: ['relPath'],
446
+ },
447
+ },
297
448
  },
298
449
  required: ['found', 'item'],
299
450
  },
@@ -302,27 +453,348 @@ export function buildContextToolDefinition(config) {
302
453
  async execute() {
303
454
  try {
304
455
  const opts = resolveOptions(config)
305
- const item = await readContext(opts.settingsFile)
306
- if (item === null) {
307
- const text = '产出台里还没记下用户打开过哪张图(需要用户先在产出台点开一张大图)。'
308
- return { found: false, item: { relPath: '', absPath: '' }, text }
456
+ const state = await readState(opts.settingsFile)
457
+ // 标记(approve / reject / finalize…)也是活跃度的一部分:人表过态的更可能是目标
458
+ let marks = {}
459
+ try { marks = (await readMarks(opts.settingsFile)).marks ?? {} } catch { marks = {} }
460
+ const markedRels = new Set(Object.keys(marks))
461
+ const currentRel = state.recent.length > 0 ? String(state.recent[0].relPath ?? '') : ''
462
+ // 批注只读一次,两处都用得上:
463
+ // ① 每张图「最后一次标注」的时间 —— 排序里排在生成 / 改动之前(老板 11-16 口径);
464
+ // ② 当前这张图的批注明细 —— 模型不用再翻文件找框在哪儿。
465
+ let feedback = {}
466
+ try { feedback = (await readFeedback(opts.settingsFile)).feedback ?? {} } catch { feedback = {} }
467
+ const rankOpts = {
468
+ currentRelPath: currentRel,
469
+ markedRels,
470
+ annotatedRels: latestAnnotationAt(feedback),
471
+ }
472
+ const ranked = rankRecent(state.recent, rankOpts)
473
+ const items = ranked.slice(0, CONTEXT_LIST_LIMIT).map((it) => ({
474
+ ...it,
475
+ // 第一梯队(此刻正开着 / 打过标记)单独标出来,渲染时另起一段,模型一眼看得清
476
+ priority: isPriority(it, rankOpts),
477
+ reasons: activityReasons(it, rankOpts),
478
+ }))
479
+ const panel = state.panel
480
+ // 打过标记、但不在「最近看过」里的图:这份列表覆盖不到它们。
481
+ // 不补这一句,用户会以为「我标过的那张怎么没出现」。
482
+ // 只提文件名与日期,不给绝对路径 —— 标记记录里只有相对路径,多根目录时硬拼会拼错,
483
+ // 让模型用 gallery_find 去定位,宁可少给也不给错。
484
+ const recentSet = new Set(state.recent.map((r) => String(r.relPath ?? '').replace(/\\/g, '/')))
485
+ const marksNotListed = Object.entries(marks)
486
+ .map(([rel, m]) => ({
487
+ relPath: String(rel).replace(/\\/g, '/'),
488
+ markedAt: Number(m?.markedAt) || 0,
489
+ action: String(m?.action ?? ''),
490
+ }))
491
+ .filter((m) => m.markedAt > 0 && !recentSet.has(m.relPath))
492
+ .sort((a, b) => b.markedAt - a.markedAt)
493
+ .slice(0, 3)
494
+ // 当前图上有没有人刚框的区域 —— 这是模型最需要、过去却完全拿不到的一条事实。
495
+ // 拿不到它,模型只能自己翻 feedback.json / frames.json / 临时目录,
496
+ // 实测一次要 97 秒。这里直接给摘要,细节留给 gallery_regions。
497
+ let annotations = []
498
+ try { annotations = annotationsFor(feedback, currentRel) } catch { annotations = [] }
499
+ const annotationBrief = annotations.map((a, i) => ({
500
+ index: i + 1,
501
+ shape: a.shape,
502
+ xPct: Math.round(a.x * 1000) / 10,
503
+ yPct: Math.round(a.y * 1000) / 10,
504
+ wPct: Math.round(a.w * 1000) / 10,
505
+ hPct: Math.round(a.h * 1000) / 10,
506
+ note: a.note,
507
+ pointCount: Array.isArray(a.polygon) ? a.polygon.length : 0,
508
+ }))
509
+ const value = {
510
+ found: items.length > 0,
511
+ item: items[0] ?? { relPath: '', absPath: '' },
512
+ items,
513
+ // 最近打开的那一张(不管它排第几,都单独告诉模型「此刻正开着的是这张」)
514
+ current: state.recent.length > 0 ? state.recent[0] : null,
515
+ panel: panel ?? { scope: '', kind: '', page: 0, total: 0, groupCount: 0 },
516
+ panelText: describePanel(panel),
517
+ // 此刻正开着的那张图上有几条框选批注(0 = 没框)
518
+ annotationCount: annotationBrief.length,
519
+ annotations: annotationBrief,
520
+ // 标记过但不在「最近看过」清单里的图(只给名字,定位走 gallery_find)
521
+ marksNotListed,
522
+ text: '',
309
523
  }
310
- const text = renderContext({}, { found: true, item })[0].text
311
- return { found: true, item, text }
524
+ value.text = renderContext({}, value)[0].text
525
+ return value
312
526
  } catch (error) {
313
527
  const text = `产出台当前状态读取失败:${String(error?.message ?? error)}`
314
- return { found: false, item: { relPath: '', absPath: '' }, text }
528
+ return { found: false, item: { relPath: '', absPath: '' }, items: [], text }
315
529
  }
316
530
  },
317
531
  }
318
532
  }
533
+ /**
534
+ * 区域工具的文字输出。
535
+ * 铁律:裁剪图的**绝对路径必须写在正文里** —— 模型只会照着正文里的路径去 read_image,
536
+ * 藏在结构化字段里它看不见(这一条在查图工具上已经吃过一次)。
537
+ */
538
+ function renderRegions(args, value) {
539
+ if (value?.error) return [{ type: 'text', text: `产出台区域查询失败:${value.error}` }]
540
+ const regions = Array.isArray(value?.regions) ? value.regions : []
541
+ if (regions.length === 0) {
542
+ return [{ type: 'text', text: value?.hint || '这张图上没有任何框选批注。' }]
543
+ }
544
+ const size = value?.image ?? { width: 0, height: 0 }
545
+ const byMask = value?.source === 'mask'
546
+ const lines = []
547
+ lines.push(`图:${value.absPath}`)
548
+ lines.push(`尺寸:${size.width} × ${size.height} 像素`)
549
+ if (byMask) {
550
+ lines.push('')
551
+ lines.push('用户已经手动画好遮罩了,遮罩文件是现成的 —— 直接用,不要再自己算坐标,也不要重新生成遮罩:')
552
+ lines.push(` 遮罩文件 ${value.maskAbsPath}`)
553
+ lines.push(' (全尺寸;选区里透明、其余保留原图。边界是用户自己画的,以它为准。)')
554
+ }
555
+ if (value?.degraded) lines.push(`注意:${value.degraded}`)
556
+ lines.push('')
557
+ regions.forEach((r) => {
558
+ const shapeText = r.shape === 'mask'
559
+ ? '遮罩覆盖范围'
560
+ : (r.shape === 'polygon' ? `不规则区域(${r.pointCount} 点)` : '矩形区域')
561
+ lines.push(`区域 ${r.index}:${shapeText}`)
562
+ lines.push(` 整图位置:左 ${r.px.x}px 上 ${r.px.y}px 宽 ${r.px.w}px 高 ${r.px.h}px`
563
+ + `(即 左 ${r.xPct}% 上 ${r.yPct}% 宽 ${r.wPct}% 高 ${r.hPct}%)`)
564
+ if (r.note !== '') lines.push(` 用户说明:${r.note}`)
565
+ if (r.cropPath) {
566
+ const cb = r.cropBox ?? {}
567
+ lines.push(` 裁剪图(已外扩一圈便于看清上下文):${r.cropPath}`)
568
+ lines.push(` 裁剪范围 左 ${cb.x}px 上 ${cb.y}px 宽 ${cb.w}px 高 ${cb.h}px`)
569
+ }
570
+ if (r.maskPath && r.shape !== 'mask') {
571
+ lines.push(` 临时遮罩(全尺寸,框内 alpha=0、框外保留原图):${r.maskPath}`)
572
+ }
573
+ })
574
+ lines.push('')
575
+ if (byMask) {
576
+ lines.push('用法:遮罩已经就位,直接拿「图 + 上面那个遮罩文件」提交重绘。')
577
+ lines.push('要确认框住的是哪个字,看一眼上面的裁剪图就够了 —— 不要再去量透明像素数、算覆盖率、画框放大、生成诊断图。')
578
+ lines.push('结果出来后立刻交付给用户看,最多整体比一眼,不要逐像素反复验收 —— 好坏由用户判断。')
579
+ } else {
580
+ lines.push('用法:先用 read_image 看一眼上面的裁剪图,确认框里到底是什么,再动手。')
581
+ lines.push('看一眼就够;结果出来后立刻交付给用户,不要自己反复量化验收。')
582
+ }
583
+ lines.push('这些裁剪图和临时遮罩都在系统临时目录,只供本次使用;要正式存进产出台,让用户在那里导出遮罩。')
584
+ return [{ type: 'text', text: lines.join('\n') }]
585
+ }
586
+
587
+ /**
588
+ * 区域感知工具(2026-11-16):把「用户在这张图上框了哪儿」一次给全。
589
+ *
590
+ * 存在的理由(实测数据):用户框选后说「把框里的字母改掉」,模型拿不到框位置,
591
+ * 翻 frames.json / feedback.json / 临时目录找了 7 次、花了 97 秒才发现框在哪,
592
+ * 又花 150 秒自己写 PIL 反解坐标。这个工具把这些全部前置。
593
+ */
594
+ export function buildRegionsToolDefinition(config) {
595
+ return {
596
+ name: REGIONS_TOOL_NAME,
597
+ description: '取产出台里「用户此刻开着的那张图」上要处理的那块区域。两种情况都会答:'
598
+ + '① 用户已经画好遮罩(右键逐点填充后导出的遮罩文件)→ 直接把现成遮罩的绝对路径、'
599
+ + '覆盖范围、外扩后的裁剪小图报回来,照用即可;'
600
+ + '② 用户只在反馈篮里框了区域 → 报每块区域的整图像素位置、外扩裁剪图、可选临时遮罩。'
601
+ + '凡是用户说「这张图」「框选的这块」「我圈的地方」「把框里的 X 改成 Y」「按这个遮罩重绘」时,'
602
+ + '第一个动作就调本工具,不要自己去找 feedback.json / frames.json / 临时目录,'
603
+ + '也不要自己写脚本量透明像素、算覆盖率、画包围盒或反解归一化坐标 —— 那些又慢又容易找错。'
604
+ + '拿到区域后不要再反复校验遮罩是否「合格」:边界是用户画的,以它为准。'
605
+ + '两者都没有时本工具会直接说明,此时再按整图处理。'
606
+ + '只读:不改资产、不写反馈、不发送消息;裁剪图只落系统临时目录。',
607
+ parameters: {
608
+ type: 'object',
609
+ properties: {
610
+ relPath: { type: 'string', description: '要查的资产相对路径;留空=用户此刻开着的那张' },
611
+ withMask: { type: 'boolean', description: '要不要顺手生成临时 RGBA 遮罩;做局部重绘时填 true' },
612
+ },
613
+ },
614
+ output: {
615
+ schema: {
616
+ type: 'object',
617
+ properties: {
618
+ found: { type: 'boolean', description: '这张图上有没有框选批注,或有没有用户画好的遮罩' },
619
+ source: { type: 'string', description: 'mask=用户已画好的遮罩文件(现成可用) / annotation=反馈篮里的框选批注 / none=都没有' },
620
+ maskAbsPath: { type: 'string', description: '用户画好的遮罩绝对路径(有就是现成的,直接用)' },
621
+ absPath: { type: 'string', description: '图本身的绝对路径' },
622
+ image: {
623
+ type: 'object',
624
+ properties: { width: { type: 'number' }, height: { type: 'number' } },
625
+ required: [],
626
+ },
627
+ regions: {
628
+ type: 'array',
629
+ items: {
630
+ type: 'object',
631
+ properties: {
632
+ index: { type: 'number' },
633
+ shape: { type: 'string' },
634
+ px: {
635
+ type: 'object',
636
+ description: '整图像素矩形',
637
+ properties: {
638
+ x: { type: 'number' }, y: { type: 'number' },
639
+ w: { type: 'number' }, h: { type: 'number' },
640
+ },
641
+ required: [],
642
+ },
643
+ xPct: { type: 'number' }, yPct: { type: 'number' },
644
+ wPct: { type: 'number' }, hPct: { type: 'number' },
645
+ note: { type: 'string' },
646
+ pointCount: { type: 'number' },
647
+ cropPath: { type: 'string', description: '外扩后的裁剪小图绝对路径' },
648
+ maskPath: { type: 'string', description: '临时遮罩绝对路径(未要求时为空)' },
649
+ pixelCount: { type: 'number', description: '遮罩里被选中的像素数(仅参考,不要拿它做验收)' },
650
+ },
651
+ required: ['index', 'shape'],
652
+ },
653
+ },
654
+ degraded: { type: 'string', description: '降级说明;正常时为空' },
655
+ hint: { type: 'string' },
656
+ error: { type: 'string' },
657
+ },
658
+ required: ['found', 'regions'],
659
+ },
660
+ render: renderRegions,
661
+ },
662
+ async execute(args) {
663
+ try {
664
+ const opts = resolveOptions(config)
665
+ const state = await readState(opts.settingsFile)
666
+ const wanted = String(args?.relPath ?? '').replace(/\\/g, '/')
667
+ let relPath = wanted
668
+ let absPath = ''
669
+ let entry = null
670
+ if (relPath === '') {
671
+ entry = state.recent.length > 0 ? state.recent[0] : null
672
+ relPath = String(entry?.relPath ?? '')
673
+ absPath = String(entry?.absPath ?? '')
674
+ } else {
675
+ // 用户点名了某张:顺带取回它的主遮罩(可能是他自己画好导出的)
676
+ entry = state.recent.find(
677
+ (r) => String(r?.relPath ?? '').replace(/\\/g, '/') === relPath,
678
+ ) ?? null
679
+ }
680
+ if (relPath === '') {
681
+ return {
682
+ found: false, regions: [], absPath: '',
683
+ image: { width: 0, height: 0 },
684
+ hint: '产出台还没记下用户打开过哪张图;请让用户先在产出台点开要处理的那张。',
685
+ }
686
+ }
687
+ if (absPath === '') {
688
+ // 只给了 relPath:按产出根还原绝对路径,绝不拼任意路径
689
+ for (const root of opts.roots) {
690
+ if (typeof root !== 'string' || root === '') continue
691
+ const abs = path.resolve(root, relPath)
692
+ if (!abs.startsWith(path.resolve(root) + path.sep)) continue
693
+ try {
694
+ const st = statSync(abs)
695
+ if (st.isFile()) { absPath = abs; break }
696
+ } catch { /* 换下一个根 */ }
697
+ }
698
+ }
699
+ if (absPath === '') {
700
+ return {
701
+ found: false, regions: [], absPath: '',
702
+ image: { width: 0, height: 0 },
703
+ hint: `找不到这张资产:${relPath}`,
704
+ }
705
+ }
706
+ const fb = await readFeedback(opts.settingsFile)
707
+ const annotations = annotationsFor(fb.feedback, relPath)
708
+ // 用户还有一条更常用的路:右键逐点填充 → 导出遮罩文件,遮罩已经躺在产出目录里。
709
+ // 这种情况根本没有批注,但现成的遮罩比批注更准 —— 必须优先把它报出来,
710
+ // 否则模型会以为「用户没框过」,然后自己从头量像素(实测耗掉三分半钟)。
711
+ const maskAbsPath = String(entry?.maskAbsPath ?? '')
712
+ const hasMask = maskAbsPath !== '' && path.isAbsolute(maskAbsPath)
713
+
714
+ if (annotations.length > 0) {
715
+ const out = await materializeRegions({
716
+ absPath,
717
+ annotations,
718
+ withCrop: args?.withCrop !== false,
719
+ withMask: args?.withMask === true,
720
+ })
721
+ return {
722
+ found: out.regions.length > 0,
723
+ source: 'annotation',
724
+ absPath,
725
+ relPath,
726
+ maskAbsPath: hasMask ? maskAbsPath : '',
727
+ image: out.image,
728
+ regions: out.regions,
729
+ degraded: out.degraded ?? '',
730
+ hint: '',
731
+ }
732
+ }
733
+
734
+ if (hasMask) {
735
+ const out = await materializeMaskRegion({ absPath, maskPath: maskAbsPath, withCrop: true })
736
+ if (out.region === null) {
737
+ return {
738
+ found: false, source: 'mask', absPath, relPath,
739
+ maskAbsPath, image: out.image, regions: [], degraded: out.degraded ?? '',
740
+ hint: `这张图有一份用户画好的遮罩(${maskAbsPath}),可以直接用于重绘;`
741
+ + `只是这次没能读出它的覆盖范围(${out.degraded || '原因未知'})。`,
742
+ }
743
+ }
744
+ return {
745
+ found: true,
746
+ source: 'mask',
747
+ absPath,
748
+ relPath,
749
+ maskAbsPath,
750
+ image: out.image,
751
+ regions: [{
752
+ index: 1,
753
+ shape: 'mask',
754
+ px: out.region.px,
755
+ xPct: out.region.xPct,
756
+ yPct: out.region.yPct,
757
+ wPct: out.region.wPct,
758
+ hPct: out.region.hPct,
759
+ note: '',
760
+ pointCount: 0,
761
+ pixelCount: out.region.pixelCount,
762
+ cropPath: out.region.cropPath,
763
+ cropBox: out.region.cropBox,
764
+ maskPath: maskAbsPath,
765
+ }],
766
+ degraded: out.degraded ?? '',
767
+ hint: '',
768
+ }
769
+ }
770
+
771
+ return {
772
+ found: false, source: 'none', regions: [], absPath, relPath,
773
+ image: { width: 0, height: 0 }, maskAbsPath: '',
774
+ hint: `这张图上既没有框选批注,也没有用户存好的遮罩(${relPath})。`
775
+ + '用户确实没在这张图上框过,请按整张图处理。',
776
+ }
777
+ } catch (error) {
778
+ return {
779
+ found: false, regions: [], absPath: '', image: { width: 0, height: 0 },
780
+ error: String(error?.message ?? error),
781
+ }
782
+ }
783
+ },
784
+ }
785
+ }
786
+
319
787
  /**
320
788
  * 在插件 apply() 里调用。
321
789
  * 返回 disposer;任何失败都吞掉并记日志 —— 绝不能因为 tool 注册失败
322
790
  * 让整个产出台插件不激活(拖累既有的资产台与全部 op)。
323
791
  */
324
792
  export function registerTools(ctx, config) {
325
- const definitions = [buildToolDefinition(config), buildContextToolDefinition(config)]
793
+ const definitions = [
794
+ buildToolDefinition(config),
795
+ buildContextToolDefinition(config),
796
+ buildRegionsToolDefinition(config),
797
+ ]
326
798
  if (!ctx?.tools || typeof ctx.tools.register !== 'function') {
327
799
  ctx?.logger?.warn?.('dsh-gallery: ctx.tools 不可用,Agent 工具未注册')
328
800
  return () => {}
@@ -341,4 +813,4 @@ export function registerTools(ctx, config) {
341
813
  return () => { for (const d of disposers) { try { d() } catch { /* 忽略 */ } } }
342
814
  }
343
815
 
344
- export { TOOL_NAME, CONTEXT_TOOL_NAME, rootOf, toRow, renderRows, renderContext }
816
+ export { TOOL_NAME, CONTEXT_TOOL_NAME, REGIONS_TOOL_NAME, rootOf, toRow, renderRows, renderContext, renderRegions }
package/index.js CHANGED
@@ -20,7 +20,11 @@
20
20
  * tools.js Agent 工具(gallery_find,Host 进程内,模型可直接调用)
21
21
  */
22
22
 
23
- import { registerMediaRoute, registerOpsRoute } from './host/http.js'
23
+ import { registerMediaRoute, registerOpsRoute, setChangeTracker } from './host/http.js'
24
+ import { createChangeTracker } from './host/changes.js'
25
+ import { readFileSync } from 'node:fs'
26
+ import path from 'node:path'
27
+ import { resolveOptions } from './host/settings.js'
24
28
  import { registerTools } from './host/tools.js'
25
29
 
26
30
  export const inject = ['connection', 'webServer', 'tools']
@@ -29,6 +33,51 @@ export function apply(ctx, config) {
29
33
  registerMediaRoute(ctx, config)
30
34
  registerOpsRoute(ctx, config)
31
35
  registerTools(ctx, config)
36
+
37
+ // ---- 资产变动追踪(增量刷新,2026-11-16)----
38
+ // 任何进程往产出根里写资产,都会被 fs.watch 感知;前端凭版本号做增量刷新。
39
+ // 全程 best-effort:失败只记日志,绝不影响面板本身。
40
+ try {
41
+ const opts = resolveOptions(config)
42
+ const roots = (opts.roots ?? []).filter((r) => typeof r === 'string' && r !== '')
43
+
44
+ // 变动文件 → 所属会话:只查 frames.json(内存里已有,零成本)。
45
+ // 插件自己写的资产(粘贴 / 裁剪 / 遮罩 / 截帧)都登记在里面,能定位到组;
46
+ // Agent 写的资产查不到就归 '',前端会退化成整表刷新兜底 —— 这种情况少,
47
+ // 不值得为它每次变动去读会话日志(几百 KB zstd 解压)。
48
+ let frameRelToSid = null
49
+ const sessionOfPath = (rel) => {
50
+ if (rel === '' || rel === null || rel === undefined) return ''
51
+ try {
52
+ if (frameRelToSid === null) {
53
+ frameRelToSid = new Map()
54
+ // readFrames 是同步语义的辅助读取,这里用同步 fs 读一次即可
55
+ const file = opts.settingsFile
56
+ const dir = path.dirname(String(file ?? ''))
57
+ const p = path.join(dir, 'dsh-gallery-frames.json')
58
+ const j2 = JSON.parse(readFileSync(p, 'utf8'))
59
+ const frames = j2?.frames ?? j2 ?? {}
60
+ for (const [k, v] of Object.entries(frames)) {
61
+ if (v !== null && typeof v === 'object' && typeof v.sessionId === 'string' && v.sessionId !== '') {
62
+ frameRelToSid.set(String(k).toLowerCase(), v.sessionId)
63
+ }
64
+ }
65
+ }
66
+ return frameRelToSid.get(String(rel).toLowerCase()) ?? ''
67
+ } catch { return '' }
68
+ }
69
+
70
+ const tracker = createChangeTracker({ roots, sessionOfPath })
71
+ const n = tracker.start()
72
+ setChangeTracker(tracker)
73
+ ctx?.logger?.info?.(`dsh-gallery: 资产变动监听已启动(${n}/${roots.length} 个产出根)`)
74
+ // 插件卸载时停掉监听
75
+ if (typeof ctx?.effect === 'function') {
76
+ ctx.effect(() => () => { try { tracker.stop() } catch { /* 忽略 */ } })
77
+ }
78
+ } catch (error) {
79
+ ctx?.logger?.warn?.('dsh-gallery: 资产变动监听未启动(不影响面板)', error)
80
+ }
32
81
  }
33
82
 
34
83
  // 对外再导出(保持与拆分前的公开接口一致)