@cloud411716/fancy-webnovel 4.9.0 → 4.10.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.
@@ -28,6 +28,8 @@ https://www.douyin.com/user/MS4wLjABAAAA...
28
28
 
29
29
  单篇作品地址、视频地址和短链会被拒绝。
30
30
 
31
+ `list` 会显示扫描时记录的账号名、抖音号、主页地址,以及 `crawled.json` 中该账号已处理的作品数量。
32
+
31
33
  ## 无参数运行
32
34
 
33
35
  ```text
@@ -88,7 +90,7 @@ cookies 会额外镜像到:
88
90
 
89
91
  ```text
90
92
  <工作区>/.fancy/douyin/
91
- ├── accounts.json # 账号主页记录
93
+ ├── accounts.json # 账号主页记录(含账号名、抖音号、sec_uid、最近扫描时间)
92
94
  ├── crawled.json # 已成功入库、确认无关或失败跳过的作品 ID
93
95
  ├── login-state.json # cookies 镜像(0600)
94
96
  ├── chrome-profile/ # Chrome 登录态
@@ -110,6 +112,27 @@ cookies 会额外镜像到:
110
112
  └── package.json
111
113
  ```
112
114
 
115
+ ## 子 Agent 并行分析
116
+
117
+ 采集阶段仍然由父进程串行完成:扫描账号、打开作品、下载图片/视频帧/文章正文。采集完成后,已准备好的作品会分发给 DSH 子 Agent 并行分析。
118
+
119
+ ```text
120
+ 父进程:扫描 → 采集 → 生成任务目录
121
+ 子 Agent:读取任务目录 → 提取素材 → 写 materials.jsonl → 运行 validate.js
122
+ 父进程:统一复验 → 导入数据库 → 写 crawled.json
123
+ ```
124
+
125
+ 并发数:
126
+
127
+ ```bash
128
+ FANCY_DOUYIN_SUBAGENTS=3 # 默认 3,范围 1–6
129
+ FANCY_DOUYIN_SUBAGENTS=0 # 关闭子 Agent,回退单 Agent 串行
130
+ ```
131
+
132
+ 要求 DSH 挂载了 subagent 服务和 `spawn` provider。没有子 Agent 服务、provider 不存在或并发数为 0 时,会自动回退到原来的单 Agent 流程。
133
+
134
+ 子 Agent 不操作 Chrome,不修改 `crawled.json`,不运行 `import.js`,也不直接写素材数据库;数据库导入和采集状态只由父进程串行处理,避免并发覆盖。
135
+
113
136
  ## 素材格式
114
137
 
115
138
  每篇作品的 LLM 输出写到:
@@ -127,7 +127,7 @@ namespace: fancy
127
127
  跳过,不超过 1 分钟的先看前 5 秒,与网文创作无关也跳过;文章按标题层级拆成原子
128
128
  设定。内容交给 LLM 提取素材,按 material JSONL 写入数据库,`source` 固定为
129
129
  `other`。已成功入库、确认无关或作品级失败的作品记录在工作区
130
- `/.fancy/douyin/crawled.json`,后续跳过。
130
+ `/.fancy/douyin/crawled.json`,后续跳过。采集完成后可由 DSH 子 Agent 并行分析,`FANCY_DOUYIN_SUBAGENTS` 控制并发数(默认 3,0 关闭);没有 subagent 服务时自动回退单 Agent。
131
131
 
132
132
  登录态保存在工作区 `/.fancy/douyin/chrome-profile/`,并镜像 cookies 到
133
133
  `login-state.json`。首次需要登录时使用有头 Chrome,登录态有效后后续运行自动
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.9.0",
3
+ "version": "4.10.0",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -31,8 +31,10 @@ import {
31
31
  readAccounts,
32
32
  readCrawled,
33
33
  removeAccount,
34
+ updateAccountProfile,
34
35
  } from './state.js';
35
36
  import { analysisPrompt, articlePrompt, capabilityPrompt, helpText, loginQuestion, summaryText, videoAnalysisPrompt, videoRelevancePrompt } from './templates.js';
37
+ import { createSerialLock, getSubagentRuntime, runJobPool, subagentWorkerCount } from './subagents.js';
36
38
 
37
39
  export const inject = ['commands', 'userQuestions'];
38
40
 
@@ -455,6 +457,36 @@ async function detectCapabilities(ctx, invocation, session, taskList, root, runD
455
457
  return { ok: false, error: 'LLM 没有返回可解析的能力自检结果' };
456
458
  }
457
459
 
460
+ async function finalizeMaterialFile({ root, target, title, materialTools }) {
461
+ const skip = readSkipMarker(target);
462
+ if (skip) {
463
+ return {
464
+ ok: true,
465
+ skipped: true,
466
+ reason: skip.reason,
467
+ inserted: 0,
468
+ skipped: 0,
469
+ };
470
+ }
471
+ try {
472
+ normalizeOtherFile(target);
473
+ } catch (err) {
474
+ return { ok: false, detail: err && err.message ? err.message : String(err) };
475
+ }
476
+ const checked = await validateOtherFile(target, materialTools.validateScript);
477
+ if (!checked.ok) return { ok: false, detail: checked.detail };
478
+ const kindProblem = kindLanguageProblem(target);
479
+ if (kindProblem) return { ok: false, detail: kindProblem };
480
+ const coverage = coverageProblem(target, title);
481
+ if (coverage) return { ok: false, detail: coverage };
482
+ try {
483
+ const result = await importOtherMaterials(root, target);
484
+ return { ok: true, ...result };
485
+ } catch (err) {
486
+ return { ok: false, error: '导入数据库失败:' + (err && err.message ? err.message : String(err)) };
487
+ }
488
+ }
489
+
458
490
  async function analyzeMaterials(ctx, invocation, session, {
459
491
  root, prompt, target, title, materialTools, taskList,
460
492
  }) {
@@ -497,44 +529,10 @@ async function analyzeMaterials(ctx, invocation, session, {
497
529
  continue;
498
530
  }
499
531
 
500
- const skip = readSkipMarker(target);
501
- if (skip) {
502
- return {
503
- ok: true,
504
- skipped: true,
505
- reason: skip.reason,
506
- inserted: 0,
507
- skipped: 0,
508
- };
509
- }
510
-
511
- try {
512
- normalizeOtherFile(target);
513
- } catch (err) {
514
- detail = err && err.message ? err.message : String(err);
515
- continue;
516
- }
517
- const checked = await validateOtherFile(target, materialTools.validateScript);
518
- if (!checked.ok) {
519
- detail = checked.detail;
520
- continue;
521
- }
522
- const kindProblem = kindLanguageProblem(target);
523
- if (kindProblem) {
524
- detail = kindProblem;
525
- continue;
526
- }
527
- const coverage = coverageProblem(target, title);
528
- if (coverage) {
529
- detail = coverage;
530
- continue;
531
- }
532
- try {
533
- const result = await importOtherMaterials(root, target);
534
- return { ok: true, ...result };
535
- } catch (err) {
536
- return { ok: false, error: '导入数据库失败:' + (err && err.message ? err.message : String(err)) };
537
- }
532
+ const finalized = await finalizeMaterialFile({ root, target, title, materialTools });
533
+ if (finalized.ok) return finalized;
534
+ if (finalized.error) return finalized;
535
+ detail = finalized.detail;
538
536
  }
539
537
  return { ok: false, error: '素材没有通过校验:' + detail };
540
538
  }
@@ -652,6 +650,125 @@ async function analyzeArticle(ctx, invocation, session, {
652
650
  });
653
651
  }
654
652
 
653
+ function analysisPromptForJob(job, root, materialTools) {
654
+ if (job.type === 'note') {
655
+ return analysisPrompt({
656
+ accountUrl: job.accountUrl,
657
+ note: job.note,
658
+ screenshots: job.screenshots,
659
+ targetFile: job.target,
660
+ workspace: root,
661
+ queryScript: materialTools.queryScript,
662
+ validateScript: materialTools.validateScript,
663
+ });
664
+ }
665
+ if (job.type === 'video') {
666
+ return videoAnalysisPrompt({
667
+ accountUrl: job.accountUrl,
668
+ video: job.video,
669
+ frames: job.video.frames || [],
670
+ targetFile: job.target,
671
+ workspace: root,
672
+ queryScript: materialTools.queryScript,
673
+ validateScript: materialTools.validateScript,
674
+ });
675
+ }
676
+ return articlePrompt({
677
+ accountUrl: job.accountUrl,
678
+ article: job.article,
679
+ targetFile: job.target,
680
+ workspace: root,
681
+ queryScript: materialTools.queryScript,
682
+ validateScript: materialTools.validateScript,
683
+ });
684
+ }
685
+
686
+ function subagentTaskPrompt(job, root, materialTools) {
687
+ return [
688
+ '你是 fancy-douyin 的分析子 Agent,只处理下面这一篇作品。',
689
+ '不要扫描账号,不要启动或操作 Chrome,不要修改 crawled.json,不要运行 import.js 或直接写素材数据库。',
690
+ '只读取给定文件,按提示词提取素材,写入目标 JSONL,运行 validate.js 后结束。',
691
+ '',
692
+ analysisPromptForJob(job, root, materialTools),
693
+ ].join('\n');
694
+ }
695
+
696
+ async function runSubagentAnalysisJob({
697
+ subagents, provider, invocation, job, root, materialTools, signal,
698
+ }) {
699
+ const prompt = subagentTaskPrompt(job, root, materialTools);
700
+ let activation;
701
+ try {
702
+ activation = await subagents.startActivation({
703
+ provider,
704
+ label: 'fancy-douyin ' + job.type + ' ' + job.id,
705
+ parent: invocation.agent,
706
+ prompt: [{ type: 'text', text: prompt }],
707
+ signal,
708
+ delivery: 'caller',
709
+ });
710
+ } catch (err) {
711
+ return { ok: false, error: '子 Agent 启动失败:' + (err && err.message ? err.message : String(err)) };
712
+ }
713
+
714
+ let result;
715
+ let timer = null;
716
+ try {
717
+ result = await Promise.race([
718
+ activation.result,
719
+ new Promise((_, reject) => {
720
+ timer = setTimeout(() => reject(new Error('子 Agent 分析超时')), ANALYSIS_TIMEOUT_MS);
721
+ if (timer && typeof timer.unref === 'function') timer.unref();
722
+ }),
723
+ ]);
724
+ } catch (err) {
725
+ return { ok: false, error: '子 Agent 执行失败:' + (err && err.message ? err.message : String(err)) };
726
+ } finally {
727
+ if (timer) clearTimeout(timer);
728
+ try { await activation.dispose(); } catch { /* best effort */ }
729
+ }
730
+ if (!fs.existsSync(job.target)) {
731
+ const stop = result && result.stopReason ? '(' + result.stopReason + ')' : '';
732
+ return { ok: false, error: '子 Agent 没有写入目标文件' + stop };
733
+ }
734
+ // 文件已经写出,由父进程在串行锁内统一校验、导入和写 crawled.json。
735
+ return { ok: true, needsFinalize: true };
736
+ }
737
+
738
+ async function runLocalAnalysisJob(ctx, invocation, session, job, {
739
+ root, materialTools, paths, taskList,
740
+ }) {
741
+ if (job.type === 'note') {
742
+ return analyzeNote(ctx, invocation, session, {
743
+ root,
744
+ note: job.note,
745
+ screenshots: job.screenshots,
746
+ target: job.target,
747
+ materialTools,
748
+ paths,
749
+ taskList,
750
+ });
751
+ }
752
+ if (job.type === 'video') {
753
+ return analyzeVideo(ctx, invocation, session, {
754
+ root,
755
+ accountUrl: job.accountUrl,
756
+ video: job.video,
757
+ target: job.target,
758
+ materialTools,
759
+ taskList,
760
+ });
761
+ }
762
+ return analyzeArticle(ctx, invocation, session, {
763
+ root,
764
+ accountUrl: job.accountUrl,
765
+ article: job.article,
766
+ target: job.target,
767
+ materialTools,
768
+ taskList,
769
+ });
770
+ }
771
+
655
772
  async function runCrawl(ctx, invocation, session, taskList) {
656
773
  const root = workspaceOf(session);
657
774
  const paths = ensureDouyinDir(root);
@@ -698,6 +815,41 @@ async function runCrawl(ctx, invocation, session, taskList) {
698
815
  try {
699
816
  const crawled = readCrawled(root);
700
817
  const failures = [];
818
+ const jobs = [];
819
+ const queued = new Set();
820
+ const subagentRuntime = getSubagentRuntime(ctx);
821
+ const subagentWorkers = subagentRuntime ? subagentWorkerCount() : 0;
822
+ const useSubagents = Boolean(subagentRuntime && subagentWorkers > 0);
823
+ const withStateLock = createSerialLock();
824
+ const abortController = new AbortController();
825
+ if (invocation.signal) {
826
+ if (invocation.signal.aborted) abortController.abort();
827
+ else invocation.signal.addEventListener('abort', () => abortController.abort(), { once: true });
828
+ }
829
+ const jobSignal = abortController.signal;
830
+ const markJobFailed = (job, reason) => {
831
+ if (!job || !job.id) return;
832
+ markCrawled(root, job.id, {
833
+ account_url: job.accountUrl,
834
+ url: job.url || (job.card && job.card.href) || '',
835
+ title: job.title || (job.card && job.card.text) || '',
836
+ type: job.type,
837
+ duration: job.duration,
838
+ screenshots: job.type === 'note' && Array.isArray(job.screenshots)
839
+ ? job.screenshots.map((shot) => shot.file)
840
+ : undefined,
841
+ body_file: job.article && job.article.body_file,
842
+ reading_time: job.article && job.article.reading_time,
843
+ body_length: job.article && job.article.body_length,
844
+ dir: job.dir,
845
+ inserted: 0,
846
+ skipped: 0,
847
+ skip: true,
848
+ failed: true,
849
+ reason,
850
+ });
851
+ crawled[job.id] = true;
852
+ };
701
853
  let scannedAccounts = 0;
702
854
  let foundNotes = 0;
703
855
  let foundVideos = 0;
@@ -752,6 +904,9 @@ async function runCrawl(ctx, invocation, session, taskList) {
752
904
  }
753
905
 
754
906
  scannedAccounts += 1;
907
+ if (scan.json.profile) {
908
+ updateAccountProfile(root, account.url, scan.json.profile);
909
+ }
755
910
  const notes = Array.isArray(scan.json.notes) ? scan.json.notes : [];
756
911
  const videos = Array.isArray(scan.json.videos) ? scan.json.videos : [];
757
912
  const articles = Array.isArray(scan.json.articles) ? scan.json.articles : [];
@@ -768,7 +923,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
768
923
  }
769
924
  const noteId = noteIdFromUrl(card.href);
770
925
  if (!noteId) continue;
771
- if (crawled[noteId]) {
926
+ if (crawled[noteId] || queued.has(noteId)) {
772
927
  skippedNotes += 1;
773
928
  continue;
774
929
  }
@@ -799,53 +954,19 @@ async function runCrawl(ctx, invocation, session, taskList) {
799
954
  processedWorks += 1;
800
955
  note.account_url = account.url;
801
956
  const target = path.join(noteDir, 'materials.jsonl');
802
- taskList.advance(4);
803
- taskList.progress(`LLM 整理图文素材(${note.title || noteId})`);
804
- const analyzed = await analyzeNote(ctx, invocation, session, {
805
- root,
957
+ jobs.push({
958
+ type: 'note',
959
+ id: noteId,
960
+ card,
961
+ accountUrl: account.url,
962
+ url: note.url || card.href,
963
+ dir: noteDir,
806
964
  note,
807
965
  screenshots: note.screenshots,
808
966
  target,
809
- materialTools,
810
- paths,
811
- taskList,
967
+ title: note.title,
812
968
  });
813
- if (!analyzed.ok) {
814
- failures.push({ id: noteId, url: card.href, reason: analyzed.error });
815
- if (analyzed.aborted) { aborted = true; break outer; }
816
- if (analyzed.fatal) break outer;
817
- markFailed(noteId, card, { type: 'note', dir: noteDir, title: note.title }, analyzed.error);
818
- continue;
819
- }
820
- if (analyzed.skipped) {
821
- skippedIrrelevant += 1;
822
- markCrawled(root, noteId, {
823
- account_url: account.url,
824
- url: note.url || card.href,
825
- title: note.title || card.text || '',
826
- type: 'note',
827
- screenshots: note.screenshots.map((shot) => shot.file),
828
- dir: noteDir,
829
- inserted: 0,
830
- skipped: 0,
831
- skip: true,
832
- reason: analyzed.reason || '与网文创作无关',
833
- });
834
- } else {
835
- inserted += analyzed.inserted;
836
- skippedMaterials += analyzed.skipped;
837
- markCrawled(root, noteId, {
838
- account_url: account.url,
839
- url: note.url || card.href,
840
- title: note.title || card.text || '',
841
- type: 'note',
842
- screenshots: note.screenshots.map((shot) => shot.file),
843
- dir: noteDir,
844
- inserted: analyzed.inserted,
845
- skipped: analyzed.skipped,
846
- });
847
- }
848
- crawled[noteId] = true;
969
+ queued.add(noteId);
849
970
  if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
850
971
  const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
851
972
  await sleep(delay);
@@ -860,7 +981,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
860
981
  }
861
982
  const videoId = noteIdFromUrl(card.href);
862
983
  if (!videoId) continue;
863
- if (crawled[videoId]) {
984
+ if (crawled[videoId] || queued.has(videoId)) {
864
985
  skippedNotes += 1;
865
986
  continue;
866
987
  }
@@ -943,51 +1064,19 @@ async function runCrawl(ctx, invocation, session, taskList) {
943
1064
  continue;
944
1065
  }
945
1066
 
946
- taskList.progress(`LLM 整理视频素材(${video.title || videoId})`);
947
- const analyzed = await analyzeVideo(ctx, invocation, session, {
948
- root,
1067
+ jobs.push({
1068
+ type: 'video',
1069
+ id: videoId,
1070
+ card,
949
1071
  accountUrl: account.url,
1072
+ url: video.url || card.href,
1073
+ dir: videoDir,
950
1074
  video,
951
1075
  target,
952
- materialTools,
953
- taskList,
1076
+ title: video.title,
1077
+ duration: video.duration,
954
1078
  });
955
- if (!analyzed.ok) {
956
- failures.push({ id: videoId, url: card.href, reason: analyzed.error });
957
- if (analyzed.aborted) { aborted = true; break outer; }
958
- if (analyzed.fatal) break outer;
959
- markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, analyzed.error);
960
- continue;
961
- }
962
- if (analyzed.skipped) {
963
- skippedIrrelevant += 1;
964
- markCrawled(root, videoId, {
965
- account_url: account.url,
966
- url: video.url || card.href,
967
- title: video.title || card.text || '',
968
- type: 'video',
969
- duration: video.duration,
970
- dir: videoDir,
971
- inserted: 0,
972
- skipped: 0,
973
- skip: true,
974
- reason: analyzed.reason || '与网文创作无关',
975
- });
976
- } else {
977
- inserted += analyzed.inserted;
978
- skippedMaterials += analyzed.skipped;
979
- markCrawled(root, videoId, {
980
- account_url: account.url,
981
- url: video.url || card.href,
982
- title: video.title || card.text || '',
983
- type: 'video',
984
- duration: video.duration,
985
- dir: videoDir,
986
- inserted: analyzed.inserted,
987
- skipped: analyzed.skipped,
988
- });
989
- }
990
- crawled[videoId] = true;
1079
+ queued.add(videoId);
991
1080
  if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
992
1081
  const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
993
1082
  await sleep(delay);
@@ -998,7 +1087,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
998
1087
  if (abortRequested(invocation)) { aborted = true; break outer; }
999
1088
  const articleId = noteIdFromUrl(card.href);
1000
1089
  if (!articleId) continue;
1001
- if (crawled[articleId]) {
1090
+ if (crawled[articleId] || queued.has(articleId)) {
1002
1091
  skippedArticles += 1;
1003
1092
  continue;
1004
1093
  }
@@ -1029,56 +1118,18 @@ async function runCrawl(ctx, invocation, session, taskList) {
1029
1118
  processedWorks += 1;
1030
1119
  article.account_url = account.url;
1031
1120
  const target = path.join(articleDir, 'materials.jsonl');
1032
- taskList.advance(4);
1033
- taskList.progress(`LLM 整理文章素材(${article.title || articleId})`);
1034
- const analyzed = await analyzeArticle(ctx, invocation, session, {
1035
- root,
1121
+ jobs.push({
1122
+ type: 'article',
1123
+ id: articleId,
1124
+ card,
1036
1125
  accountUrl: account.url,
1126
+ url: article.url || card.href,
1127
+ dir: articleDir,
1037
1128
  article,
1038
1129
  target,
1039
- materialTools,
1040
- taskList,
1130
+ title: article.title,
1041
1131
  });
1042
- if (!analyzed.ok) {
1043
- failures.push({ id: articleId, url: card.href, reason: analyzed.error });
1044
- if (analyzed.aborted) { aborted = true; break outer; }
1045
- if (analyzed.fatal) break outer;
1046
- markFailed(articleId, card, { type: 'article', dir: articleDir, title: article.title }, analyzed.error);
1047
- continue;
1048
- }
1049
- if (analyzed.skipped) {
1050
- skippedIrrelevant += 1;
1051
- markCrawled(root, articleId, {
1052
- account_url: account.url,
1053
- url: article.url || card.href,
1054
- title: article.title || card.text || '',
1055
- type: 'article',
1056
- body_file: article.body_file,
1057
- reading_time: article.reading_time,
1058
- body_length: article.body_length,
1059
- dir: articleDir,
1060
- inserted: 0,
1061
- skipped: 0,
1062
- skip: true,
1063
- reason: analyzed.reason || '与网文创作无关',
1064
- });
1065
- } else {
1066
- inserted += analyzed.inserted;
1067
- skippedMaterials += analyzed.skipped;
1068
- markCrawled(root, articleId, {
1069
- account_url: account.url,
1070
- url: article.url || card.href,
1071
- title: article.title || card.text || '',
1072
- type: 'article',
1073
- body_file: article.body_file,
1074
- reading_time: article.reading_time,
1075
- body_length: article.body_length,
1076
- dir: articleDir,
1077
- inserted: analyzed.inserted,
1078
- skipped: analyzed.skipped,
1079
- });
1080
- }
1081
- crawled[articleId] = true;
1132
+ queued.add(articleId);
1082
1133
  if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
1083
1134
  const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
1084
1135
  await sleep(delay);
@@ -1086,6 +1137,118 @@ async function runCrawl(ctx, invocation, session, taskList) {
1086
1137
  }
1087
1138
  }
1088
1139
 
1140
+ if (jobs.length) {
1141
+ taskList.advance(4);
1142
+ let finishedJobs = 0;
1143
+ const progressText = () => useSubagents
1144
+ ? `子 Agent 并行分析(${finishedJobs}/${jobs.length})`
1145
+ : `LLM 整理素材(${finishedJobs}/${jobs.length})`;
1146
+ taskList.progress(progressText());
1147
+
1148
+ const finalizeJob = async (job, analyzed) => {
1149
+ await withStateLock(async () => {
1150
+ if (analyzed && analyzed.needsFinalize) {
1151
+ analyzed = await finalizeMaterialFile({
1152
+ root,
1153
+ target: job.target,
1154
+ title: job.title,
1155
+ materialTools,
1156
+ });
1157
+ }
1158
+ if (analyzed && analyzed.aborted) {
1159
+ aborted = true;
1160
+ return;
1161
+ }
1162
+ if (!analyzed || !analyzed.ok) {
1163
+ const reason = (analyzed && (analyzed.error || analyzed.detail)) || '素材没有通过校验';
1164
+ failures.push({ id: job.id, url: job.url, reason });
1165
+ markJobFailed(job, reason);
1166
+ return;
1167
+ }
1168
+ if (analyzed.skipped) {
1169
+ skippedIrrelevant += 1;
1170
+ markCrawled(root, job.id, {
1171
+ account_url: job.accountUrl,
1172
+ url: job.url,
1173
+ title: job.title || (job.card && job.card.text) || '',
1174
+ type: job.type,
1175
+ duration: job.duration,
1176
+ screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1177
+ ? job.screenshots.map((shot) => shot.file)
1178
+ : undefined,
1179
+ body_file: job.article && job.article.body_file,
1180
+ reading_time: job.article && job.article.reading_time,
1181
+ body_length: job.article && job.article.body_length,
1182
+ dir: job.dir,
1183
+ inserted: 0,
1184
+ skipped: 0,
1185
+ skip: true,
1186
+ reason: analyzed.reason || '与网文创作无关',
1187
+ });
1188
+ } else {
1189
+ inserted += analyzed.inserted || 0;
1190
+ skippedMaterials += analyzed.skipped || 0;
1191
+ markCrawled(root, job.id, {
1192
+ account_url: job.accountUrl,
1193
+ url: job.url,
1194
+ title: job.title || (job.card && job.card.text) || '',
1195
+ type: job.type,
1196
+ duration: job.duration,
1197
+ screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1198
+ ? job.screenshots.map((shot) => shot.file)
1199
+ : undefined,
1200
+ body_file: job.article && job.article.body_file,
1201
+ reading_time: job.article && job.article.reading_time,
1202
+ body_length: job.article && job.article.body_length,
1203
+ dir: job.dir,
1204
+ inserted: analyzed.inserted || 0,
1205
+ skipped: analyzed.skipped || 0,
1206
+ });
1207
+ }
1208
+ crawled[job.id] = true;
1209
+ finishedJobs += 1;
1210
+ taskList.progress(progressText());
1211
+ });
1212
+ };
1213
+
1214
+ if (useSubagents) {
1215
+ taskList.progress(`子 Agent 并行分析(0/${jobs.length},并发 ${subagentWorkers})`);
1216
+ await runJobPool(jobs, subagentWorkers, async (job) => {
1217
+ if (abortRequested(invocation)) { aborted = true; return; }
1218
+ let analyzed;
1219
+ try {
1220
+ analyzed = await runSubagentAnalysisJob({
1221
+ subagents: subagentRuntime,
1222
+ provider: 'spawn',
1223
+ invocation,
1224
+ job,
1225
+ root,
1226
+ materialTools,
1227
+ signal: jobSignal,
1228
+ });
1229
+ } catch (err) {
1230
+ analyzed = {
1231
+ ok: false,
1232
+ error: '子 Agent 分析失败:' + (err && err.message ? err.message : String(err)),
1233
+ };
1234
+ }
1235
+ await finalizeJob(job, analyzed);
1236
+ });
1237
+ } else {
1238
+ for (const job of jobs) {
1239
+ if (abortRequested(invocation)) { aborted = true; break; }
1240
+ const analyzed = await runLocalAnalysisJob(ctx, invocation, session, job, {
1241
+ root,
1242
+ materialTools,
1243
+ paths,
1244
+ taskList,
1245
+ });
1246
+ await finalizeJob(job, analyzed);
1247
+ if (analyzed && analyzed.fatal) { aborted = true; break; }
1248
+ }
1249
+ }
1250
+ }
1251
+
1089
1252
  taskList.advance(5);
1090
1253
  return notify(session, (aborted || failures.length) ? 'error' : 'success', summaryText({
1091
1254
  accounts: accounts.length,
@@ -1107,6 +1270,8 @@ async function runCrawl(ctx, invocation, session, taskList) {
1107
1270
  stateFile: paths.crawled,
1108
1271
  aborted,
1109
1272
  mode: browser.mode,
1273
+ analysisMode: useSubagents ? 'subagent' : 'single',
1274
+ subagentWorkers,
1110
1275
  }));
1111
1276
  } finally {
1112
1277
  await stopChrome(root, tools, paths);
@@ -1157,7 +1322,7 @@ function douyinTaskTitles(invocation) {
1157
1322
  'LLM 能力自检(图片 / 视频)',
1158
1323
  '扫描账号主页',
1159
1324
  '采集图文 / 视频 / 文章作品',
1160
- 'LLM 整理素材',
1325
+ '分析作品素材',
1161
1326
  '写入素材库',
1162
1327
  ];
1163
1328
  }
@@ -20,6 +20,23 @@ function normalize(url) {
20
20
  return String(url);
21
21
  }
22
22
 
23
+ async function readProfile(page) {
24
+ return await page.evaluate(() => {
25
+ const title = String(document.title || '')
26
+ .replace(/\s*-\s*抖音\s*$/, '')
27
+ .replace(/的抖音.*$/, '')
28
+ .trim();
29
+ const body = document.body && document.body.innerText ? document.body.innerText : '';
30
+ const idMatch = body.match(/抖音号[::]\s*([A-Za-z0-9_.-]+)/);
31
+ const secMatch = location.pathname.match(/\/user\/([^/?#]+)/);
32
+ return {
33
+ name: title || '',
34
+ douyin_id: idMatch ? idMatch[1] : '',
35
+ sec_uid: secMatch ? secMatch[1] : '',
36
+ };
37
+ });
38
+ }
39
+
23
40
  async function collectCards(page) {
24
41
  const cards = new Map();
25
42
  let stable = 0;
@@ -162,11 +179,13 @@ async function main() {
162
179
  const notes = cards.filter((card) => card.kind === 'note');
163
180
  const videos = cards.filter((card) => card.kind === 'video');
164
181
  const articles = cards.filter((card) => card.kind === 'article');
182
+ const profile = await readProfile(page);
165
183
  printJson({
166
184
  ok: true,
167
185
  login_required: false,
168
186
  account,
169
187
  title: await page.title(),
188
+ profile,
170
189
  notes,
171
190
  videos,
172
191
  articles,
@@ -5,8 +5,8 @@
5
5
  * live under <workspace>/.fancy/douyin. The deployed crawler scripts live under
6
6
  * <workspace>/.fancy-tools/fancy-douyin.
7
7
  *
8
- * The crawl history is keyed by the note/video id parsed from /note/<id> or
9
- * /video/<id>. A work is written only after its analysis has been imported into
8
+ * The crawl history is keyed by the work id parsed from /note/<id>, /video/<id>
9
+ * or /article/<id>. A work is written only after its analysis has been imported into
10
10
  * the material library, or after it was confirmed irrelevant/long and skipped,
11
11
  * so failed works are retried on the next run.
12
12
  */
@@ -98,6 +98,10 @@ export function readAccounts(root) {
98
98
  .map((item) => ({
99
99
  url: item.url,
100
100
  added_at: item.added_at || '',
101
+ name: typeof item.name === 'string' ? item.name : '',
102
+ douyin_id: typeof item.douyin_id === 'string' ? item.douyin_id : '',
103
+ sec_uid: typeof item.sec_uid === 'string' ? item.sec_uid : '',
104
+ last_scan_at: typeof item.last_scan_at === 'string' ? item.last_scan_at : '',
101
105
  }));
102
106
  }
103
107
 
@@ -106,6 +110,7 @@ export function writeAccounts(root, accounts) {
106
110
  atomicWriteJson(paths.accounts, {
107
111
  version: 1,
108
112
  accounts: accounts.map((item) => ({
113
+ ...item,
109
114
  url: item.url,
110
115
  added_at: item.added_at || new Date().toISOString(),
111
116
  })),
@@ -128,6 +133,31 @@ export function addAccount(root, rawUrl) {
128
133
  return { added: true, url, accounts };
129
134
  }
130
135
 
136
+ /**
137
+ * Record the profile fields discovered while scanning an account homepage.
138
+ * Existing accounts keep all other state; unknown accounts are ignored.
139
+ *
140
+ * @param {string} root workspace directory
141
+ * @param {string} url normalized account URL
142
+ * @param {{name?: string, douyin_id?: string, sec_uid?: string, last_scan_at?: string}} profile
143
+ * @returns {object|null} updated account
144
+ */
145
+ export function updateAccountProfile(root, url, profile) {
146
+ const accounts = readAccounts(root);
147
+ const index = accounts.findIndex((item) => item.url === url);
148
+ if (index < 0) return null;
149
+ const next = {
150
+ ...accounts[index],
151
+ ...(profile && typeof profile.name === 'string' && profile.name.trim() ? { name: profile.name.trim() } : {}),
152
+ ...(profile && typeof profile.douyin_id === 'string' && profile.douyin_id.trim() ? { douyin_id: profile.douyin_id.trim() } : {}),
153
+ ...(profile && typeof profile.sec_uid === 'string' && profile.sec_uid.trim() ? { sec_uid: profile.sec_uid.trim() } : {}),
154
+ last_scan_at: new Date().toISOString(),
155
+ };
156
+ accounts[index] = next;
157
+ writeAccounts(root, accounts);
158
+ return next;
159
+ }
160
+
131
161
  /**
132
162
  * Remove an account by 1-based list index or by homepage URL.
133
163
  *
@@ -188,11 +218,17 @@ export function accountListText(root) {
188
218
  if (!item || typeof item !== 'object' || !item.account_url) continue;
189
219
  counts.set(item.account_url, (counts.get(item.account_url) || 0) + 1);
190
220
  }
191
- return [
192
- '已记录的抖音账号:',
193
- ...accounts.map((item, index) => {
194
- const count = counts.get(item.url) || 0;
195
- return `${index + 1}. ${item.url}(已采集 ${count} 篇)`;
196
- }),
197
- ].join('\n');
221
+ const lines = ['已记录的抖音账号:'];
222
+ accounts.forEach((item, index) => {
223
+ const count = counts.get(item.url) || 0;
224
+ if (item.name) {
225
+ const idText = item.douyin_id ? '抖音号:' + item.douyin_id : '抖音号未获取';
226
+ lines.push(`${index + 1}. ${item.name}(${idText})`);
227
+ lines.push(' ' + item.url);
228
+ } else {
229
+ lines.push(`${index + 1}. ${item.url}(未获取账号名/抖音号)`);
230
+ }
231
+ lines.push(` 已采集 ${count} 篇`);
232
+ });
233
+ return lines.join('\n');
198
234
  }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Helpers for the optional DSH subagent analysis pool.
3
+ *
4
+ * The Douyin crawler still runs in the parent process. Only the LLM analysis
5
+ * of already-prepared works is delegated to child agents. That keeps Chrome,
6
+ * `crawled.json`, and material imports single-writer while allowing several
7
+ * image/video/article analyses to run at once.
8
+ */
9
+
10
+ export const DEFAULT_SUBAGENT_WORKERS = 3;
11
+ export const MAX_SUBAGENT_WORKERS = 6;
12
+
13
+ export function subagentWorkerCount(env = process.env) {
14
+ const raw = env && env.FANCY_DOUYIN_SUBAGENTS;
15
+ if (raw === undefined || raw === null || String(raw).trim() === '') return DEFAULT_SUBAGENT_WORKERS;
16
+ const value = Number(String(raw).trim());
17
+ if (!Number.isFinite(value) || value <= 0) return 0;
18
+ return Math.max(1, Math.min(MAX_SUBAGENT_WORKERS, Math.floor(value)));
19
+ }
20
+
21
+ /**
22
+ * Resolve the DSH subagent runtime from a plugin context. The service is
23
+ * optional: older hosts or a profile without subagents simply fall back to the
24
+ * existing single-agent path.
25
+ */
26
+ export function getSubagentRuntime(ctx, provider = 'spawn') {
27
+ if (!ctx) return null;
28
+ let service = null;
29
+ try {
30
+ service = typeof ctx.get === 'function' ? ctx.get('subagents') : ctx.subagents;
31
+ } catch {
32
+ return null;
33
+ }
34
+ if (!service || typeof service.startActivation !== 'function') return null;
35
+ if (typeof service.getProvider === 'function' && !service.getProvider(provider)) return null;
36
+ return service;
37
+ }
38
+
39
+ /**
40
+ * Run a fixed list of jobs through at most `concurrency` workers.
41
+ * `worker` receives each item and is awaited before that worker takes another.
42
+ */
43
+ export async function runJobPool(items, concurrency, worker) {
44
+ const list = Array.isArray(items) ? items : [];
45
+ const limit = Math.max(1, Math.min(Number(concurrency) || 1, list.length || 1));
46
+ let cursor = 0;
47
+ const runners = Array.from({ length: limit }, async () => {
48
+ while (true) {
49
+ const index = cursor;
50
+ cursor += 1;
51
+ if (index >= list.length) return;
52
+ await worker(list[index], index);
53
+ }
54
+ });
55
+ await Promise.all(runners);
56
+ }
57
+
58
+ /**
59
+ * A small async mutex. Finalization is deliberately serialized because it
60
+ * writes crawled.json and opens the material database; the LLM work itself is
61
+ * already parallel.
62
+ */
63
+ export function createSerialLock() {
64
+ let chain = Promise.resolve();
65
+ return function withLock(fn) {
66
+ const next = chain.then(fn, fn);
67
+ chain = next.catch(() => {});
68
+ return next;
69
+ };
70
+ }
@@ -16,7 +16,7 @@ export function helpText() {
16
16
  return `🎬 抖音素材采集 用法
