@cloud411716/fancy-webnovel 4.0.3 → 4.1.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.
@@ -7,7 +7,9 @@ import { askUserQuestion, llmFollowup, notify, spawnScript } from '#infra';
7
7
  import { readDeployedState, deployedStateProblemText } from '#deployed-state';
8
8
  import { isSensitiveProjectPath, isValidProjectPath } from '#path-guard';
9
9
  import { resolveWorkspace } from '#workspace';
10
- import { localDateStamp, DEFAULT_SCAN_MODE } from '#scraper-utils';
10
+ import { localDateStamp, DEFAULT_SCAN_MODE, SCAN_MODE_VISION } from '#scraper-utils';
11
+ import { registerCommandWithTasks } from '#task-list';
12
+ import { atomicWriteFile } from '#atomic-write';
11
13
  import {
12
14
  backupTopicDecision,
13
15
  listMarkerBlocks,
@@ -22,6 +24,15 @@ import { captureFileState, verifyBlockWritten } from './scripts/report-validate.
22
24
  import { inspectExistingBlock, EXISTING_BLOCK_STATUS } from './existing-block.js';
23
25
  import { waitForAnalysisTurn } from './wait-turn.js';
24
26
  import { deployScanTools, writeScanManifest } from './tool-deploy.js';
27
+ import {
28
+ buildVisionPrompt,
29
+ mergeVisionCategory,
30
+ parseVisionResult,
31
+ readVisionManifest,
32
+ renderVisionMarkdown,
33
+ visionMarkdownFileName,
34
+ visionResultPath,
35
+ } from './vision.js';
25
36
 
26
37
  export const inject = ['commands', 'userQuestions'];
27
38
 
@@ -71,14 +82,213 @@ function getRankLabels(rankIds, platform) {
71
82
  return labels.join('、');
72
83
  }
73
84
 
85
+ /**
86
+ * 命令开始时的任务表。扫描方式还没选出来,所以先不把“视觉识别”
87
+ * 写死进去;选完方式后会按实际模式 reset 一次。
88
+ */
89
+ function scanTaskTitles(rawInput) {
90
+ if (String(rawInput || '').trim().toLowerCase() === 'help') {
91
+ return ['显示扫榜帮助'];
92
+ }
93
+ return [
94
+ '选择平台、榜单与扫描方式',
95
+ '采集榜单数据',
96
+ 'LLM 分析并写入报告',
97
+ '校验报告写入',
98
+ ];
99
+ }
100
+
101
+ /**
102
+ * vision 模式:把 scraper 写出的 manifest 逐题材交给 LLM 视觉识别,
103
+ * 再把识别结果渲染成标准扫榜 md。
104
+ *
105
+ * 为什么按题材分批(而不是整榜一次):
106
+ * - 一个题材 10 本书 = 10 张卡片截图,一轮 LLM 的上下文可控;
107
+ * - 某个题材失败时只重跑该题材,不会把整榜 20 个题材全部拖垮;
108
+ * - 每完成一个题材就能更新任务列表进度。
109
+ *
110
+ * 硬约束:
111
+ * - 只调用视觉识别,**绝不调用 ocrFile / tesseract**;
112
+ * - 模型自报不支持视觉时立即停止,并把原因原样带回命令层。
113
+ */
114
+ export async function runVisionRecognition({
115
+ invocation,
116
+ tasks,
117
+ projectRoot,
118
+ manifestPath,
119
+ date,
120
+ signal,
121
+ // 测试注入点:生产调用不传,默认就是真实的 LLM 派活与等待。
122
+ followup = llmFollowup,
123
+ waitTurn = waitForAnalysisTurn,
124
+ }) {
125
+ let manifest;
126
+ try {
127
+ manifest = readVisionManifest(manifestPath);
128
+ } catch (e) {
129
+ return { ok: false, error: e.message };
130
+ }
131
+
132
+ const allCategories = Array.isArray(manifest.categories) ? manifest.categories : [];
133
+ const recognisable = allCategories.filter((cat) => !cat.error && Array.isArray(cat.books) && cat.books.length);
134
+ if (!recognisable.length) {
135
+ return { ok: false, error: '视觉清单里没有可识别的题材' };
136
+ }
137
+
138
+ const results = [];
139
+ const failed = [];
140
+ let recognisableIndex = 0;
141
+
142
+ for (let manifestIndex = 0; manifestIndex < allCategories.length; manifestIndex += 1) {
143
+ if (signal?.aborted) {
144
+ return { ok: false, aborted: true, error: '操作已取消' };
145
+ }
146
+ const cat = allCategories[manifestIndex];
147
+ const catName = cat && cat.name ? String(cat.name) : '未分类';
148
+
149
+ if (cat && cat.error) {
150
+ results.push({ name: catName, error: cat.error });
151
+ failed.push({ name: catName, error: cat.error });
152
+ continue;
153
+ }
154
+ if (!Array.isArray(cat.books) || !cat.books.length) {
155
+ results.push({ name: catName, error: '没有可用截图' });
156
+ failed.push({ name: catName, error: '没有可用截图' });
157
+ continue;
158
+ }
159
+ // 全部截图都丢了时不要派给 LLM:它只能看到“(截图缺失)”,
160
+ // 白白烧一轮 token,最后也只会得到一页占位书名。
161
+ if (!cat.books.some((b) => b && b.screen && existsSync(b.screen))) {
162
+ results.push({ name: catName, error: '截图文件全部缺失' });
163
+ failed.push({ name: catName, error: '截图文件全部缺失' });
164
+ continue;
165
+ }
166
+
167
+ const resultPath = visionResultPath(manifestPath, manifestIndex);
168
+ mkdirSync(dirname(resultPath), { recursive: true });
169
+
170
+ let parsed = null;
171
+ let lastError = '';
172
+ // 每个题材最多两轮:第一轮正常识别;结果文件缺失/JSON 坏掉时
173
+ // 再给一次机会。模型明确说“不支持视觉”时不再重试。
174
+ for (let attempt = 0; attempt < 2 && !parsed; attempt += 1) {
175
+ try { unlinkSync(resultPath); } catch { /* 不存在 */ }
176
+
177
+ let prompt = buildVisionPrompt({
178
+ manifest,
179
+ category: cat,
180
+ categoryIndex: recognisableIndex,
181
+ categoryCount: recognisable.length,
182
+ resultPath,
183
+ });
184
+ if (attempt > 0) {
185
+ prompt += `\n\n注意:上一次的结果文件${lastError ? `有问题(${lastError})` : '没有生成'},请重新识别并覆盖写入同一个路径。`;
186
+ }
187
+
188
+ const follow = await followup(invocation, prompt, { appendTempRule: false });
189
+ if (!follow || follow.ok !== true) {
190
+ return {
191
+ ok: false,
192
+ error: '视觉识别提示词投递失败:' + ((follow && follow.error) || '未知错误'),
193
+ };
194
+ }
195
+ // 新 turn 开始时 DSH 会清空任务列表;watcher 会在 turn 开始/结束时写回。
196
+ tasks.watchTurns(invocation);
197
+
198
+ const waited = await waitTurn(invocation, { signal });
199
+ if (waited && waited.code === 'ABORTED') {
200
+ return { ok: false, aborted: true, error: '操作已取消' };
201
+ }
202
+ if (!existsSync(resultPath)) {
203
+ lastError = '结果文件没有生成';
204
+ continue;
205
+ }
206
+
207
+ let raw = '';
208
+ try {
209
+ raw = readFileSync(resultPath, 'utf-8');
210
+ } catch (e) {
211
+ lastError = '结果文件读不出来:' + (e && e.message ? e.message : String(e));
212
+ continue;
213
+ }
214
+ try {
215
+ parsed = parseVisionResult(raw);
216
+ } catch (e) {
217
+ lastError = e && e.message ? e.message : String(e);
218
+ continue;
219
+ }
220
+ // “支持视觉但一本书都没识别出来”不能当成功:继续合并只会得到
221
+ // 一整篇 `(bookId: xxx) / 未知`,看起来像采集成功,实际全是占位。
222
+ if (parsed.visionSupported && !parsed.books.length) {
223
+ lastError = '模型没有识别出任何书';
224
+ parsed = null;
225
+ }
226
+ }
227
+
228
+ recognisableIndex += 1;
229
+
230
+ if (!parsed) {
231
+ results.push({ name: catName, error: lastError || '模型没有返回可解析的识别结果' });
232
+ failed.push({ name: catName, error: lastError || '模型没有返回可解析的识别结果' });
233
+ tasks.progress(`LLM 视觉识别截图(${recognisableIndex}/${recognisable.length} 题材)`);
234
+ continue;
235
+ }
236
+
237
+ if (parsed.visionSupported === false) {
238
+ return {
239
+ ok: false,
240
+ unsupported: true,
241
+ error: parsed.reason || '当前模型不支持视觉识别',
242
+ };
243
+ }
244
+
245
+ const merged = mergeVisionCategory(cat, parsed);
246
+ if (merged.missing.length === cat.books.length) {
247
+ // 一条都对不上 = 模型给的 bookId/rank 全是错的。不能把它当
248
+ // “部分识别成功”写进 md,否则整篇都是占位书名。
249
+ results.push({ name: catName, error: '识别结果与截图清单无法对应' });
250
+ failed.push({ name: catName, error: '识别结果与截图清单无法对应' });
251
+ tasks.progress(`LLM 视觉识别截图(${recognisableIndex}/${recognisable.length} 题材)`);
252
+ continue;
253
+ }
254
+ results.push({ name: catName, books: merged.books });
255
+ if (merged.missing.length) {
256
+ failed.push({
257
+ name: catName,
258
+ error: `${merged.missing.length} 本没有识别到:${merged.missing.join('、')}`,
259
+ });
260
+ }
261
+ tasks.progress(`LLM 视觉识别截图(${recognisableIndex}/${recognisable.length} 题材)`);
262
+ }
263
+
264
+ // 一个题材都没识别成功时不要写空 md —— 让上层按失败处理,
265
+ // 避免把一份全是“识别失败”的文件交给分析模型。
266
+ const successful = results.filter((r) => Array.isArray(r.books) && r.books.length > 0);
267
+ if (!successful.length) {
268
+ return {
269
+ ok: false,
270
+ error: failed.length
271
+ ? '所有题材的视觉识别都失败:' + failed.map((f) => `${f.name}(${f.error})`).join(';')
272
+ : '所有题材的视觉识别都失败',
273
+ };
274
+ }
275
+
276
+ const outName = visionMarkdownFileName(manifest, date || manifest.date || localDateStamp());
277
+ const outPath = join(projectRoot, '扫榜结果', outName);
278
+ const markdown = renderVisionMarkdown(manifest, results, date);
279
+ atomicWriteFile(outPath, markdown);
280
+
281
+ return { ok: true, file: outPath, failed };
282
+ }
283
+
74
284
  export async function apply(ctx) {
75
- ctx.commands.register({
285
+ registerCommandWithTasks(ctx, {
76
286
  name: 'fancy-scan',
77
287
  description: '📊 扫榜分析 ( usage: /fancy-scan [help] )',
78
288
  input: {
79
289
  hint: '.',
80
290
  },
81
- handler: async (invocation) => {
291
+ handler: async (invocation, tasks) => {
82
292
  const session = invocation.agent.session;
83
293
  const { signal } = invocation;
84
294
 
@@ -291,6 +501,26 @@ export async function apply(ctx) {
291
501
  scanMode = parsedMode;
292
502
  }
293
503
 
504
+ // 扫描方式选完后才知道要不要加“视觉识别”这一步。
505
+ // reset 保留第一项 completed,其余按新流程重排。
506
+ tasks.reset(
507
+ scanMode === SCAN_MODE_VISION
508
+ ? [
509
+ '选择平台、榜单与扫描方式',
510
+ '采集榜单并截图',
511
+ 'LLM 视觉识别截图',
512
+ 'LLM 分析并写入报告',
513
+ '校验报告写入',
514
+ ]
515
+ : [
516
+ '选择平台、榜单与扫描方式',
517
+ '采集榜单数据',
518
+ 'LLM 分析并写入报告',
519
+ '校验报告写入',
520
+ ],
521
+ { completed: 1 }
522
+ );
523
+
294
524
  // ── 部署工作区内工具脚本 ──────────────────────────────────────
295
525
  // 提示词里的预检/追加命令只能引用工作区内路径。脚本放在插件目录下时,
296
526
  // 模型会去 node_modules 里执行:路径长、随安装位置变化、且那里是
@@ -311,6 +541,7 @@ export async function apply(ctx) {
311
541
  const succeededRankIds = [];
312
542
  const receiptDates = new Set();
313
543
  let lastDate = '';
544
+ let processedRanks = 0;
314
545
  for (const rankId of rankIds) {
315
546
  // 用户按停止后不要再启动下一个榜单的采集(每个榜单可能跑几十分钟)。
316
547
  if (signal?.aborted) {
@@ -318,6 +549,11 @@ export async function apply(ctx) {
318
549
  }
319
550
  const rankRow = RANK_LISTS[platform]?.find(r => r.id === rankId);
320
551
  const rankLabel = rankRow ? rankRow.label : rankId;
552
+ processedRanks += 1;
553
+ tasks.progress(
554
+ `${scanMode === SCAN_MODE_VISION ? '采集榜单并截图' : '采集榜单数据'}` +
555
+ `(${processedRanks}/${rankIds.length}:${rankLabel})`
556
+ );
321
557
 
322
558
  const scriptResult = await spawnScript(
323
559
  'node',
@@ -358,8 +594,57 @@ export async function apply(ctx) {
358
594
  failedRanks.push({ label: rankLabel, error: '采集回执里没有 scan_files 数组' });
359
595
  continue;
360
596
  }
361
- allFiles.push(...files);
362
- if (files.length > 0) succeededRankIds.push(rankId);
597
+
598
+ if (scanMode === SCAN_MODE_VISION) {
599
+ // vision 的 scan_files 是截图清单,不是可分析的 md。
600
+ // 先逐题材交给 LLM 识别,再把渲染出的标准 md 放进 allFiles。
601
+ const manifests = Array.isArray(receipt.vision_manifests) ? receipt.vision_manifests : [];
602
+ if (!manifests.length) {
603
+ failedRanks.push({ label: rankLabel, error: '采集回执里没有 vision_manifests' });
604
+ continue;
605
+ }
606
+ let visionOk = false;
607
+ for (const manifestPath of manifests) {
608
+ if (signal?.aborted) {
609
+ return notify(session, 'error', scan.notify({ type: 'cancelled' }));
610
+ }
611
+ tasks.progress(`LLM 视觉识别截图(准备中:${rankLabel})`);
612
+ const vr = await runVisionRecognition({
613
+ invocation,
614
+ tasks,
615
+ projectRoot,
616
+ manifestPath,
617
+ date: receipt.date || lastDate,
618
+ signal,
619
+ });
620
+ if (vr.aborted) {
621
+ return notify(session, 'error', scan.notify({ type: 'cancelled' }));
622
+ }
623
+ if (vr.unsupported) {
624
+ return notify(session, 'error', scan.notify({
625
+ type: 'vision_unsupported',
626
+ err: vr.error,
627
+ }));
628
+ }
629
+ if (!vr.ok) {
630
+ failedRanks.push({ label: rankLabel, error: vr.error });
631
+ continue;
632
+ }
633
+ visionOk = true;
634
+ allFiles.push(vr.file);
635
+ if (Array.isArray(vr.failed) && vr.failed.length) {
636
+ failedRanks.push({
637
+ label: rankLabel,
638
+ error: '部分题材视觉识别失败:'
639
+ + vr.failed.map((f) => `${f.name}(${f.error})`).join(';'),
640
+ });
641
+ }
642
+ }
643
+ if (visionOk) succeededRankIds.push(rankId);
644
+ } else {
645
+ allFiles.push(...files);
646
+ if (files.length > 0) succeededRankIds.push(rankId);
647
+ }
363
648
  // scraper 内部的部分失败(番茄某个题材采失败)必须透出:
364
649
  // run-scan.js 对这种情况仍报 ok:true(只要有文件),
365
650
  // 若这里不读 partialReasons,失败信息会在插件层被整个吞掉,
@@ -598,6 +883,10 @@ export async function apply(ctx) {
598
883
  preWrite = null;
599
884
  }
600
885
 
886
+ const analysisTaskIndex = scanMode === SCAN_MODE_VISION ? 3 : 2;
887
+ tasks.advance(analysisTaskIndex);
888
+ tasks.progress('LLM 分析并写入报告');
889
+
601
890
  const follow = await llmFollowup(invocation, scan.llmAnalysisPrompt({
602
891
  platform,
603
892
  rankLists: effectiveRankLabels ? effectiveRankLabels.split('、') : ['全选'],
@@ -619,6 +908,9 @@ export async function apply(ctx) {
619
908
  err: (follow && follow.error) || '提示词投递失败'
620
909
  }));
621
910
  }
911
+ // 新 turn/start 会清空 todo 列表;watcher 在 turn 开始/结束时
912
+ // 把命令自己的进度写回去。
913
+ tasks.watchTurns(invocation);
622
914
 
623
915
  // llmFollowup 只代表“消息已入队”,模型是异步跑的。
624
916
  // 必须等这一轮真正结束再复核;否则会在模型还没开始写的时候
@@ -645,6 +937,9 @@ export async function apply(ctx) {
645
937
  }
646
938
  }
647
939
 
940
+ tasks.advance(analysisTaskIndex + 1);
941
+ tasks.progress('校验报告写入');
942
+
648
943
  // ── 复核:这一次到底写进去没有、写对没有 ──────────────────
649
944
  // 提示词里唯一的写入路径是 append-block.js(它自己会校验),
650
945
  // 但模型**可能绕过脚本**。所以插件自己再查一遍:
@@ -704,5 +999,5 @@ export async function apply(ctx) {
704
999
  const dirtText = dirt ? '\n\n' + scan.notify({ type: 'dirty_file', dirt }) : '';
705
1000
  return notify(session, 'success', doneText + dirtText);
706
1001
  }
707
- });
1002
+ }, (invocation) => scanTaskTitles(invocation.rawInput));
708
1003
  }
@@ -510,6 +510,9 @@ async function runScraper(platform, rank, outDir, scanMode) {
510
510
  return {
511
511
  ok: true,
512
512
  writtenFiles,
513
+ // vision 模式的产物是截图清单,不是最终 md;插件拿到这些路径后
514
+ // 派给 LLM 识别,再把标准 md 写回 扫榜结果/。
515
+ visionManifests: Array.isArray(receipt.vision_manifests) ? receipt.vision_manifests : [],
513
516
  failed: receipt.failed || 0,
514
517
  // 成功采集到的品类数(番茄 receipt 提供)。没有这个字段的平台
515
518
  // (起点/晋江/七猫)返回 undefined —— 调用方按"未知"处理,不拦。
@@ -610,6 +613,16 @@ async function main() {
610
613
  throw new Error(`scraper 返回了非法输出文件: ${f}`);
611
614
  }
612
615
  }
616
+ // vision 清单是插件接下来要读的输入,和 scan_files 一样按不可信路径处理:
617
+ // 必须在 扫榜结果/ 内、真实存在、且是文件。
618
+ for (const f of (Array.isArray(r.visionManifests) ? r.visionManifests : [])) {
619
+ let realFile = '';
620
+ try { realFile = realpathSync(f); } catch { /* 不存在 */ }
621
+ if (!realFile || !isPathInside(scanDirReal, realFile)
622
+ || !existsSync(realFile) || !statSync(realFile).isFile()) {
623
+ throw new Error(`scraper 返回了非法的视觉清单: ${f}`);
624
+ }
625
+ }
613
626
  failed = r.failed || 0;
614
627
  if (Array.isArray(r.partialReasons)) partialReasons.push(...r.partialReasons);
615
628
 
@@ -644,6 +657,7 @@ async function main() {
644
657
  rank,
645
658
  date: today,
646
659
  scan_files: scanFiles,
660
+ vision_manifests: Array.isArray(r.visionManifests) ? r.visionManifests : [],
647
661
  topic_decision: join(scanDir, `topic_decision_${today}.md`),
648
662
  written: scanFiles.length,
649
663
  failed,