@cloud411716/fancy-webnovel 4.11.2 → 4.12.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.
@@ -144,7 +144,14 @@ FANCY_DOUYIN_SUBAGENTS=0 # 关闭子 Agent,回退单 Agent 串行
144
144
 
145
145
  子 Agent 不操作 Chrome,不修改 `crawled.json`,不运行 `import.js`,也不直接写素材数据库;数据库导入和采集状态只由父进程串行处理,避免并发覆盖。
146
146
 
147
- 子 Agent 是独立的新会话,不继承父 Agent 当前对话。因此 `.tmp` 临时文件规则和“不要删除测试文件/不要执行 rm”的约束会直接写进子 Agent 任务提示,而不是依赖父对话。
147
+ 子 Agent 是独立的新会话,不继承父 Agent 当前对话。因此 `.tmp` 临时文件规则、完整分析提示词和“不要删除测试文件/不要执行 rm”的约束都会直接写进子 Agent 任务提示,而不是依赖父对话。
148
+
149
+ 有子 Agent 服务时,视觉能力自检和视频前 5 秒相关性判断也会交给子 Agent:
150
+
151
+ - 能力自检子 Agent 写 `capabilities.json`
152
+ - 视频子 Agent 先读前 5 秒关键帧:无关就只写 skip,有关再继续完整分析
153
+ - 主对话只保留采集进度和结果,不再出现这两段分析提示词
154
+ - 没有子 Agent 服务时才回退到父 Agent
148
155
 
149
156
  ## 素材格式
150
157
 
@@ -91,9 +91,14 @@ DEFINE INDEX IF NOT EXISTS douyin_job_analysis_status ON douyin_job FIELDS analy
91
91
  DEFINE INDEX IF NOT EXISTS douyin_job_import_status ON douyin_job FIELDS import_status;
92
92
  DEFINE INDEX IF NOT EXISTS douyin_job_updated_at ON douyin_job FIELDS updated_at;
93
93
 
94
+ -- 允许工作区数据库用户读写任务表;schema 本身仍由 root 创建。
95
+ ALTER TABLE douyin_job PERMISSIONS FOR select, create, update, delete FULL;
96
+
94
97
  -- 迁移/维护标记(例如 crawled.json 是否已导入任务表)
95
98
  DEFINE TABLE IF NOT EXISTS douyin_meta SCHEMAFULL;
96
99
  DEFINE FIELD OVERWRITE meta_key ON douyin_meta TYPE string;
97
100
  DEFINE FIELD OVERWRITE meta_value ON douyin_meta TYPE string;
98
101
  DEFINE FIELD OVERWRITE updated_at ON douyin_meta TYPE datetime VALUE time::now();
99
102
  DEFINE INDEX IF NOT EXISTS douyin_meta_key_unique ON douyin_meta FIELDS meta_key UNIQUE;
103
+
104
+ ALTER TABLE douyin_meta PERMISSIONS FOR select, create, update, delete FULL;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.11.2",
3
+ "version": "4.12.0",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -416,7 +416,59 @@ export function readRelevanceMarker(file) {
416
416
  return null;
417
417
  }
418
418
 
419
- async function detectCapabilities(ctx, invocation, session, taskList, root, runDir) {
419
+ async function detectCapabilitiesWithSubagent(subagents, invocation, taskList, runDir, signal) {
420
+ const file = path.join(runDir, 'capabilities.json');
421
+ taskList.watchTurns(invocation);
422
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
423
+ try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
424
+ let activation;
425
+ try {
426
+ activation = await subagents.startActivation({
427
+ provider: 'spawn',
428
+ label: 'fancy-douyin capability probe',
429
+ parent: invocation.agent,
430
+ prompt: [{ type: 'text', text: capabilityPrompt({ capabilityFile: file }) }],
431
+ signal,
432
+ delivery: 'caller',
433
+ });
434
+ } catch (err) {
435
+ return { ok: false, error: '能力自检子 Agent 启动失败:' + (err && err.message ? err.message : String(err)) };
436
+ }
437
+ let timer = null;
438
+ try {
439
+ await Promise.race([
440
+ activation.result,
441
+ new Promise((_, reject) => {
442
+ timer = setTimeout(() => reject(new Error('能力自检子 Agent 超时')), CAPABILITY_TIMEOUT_MS);
443
+ if (timer && typeof timer.unref === 'function') timer.unref();
444
+ }),
445
+ ]);
446
+ } catch (err) {
447
+ if (signal && signal.aborted) return { ok: false, aborted: true, error: '用户中断' };
448
+ return { ok: false, error: '能力自检子 Agent 执行失败:' + (err && err.message ? err.message : String(err)) };
449
+ } finally {
450
+ if (timer) clearTimeout(timer);
451
+ try { await activation.dispose(); } catch { /* best effort */ }
452
+ }
453
+ let text = '';
454
+ try { text = fs.readFileSync(file, 'utf8'); } catch { /* retry */ }
455
+ const parsed = parseCapabilityResult(text);
456
+ if (parsed) return { ok: true, ...parsed };
457
+ }
458
+ return { ok: false, error: '能力自检子 Agent 没有返回可解析结果' };
459
+ }
460
+
461
+ async function detectCapabilities(ctx, invocation, session, taskList, root, runDir, options = {}) {
462
+ if (options.subagentRuntime) {
463
+ return detectCapabilitiesWithSubagent(
464
+ options.subagentRuntime,
465
+ invocation,
466
+ taskList,
467
+ runDir,
468
+ options.signal,
469
+ );
470
+ }
471
+
420
472
  const file = path.join(runDir, 'capabilities.json');
421
473
  try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
422
474
  taskList.watchTurns(invocation);
@@ -687,18 +739,48 @@ function analysisPromptForJob(job, root, materialTools) {
687
739
  });