17
17
 
18
18
  /fancy-douyin add <主页地址> 记录一个抖音账号主页
19
- /fancy-douyin list 查看已记录的账号
19
+ /fancy-douyin list 查看账号名、抖音号和已采集数量
20
20
  /fancy-douyin remove <序号|地址> 删除已记录的账号
21
21
  /fancy-douyin 依次采集所有账号下未处理的图文、视频和文章作品
22
22
  /fancy-douyin help 显示本帮助
@@ -29,6 +29,8 @@ export function helpText() {
29
29
  - 图片和视频能力都没有时,跳过图文/视频,只处理文章。
30
30
  - 图文作品会下载轮播原图并转成 JPG;如果轮播里混有视频页,会下载该页短视频,用场景变化检测 + 固定间隔兜底抽取关键帧拼图。
31
31
  - 文章作品直接提取标题、发布日期、阅读时长和正文,按长文设定拆成原子素材。
32
+ - 采集完成后可由 DSH 子 Agent 并行分析作品:父进程负责采集、校验、入库和写 crawled.json,子 Agent 只写各作品的 materials.jsonl。
33
+ - 子 Agent 并发数由 FANCY_DOUYIN_SUBAGENTS 控制(默认 3,0 关闭);DSH 没有 subagent 服务或 spawn provider 时自动回退单 Agent 串行。
32
34
  - 视频作品先判断时长:超过 1 分钟直接跳过;不超过 1 分钟的先看前 5 秒,
33
35
  与网文创作无关就跳过,有关才继续分析关键帧。
34
36
  - 如果内容与网文创作无关,LLM 会写入 skip 标记,该作品记为已处理并跳过。
@@ -237,11 +239,14 @@ export function summaryText({
237
239
  stateFile,
238
240
  aborted,
239
241
  mode,
242
+ analysisMode = 'single',
243
+ subagentWorkers = 0,
240
244
  }) {
241
245
  const lines = [
242
246
  aborted ? '⚠️ 抖音采集已中断' : '✅ 抖音采集完成',
243
247
  '账号:' + accounts + ' 个(本次扫描 ' + scannedAccounts + ' 个)',
244
248
  '浏览器:' + (mode === 'headless' ? '无头' : '有头'),
249
+ '分析模式:' + (analysisMode === 'subagent' ? '子 Agent 并行(' + subagentWorkers + ' 个)' : '单 Agent 串行'),
245
250
  '发现图文:' + foundNotes + ' 篇',
246
251
  '发现视频:' + foundVideos + ' 个',
247
252
  '发现文章:' + foundArticles + ' 篇',