688
740
  }
689
741
 
690
- function subagentTaskPrompt(job, root, materialTools) {
691
- return [
742
+ function first5sFrames(video) {
743
+ if (video && Array.isArray(video.first5s) && video.first5s.length) return video.first5s;
744
+ const frames = video && Array.isArray(video.frames) ? video.frames : [];
745
+ const early = frames.filter((frame) => Number(frame.time) < 5);
746
+ return early.length ? early : frames.slice(0, 1);
747
+ }
748
+
749
+ function first5sFrameText(video) {
750
+ return first5sFrames(video)
751
+ .map((frame) => `- \`${frame.file}\`(第 ${frame.time} 秒)`)
752
+ .join('\n');
753
+ }
754
+
755
+ export function subagentTaskPrompt(job, root, materialTools) {
756
+ const lines = [
692
757
  '你是 fancy-douyin 的分析子 Agent,只处理下面这一篇作品。',
693
758
  '不要扫描账号,不要启动或操作 Chrome,不要修改 crawled.json,不要运行 import.js 或直接写素材数据库。',
694
759
  '只读取给定文件,按提示词提取素材,写入目标 JSONL,运行 validate.js 后结束。',
695
760
  '如果需要创建测试文件,放在当前项目的 `.tmp` 目录下(绝对路径:`' + path.join(root, '.tmp') + '`),并且测试后不需要删除测试文件。',
696
761
  '禁止执行 rm、rmdir、find -delete、git clean 等删除命令,也不要删除已有文件。',
697
762
  '',
698
- '以下是本作品的完整分析提示词,必须逐条遵守(包括提取规则、字段要求、清单逐条规则、同风格扩写和校验命令):',
699
- '',
700
- analysisPromptForJob(job, root, materialTools),
701
- ].join('\n');
763
+ ];
764
+ if (job.type === 'video' && job.relevanceGate) {
765
+ lines.push('## 第一步:前 5 秒相关性判断');
766
+ lines.push('');
767
+ lines.push('只根据下面这些前 5 秒关键帧判断内容是否与网文小说创作素材、灵感、设定、写作技巧有关:');
768
+ lines.push('');
769
+ lines.push(first5sFrameText(job.video) || '(没有前 5 秒关键帧)');
770
+ lines.push('');
771
+ lines.push('如果无关:不要继续分析,只把下面的 skip 标记写进目标文件,然后结束:');
772
+ lines.push('```json');
773
+ lines.push('{"skip": true, "reason": "前 5 秒与网文创作无关:<一句话原因>"}');
774
+ lines.push('```');
775
+ lines.push('如果有关:继续执行第二步的完整视频分析。');
776
+ lines.push('');
777
+ lines.push('## 第二步:完整视频分析');
778
+ lines.push('');
779
+ }
780
+ lines.push('以下是本作品的完整分析提示词,必须逐条遵守(包括提取规则、字段要求、清单逐条规则、同风格扩写和校验命令):');
781
+ lines.push('');
782
+ lines.push(analysisPromptForJob(job, root, materialTools));
783
+ return lines.join('\n');
702
784
  }
703
785
 
704
786
  async function runSubagentAnalysisJob({
@@ -826,11 +908,24 @@ async function runCrawl(ctx, invocation, session, taskList) {
826
908
  fs.mkdirSync(runDir, { recursive: true });
827
909
  fs.mkdirSync(paths.jobs, { recursive: true });
828
910
 
911
+ const subagentRuntime = getSubagentRuntime(ctx);
912
+ const subagentWorkers = subagentRuntime ? subagentWorkerCount() : 0;
913
+ const useSubagents = Boolean(subagentRuntime && subagentWorkers > 0);
914
+ const abortController = new AbortController();
915
+ if (invocation.signal) {
916
+ if (invocation.signal.aborted) abortController.abort();
917
+ else invocation.signal.addEventListener('abort', () => abortController.abort(), { once: true });
918
+ }
919
+ const jobSignal = abortController.signal;
920
+
829
921
  // 先做能力自检:如果模型既不能看图也不能看视频,直接退出,
830
922
  // 不启动 Chrome,也不扫描账号。
831
923
  taskList.advance(1);
832
924
  taskList.progress('LLM 能力自检(图片 / 视频)');
833
- const capabilities = await detectCapabilities(ctx, invocation, session, taskList, root, runDir);
925
+ const capabilities = await detectCapabilities(ctx, invocation, session, taskList, root, runDir, {
926
+ subagentRuntime,
927
+ signal: jobSignal,
928
+ });
834
929
  if (!capabilities.ok) {
835
930
  return notify(session, 'error', '❌ LLM 能力自检失败:' + capabilities.error);
836
931
  }
@@ -875,16 +970,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
875
970
  const failures = [];
876
971
  const jobs = [];
877
972
  const queued = new Set();
878
- const subagentRuntime = getSubagentRuntime(ctx);
879
- const subagentWorkers = subagentRuntime ? subagentWorkerCount() : 0;
880
- const useSubagents = Boolean(subagentRuntime && subagentWorkers > 0);
881
973
  const withStateLock = createSerialLock();
882
- const abortController = new AbortController();
883
- if (invocation.signal) {
884
- if (invocation.signal.aborted) abortController.abort();
885
- else invocation.signal.addEventListener('abort', () => abortController.abort(), { once: true });
886
- }
887
- const jobSignal = abortController.signal;
888
974
  const markJobFailedLocked = async (job, reason, { crawl = false } = {}) => {
889
975
  if (!job || !job.id) return;
890
976
  markCrawled(root, job.id, {
@@ -967,9 +1053,15 @@ async function runCrawl(ctx, invocation, session, taskList) {
967
1053
  let skippedMaterials = 0;
968
1054
  let aborted = false;
969
1055
 
970
- const progressText = () => queue
971
- ? `分析素材(子 Agent 并行:${queueStats.finished}/${queueStats.queued},并发 ${subagentWorkers})`
972
- : `分析素材(${queueStats.finished}/${jobs.length})`;
1056
+ const progressText = () => {
1057
+ if (taskList.index <= 3) {
1058
+ return `采集作品(已入队 ${queueStats.queued},已分析 ${queueStats.finished})`;
1059
+ }
1060
+ if (queue) {
1061
+ return `分析素材(子 Agent 并行:${queueStats.finished}/${queueStats.queued},并发 ${subagentWorkers})`;
1062
+ }
1063
+ return `分析素材(${queueStats.finished}/${jobs.length})`;
1064
+ };
973
1065
 
974
1066
  const jobRecord = (job, extra = {}) => ({
975
1067
  account_url: job.accountUrl,
@@ -1066,14 +1158,13 @@ async function runCrawl(ctx, invocation, session, taskList) {
1066
1158
  reason: '',
1067
1159
  });
1068
1160
  }
1161
+ queueStats.queued += 1;
1069
1162
  if (queue) {
1070
- queueStats.queued += 1;
1071
- if (taskList.index < 4) taskList.advance(4);
1072
1163
  queue.push(job);
1073
- taskList.progress(progressText());
1074
1164
  } else {
1075
1165
  jobs.push(job);
1076
1166
  }
1167
+ taskList.progress(progressText());
1077
1168
  };
1078
1169
 
1079
1170
  const runWorker = async () => {
@@ -1431,35 +1522,43 @@ async function runCrawl(ctx, invocation, session, taskList) {
1431
1522
 
1432
1523
  processedWorks += 1;
1433
1524
  video.account_url = account.url;
1434
- if (taskList.index < 4) taskList.advance(4);
1435
- taskList.progress(`分析素材(视频前 5 秒筛选:${video.title || videoId})`);
1436
- const relevance = await analyzeVideoRelevance(ctx, invocation, session, {
1437
- root,
1438
- accountUrl: account.url,
1439
- video,
1440
- target,
1441
- taskList,
1442
- });
1443
- if (!relevance.ok) {
1444
- failures.push({ id: videoId, url: card.href, reason: relevance.error });
1445
- if (relevance.aborted) { aborted = true; break outer; }
1446
- await markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
1447
- continue;
1448
- }
1449
- if (relevance.skip) {
1450
- skippedIrrelevant += 1;
1451
- await markJobSkipped({
1452
- id: videoId,
1453
- jobKey,
1525
+ let relevanceGate = false;
1526
+ if (!useSubagents) {
1527
+ if (taskList.index <= 3) {
1528
+ taskList.progress(`采集作品(视频前 5 秒筛选:${video.title || videoId})`);
1529
+ } else {
1530
+ taskList.progress(`分析素材(视频前 5 秒筛选:${video.title || videoId})`);
1531
+ }
1532
+ const relevance = await analyzeVideoRelevance(ctx, invocation, session, {
1533
+ root,
1454
1534
  accountUrl: account.url,
1455
- url: video.url || card.href,
1456
- title: video.title || card.text || '',
1457
- type: 'video',
1458
- duration: video.duration,
1459
- dir: videoDir,
1460
- card,
1461
- }, relevance.reason || '前 5 秒与网文创作无关');
1462
- continue;
1535
+ video,
1536
+ target,
1537
+ taskList,
1538
+ });
1539
+ if (!relevance.ok) {
1540
+ failures.push({ id: videoId, url: card.href, reason: relevance.error });
1541
+ if (relevance.aborted) { aborted = true; break outer; }
1542
+ await markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
1543
+ continue;
1544
+ }
1545
+ if (relevance.skip) {
1546
+ skippedIrrelevant += 1;
1547
+ await markJobSkipped({
1548
+ id: videoId,
1549
+ jobKey,
1550
+ accountUrl: account.url,
1551
+ url: video.url || card.href,
1552
+ title: video.title || card.text || '',
1553
+ type: 'video',
1554
+ duration: video.duration,
1555
+ dir: videoDir,
1556
+ card,
1557
+ }, relevance.reason || '前 5 秒与网文创作无关');
1558
+ continue;
1559
+ }
1560
+ } else {
1561
+ relevanceGate = true;
1463
1562
  }
1464
1563
 
1465
1564
  await enqueueJob({
@@ -1472,6 +1571,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
1472
1571
  dir: videoDir,
1473
1572
  dirRel,
1474
1573
  video,
1574
+ relevanceGate,
1475
1575
  target,
1476
1576
  title: video.title,
1477
1577
  duration: video.duration,
@@ -1600,6 +1700,10 @@ async function runCrawl(ctx, invocation, session, taskList) {
1600
1700
  }
1601
1701
 
1602
1702
  if (queue) {
1703
+ if (taskList.index < 4) {
1704
+ taskList.advance(4);
1705
+ taskList.progress(progressText());
1706
+ }
1603
1707
  queue.close();
1604
1708
  await Promise.all(workerPromises);
1605
1709
  } else if (jobs.length) {
@@ -1705,7 +1809,7 @@ function douyinTaskTitles(invocation) {
1705
1809
  '检查账号与素材库',
1706
1810
  'LLM 能力自检(图片 / 视频)',
1707
1811
  '扫描账号主页',
1708
- '采集图文 / 视频 / 文章作品',
1812
+ '采集作品',
1709
1813
  '分析素材',
1710
1814
  '写入素材库',
1711
1815
  ];
@@ -32,6 +32,7 @@ export function helpText() {
32
32
  - 扫描一个账号后,未处理作品会边采集边交给子 Agent 分析,不再等所有账号采集完。
33
33
  - 父进程负责采集、校验、入库和任务状态;子 Agent 只写各作品的 materials.jsonl。
34
34
  - 作品任务状态记录在素材库的 douyin_job 表;中途重启会复用稳定任务目录,已导入/已跳过的作品不会重采。
35
+ - 有子 Agent 时,视觉能力自检和视频前 5 秒相关性判断也由子 Agent 完成,主对话不再出现这些分析提示词。
35
36
  - 子 Agent 并发数由 FANCY_DOUYIN_SUBAGENTS 控制(默认 3,0 关闭);DSH 没有 subagent 服务或 spawn provider 时自动回退单 Agent 串行。
36
37
  - 视频作品先判断时长:超过 1 分钟直接跳过;不超过 1 分钟的先看前 5 秒,
37
38
  与网文创作无关就跳过,有关才继续分析关键帧。